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
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/tkFileDialog.py
python
askdirectory
(**options)
return Directory(**options).show()
Ask for a directory, and return the file name
Ask for a directory, and return the file name
[ "Ask", "for", "a", "directory", "and", "return", "the", "file", "name" ]
def askdirectory (**options): "Ask for a directory, and return the file name" return Directory(**options).show()
[ "def", "askdirectory", "(", "*", "*", "options", ")", ":", "return", "Directory", "(", "*", "*", "options", ")", ".", "show", "(", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/tkFileDialog.py#L176-L178
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/agilepy/lib_wx/processdialog.py
python
ProcessDialogInteractive.on_cancel
(self, event)
Apply values, destroy itself and parent
Apply values, destroy itself and parent
[ "Apply", "values", "destroy", "itself", "and", "parent" ]
def on_cancel(self, event): """ Apply values, destroy itself and parent """ # print 'on_cancel' self.on_close(event)
[ "def", "on_cancel", "(", "self", ",", "event", ")", ":", "# print 'on_cancel'", "self", ".", "on_close", "(", "event", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/agilepy/lib_wx/processdialog.py#L432-L437
clementine-player/Clementine
111379dfd027802b59125829fcf87e3e1d0ad73b
dist/cpplint.py
python
CheckMakePairUsesDeduction
(filename, clean_lines, linenum, error)
Check that make_pair's template arguments are deduced. G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are specified explicitly, and such use isn't intended in any case. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Check that make_pair's template arguments are deduced.
[ "Check", "that", "make_pair", "s", "template", "arguments", "are", "deduced", "." ]
def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error): """Check that make_pair's template arguments are deduced. G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are specified explicitly, and such use isn't intended in any case. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line) if match: error(filename, linenum, 'build/explicit_make_pair', 4, # 4 = high confidence 'For C++11-compatibility, omit template arguments from make_pair' ' OR use pair directly OR if appropriate, construct a pair directly')
[ "def", "CheckMakePairUsesDeduction", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "match", "=", "_RE_PATTERN_EXPLICIT_MAKEPAIR", ".", "search", "(", "line", ")", "if", "match", ":", "error", "(", "filename", ",", "linenum", ",", "'build/explicit_make_pair'", ",", "4", ",", "# 4 = high confidence", "'For C++11-compatibility, omit template arguments from make_pair'", "' OR use pair directly OR if appropriate, construct a pair directly'", ")" ]
https://github.com/clementine-player/Clementine/blob/111379dfd027802b59125829fcf87e3e1d0ad73b/dist/cpplint.py#L5549-L5567
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/optimize/optimize.py
python
check_grad
(func, grad, x0, *args, **kwargs)
return sqrt(sum((grad(x0, *args) - approx_fprime(x0, func, step, *args))**2))
Check the correctness of a gradient function by comparing it against a (forward) finite-difference approximation of the gradient. Parameters ---------- func : callable ``func(x0, *args)`` Function whose derivative is to be checked. grad : callable ``grad(x0, *args)`` Gradient of `func`. x0 : ndarray Points to check `grad` against forward difference approximation of grad using `func`. args : \*args, optional Extra arguments passed to `func` and `grad`. epsilon : float, optional Step size used for the finite difference approximation. It defaults to ``sqrt(numpy.finfo(float).eps)``, which is approximately 1.49e-08. Returns ------- err : float The square root of the sum of squares (i.e. the 2-norm) of the difference between ``grad(x0, *args)`` and the finite difference approximation of `grad` using func at the points `x0`. See Also -------- approx_fprime Examples -------- >>> def func(x): ... return x[0]**2 - 0.5 * x[1]**3 >>> def grad(x): ... return [2 * x[0], -1.5 * x[1]**2] >>> from scipy.optimize import check_grad >>> check_grad(func, grad, [1.5, -1.5]) 2.9802322387695312e-08
Check the correctness of a gradient function by comparing it against a (forward) finite-difference approximation of the gradient.
[ "Check", "the", "correctness", "of", "a", "gradient", "function", "by", "comparing", "it", "against", "a", "(", "forward", ")", "finite", "-", "difference", "approximation", "of", "the", "gradient", "." ]
def check_grad(func, grad, x0, *args, **kwargs): """Check the correctness of a gradient function by comparing it against a (forward) finite-difference approximation of the gradient. Parameters ---------- func : callable ``func(x0, *args)`` Function whose derivative is to be checked. grad : callable ``grad(x0, *args)`` Gradient of `func`. x0 : ndarray Points to check `grad` against forward difference approximation of grad using `func`. args : \*args, optional Extra arguments passed to `func` and `grad`. epsilon : float, optional Step size used for the finite difference approximation. It defaults to ``sqrt(numpy.finfo(float).eps)``, which is approximately 1.49e-08. Returns ------- err : float The square root of the sum of squares (i.e. the 2-norm) of the difference between ``grad(x0, *args)`` and the finite difference approximation of `grad` using func at the points `x0`. See Also -------- approx_fprime Examples -------- >>> def func(x): ... return x[0]**2 - 0.5 * x[1]**3 >>> def grad(x): ... return [2 * x[0], -1.5 * x[1]**2] >>> from scipy.optimize import check_grad >>> check_grad(func, grad, [1.5, -1.5]) 2.9802322387695312e-08 """ step = kwargs.pop('epsilon', _epsilon) if kwargs: raise ValueError("Unknown keyword arguments: %r" % (list(kwargs.keys()),)) return sqrt(sum((grad(x0, *args) - approx_fprime(x0, func, step, *args))**2))
[ "def", "check_grad", "(", "func", ",", "grad", ",", "x0", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "step", "=", "kwargs", ".", "pop", "(", "'epsilon'", ",", "_epsilon", ")", "if", "kwargs", ":", "raise", "ValueError", "(", "\"Unknown keyword arguments: %r\"", "%", "(", "list", "(", "kwargs", ".", "keys", "(", ")", ")", ",", ")", ")", "return", "sqrt", "(", "sum", "(", "(", "grad", "(", "x0", ",", "*", "args", ")", "-", "approx_fprime", "(", "x0", ",", "func", ",", "step", ",", "*", "args", ")", ")", "**", "2", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/optimize/optimize.py#L691-L737
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/python/turicreate/data_structures/sframe.py
python
SFrame.__setitem__
(self, key, value)
A wrapper around add_column(s). Key can be either a list or a str. If value is an SArray, it is added to the SFrame as a column. If it is a constant value (int, str, or float), then a column is created where every entry is equal to the constant value. Existing columns can also be replaced using this wrapper.
A wrapper around add_column(s). Key can be either a list or a str. If value is an SArray, it is added to the SFrame as a column. If it is a constant value (int, str, or float), then a column is created where every entry is equal to the constant value. Existing columns can also be replaced using this wrapper.
[ "A", "wrapper", "around", "add_column", "(", "s", ")", ".", "Key", "can", "be", "either", "a", "list", "or", "a", "str", ".", "If", "value", "is", "an", "SArray", "it", "is", "added", "to", "the", "SFrame", "as", "a", "column", ".", "If", "it", "is", "a", "constant", "value", "(", "int", "str", "or", "float", ")", "then", "a", "column", "is", "created", "where", "every", "entry", "is", "equal", "to", "the", "constant", "value", ".", "Existing", "columns", "can", "also", "be", "replaced", "using", "this", "wrapper", "." ]
def __setitem__(self, key, value): """ A wrapper around add_column(s). Key can be either a list or a str. If value is an SArray, it is added to the SFrame as a column. If it is a constant value (int, str, or float), then a column is created where every entry is equal to the constant value. Existing columns can also be replaced using this wrapper. """ if type(key) is list: self.add_columns(value, key, inplace=True) elif type(key) is str: sa_value = None if type(value) is SArray: sa_value = value elif _is_non_string_iterable(value): # wrap list, array... to sarray sa_value = SArray(value) else: # create an sarray of constant value sa_value = SArray.from_const(value, self.num_rows()) # set new column if not key in self.column_names(): with cython_context(): self.add_column(sa_value, key, inplace=True) else: # special case if replacing the only column. # server would fail the replacement if the new column has different # length than current one, which doesn't make sense if we are replacing # the only column. To support this, we first take out the only column # and then put it back if exception happens single_column = self.num_columns() == 1 if single_column: tmpname = key saved_column = self.select_column(key) self.remove_column(key, inplace=True) else: # add the column to a unique column name. tmpname = "__" + "-".join(self.column_names()) try: self.add_column(sa_value, tmpname, inplace=True) except Exception: if single_column: self.add_column(saved_column, key, inplace=True) raise if not single_column: # if add succeeded, remove the column name and rename tmpname->columnname. self.swap_columns(key, tmpname, inplace=True) self.remove_column(key, inplace=True) self.rename({tmpname: key}, inplace=True) else: raise TypeError("Cannot set column with key type " + str(type(key)))
[ "def", "__setitem__", "(", "self", ",", "key", ",", "value", ")", ":", "if", "type", "(", "key", ")", "is", "list", ":", "self", ".", "add_columns", "(", "value", ",", "key", ",", "inplace", "=", "True", ")", "elif", "type", "(", "key", ")", "is", "str", ":", "sa_value", "=", "None", "if", "type", "(", "value", ")", "is", "SArray", ":", "sa_value", "=", "value", "elif", "_is_non_string_iterable", "(", "value", ")", ":", "# wrap list, array... to sarray", "sa_value", "=", "SArray", "(", "value", ")", "else", ":", "# create an sarray of constant value", "sa_value", "=", "SArray", ".", "from_const", "(", "value", ",", "self", ".", "num_rows", "(", ")", ")", "# set new column", "if", "not", "key", "in", "self", ".", "column_names", "(", ")", ":", "with", "cython_context", "(", ")", ":", "self", ".", "add_column", "(", "sa_value", ",", "key", ",", "inplace", "=", "True", ")", "else", ":", "# special case if replacing the only column.", "# server would fail the replacement if the new column has different", "# length than current one, which doesn't make sense if we are replacing", "# the only column. To support this, we first take out the only column", "# and then put it back if exception happens", "single_column", "=", "self", ".", "num_columns", "(", ")", "==", "1", "if", "single_column", ":", "tmpname", "=", "key", "saved_column", "=", "self", ".", "select_column", "(", "key", ")", "self", ".", "remove_column", "(", "key", ",", "inplace", "=", "True", ")", "else", ":", "# add the column to a unique column name.", "tmpname", "=", "\"__\"", "+", "\"-\"", ".", "join", "(", "self", ".", "column_names", "(", ")", ")", "try", ":", "self", ".", "add_column", "(", "sa_value", ",", "tmpname", ",", "inplace", "=", "True", ")", "except", "Exception", ":", "if", "single_column", ":", "self", ".", "add_column", "(", "saved_column", ",", "key", ",", "inplace", "=", "True", ")", "raise", "if", "not", "single_column", ":", "# if add succeeded, remove the column name and rename tmpname->columnname.", "self", ".", "swap_columns", "(", "key", ",", "tmpname", ",", "inplace", "=", "True", ")", "self", ".", "remove_column", "(", "key", ",", "inplace", "=", "True", ")", "self", ".", "rename", "(", "{", "tmpname", ":", "key", "}", ",", "inplace", "=", "True", ")", "else", ":", "raise", "TypeError", "(", "\"Cannot set column with key type \"", "+", "str", "(", "type", "(", "key", ")", ")", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/data_structures/sframe.py#L3889-L3940
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/VBox/ValidationKit/common/utils.py
python
unpackFile
(sArchive, sDstDir, fnLog, fnError = None, fnFilter = None)
return []
Unpacks the given file if it has a know archive extension, otherwise do nothing. fnLog & fnError both take a string parameter. fnFilter takes a member name (string) and returns True if it's included and False if excluded. Returns list of the extracted files (full path) on success. Returns empty list if not a supported archive format. Returns None on failure. Raises no exceptions.
Unpacks the given file if it has a know archive extension, otherwise do nothing.
[ "Unpacks", "the", "given", "file", "if", "it", "has", "a", "know", "archive", "extension", "otherwise", "do", "nothing", "." ]
def unpackFile(sArchive, sDstDir, fnLog, fnError = None, fnFilter = None): # type: (string, string, (string) -> None, (string) -> None, (string) -> bool) -> list[string] """ Unpacks the given file if it has a know archive extension, otherwise do nothing. fnLog & fnError both take a string parameter. fnFilter takes a member name (string) and returns True if it's included and False if excluded. Returns list of the extracted files (full path) on success. Returns empty list if not a supported archive format. Returns None on failure. Raises no exceptions. """ sBaseNameLower = os.path.basename(sArchive).lower(); # # Zip file? # if sBaseNameLower.endswith('.zip'): return unpackZipFile(sArchive, sDstDir, fnLog, fnError, fnFilter); # # Tarball? # if sBaseNameLower.endswith('.tar') \ or sBaseNameLower.endswith('.tar.gz') \ or sBaseNameLower.endswith('.tgz') \ or sBaseNameLower.endswith('.tar.bz2'): return unpackTarFile(sArchive, sDstDir, fnLog, fnError, fnFilter); # # Cannot classify it from the name, so just return that to the caller. # fnLog('Not unpacking "%s".' % (sArchive,)); return [];
[ "def", "unpackFile", "(", "sArchive", ",", "sDstDir", ",", "fnLog", ",", "fnError", "=", "None", ",", "fnFilter", "=", "None", ")", ":", "# type: (string, string, (string) -> None, (string) -> None, (string) -> bool) -> list[string]", "sBaseNameLower", "=", "os", ".", "path", ".", "basename", "(", "sArchive", ")", ".", "lower", "(", ")", "#", "# Zip file?", "#", "if", "sBaseNameLower", ".", "endswith", "(", "'.zip'", ")", ":", "return", "unpackZipFile", "(", "sArchive", ",", "sDstDir", ",", "fnLog", ",", "fnError", ",", "fnFilter", ")", "#", "# Tarball?", "#", "if", "sBaseNameLower", ".", "endswith", "(", "'.tar'", ")", "or", "sBaseNameLower", ".", "endswith", "(", "'.tar.gz'", ")", "or", "sBaseNameLower", ".", "endswith", "(", "'.tgz'", ")", "or", "sBaseNameLower", ".", "endswith", "(", "'.tar.bz2'", ")", ":", "return", "unpackTarFile", "(", "sArchive", ",", "sDstDir", ",", "fnLog", ",", "fnError", ",", "fnFilter", ")", "#", "# Cannot classify it from the name, so just return that to the caller.", "#", "fnLog", "(", "'Not unpacking \"%s\".'", "%", "(", "sArchive", ",", ")", ")", "return", "[", "]" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/VBox/ValidationKit/common/utils.py#L1928-L1964
metashell/metashell
f4177e4854ea00c8dbc722cadab26ef413d798ea
3rd/templight/compiler-rt/lib/sanitizer_common/scripts/cpplint.py
python
NestingState.InnermostClass
(self)
return None
Get class info on the top of the stack. Returns: A _ClassInfo object if we are inside a class, or None otherwise.
Get class info on the top of the stack.
[ "Get", "class", "info", "on", "the", "top", "of", "the", "stack", "." ]
def InnermostClass(self): """Get class info on the top of the stack. Returns: A _ClassInfo object if we are inside a class, or None otherwise. """ for i in range(len(self.stack), 0, -1): classinfo = self.stack[i - 1] if isinstance(classinfo, _ClassInfo): return classinfo return None
[ "def", "InnermostClass", "(", "self", ")", ":", "for", "i", "in", "range", "(", "len", "(", "self", ".", "stack", ")", ",", "0", ",", "-", "1", ")", ":", "classinfo", "=", "self", ".", "stack", "[", "i", "-", "1", "]", "if", "isinstance", "(", "classinfo", ",", "_ClassInfo", ")", ":", "return", "classinfo", "return", "None" ]
https://github.com/metashell/metashell/blob/f4177e4854ea00c8dbc722cadab26ef413d798ea/3rd/templight/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L2746-L2756
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/traitlets/py2/traitlets/traitlets.py
python
TraitType.__init__
(self, default_value=Undefined, allow_none=False, read_only=None, help=None, config=None, **kwargs)
Declare a traitlet. If *allow_none* is True, None is a valid value in addition to any values that are normally valid. The default is up to the subclass. For most trait types, the default value for ``allow_none`` is False. Extra metadata can be associated with the traitlet using the .tag() convenience method or by using the traitlet instance's .metadata dictionary.
Declare a traitlet.
[ "Declare", "a", "traitlet", "." ]
def __init__(self, default_value=Undefined, allow_none=False, read_only=None, help=None, config=None, **kwargs): """Declare a traitlet. If *allow_none* is True, None is a valid value in addition to any values that are normally valid. The default is up to the subclass. For most trait types, the default value for ``allow_none`` is False. Extra metadata can be associated with the traitlet using the .tag() convenience method or by using the traitlet instance's .metadata dictionary. """ if default_value is not Undefined: self.default_value = default_value if allow_none: self.allow_none = allow_none if read_only is not None: self.read_only = read_only self.help = help if help is not None else '' if len(kwargs) > 0: stacklevel = 1 f = inspect.currentframe() # count supers to determine stacklevel for warning while f.f_code.co_name == '__init__': stacklevel += 1 f = f.f_back mod = f.f_globals.get('__name__') or '' pkg = mod.split('.', 1)[0] key = tuple(['metadata-tag', pkg] + sorted(kwargs)) if _should_warn(key): warn("metadata %s was set from the constructor. " "With traitlets 4.1, metadata should be set using the .tag() method, " "e.g., Int().tag(key1='value1', key2='value2')" % (kwargs,), DeprecationWarning, stacklevel=stacklevel) if len(self.metadata) > 0: self.metadata = self.metadata.copy() self.metadata.update(kwargs) else: self.metadata = kwargs else: self.metadata = self.metadata.copy() if config is not None: self.metadata['config'] = config # We add help to the metadata during a deprecation period so that # code that looks for the help string there can find it. if help is not None: self.metadata['help'] = help
[ "def", "__init__", "(", "self", ",", "default_value", "=", "Undefined", ",", "allow_none", "=", "False", ",", "read_only", "=", "None", ",", "help", "=", "None", ",", "config", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "default_value", "is", "not", "Undefined", ":", "self", ".", "default_value", "=", "default_value", "if", "allow_none", ":", "self", ".", "allow_none", "=", "allow_none", "if", "read_only", "is", "not", "None", ":", "self", ".", "read_only", "=", "read_only", "self", ".", "help", "=", "help", "if", "help", "is", "not", "None", "else", "''", "if", "len", "(", "kwargs", ")", ">", "0", ":", "stacklevel", "=", "1", "f", "=", "inspect", ".", "currentframe", "(", ")", "# count supers to determine stacklevel for warning", "while", "f", ".", "f_code", ".", "co_name", "==", "'__init__'", ":", "stacklevel", "+=", "1", "f", "=", "f", ".", "f_back", "mod", "=", "f", ".", "f_globals", ".", "get", "(", "'__name__'", ")", "or", "''", "pkg", "=", "mod", ".", "split", "(", "'.'", ",", "1", ")", "[", "0", "]", "key", "=", "tuple", "(", "[", "'metadata-tag'", ",", "pkg", "]", "+", "sorted", "(", "kwargs", ")", ")", "if", "_should_warn", "(", "key", ")", ":", "warn", "(", "\"metadata %s was set from the constructor. \"", "\"With traitlets 4.1, metadata should be set using the .tag() method, \"", "\"e.g., Int().tag(key1='value1', key2='value2')\"", "%", "(", "kwargs", ",", ")", ",", "DeprecationWarning", ",", "stacklevel", "=", "stacklevel", ")", "if", "len", "(", "self", ".", "metadata", ")", ">", "0", ":", "self", ".", "metadata", "=", "self", ".", "metadata", ".", "copy", "(", ")", "self", ".", "metadata", ".", "update", "(", "kwargs", ")", "else", ":", "self", ".", "metadata", "=", "kwargs", "else", ":", "self", ".", "metadata", "=", "self", ".", "metadata", ".", "copy", "(", ")", "if", "config", "is", "not", "None", ":", "self", ".", "metadata", "[", "'config'", "]", "=", "config", "# We add help to the metadata during a deprecation period so that", "# code that looks for the help string there can find it.", "if", "help", "is", "not", "None", ":", "self", ".", "metadata", "[", "'help'", "]", "=", "help" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/traitlets/py2/traitlets/traitlets.py#L419-L466
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/update_fusion_version.py
python
FindUpdateCurrentVersion
(fusion_version_file, long_version, short_version, year)
return (old_long, old_short)
Find and update long and short version names in the fusion_version_file. Args: fusion_version_file: Absolute filename for fusion_version.txt long_version: The new long_version to update to. short_version: The new short_version to update to. year: The current year to be used in copyright statement. Returns: A couple of string (in a list) representing current long and short respectively. Raises: AssertionError: Whenever anything fails.
Find and update long and short version names in the fusion_version_file.
[ "Find", "and", "update", "long", "and", "short", "version", "names", "in", "the", "fusion_version_file", "." ]
def FindUpdateCurrentVersion(fusion_version_file, long_version, short_version, year): """Find and update long and short version names in the fusion_version_file. Args: fusion_version_file: Absolute filename for fusion_version.txt long_version: The new long_version to update to. short_version: The new short_version to update to. year: The current year to be used in copyright statement. Returns: A couple of string (in a list) representing current long and short respectively. Raises: AssertionError: Whenever anything fails. """ cmd = 'cd %s; g4 open %s' % (os.path.dirname(fusion_version_file), os.path.basename(fusion_version_file)) if os.system(cmd): raise AssertionError('Cannot run command "%s"' % cmd) stage = 0 # not yet reached long_version for line in fileinput.FileInput(fusion_version_file, inplace=1): if stage == 0: if not line.startswith('#'): stage = 1 # long_version reached old_long = line[:-1] print long_version else: # TODO: Create script to do this for all copyrights. if line.startswith('# Copyright'): print '# Copyright %d Google Inc. All Rights Reserved.' % year else: print line, elif stage == 1: old_short = line[:-1] print short_version stage = 2 # short version reached else: raise AssertionError('Cannot comprehend line "%s" in %s' % ( line, fusion_version_file)) return (old_long, old_short)
[ "def", "FindUpdateCurrentVersion", "(", "fusion_version_file", ",", "long_version", ",", "short_version", ",", "year", ")", ":", "cmd", "=", "'cd %s; g4 open %s'", "%", "(", "os", ".", "path", ".", "dirname", "(", "fusion_version_file", ")", ",", "os", ".", "path", ".", "basename", "(", "fusion_version_file", ")", ")", "if", "os", ".", "system", "(", "cmd", ")", ":", "raise", "AssertionError", "(", "'Cannot run command \"%s\"'", "%", "cmd", ")", "stage", "=", "0", "# not yet reached long_version", "for", "line", "in", "fileinput", ".", "FileInput", "(", "fusion_version_file", ",", "inplace", "=", "1", ")", ":", "if", "stage", "==", "0", ":", "if", "not", "line", ".", "startswith", "(", "'#'", ")", ":", "stage", "=", "1", "# long_version reached", "old_long", "=", "line", "[", ":", "-", "1", "]", "print", "long_version", "else", ":", "# TODO: Create script to do this for all copyrights.", "if", "line", ".", "startswith", "(", "'# Copyright'", ")", ":", "print", "'# Copyright %d Google Inc. All Rights Reserved.'", "%", "year", "else", ":", "print", "line", ",", "elif", "stage", "==", "1", ":", "old_short", "=", "line", "[", ":", "-", "1", "]", "print", "short_version", "stage", "=", "2", "# short version reached", "else", ":", "raise", "AssertionError", "(", "'Cannot comprehend line \"%s\" in %s'", "%", "(", "line", ",", "fusion_version_file", ")", ")", "return", "(", "old_long", ",", "old_short", ")" ]
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/update_fusion_version.py#L53-L94
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/rds/__init__.py
python
RDSConnection.create_parameter_group
(self, name, engine='MySQL5.1', description='')
return self.get_object('CreateDBParameterGroup', params, ParameterGroup)
Create a new dbparameter group for your account. :type name: string :param name: The name of the new dbparameter group :type engine: str :param engine: Name of database engine. :type description: string :param description: The description of the new dbparameter group :rtype: :class:`boto.rds.parametergroup.ParameterGroup` :return: The newly created ParameterGroup
Create a new dbparameter group for your account.
[ "Create", "a", "new", "dbparameter", "group", "for", "your", "account", "." ]
def create_parameter_group(self, name, engine='MySQL5.1', description=''): """ Create a new dbparameter group for your account. :type name: string :param name: The name of the new dbparameter group :type engine: str :param engine: Name of database engine. :type description: string :param description: The description of the new dbparameter group :rtype: :class:`boto.rds.parametergroup.ParameterGroup` :return: The newly created ParameterGroup """ params = {'DBParameterGroupName': name, 'DBParameterGroupFamily': engine, 'Description': description} return self.get_object('CreateDBParameterGroup', params, ParameterGroup)
[ "def", "create_parameter_group", "(", "self", ",", "name", ",", "engine", "=", "'MySQL5.1'", ",", "description", "=", "''", ")", ":", "params", "=", "{", "'DBParameterGroupName'", ":", "name", ",", "'DBParameterGroupFamily'", ":", "engine", ",", "'Description'", ":", "description", "}", "return", "self", ".", "get_object", "(", "'CreateDBParameterGroup'", ",", "params", ",", "ParameterGroup", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/rds/__init__.py#L817-L836
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/grid.py
python
GridTableBase.GetNumberCols
(*args, **kwargs)
return _grid.GridTableBase_GetNumberCols(*args, **kwargs)
GetNumberCols(self) -> int
GetNumberCols(self) -> int
[ "GetNumberCols", "(", "self", ")", "-", ">", "int" ]
def GetNumberCols(*args, **kwargs): """GetNumberCols(self) -> int""" return _grid.GridTableBase_GetNumberCols(*args, **kwargs)
[ "def", "GetNumberCols", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "GridTableBase_GetNumberCols", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/grid.py#L806-L808
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/foldpanelbar.py
python
CaptionBarEvent.GetBar
(self)
return self._bar
Returns the selected :class:`CaptionBar`.
Returns the selected :class:`CaptionBar`.
[ "Returns", "the", "selected", ":", "class", ":", "CaptionBar", "." ]
def GetBar(self): """ Returns the selected :class:`CaptionBar`. """ return self._bar
[ "def", "GetBar", "(", "self", ")", ":", "return", "self", ".", "_bar" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/foldpanelbar.py#L552-L555
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/src/robotsim.py
python
TransformPoser.set
(self, R, t)
return _robotsim.TransformPoser_set(self, R, t)
set(TransformPoser self, double const [9] R, double const [3] t)
set(TransformPoser self, double const [9] R, double const [3] t)
[ "set", "(", "TransformPoser", "self", "double", "const", "[", "9", "]", "R", "double", "const", "[", "3", "]", "t", ")" ]
def set(self, R, t): """ set(TransformPoser self, double const [9] R, double const [3] t) """ return _robotsim.TransformPoser_set(self, R, t)
[ "def", "set", "(", "self", ",", "R", ",", "t", ")", ":", "return", "_robotsim", ".", "TransformPoser_set", "(", "self", ",", "R", ",", "t", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/src/robotsim.py#L3252-L3259
chromiumembedded/cef
80caf947f3fe2210e5344713c5281d8af9bdc295
tools/automate/automate-git.py
python
get_git_url
(path)
return 'Unknown'
Returns the origin url for the specified path.
Returns the origin url for the specified path.
[ "Returns", "the", "origin", "url", "for", "the", "specified", "path", "." ]
def get_git_url(path): """ Returns the origin url for the specified path. """ cmd = "%s config --get remote.origin.url" % (git_exe) result = exec_cmd(cmd, path) if result['out'] != '': return result['out'].strip() return 'Unknown'
[ "def", "get_git_url", "(", "path", ")", ":", "cmd", "=", "\"%s config --get remote.origin.url\"", "%", "(", "git_exe", ")", "result", "=", "exec_cmd", "(", "cmd", ",", "path", ")", "if", "result", "[", "'out'", "]", "!=", "''", ":", "return", "result", "[", "'out'", "]", ".", "strip", "(", ")", "return", "'Unknown'" ]
https://github.com/chromiumembedded/cef/blob/80caf947f3fe2210e5344713c5281d8af9bdc295/tools/automate/automate-git.py#L172-L178
tensorflow/deepmath
b5b721f54de1d5d6a02d78f5da5995237f9995f9
deepmath/premises/model_final_cnn_3x.py
python
Model.axiom_embedding
(self, axioms)
return self.make_embedding(axioms)
Compute the embedding for each of the axioms.
Compute the embedding for each of the axioms.
[ "Compute", "the", "embedding", "for", "each", "of", "the", "axioms", "." ]
def axiom_embedding(self, axioms): """Compute the embedding for each of the axioms.""" return self.make_embedding(axioms)
[ "def", "axiom_embedding", "(", "self", ",", "axioms", ")", ":", "return", "self", ".", "make_embedding", "(", "axioms", ")" ]
https://github.com/tensorflow/deepmath/blob/b5b721f54de1d5d6a02d78f5da5995237f9995f9/deepmath/premises/model_final_cnn_3x.py#L54-L56
0ad/0ad
f58db82e0e925016d83f4e3fa7ca599e3866e2af
source/tools/i18n/checkDiff.py
python
get_diff
()
return io.StringIO(diff_process.stdout.decode())
Return a diff using svn diff
Return a diff using svn diff
[ "Return", "a", "diff", "using", "svn", "diff" ]
def get_diff(): """Return a diff using svn diff""" os.chdir(projectRootDirectory) diff_process = subprocess.run(["svn", "diff", "binaries"], capture_output=True) if diff_process.returncode != 0: print(f"Error running svn diff: {diff_process.stderr.decode()}. Exiting.") return return io.StringIO(diff_process.stdout.decode())
[ "def", "get_diff", "(", ")", ":", "os", ".", "chdir", "(", "projectRootDirectory", ")", "diff_process", "=", "subprocess", ".", "run", "(", "[", "\"svn\"", ",", "\"diff\"", ",", "\"binaries\"", "]", ",", "capture_output", "=", "True", ")", "if", "diff_process", ".", "returncode", "!=", "0", ":", "print", "(", "f\"Error running svn diff: {diff_process.stderr.decode()}. Exiting.\"", ")", "return", "return", "io", ".", "StringIO", "(", "diff_process", ".", "stdout", ".", "decode", "(", ")", ")" ]
https://github.com/0ad/0ad/blob/f58db82e0e925016d83f4e3fa7ca599e3866e2af/source/tools/i18n/checkDiff.py#L26-L34
gnuradio/gnuradio
09c3c4fa4bfb1a02caac74cb5334dfe065391e3b
grc/core/utils/expr_utils.py
python
get_variable_dependencies
(expr, vars)
return set(v for v in vars if v in expr_toks)
Return a set of variables used in this expression. Args: expr: an expression string vars: a list of variable names Returns: a subset of vars used in the expression
Return a set of variables used in this expression.
[ "Return", "a", "set", "of", "variables", "used", "in", "this", "expression", "." ]
def get_variable_dependencies(expr, vars): """ Return a set of variables used in this expression. Args: expr: an expression string vars: a list of variable names Returns: a subset of vars used in the expression """ expr_toks = _expr_split(expr) return set(v for v in vars if v in expr_toks)
[ "def", "get_variable_dependencies", "(", "expr", ",", "vars", ")", ":", "expr_toks", "=", "_expr_split", "(", "expr", ")", "return", "set", "(", "v", "for", "v", "in", "vars", "if", "v", "in", "expr_toks", ")" ]
https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/grc/core/utils/expr_utils.py#L32-L44
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/deps/v8/tools/stats-viewer.py
python
Main
(data_file, name_filter)
Run the stats counter. Args: data_file: The counters file to monitor. name_filter: The regexp filter to apply to counter names.
Run the stats counter.
[ "Run", "the", "stats", "counter", "." ]
def Main(data_file, name_filter): """Run the stats counter. Args: data_file: The counters file to monitor. name_filter: The regexp filter to apply to counter names. """ StatsViewer(data_file, name_filter).Run()
[ "def", "Main", "(", "data_file", ",", "name_filter", ")", ":", "StatsViewer", "(", "data_file", ",", "name_filter", ")", ".", "Run", "(", ")" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/v8/tools/stats-viewer.py#L454-L461
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/polynomial/hermite_e.py
python
hermeroots
(c)
return r
Compute the roots of a HermiteE series. Return the roots (a.k.a. "zeros") of the polynomial .. math:: p(x) = \\sum_i c[i] * He_i(x). Parameters ---------- c : 1-D array_like 1-D array of coefficients. Returns ------- out : ndarray Array of the roots of the series. If all the roots are real, then `out` is also real, otherwise it is complex. See Also -------- polyroots, legroots, lagroots, hermroots, chebroots Notes ----- The root estimates are obtained as the eigenvalues of the companion matrix, Roots far from the origin of the complex plane may have large errors due to the numerical instability of the series for such values. Roots with multiplicity greater than 1 will also show larger errors as the value of the series near such points is relatively insensitive to errors in the roots. Isolated roots near the origin can be improved by a few iterations of Newton's method. The HermiteE series basis polynomials aren't powers of `x` so the results of this function may seem unintuitive. Examples -------- >>> from numpy.polynomial.hermite_e import hermeroots, hermefromroots >>> coef = hermefromroots([-1, 0, 1]) >>> coef array([ 0., 2., 0., 1.]) >>> hermeroots(coef) array([-1., 0., 1.])
Compute the roots of a HermiteE series.
[ "Compute", "the", "roots", "of", "a", "HermiteE", "series", "." ]
def hermeroots(c): """ Compute the roots of a HermiteE series. Return the roots (a.k.a. "zeros") of the polynomial .. math:: p(x) = \\sum_i c[i] * He_i(x). Parameters ---------- c : 1-D array_like 1-D array of coefficients. Returns ------- out : ndarray Array of the roots of the series. If all the roots are real, then `out` is also real, otherwise it is complex. See Also -------- polyroots, legroots, lagroots, hermroots, chebroots Notes ----- The root estimates are obtained as the eigenvalues of the companion matrix, Roots far from the origin of the complex plane may have large errors due to the numerical instability of the series for such values. Roots with multiplicity greater than 1 will also show larger errors as the value of the series near such points is relatively insensitive to errors in the roots. Isolated roots near the origin can be improved by a few iterations of Newton's method. The HermiteE series basis polynomials aren't powers of `x` so the results of this function may seem unintuitive. Examples -------- >>> from numpy.polynomial.hermite_e import hermeroots, hermefromroots >>> coef = hermefromroots([-1, 0, 1]) >>> coef array([ 0., 2., 0., 1.]) >>> hermeroots(coef) array([-1., 0., 1.]) """ # c is a trimmed copy [c] = pu.as_series([c]) if len(c) <= 1: return np.array([], dtype=c.dtype) if len(c) == 2: return np.array([-c[0]/c[1]]) m = hermecompanion(c) r = la.eigvals(m) r.sort() return r
[ "def", "hermeroots", "(", "c", ")", ":", "# c is a trimmed copy", "[", "c", "]", "=", "pu", ".", "as_series", "(", "[", "c", "]", ")", "if", "len", "(", "c", ")", "<=", "1", ":", "return", "np", ".", "array", "(", "[", "]", ",", "dtype", "=", "c", ".", "dtype", ")", "if", "len", "(", "c", ")", "==", "2", ":", "return", "np", ".", "array", "(", "[", "-", "c", "[", "0", "]", "/", "c", "[", "1", "]", "]", ")", "m", "=", "hermecompanion", "(", "c", ")", "r", "=", "la", ".", "eigvals", "(", "m", ")", "r", ".", "sort", "(", ")", "return", "r" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/polynomial/hermite_e.py#L1612-L1668
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/ao/quantization/quantize.py
python
swap_module
(mod, mapping, custom_module_class_mapping)
return new_mod
r"""Swaps the module if it has a quantized counterpart and it has an `observer` attached. Args: mod: input module mapping: a dictionary that maps from nn module to nnq module Return: The corresponding quantized module of `mod`
r"""Swaps the module if it has a quantized counterpart and it has an `observer` attached.
[ "r", "Swaps", "the", "module", "if", "it", "has", "a", "quantized", "counterpart", "and", "it", "has", "an", "observer", "attached", "." ]
def swap_module(mod, mapping, custom_module_class_mapping): r"""Swaps the module if it has a quantized counterpart and it has an `observer` attached. Args: mod: input module mapping: a dictionary that maps from nn module to nnq module Return: The corresponding quantized module of `mod` """ new_mod = mod if hasattr(mod, 'qconfig') and mod.qconfig is not None: swapped = False if type(mod) in custom_module_class_mapping: new_mod = custom_module_class_mapping[type(mod)].from_observed(mod) swapped = True elif type(mod) in mapping: new_mod = mapping[type(mod)].from_float(mod) swapped = True if swapped: # Preserve module's pre forward hooks. They'll be called on quantized input for pre_hook_fn in mod._forward_pre_hooks.values(): new_mod.register_forward_pre_hook(pre_hook_fn) # Preserve module's post forward hooks except _observer_forward_hook # After convert they'll work with quantized output for hook_fn in mod._forward_hooks.values(): if hook_fn is not _observer_forward_hook: new_mod.register_forward_hook(hook_fn) # respect device affinity when swapping modules devices = get_unique_devices_(mod) assert len(devices) <= 1, ( "swap_module only works with cpu or single-device CUDA modules, " "but got devices {}".format(devices) ) device = next(iter(devices)) if len(devices) > 0 else None if device: new_mod.to(device) return new_mod
[ "def", "swap_module", "(", "mod", ",", "mapping", ",", "custom_module_class_mapping", ")", ":", "new_mod", "=", "mod", "if", "hasattr", "(", "mod", ",", "'qconfig'", ")", "and", "mod", ".", "qconfig", "is", "not", "None", ":", "swapped", "=", "False", "if", "type", "(", "mod", ")", "in", "custom_module_class_mapping", ":", "new_mod", "=", "custom_module_class_mapping", "[", "type", "(", "mod", ")", "]", ".", "from_observed", "(", "mod", ")", "swapped", "=", "True", "elif", "type", "(", "mod", ")", "in", "mapping", ":", "new_mod", "=", "mapping", "[", "type", "(", "mod", ")", "]", ".", "from_float", "(", "mod", ")", "swapped", "=", "True", "if", "swapped", ":", "# Preserve module's pre forward hooks. They'll be called on quantized input", "for", "pre_hook_fn", "in", "mod", ".", "_forward_pre_hooks", ".", "values", "(", ")", ":", "new_mod", ".", "register_forward_pre_hook", "(", "pre_hook_fn", ")", "# Preserve module's post forward hooks except _observer_forward_hook", "# After convert they'll work with quantized output", "for", "hook_fn", "in", "mod", ".", "_forward_hooks", ".", "values", "(", ")", ":", "if", "hook_fn", "is", "not", "_observer_forward_hook", ":", "new_mod", ".", "register_forward_hook", "(", "hook_fn", ")", "# respect device affinity when swapping modules", "devices", "=", "get_unique_devices_", "(", "mod", ")", "assert", "len", "(", "devices", ")", "<=", "1", ",", "(", "\"swap_module only works with cpu or single-device CUDA modules, \"", "\"but got devices {}\"", ".", "format", "(", "devices", ")", ")", "device", "=", "next", "(", "iter", "(", "devices", ")", ")", "if", "len", "(", "devices", ")", ">", "0", "else", "None", "if", "device", ":", "new_mod", ".", "to", "(", "device", ")", "return", "new_mod" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/ao/quantization/quantize.py#L550-L590
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/autograph/operators/slices.py
python
_py_set_item
(target, i, x)
return target
Overload of set_item that executes a Python list modification.
Overload of set_item that executes a Python list modification.
[ "Overload", "of", "set_item", "that", "executes", "a", "Python", "list", "modification", "." ]
def _py_set_item(target, i, x): """Overload of set_item that executes a Python list modification.""" target[i] = x return target
[ "def", "_py_set_item", "(", "target", ",", "i", ",", "x", ")", ":", "target", "[", "i", "]", "=", "x", "return", "target" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/autograph/operators/slices.py#L143-L146
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/locale.py
python
format_string
(f, val, grouping=False)
return new_f % val
Formats a string in the same way that the % formatting would use, but takes the current locale into account. Grouping is applied if the third parameter is true.
Formats a string in the same way that the % formatting would use, but takes the current locale into account. Grouping is applied if the third parameter is true.
[ "Formats", "a", "string", "in", "the", "same", "way", "that", "the", "%", "formatting", "would", "use", "but", "takes", "the", "current", "locale", "into", "account", ".", "Grouping", "is", "applied", "if", "the", "third", "parameter", "is", "true", "." ]
def format_string(f, val, grouping=False): """Formats a string in the same way that the % formatting would use, but takes the current locale into account. Grouping is applied if the third parameter is true.""" percents = list(_percent_re.finditer(f)) new_f = _percent_re.sub('%s', f) if operator.isMappingType(val): new_val = [] for perc in percents: if perc.group()[-1]=='%': new_val.append('%') else: new_val.append(format(perc.group(), val, grouping)) else: if not isinstance(val, tuple): val = (val,) new_val = [] i = 0 for perc in percents: if perc.group()[-1]=='%': new_val.append('%') else: starcount = perc.group('modifiers').count('*') new_val.append(_format(perc.group(), val[i], grouping, False, *val[i+1:i+1+starcount])) i += (1 + starcount) val = tuple(new_val) return new_f % val
[ "def", "format_string", "(", "f", ",", "val", ",", "grouping", "=", "False", ")", ":", "percents", "=", "list", "(", "_percent_re", ".", "finditer", "(", "f", ")", ")", "new_f", "=", "_percent_re", ".", "sub", "(", "'%s'", ",", "f", ")", "if", "operator", ".", "isMappingType", "(", "val", ")", ":", "new_val", "=", "[", "]", "for", "perc", "in", "percents", ":", "if", "perc", ".", "group", "(", ")", "[", "-", "1", "]", "==", "'%'", ":", "new_val", ".", "append", "(", "'%'", ")", "else", ":", "new_val", ".", "append", "(", "format", "(", "perc", ".", "group", "(", ")", ",", "val", ",", "grouping", ")", ")", "else", ":", "if", "not", "isinstance", "(", "val", ",", "tuple", ")", ":", "val", "=", "(", "val", ",", ")", "new_val", "=", "[", "]", "i", "=", "0", "for", "perc", "in", "percents", ":", "if", "perc", ".", "group", "(", ")", "[", "-", "1", "]", "==", "'%'", ":", "new_val", ".", "append", "(", "'%'", ")", "else", ":", "starcount", "=", "perc", ".", "group", "(", "'modifiers'", ")", ".", "count", "(", "'*'", ")", "new_val", ".", "append", "(", "_format", "(", "perc", ".", "group", "(", ")", ",", "val", "[", "i", "]", ",", "grouping", ",", "False", ",", "*", "val", "[", "i", "+", "1", ":", "i", "+", "1", "+", "starcount", "]", ")", ")", "i", "+=", "(", "1", "+", "starcount", ")", "val", "=", "tuple", "(", "new_val", ")", "return", "new_f", "%", "val" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/locale.py#L222-L254
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_gdi.py
python
GraphicsMatrix.Scale
(*args, **kwargs)
return _gdi_.GraphicsMatrix_Scale(*args, **kwargs)
Scale(self, Double xScale, Double yScale) Scales this matrix.
Scale(self, Double xScale, Double yScale)
[ "Scale", "(", "self", "Double", "xScale", "Double", "yScale", ")" ]
def Scale(*args, **kwargs): """ Scale(self, Double xScale, Double yScale) Scales this matrix. """ return _gdi_.GraphicsMatrix_Scale(*args, **kwargs)
[ "def", "Scale", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "GraphicsMatrix_Scale", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L5665-L5671
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/importlib/_bootstrap.py
python
_ImportLockContext.__enter__
(self)
Acquire the import lock.
Acquire the import lock.
[ "Acquire", "the", "import", "lock", "." ]
def __enter__(self): """Acquire the import lock.""" _imp.acquire_lock()
[ "def", "__enter__", "(", "self", ")", ":", "_imp", ".", "acquire_lock", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/importlib/_bootstrap.py#L855-L857
perilouswithadollarsign/cstrike15_src
f82112a2388b841d72cb62ca48ab1846dfcc11c8
thirdparty/protobuf-2.5.0/python/google/protobuf/internal/cpp_message.py
python
ExtensionDict._FindExtensionByName
(self, name)
return self._message._extensions_by_name.get(name, None)
Tries to find a known extension with the specified name. Args: name: Extension full name. Returns: Extension field descriptor.
Tries to find a known extension with the specified name.
[ "Tries", "to", "find", "a", "known", "extension", "with", "the", "specified", "name", "." ]
def _FindExtensionByName(self, name): """Tries to find a known extension with the specified name. Args: name: Extension full name. Returns: Extension field descriptor. """ return self._message._extensions_by_name.get(name, None)
[ "def", "_FindExtensionByName", "(", "self", ",", "name", ")", ":", "return", "self", ".", "_message", ".", "_extensions_by_name", ".", "get", "(", "name", ",", "None", ")" ]
https://github.com/perilouswithadollarsign/cstrike15_src/blob/f82112a2388b841d72cb62ca48ab1846dfcc11c8/thirdparty/protobuf-2.5.0/python/google/protobuf/internal/cpp_message.py#L345-L354
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_gdi.py
python
Locale_AddCatalogLookupPathPrefix
(*args, **kwargs)
return _gdi_.Locale_AddCatalogLookupPathPrefix(*args, **kwargs)
Locale_AddCatalogLookupPathPrefix(String prefix)
Locale_AddCatalogLookupPathPrefix(String prefix)
[ "Locale_AddCatalogLookupPathPrefix", "(", "String", "prefix", ")" ]
def Locale_AddCatalogLookupPathPrefix(*args, **kwargs): """Locale_AddCatalogLookupPathPrefix(String prefix)""" return _gdi_.Locale_AddCatalogLookupPathPrefix(*args, **kwargs)
[ "def", "Locale_AddCatalogLookupPathPrefix", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "Locale_AddCatalogLookupPathPrefix", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L3112-L3114
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/dashboard/dashboard/alerts.py
python
StoppageAlertDicts
(stoppage_alerts)
return [_GetStoppageAlertDict(a) for a in stoppage_alerts]
Makes a list of dicts with properties of StoppageAlert entities.
Makes a list of dicts with properties of StoppageAlert entities.
[ "Makes", "a", "list", "of", "dicts", "with", "properties", "of", "StoppageAlert", "entities", "." ]
def StoppageAlertDicts(stoppage_alerts): """Makes a list of dicts with properties of StoppageAlert entities.""" return [_GetStoppageAlertDict(a) for a in stoppage_alerts]
[ "def", "StoppageAlertDicts", "(", "stoppage_alerts", ")", ":", "return", "[", "_GetStoppageAlertDict", "(", "a", ")", "for", "a", "in", "stoppage_alerts", "]" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/dashboard/dashboard/alerts.py#L141-L143
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
dom/bindings/parser/WebIDL.py
python
IDLInterface.findInterfaceLoopPoint
(self, otherInterface)
return None
Finds an interface, amongst our ancestors and consequential interfaces, that inherits from otherInterface or implements otherInterface directly. If there is no such interface, returns None.
Finds an interface, amongst our ancestors and consequential interfaces, that inherits from otherInterface or implements otherInterface directly. If there is no such interface, returns None.
[ "Finds", "an", "interface", "amongst", "our", "ancestors", "and", "consequential", "interfaces", "that", "inherits", "from", "otherInterface", "or", "implements", "otherInterface", "directly", ".", "If", "there", "is", "no", "such", "interface", "returns", "None", "." ]
def findInterfaceLoopPoint(self, otherInterface): """ Finds an interface, amongst our ancestors and consequential interfaces, that inherits from otherInterface or implements otherInterface directly. If there is no such interface, returns None. """ if self.parent: if self.parent == otherInterface: return self loopPoint = self.parent.findInterfaceLoopPoint(otherInterface) if loopPoint: return loopPoint if otherInterface in self.implementedInterfaces: return self for iface in self.implementedInterfaces: loopPoint = iface.findInterfaceLoopPoint(otherInterface) if loopPoint: return loopPoint return None
[ "def", "findInterfaceLoopPoint", "(", "self", ",", "otherInterface", ")", ":", "if", "self", ".", "parent", ":", "if", "self", ".", "parent", "==", "otherInterface", ":", "return", "self", "loopPoint", "=", "self", ".", "parent", ".", "findInterfaceLoopPoint", "(", "otherInterface", ")", "if", "loopPoint", ":", "return", "loopPoint", "if", "otherInterface", "in", "self", ".", "implementedInterfaces", ":", "return", "self", "for", "iface", "in", "self", ".", "implementedInterfaces", ":", "loopPoint", "=", "iface", ".", "findInterfaceLoopPoint", "(", "otherInterface", ")", "if", "loopPoint", ":", "return", "loopPoint", "return", "None" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/dom/bindings/parser/WebIDL.py#L1289-L1307
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/robotsim.py
python
GeneralizedIKObjective.sampleTransform
(self)
return _robotsim.GeneralizedIKObjective_sampleTransform(self)
r""" Returns a transformation (R,t) from link relative to link2, sampled at random from the space of transforms that satisfies the objective obj.
r""" Returns a transformation (R,t) from link relative to link2, sampled at random from the space of transforms that satisfies the objective obj.
[ "r", "Returns", "a", "transformation", "(", "R", "t", ")", "from", "link", "relative", "to", "link2", "sampled", "at", "random", "from", "the", "space", "of", "transforms", "that", "satisfies", "the", "objective", "obj", "." ]
def sampleTransform(self) ->None: r""" Returns a transformation (R,t) from link relative to link2, sampled at random from the space of transforms that satisfies the objective obj. """ return _robotsim.GeneralizedIKObjective_sampleTransform(self)
[ "def", "sampleTransform", "(", "self", ")", "->", "None", ":", "return", "_robotsim", ".", "GeneralizedIKObjective_sampleTransform", "(", "self", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/robotsim.py#L6632-L6638
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_pyio.py
python
RawIOBase.write
(self, b)
Write the given buffer to the IO stream. Returns the number of bytes written, which may be less than the length of b in bytes.
Write the given buffer to the IO stream.
[ "Write", "the", "given", "buffer", "to", "the", "IO", "stream", "." ]
def write(self, b): """Write the given buffer to the IO stream. Returns the number of bytes written, which may be less than the length of b in bytes. """ self._unsupported("write")
[ "def", "write", "(", "self", ",", "b", ")", ":", "self", ".", "_unsupported", "(", "\"write\"", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_pyio.py#L614-L620
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/pyrsistent/_pdeque.py
python
pdeque
(iterable=(), maxlen=None)
return PDeque(left, right, length, maxlen)
Return deque containing the elements of iterable. If maxlen is specified then len(iterable) - maxlen elements are discarded from the left to if len(iterable) > maxlen. >>> pdeque([1, 2, 3]) pdeque([1, 2, 3]) >>> pdeque([1, 2, 3, 4], maxlen=2) pdeque([3, 4], maxlen=2)
Return deque containing the elements of iterable. If maxlen is specified then len(iterable) - maxlen elements are discarded from the left to if len(iterable) > maxlen.
[ "Return", "deque", "containing", "the", "elements", "of", "iterable", ".", "If", "maxlen", "is", "specified", "then", "len", "(", "iterable", ")", "-", "maxlen", "elements", "are", "discarded", "from", "the", "left", "to", "if", "len", "(", "iterable", ")", ">", "maxlen", "." ]
def pdeque(iterable=(), maxlen=None): """ Return deque containing the elements of iterable. If maxlen is specified then len(iterable) - maxlen elements are discarded from the left to if len(iterable) > maxlen. >>> pdeque([1, 2, 3]) pdeque([1, 2, 3]) >>> pdeque([1, 2, 3, 4], maxlen=2) pdeque([3, 4], maxlen=2) """ t = tuple(iterable) if maxlen is not None: t = t[-maxlen:] length = len(t) pivot = int(length / 2) left = plist(t[:pivot]) right = plist(t[pivot:], reverse=True) return PDeque(left, right, length, maxlen)
[ "def", "pdeque", "(", "iterable", "=", "(", ")", ",", "maxlen", "=", "None", ")", ":", "t", "=", "tuple", "(", "iterable", ")", "if", "maxlen", "is", "not", "None", ":", "t", "=", "t", "[", "-", "maxlen", ":", "]", "length", "=", "len", "(", "t", ")", "pivot", "=", "int", "(", "length", "/", "2", ")", "left", "=", "plist", "(", "t", "[", ":", "pivot", "]", ")", "right", "=", "plist", "(", "t", "[", "pivot", ":", "]", ",", "reverse", "=", "True", ")", "return", "PDeque", "(", "left", ",", "right", ",", "length", ",", "maxlen", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/pyrsistent/_pdeque.py#L350-L367
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py2/pkg_resources/__init__.py
python
IResourceProvider.resource_isdir
(resource_name)
Is the named resource a directory? (like ``os.path.isdir()``)
Is the named resource a directory? (like ``os.path.isdir()``)
[ "Is", "the", "named", "resource", "a", "directory?", "(", "like", "os", ".", "path", ".", "isdir", "()", ")" ]
def resource_isdir(resource_name): """Is the named resource a directory? (like ``os.path.isdir()``)"""
[ "def", "resource_isdir", "(", "resource_name", ")", ":" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/pkg_resources/__init__.py#L546-L547
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/win32/Demos/desktopmanager.py
python
get_new_desktop_name
(parent_hwnd)
Create a dialog box to ask the user for name of desktop to be created
Create a dialog box to ask the user for name of desktop to be created
[ "Create", "a", "dialog", "box", "to", "ask", "the", "user", "for", "name", "of", "desktop", "to", "be", "created" ]
def get_new_desktop_name(parent_hwnd): """ Create a dialog box to ask the user for name of desktop to be created """ msgs={win32con.WM_COMMAND:desktop_name_dlgproc, win32con.WM_CLOSE:desktop_name_dlgproc, win32con.WM_DESTROY:desktop_name_dlgproc} # dlg item [type, caption, id, (x,y,cx,cy), style, ex style style=win32con.WS_BORDER|win32con.WS_VISIBLE|win32con.WS_CAPTION|win32con.WS_SYSMENU ## |win32con.DS_SYSMODAL h=win32gui.CreateDialogIndirect( win32api.GetModuleHandle(None), [['One ugly dialog box !',(100,100,200,100),style,0], ['Button','Create', win32con.IDOK, (10,10,30,20),win32con.WS_VISIBLE|win32con.WS_TABSTOP|win32con.BS_HOLLOW|win32con.BS_DEFPUSHBUTTON], ['Button','Never mind', win32con.IDCANCEL, (45,10,50,20),win32con.WS_VISIBLE|win32con.WS_TABSTOP|win32con.BS_HOLLOW], ['Static','Desktop name:',71,(10,40,70,10),win32con.WS_VISIBLE], ['Edit','',72,(75,40,90,10),win32con.WS_VISIBLE]], parent_hwnd, msgs) ## parent_hwnd, msgs) win32gui.EnableWindow(h,True) hcontrol=win32gui.GetDlgItem(h,72) win32gui.EnableWindow(hcontrol,True) win32gui.SetFocus(hcontrol)
[ "def", "get_new_desktop_name", "(", "parent_hwnd", ")", ":", "msgs", "=", "{", "win32con", ".", "WM_COMMAND", ":", "desktop_name_dlgproc", ",", "win32con", ".", "WM_CLOSE", ":", "desktop_name_dlgproc", ",", "win32con", ".", "WM_DESTROY", ":", "desktop_name_dlgproc", "}", "# dlg item [type, caption, id, (x,y,cx,cy), style, ex style", "style", "=", "win32con", ".", "WS_BORDER", "|", "win32con", ".", "WS_VISIBLE", "|", "win32con", ".", "WS_CAPTION", "|", "win32con", ".", "WS_SYSMENU", "## |win32con.DS_SYSMODAL", "h", "=", "win32gui", ".", "CreateDialogIndirect", "(", "win32api", ".", "GetModuleHandle", "(", "None", ")", ",", "[", "[", "'One ugly dialog box !'", ",", "(", "100", ",", "100", ",", "200", ",", "100", ")", ",", "style", ",", "0", "]", ",", "[", "'Button'", ",", "'Create'", ",", "win32con", ".", "IDOK", ",", "(", "10", ",", "10", ",", "30", ",", "20", ")", ",", "win32con", ".", "WS_VISIBLE", "|", "win32con", ".", "WS_TABSTOP", "|", "win32con", ".", "BS_HOLLOW", "|", "win32con", ".", "BS_DEFPUSHBUTTON", "]", ",", "[", "'Button'", ",", "'Never mind'", ",", "win32con", ".", "IDCANCEL", ",", "(", "45", ",", "10", ",", "50", ",", "20", ")", ",", "win32con", ".", "WS_VISIBLE", "|", "win32con", ".", "WS_TABSTOP", "|", "win32con", ".", "BS_HOLLOW", "]", ",", "[", "'Static'", ",", "'Desktop name:'", ",", "71", ",", "(", "10", ",", "40", ",", "70", ",", "10", ")", ",", "win32con", ".", "WS_VISIBLE", "]", ",", "[", "'Edit'", ",", "''", ",", "72", ",", "(", "75", ",", "40", ",", "90", ",", "10", ")", ",", "win32con", ".", "WS_VISIBLE", "]", "]", ",", "parent_hwnd", ",", "msgs", ")", "## parent_hwnd, msgs)", "win32gui", ".", "EnableWindow", "(", "h", ",", "True", ")", "hcontrol", "=", "win32gui", ".", "GetDlgItem", "(", "h", ",", "72", ")", "win32gui", ".", "EnableWindow", "(", "hcontrol", ",", "True", ")", "win32gui", ".", "SetFocus", "(", "hcontrol", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/win32/Demos/desktopmanager.py#L24-L43
google/llvm-propeller
45c226984fe8377ebfb2ad7713c680d652ba678d
lldb/utils/lui/lldbutil.py
python
print_stacktraces
(process, string_buffer=False)
Prints the stack traces of all the threads.
Prints the stack traces of all the threads.
[ "Prints", "the", "stack", "traces", "of", "all", "the", "threads", "." ]
def print_stacktraces(process, string_buffer=False): """Prints the stack traces of all the threads.""" output = io.StringIO() if string_buffer else sys.stdout print("Stack traces for " + str(process), file=output) for thread in process: print(print_stacktrace(thread, string_buffer=True), file=output) if string_buffer: return output.getvalue()
[ "def", "print_stacktraces", "(", "process", ",", "string_buffer", "=", "False", ")", ":", "output", "=", "io", ".", "StringIO", "(", ")", "if", "string_buffer", "else", "sys", ".", "stdout", "print", "(", "\"Stack traces for \"", "+", "str", "(", "process", ")", ",", "file", "=", "output", ")", "for", "thread", "in", "process", ":", "print", "(", "print_stacktrace", "(", "thread", ",", "string_buffer", "=", "True", ")", ",", "file", "=", "output", ")", "if", "string_buffer", ":", "return", "output", ".", "getvalue", "(", ")" ]
https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/lldb/utils/lui/lldbutil.py#L819-L830
chromiumembedded/cef
80caf947f3fe2210e5344713c5281d8af9bdc295
tools/yapf/yapf/yapflib/pytree_unwrapper.py
python
_DetermineMustSplitAnnotation
(node)
Enforce a split in the list if the list ends with a comma.
Enforce a split in the list if the list ends with a comma.
[ "Enforce", "a", "split", "in", "the", "list", "if", "the", "list", "ends", "with", "a", "comma", "." ]
def _DetermineMustSplitAnnotation(node): """Enforce a split in the list if the list ends with a comma.""" if not _ContainsComments(node): if (not isinstance(node.children[-1], pytree.Leaf) or node.children[-1].value != ','): return num_children = len(node.children) index = 0 _SetMustSplitOnFirstLeaf(node.children[0]) while index < num_children - 1: child = node.children[index] if isinstance(child, pytree.Leaf) and child.value == ',': next_child = node.children[index + 1] if next_child.type == grammar_token.COMMENT: index += 1 if index >= num_children - 1: break _SetMustSplitOnFirstLeaf(node.children[index + 1]) index += 1
[ "def", "_DetermineMustSplitAnnotation", "(", "node", ")", ":", "if", "not", "_ContainsComments", "(", "node", ")", ":", "if", "(", "not", "isinstance", "(", "node", ".", "children", "[", "-", "1", "]", ",", "pytree", ".", "Leaf", ")", "or", "node", ".", "children", "[", "-", "1", "]", ".", "value", "!=", "','", ")", ":", "return", "num_children", "=", "len", "(", "node", ".", "children", ")", "index", "=", "0", "_SetMustSplitOnFirstLeaf", "(", "node", ".", "children", "[", "0", "]", ")", "while", "index", "<", "num_children", "-", "1", ":", "child", "=", "node", ".", "children", "[", "index", "]", "if", "isinstance", "(", "child", ",", "pytree", ".", "Leaf", ")", "and", "child", ".", "value", "==", "','", ":", "next_child", "=", "node", ".", "children", "[", "index", "+", "1", "]", "if", "next_child", ".", "type", "==", "grammar_token", ".", "COMMENT", ":", "index", "+=", "1", "if", "index", ">=", "num_children", "-", "1", ":", "break", "_SetMustSplitOnFirstLeaf", "(", "node", ".", "children", "[", "index", "+", "1", "]", ")", "index", "+=", "1" ]
https://github.com/chromiumembedded/cef/blob/80caf947f3fe2210e5344713c5281d8af9bdc295/tools/yapf/yapf/yapflib/pytree_unwrapper.py#L336-L354
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/pickle.py
python
whichmodule
(func, funcname)
return name
Figure out the module in which a function occurs. Search sys.modules for the module. Cache in classmap. Return a module name. If the function cannot be found, return "__main__".
Figure out the module in which a function occurs.
[ "Figure", "out", "the", "module", "in", "which", "a", "function", "occurs", "." ]
def whichmodule(func, funcname): """Figure out the module in which a function occurs. Search sys.modules for the module. Cache in classmap. Return a module name. If the function cannot be found, return "__main__". """ # Python functions should always get an __module__ from their globals. mod = getattr(func, "__module__", None) if mod is not None: return mod if func in classmap: return classmap[func] for name, module in sys.modules.items(): if module is None: continue # skip dummy package entries if name != '__main__' and getattr(module, funcname, None) is func: break else: name = '__main__' classmap[func] = name return name
[ "def", "whichmodule", "(", "func", ",", "funcname", ")", ":", "# Python functions should always get an __module__ from their globals.", "mod", "=", "getattr", "(", "func", ",", "\"__module__\"", ",", "None", ")", "if", "mod", "is", "not", "None", ":", "return", "mod", "if", "func", "in", "classmap", ":", "return", "classmap", "[", "func", "]", "for", "name", ",", "module", "in", "sys", ".", "modules", ".", "items", "(", ")", ":", "if", "module", "is", "None", ":", "continue", "# skip dummy package entries", "if", "name", "!=", "'__main__'", "and", "getattr", "(", "module", ",", "funcname", ",", "None", ")", "is", "func", ":", "break", "else", ":", "name", "=", "'__main__'", "classmap", "[", "func", "]", "=", "name", "return", "name" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/pickle.py#L799-L822
google/certificate-transparency
2588562fd306a447958471b6f06c1069619c1641
python/ct/crypto/pem.py
python
PemWriter.write_blocks
(self, blobs)
Write PEM blobs. Args: blobs: an iterable of binary blobs. Raises: IOError: the file could not be written to.
Write PEM blobs.
[ "Write", "PEM", "blobs", "." ]
def write_blocks(self, blobs): """Write PEM blobs. Args: blobs: an iterable of binary blobs. Raises: IOError: the file could not be written to. """ check_newline = True for b in blobs: self.write(b, check_newline=check_newline) check_newline = False
[ "def", "write_blocks", "(", "self", ",", "blobs", ")", ":", "check_newline", "=", "True", "for", "b", "in", "blobs", ":", "self", ".", "write", "(", "b", ",", "check_newline", "=", "check_newline", ")", "check_newline", "=", "False" ]
https://github.com/google/certificate-transparency/blob/2588562fd306a447958471b6f06c1069619c1641/python/ct/crypto/pem.py#L257-L269
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/propgrid.py
python
PropertyGrid.SetupTextCtrlValue
(*args, **kwargs)
return _propgrid.PropertyGrid_SetupTextCtrlValue(*args, **kwargs)
SetupTextCtrlValue(self, String text)
SetupTextCtrlValue(self, String text)
[ "SetupTextCtrlValue", "(", "self", "String", "text", ")" ]
def SetupTextCtrlValue(*args, **kwargs): """SetupTextCtrlValue(self, String text)""" return _propgrid.PropertyGrid_SetupTextCtrlValue(*args, **kwargs)
[ "def", "SetupTextCtrlValue", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PropertyGrid_SetupTextCtrlValue", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/propgrid.py#L2443-L2445
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
VersionInfo.__init__
(self, *args, **kwargs)
__init__(self, String name, int major, int minor, int micro=0, String description=wxEmptyString, String copyright=wxEmptyString) -> VersionInfo
__init__(self, String name, int major, int minor, int micro=0, String description=wxEmptyString, String copyright=wxEmptyString) -> VersionInfo
[ "__init__", "(", "self", "String", "name", "int", "major", "int", "minor", "int", "micro", "=", "0", "String", "description", "=", "wxEmptyString", "String", "copyright", "=", "wxEmptyString", ")", "-", ">", "VersionInfo" ]
def __init__(self, *args, **kwargs): """ __init__(self, String name, int major, int minor, int micro=0, String description=wxEmptyString, String copyright=wxEmptyString) -> VersionInfo """ _core_.VersionInfo_swiginit(self,_core_.new_VersionInfo(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_core_", ".", "VersionInfo_swiginit", "(", "self", ",", "_core_", ".", "new_VersionInfo", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L16555-L16560
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/dummyarray.py
python
Array.iter_contiguous_extent
(self)
Generates extents
Generates extents
[ "Generates", "extents" ]
def iter_contiguous_extent(self): """ Generates extents """ if self.is_c_contig or self.is_f_contig: yield self.extent else: if self.dims[0].stride < self.dims[-1].stride: innerdim = self.dims[0] outerdims = self.dims[1:] outershape = self.shape[1:] else: innerdim = self.dims[-1] outerdims = self.dims[:-1] outershape = self.shape[:-1] if innerdim.is_contiguous(self.itemsize): oslen = [range(s) for s in outershape] for indices in itertools.product(*oslen): base = compute_index(indices, outerdims) yield base + innerdim.start, base + innerdim.stop else: oslen = [range(s) for s in self.shape] for indices in itertools.product(*oslen): offset = compute_index(indices, self.dims) yield offset, offset + self.itemsize
[ "def", "iter_contiguous_extent", "(", "self", ")", ":", "if", "self", ".", "is_c_contig", "or", "self", ".", "is_f_contig", ":", "yield", "self", ".", "extent", "else", ":", "if", "self", ".", "dims", "[", "0", "]", ".", "stride", "<", "self", ".", "dims", "[", "-", "1", "]", ".", "stride", ":", "innerdim", "=", "self", ".", "dims", "[", "0", "]", "outerdims", "=", "self", ".", "dims", "[", "1", ":", "]", "outershape", "=", "self", ".", "shape", "[", "1", ":", "]", "else", ":", "innerdim", "=", "self", ".", "dims", "[", "-", "1", "]", "outerdims", "=", "self", ".", "dims", "[", ":", "-", "1", "]", "outershape", "=", "self", ".", "shape", "[", ":", "-", "1", "]", "if", "innerdim", ".", "is_contiguous", "(", "self", ".", "itemsize", ")", ":", "oslen", "=", "[", "range", "(", "s", ")", "for", "s", "in", "outershape", "]", "for", "indices", "in", "itertools", ".", "product", "(", "*", "oslen", ")", ":", "base", "=", "compute_index", "(", "indices", ",", "outerdims", ")", "yield", "base", "+", "innerdim", ".", "start", ",", "base", "+", "innerdim", ".", "stop", "else", ":", "oslen", "=", "[", "range", "(", "s", ")", "for", "s", "in", "self", ".", "shape", "]", "for", "indices", "in", "itertools", ".", "product", "(", "*", "oslen", ")", ":", "offset", "=", "compute_index", "(", "indices", ",", "self", ".", "dims", ")", "yield", "offset", ",", "offset", "+", "self", ".", "itemsize" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/dummyarray.py#L238-L262
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/xml/etree/ElementTree.py
python
XMLParser.doctype
(self, name, pubid, system)
This method of XMLParser is deprecated.
This method of XMLParser is deprecated.
[ "This", "method", "of", "XMLParser", "is", "deprecated", "." ]
def doctype(self, name, pubid, system): """This method of XMLParser is deprecated.""" warnings.warn( "This method of XMLParser is deprecated. Define doctype() " "method on the TreeBuilder target.", DeprecationWarning, )
[ "def", "doctype", "(", "self", ",", "name", ",", "pubid", ",", "system", ")", ":", "warnings", ".", "warn", "(", "\"This method of XMLParser is deprecated. Define doctype() \"", "\"method on the TreeBuilder target.\"", ",", "DeprecationWarning", ",", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/xml/etree/ElementTree.py#L1622-L1628
ZeroCM/zcm
a4f8a1c2d81414a13116a70c0979b1bf546866df
waftools/wafcache.py
python
fcache.copy_from_cache
(self, sig, files_from, files_to)
return OK
Copy files from the cache
Copy files from the cache
[ "Copy", "files", "from", "the", "cache" ]
def copy_from_cache(self, sig, files_from, files_to): """ Copy files from the cache """ try: for i, x in enumerate(files_to): orig = os.path.join(CACHE_DIR, sig[:2], sig, str(i)) atomic_copy(orig, x) # success! update the cache time os.utime(os.path.join(CACHE_DIR, sig[:2], sig), None) except Exception: return traceback.format_exc() return OK
[ "def", "copy_from_cache", "(", "self", ",", "sig", ",", "files_from", ",", "files_to", ")", ":", "try", ":", "for", "i", ",", "x", "in", "enumerate", "(", "files_to", ")", ":", "orig", "=", "os", ".", "path", ".", "join", "(", "CACHE_DIR", ",", "sig", "[", ":", "2", "]", ",", "sig", ",", "str", "(", "i", ")", ")", "atomic_copy", "(", "orig", ",", "x", ")", "# success! update the cache time", "os", ".", "utime", "(", "os", ".", "path", ".", "join", "(", "CACHE_DIR", ",", "sig", "[", ":", "2", "]", ",", "sig", ")", ",", "None", ")", "except", "Exception", ":", "return", "traceback", ".", "format_exc", "(", ")", "return", "OK" ]
https://github.com/ZeroCM/zcm/blob/a4f8a1c2d81414a13116a70c0979b1bf546866df/waftools/wafcache.py#L484-L497
su2code/SU2
72b2fa977b64b9683a388920f05298a40d39e5c5
SU2_PY/config_gui.py
python
prepare_data
()
return option_data
Method to get configuration data from source files. Outputs a dictionary of categories as keys and lists of config_options as values
Method to get configuration data from source files. Outputs a dictionary of categories as keys and lists of config_options as values
[ "Method", "to", "get", "configuration", "data", "from", "source", "files", ".", "Outputs", "a", "dictionary", "of", "categories", "as", "keys", "and", "lists", "of", "config_options", "as", "values" ]
def prepare_data(): """ Method to get configuration data from source files. Outputs a dictionary of categories as keys and lists of config_options as values """ # These variables should point to the configuration files su2_basedir = os.environ['SU2_HOME'] config_cpp = os.path.join(su2_basedir,'Common/src/config_structure.cpp') config_hpp = os.path.join(su2_basedir,'Common/include/option_structure.hpp') # Check that files exist if not os.path.isfile(config_cpp): sys.exit('Could not find cpp file, please check that su2_basedir is set correctly in config_gui.py') if not os.path.isfile(config_hpp): sys.exit('Could not find hpp file, please check that su2_basedir is set correctly in config_gui.py') # Run the parser option_list = parse_config(config_cpp, config_hpp) # Organize data into dictionary with categories as keys option_data = {} for opt in option_list: if not opt.option_category in option_data: option_data[opt.option_category] = [] option_data[opt.option_category].append(opt) return option_data
[ "def", "prepare_data", "(", ")", ":", "# These variables should point to the configuration files", "su2_basedir", "=", "os", ".", "environ", "[", "'SU2_HOME'", "]", "config_cpp", "=", "os", ".", "path", ".", "join", "(", "su2_basedir", ",", "'Common/src/config_structure.cpp'", ")", "config_hpp", "=", "os", ".", "path", ".", "join", "(", "su2_basedir", ",", "'Common/include/option_structure.hpp'", ")", "# Check that files exist", "if", "not", "os", ".", "path", ".", "isfile", "(", "config_cpp", ")", ":", "sys", ".", "exit", "(", "'Could not find cpp file, please check that su2_basedir is set correctly in config_gui.py'", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "config_hpp", ")", ":", "sys", ".", "exit", "(", "'Could not find hpp file, please check that su2_basedir is set correctly in config_gui.py'", ")", "# Run the parser", "option_list", "=", "parse_config", "(", "config_cpp", ",", "config_hpp", ")", "# Organize data into dictionary with categories as keys", "option_data", "=", "{", "}", "for", "opt", "in", "option_list", ":", "if", "not", "opt", ".", "option_category", "in", "option_data", ":", "option_data", "[", "opt", ".", "option_category", "]", "=", "[", "]", "option_data", "[", "opt", ".", "option_category", "]", ".", "append", "(", "opt", ")", "return", "option_data" ]
https://github.com/su2code/SU2/blob/72b2fa977b64b9683a388920f05298a40d39e5c5/SU2_PY/config_gui.py#L282-L308
mapnik/mapnik
f3da900c355e1d15059c4a91b00203dcc9d9f0ef
scons/scons-local-4.1.0/SCons/Script/Interactive.py
python
SConsInteractiveCmd.do_build
(self, argv)
\ build [TARGETS] Build the specified TARGETS and their dependencies. 'b' is a synonym.
\ build [TARGETS] Build the specified TARGETS and their dependencies. 'b' is a synonym.
[ "\\", "build", "[", "TARGETS", "]", "Build", "the", "specified", "TARGETS", "and", "their", "dependencies", ".", "b", "is", "a", "synonym", "." ]
def do_build(self, argv): """\ build [TARGETS] Build the specified TARGETS and their dependencies. 'b' is a synonym. """ import SCons.Node import SCons.SConsign import SCons.Script.Main options = copy.deepcopy(self.options) options, targets = self.parser.parse_args(argv[1:], values=options) SCons.Script.COMMAND_LINE_TARGETS = targets if targets: SCons.Script.BUILD_TARGETS = targets else: # If the user didn't specify any targets on the command line, # use the list of default targets. SCons.Script.BUILD_TARGETS = SCons.Script._build_plus_default nodes = SCons.Script.Main._build_targets(self.fs, options, targets, self.target_top) if not nodes: return # Call each of the Node's alter_targets() methods, which may # provide additional targets that ended up as part of the build # (the canonical example being a VariantDir() when we're building # from a source directory) and which we therefore need their # state cleared, too. x = [] for n in nodes: x.extend(n.alter_targets()[0]) nodes.extend(x) # Clean up so that we can perform the next build correctly. # # We do this by walking over all the children of the targets, # and clearing their state. # # We currently have to re-scan each node to find their # children, because built nodes have already been partially # cleared and don't remember their children. (In scons # 0.96.1 and earlier, this wasn't the case, and we didn't # have to re-scan the nodes.) # # Because we have to re-scan each node, we can't clear the # nodes as we walk over them, because we may end up rescanning # a cleared node as we scan a later node. Therefore, only # store the list of nodes that need to be cleared as we walk # the tree, and clear them in a separate pass. # # XXX: Someone more familiar with the inner workings of scons # may be able to point out a more efficient way to do this. SCons.Script.Main.progress_display("scons: Clearing cached node information ...") seen_nodes = {} def get_unseen_children(node, parent, seen_nodes=seen_nodes): def is_unseen(node, seen_nodes=seen_nodes): return node not in seen_nodes return [child for child in node.children(scan=1) if is_unseen(child)] def add_to_seen_nodes(node, parent, seen_nodes=seen_nodes): seen_nodes[node] = 1 # If this file is in a VariantDir and has a # corresponding source file in the source tree, remember the # node in the source tree, too. This is needed in # particular to clear cached implicit dependencies on the # source file, since the scanner will scan it if the # VariantDir was created with duplicate=0. try: rfile_method = node.rfile except AttributeError: return else: rfile = rfile_method() if rfile != node: seen_nodes[rfile] = 1 for node in nodes: walker = SCons.Node.Walker(node, kids_func=get_unseen_children, eval_func=add_to_seen_nodes) n = walker.get_next() while n: n = walker.get_next() for node in seen_nodes.keys(): # Call node.clear() to clear most of the state node.clear() # node.clear() doesn't reset node.state, so call # node.set_state() to reset it manually node.set_state(SCons.Node.no_state) node.implicit = None # Debug: Uncomment to verify that all Taskmaster reference # counts have been reset to zero. #if node.ref_count != 0: # from SCons.Debug import Trace # Trace('node %s, ref_count %s !!!\n' % (node, node.ref_count)) SCons.SConsign.Reset() SCons.Script.Main.progress_display("scons: done clearing node information.")
[ "def", "do_build", "(", "self", ",", "argv", ")", ":", "import", "SCons", ".", "Node", "import", "SCons", ".", "SConsign", "import", "SCons", ".", "Script", ".", "Main", "options", "=", "copy", ".", "deepcopy", "(", "self", ".", "options", ")", "options", ",", "targets", "=", "self", ".", "parser", ".", "parse_args", "(", "argv", "[", "1", ":", "]", ",", "values", "=", "options", ")", "SCons", ".", "Script", ".", "COMMAND_LINE_TARGETS", "=", "targets", "if", "targets", ":", "SCons", ".", "Script", ".", "BUILD_TARGETS", "=", "targets", "else", ":", "# If the user didn't specify any targets on the command line,", "# use the list of default targets.", "SCons", ".", "Script", ".", "BUILD_TARGETS", "=", "SCons", ".", "Script", ".", "_build_plus_default", "nodes", "=", "SCons", ".", "Script", ".", "Main", ".", "_build_targets", "(", "self", ".", "fs", ",", "options", ",", "targets", ",", "self", ".", "target_top", ")", "if", "not", "nodes", ":", "return", "# Call each of the Node's alter_targets() methods, which may", "# provide additional targets that ended up as part of the build", "# (the canonical example being a VariantDir() when we're building", "# from a source directory) and which we therefore need their", "# state cleared, too.", "x", "=", "[", "]", "for", "n", "in", "nodes", ":", "x", ".", "extend", "(", "n", ".", "alter_targets", "(", ")", "[", "0", "]", ")", "nodes", ".", "extend", "(", "x", ")", "# Clean up so that we can perform the next build correctly.", "#", "# We do this by walking over all the children of the targets,", "# and clearing their state.", "#", "# We currently have to re-scan each node to find their", "# children, because built nodes have already been partially", "# cleared and don't remember their children. (In scons", "# 0.96.1 and earlier, this wasn't the case, and we didn't", "# have to re-scan the nodes.)", "#", "# Because we have to re-scan each node, we can't clear the", "# nodes as we walk over them, because we may end up rescanning", "# a cleared node as we scan a later node. Therefore, only", "# store the list of nodes that need to be cleared as we walk", "# the tree, and clear them in a separate pass.", "#", "# XXX: Someone more familiar with the inner workings of scons", "# may be able to point out a more efficient way to do this.", "SCons", ".", "Script", ".", "Main", ".", "progress_display", "(", "\"scons: Clearing cached node information ...\"", ")", "seen_nodes", "=", "{", "}", "def", "get_unseen_children", "(", "node", ",", "parent", ",", "seen_nodes", "=", "seen_nodes", ")", ":", "def", "is_unseen", "(", "node", ",", "seen_nodes", "=", "seen_nodes", ")", ":", "return", "node", "not", "in", "seen_nodes", "return", "[", "child", "for", "child", "in", "node", ".", "children", "(", "scan", "=", "1", ")", "if", "is_unseen", "(", "child", ")", "]", "def", "add_to_seen_nodes", "(", "node", ",", "parent", ",", "seen_nodes", "=", "seen_nodes", ")", ":", "seen_nodes", "[", "node", "]", "=", "1", "# If this file is in a VariantDir and has a", "# corresponding source file in the source tree, remember the", "# node in the source tree, too. This is needed in", "# particular to clear cached implicit dependencies on the", "# source file, since the scanner will scan it if the", "# VariantDir was created with duplicate=0.", "try", ":", "rfile_method", "=", "node", ".", "rfile", "except", "AttributeError", ":", "return", "else", ":", "rfile", "=", "rfile_method", "(", ")", "if", "rfile", "!=", "node", ":", "seen_nodes", "[", "rfile", "]", "=", "1", "for", "node", "in", "nodes", ":", "walker", "=", "SCons", ".", "Node", ".", "Walker", "(", "node", ",", "kids_func", "=", "get_unseen_children", ",", "eval_func", "=", "add_to_seen_nodes", ")", "n", "=", "walker", ".", "get_next", "(", ")", "while", "n", ":", "n", "=", "walker", ".", "get_next", "(", ")", "for", "node", "in", "seen_nodes", ".", "keys", "(", ")", ":", "# Call node.clear() to clear most of the state", "node", ".", "clear", "(", ")", "# node.clear() doesn't reset node.state, so call", "# node.set_state() to reset it manually", "node", ".", "set_state", "(", "SCons", ".", "Node", ".", "no_state", ")", "node", ".", "implicit", "=", "None", "# Debug: Uncomment to verify that all Taskmaster reference", "# counts have been reset to zero.", "#if node.ref_count != 0:", "# from SCons.Debug import Trace", "# Trace('node %s, ref_count %s !!!\\n' % (node, node.ref_count))", "SCons", ".", "SConsign", ".", "Reset", "(", ")", "SCons", ".", "Script", ".", "Main", ".", "progress_display", "(", "\"scons: done clearing node information.\"", ")" ]
https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Script/Interactive.py#L151-L261
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/html.py
python
HtmlWindowInterface.GetHTMLBackgroundColour
(*args, **kwargs)
return _html.HtmlWindowInterface_GetHTMLBackgroundColour(*args, **kwargs)
GetHTMLBackgroundColour(self) -> Colour
GetHTMLBackgroundColour(self) -> Colour
[ "GetHTMLBackgroundColour", "(", "self", ")", "-", ">", "Colour" ]
def GetHTMLBackgroundColour(*args, **kwargs): """GetHTMLBackgroundColour(self) -> Colour""" return _html.HtmlWindowInterface_GetHTMLBackgroundColour(*args, **kwargs)
[ "def", "GetHTMLBackgroundColour", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_html", ".", "HtmlWindowInterface_GetHTMLBackgroundColour", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/html.py#L936-L938
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/jinja2/filters.py
python
do_reject
(*args, **kwargs)
return _select_or_reject(args, kwargs, lambda x: not x, False)
Filters a sequence of objects by appying a test to either the object or the attribute and rejecting the ones with the test succeeding. Example usage: .. sourcecode:: jinja {{ numbers|reject("odd") }} .. versionadded:: 2.7
Filters a sequence of objects by appying a test to either the object or the attribute and rejecting the ones with the test succeeding.
[ "Filters", "a", "sequence", "of", "objects", "by", "appying", "a", "test", "to", "either", "the", "object", "or", "the", "attribute", "and", "rejecting", "the", "ones", "with", "the", "test", "succeeding", "." ]
def do_reject(*args, **kwargs): """Filters a sequence of objects by appying a test to either the object or the attribute and rejecting the ones with the test succeeding. Example usage: .. sourcecode:: jinja {{ numbers|reject("odd") }} .. versionadded:: 2.7 """ return _select_or_reject(args, kwargs, lambda x: not x, False)
[ "def", "do_reject", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_select_or_reject", "(", "args", ",", "kwargs", ",", "lambda", "x", ":", "not", "x", ",", "False", ")" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/jinja2/filters.py#L860-L872
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/_vendor/ordered_set.py
python
is_iterable
(obj)
return ( hasattr(obj, "__iter__") and not isinstance(obj, str) and not isinstance(obj, tuple) )
Are we being asked to look up a list of things, instead of a single thing? We check for the `__iter__` attribute so that this can cover types that don't have to be known by this module, such as NumPy arrays. Strings, however, should be considered as atomic values to look up, not iterables. The same goes for tuples, since they are immutable and therefore valid entries. We don't need to check for the Python 2 `unicode` type, because it doesn't have an `__iter__` attribute anyway.
Are we being asked to look up a list of things, instead of a single thing? We check for the `__iter__` attribute so that this can cover types that don't have to be known by this module, such as NumPy arrays.
[ "Are", "we", "being", "asked", "to", "look", "up", "a", "list", "of", "things", "instead", "of", "a", "single", "thing?", "We", "check", "for", "the", "__iter__", "attribute", "so", "that", "this", "can", "cover", "types", "that", "don", "t", "have", "to", "be", "known", "by", "this", "module", "such", "as", "NumPy", "arrays", "." ]
def is_iterable(obj): """ Are we being asked to look up a list of things, instead of a single thing? We check for the `__iter__` attribute so that this can cover types that don't have to be known by this module, such as NumPy arrays. Strings, however, should be considered as atomic values to look up, not iterables. The same goes for tuples, since they are immutable and therefore valid entries. We don't need to check for the Python 2 `unicode` type, because it doesn't have an `__iter__` attribute anyway. """ return ( hasattr(obj, "__iter__") and not isinstance(obj, str) and not isinstance(obj, tuple) )
[ "def", "is_iterable", "(", "obj", ")", ":", "return", "(", "hasattr", "(", "obj", ",", "\"__iter__\"", ")", "and", "not", "isinstance", "(", "obj", ",", "str", ")", "and", "not", "isinstance", "(", "obj", ",", "tuple", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/_vendor/ordered_set.py#L22-L39
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/scipy/optimize/line_search.py
python
LineSearch.__init__
(self, func)
Initialize LineSearch.
Initialize LineSearch.
[ "Initialize", "LineSearch", "." ]
def __init__(self, func): """Initialize LineSearch.""" super(LineSearch, self).__init__() self.func = func
[ "def", "__init__", "(", "self", ",", "func", ")", ":", "super", "(", "LineSearch", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "func", "=", "func" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/scipy/optimize/line_search.py#L190-L193
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
commonTools/release/updateTrilinosDB.py
python
database_stats
(package_db)
return {"Total number of packages" : num_packages, "Number of Trilinos packages" : num_trilinos_packages, "Number of Trilinos sub-packages" : num_trilinos_sub_packages, "Number of third-party libraries" : num_tpls }
Return a dictionary storing statistical information about the given package database.
Return a dictionary storing statistical information about the given package database.
[ "Return", "a", "dictionary", "storing", "statistical", "information", "about", "the", "given", "package", "database", "." ]
def database_stats(package_db): """ Return a dictionary storing statistical information about the given package database. """ num_packages = len(package_db) num_trilinos_packages = 0 num_trilinos_sub_packages = 0 num_tpls = 0 for packageData in package_db.values(): name = packageData["name" ] parent = packageData["parent"] if name == "Trilinos": pass elif parent.startswith("Trilinos"): num_trilinos_packages += 1 elif parent == "": num_tpls += 1 else: num_trilinos_sub_packages += 1 return {"Total number of packages" : num_packages, "Number of Trilinos packages" : num_trilinos_packages, "Number of Trilinos sub-packages" : num_trilinos_sub_packages, "Number of third-party libraries" : num_tpls }
[ "def", "database_stats", "(", "package_db", ")", ":", "num_packages", "=", "len", "(", "package_db", ")", "num_trilinos_packages", "=", "0", "num_trilinos_sub_packages", "=", "0", "num_tpls", "=", "0", "for", "packageData", "in", "package_db", ".", "values", "(", ")", ":", "name", "=", "packageData", "[", "\"name\"", "]", "parent", "=", "packageData", "[", "\"parent\"", "]", "if", "name", "==", "\"Trilinos\"", ":", "pass", "elif", "parent", ".", "startswith", "(", "\"Trilinos\"", ")", ":", "num_trilinos_packages", "+=", "1", "elif", "parent", "==", "\"\"", ":", "num_tpls", "+=", "1", "else", ":", "num_trilinos_sub_packages", "+=", "1", "return", "{", "\"Total number of packages\"", ":", "num_packages", ",", "\"Number of Trilinos packages\"", ":", "num_trilinos_packages", ",", "\"Number of Trilinos sub-packages\"", ":", "num_trilinos_sub_packages", ",", "\"Number of third-party libraries\"", ":", "num_tpls", "}" ]
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/commonTools/release/updateTrilinosDB.py#L329-L353
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
PNEANet.GetEAStrI
(self, *args)
return _snap.PNEANet_GetEAStrI(self, *args)
GetEAStrI(PNEANet self, TStr attr, int const & EId) -> TNEANet::TAStrI Parameters: attr: TStr const & EId: int const &
GetEAStrI(PNEANet self, TStr attr, int const & EId) -> TNEANet::TAStrI
[ "GetEAStrI", "(", "PNEANet", "self", "TStr", "attr", "int", "const", "&", "EId", ")", "-", ">", "TNEANet", "::", "TAStrI" ]
def GetEAStrI(self, *args): """ GetEAStrI(PNEANet self, TStr attr, int const & EId) -> TNEANet::TAStrI Parameters: attr: TStr const & EId: int const & """ return _snap.PNEANet_GetEAStrI(self, *args)
[ "def", "GetEAStrI", "(", "self", ",", "*", "args", ")", ":", "return", "_snap", ".", "PNEANet_GetEAStrI", "(", "self", ",", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L23685-L23694
envoyproxy/envoy-wasm
ab5d9381fdf92a1efa0b87cff80036b5b3e81198
source/extensions/filters/network/kafka/protocol/generator.py
python
Complex.compute_constructors
(self)
return sorted(signature_to_constructor.values(), key=lambda x: x['versions'][0])
Field lists for different versions may not differ (as Kafka can bump version without any changes). But constructors need to be unique, so we need to remove duplicates if the signatures match.
Field lists for different versions may not differ (as Kafka can bump version without any changes). But constructors need to be unique, so we need to remove duplicates if the signatures match.
[ "Field", "lists", "for", "different", "versions", "may", "not", "differ", "(", "as", "Kafka", "can", "bump", "version", "without", "any", "changes", ")", ".", "But", "constructors", "need", "to", "be", "unique", "so", "we", "need", "to", "remove", "duplicates", "if", "the", "signatures", "match", "." ]
def compute_constructors(self): """ Field lists for different versions may not differ (as Kafka can bump version without any changes). But constructors need to be unique, so we need to remove duplicates if the signatures match. """ signature_to_constructor = {} for field_list in self.compute_field_lists(): signature = field_list.constructor_signature() constructor = signature_to_constructor.get(signature) if constructor is None: entry = {} entry['versions'] = [field_list.version] entry['signature'] = signature if (len(signature) > 0): entry['full_declaration'] = '%s(%s): %s {};' % (self.name, signature, field_list.constructor_init_list()) else: entry['full_declaration'] = '%s() {};' % self.name signature_to_constructor[signature] = entry else: constructor['versions'].append(field_list.version) return sorted(signature_to_constructor.values(), key=lambda x: x['versions'][0])
[ "def", "compute_constructors", "(", "self", ")", ":", "signature_to_constructor", "=", "{", "}", "for", "field_list", "in", "self", ".", "compute_field_lists", "(", ")", ":", "signature", "=", "field_list", ".", "constructor_signature", "(", ")", "constructor", "=", "signature_to_constructor", ".", "get", "(", "signature", ")", "if", "constructor", "is", "None", ":", "entry", "=", "{", "}", "entry", "[", "'versions'", "]", "=", "[", "field_list", ".", "version", "]", "entry", "[", "'signature'", "]", "=", "signature", "if", "(", "len", "(", "signature", ")", ">", "0", ")", ":", "entry", "[", "'full_declaration'", "]", "=", "'%s(%s): %s {};'", "%", "(", "self", ".", "name", ",", "signature", ",", "field_list", ".", "constructor_init_list", "(", ")", ")", "else", ":", "entry", "[", "'full_declaration'", "]", "=", "'%s() {};'", "%", "self", ".", "name", "signature_to_constructor", "[", "signature", "]", "=", "entry", "else", ":", "constructor", "[", "'versions'", "]", ".", "append", "(", "field_list", ".", "version", ")", "return", "sorted", "(", "signature_to_constructor", ".", "values", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", "[", "'versions'", "]", "[", "0", "]", ")" ]
https://github.com/envoyproxy/envoy-wasm/blob/ab5d9381fdf92a1efa0b87cff80036b5b3e81198/source/extensions/filters/network/kafka/protocol/generator.py#L621-L643
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/stc.py
python
StyledTextCtrl.SelectionIsRectangle
(*args, **kwargs)
return _stc.StyledTextCtrl_SelectionIsRectangle(*args, **kwargs)
SelectionIsRectangle(self) -> bool Is the selection rectangular? The alternative is the more common stream selection.
SelectionIsRectangle(self) -> bool
[ "SelectionIsRectangle", "(", "self", ")", "-", ">", "bool" ]
def SelectionIsRectangle(*args, **kwargs): """ SelectionIsRectangle(self) -> bool Is the selection rectangular? The alternative is the more common stream selection. """ return _stc.StyledTextCtrl_SelectionIsRectangle(*args, **kwargs)
[ "def", "SelectionIsRectangle", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_SelectionIsRectangle", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L4964-L4970
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/build/android/pylib/symbols/deobfuscator.py
python
Deobfuscator.TransformLines
(self, lines)
Deobfuscates obfuscated names found in the given lines. If anything goes wrong (process crashes, timeout, etc), returns |lines|. Args: lines: A list of strings without trailing newlines. Returns: A list of strings without trailing newlines.
Deobfuscates obfuscated names found in the given lines.
[ "Deobfuscates", "obfuscated", "names", "found", "in", "the", "given", "lines", "." ]
def TransformLines(self, lines): """Deobfuscates obfuscated names found in the given lines. If anything goes wrong (process crashes, timeout, etc), returns |lines|. Args: lines: A list of strings without trailing newlines. Returns: A list of strings without trailing newlines. """ if not lines: return [] # Deobfuscated stacks contain more frames than obfuscated ones when method # inlining occurs. To account for the extra output lines, keep reading until # this eof_line token is reached. eof_line = uuid.uuid4().hex out_lines = [] def deobfuscate_reader(): while True: line = self._proc.stdout.readline() # Return an empty string at EOF (when stdin is closed). if not line: break line = line[:-1] if line == eof_line: break out_lines.append(line) if self.IsBusy(): logging.warning('deobfuscator: Having to wait for Java deobfuscation.') # Allow only one thread to operate at a time. with self._lock: if self.IsClosed(): if not self._closed_called: logging.warning('deobfuscator: Process exited with code=%d.', self._proc.returncode) self.Close() return lines # TODO(agrieve): Can probably speed this up by only sending lines through # that might contain an obfuscated name. reader_thread = reraiser_thread.ReraiserThread(deobfuscate_reader) reader_thread.start() try: self._proc.stdin.write('\n'.join(lines)) self._proc.stdin.write('\n{}\n'.format(eof_line)) self._proc.stdin.flush() time_since_proc_start = time.time() - self._proc_start_time timeout = (max(0, _PROCESS_START_TIMEOUT - time_since_proc_start) + max(_MINIUMUM_TIMEOUT, len(lines) * _PER_LINE_TIMEOUT)) reader_thread.join(timeout) if self.IsClosed(): logging.warning( 'deobfuscator: Close() called by another thread during join().') return lines if reader_thread.is_alive(): logging.error('deobfuscator: Timed out.') self.Close() return lines return out_lines except IOError: logging.exception('deobfuscator: Exception during java_deobfuscate') self.Close() return lines
[ "def", "TransformLines", "(", "self", ",", "lines", ")", ":", "if", "not", "lines", ":", "return", "[", "]", "# Deobfuscated stacks contain more frames than obfuscated ones when method", "# inlining occurs. To account for the extra output lines, keep reading until", "# this eof_line token is reached.", "eof_line", "=", "uuid", ".", "uuid4", "(", ")", ".", "hex", "out_lines", "=", "[", "]", "def", "deobfuscate_reader", "(", ")", ":", "while", "True", ":", "line", "=", "self", ".", "_proc", ".", "stdout", ".", "readline", "(", ")", "# Return an empty string at EOF (when stdin is closed).", "if", "not", "line", ":", "break", "line", "=", "line", "[", ":", "-", "1", "]", "if", "line", "==", "eof_line", ":", "break", "out_lines", ".", "append", "(", "line", ")", "if", "self", ".", "IsBusy", "(", ")", ":", "logging", ".", "warning", "(", "'deobfuscator: Having to wait for Java deobfuscation.'", ")", "# Allow only one thread to operate at a time.", "with", "self", ".", "_lock", ":", "if", "self", ".", "IsClosed", "(", ")", ":", "if", "not", "self", ".", "_closed_called", ":", "logging", ".", "warning", "(", "'deobfuscator: Process exited with code=%d.'", ",", "self", ".", "_proc", ".", "returncode", ")", "self", ".", "Close", "(", ")", "return", "lines", "# TODO(agrieve): Can probably speed this up by only sending lines through", "# that might contain an obfuscated name.", "reader_thread", "=", "reraiser_thread", ".", "ReraiserThread", "(", "deobfuscate_reader", ")", "reader_thread", ".", "start", "(", ")", "try", ":", "self", ".", "_proc", ".", "stdin", ".", "write", "(", "'\\n'", ".", "join", "(", "lines", ")", ")", "self", ".", "_proc", ".", "stdin", ".", "write", "(", "'\\n{}\\n'", ".", "format", "(", "eof_line", ")", ")", "self", ".", "_proc", ".", "stdin", ".", "flush", "(", ")", "time_since_proc_start", "=", "time", ".", "time", "(", ")", "-", "self", ".", "_proc_start_time", "timeout", "=", "(", "max", "(", "0", ",", "_PROCESS_START_TIMEOUT", "-", "time_since_proc_start", ")", "+", "max", "(", "_MINIUMUM_TIMEOUT", ",", "len", "(", "lines", ")", "*", "_PER_LINE_TIMEOUT", ")", ")", "reader_thread", ".", "join", "(", "timeout", ")", "if", "self", ".", "IsClosed", "(", ")", ":", "logging", ".", "warning", "(", "'deobfuscator: Close() called by another thread during join().'", ")", "return", "lines", "if", "reader_thread", ".", "is_alive", "(", ")", ":", "logging", ".", "error", "(", "'deobfuscator: Timed out.'", ")", "self", ".", "Close", "(", ")", "return", "lines", "return", "out_lines", "except", "IOError", ":", "logging", ".", "exception", "(", "'deobfuscator: Exception during java_deobfuscate'", ")", "self", ".", "Close", "(", ")", "return", "lines" ]
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/android/pylib/symbols/deobfuscator.py#L52-L120
Evolving-AI-Lab/fooling
66f097dd6bd2eb6794ade3e187a7adfdf1887688
caffe/python/caffe/io.py
python
datum_to_array
(datum)
Converts a datum to an array. Note that the label is not returned, as one can easily get it by calling datum.label.
Converts a datum to an array. Note that the label is not returned, as one can easily get it by calling datum.label.
[ "Converts", "a", "datum", "to", "an", "array", ".", "Note", "that", "the", "label", "is", "not", "returned", "as", "one", "can", "easily", "get", "it", "by", "calling", "datum", ".", "label", "." ]
def datum_to_array(datum): """Converts a datum to an array. Note that the label is not returned, as one can easily get it by calling datum.label. """ if len(datum.data): return np.fromstring(datum.data, dtype = np.uint8).reshape( datum.channels, datum.height, datum.width) else: return np.array(datum.float_data).astype(float).reshape( datum.channels, datum.height, datum.width)
[ "def", "datum_to_array", "(", "datum", ")", ":", "if", "len", "(", "datum", ".", "data", ")", ":", "return", "np", ".", "fromstring", "(", "datum", ".", "data", ",", "dtype", "=", "np", ".", "uint8", ")", ".", "reshape", "(", "datum", ".", "channels", ",", "datum", ".", "height", ",", "datum", ".", "width", ")", "else", ":", "return", "np", ".", "array", "(", "datum", ".", "float_data", ")", ".", "astype", "(", "float", ")", ".", "reshape", "(", "datum", ".", "channels", ",", "datum", ".", "height", ",", "datum", ".", "width", ")" ]
https://github.com/Evolving-AI-Lab/fooling/blob/66f097dd6bd2eb6794ade3e187a7adfdf1887688/caffe/python/caffe/io.py#L150-L159
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/ndarray/ndarray.py
python
NDArray.__hash__
(self)
return id(self)//16
Default hash function.
Default hash function.
[ "Default", "hash", "function", "." ]
def __hash__(self): """Default hash function.""" return id(self)//16
[ "def", "__hash__", "(", "self", ")", ":", "return", "id", "(", "self", ")", "//", "16" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/ndarray/ndarray.py#L425-L427
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/bitstring/bitstring.py
python
Bits._setsie
(self, i)
Initialise bitstring with signed interleaved exponential-Golomb code for integer i.
Initialise bitstring with signed interleaved exponential-Golomb code for integer i.
[ "Initialise", "bitstring", "with", "signed", "interleaved", "exponential", "-", "Golomb", "code", "for", "integer", "i", "." ]
def _setsie(self, i): """Initialise bitstring with signed interleaved exponential-Golomb code for integer i.""" if not i: self._setbin_unsafe('1') else: self._setuie(abs(i)) self._append(Bits([i < 0]))
[ "def", "_setsie", "(", "self", ",", "i", ")", ":", "if", "not", "i", ":", "self", ".", "_setbin_unsafe", "(", "'1'", ")", "else", ":", "self", ".", "_setuie", "(", "abs", "(", "i", ")", ")", "self", ".", "_append", "(", "Bits", "(", "[", "i", "<", "0", "]", ")", ")" ]
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/bitstring/bitstring.py#L1758-L1764
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/html.py
python
HtmlRenderingState.GetBgColour
(*args, **kwargs)
return _html.HtmlRenderingState_GetBgColour(*args, **kwargs)
GetBgColour(self) -> Colour
GetBgColour(self) -> Colour
[ "GetBgColour", "(", "self", ")", "-", ">", "Colour" ]
def GetBgColour(*args, **kwargs): """GetBgColour(self) -> Colour""" return _html.HtmlRenderingState_GetBgColour(*args, **kwargs)
[ "def", "GetBgColour", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_html", ".", "HtmlRenderingState_GetBgColour", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/html.py#L529-L531
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/closure_linter/closure_linter/ecmalintrules.py
python
EcmaScriptLintRules.InExplicitlyTypedLanguage
(self)
return False
Returns whether this ecma implementation is explicitly typed.
Returns whether this ecma implementation is explicitly typed.
[ "Returns", "whether", "this", "ecma", "implementation", "is", "explicitly", "typed", "." ]
def InExplicitlyTypedLanguage(self): """Returns whether this ecma implementation is explicitly typed.""" return False
[ "def", "InExplicitlyTypedLanguage", "(", "self", ")", ":", "return", "False" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/closure_linter/closure_linter/ecmalintrules.py#L784-L786
emscripten-core/emscripten
0d413d3c5af8b28349682496edc14656f5700c2f
third_party/ply/example/newclasscalc/calc.py
python
Calc.t_NUMBER
(self, t)
return t
r'\d+
r'\d+
[ "r", "\\", "d", "+" ]
def t_NUMBER(self, t): r'\d+' try: t.value = int(t.value) except ValueError: print("Integer value too large %s" % t.value) t.value = 0 #print "parsed number %s" % repr(t.value) return t
[ "def", "t_NUMBER", "(", "self", ",", "t", ")", ":", "try", ":", "t", ".", "value", "=", "int", "(", "t", ".", "value", ")", "except", "ValueError", ":", "print", "(", "\"Integer value too large %s\"", "%", "t", ".", "value", ")", "t", ".", "value", "=", "0", "#print \"parsed number %s\" % repr(t.value)", "return", "t" ]
https://github.com/emscripten-core/emscripten/blob/0d413d3c5af8b28349682496edc14656f5700c2f/third_party/ply/example/newclasscalc/calc.py#L80-L88
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/numpy/files/numpy/lib/function_base.py
python
extract
(condition, arr)
return _nx.take(ravel(arr), nonzero(ravel(condition))[0])
Return the elements of an array that satisfy some condition. This is equivalent to ``np.compress(ravel(condition), ravel(arr))``. If `condition` is boolean ``np.extract`` is equivalent to ``arr[condition]``. Parameters ---------- condition : array_like An array whose nonzero or True entries indicate the elements of `arr` to extract. arr : array_like Input array of the same size as `condition`. See Also -------- take, put, putmask, compress Examples -------- >>> arr = np.arange(12).reshape((3, 4)) >>> arr array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> condition = np.mod(arr, 3)==0 >>> condition array([[ True, False, False, True], [False, False, True, False], [False, True, False, False]], dtype=bool) >>> np.extract(condition, arr) array([0, 3, 6, 9]) If `condition` is boolean: >>> arr[condition] array([0, 3, 6, 9])
Return the elements of an array that satisfy some condition.
[ "Return", "the", "elements", "of", "an", "array", "that", "satisfy", "some", "condition", "." ]
def extract(condition, arr): """ Return the elements of an array that satisfy some condition. This is equivalent to ``np.compress(ravel(condition), ravel(arr))``. If `condition` is boolean ``np.extract`` is equivalent to ``arr[condition]``. Parameters ---------- condition : array_like An array whose nonzero or True entries indicate the elements of `arr` to extract. arr : array_like Input array of the same size as `condition`. See Also -------- take, put, putmask, compress Examples -------- >>> arr = np.arange(12).reshape((3, 4)) >>> arr array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> condition = np.mod(arr, 3)==0 >>> condition array([[ True, False, False, True], [False, False, True, False], [False, True, False, False]], dtype=bool) >>> np.extract(condition, arr) array([0, 3, 6, 9]) If `condition` is boolean: >>> arr[condition] array([0, 3, 6, 9]) """ return _nx.take(ravel(arr), nonzero(ravel(condition))[0])
[ "def", "extract", "(", "condition", ",", "arr", ")", ":", "return", "_nx", ".", "take", "(", "ravel", "(", "arr", ")", ",", "nonzero", "(", "ravel", "(", "condition", ")", ")", "[", "0", "]", ")" ]
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/lib/function_base.py#L1258-L1299
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/resample.py
python
Resampler._get_binner
(self)
return binner, bin_grouper
Create the BinGrouper, assume that self.set_grouper(obj) has already been called.
Create the BinGrouper, assume that self.set_grouper(obj) has already been called.
[ "Create", "the", "BinGrouper", "assume", "that", "self", ".", "set_grouper", "(", "obj", ")", "has", "already", "been", "called", "." ]
def _get_binner(self): """ Create the BinGrouper, assume that self.set_grouper(obj) has already been called. """ binner, bins, binlabels = self._get_binner_for_time() assert len(bins) == len(binlabels) bin_grouper = BinGrouper(bins, binlabels, indexer=self.groupby.indexer) return binner, bin_grouper
[ "def", "_get_binner", "(", "self", ")", ":", "binner", ",", "bins", ",", "binlabels", "=", "self", ".", "_get_binner_for_time", "(", ")", "assert", "len", "(", "bins", ")", "==", "len", "(", "binlabels", ")", "bin_grouper", "=", "BinGrouper", "(", "bins", ",", "binlabels", ",", "indexer", "=", "self", ".", "groupby", ".", "indexer", ")", "return", "binner", ",", "bin_grouper" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/resample.py#L236-L244
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/tornado/tornado-6/tornado/iostream.py
python
BaseIOStream.read_from_fd
(self, buf: Union[bytearray, memoryview])
Attempts to read from the underlying file. Reads up to ``len(buf)`` bytes, storing them in the buffer. Returns the number of bytes read. Returns None if there was nothing to read (the socket returned `~errno.EWOULDBLOCK` or equivalent), and zero on EOF. .. versionchanged:: 5.0 Interface redesigned to take a buffer and return a number of bytes instead of a freshly-allocated object.
Attempts to read from the underlying file.
[ "Attempts", "to", "read", "from", "the", "underlying", "file", "." ]
def read_from_fd(self, buf: Union[bytearray, memoryview]) -> Optional[int]: """Attempts to read from the underlying file. Reads up to ``len(buf)`` bytes, storing them in the buffer. Returns the number of bytes read. Returns None if there was nothing to read (the socket returned `~errno.EWOULDBLOCK` or equivalent), and zero on EOF. .. versionchanged:: 5.0 Interface redesigned to take a buffer and return a number of bytes instead of a freshly-allocated object. """ raise NotImplementedError()
[ "def", "read_from_fd", "(", "self", ",", "buf", ":", "Union", "[", "bytearray", ",", "memoryview", "]", ")", "->", "Optional", "[", "int", "]", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/tornado/tornado-6/tornado/iostream.py#L305-L318
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/idl/idl/binder.py
python
_bind_server_parameter_set_at
(ctxt, param)
Translate set_at options to C++ enum value.
Translate set_at options to C++ enum value.
[ "Translate", "set_at", "options", "to", "C", "++", "enum", "value", "." ]
def _bind_server_parameter_set_at(ctxt, param): # type: (errors.ParserContext, syntax.ServerParameter) -> str """Translate set_at options to C++ enum value.""" if param.set_at == ['readonly']: # Readonly may not be mixed with startup or runtime return "ServerParameterType::kReadOnly" set_at = 0 for psa in param.set_at: if psa.lower() == 'startup': set_at |= 1 elif psa.lower() == 'runtime': set_at |= 2 else: ctxt.add_bad_setat_specifier(param, psa) return None if set_at == 1: return "ServerParameterType::kStartupOnly" elif set_at == 2: return "ServerParameterType::kRuntimeOnly" elif set_at == 3: return "ServerParameterType::kStartupAndRuntime" else: # Can't happen based on above logic. ctxt.add_bad_setat_specifier(param, ','.join(param.set_at)) return None
[ "def", "_bind_server_parameter_set_at", "(", "ctxt", ",", "param", ")", ":", "# type: (errors.ParserContext, syntax.ServerParameter) -> str", "if", "param", ".", "set_at", "==", "[", "'readonly'", "]", ":", "# Readonly may not be mixed with startup or runtime", "return", "\"ServerParameterType::kReadOnly\"", "set_at", "=", "0", "for", "psa", "in", "param", ".", "set_at", ":", "if", "psa", ".", "lower", "(", ")", "==", "'startup'", ":", "set_at", "|=", "1", "elif", "psa", ".", "lower", "(", ")", "==", "'runtime'", ":", "set_at", "|=", "2", "else", ":", "ctxt", ".", "add_bad_setat_specifier", "(", "param", ",", "psa", ")", "return", "None", "if", "set_at", "==", "1", ":", "return", "\"ServerParameterType::kStartupOnly\"", "elif", "set_at", "==", "2", ":", "return", "\"ServerParameterType::kRuntimeOnly\"", "elif", "set_at", "==", "3", ":", "return", "\"ServerParameterType::kStartupAndRuntime\"", "else", ":", "# Can't happen based on above logic.", "ctxt", ".", "add_bad_setat_specifier", "(", "param", ",", "','", ".", "join", "(", "param", ".", "set_at", ")", ")", "return", "None" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl/binder.py#L1317-L1344
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py
python
uCSIsMiscellaneousSymbols
(code)
return ret
Check whether the character is part of MiscellaneousSymbols UCS Block
Check whether the character is part of MiscellaneousSymbols UCS Block
[ "Check", "whether", "the", "character", "is", "part", "of", "MiscellaneousSymbols", "UCS", "Block" ]
def uCSIsMiscellaneousSymbols(code): """Check whether the character is part of MiscellaneousSymbols UCS Block """ ret = libxml2mod.xmlUCSIsMiscellaneousSymbols(code) return ret
[ "def", "uCSIsMiscellaneousSymbols", "(", "code", ")", ":", "ret", "=", "libxml2mod", ".", "xmlUCSIsMiscellaneousSymbols", "(", "code", ")", "return", "ret" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L2752-L2756
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/richtext.py
python
RichTextParagraphLayoutBox.CopyFragment
(*args, **kwargs)
return _richtext.RichTextParagraphLayoutBox_CopyFragment(*args, **kwargs)
CopyFragment(self, RichTextRange range, RichTextParagraphLayoutBox fragment) -> bool
CopyFragment(self, RichTextRange range, RichTextParagraphLayoutBox fragment) -> bool
[ "CopyFragment", "(", "self", "RichTextRange", "range", "RichTextParagraphLayoutBox", "fragment", ")", "-", ">", "bool" ]
def CopyFragment(*args, **kwargs): """CopyFragment(self, RichTextRange range, RichTextParagraphLayoutBox fragment) -> bool""" return _richtext.RichTextParagraphLayoutBox_CopyFragment(*args, **kwargs)
[ "def", "CopyFragment", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextParagraphLayoutBox_CopyFragment", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/richtext.py#L1814-L1816
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/optimize/_trustregion.py
python
_minimize_trust_region
(fun, x0, args=(), jac=None, hess=None, hessp=None, subproblem=None, initial_trust_radius=1.0, max_trust_radius=1000.0, eta=0.15, gtol=1e-4, maxiter=None, disp=False, return_all=False, callback=None, inexact=True, **unknown_options)
return result
Minimization of scalar function of one or more variables using a trust-region algorithm. Options for the trust-region algorithm are: initial_trust_radius : float Initial trust radius. max_trust_radius : float Never propose steps that are longer than this value. eta : float Trust region related acceptance stringency for proposed steps. gtol : float Gradient norm must be less than `gtol` before successful termination. maxiter : int Maximum number of iterations to perform. disp : bool If True, print convergence message. inexact : bool Accuracy to solve subproblems. If True requires less nonlinear iterations, but more vector products. Only effective for method trust-krylov. This function is called by the `minimize` function. It is not supposed to be called directly.
Minimization of scalar function of one or more variables using a trust-region algorithm.
[ "Minimization", "of", "scalar", "function", "of", "one", "or", "more", "variables", "using", "a", "trust", "-", "region", "algorithm", "." ]
def _minimize_trust_region(fun, x0, args=(), jac=None, hess=None, hessp=None, subproblem=None, initial_trust_radius=1.0, max_trust_radius=1000.0, eta=0.15, gtol=1e-4, maxiter=None, disp=False, return_all=False, callback=None, inexact=True, **unknown_options): """ Minimization of scalar function of one or more variables using a trust-region algorithm. Options for the trust-region algorithm are: initial_trust_radius : float Initial trust radius. max_trust_radius : float Never propose steps that are longer than this value. eta : float Trust region related acceptance stringency for proposed steps. gtol : float Gradient norm must be less than `gtol` before successful termination. maxiter : int Maximum number of iterations to perform. disp : bool If True, print convergence message. inexact : bool Accuracy to solve subproblems. If True requires less nonlinear iterations, but more vector products. Only effective for method trust-krylov. This function is called by the `minimize` function. It is not supposed to be called directly. """ _check_unknown_options(unknown_options) if jac is None: raise ValueError('Jacobian is currently required for trust-region ' 'methods') if hess is None and hessp is None: raise ValueError('Either the Hessian or the Hessian-vector product ' 'is currently required for trust-region methods') if subproblem is None: raise ValueError('A subproblem solving strategy is required for ' 'trust-region methods') if not (0 <= eta < 0.25): raise Exception('invalid acceptance stringency') if max_trust_radius <= 0: raise Exception('the max trust radius must be positive') if initial_trust_radius <= 0: raise ValueError('the initial trust radius must be positive') if initial_trust_radius >= max_trust_radius: raise ValueError('the initial trust radius must be less than the ' 'max trust radius') # force the initial guess into a nice format x0 = np.asarray(x0).flatten() # Wrap the functions, for a couple reasons. # This tracks how many times they have been called # and it automatically passes the args. nfun, fun = wrap_function(fun, args) njac, jac = wrap_function(jac, args) nhess, hess = wrap_function(hess, args) nhessp, hessp = wrap_function(hessp, args) # limit the number of iterations if maxiter is None: maxiter = len(x0)*200 # init the search status warnflag = 0 # initialize the search trust_radius = initial_trust_radius x = x0 if return_all: allvecs = [x] m = subproblem(x, fun, jac, hess, hessp) k = 0 # search for the function min # do not even start if the gradient is small enough while m.jac_mag >= gtol: # Solve the sub-problem. # This gives us the proposed step relative to the current position # and it tells us whether the proposed step # has reached the trust region boundary or not. try: p, hits_boundary = m.solve(trust_radius) except np.linalg.linalg.LinAlgError as e: warnflag = 3 break # calculate the predicted value at the proposed point predicted_value = m(p) # define the local approximation at the proposed point x_proposed = x + p m_proposed = subproblem(x_proposed, fun, jac, hess, hessp) # evaluate the ratio defined in equation (4.4) actual_reduction = m.fun - m_proposed.fun predicted_reduction = m.fun - predicted_value if predicted_reduction <= 0: warnflag = 2 break rho = actual_reduction / predicted_reduction # update the trust radius according to the actual/predicted ratio if rho < 0.25: trust_radius *= 0.25 elif rho > 0.75 and hits_boundary: trust_radius = min(2*trust_radius, max_trust_radius) # if the ratio is high enough then accept the proposed step if rho > eta: x = x_proposed m = m_proposed # append the best guess, call back, increment the iteration count if return_all: allvecs.append(np.copy(x)) if callback is not None: callback(np.copy(x)) k += 1 # check if the gradient is small enough to stop if m.jac_mag < gtol: warnflag = 0 break # check if we have looked at enough iterations if k >= maxiter: warnflag = 1 break # print some stuff if requested status_messages = ( _status_message['success'], _status_message['maxiter'], 'A bad approximation caused failure to predict improvement.', 'A linalg error occurred, such as a non-psd Hessian.', ) if disp: if warnflag == 0: print(status_messages[warnflag]) else: print('Warning: ' + status_messages[warnflag]) print(" Current function value: %f" % m.fun) print(" Iterations: %d" % k) print(" Function evaluations: %d" % nfun[0]) print(" Gradient evaluations: %d" % njac[0]) print(" Hessian evaluations: %d" % nhess[0]) result = OptimizeResult(x=x, success=(warnflag == 0), status=warnflag, fun=m.fun, jac=m.jac, nfev=nfun[0], njev=njac[0], nhev=nhess[0], nit=k, message=status_messages[warnflag]) if hess is not None: result['hess'] = m.hess if return_all: result['allvecs'] = allvecs return result
[ "def", "_minimize_trust_region", "(", "fun", ",", "x0", ",", "args", "=", "(", ")", ",", "jac", "=", "None", ",", "hess", "=", "None", ",", "hessp", "=", "None", ",", "subproblem", "=", "None", ",", "initial_trust_radius", "=", "1.0", ",", "max_trust_radius", "=", "1000.0", ",", "eta", "=", "0.15", ",", "gtol", "=", "1e-4", ",", "maxiter", "=", "None", ",", "disp", "=", "False", ",", "return_all", "=", "False", ",", "callback", "=", "None", ",", "inexact", "=", "True", ",", "*", "*", "unknown_options", ")", ":", "_check_unknown_options", "(", "unknown_options", ")", "if", "jac", "is", "None", ":", "raise", "ValueError", "(", "'Jacobian is currently required for trust-region '", "'methods'", ")", "if", "hess", "is", "None", "and", "hessp", "is", "None", ":", "raise", "ValueError", "(", "'Either the Hessian or the Hessian-vector product '", "'is currently required for trust-region methods'", ")", "if", "subproblem", "is", "None", ":", "raise", "ValueError", "(", "'A subproblem solving strategy is required for '", "'trust-region methods'", ")", "if", "not", "(", "0", "<=", "eta", "<", "0.25", ")", ":", "raise", "Exception", "(", "'invalid acceptance stringency'", ")", "if", "max_trust_radius", "<=", "0", ":", "raise", "Exception", "(", "'the max trust radius must be positive'", ")", "if", "initial_trust_radius", "<=", "0", ":", "raise", "ValueError", "(", "'the initial trust radius must be positive'", ")", "if", "initial_trust_radius", ">=", "max_trust_radius", ":", "raise", "ValueError", "(", "'the initial trust radius must be less than the '", "'max trust radius'", ")", "# force the initial guess into a nice format", "x0", "=", "np", ".", "asarray", "(", "x0", ")", ".", "flatten", "(", ")", "# Wrap the functions, for a couple reasons.", "# This tracks how many times they have been called", "# and it automatically passes the args.", "nfun", ",", "fun", "=", "wrap_function", "(", "fun", ",", "args", ")", "njac", ",", "jac", "=", "wrap_function", "(", "jac", ",", "args", ")", "nhess", ",", "hess", "=", "wrap_function", "(", "hess", ",", "args", ")", "nhessp", ",", "hessp", "=", "wrap_function", "(", "hessp", ",", "args", ")", "# limit the number of iterations", "if", "maxiter", "is", "None", ":", "maxiter", "=", "len", "(", "x0", ")", "*", "200", "# init the search status", "warnflag", "=", "0", "# initialize the search", "trust_radius", "=", "initial_trust_radius", "x", "=", "x0", "if", "return_all", ":", "allvecs", "=", "[", "x", "]", "m", "=", "subproblem", "(", "x", ",", "fun", ",", "jac", ",", "hess", ",", "hessp", ")", "k", "=", "0", "# search for the function min", "# do not even start if the gradient is small enough", "while", "m", ".", "jac_mag", ">=", "gtol", ":", "# Solve the sub-problem.", "# This gives us the proposed step relative to the current position", "# and it tells us whether the proposed step", "# has reached the trust region boundary or not.", "try", ":", "p", ",", "hits_boundary", "=", "m", ".", "solve", "(", "trust_radius", ")", "except", "np", ".", "linalg", ".", "linalg", ".", "LinAlgError", "as", "e", ":", "warnflag", "=", "3", "break", "# calculate the predicted value at the proposed point", "predicted_value", "=", "m", "(", "p", ")", "# define the local approximation at the proposed point", "x_proposed", "=", "x", "+", "p", "m_proposed", "=", "subproblem", "(", "x_proposed", ",", "fun", ",", "jac", ",", "hess", ",", "hessp", ")", "# evaluate the ratio defined in equation (4.4)", "actual_reduction", "=", "m", ".", "fun", "-", "m_proposed", ".", "fun", "predicted_reduction", "=", "m", ".", "fun", "-", "predicted_value", "if", "predicted_reduction", "<=", "0", ":", "warnflag", "=", "2", "break", "rho", "=", "actual_reduction", "/", "predicted_reduction", "# update the trust radius according to the actual/predicted ratio", "if", "rho", "<", "0.25", ":", "trust_radius", "*=", "0.25", "elif", "rho", ">", "0.75", "and", "hits_boundary", ":", "trust_radius", "=", "min", "(", "2", "*", "trust_radius", ",", "max_trust_radius", ")", "# if the ratio is high enough then accept the proposed step", "if", "rho", ">", "eta", ":", "x", "=", "x_proposed", "m", "=", "m_proposed", "# append the best guess, call back, increment the iteration count", "if", "return_all", ":", "allvecs", ".", "append", "(", "np", ".", "copy", "(", "x", ")", ")", "if", "callback", "is", "not", "None", ":", "callback", "(", "np", ".", "copy", "(", "x", ")", ")", "k", "+=", "1", "# check if the gradient is small enough to stop", "if", "m", ".", "jac_mag", "<", "gtol", ":", "warnflag", "=", "0", "break", "# check if we have looked at enough iterations", "if", "k", ">=", "maxiter", ":", "warnflag", "=", "1", "break", "# print some stuff if requested", "status_messages", "=", "(", "_status_message", "[", "'success'", "]", ",", "_status_message", "[", "'maxiter'", "]", ",", "'A bad approximation caused failure to predict improvement.'", ",", "'A linalg error occurred, such as a non-psd Hessian.'", ",", ")", "if", "disp", ":", "if", "warnflag", "==", "0", ":", "print", "(", "status_messages", "[", "warnflag", "]", ")", "else", ":", "print", "(", "'Warning: '", "+", "status_messages", "[", "warnflag", "]", ")", "print", "(", "\" Current function value: %f\"", "%", "m", ".", "fun", ")", "print", "(", "\" Iterations: %d\"", "%", "k", ")", "print", "(", "\" Function evaluations: %d\"", "%", "nfun", "[", "0", "]", ")", "print", "(", "\" Gradient evaluations: %d\"", "%", "njac", "[", "0", "]", ")", "print", "(", "\" Hessian evaluations: %d\"", "%", "nhess", "[", "0", "]", ")", "result", "=", "OptimizeResult", "(", "x", "=", "x", ",", "success", "=", "(", "warnflag", "==", "0", ")", ",", "status", "=", "warnflag", ",", "fun", "=", "m", ".", "fun", ",", "jac", "=", "m", ".", "jac", ",", "nfev", "=", "nfun", "[", "0", "]", ",", "njev", "=", "njac", "[", "0", "]", ",", "nhev", "=", "nhess", "[", "0", "]", ",", "nit", "=", "k", ",", "message", "=", "status_messages", "[", "warnflag", "]", ")", "if", "hess", "is", "not", "None", ":", "result", "[", "'hess'", "]", "=", "m", ".", "hess", "if", "return_all", ":", "result", "[", "'allvecs'", "]", "=", "allvecs", "return", "result" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/optimize/_trustregion.py#L102-L266
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/LoadDNSLegacy.py
python
LoadDNSLegacy.name
(self)
return "LoadDNSLegacy"
Returns name
Returns name
[ "Returns", "name" ]
def name(self): """ Returns name """ return "LoadDNSLegacy"
[ "def", "name", "(", "self", ")", ":", "return", "\"LoadDNSLegacy\"" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/LoadDNSLegacy.py#L39-L43
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/idlelib/ScriptBinding.py
python
ScriptBinding.run_module_event
(self, event)
return 'break'
Run the module after setting up the environment. First check the syntax. If OK, make sure the shell is active and then transfer the arguments, set the run environment's working directory to the directory of the module being executed and also add that directory to its sys.path if not already included.
Run the module after setting up the environment.
[ "Run", "the", "module", "after", "setting", "up", "the", "environment", "." ]
def run_module_event(self, event): """Run the module after setting up the environment. First check the syntax. If OK, make sure the shell is active and then transfer the arguments, set the run environment's working directory to the directory of the module being executed and also add that directory to its sys.path if not already included. """ filename = self.getfilename() if not filename: return 'break' code = self.checksyntax(filename) if not code: return 'break' if not self.tabnanny(filename): return 'break' interp = self.shell.interp if PyShell.use_subprocess: interp.restart_subprocess(with_cwd=False, filename=code.co_filename) dirname = os.path.dirname(filename) # XXX Too often this discards arguments the user just set... interp.runcommand("""if 1: __file__ = {filename!r} import sys as _sys from os.path import basename as _basename if (not _sys.argv or _basename(_sys.argv[0]) != _basename(__file__)): _sys.argv = [__file__] import os as _os _os.chdir({dirname!r}) del _sys, _basename, _os \n""".format(filename=filename, dirname=dirname)) interp.prepend_syspath(filename) # XXX KBK 03Jul04 When run w/o subprocess, runtime warnings still # go to __stderr__. With subprocess, they go to the shell. # Need to change streams in PyShell.ModifiedInterpreter. interp.runcode(code) return 'break'
[ "def", "run_module_event", "(", "self", ",", "event", ")", ":", "filename", "=", "self", ".", "getfilename", "(", ")", "if", "not", "filename", ":", "return", "'break'", "code", "=", "self", ".", "checksyntax", "(", "filename", ")", "if", "not", "code", ":", "return", "'break'", "if", "not", "self", ".", "tabnanny", "(", "filename", ")", ":", "return", "'break'", "interp", "=", "self", ".", "shell", ".", "interp", "if", "PyShell", ".", "use_subprocess", ":", "interp", ".", "restart_subprocess", "(", "with_cwd", "=", "False", ",", "filename", "=", "code", ".", "co_filename", ")", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "filename", ")", "# XXX Too often this discards arguments the user just set...", "interp", ".", "runcommand", "(", "\"\"\"if 1:\n __file__ = {filename!r}\n import sys as _sys\n from os.path import basename as _basename\n if (not _sys.argv or\n _basename(_sys.argv[0]) != _basename(__file__)):\n _sys.argv = [__file__]\n import os as _os\n _os.chdir({dirname!r})\n del _sys, _basename, _os\n \\n\"\"\"", ".", "format", "(", "filename", "=", "filename", ",", "dirname", "=", "dirname", ")", ")", "interp", ".", "prepend_syspath", "(", "filename", ")", "# XXX KBK 03Jul04 When run w/o subprocess, runtime warnings still", "# go to __stderr__. With subprocess, they go to the shell.", "# Need to change streams in PyShell.ModifiedInterpreter.", "interp", ".", "runcode", "(", "code", ")", "return", "'break'" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/idlelib/ScriptBinding.py#L131-L169
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py
python
Listbox.selection_clear
(self, first, last=None)
Clear the selection from FIRST to LAST (not included).
Clear the selection from FIRST to LAST (not included).
[ "Clear", "the", "selection", "from", "FIRST", "to", "LAST", "(", "not", "included", ")", "." ]
def selection_clear(self, first, last=None): """Clear the selection from FIRST to LAST (not included).""" self.tk.call(self._w, 'selection', 'clear', first, last)
[ "def", "selection_clear", "(", "self", ",", "first", ",", "last", "=", "None", ")", ":", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "'selection'", ",", "'clear'", ",", "first", ",", "last", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py#L2600-L2603
continental/ecal
204dab80a24fe01abca62541133b311bf0c09608
samples/python/ecalhdf5_rw/ecalhdf5_rw.py
python
main
()
eCALHDF5 Write & Read Sample Step 1: create hdf5 file and add some data Step 2: read data from newly created file
eCALHDF5 Write & Read Sample Step 1: create hdf5 file and add some data Step 2: read data from newly created file
[ "eCALHDF5", "Write", "&", "Read", "Sample", "Step", "1", ":", "create", "hdf5", "file", "and", "add", "some", "data", "Step", "2", ":", "read", "data", "from", "newly", "created", "file" ]
def main(): """ eCALHDF5 Write & Read Sample Step 1: create hdf5 file and add some data Step 2: read data from newly created file """ ENTRY_COUNT = 30 MAX_ENTRY_DATA_SIZE = 32767 # Step 1: create hdf5 file and add some data # File properties output_dir = "ecalhdf5_rw_meas_folder" file_name = "measurement" channels = [] channels.append(ecalhdf5.Channel("Image", b"Image description", "Image type")) channels.append(ecalhdf5.Channel("Status", b"Status description", "Status type")) max_size_per_file = 500 # MB meas = ecalhdf5.Meas(output_dir, 1) meas.set_file_base_name(file_name) meas.set_max_size_per_file(max_size_per_file) for channel in channels: meas.set_channel_description(channel.name, channel.description) meas.set_channel_type(channel.name, channel.type) print("Creating {}/{}.hdf5 \n".format(output_dir, file_name)) # Generate timestamps and random data and write them timestamp = 0 for entry_no in range(ENTRY_COUNT): timestamp += 100000 # µs data_size = random.randint(1, MAX_ENTRY_DATA_SIZE) data = "" for i in range(data_size): data = data + chr(random.randint(0, 255)) # randomly select to which channel to add the generated data index = random.randint(0, MAX_ENTRY_DATA_SIZE) % len(channels) channel_to_write_to = channels[index].name print(" Entry {}\t{}\ttimestamp: {}\tsize[b]: {}".format(entry_no, channel_to_write_to, timestamp, data_size)) # Write entry to file meas.add_entry_to_file(str.encode(data), timestamp, timestamp, channel_to_write_to) print("\nTotal entries written: {}\n".format(ENTRY_COUNT)) if meas.is_ok() == False: print("Write error!") sys.exit() meas.close() # Step 2: read data from newly created file print("******************************************************************************\n") meas = ecalhdf5.Meas(output_dir, 0) # Alternately single file can be used # meas = ecalhdf5.Meas(output_dir + "/" + file_name + ".hdf5", 0) # Both file and directory path are supported if meas.is_ok() == False: print("Read error!") sys.exit() print("Reading {}\n".format(output_dir)) print(" File version: {}".format(meas.get_file_version())) print(" Channels No: {}\n".format(len(meas.get_channel_names()))) print(" Channels: \n") channel_names_set = meas.get_channel_names() for channel_name in channel_names_set: print(" Name: {}".format(channel_name)) print(" Type: {}".format(meas.get_channel_type(channel_name))) print(" Description: {}".format(meas.get_channel_description(channel_name))) print(" Min timestamp: {}".format(meas.get_min_timestamp(channel_name))) print(" Max timestamp: {}".format(meas.get_max_timestamp(channel_name))) entries_info_read = meas.get_entries_info(channel_name) print(" Entries count: {}\n".format(len(entries_info_read))) """ # Alternately range entries info can be used, for example get the entries from the first timestamp until "the middle" min_timestamp = meas.get_min_timestamp(channel_name) max_timestamp = meas.get_max_timestamp(channel_name) middle_timestamp = min_timestamp / 2 + max_timestamp / 2 entries_info_read = meas.get_entries_info_range(channel_name, min_timestamp, middle_timestamp) print(" Entries count in timestamp interval [{}; {}]: {}\n\n".format(min_timestamp, middle_timestamp, len(entries_info_read))) print(" Reading entries info(timestamp ordered): \n") """ for entry_read in entries_info_read: data_size = meas.get_entry_data_size(entry_read['id']) print(" Entry {}\tsnd_timestamp: {}\trcv_timestamp: {}\tsize[bytes]: {}".format(entry_read['id'], entry_read['snd_timestamp'], entry_read['rcv_timestamp'], data_size)) entry_data = meas.get_entry_data(entry_read['id']) print("") meas.close()
[ "def", "main", "(", ")", ":", "ENTRY_COUNT", "=", "30", "MAX_ENTRY_DATA_SIZE", "=", "32767", "# Step 1: create hdf5 file and add some data", "# File properties", "output_dir", "=", "\"ecalhdf5_rw_meas_folder\"", "file_name", "=", "\"measurement\"", "channels", "=", "[", "]", "channels", ".", "append", "(", "ecalhdf5", ".", "Channel", "(", "\"Image\"", ",", "b\"Image description\"", ",", "\"Image type\"", ")", ")", "channels", ".", "append", "(", "ecalhdf5", ".", "Channel", "(", "\"Status\"", ",", "b\"Status description\"", ",", "\"Status type\"", ")", ")", "max_size_per_file", "=", "500", "# MB", "meas", "=", "ecalhdf5", ".", "Meas", "(", "output_dir", ",", "1", ")", "meas", ".", "set_file_base_name", "(", "file_name", ")", "meas", ".", "set_max_size_per_file", "(", "max_size_per_file", ")", "for", "channel", "in", "channels", ":", "meas", ".", "set_channel_description", "(", "channel", ".", "name", ",", "channel", ".", "description", ")", "meas", ".", "set_channel_type", "(", "channel", ".", "name", ",", "channel", ".", "type", ")", "print", "(", "\"Creating {}/{}.hdf5 \\n\"", ".", "format", "(", "output_dir", ",", "file_name", ")", ")", "# Generate timestamps and random data and write them", "timestamp", "=", "0", "for", "entry_no", "in", "range", "(", "ENTRY_COUNT", ")", ":", "timestamp", "+=", "100000", "# µs", "data_size", "=", "random", ".", "randint", "(", "1", ",", "MAX_ENTRY_DATA_SIZE", ")", "data", "=", "\"\"", "for", "i", "in", "range", "(", "data_size", ")", ":", "data", "=", "data", "+", "chr", "(", "random", ".", "randint", "(", "0", ",", "255", ")", ")", "# randomly select to which channel to add the generated data ", "index", "=", "random", ".", "randint", "(", "0", ",", "MAX_ENTRY_DATA_SIZE", ")", "%", "len", "(", "channels", ")", "channel_to_write_to", "=", "channels", "[", "index", "]", ".", "name", "print", "(", "\" Entry {}\\t{}\\ttimestamp: {}\\tsize[b]: {}\"", ".", "format", "(", "entry_no", ",", "channel_to_write_to", ",", "timestamp", ",", "data_size", ")", ")", "# Write entry to file ", "meas", ".", "add_entry_to_file", "(", "str", ".", "encode", "(", "data", ")", ",", "timestamp", ",", "timestamp", ",", "channel_to_write_to", ")", "print", "(", "\"\\nTotal entries written: {}\\n\"", ".", "format", "(", "ENTRY_COUNT", ")", ")", "if", "meas", ".", "is_ok", "(", ")", "==", "False", ":", "print", "(", "\"Write error!\"", ")", "sys", ".", "exit", "(", ")", "meas", ".", "close", "(", ")", "# Step 2: read data from newly created file", "print", "(", "\"******************************************************************************\\n\"", ")", "meas", "=", "ecalhdf5", ".", "Meas", "(", "output_dir", ",", "0", ")", "# Alternately single file can be used", "# meas = ecalhdf5.Meas(output_dir + \"/\" + file_name + \".hdf5\", 0)", "# Both file and directory path are supported", "if", "meas", ".", "is_ok", "(", ")", "==", "False", ":", "print", "(", "\"Read error!\"", ")", "sys", ".", "exit", "(", ")", "print", "(", "\"Reading {}\\n\"", ".", "format", "(", "output_dir", ")", ")", "print", "(", "\" File version: {}\"", ".", "format", "(", "meas", ".", "get_file_version", "(", ")", ")", ")", "print", "(", "\" Channels No: {}\\n\"", ".", "format", "(", "len", "(", "meas", ".", "get_channel_names", "(", ")", ")", ")", ")", "print", "(", "\" Channels: \\n\"", ")", "channel_names_set", "=", "meas", ".", "get_channel_names", "(", ")", "for", "channel_name", "in", "channel_names_set", ":", "print", "(", "\" Name: {}\"", ".", "format", "(", "channel_name", ")", ")", "print", "(", "\" Type: {}\"", ".", "format", "(", "meas", ".", "get_channel_type", "(", "channel_name", ")", ")", ")", "print", "(", "\" Description: {}\"", ".", "format", "(", "meas", ".", "get_channel_description", "(", "channel_name", ")", ")", ")", "print", "(", "\" Min timestamp: {}\"", ".", "format", "(", "meas", ".", "get_min_timestamp", "(", "channel_name", ")", ")", ")", "print", "(", "\" Max timestamp: {}\"", ".", "format", "(", "meas", ".", "get_max_timestamp", "(", "channel_name", ")", ")", ")", "entries_info_read", "=", "meas", ".", "get_entries_info", "(", "channel_name", ")", "print", "(", "\" Entries count: {}\\n\"", ".", "format", "(", "len", "(", "entries_info_read", ")", ")", ")", "\"\"\"\n # Alternately range entries info can be used, for example get the entries from the first timestamp until \"the middle\" \n\n min_timestamp = meas.get_min_timestamp(channel_name)\n max_timestamp = meas.get_max_timestamp(channel_name)\n middle_timestamp = min_timestamp / 2 + max_timestamp / 2\n\n entries_info_read = meas.get_entries_info_range(channel_name, min_timestamp, middle_timestamp)\n\n print(\" Entries count in timestamp interval [{}; {}]: {}\\n\\n\".format(min_timestamp, middle_timestamp, len(entries_info_read)))\n print(\" Reading entries info(timestamp ordered): \\n\")\n \"\"\"", "for", "entry_read", "in", "entries_info_read", ":", "data_size", "=", "meas", ".", "get_entry_data_size", "(", "entry_read", "[", "'id'", "]", ")", "print", "(", "\" Entry {}\\tsnd_timestamp: {}\\trcv_timestamp: {}\\tsize[bytes]: {}\"", ".", "format", "(", "entry_read", "[", "'id'", "]", ",", "entry_read", "[", "'snd_timestamp'", "]", ",", "entry_read", "[", "'rcv_timestamp'", "]", ",", "data_size", ")", ")", "entry_data", "=", "meas", ".", "get_entry_data", "(", "entry_read", "[", "'id'", "]", ")", "print", "(", "\"\"", ")", "meas", ".", "close", "(", ")" ]
https://github.com/continental/ecal/blob/204dab80a24fe01abca62541133b311bf0c09608/samples/python/ecalhdf5_rw/ecalhdf5_rw.py#L24-L133
RegrowthStudios/SoACode-Public
c3ddd69355b534d5e70e2e6d0c489b4e93ab1ffe
utils/git-hooks/cpplint/cpplint.py
python
_IncludeState.CanonicalizeAlphabeticalOrder
(self, header_path)
return header_path.replace('-inl.h', '.h').replace('-', '_').lower()
Returns a path canonicalized for alphabetical comparison. - replaces "-" with "_" so they both cmp the same. - removes '-inl' since we don't require them to be after the main header. - lowercase everything, just in case. Args: header_path: Path to be canonicalized. Returns: Canonicalized path.
Returns a path canonicalized for alphabetical comparison.
[ "Returns", "a", "path", "canonicalized", "for", "alphabetical", "comparison", "." ]
def CanonicalizeAlphabeticalOrder(self, header_path): """Returns a path canonicalized for alphabetical comparison. - replaces "-" with "_" so they both cmp the same. - removes '-inl' since we don't require them to be after the main header. - lowercase everything, just in case. Args: header_path: Path to be canonicalized. Returns: Canonicalized path. """ return header_path.replace('-inl.h', '.h').replace('-', '_').lower()
[ "def", "CanonicalizeAlphabeticalOrder", "(", "self", ",", "header_path", ")", ":", "return", "header_path", ".", "replace", "(", "'-inl.h'", ",", "'.h'", ")", ".", "replace", "(", "'-'", ",", "'_'", ")", ".", "lower", "(", ")" ]
https://github.com/RegrowthStudios/SoACode-Public/blob/c3ddd69355b534d5e70e2e6d0c489b4e93ab1ffe/utils/git-hooks/cpplint/cpplint.py#L426-L439
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
src/ceph-volume/ceph_volume/util/prepare.py
python
create_id
(fsid, json_secrets, osd_id=None)
return ' '.join(stdout).strip()
:param fsid: The osd fsid to create, always required :param json_secrets: a json-ready object with whatever secrets are wanted to be passed to the monitor :param osd_id: Reuse an existing ID from an OSD that's been destroyed, if the id does not exist in the cluster a new ID will be created
:param fsid: The osd fsid to create, always required :param json_secrets: a json-ready object with whatever secrets are wanted to be passed to the monitor :param osd_id: Reuse an existing ID from an OSD that's been destroyed, if the id does not exist in the cluster a new ID will be created
[ ":", "param", "fsid", ":", "The", "osd", "fsid", "to", "create", "always", "required", ":", "param", "json_secrets", ":", "a", "json", "-", "ready", "object", "with", "whatever", "secrets", "are", "wanted", "to", "be", "passed", "to", "the", "monitor", ":", "param", "osd_id", ":", "Reuse", "an", "existing", "ID", "from", "an", "OSD", "that", "s", "been", "destroyed", "if", "the", "id", "does", "not", "exist", "in", "the", "cluster", "a", "new", "ID", "will", "be", "created" ]
def create_id(fsid, json_secrets, osd_id=None): """ :param fsid: The osd fsid to create, always required :param json_secrets: a json-ready object with whatever secrets are wanted to be passed to the monitor :param osd_id: Reuse an existing ID from an OSD that's been destroyed, if the id does not exist in the cluster a new ID will be created """ bootstrap_keyring = '/var/lib/ceph/bootstrap-osd/%s.keyring' % conf.cluster cmd = [ 'ceph', '--cluster', conf.cluster, '--name', 'client.bootstrap-osd', '--keyring', bootstrap_keyring, '-i', '-', 'osd', 'new', fsid ] if osd_id is not None: if osd_id_available(osd_id): cmd.append(osd_id) else: raise RuntimeError("The osd ID {} is already in use or does not exist.".format(osd_id)) stdout, stderr, returncode = process.call( cmd, stdin=json_secrets, show_command=True ) if returncode != 0: raise RuntimeError('Unable to create a new OSD id') return ' '.join(stdout).strip()
[ "def", "create_id", "(", "fsid", ",", "json_secrets", ",", "osd_id", "=", "None", ")", ":", "bootstrap_keyring", "=", "'/var/lib/ceph/bootstrap-osd/%s.keyring'", "%", "conf", ".", "cluster", "cmd", "=", "[", "'ceph'", ",", "'--cluster'", ",", "conf", ".", "cluster", ",", "'--name'", ",", "'client.bootstrap-osd'", ",", "'--keyring'", ",", "bootstrap_keyring", ",", "'-i'", ",", "'-'", ",", "'osd'", ",", "'new'", ",", "fsid", "]", "if", "osd_id", "is", "not", "None", ":", "if", "osd_id_available", "(", "osd_id", ")", ":", "cmd", ".", "append", "(", "osd_id", ")", "else", ":", "raise", "RuntimeError", "(", "\"The osd ID {} is already in use or does not exist.\"", ".", "format", "(", "osd_id", ")", ")", "stdout", ",", "stderr", ",", "returncode", "=", "process", ".", "call", "(", "cmd", ",", "stdin", "=", "json_secrets", ",", "show_command", "=", "True", ")", "if", "returncode", "!=", "0", ":", "raise", "RuntimeError", "(", "'Unable to create a new OSD id'", ")", "return", "' '", ".", "join", "(", "stdout", ")", ".", "strip", "(", ")" ]
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/ceph-volume/ceph_volume/util/prepare.py#L145-L174
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_controls.py
python
TreeCtrl.SetImageList
(*args, **kwargs)
return _controls_.TreeCtrl_SetImageList(*args, **kwargs)
SetImageList(self, ImageList imageList)
SetImageList(self, ImageList imageList)
[ "SetImageList", "(", "self", "ImageList", "imageList", ")" ]
def SetImageList(*args, **kwargs): """SetImageList(self, ImageList imageList)""" return _controls_.TreeCtrl_SetImageList(*args, **kwargs)
[ "def", "SetImageList", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "TreeCtrl_SetImageList", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L5237-L5239
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/lib2to3/pytree.py
python
Leaf._eq
(self, other)
return (self.type, self.value) == (other.type, other.value)
Compare two nodes for equality.
Compare two nodes for equality.
[ "Compare", "two", "nodes", "for", "equality", "." ]
def _eq(self, other): """Compare two nodes for equality.""" return (self.type, self.value) == (other.type, other.value)
[ "def", "_eq", "(", "self", ",", "other", ")", ":", "return", "(", "self", ".", "type", ",", "self", ".", "value", ")", "==", "(", "other", ".", "type", ",", "other", ".", "value", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/lib2to3/pytree.py#L362-L364
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/plat-mac/FrameWork.py
python
ostypecode
(x)
return s
Convert a long int to the 4-character code it really is
Convert a long int to the 4-character code it really is
[ "Convert", "a", "long", "int", "to", "the", "4", "-", "character", "code", "it", "really", "is" ]
def ostypecode(x): "Convert a long int to the 4-character code it really is" s = '' for i in range(4): x, c = divmod(x, 256) s = chr(c) + s return s
[ "def", "ostypecode", "(", "x", ")", ":", "s", "=", "''", "for", "i", "in", "range", "(", "4", ")", ":", "x", ",", "c", "=", "divmod", "(", "x", ",", "256", ")", "s", "=", "chr", "(", "c", ")", "+", "s", "return", "s" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/plat-mac/FrameWork.py#L1074-L1080
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/vendor/distlib/wheel.py
python
Wheel.__init__
(self, filename=None, sign=False, verify=False)
Initialise an instance using a (valid) filename.
Initialise an instance using a (valid) filename.
[ "Initialise", "an", "instance", "using", "a", "(", "valid", ")", "filename", "." ]
def __init__(self, filename=None, sign=False, verify=False): """ Initialise an instance using a (valid) filename. """ self.sign = sign self.verify = verify self.buildver = '' self.pyver = [PYVER] self.abi = ['none'] self.arch = ['any'] self.dirname = os.getcwd() if filename is None: self.name = 'dummy' self.version = '0.1' self._filename = self.filename else: m = NAME_VERSION_RE.match(filename) if m: info = m.groupdict('') self.name = info['nm'] self.version = info['vn'] self.buildver = info['bn'] self._filename = self.filename else: dirname, filename = os.path.split(filename) m = FILENAME_RE.match(filename) if not m: raise DistlibException('Invalid name or ' 'filename: %r' % filename) if dirname: self.dirname = os.path.abspath(dirname) self._filename = filename info = m.groupdict('') self.name = info['nm'] self.version = info['vn'] self.buildver = info['bn'] self.pyver = info['py'].split('.') self.abi = info['bi'].split('.') self.arch = info['ar'].split('.')
[ "def", "__init__", "(", "self", ",", "filename", "=", "None", ",", "sign", "=", "False", ",", "verify", "=", "False", ")", ":", "self", ".", "sign", "=", "sign", "self", ".", "verify", "=", "verify", "self", ".", "buildver", "=", "''", "self", ".", "pyver", "=", "[", "PYVER", "]", "self", ".", "abi", "=", "[", "'none'", "]", "self", ".", "arch", "=", "[", "'any'", "]", "self", ".", "dirname", "=", "os", ".", "getcwd", "(", ")", "if", "filename", "is", "None", ":", "self", ".", "name", "=", "'dummy'", "self", ".", "version", "=", "'0.1'", "self", ".", "_filename", "=", "self", ".", "filename", "else", ":", "m", "=", "NAME_VERSION_RE", ".", "match", "(", "filename", ")", "if", "m", ":", "info", "=", "m", ".", "groupdict", "(", "''", ")", "self", ".", "name", "=", "info", "[", "'nm'", "]", "self", ".", "version", "=", "info", "[", "'vn'", "]", "self", ".", "buildver", "=", "info", "[", "'bn'", "]", "self", ".", "_filename", "=", "self", ".", "filename", "else", ":", "dirname", ",", "filename", "=", "os", ".", "path", ".", "split", "(", "filename", ")", "m", "=", "FILENAME_RE", ".", "match", "(", "filename", ")", "if", "not", "m", ":", "raise", "DistlibException", "(", "'Invalid name or '", "'filename: %r'", "%", "filename", ")", "if", "dirname", ":", "self", ".", "dirname", "=", "os", ".", "path", ".", "abspath", "(", "dirname", ")", "self", ".", "_filename", "=", "filename", "info", "=", "m", ".", "groupdict", "(", "''", ")", "self", ".", "name", "=", "info", "[", "'nm'", "]", "self", ".", "version", "=", "info", "[", "'vn'", "]", "self", ".", "buildver", "=", "info", "[", "'bn'", "]", "self", ".", "pyver", "=", "info", "[", "'py'", "]", ".", "split", "(", "'.'", ")", "self", ".", "abi", "=", "info", "[", "'bi'", "]", ".", "split", "(", "'.'", ")", "self", ".", "arch", "=", "info", "[", "'ar'", "]", ".", "split", "(", "'.'", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/vendor/distlib/wheel.py#L129-L167
zhaoweicai/cascade-rcnn
2252f46158ea6555868ca6fa5c221ea71d9b5e6c
python/caffe/io.py
python
Transformer.deprocess
(self, in_, data)
return decaf_in
Invert Caffe formatting; see preprocess().
Invert Caffe formatting; see preprocess().
[ "Invert", "Caffe", "formatting", ";", "see", "preprocess", "()", "." ]
def deprocess(self, in_, data): """ Invert Caffe formatting; see preprocess(). """ self.__check_input(in_) decaf_in = data.copy().squeeze() transpose = self.transpose.get(in_) channel_swap = self.channel_swap.get(in_) raw_scale = self.raw_scale.get(in_) mean = self.mean.get(in_) input_scale = self.input_scale.get(in_) if input_scale is not None: decaf_in /= input_scale if mean is not None: decaf_in += mean if raw_scale is not None: decaf_in /= raw_scale if channel_swap is not None: decaf_in = decaf_in[np.argsort(channel_swap), :, :] if transpose is not None: decaf_in = decaf_in.transpose(np.argsort(transpose)) return decaf_in
[ "def", "deprocess", "(", "self", ",", "in_", ",", "data", ")", ":", "self", ".", "__check_input", "(", "in_", ")", "decaf_in", "=", "data", ".", "copy", "(", ")", ".", "squeeze", "(", ")", "transpose", "=", "self", ".", "transpose", ".", "get", "(", "in_", ")", "channel_swap", "=", "self", ".", "channel_swap", ".", "get", "(", "in_", ")", "raw_scale", "=", "self", ".", "raw_scale", ".", "get", "(", "in_", ")", "mean", "=", "self", ".", "mean", ".", "get", "(", "in_", ")", "input_scale", "=", "self", ".", "input_scale", ".", "get", "(", "in_", ")", "if", "input_scale", "is", "not", "None", ":", "decaf_in", "/=", "input_scale", "if", "mean", "is", "not", "None", ":", "decaf_in", "+=", "mean", "if", "raw_scale", "is", "not", "None", ":", "decaf_in", "/=", "raw_scale", "if", "channel_swap", "is", "not", "None", ":", "decaf_in", "=", "decaf_in", "[", "np", ".", "argsort", "(", "channel_swap", ")", ",", ":", ",", ":", "]", "if", "transpose", "is", "not", "None", ":", "decaf_in", "=", "decaf_in", ".", "transpose", "(", "np", ".", "argsort", "(", "transpose", ")", ")", "return", "decaf_in" ]
https://github.com/zhaoweicai/cascade-rcnn/blob/2252f46158ea6555868ca6fa5c221ea71d9b5e6c/python/caffe/io.py#L164-L185
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/html5lib/_inputstream.py
python
EncodingBytes.matchBytes
(self, bytes)
return rv
Look for a sequence of bytes at the start of a string. If the bytes are found return True and advance the position to the byte after the match. Otherwise return False and leave the position alone
Look for a sequence of bytes at the start of a string. If the bytes are found return True and advance the position to the byte after the match. Otherwise return False and leave the position alone
[ "Look", "for", "a", "sequence", "of", "bytes", "at", "the", "start", "of", "a", "string", ".", "If", "the", "bytes", "are", "found", "return", "True", "and", "advance", "the", "position", "to", "the", "byte", "after", "the", "match", ".", "Otherwise", "return", "False", "and", "leave", "the", "position", "alone" ]
def matchBytes(self, bytes): """Look for a sequence of bytes at the start of a string. If the bytes are found return True and advance the position to the byte after the match. Otherwise return False and leave the position alone""" rv = self.startswith(bytes, self.position) if rv: self.position += len(bytes) return rv
[ "def", "matchBytes", "(", "self", ",", "bytes", ")", ":", "rv", "=", "self", ".", "startswith", "(", "bytes", ",", "self", ".", "position", ")", "if", "rv", ":", "self", ".", "position", "+=", "len", "(", "bytes", ")", "return", "rv" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/html5lib/_inputstream.py#L657-L664
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/buildscripts/ciconfig/tags.py
python
TagsConfig.get_test_kinds
(self)
return self._conf.keys()
List the test kinds.
List the test kinds.
[ "List", "the", "test", "kinds", "." ]
def get_test_kinds(self): """List the test kinds.""" return self._conf.keys()
[ "def", "get_test_kinds", "(", "self", ")", ":", "return", "self", ".", "_conf", ".", "keys", "(", ")" ]
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/ciconfig/tags.py#L56-L58
infinit/elle
a8154593c42743f45b9df09daf62b44630c24a02
drake/src/drake/ocaml/__init__.py
python
Source.to_objects
(self, toolkit, config)
return [obj]
Convert to the associated bytecode object file.
Convert to the associated bytecode object file.
[ "Convert", "to", "the", "associated", "bytecode", "object", "file", "." ]
def to_objects(self, toolkit, config): '''Convert to the associated bytecode object file.''' kind = InterfaceObject if isinstance(self, Interface) else ImplementationObject obj = kind(self.name().with_extension(self.extension)) Compiler(self, obj, toolkit, config) return [obj]
[ "def", "to_objects", "(", "self", ",", "toolkit", ",", "config", ")", ":", "kind", "=", "InterfaceObject", "if", "isinstance", "(", "self", ",", "Interface", ")", "else", "ImplementationObject", "obj", "=", "kind", "(", "self", ".", "name", "(", ")", ".", "with_extension", "(", "self", ".", "extension", ")", ")", "Compiler", "(", "self", ",", "obj", ",", "toolkit", ",", "config", ")", "return", "[", "obj", "]" ]
https://github.com/infinit/elle/blob/a8154593c42743f45b9df09daf62b44630c24a02/drake/src/drake/ocaml/__init__.py#L132-L139
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/__init__.py
python
connect_fps
(aws_access_key_id=None, aws_secret_access_key=None, **kwargs)
return FPSConnection(aws_access_key_id, aws_secret_access_key, **kwargs)
:type aws_access_key_id: string :param aws_access_key_id: Your AWS Access Key ID :type aws_secret_access_key: string :param aws_secret_access_key: Your AWS Secret Access Key :rtype: :class:`boto.fps.connection.FPSConnection` :return: A connection to FPS
:type aws_access_key_id: string :param aws_access_key_id: Your AWS Access Key ID
[ ":", "type", "aws_access_key_id", ":", "string", ":", "param", "aws_access_key_id", ":", "Your", "AWS", "Access", "Key", "ID" ]
def connect_fps(aws_access_key_id=None, aws_secret_access_key=None, **kwargs): """ :type aws_access_key_id: string :param aws_access_key_id: Your AWS Access Key ID :type aws_secret_access_key: string :param aws_secret_access_key: Your AWS Secret Access Key :rtype: :class:`boto.fps.connection.FPSConnection` :return: A connection to FPS """ from boto.fps.connection import FPSConnection return FPSConnection(aws_access_key_id, aws_secret_access_key, **kwargs)
[ "def", "connect_fps", "(", "aws_access_key_id", "=", "None", ",", "aws_secret_access_key", "=", "None", ",", "*", "*", "kwargs", ")", ":", "from", "boto", ".", "fps", ".", "connection", "import", "FPSConnection", "return", "FPSConnection", "(", "aws_access_key_id", ",", "aws_secret_access_key", ",", "*", "*", "kwargs", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/__init__.py#L243-L255
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/io/matlab/mio4.py
python
VarReader4.shape_from_header
(self, hdr)
return shape
Read the shape of the array described by the header. The file position after this call is unspecified.
Read the shape of the array described by the header. The file position after this call is unspecified.
[ "Read", "the", "shape", "of", "the", "array", "described", "by", "the", "header", ".", "The", "file", "position", "after", "this", "call", "is", "unspecified", "." ]
def shape_from_header(self, hdr): '''Read the shape of the array described by the header. The file position after this call is unspecified. ''' mclass = hdr.mclass if mclass == mxFULL_CLASS: shape = tuple(map(int, hdr.dims)) elif mclass == mxCHAR_CLASS: shape = tuple(map(int, hdr.dims)) if self.chars_as_strings: shape = shape[:-1] elif mclass == mxSPARSE_CLASS: dt = hdr.dtype dims = hdr.dims if not (len(dims) == 2 and dims[0] >= 1 and dims[1] >= 1): return () # Read only the row and column counts self.mat_stream.seek(dt.itemsize * (dims[0] - 1), 1) rows = np.ndarray(shape=(1,), dtype=dt, buffer=self.mat_stream.read(dt.itemsize)) self.mat_stream.seek(dt.itemsize * (dims[0] - 1), 1) cols = np.ndarray(shape=(1,), dtype=dt, buffer=self.mat_stream.read(dt.itemsize)) shape = (int(rows), int(cols)) else: raise TypeError('No reader for class code %s' % mclass) if self.squeeze_me: shape = tuple([x for x in shape if x != 1]) return shape
[ "def", "shape_from_header", "(", "self", ",", "hdr", ")", ":", "mclass", "=", "hdr", ".", "mclass", "if", "mclass", "==", "mxFULL_CLASS", ":", "shape", "=", "tuple", "(", "map", "(", "int", ",", "hdr", ".", "dims", ")", ")", "elif", "mclass", "==", "mxCHAR_CLASS", ":", "shape", "=", "tuple", "(", "map", "(", "int", ",", "hdr", ".", "dims", ")", ")", "if", "self", ".", "chars_as_strings", ":", "shape", "=", "shape", "[", ":", "-", "1", "]", "elif", "mclass", "==", "mxSPARSE_CLASS", ":", "dt", "=", "hdr", ".", "dtype", "dims", "=", "hdr", ".", "dims", "if", "not", "(", "len", "(", "dims", ")", "==", "2", "and", "dims", "[", "0", "]", ">=", "1", "and", "dims", "[", "1", "]", ">=", "1", ")", ":", "return", "(", ")", "# Read only the row and column counts", "self", ".", "mat_stream", ".", "seek", "(", "dt", ".", "itemsize", "*", "(", "dims", "[", "0", "]", "-", "1", ")", ",", "1", ")", "rows", "=", "np", ".", "ndarray", "(", "shape", "=", "(", "1", ",", ")", ",", "dtype", "=", "dt", ",", "buffer", "=", "self", ".", "mat_stream", ".", "read", "(", "dt", ".", "itemsize", ")", ")", "self", ".", "mat_stream", ".", "seek", "(", "dt", ".", "itemsize", "*", "(", "dims", "[", "0", "]", "-", "1", ")", ",", "1", ")", "cols", "=", "np", ".", "ndarray", "(", "shape", "=", "(", "1", ",", ")", ",", "dtype", "=", "dt", ",", "buffer", "=", "self", ".", "mat_stream", ".", "read", "(", "dt", ".", "itemsize", ")", ")", "shape", "=", "(", "int", "(", "rows", ")", ",", "int", "(", "cols", ")", ")", "else", ":", "raise", "TypeError", "(", "'No reader for class code %s'", "%", "mclass", ")", "if", "self", ".", "squeeze_me", ":", "shape", "=", "tuple", "(", "[", "x", "for", "x", "in", "shape", "if", "x", "!=", "1", "]", ")", "return", "shape" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/io/matlab/mio4.py#L269-L301
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
FWCore/Utilities/python/Enumerate.py
python
Enumerate.isValidKey
(self, key)
return key in self.__dict__
Returns true if this value is a valid enum key
Returns true if this value is a valid enum key
[ "Returns", "true", "if", "this", "value", "is", "a", "valid", "enum", "key" ]
def isValidKey (self, key): """ Returns true if this value is a valid enum key""" return key in self.__dict__
[ "def", "isValidKey", "(", "self", ",", "key", ")", ":", "return", "key", "in", "self", ".", "__dict__" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/FWCore/Utilities/python/Enumerate.py#L35-L37
H-uru/Plasma
c2140ea046e82e9c199e257a7f2e7edb42602871
Scripts/Python/xAvatarCustomization.py
python
CanShowClothingItem
(clothingItem)
return False
returns true if this item is elegable for showing
returns true if this item is elegable for showing
[ "returns", "true", "if", "this", "item", "is", "elegable", "for", "showing" ]
def CanShowClothingItem(clothingItem): "returns true if this item is elegable for showing" # make sure we're not supposed to hide the item if (clothingItem.internalOnly and PtIsInternalRelease()) or not clothingItem.internalOnly: if (clothingItem.nonStandardItem and ItemInWardrobe(clothingItem)) or not clothingItem.nonStandardItem: if (PtIsSinglePlayerMode() and clothingItem.singlePlayer) or not PtIsSinglePlayerMode(): if CanShowSeasonal(clothingItem): return True else: PtDebugPrint('CanShowClothingItem(): Hiding item %s because it is seasonal' % (clothingItem.name)) else: PtDebugPrint('CanShowClothingItem(): Hiding item %s because it is a multiplayer-only option' % (clothingItem.name)) else: PtDebugPrint('CanShowClothingItem(): Hiding item %s because it is optional and is not in your closet' % (clothingItem.name)) else: PtDebugPrint('CanShowClothingItem(): Hiding item %s because it is an internal-only option' % (clothingItem.name)) return False
[ "def", "CanShowClothingItem", "(", "clothingItem", ")", ":", "# make sure we're not supposed to hide the item", "if", "(", "clothingItem", ".", "internalOnly", "and", "PtIsInternalRelease", "(", ")", ")", "or", "not", "clothingItem", ".", "internalOnly", ":", "if", "(", "clothingItem", ".", "nonStandardItem", "and", "ItemInWardrobe", "(", "clothingItem", ")", ")", "or", "not", "clothingItem", ".", "nonStandardItem", ":", "if", "(", "PtIsSinglePlayerMode", "(", ")", "and", "clothingItem", ".", "singlePlayer", ")", "or", "not", "PtIsSinglePlayerMode", "(", ")", ":", "if", "CanShowSeasonal", "(", "clothingItem", ")", ":", "return", "True", "else", ":", "PtDebugPrint", "(", "'CanShowClothingItem(): Hiding item %s because it is seasonal'", "%", "(", "clothingItem", ".", "name", ")", ")", "else", ":", "PtDebugPrint", "(", "'CanShowClothingItem(): Hiding item %s because it is a multiplayer-only option'", "%", "(", "clothingItem", ".", "name", ")", ")", "else", ":", "PtDebugPrint", "(", "'CanShowClothingItem(): Hiding item %s because it is optional and is not in your closet'", "%", "(", "clothingItem", ".", "name", ")", ")", "else", ":", "PtDebugPrint", "(", "'CanShowClothingItem(): Hiding item %s because it is an internal-only option'", "%", "(", "clothingItem", ".", "name", ")", ")", "return", "False" ]
https://github.com/H-uru/Plasma/blob/c2140ea046e82e9c199e257a7f2e7edb42602871/Scripts/Python/xAvatarCustomization.py#L475-L492
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/richtext.py
python
RichTextBuffer.GetExtWildcard
(*args, **kwargs)
return _richtext.RichTextBuffer_GetExtWildcard(*args, **kwargs)
GetExtWildcard(self, bool combine=False, bool save=False) --> (wildcards, types) Gets a wildcard string for the file dialog based on all the currently loaded richtext file handlers, and a list that can be used to map those filter types to the file handler type.
GetExtWildcard(self, bool combine=False, bool save=False) --> (wildcards, types)
[ "GetExtWildcard", "(", "self", "bool", "combine", "=", "False", "bool", "save", "=", "False", ")", "--", ">", "(", "wildcards", "types", ")" ]
def GetExtWildcard(*args, **kwargs): """ GetExtWildcard(self, bool combine=False, bool save=False) --> (wildcards, types) Gets a wildcard string for the file dialog based on all the currently loaded richtext file handlers, and a list that can be used to map those filter types to the file handler type. """ return _richtext.RichTextBuffer_GetExtWildcard(*args, **kwargs)
[ "def", "GetExtWildcard", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextBuffer_GetExtWildcard", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L2584-L2592
apache/qpid-proton
6bcdfebb55ea3554bc29b1901422532db331a591
python/proton/_url.py
python
Url.defaults
(self)
return self
Fill in missing values (scheme, host or port) with defaults :return: self
Fill in missing values (scheme, host or port) with defaults :return: self
[ "Fill", "in", "missing", "values", "(", "scheme", "host", "or", "port", ")", "with", "defaults", ":", "return", ":", "self" ]
def defaults(self): """ Fill in missing values (scheme, host or port) with defaults :return: self """ self.scheme = self.scheme or self.AMQP self._host = self._host or '0.0.0.0' self._port = self._port or self.Port(self.scheme) return self
[ "def", "defaults", "(", "self", ")", ":", "self", ".", "scheme", "=", "self", ".", "scheme", "or", "self", ".", "AMQP", "self", ".", "_host", "=", "self", ".", "_host", "or", "'0.0.0.0'", "self", ".", "_port", "=", "self", ".", "_port", "or", "self", ".", "Port", "(", "self", ".", "scheme", ")", "return", "self" ]
https://github.com/apache/qpid-proton/blob/6bcdfebb55ea3554bc29b1901422532db331a591/python/proton/_url.py#L257-L265
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBProcess_GetRestartedFromEvent
(*args)
return _lldb.SBProcess_GetRestartedFromEvent(*args)
SBProcess_GetRestartedFromEvent(SBEvent event) -> bool
SBProcess_GetRestartedFromEvent(SBEvent event) -> bool
[ "SBProcess_GetRestartedFromEvent", "(", "SBEvent", "event", ")", "-", ">", "bool" ]
def SBProcess_GetRestartedFromEvent(*args): """SBProcess_GetRestartedFromEvent(SBEvent event) -> bool""" return _lldb.SBProcess_GetRestartedFromEvent(*args)
[ "def", "SBProcess_GetRestartedFromEvent", "(", "*", "args", ")", ":", "return", "_lldb", ".", "SBProcess_GetRestartedFromEvent", "(", "*", "args", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L7471-L7473
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/constants/constants.py
python
convert_temperature
(val, old_scale, new_scale)
return res
Convert from a temperature scale to another one among Celsius, Kelvin, Fahrenheit and Rankine scales. Parameters ---------- val : array_like Value(s) of the temperature(s) to be converted expressed in the original scale. old_scale: str Specifies as a string the original scale from which the temperature value(s) will be converted. Supported scales are Celsius ('Celsius', 'celsius', 'C' or 'c'), Kelvin ('Kelvin', 'kelvin', 'K', 'k'), Fahrenheit ('Fahrenheit', 'fahrenheit', 'F' or 'f') and Rankine ('Rankine', 'rankine', 'R', 'r'). new_scale: str Specifies as a string the new scale to which the temperature value(s) will be converted. Supported scales are Celsius ('Celsius', 'celsius', 'C' or 'c'), Kelvin ('Kelvin', 'kelvin', 'K', 'k'), Fahrenheit ('Fahrenheit', 'fahrenheit', 'F' or 'f') and Rankine ('Rankine', 'rankine', 'R', 'r'). Returns ------- res : float or array of floats Value(s) of the converted temperature(s) expressed in the new scale. Notes ----- .. versionadded:: 0.18.0 Examples -------- >>> from scipy.constants import convert_temperature >>> convert_temperature(np.array([-40, 40.0]), 'Celsius', 'Kelvin') array([ 233.15, 313.15])
Convert from a temperature scale to another one among Celsius, Kelvin, Fahrenheit and Rankine scales.
[ "Convert", "from", "a", "temperature", "scale", "to", "another", "one", "among", "Celsius", "Kelvin", "Fahrenheit", "and", "Rankine", "scales", "." ]
def convert_temperature(val, old_scale, new_scale): """ Convert from a temperature scale to another one among Celsius, Kelvin, Fahrenheit and Rankine scales. Parameters ---------- val : array_like Value(s) of the temperature(s) to be converted expressed in the original scale. old_scale: str Specifies as a string the original scale from which the temperature value(s) will be converted. Supported scales are Celsius ('Celsius', 'celsius', 'C' or 'c'), Kelvin ('Kelvin', 'kelvin', 'K', 'k'), Fahrenheit ('Fahrenheit', 'fahrenheit', 'F' or 'f') and Rankine ('Rankine', 'rankine', 'R', 'r'). new_scale: str Specifies as a string the new scale to which the temperature value(s) will be converted. Supported scales are Celsius ('Celsius', 'celsius', 'C' or 'c'), Kelvin ('Kelvin', 'kelvin', 'K', 'k'), Fahrenheit ('Fahrenheit', 'fahrenheit', 'F' or 'f') and Rankine ('Rankine', 'rankine', 'R', 'r'). Returns ------- res : float or array of floats Value(s) of the converted temperature(s) expressed in the new scale. Notes ----- .. versionadded:: 0.18.0 Examples -------- >>> from scipy.constants import convert_temperature >>> convert_temperature(np.array([-40, 40.0]), 'Celsius', 'Kelvin') array([ 233.15, 313.15]) """ # Convert from `old_scale` to Kelvin if old_scale.lower() in ['celsius', 'c']: tempo = _np.asanyarray(val) + zero_Celsius elif old_scale.lower() in ['kelvin', 'k']: tempo = _np.asanyarray(val) elif old_scale.lower() in ['fahrenheit', 'f']: tempo = (_np.asanyarray(val) - 32.) * 5. / 9. + zero_Celsius elif old_scale.lower() in ['rankine', 'r']: tempo = _np.asanyarray(val) * 5. / 9. else: raise NotImplementedError("%s scale is unsupported: supported scales " "are Celsius, Kelvin, Fahrenheit and " "Rankine" % old_scale) # and from Kelvin to `new_scale`. if new_scale.lower() in ['celsius', 'c']: res = tempo - zero_Celsius elif new_scale.lower() in ['kelvin', 'k']: res = tempo elif new_scale.lower() in ['fahrenheit', 'f']: res = (tempo - zero_Celsius) * 9. / 5. + 32. elif new_scale.lower() in ['rankine', 'r']: res = tempo * 9. / 5. else: raise NotImplementedError("'%s' scale is unsupported: supported " "scales are 'Celsius', 'Kelvin', " "'Fahrenheit' and 'Rankine'" % new_scale) return res
[ "def", "convert_temperature", "(", "val", ",", "old_scale", ",", "new_scale", ")", ":", "# Convert from `old_scale` to Kelvin", "if", "old_scale", ".", "lower", "(", ")", "in", "[", "'celsius'", ",", "'c'", "]", ":", "tempo", "=", "_np", ".", "asanyarray", "(", "val", ")", "+", "zero_Celsius", "elif", "old_scale", ".", "lower", "(", ")", "in", "[", "'kelvin'", ",", "'k'", "]", ":", "tempo", "=", "_np", ".", "asanyarray", "(", "val", ")", "elif", "old_scale", ".", "lower", "(", ")", "in", "[", "'fahrenheit'", ",", "'f'", "]", ":", "tempo", "=", "(", "_np", ".", "asanyarray", "(", "val", ")", "-", "32.", ")", "*", "5.", "/", "9.", "+", "zero_Celsius", "elif", "old_scale", ".", "lower", "(", ")", "in", "[", "'rankine'", ",", "'r'", "]", ":", "tempo", "=", "_np", ".", "asanyarray", "(", "val", ")", "*", "5.", "/", "9.", "else", ":", "raise", "NotImplementedError", "(", "\"%s scale is unsupported: supported scales \"", "\"are Celsius, Kelvin, Fahrenheit and \"", "\"Rankine\"", "%", "old_scale", ")", "# and from Kelvin to `new_scale`.", "if", "new_scale", ".", "lower", "(", ")", "in", "[", "'celsius'", ",", "'c'", "]", ":", "res", "=", "tempo", "-", "zero_Celsius", "elif", "new_scale", ".", "lower", "(", ")", "in", "[", "'kelvin'", ",", "'k'", "]", ":", "res", "=", "tempo", "elif", "new_scale", ".", "lower", "(", ")", "in", "[", "'fahrenheit'", ",", "'f'", "]", ":", "res", "=", "(", "tempo", "-", "zero_Celsius", ")", "*", "9.", "/", "5.", "+", "32.", "elif", "new_scale", ".", "lower", "(", ")", "in", "[", "'rankine'", ",", "'r'", "]", ":", "res", "=", "tempo", "*", "9.", "/", "5.", "else", ":", "raise", "NotImplementedError", "(", "\"'%s' scale is unsupported: supported \"", "\"scales are 'Celsius', 'Kelvin', \"", "\"'Fahrenheit' and 'Rankine'\"", "%", "new_scale", ")", "return", "res" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/constants/constants.py#L178-L246
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/SANS/sans/state/StateObjects/state_instrument_info.py
python
_set_detector_names
(state: StateInstrumentInfo, ipf_path, invalid_detector_types=None)
Sets the detectors names on a State object which has a `detector` map entry, e.g. StateMask :param state: the state object :param ipf_path: the path to the Instrument Parameter File :param invalid_detector_types: a list of invalid detector types which don't exist for the instrument
Sets the detectors names on a State object which has a `detector` map entry, e.g. StateMask
[ "Sets", "the", "detectors", "names", "on", "a", "State", "object", "which", "has", "a", "detector", "map", "entry", "e", ".", "g", ".", "StateMask" ]
def _set_detector_names(state: StateInstrumentInfo, ipf_path, invalid_detector_types=None): """ Sets the detectors names on a State object which has a `detector` map entry, e.g. StateMask :param state: the state object :param ipf_path: the path to the Instrument Parameter File :param invalid_detector_types: a list of invalid detector types which don't exist for the instrument """ if invalid_detector_types is None: invalid_detector_types = [] lab_keyword = DetectorType.LAB.value hab_keyword = DetectorType.HAB.value detector_names = {lab_keyword: "low-angle-detector-name", hab_keyword: "high-angle-detector-name"} detector_names_short = {lab_keyword: "low-angle-detector-short-name", hab_keyword: "high-angle-detector-short-name"} names_to_search = [] names_to_search.extend(list(detector_names.values())) names_to_search.extend(list(detector_names_short.values())) found_detector_names = get_named_elements_from_ipf_file(ipf_path, names_to_search, str) for detector_type in state.detector_names: try: if DetectorType(detector_type) in invalid_detector_types: continue detector_name_tag = detector_names[detector_type] detector_name_short_tag = detector_names_short[detector_type] detector_name = found_detector_names[detector_name_tag] detector_name_short = found_detector_names[detector_name_short_tag] except KeyError: continue state.detector_names[detector_type].detector_name = detector_name state.detector_names[detector_type].detector_name_short = detector_name_short
[ "def", "_set_detector_names", "(", "state", ":", "StateInstrumentInfo", ",", "ipf_path", ",", "invalid_detector_types", "=", "None", ")", ":", "if", "invalid_detector_types", "is", "None", ":", "invalid_detector_types", "=", "[", "]", "lab_keyword", "=", "DetectorType", ".", "LAB", ".", "value", "hab_keyword", "=", "DetectorType", ".", "HAB", ".", "value", "detector_names", "=", "{", "lab_keyword", ":", "\"low-angle-detector-name\"", ",", "hab_keyword", ":", "\"high-angle-detector-name\"", "}", "detector_names_short", "=", "{", "lab_keyword", ":", "\"low-angle-detector-short-name\"", ",", "hab_keyword", ":", "\"high-angle-detector-short-name\"", "}", "names_to_search", "=", "[", "]", "names_to_search", ".", "extend", "(", "list", "(", "detector_names", ".", "values", "(", ")", ")", ")", "names_to_search", ".", "extend", "(", "list", "(", "detector_names_short", ".", "values", "(", ")", ")", ")", "found_detector_names", "=", "get_named_elements_from_ipf_file", "(", "ipf_path", ",", "names_to_search", ",", "str", ")", "for", "detector_type", "in", "state", ".", "detector_names", ":", "try", ":", "if", "DetectorType", "(", "detector_type", ")", "in", "invalid_detector_types", ":", "continue", "detector_name_tag", "=", "detector_names", "[", "detector_type", "]", "detector_name_short_tag", "=", "detector_names_short", "[", "detector_type", "]", "detector_name", "=", "found_detector_names", "[", "detector_name_tag", "]", "detector_name_short", "=", "found_detector_names", "[", "detector_name_short_tag", "]", "except", "KeyError", ":", "continue", "state", ".", "detector_names", "[", "detector_type", "]", ".", "detector_name", "=", "detector_name", "state", ".", "detector_names", "[", "detector_type", "]", ".", "detector_name_short", "=", "detector_name_short" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/sans/state/StateObjects/state_instrument_info.py#L60-L95
NervanaSystems/ngraph
f677a119765ca30636cf407009dabd118664951f
python/src/ngraph/ops.py
python
cum_sum
( arg: NodeInput, axis: NodeInput, exclusive: bool = False, reverse: bool = False, name: Optional[str] = None, )
return _get_node_factory().create( "CumSum", as_nodes(arg, axis), {"exclusive": exclusive, "reverse": reverse} )
Construct a cumulative summation operation. :param arg: The tensor to be summed. :param axis: zero dimension tensor specifying axis position along which sum will be performed. :param exclusive: if set to true, the top element is not included :param reverse: if set to true, will perform the sums in reverse direction :return: New node performing the operation
Construct a cumulative summation operation.
[ "Construct", "a", "cumulative", "summation", "operation", "." ]
def cum_sum( arg: NodeInput, axis: NodeInput, exclusive: bool = False, reverse: bool = False, name: Optional[str] = None, ) -> Node: """Construct a cumulative summation operation. :param arg: The tensor to be summed. :param axis: zero dimension tensor specifying axis position along which sum will be performed. :param exclusive: if set to true, the top element is not included :param reverse: if set to true, will perform the sums in reverse direction :return: New node performing the operation """ return _get_node_factory().create( "CumSum", as_nodes(arg, axis), {"exclusive": exclusive, "reverse": reverse} )
[ "def", "cum_sum", "(", "arg", ":", "NodeInput", ",", "axis", ":", "NodeInput", ",", "exclusive", ":", "bool", "=", "False", ",", "reverse", ":", "bool", "=", "False", ",", "name", ":", "Optional", "[", "str", "]", "=", "None", ",", ")", "->", "Node", ":", "return", "_get_node_factory", "(", ")", ".", "create", "(", "\"CumSum\"", ",", "as_nodes", "(", "arg", ",", "axis", ")", ",", "{", "\"exclusive\"", ":", "exclusive", ",", "\"reverse\"", ":", "reverse", "}", ")" ]
https://github.com/NervanaSystems/ngraph/blob/f677a119765ca30636cf407009dabd118664951f/python/src/ngraph/ops.py#L2048-L2065
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
gpu/command_buffer/build_gles2_cmd_buffer.py
python
Function.__GetArgList
(self, arg_string, add_comma)
return "%s%s" % (comma, arg_string)
Adds a comma if arg_string is not empty and add_comma is true.
Adds a comma if arg_string is not empty and add_comma is true.
[ "Adds", "a", "comma", "if", "arg_string", "is", "not", "empty", "and", "add_comma", "is", "true", "." ]
def __GetArgList(self, arg_string, add_comma): """Adds a comma if arg_string is not empty and add_comma is true.""" comma = "" if add_comma and len(arg_string): comma = ", " return "%s%s" % (comma, arg_string)
[ "def", "__GetArgList", "(", "self", ",", "arg_string", ",", "add_comma", ")", ":", "comma", "=", "\"\"", "if", "add_comma", "and", "len", "(", "arg_string", ")", ":", "comma", "=", "\", \"", "return", "\"%s%s\"", "%", "(", "comma", ",", "arg_string", ")" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/gpu/command_buffer/build_gles2_cmd_buffer.py#L5204-L5209
msitt/blpapi-python
bebcf43668c9e5f5467b1f685f9baebbfc45bc87
src/blpapi/element.py
python
Element.getValueAsString
(self, index=0)
return res[1]
Args: index (int): Index of the value in the element Returns: str: ``index``\ th entry in the :class:`Element` as a string. Raises: InvalidConversionException: If the data type of this :class:`Element` cannot be converted to a string. IndexOutOfRangeException: If ``index >= numValues()``.
Args: index (int): Index of the value in the element
[ "Args", ":", "index", "(", "int", ")", ":", "Index", "of", "the", "value", "in", "the", "element" ]
def getValueAsString(self, index=0): """ Args: index (int): Index of the value in the element Returns: str: ``index``\ th entry in the :class:`Element` as a string. Raises: InvalidConversionException: If the data type of this :class:`Element` cannot be converted to a string. IndexOutOfRangeException: If ``index >= numValues()``. """ self.__assertIsValid() res = internals.blpapi_Element_getValueAsString(self.__handle, index) _ExceptionUtil.raiseOnError(res[0]) return res[1]
[ "def", "getValueAsString", "(", "self", ",", "index", "=", "0", ")", ":", "self", ".", "__assertIsValid", "(", ")", "res", "=", "internals", ".", "blpapi_Element_getValueAsString", "(", "self", ".", "__handle", ",", "index", ")", "_ExceptionUtil", ".", "raiseOnError", "(", "res", "[", "0", "]", ")", "return", "res", "[", "1", "]" ]
https://github.com/msitt/blpapi-python/blob/bebcf43668c9e5f5467b1f685f9baebbfc45bc87/src/blpapi/element.py#L670-L687
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py3/prompt_toolkit/input/win32_pipe.py
python
Win32PipeInput.flush_keys
(self)
return result
Flush pending keys and return them. (Used for flushing the 'escape' key.)
Flush pending keys and return them. (Used for flushing the 'escape' key.)
[ "Flush", "pending", "keys", "and", "return", "them", ".", "(", "Used", "for", "flushing", "the", "escape", "key", ".", ")" ]
def flush_keys(self) -> List[KeyPress]: """ Flush pending keys and return them. (Used for flushing the 'escape' key.) """ # Flush all pending keys. (This is most important to flush the vt100 # 'Escape' key early when nothing else follows.) self.vt100_parser.flush() # Return result. result = self._buffer self._buffer = [] return result
[ "def", "flush_keys", "(", "self", ")", "->", "List", "[", "KeyPress", "]", ":", "# Flush all pending keys. (This is most important to flush the vt100", "# 'Escape' key early when nothing else follows.)", "self", ".", "vt100_parser", ".", "flush", "(", ")", "# Return result.", "result", "=", "self", ".", "_buffer", "self", ".", "_buffer", "=", "[", "]", "return", "result" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/input/win32_pipe.py#L94-L106
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/import/vissim/tls_vissimXML2SUMOnet_update.py
python
is_verbinder
(xmldoc)
return is_verbinder_d
checks if a given link is a verbinder
checks if a given link is a verbinder
[ "checks", "if", "a", "given", "link", "is", "a", "verbinder" ]
def is_verbinder(xmldoc): """checks if a given link is a verbinder""" is_verbinder_d = dict() for link in xmldoc.getElementsByTagName("link"): if len(link.getElementsByTagName("fromLinkEndPt")) > 0: is_verbinder_d[link.getAttribute("no")] = True else: is_verbinder_d[link.getAttribute("no")] = False return is_verbinder_d
[ "def", "is_verbinder", "(", "xmldoc", ")", ":", "is_verbinder_d", "=", "dict", "(", ")", "for", "link", "in", "xmldoc", ".", "getElementsByTagName", "(", "\"link\"", ")", ":", "if", "len", "(", "link", ".", "getElementsByTagName", "(", "\"fromLinkEndPt\"", ")", ")", ">", "0", ":", "is_verbinder_d", "[", "link", ".", "getAttribute", "(", "\"no\"", ")", "]", "=", "True", "else", ":", "is_verbinder_d", "[", "link", ".", "getAttribute", "(", "\"no\"", ")", "]", "=", "False", "return", "is_verbinder_d" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/import/vissim/tls_vissimXML2SUMOnet_update.py#L429-L437
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/tensor_array_ops.py
python
_GraphTensorArrayV2.write
(self, index, value, name=None)
See TensorArray.
See TensorArray.
[ "See", "TensorArray", "." ]
def write(self, index, value, name=None): """See TensorArray.""" with ops.name_scope(name, "TensorArrayV2Write", [self._flow, index, value]): # TODO(b/129870929): Fix after all callers provide proper init dtype. value = ops.convert_to_tensor( value, preferred_dtype=self._dtype, name="value") _check_dtypes(value, self._dtype) self._check_element_shape(value.shape) flow_out = list_ops.tensor_list_set_item( input_handle=self._flow, index=index, item=value, resize_if_index_out_of_bounds=self._dynamic_size, name=name) return build_ta_with_new_flow(self, flow_out)
[ "def", "write", "(", "self", ",", "index", ",", "value", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "name_scope", "(", "name", ",", "\"TensorArrayV2Write\"", ",", "[", "self", ".", "_flow", ",", "index", ",", "value", "]", ")", ":", "# TODO(b/129870929): Fix after all callers provide proper init dtype.", "value", "=", "ops", ".", "convert_to_tensor", "(", "value", ",", "preferred_dtype", "=", "self", ".", "_dtype", ",", "name", "=", "\"value\"", ")", "_check_dtypes", "(", "value", ",", "self", ".", "_dtype", ")", "self", ".", "_check_element_shape", "(", "value", ".", "shape", ")", "flow_out", "=", "list_ops", ".", "tensor_list_set_item", "(", "input_handle", "=", "self", ".", "_flow", ",", "index", "=", "index", ",", "item", "=", "value", ",", "resize_if_index_out_of_bounds", "=", "self", ".", "_dynamic_size", ",", "name", "=", "name", ")", "return", "build_ta_with_new_flow", "(", "self", ",", "flow_out", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/tensor_array_ops.py#L537-L551
choasup/caffe-yolo9000
e8a476c4c23d756632f7a26c681a96e3ab672544
scripts/cpp_lint.py
python
FileInfo.BaseName
(self)
return self.Split()[1]
File base name - text after the final slash, before the final period.
File base name - text after the final slash, before the final period.
[ "File", "base", "name", "-", "text", "after", "the", "final", "slash", "before", "the", "final", "period", "." ]
def BaseName(self): """File base name - text after the final slash, before the final period.""" return self.Split()[1]
[ "def", "BaseName", "(", "self", ")", ":", "return", "self", ".", "Split", "(", ")", "[", "1", "]" ]
https://github.com/choasup/caffe-yolo9000/blob/e8a476c4c23d756632f7a26c681a96e3ab672544/scripts/cpp_lint.py#L944-L946
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_controls.py
python
PreListCtrl
(*args, **kwargs)
return val
PreListCtrl() -> ListCtrl
PreListCtrl() -> ListCtrl
[ "PreListCtrl", "()", "-", ">", "ListCtrl" ]
def PreListCtrl(*args, **kwargs): """PreListCtrl() -> ListCtrl""" val = _controls_.new_PreListCtrl(*args, **kwargs) return val
[ "def", "PreListCtrl", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "val", "=", "_controls_", ".", "new_PreListCtrl", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "val" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L4864-L4867
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/distribute/merge_call_interim.py
python
maybe_merge_call
(fn, strategy, *args, **kwargs)
Maybe invoke `fn` via `merge_call` which may or may not be fulfilled. The caller of this utility function requests to invoke `fn` via `merge_call` at `tf.distribute.Strategy`'s best efforts. It is `tf.distribute`'s internal whether the request is honored, depending on the `Strategy`. See `tf.distribute.ReplicaContext.merge_call()` for more information. This is an interim API which is subject to removal and does not guarantee backward-compatibility. Args: fn: the function to be invoked. strategy: the `tf.distribute.Strategy` to call `fn` with. *args: the positional arguments to be passed in to `fn`. **kwargs: the keyword arguments to be passed in to `fn`. Returns: The return value of the `fn` call.
Maybe invoke `fn` via `merge_call` which may or may not be fulfilled.
[ "Maybe", "invoke", "fn", "via", "merge_call", "which", "may", "or", "may", "not", "be", "fulfilled", "." ]
def maybe_merge_call(fn, strategy, *args, **kwargs): """Maybe invoke `fn` via `merge_call` which may or may not be fulfilled. The caller of this utility function requests to invoke `fn` via `merge_call` at `tf.distribute.Strategy`'s best efforts. It is `tf.distribute`'s internal whether the request is honored, depending on the `Strategy`. See `tf.distribute.ReplicaContext.merge_call()` for more information. This is an interim API which is subject to removal and does not guarantee backward-compatibility. Args: fn: the function to be invoked. strategy: the `tf.distribute.Strategy` to call `fn` with. *args: the positional arguments to be passed in to `fn`. **kwargs: the keyword arguments to be passed in to `fn`. Returns: The return value of the `fn` call. """ if strategy_supports_no_merge_call(): return fn(strategy, *args, **kwargs) else: return distribution_strategy_context.get_replica_context().merge_call( fn, args=args, kwargs=kwargs)
[ "def", "maybe_merge_call", "(", "fn", ",", "strategy", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "strategy_supports_no_merge_call", "(", ")", ":", "return", "fn", "(", "strategy", ",", "*", "args", ",", "*", "*", "kwargs", ")", "else", ":", "return", "distribution_strategy_context", ".", "get_replica_context", "(", ")", ".", "merge_call", "(", "fn", ",", "args", "=", "args", ",", "kwargs", "=", "kwargs", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/distribute/merge_call_interim.py#L30-L54
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/tools/grit/grit/format/android_xml.py
python
_FormatPluralMessage
(message)
return ''.join(lines)
Compiles ICU plural syntax to the body of an Android <plurals> element. 1. In a .grd file, we can write a plural string like this: <message name="IDS_THINGS"> {NUM_THINGS, plural, =1 {1 thing} other {# things}} </message> 2. The Android equivalent looks like this: <plurals name="things"> <item quantity="one">1 thing</item> <item quantity="other">%d things</item> </plurals> This method takes the body of (1) and converts it to the body of (2). If the message is *not* a plural string, this function returns `None`. If the message includes quantities without an equivalent format in Android, it raises an exception.
Compiles ICU plural syntax to the body of an Android <plurals> element.
[ "Compiles", "ICU", "plural", "syntax", "to", "the", "body", "of", "an", "Android", "<plurals", ">", "element", "." ]
def _FormatPluralMessage(message): """Compiles ICU plural syntax to the body of an Android <plurals> element. 1. In a .grd file, we can write a plural string like this: <message name="IDS_THINGS"> {NUM_THINGS, plural, =1 {1 thing} other {# things}} </message> 2. The Android equivalent looks like this: <plurals name="things"> <item quantity="one">1 thing</item> <item quantity="other">%d things</item> </plurals> This method takes the body of (1) and converts it to the body of (2). If the message is *not* a plural string, this function returns `None`. If the message includes quantities without an equivalent format in Android, it raises an exception. """ ret = {} plural_match = _PLURALS_PATTERN.match(message) if not plural_match: return None body_in = plural_match.group('items').strip() lines = [] quantities_so_far = set() for item_match in _PLURALS_ITEM_PATTERN.finditer(body_in): quantity_in = item_match.group('quantity') quantity_out = _PLURALS_QUANTITY_MAP.get(quantity_in) value_in = item_match.group('value') value_out = '"' + value_in.replace('#', '%d') + '"' if quantity_out: # only one line per quantity out (https://crbug.com/787488) if quantity_out not in quantities_so_far: quantities_so_far.add(quantity_out) lines.append(_PLURALS_ITEM_TEMPLATE % (quantity_out, value_out)) else: raise Exception('Unsupported plural quantity for android ' 'strings.xml: %s' % quantity_in) return ''.join(lines)
[ "def", "_FormatPluralMessage", "(", "message", ")", ":", "ret", "=", "{", "}", "plural_match", "=", "_PLURALS_PATTERN", ".", "match", "(", "message", ")", "if", "not", "plural_match", ":", "return", "None", "body_in", "=", "plural_match", ".", "group", "(", "'items'", ")", ".", "strip", "(", ")", "lines", "=", "[", "]", "quantities_so_far", "=", "set", "(", ")", "for", "item_match", "in", "_PLURALS_ITEM_PATTERN", ".", "finditer", "(", "body_in", ")", ":", "quantity_in", "=", "item_match", ".", "group", "(", "'quantity'", ")", "quantity_out", "=", "_PLURALS_QUANTITY_MAP", ".", "get", "(", "quantity_in", ")", "value_in", "=", "item_match", ".", "group", "(", "'value'", ")", "value_out", "=", "'\"'", "+", "value_in", ".", "replace", "(", "'#'", ",", "'%d'", ")", "+", "'\"'", "if", "quantity_out", ":", "# only one line per quantity out (https://crbug.com/787488)", "if", "quantity_out", "not", "in", "quantities_so_far", ":", "quantities_so_far", ".", "add", "(", "quantity_out", ")", "lines", ".", "append", "(", "_PLURALS_ITEM_TEMPLATE", "%", "(", "quantity_out", ",", "value_out", ")", ")", "else", ":", "raise", "Exception", "(", "'Unsupported plural quantity for android '", "'strings.xml: %s'", "%", "quantity_in", ")", "return", "''", ".", "join", "(", "lines", ")" ]
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/tools/grit/grit/format/android_xml.py#L147-L191
CalcProgrammer1/OpenRGB
8156b0167a7590dd8ba561dfde524bfcacf46b5e
dependencies/mbedtls-2.24.0/scripts/config.py
python
ConfigFile._format_template
(self, name, indent, middle)
return ''.join([indent, '' if setting.active else '//', middle, value]).rstrip()
Build a line for config.h for the given setting. The line has the form "<indent>#define <name> <value>" where <middle> is "#define <name> ".
Build a line for config.h for the given setting.
[ "Build", "a", "line", "for", "config", ".", "h", "for", "the", "given", "setting", "." ]
def _format_template(self, name, indent, middle): """Build a line for config.h for the given setting. The line has the form "<indent>#define <name> <value>" where <middle> is "#define <name> ". """ setting = self.settings[name] value = setting.value if value is None: value = '' # Normally the whitespace to separte the symbol name from the # value is part of middle, and there's no whitespace for a symbol # with no value. But if a symbol has been changed from having a # value to not having one, the whitespace is wrong, so fix it. if value: if middle[-1] not in '\t ': middle += ' ' else: middle = middle.rstrip() return ''.join([indent, '' if setting.active else '//', middle, value]).rstrip()
[ "def", "_format_template", "(", "self", ",", "name", ",", "indent", ",", "middle", ")", ":", "setting", "=", "self", ".", "settings", "[", "name", "]", "value", "=", "setting", ".", "value", "if", "value", "is", "None", ":", "value", "=", "''", "# Normally the whitespace to separte the symbol name from the", "# value is part of middle, and there's no whitespace for a symbol", "# with no value. But if a symbol has been changed from having a", "# value to not having one, the whitespace is wrong, so fix it.", "if", "value", ":", "if", "middle", "[", "-", "1", "]", "not", "in", "'\\t '", ":", "middle", "+=", "' '", "else", ":", "middle", "=", "middle", ".", "rstrip", "(", ")", "return", "''", ".", "join", "(", "[", "indent", ",", "''", "if", "setting", ".", "active", "else", "'//'", ",", "middle", ",", "value", "]", ")", ".", "rstrip", "(", ")" ]
https://github.com/CalcProgrammer1/OpenRGB/blob/8156b0167a7590dd8ba561dfde524bfcacf46b5e/dependencies/mbedtls-2.24.0/scripts/config.py#L392-L414