nwo
stringlengths
5
86
sha
stringlengths
40
40
path
stringlengths
4
189
language
stringclasses
1 value
identifier
stringlengths
1
94
parameters
stringlengths
2
4.03k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
11.5k
docstring
stringlengths
1
33.2k
docstring_summary
stringlengths
0
5.15k
docstring_tokens
list
function
stringlengths
34
151k
function_tokens
list
url
stringlengths
90
278
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/syntax/_cobra.py
python
AutoIndenter
(estc, pos, ichar)
Auto indent cobra code. @param estc: EditraStyledTextCtrl @param pos: current carat position @param ichar: Indentation character
Auto indent cobra code. @param estc: EditraStyledTextCtrl @param pos: current carat position @param ichar: Indentation character
[ "Auto", "indent", "cobra", "code", ".", "@param", "estc", ":", "EditraStyledTextCtrl", "@param", "pos", ":", "current", "carat", "position", "@param", "ichar", ":", "Indentation", "character" ]
def AutoIndenter(estc, pos, ichar): """Auto indent cobra code. @param estc: EditraStyledTextCtrl @param pos: current carat position @param ichar: Indentation character """ line = estc.GetCurrentLine() spos = estc.PositionFromLine(line) text = estc.GetTextRange(spos, pos) eolch = estc.GetEOLChar() inspace = text.isspace() # Cursor is in the indent area somewhere if inspace: estc.AddText(eolch + text) return # Check if the cursor is in column 0 and just return newline. if not len(text): estc.AddText(eolch) return indent = estc.GetLineIndentation(line) if ichar == u"\t": tabw = estc.GetTabWidth() else: tabw = estc.GetIndent() i_space = indent / tabw end_spaces = ((indent - (tabw * i_space)) * u" ") tokens = filter(None, text.strip().split()) if tokens and not inspace: if tokens[-1].endswith(u""): if tokens[0] in INDENT_KW: i_space += 1 elif tokens[0] in UNINDENT_KW: i_space = max(i_space - 1, 0) elif tokens[-1].endswith(u"\\"): i_space += 1 rval = eolch + (ichar * i_space) + end_spaces if inspace and ichar != u"\t": rpos = indent - (pos - spos) if rpos < len(rval) and rpos > 0: rval = rval[:-rpos] elif rpos >= len(rval): rval = eolch # Put text in the buffer estc.AddText(rval)
[ "def", "AutoIndenter", "(", "estc", ",", "pos", ",", "ichar", ")", ":", "line", "=", "estc", ".", "GetCurrentLine", "(", ")", "spos", "=", "estc", ".", "PositionFromLine", "(", "line", ")", "text", "=", "estc", ".", "GetTextRange", "(", "spos", ",", ...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/syntax/_cobra.py#L101-L152
openMSX/openMSX
c9cfbc0a2a2baaf2c4513c87543fe29bfe8cf806
build/probe.py
python
tryCompile
(log, compileCommand, sourcePath, lines)
Write the program defined by "lines" to a text file specified by "path" and try to compile it. Returns True iff compilation succeeded.
Write the program defined by "lines" to a text file specified by "path" and try to compile it. Returns True iff compilation succeeded.
[ "Write", "the", "program", "defined", "by", "lines", "to", "a", "text", "file", "specified", "by", "path", "and", "try", "to", "compile", "it", ".", "Returns", "True", "iff", "compilation", "succeeded", "." ]
def tryCompile(log, compileCommand, sourcePath, lines): '''Write the program defined by "lines" to a text file specified by "path" and try to compile it. Returns True iff compilation succeeded. ''' assert sourcePath.endswith('.cc') objectPath = sourcePath[ : -3] + '.o' writeFile(sourcePath, lines) try: return compileCommand.compile(log, sourcePath, objectPath) finally: remove(sourcePath) if isfile(objectPath): remove(objectPath)
[ "def", "tryCompile", "(", "log", ",", "compileCommand", ",", "sourcePath", ",", "lines", ")", ":", "assert", "sourcePath", ".", "endswith", "(", "'.cc'", ")", "objectPath", "=", "sourcePath", "[", ":", "-", "3", "]", "+", "'.o'", "writeFile", "(", "sourc...
https://github.com/openMSX/openMSX/blob/c9cfbc0a2a2baaf2c4513c87543fe29bfe8cf806/build/probe.py#L41-L54
protocolbuffers/protobuf
b5ab0b7a18b7336c60130f4ddb2d97c51792f896
python/google/protobuf/internal/python_message.py
python
_AddEqualsMethod
(message_descriptor, cls)
Helper for _AddMessageMethods().
Helper for _AddMessageMethods().
[ "Helper", "for", "_AddMessageMethods", "()", "." ]
def _AddEqualsMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def __eq__(self, other): if (not isinstance(other, message_mod.Message) or other.DESCRIPTOR != self.DESCRIPTOR): return False if self is other: return True if self.DESCRIPTOR.full_name == _AnyFullTypeName: any_a = _InternalUnpackAny(self) any_b = _InternalUnpackAny(other) if any_a and any_b: return any_a == any_b if not self.ListFields() == other.ListFields(): return False # TODO(jieluo): Fix UnknownFieldSet to consider MessageSet extensions, # then use it for the comparison. unknown_fields = list(self._unknown_fields) unknown_fields.sort() other_unknown_fields = list(other._unknown_fields) other_unknown_fields.sort() return unknown_fields == other_unknown_fields cls.__eq__ = __eq__
[ "def", "_AddEqualsMethod", "(", "message_descriptor", ",", "cls", ")", ":", "def", "__eq__", "(", "self", ",", "other", ")", ":", "if", "(", "not", "isinstance", "(", "other", ",", "message_mod", ".", "Message", ")", "or", "other", ".", "DESCRIPTOR", "!=...
https://github.com/protocolbuffers/protobuf/blob/b5ab0b7a18b7336c60130f4ddb2d97c51792f896/python/google/protobuf/internal/python_message.py#L978-L1005
NVIDIA/DALI
bf16cc86ba8f091b145f91962f21fe1b6aff243d
docs/examples/use_cases/video_superres/common/fp16.py
python
FP16_Optimizer.load_state_dict
(self, state_dict)
Loads a state_dict created by an earlier call to state_dict. Untested.
Loads a state_dict created by an earlier call to state_dict.
[ "Loads", "a", "state_dict", "created", "by", "an", "earlier", "call", "to", "state_dict", "." ]
def load_state_dict(self, state_dict): """ Loads a state_dict created by an earlier call to state_dict. Untested. """ self.loss_scaler = state_dict['loss_scaler'] self.dynamic_loss_scale = state_dict['dynamic_loss_scale'] self.overflow = state_dict['overflow'] self.first_closure_call_this_step = state_dict['first_closure_call_this_step'] self.optimizer.load_state_dict(state_dict['optimizer_state_dict'])
[ "def", "load_state_dict", "(", "self", ",", "state_dict", ")", ":", "self", ".", "loss_scaler", "=", "state_dict", "[", "'loss_scaler'", "]", "self", ".", "dynamic_loss_scale", "=", "state_dict", "[", "'dynamic_loss_scale'", "]", "self", ".", "overflow", "=", ...
https://github.com/NVIDIA/DALI/blob/bf16cc86ba8f091b145f91962f21fe1b6aff243d/docs/examples/use_cases/video_superres/common/fp16.py#L212-L222
PixarAnimationStudios/USD
faed18ce62c8736b02413635b584a2f637156bad
pxr/base/tf/__init__.py
python
Fatal
(msg)
Raise a fatal error to the Tf Diagnostic system.
Raise a fatal error to the Tf Diagnostic system.
[ "Raise", "a", "fatal", "error", "to", "the", "Tf", "Diagnostic", "system", "." ]
def Fatal(msg): """Raise a fatal error to the Tf Diagnostic system.""" codeInfo = GetCodeLocation(framesUp=1) _Fatal(msg, codeInfo[0], codeInfo[1], codeInfo[2], codeInfo[3])
[ "def", "Fatal", "(", "msg", ")", ":", "codeInfo", "=", "GetCodeLocation", "(", "framesUp", "=", "1", ")", "_Fatal", "(", "msg", ",", "codeInfo", "[", "0", "]", ",", "codeInfo", "[", "1", "]", ",", "codeInfo", "[", "2", "]", ",", "codeInfo", "[", ...
https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/pxr/base/tf/__init__.py#L205-L208
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/config/expandlibs.py
python
relativize
(path)
return path
Returns a path relative to the current working directory, if it is shorter than the given path
Returns a path relative to the current working directory, if it is shorter than the given path
[ "Returns", "a", "path", "relative", "to", "the", "current", "working", "directory", "if", "it", "is", "shorter", "than", "the", "given", "path" ]
def relativize(path): '''Returns a path relative to the current working directory, if it is shorter than the given path''' def splitpath(path): dir, file = os.path.split(path) if os.path.splitdrive(dir)[1] == os.sep: return [file] return splitpath(dir) + [file] if not os.path.exists(path): return path curdir = splitpath(os.path.abspath(os.curdir)) abspath = splitpath(os.path.abspath(path)) while curdir and abspath and curdir[0] == abspath[0]: del curdir[0] del abspath[0] if not curdir and not abspath: return '.' relpath = os.path.join(*[os.pardir for i in curdir] + abspath) if len(path) > len(relpath): return relpath return path
[ "def", "relativize", "(", "path", ")", ":", "def", "splitpath", "(", "path", ")", ":", "dir", ",", "file", "=", "os", ".", "path", ".", "split", "(", "path", ")", "if", "os", ".", "path", ".", "splitdrive", "(", "dir", ")", "[", "1", "]", "==",...
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/config/expandlibs.py#L43-L64
pgRouting/osm2pgrouting
8491929fc4037d308f271e84d59bb96da3c28aa2
tools/cpplint.py
python
_DropCommonSuffixes
(filename)
return os.path.splitext(filename)[0]
Drops common suffixes like _test.cc or -inl.h from filename. For example: >>> _DropCommonSuffixes('foo/foo-inl.h') 'foo/foo' >>> _DropCommonSuffixes('foo/bar/foo.cc') 'foo/bar/foo' >>> _DropCommonSuffixes('foo/foo_internal.h') 'foo/foo' >>> _DropCommonSuffixes('foo/foo_unusualinternal.h') 'foo/foo_unusualinternal' Args: filename: The input filename. Returns: The filename with the common suffix removed.
Drops common suffixes like _test.cc or -inl.h from filename.
[ "Drops", "common", "suffixes", "like", "_test", ".", "cc", "or", "-", "inl", ".", "h", "from", "filename", "." ]
def _DropCommonSuffixes(filename): """Drops common suffixes like _test.cc or -inl.h from filename. For example: >>> _DropCommonSuffixes('foo/foo-inl.h') 'foo/foo' >>> _DropCommonSuffixes('foo/bar/foo.cc') 'foo/bar/foo' >>> _DropCommonSuffixes('foo/foo_internal.h') 'foo/foo' >>> _DropCommonSuffixes('foo/foo_unusualinternal.h') 'foo/foo_unusualinternal' Args: filename: The input filename. Returns: The filename with the common suffix removed. """ for suffix in ('test.cc', 'regtest.cc', 'unittest.cc', 'inl.h', 'impl.h', 'internal.h'): if (filename.endswith(suffix) and len(filename) > len(suffix) and filename[-len(suffix) - 1] in ('-', '_')): return filename[:-len(suffix) - 1] return os.path.splitext(filename)[0]
[ "def", "_DropCommonSuffixes", "(", "filename", ")", ":", "for", "suffix", "in", "(", "'test.cc'", ",", "'regtest.cc'", ",", "'unittest.cc'", ",", "'inl.h'", ",", "'impl.h'", ",", "'internal.h'", ")", ":", "if", "(", "filename", ".", "endswith", "(", "suffix"...
https://github.com/pgRouting/osm2pgrouting/blob/8491929fc4037d308f271e84d59bb96da3c28aa2/tools/cpplint.py#L4499-L4523
stan-dev/math
5fd79f89933269a4ca4d8dd1fde2a36d53d4768c
runChecks.py
python
files_in_folder
(folder)
return files
Returns a list of files in the folder and all its subfolders recursively. The folder can be written with wildcards as with the Unix find command.
Returns a list of files in the folder and all its subfolders recursively. The folder can be written with wildcards as with the Unix find command.
[ "Returns", "a", "list", "of", "files", "in", "the", "folder", "and", "all", "its", "subfolders", "recursively", ".", "The", "folder", "can", "be", "written", "with", "wildcards", "as", "with", "the", "Unix", "find", "command", "." ]
def files_in_folder(folder): """Returns a list of files in the folder and all its subfolders recursively. The folder can be written with wildcards as with the Unix find command. """ files = [] for f in glob.glob(folder): if os.path.isdir(f): files.extend(files_in_folder(f + os.sep + "**")) else: files.append(f) return files
[ "def", "files_in_folder", "(", "folder", ")", ":", "files", "=", "[", "]", "for", "f", "in", "glob", ".", "glob", "(", "folder", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "f", ")", ":", "files", ".", "extend", "(", "files_in_folder", ...
https://github.com/stan-dev/math/blob/5fd79f89933269a4ca4d8dd1fde2a36d53d4768c/runChecks.py#L20-L31
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/perspective.py
python
PerspectiveManager.GetPerspectiveList
(self)
return sorted(self._viewset.keys())
Returns a list of all the loaded perspectives. The returned list only provides the names of the perspectives and not the actual data. @return: list of all managed perspectives
Returns a list of all the loaded perspectives. The returned list only provides the names of the perspectives and not the actual data. @return: list of all managed perspectives
[ "Returns", "a", "list", "of", "all", "the", "loaded", "perspectives", ".", "The", "returned", "list", "only", "provides", "the", "names", "of", "the", "perspectives", "and", "not", "the", "actual", "data", ".", "@return", ":", "list", "of", "all", "managed...
def GetPerspectiveList(self): """Returns a list of all the loaded perspectives. The returned list only provides the names of the perspectives and not the actual data. @return: list of all managed perspectives """ return sorted(self._viewset.keys())
[ "def", "GetPerspectiveList", "(", "self", ")", ":", "return", "sorted", "(", "self", ".", "_viewset", ".", "keys", "(", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/perspective.py#L186-L193
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/richtext.py
python
RichTextBuffer.BeginURL
(*args, **kwargs)
return _richtext.RichTextBuffer_BeginURL(*args, **kwargs)
BeginURL(self, String url, String characterStyle=wxEmptyString) -> bool
BeginURL(self, String url, String characterStyle=wxEmptyString) -> bool
[ "BeginURL", "(", "self", "String", "url", "String", "characterStyle", "=", "wxEmptyString", ")", "-", ">", "bool" ]
def BeginURL(*args, **kwargs): """BeginURL(self, String url, String characterStyle=wxEmptyString) -> bool""" return _richtext.RichTextBuffer_BeginURL(*args, **kwargs)
[ "def", "BeginURL", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextBuffer_BeginURL", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L2475-L2477
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/ImageStat.py
python
Stat._getstddev
(self)
return v
Get standard deviation for each layer
Get standard deviation for each layer
[ "Get", "standard", "deviation", "for", "each", "layer" ]
def _getstddev(self): """Get standard deviation for each layer""" v = [] for i in self.bands: v.append(math.sqrt(self.var[i])) return v
[ "def", "_getstddev", "(", "self", ")", ":", "v", "=", "[", "]", "for", "i", "in", "self", ".", "bands", ":", "v", ".", "append", "(", "math", ".", "sqrt", "(", "self", ".", "var", "[", "i", "]", ")", ")", "return", "v" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/ImageStat.py#L138-L144
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/coremodules/demand/detectorflows_wxgui.py
python
DetectorflowsWxGuiMixin.on_clear_flows
(self, event=None)
Clear all detectors and slows.
Clear all detectors and slows.
[ "Clear", "all", "detectors", "and", "slows", "." ]
def on_clear_flows(self, event=None): """Clear all detectors and slows. """ self._demand.detectorflows.flowmeasurements.clear() self._mainframe.browse_obj(self._demand.detectorflows)
[ "def", "on_clear_flows", "(", "self", ",", "event", "=", "None", ")", ":", "self", ".", "_demand", ".", "detectorflows", ".", "flowmeasurements", ".", "clear", "(", ")", "self", ".", "_mainframe", ".", "browse_obj", "(", "self", ".", "_demand", ".", "det...
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/coremodules/demand/detectorflows_wxgui.py#L146-L150
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/_osx_support.py
python
_override_all_archs
(_config_vars)
return _config_vars
Allow override of all archs with ARCHFLAGS env var
Allow override of all archs with ARCHFLAGS env var
[ "Allow", "override", "of", "all", "archs", "with", "ARCHFLAGS", "env", "var" ]
def _override_all_archs(_config_vars): """Allow override of all archs with ARCHFLAGS env var""" # NOTE: This name was introduced by Apple in OSX 10.5 and # is used by several scripting languages distributed with # that OS release. if 'ARCHFLAGS' in os.environ: arch = os.environ['ARCHFLAGS'] for cv in _UNIVERSAL_CONFIG_VARS: if cv in _config_vars and '-arch' in _config_vars[cv]: flags = _config_vars[cv] flags = re.sub(r'-arch\s+\w+\s', ' ', flags) flags = flags + ' ' + arch _save_modified_value(_config_vars, cv, flags) return _config_vars
[ "def", "_override_all_archs", "(", "_config_vars", ")", ":", "# NOTE: This name was introduced by Apple in OSX 10.5 and", "# is used by several scripting languages distributed with", "# that OS release.", "if", "'ARCHFLAGS'", "in", "os", ".", "environ", ":", "arch", "=", "os", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/_osx_support.py#L314-L328
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/protobuf/py2/google/protobuf/internal/python_message.py
python
_AddPropertiesForRepeatedField
(field, cls)
Adds a public property for a "repeated" protocol message field. Clients can use this property to get the value of the field, which will be either a RepeatedScalarFieldContainer or RepeatedCompositeFieldContainer (see below). Note that when clients add values to these containers, we perform type-checking in the case of repeated scalar fields, and we also set any necessary "has" bits as a side-effect. Args: field: A FieldDescriptor for this field. cls: The class we're constructing.
Adds a public property for a "repeated" protocol message field. Clients can use this property to get the value of the field, which will be either a RepeatedScalarFieldContainer or RepeatedCompositeFieldContainer (see below).
[ "Adds", "a", "public", "property", "for", "a", "repeated", "protocol", "message", "field", ".", "Clients", "can", "use", "this", "property", "to", "get", "the", "value", "of", "the", "field", "which", "will", "be", "either", "a", "RepeatedScalarFieldContainer"...
def _AddPropertiesForRepeatedField(field, cls): """Adds a public property for a "repeated" protocol message field. Clients can use this property to get the value of the field, which will be either a RepeatedScalarFieldContainer or RepeatedCompositeFieldContainer (see below). Note that when clients add values to these containers, we perform type-checking in the case of repeated scalar fields, and we also set any necessary "has" bits as a side-effect. Args: field: A FieldDescriptor for this field. cls: The class we're constructing. """ proto_field_name = field.name property_name = _PropertyName(proto_field_name) def getter(self): field_value = self._fields.get(field) if field_value is None: # Construct a new object to represent this field. field_value = field._default_constructor(self) # Atomically check if another thread has preempted us and, if not, swap # in the new object we just created. If someone has preempted us, we # take that object and discard ours. # WARNING: We are relying on setdefault() being atomic. This is true # in CPython but we haven't investigated others. This warning appears # in several other locations in this file. field_value = self._fields.setdefault(field, field_value) return field_value getter.__module__ = None getter.__doc__ = 'Getter for %s.' % proto_field_name # We define a setter just so we can throw an exception with a more # helpful error message. def setter(self, new_value): raise AttributeError('Assignment not allowed to repeated field ' '"%s" in protocol message object.' % proto_field_name) doc = 'Magic attribute generated for "%s" proto field.' % proto_field_name setattr(cls, property_name, _FieldProperty(field, getter, setter, doc=doc))
[ "def", "_AddPropertiesForRepeatedField", "(", "field", ",", "cls", ")", ":", "proto_field_name", "=", "field", ".", "name", "property_name", "=", "_PropertyName", "(", "proto_field_name", ")", "def", "getter", "(", "self", ")", ":", "field_value", "=", "self", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py2/google/protobuf/internal/python_message.py#L638-L679
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
python/mooseutils/gitutils.py
python
git_init_submodule
(path, working_dir=os.getcwd())
Check if given path is a submodule and initialize it (unless it already has been) if so.
Check if given path is a submodule and initialize it (unless it already has been) if so.
[ "Check", "if", "given", "path", "is", "a", "submodule", "and", "initialize", "it", "(", "unless", "it", "already", "has", "been", ")", "if", "so", "." ]
def git_init_submodule(path, working_dir=os.getcwd()): """ Check if given path is a submodule and initialize it (unless it already has been) if so. """ status = git_submodule_info(working_dir) for submodule, status in status.items(): if (submodule == path) and ((status[0] == '-') or ('(null)' in status[2])): subprocess.call(['git', 'submodule', 'update', '--init', path], cwd=working_dir) break
[ "def", "git_init_submodule", "(", "path", ",", "working_dir", "=", "os", ".", "getcwd", "(", ")", ")", ":", "status", "=", "git_submodule_info", "(", "working_dir", ")", "for", "submodule", ",", "status", "in", "status", ".", "items", "(", ")", ":", "if"...
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/mooseutils/gitutils.py#L105-L113
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_misc.py
python
ConfigBase.GetStyle
(*args, **kwargs)
return _misc_.ConfigBase_GetStyle(*args, **kwargs)
GetStyle(self) -> long
GetStyle(self) -> long
[ "GetStyle", "(", "self", ")", "-", ">", "long" ]
def GetStyle(*args, **kwargs): """GetStyle(self) -> long""" return _misc_.ConfigBase_GetStyle(*args, **kwargs)
[ "def", "GetStyle", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "ConfigBase_GetStyle", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L3433-L3435
citizenfx/fivem
88276d40cc7baf8285d02754cc5ae42ec7a8563f
vendor/chromium/base/win/embedded_i18n/create_string_rc.py
python
GrdHandler.__IsExtractingMessage
(self)
return self.__message_name is not None
Returns True if a message is currently being extracted.
Returns True if a message is currently being extracted.
[ "Returns", "True", "if", "a", "message", "is", "currently", "being", "extracted", "." ]
def __IsExtractingMessage(self): """Returns True if a message is currently being extracted.""" return self.__message_name is not None
[ "def", "__IsExtractingMessage", "(", "self", ")", ":", "return", "self", ".", "__message_name", "is", "not", "None" ]
https://github.com/citizenfx/fivem/blob/88276d40cc7baf8285d02754cc5ae42ec7a8563f/vendor/chromium/base/win/embedded_i18n/create_string_rc.py#L121-L123
SeisSol/SeisSol
955fbeb8c5d40d3363a2da0edc611259aebe1653
generated_code/memlayout.py
python
findCandidates
(search_path)
return candidates
Determine Candidate attributes from file name.
Determine Candidate attributes from file name.
[ "Determine", "Candidate", "attributes", "from", "file", "name", "." ]
def findCandidates(search_path): """Determine Candidate attributes from file name.""" archs = arch.getArchitectures() pes = [arch.getCpu(a) for a in archs] candidates = dict() for c in os.listdir(search_path): name, ext = os.path.splitext(c) atts = dict() for att in name.split('_'): multipleSimulations = re.match('ms([0-9]+)', att) order = re.match('O([0-9]+)', att) if multipleSimulations: atts['multipleSimulations'] = int(multipleSimulations.group(1)) elif order: atts['order'] = int(order.group(1)) elif att.lower() in ['s', 'd']: atts['precision'] = att.lower() elif att.lower() in pes: atts['pe'] = att.lower() else: atts['equations'] = att candidates[c] = Candidate(atts) return candidates
[ "def", "findCandidates", "(", "search_path", ")", ":", "archs", "=", "arch", ".", "getArchitectures", "(", ")", "pes", "=", "[", "arch", ".", "getCpu", "(", "a", ")", "for", "a", "in", "archs", "]", "candidates", "=", "dict", "(", ")", "for", "c", ...
https://github.com/SeisSol/SeisSol/blob/955fbeb8c5d40d3363a2da0edc611259aebe1653/generated_code/memlayout.py#L72-L96
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/devil/devil/android/device_utils.py
python
DeviceUtils.GetApplicationDataDirectory
(self, package, timeout=None, retries=None)
return None
Get the data directory on the device for the given package. Args: package: Name of the package. Returns: The package's data directory, or None if the package doesn't exist on the device.
Get the data directory on the device for the given package.
[ "Get", "the", "data", "directory", "on", "the", "device", "for", "the", "given", "package", "." ]
def GetApplicationDataDirectory(self, package, timeout=None, retries=None): """Get the data directory on the device for the given package. Args: package: Name of the package. Returns: The package's data directory, or None if the package doesn't exist on the device. """ try: output = self._RunPipedShellCommand( 'pm dump %s | grep dataDir=' % cmd_helper.SingleQuote(package)) for line in output: _, _, dataDir = line.partition('dataDir=') if dataDir: return dataDir except device_errors.CommandFailedError: logging.exception('Could not find data directory for %s', package) return None
[ "def", "GetApplicationDataDirectory", "(", "self", ",", "package", ",", "timeout", "=", "None", ",", "retries", "=", "None", ")", ":", "try", ":", "output", "=", "self", ".", "_RunPipedShellCommand", "(", "'pm dump %s | grep dataDir='", "%", "cmd_helper", ".", ...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/devil/devil/android/device_utils.py#L521-L540
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/tools/inspector_protocol/jinja2/idtracking.py
python
FrameSymbolVisitor.visit_Scope
(self, node, **kwargs)
Stop visiting at scopes.
Stop visiting at scopes.
[ "Stop", "visiting", "at", "scopes", "." ]
def visit_Scope(self, node, **kwargs): """Stop visiting at scopes."""
[ "def", "visit_Scope", "(", "self", ",", "node", ",", "*", "*", "kwargs", ")", ":" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/inspector_protocol/jinja2/idtracking.py#L279-L280
google/mysql-protobuf
467cda676afaa49e762c5c9164a43f6ad31a1fbf
protobuf/python/mox.py
python
MockMethod._PopNextMethod
(self)
Pop the next method from our call queue.
Pop the next method from our call queue.
[ "Pop", "the", "next", "method", "from", "our", "call", "queue", "." ]
def _PopNextMethod(self): """Pop the next method from our call queue.""" try: return self._call_queue.popleft() except IndexError: raise UnexpectedMethodCallError(self, None)
[ "def", "_PopNextMethod", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_call_queue", ".", "popleft", "(", ")", "except", "IndexError", ":", "raise", "UnexpectedMethodCallError", "(", "self", ",", "None", ")" ]
https://github.com/google/mysql-protobuf/blob/467cda676afaa49e762c5c9164a43f6ad31a1fbf/protobuf/python/mox.py#L581-L586
calamares/calamares
9f6f82405b3074af7c99dc26487d2e46e4ece3e5
src/modules/packages/main.py
python
PackageManager.remove
(self, pkgs)
Removes packages. @param pkgs: list[str] list of package names
Removes packages.
[ "Removes", "packages", "." ]
def remove(self, pkgs): """ Removes packages. @param pkgs: list[str] list of package names """ pass
[ "def", "remove", "(", "self", ",", "pkgs", ")", ":", "pass" ]
https://github.com/calamares/calamares/blob/9f6f82405b3074af7c99dc26487d2e46e4ece3e5/src/modules/packages/main.py#L109-L116
ucbrise/clipper
9f25e3fc7f8edc891615e81c5b80d3d8aed72608
clipper_admin/clipper_admin/container_manager.py
python
ContainerManager.stop_all
(self, graceful=True)
Stop all resources associated with Clipper. Parameters ---------- graceful : bool If set to True, Clipper will try to shutdown all containers gracefully. This option will only work in Docker (Using Docker stop instead of kill).
Stop all resources associated with Clipper.
[ "Stop", "all", "resources", "associated", "with", "Clipper", "." ]
def stop_all(self, graceful=True): """Stop all resources associated with Clipper. Parameters ---------- graceful : bool If set to True, Clipper will try to shutdown all containers gracefully. This option will only work in Docker (Using Docker stop instead of kill). """ pass
[ "def", "stop_all", "(", "self", ",", "graceful", "=", "True", ")", ":", "pass" ]
https://github.com/ucbrise/clipper/blob/9f25e3fc7f8edc891615e81c5b80d3d8aed72608/clipper_admin/clipper_admin/container_manager.py#L136-L145
psi4/psi4
be533f7f426b6ccc263904e55122899b16663395
psi4/driver/qcdb/libmintsgshell.py
python
ShellInfo.amchar
(self)
return 'spdfghiklmnopqrtuvwxyz'[self.l]
Return the character symbol for the angular momentum of the given contraction
Return the character symbol for the angular momentum of the given contraction
[ "Return", "the", "character", "symbol", "for", "the", "angular", "momentum", "of", "the", "given", "contraction" ]
def amchar(self): """Return the character symbol for the angular momentum of the given contraction""" return 'spdfghiklmnopqrtuvwxyz'[self.l]
[ "def", "amchar", "(", "self", ")", ":", "return", "'spdfghiklmnopqrtuvwxyz'", "[", "self", ".", "l", "]" ]
https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/qcdb/libmintsgshell.py#L282-L284
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/xml/sax/xmlreader.py
python
XMLReader.setContentHandler
(self, handler)
Registers a new object to receive document content events.
Registers a new object to receive document content events.
[ "Registers", "a", "new", "object", "to", "receive", "document", "content", "events", "." ]
def setContentHandler(self, handler): "Registers a new object to receive document content events." self._cont_handler = handler
[ "def", "setContentHandler", "(", "self", ",", "handler", ")", ":", "self", ".", "_cont_handler", "=", "handler" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/xml/sax/xmlreader.py#L38-L40
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
WindowDestroyEvent.__init__
(self, *args, **kwargs)
__init__(self, Window win=None) -> WindowDestroyEvent The EVT_WINDOW_DESTROY event is sent from the `wx.Window` destructor when the GUI window is destroyed. When a class derived from `wx.Window` is destroyed its destructor will have already run by the time this event is sent. Therefore this event will not usually be received at all by the window itself. Since it is received after the destructor has run, an object should not try to handle its own wx.WindowDestroyEvent, but it can be used to get notification of the destruction of another window.
__init__(self, Window win=None) -> WindowDestroyEvent
[ "__init__", "(", "self", "Window", "win", "=", "None", ")", "-", ">", "WindowDestroyEvent" ]
def __init__(self, *args, **kwargs): """ __init__(self, Window win=None) -> WindowDestroyEvent The EVT_WINDOW_DESTROY event is sent from the `wx.Window` destructor when the GUI window is destroyed. When a class derived from `wx.Window` is destroyed its destructor will have already run by the time this event is sent. Therefore this event will not usually be received at all by the window itself. Since it is received after the destructor has run, an object should not try to handle its own wx.WindowDestroyEvent, but it can be used to get notification of the destruction of another window. """ _core_.WindowDestroyEvent_swiginit(self,_core_.new_WindowDestroyEvent(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_core_", ".", "WindowDestroyEvent_swiginit", "(", "self", ",", "_core_", ".", "new_WindowDestroyEvent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L7365-L7379
0ad/0ad
f58db82e0e925016d83f4e3fa7ca599e3866e2af
source/tools/lobbybots/xpartamupp/echelon.py
python
Leaderboard.get_rating_messages
(self)
return self.rating_messages
Get messages announcing rated games. Returns: list with the a messages about rated games
Get messages announcing rated games.
[ "Get", "messages", "announcing", "rated", "games", "." ]
def get_rating_messages(self): """Get messages announcing rated games. Returns: list with the a messages about rated games """ return self.rating_messages
[ "def", "get_rating_messages", "(", "self", ")", ":", "return", "self", ".", "rating_messages" ]
https://github.com/0ad/0ad/blob/f58db82e0e925016d83f4e3fa7ca599e3866e2af/source/tools/lobbybots/xpartamupp/echelon.py#L267-L274
opencv/opencv
76aff8478883858f0e46746044348ebb16dc3c67
doc/pattern_tools/svgfig.py
python
Ellipse.SVG
(self, trans=None)
return self.Path(trans).SVG()
Apply the transformation "trans" and return an SVG object.
Apply the transformation "trans" and return an SVG object.
[ "Apply", "the", "transformation", "trans", "and", "return", "an", "SVG", "object", "." ]
def SVG(self, trans=None): """Apply the transformation "trans" and return an SVG object.""" return self.Path(trans).SVG()
[ "def", "SVG", "(", "self", ",", "trans", "=", "None", ")", ":", "return", "self", ".", "Path", "(", "trans", ")", ".", "SVG", "(", ")" ]
https://github.com/opencv/opencv/blob/76aff8478883858f0e46746044348ebb16dc3c67/doc/pattern_tools/svgfig.py#L2494-L2496
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/cgi.py
python
FieldStorage.make_file
(self, binary=None)
return tempfile.TemporaryFile("w+b")
Overridable: return a readable & writable file. The file will be used as follows: - data is written to it - seek(0) - data is read from it The 'binary' argument is unused -- the file is always opened in binary mode. This version opens a temporary file for reading and writing, and immediately deletes (unlinks) it. The trick (on Unix!) is that the file can still be used, but it can't be opened by another process, and it will automatically be deleted when it is closed or when the current process terminates. If you want a more permanent file, you derive a class which overrides this method. If you want a visible temporary file that is nevertheless automatically deleted when the script terminates, try defining a __del__ method in a derived class which unlinks the temporary files you have created.
Overridable: return a readable & writable file.
[ "Overridable", ":", "return", "a", "readable", "&", "writable", "file", "." ]
def make_file(self, binary=None): """Overridable: return a readable & writable file. The file will be used as follows: - data is written to it - seek(0) - data is read from it The 'binary' argument is unused -- the file is always opened in binary mode. This version opens a temporary file for reading and writing, and immediately deletes (unlinks) it. The trick (on Unix!) is that the file can still be used, but it can't be opened by another process, and it will automatically be deleted when it is closed or when the current process terminates. If you want a more permanent file, you derive a class which overrides this method. If you want a visible temporary file that is nevertheless automatically deleted when the script terminates, try defining a __del__ method in a derived class which unlinks the temporary files you have created. """ import tempfile return tempfile.TemporaryFile("w+b")
[ "def", "make_file", "(", "self", ",", "binary", "=", "None", ")", ":", "import", "tempfile", "return", "tempfile", ".", "TemporaryFile", "(", "\"w+b\"", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/cgi.py#L742-L767
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/arrayterator.py
python
Arrayterator.shape
(self)
return tuple(((stop-start-1)//step+1) for start, stop, step in zip(self.start, self.stop, self.step))
The shape of the array to be iterated over. For an example, see `Arrayterator`.
The shape of the array to be iterated over.
[ "The", "shape", "of", "the", "array", "to", "be", "iterated", "over", "." ]
def shape(self): """ The shape of the array to be iterated over. For an example, see `Arrayterator`. """ return tuple(((stop-start-1)//step+1) for start, stop, step in zip(self.start, self.stop, self.step))
[ "def", "shape", "(", "self", ")", ":", "return", "tuple", "(", "(", "(", "stop", "-", "start", "-", "1", ")", "//", "step", "+", "1", ")", "for", "start", ",", "stop", ",", "step", "in", "zip", "(", "self", ".", "start", ",", "self", ".", "st...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/arrayterator.py#L170-L178
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/io/excel/_util.py
python
combine_kwargs
(engine_kwargs: dict[str, Any] | None, kwargs: dict)
return result
Used to combine two sources of kwargs for the backend engine. Use of kwargs is deprecated, this function is solely for use in 1.3 and should be removed in 1.4/2.0. Also _base.ExcelWriter.__new__ ensures either engine_kwargs or kwargs must be None or empty respectively. Parameters ---------- engine_kwargs: dict kwargs to be passed through to the engine. kwargs: dict kwargs to be psased through to the engine (deprecated) Returns ------- engine_kwargs combined with kwargs
Used to combine two sources of kwargs for the backend engine.
[ "Used", "to", "combine", "two", "sources", "of", "kwargs", "for", "the", "backend", "engine", "." ]
def combine_kwargs(engine_kwargs: dict[str, Any] | None, kwargs: dict) -> dict: """ Used to combine two sources of kwargs for the backend engine. Use of kwargs is deprecated, this function is solely for use in 1.3 and should be removed in 1.4/2.0. Also _base.ExcelWriter.__new__ ensures either engine_kwargs or kwargs must be None or empty respectively. Parameters ---------- engine_kwargs: dict kwargs to be passed through to the engine. kwargs: dict kwargs to be psased through to the engine (deprecated) Returns ------- engine_kwargs combined with kwargs """ if engine_kwargs is None: result = {} else: result = engine_kwargs.copy() result.update(kwargs) return result
[ "def", "combine_kwargs", "(", "engine_kwargs", ":", "dict", "[", "str", ",", "Any", "]", "|", "None", ",", "kwargs", ":", "dict", ")", "->", "dict", ":", "if", "engine_kwargs", "is", "None", ":", "result", "=", "{", "}", "else", ":", "result", "=", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/io/excel/_util.py#L254-L278
perilouswithadollarsign/cstrike15_src
f82112a2388b841d72cb62ca48ab1846dfcc11c8
thirdparty/protobuf-2.5.0/python/google/protobuf/internal/wire_format.py
python
UnpackTag
(tag)
return (tag >> TAG_TYPE_BITS), (tag & TAG_TYPE_MASK)
The inverse of PackTag(). Given an unsigned 32-bit number, returns a (field_number, wire_type) tuple.
The inverse of PackTag(). Given an unsigned 32-bit number, returns a (field_number, wire_type) tuple.
[ "The", "inverse", "of", "PackTag", "()", ".", "Given", "an", "unsigned", "32", "-", "bit", "number", "returns", "a", "(", "field_number", "wire_type", ")", "tuple", "." ]
def UnpackTag(tag): """The inverse of PackTag(). Given an unsigned 32-bit number, returns a (field_number, wire_type) tuple. """ return (tag >> TAG_TYPE_BITS), (tag & TAG_TYPE_MASK)
[ "def", "UnpackTag", "(", "tag", ")", ":", "return", "(", "tag", ">>", "TAG_TYPE_BITS", ")", ",", "(", "tag", "&", "TAG_TYPE_MASK", ")" ]
https://github.com/perilouswithadollarsign/cstrike15_src/blob/f82112a2388b841d72cb62ca48ab1846dfcc11c8/thirdparty/protobuf-2.5.0/python/google/protobuf/internal/wire_format.py#L93-L97
arangodb/arangodb
0d658689c7d1b721b314fa3ca27d38303e1570c8
3rdParty/V8/v7.9.317/tools/sanitizers/sancov_merger.py
python
merge
(args)
return executable, result_file_name
Merge several sancov files into one. Called trough multiprocessing pool. The args are expected to unpack to: keep: Option if source and intermediate sancov files should be kept. coverage_dir: Folder where to find the sancov files. executable: Name of the executable whose sancov files should be merged. index: A number to be put into the intermediate result file name. If None, this is a final result. bucket: The list of sancov files to be merged. Returns: A tuple with the executable name and the result file name.
Merge several sancov files into one.
[ "Merge", "several", "sancov", "files", "into", "one", "." ]
def merge(args): """Merge several sancov files into one. Called trough multiprocessing pool. The args are expected to unpack to: keep: Option if source and intermediate sancov files should be kept. coverage_dir: Folder where to find the sancov files. executable: Name of the executable whose sancov files should be merged. index: A number to be put into the intermediate result file name. If None, this is a final result. bucket: The list of sancov files to be merged. Returns: A tuple with the executable name and the result file name. """ keep, coverage_dir, executable, index, bucket = args process = subprocess.Popen( [SANCOV_TOOL, 'merge'] + bucket, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=coverage_dir, ) output, _ = process.communicate() assert process.returncode == 0 if index is not None: # This is an intermediate result, add the bucket index to the file name. result_file_name = '%s.result.%d.sancov' % (executable, index) else: # This is the final result without bucket index. result_file_name = '%s.result.sancov' % executable with open(os.path.join(coverage_dir, result_file_name), "wb") as f: f.write(output) if not keep: for f in bucket: os.remove(os.path.join(coverage_dir, f)) return executable, result_file_name
[ "def", "merge", "(", "args", ")", ":", "keep", ",", "coverage_dir", ",", "executable", ",", "index", ",", "bucket", "=", "args", "process", "=", "subprocess", ".", "Popen", "(", "[", "SANCOV_TOOL", ",", "'merge'", "]", "+", "bucket", ",", "stdout", "="...
https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/v7.9.317/tools/sanitizers/sancov_merger.py#L57-L89
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/datetime.py
python
date.isoweekday
(self)
return self.toordinal() % 7 or 7
Return day of the week, where Monday == 1 ... Sunday == 7.
Return day of the week, where Monday == 1 ... Sunday == 7.
[ "Return", "day", "of", "the", "week", "where", "Monday", "==", "1", "...", "Sunday", "==", "7", "." ]
def isoweekday(self): "Return day of the week, where Monday == 1 ... Sunday == 7." # 1-Jan-0001 is a Monday return self.toordinal() % 7 or 7
[ "def", "isoweekday", "(", "self", ")", ":", "# 1-Jan-0001 is a Monday", "return", "self", ".", "toordinal", "(", ")", "%", "7", "or", "7" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/datetime.py#L1092-L1095
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/psutil/_pslinux.py
python
cpu_stats
()
return _common.scpustats( ctx_switches, interrupts, soft_interrupts, syscalls)
Return various CPU stats as a named tuple.
Return various CPU stats as a named tuple.
[ "Return", "various", "CPU", "stats", "as", "a", "named", "tuple", "." ]
def cpu_stats(): """Return various CPU stats as a named tuple.""" with open_binary('%s/stat' % get_procfs_path()) as f: ctx_switches = None interrupts = None soft_interrupts = None for line in f: if line.startswith(b'ctxt'): ctx_switches = int(line.split()[1]) elif line.startswith(b'intr'): interrupts = int(line.split()[1]) elif line.startswith(b'softirq'): soft_interrupts = int(line.split()[1]) if ctx_switches is not None and soft_interrupts is not None \ and interrupts is not None: break syscalls = 0 return _common.scpustats( ctx_switches, interrupts, soft_interrupts, syscalls)
[ "def", "cpu_stats", "(", ")", ":", "with", "open_binary", "(", "'%s/stat'", "%", "get_procfs_path", "(", ")", ")", "as", "f", ":", "ctx_switches", "=", "None", "interrupts", "=", "None", "soft_interrupts", "=", "None", "for", "line", "in", "f", ":", "if"...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/psutil/_pslinux.py#L655-L673
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
docs/scripts/doxy_md_filter.py
python
DoxyMDFilter.get_parent_folder
(self)
return self.md_file.parents[0]
Get parent folder of a markdown file
Get parent folder of a markdown file
[ "Get", "parent", "folder", "of", "a", "markdown", "file" ]
def get_parent_folder(self): """ Get parent folder of a markdown file """ return self.md_file.parents[0]
[ "def", "get_parent_folder", "(", "self", ")", ":", "return", "self", ".", "md_file", ".", "parents", "[", "0", "]" ]
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/docs/scripts/doxy_md_filter.py#L39-L43
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/functools.py
python
_le_from_gt
(self, other, NotImplemented=NotImplemented)
return not op_result
Return a <= b. Computed by @total_ordering from (not a > b).
Return a <= b. Computed by
[ "Return", "a", "<", "=", "b", ".", "Computed", "by" ]
def _le_from_gt(self, other, NotImplemented=NotImplemented): 'Return a <= b. Computed by @total_ordering from (not a > b).' op_result = self.__gt__(other) if op_result is NotImplemented: return op_result return not op_result
[ "def", "_le_from_gt", "(", "self", ",", "other", ",", "NotImplemented", "=", "NotImplemented", ")", ":", "op_result", "=", "self", ".", "__gt__", "(", "other", ")", "if", "op_result", "is", "NotImplemented", ":", "return", "op_result", "return", "not", "op_r...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/functools.py#L143-L148
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/plotting/_core.py
python
hist_frame
( data: DataFrame, column: IndexLabel = None, by=None, grid: bool = True, xlabelsize: int | None = None, xrot: float | None = None, ylabelsize: int | None = None, yrot: float | None = None, ax=None, sharex: bool = False, sharey: bool = False, figsize: tuple[int, int] | None = None, layout: tuple[int, int] | None = None, bins: int | Sequence[int] = 10, backend: str | None = None, legend: bool = False, **kwargs, )
return plot_backend.hist_frame( data, column=column, by=by, grid=grid, xlabelsize=xlabelsize, xrot=xrot, ylabelsize=ylabelsize, yrot=yrot, ax=ax, sharex=sharex, sharey=sharey, figsize=figsize, layout=layout, legend=legend, bins=bins, **kwargs, )
Make a histogram of the DataFrame's columns. A `histogram`_ is a representation of the distribution of data. This function calls :meth:`matplotlib.pyplot.hist`, on each series in the DataFrame, resulting in one histogram per column. .. _histogram: https://en.wikipedia.org/wiki/Histogram Parameters ---------- data : DataFrame The pandas object holding the data. column : str or sequence, optional If passed, will be used to limit data to a subset of columns. by : object, optional If passed, then used to form histograms for separate groups. grid : bool, default True Whether to show axis grid lines. xlabelsize : int, default None If specified changes the x-axis label size. xrot : float, default None Rotation of x axis labels. For example, a value of 90 displays the x labels rotated 90 degrees clockwise. ylabelsize : int, default None If specified changes the y-axis label size. yrot : float, default None Rotation of y axis labels. For example, a value of 90 displays the y labels rotated 90 degrees clockwise. ax : Matplotlib axes object, default None The axes to plot the histogram on. sharex : bool, default True if ax is None else False In case subplots=True, share x axis and set some x axis labels to invisible; defaults to True if ax is None otherwise False if an ax is passed in. Note that passing in both an ax and sharex=True will alter all x axis labels for all subplots in a figure. sharey : bool, default False In case subplots=True, share y axis and set some y axis labels to invisible. figsize : tuple, optional The size in inches of the figure to create. Uses the value in `matplotlib.rcParams` by default. layout : tuple, optional Tuple of (rows, columns) for the layout of the histograms. bins : int or sequence, default 10 Number of histogram bins to be used. If an integer is given, bins + 1 bin edges are calculated and returned. If bins is a sequence, gives bin edges, including left edge of first bin and right edge of last bin. In this case, bins is returned unmodified. backend : str, default None Backend to use instead of the backend specified in the option ``plotting.backend``. For instance, 'matplotlib'. Alternatively, to specify the ``plotting.backend`` for the whole session, set ``pd.options.plotting.backend``. .. versionadded:: 1.0.0 legend : bool, default False Whether to show the legend. .. versionadded:: 1.1.0 **kwargs All other plotting keyword arguments to be passed to :meth:`matplotlib.pyplot.hist`. Returns ------- matplotlib.AxesSubplot or numpy.ndarray of them See Also -------- matplotlib.pyplot.hist : Plot a histogram using matplotlib. Examples -------- This example draws a histogram based on the length and width of some animals, displayed in three bins .. plot:: :context: close-figs >>> df = pd.DataFrame({ ... 'length': [1.5, 0.5, 1.2, 0.9, 3], ... 'width': [0.7, 0.2, 0.15, 0.2, 1.1] ... }, index=['pig', 'rabbit', 'duck', 'chicken', 'horse']) >>> hist = df.hist(bins=3)
Make a histogram of the DataFrame's columns.
[ "Make", "a", "histogram", "of", "the", "DataFrame", "s", "columns", "." ]
def hist_frame( data: DataFrame, column: IndexLabel = None, by=None, grid: bool = True, xlabelsize: int | None = None, xrot: float | None = None, ylabelsize: int | None = None, yrot: float | None = None, ax=None, sharex: bool = False, sharey: bool = False, figsize: tuple[int, int] | None = None, layout: tuple[int, int] | None = None, bins: int | Sequence[int] = 10, backend: str | None = None, legend: bool = False, **kwargs, ): """ Make a histogram of the DataFrame's columns. A `histogram`_ is a representation of the distribution of data. This function calls :meth:`matplotlib.pyplot.hist`, on each series in the DataFrame, resulting in one histogram per column. .. _histogram: https://en.wikipedia.org/wiki/Histogram Parameters ---------- data : DataFrame The pandas object holding the data. column : str or sequence, optional If passed, will be used to limit data to a subset of columns. by : object, optional If passed, then used to form histograms for separate groups. grid : bool, default True Whether to show axis grid lines. xlabelsize : int, default None If specified changes the x-axis label size. xrot : float, default None Rotation of x axis labels. For example, a value of 90 displays the x labels rotated 90 degrees clockwise. ylabelsize : int, default None If specified changes the y-axis label size. yrot : float, default None Rotation of y axis labels. For example, a value of 90 displays the y labels rotated 90 degrees clockwise. ax : Matplotlib axes object, default None The axes to plot the histogram on. sharex : bool, default True if ax is None else False In case subplots=True, share x axis and set some x axis labels to invisible; defaults to True if ax is None otherwise False if an ax is passed in. Note that passing in both an ax and sharex=True will alter all x axis labels for all subplots in a figure. sharey : bool, default False In case subplots=True, share y axis and set some y axis labels to invisible. figsize : tuple, optional The size in inches of the figure to create. Uses the value in `matplotlib.rcParams` by default. layout : tuple, optional Tuple of (rows, columns) for the layout of the histograms. bins : int or sequence, default 10 Number of histogram bins to be used. If an integer is given, bins + 1 bin edges are calculated and returned. If bins is a sequence, gives bin edges, including left edge of first bin and right edge of last bin. In this case, bins is returned unmodified. backend : str, default None Backend to use instead of the backend specified in the option ``plotting.backend``. For instance, 'matplotlib'. Alternatively, to specify the ``plotting.backend`` for the whole session, set ``pd.options.plotting.backend``. .. versionadded:: 1.0.0 legend : bool, default False Whether to show the legend. .. versionadded:: 1.1.0 **kwargs All other plotting keyword arguments to be passed to :meth:`matplotlib.pyplot.hist`. Returns ------- matplotlib.AxesSubplot or numpy.ndarray of them See Also -------- matplotlib.pyplot.hist : Plot a histogram using matplotlib. Examples -------- This example draws a histogram based on the length and width of some animals, displayed in three bins .. plot:: :context: close-figs >>> df = pd.DataFrame({ ... 'length': [1.5, 0.5, 1.2, 0.9, 3], ... 'width': [0.7, 0.2, 0.15, 0.2, 1.1] ... }, index=['pig', 'rabbit', 'duck', 'chicken', 'horse']) >>> hist = df.hist(bins=3) """ plot_backend = _get_plot_backend(backend) return plot_backend.hist_frame( data, column=column, by=by, grid=grid, xlabelsize=xlabelsize, xrot=xrot, ylabelsize=ylabelsize, yrot=yrot, ax=ax, sharex=sharex, sharey=sharey, figsize=figsize, layout=layout, legend=legend, bins=bins, **kwargs, )
[ "def", "hist_frame", "(", "data", ":", "DataFrame", ",", "column", ":", "IndexLabel", "=", "None", ",", "by", "=", "None", ",", "grid", ":", "bool", "=", "True", ",", "xlabelsize", ":", "int", "|", "None", "=", "None", ",", "xrot", ":", "float", "|...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/plotting/_core.py#L116-L243
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/cudnn_rnn/python/layers/cudnn_rnn.py
python
_CudnnRNN.input_mode
(self)
return self._input_mode
Input mode of first layer. Indicates whether there is a linear projection between the input and the actual computation before the first layer. It can be * 'linear_input': (default) always applies a linear projection of input onto RNN hidden state. (standard RNN behavior) * 'skip_input': 'skip_input' is only allowed when input_size == num_units. * 'auto_select'. implies 'skip_input' when input_size == num_units; otherwise, it implies 'linear_input'. Returns: 'linear_input', 'skip_input' or 'auto_select'.
Input mode of first layer.
[ "Input", "mode", "of", "first", "layer", "." ]
def input_mode(self): """Input mode of first layer. Indicates whether there is a linear projection between the input and the actual computation before the first layer. It can be * 'linear_input': (default) always applies a linear projection of input onto RNN hidden state. (standard RNN behavior) * 'skip_input': 'skip_input' is only allowed when input_size == num_units. * 'auto_select'. implies 'skip_input' when input_size == num_units; otherwise, it implies 'linear_input'. Returns: 'linear_input', 'skip_input' or 'auto_select'. """ return self._input_mode
[ "def", "input_mode", "(", "self", ")", ":", "return", "self", ".", "_input_mode" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/cudnn_rnn/python/layers/cudnn_rnn.py#L230-L244
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/stc.py
python
StyledTextEvent.SetLParam
(*args, **kwargs)
return _stc.StyledTextEvent_SetLParam(*args, **kwargs)
SetLParam(self, int val)
SetLParam(self, int val)
[ "SetLParam", "(", "self", "int", "val", ")" ]
def SetLParam(*args, **kwargs): """SetLParam(self, int val)""" return _stc.StyledTextEvent_SetLParam(*args, **kwargs)
[ "def", "SetLParam", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextEvent_SetLParam", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L7078-L7080
fmtlib/fmt
ecd6022c24e4fed94e1ea09029c386f36da4a2b8
support/docopt.py
python
transform
(pattern)
return Either(*[Required(*e) for e in result])
Expand pattern into an (almost) equivalent one, but with single Either. Example: ((-a | -b) (-c | -d)) => (-a -c | -a -d | -b -c | -b -d) Quirks: [-a] => (-a), (-a...) => (-a -a)
Expand pattern into an (almost) equivalent one, but with single Either.
[ "Expand", "pattern", "into", "an", "(", "almost", ")", "equivalent", "one", "but", "with", "single", "Either", "." ]
def transform(pattern): """Expand pattern into an (almost) equivalent one, but with single Either. Example: ((-a | -b) (-c | -d)) => (-a -c | -a -d | -b -c | -b -d) Quirks: [-a] => (-a), (-a...) => (-a -a) """ result = [] groups = [[pattern]] while groups: children = groups.pop(0) parents = [Required, Optional, OptionsShortcut, Either, OneOrMore] if any(t in map(type, children) for t in parents): child = [c for c in children if type(c) in parents][0] children.remove(child) if type(child) is Either: for c in child.children: groups.append([c] + children) elif type(child) is OneOrMore: groups.append(child.children * 2 + children) else: groups.append(child.children + children) else: result.append(children) return Either(*[Required(*e) for e in result])
[ "def", "transform", "(", "pattern", ")", ":", "result", "=", "[", "]", "groups", "=", "[", "[", "pattern", "]", "]", "while", "groups", ":", "children", "=", "groups", ".", "pop", "(", "0", ")", "parents", "=", "[", "Required", ",", "Optional", ","...
https://github.com/fmtlib/fmt/blob/ecd6022c24e4fed94e1ea09029c386f36da4a2b8/support/docopt.py#L72-L96
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/imaplib.py
python
IMAP4.delete
(self, mailbox)
return self._simple_command('DELETE', mailbox)
Delete old mailbox. (typ, [data]) = <instance>.delete(mailbox)
Delete old mailbox.
[ "Delete", "old", "mailbox", "." ]
def delete(self, mailbox): """Delete old mailbox. (typ, [data]) = <instance>.delete(mailbox) """ return self._simple_command('DELETE', mailbox)
[ "def", "delete", "(", "self", ",", "mailbox", ")", ":", "return", "self", ".", "_simple_command", "(", "'DELETE'", ",", "mailbox", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/imaplib.py#L483-L488
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TSS_KEY.__init__
(self, publicPart = None, privatePart = None)
Contains the public and private part of a TPM key Attributes: publicPart (TPMT_PUBLIC): Public part of key privatePart (bytes): Private part is the encrypted sensitive part of key
Contains the public and private part of a TPM key
[ "Contains", "the", "public", "and", "private", "part", "of", "a", "TPM", "key" ]
def __init__(self, publicPart = None, privatePart = None): """ Contains the public and private part of a TPM key Attributes: publicPart (TPMT_PUBLIC): Public part of key privatePart (bytes): Private part is the encrypted sensitive part of key """ self.publicPart = publicPart self.privatePart = privatePart
[ "def", "__init__", "(", "self", ",", "publicPart", "=", "None", ",", "privatePart", "=", "None", ")", ":", "self", ".", "publicPart", "=", "publicPart", "self", ".", "privatePart", "=", "privatePart" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L18197-L18206
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/macpath.py
python
split
(s)
return path, file
Split a pathname into two parts: the directory leading up to the final bit, and the basename (the filename, without colons, in that directory). The result (s, t) is such that join(s, t) yields the original argument.
Split a pathname into two parts: the directory leading up to the final bit, and the basename (the filename, without colons, in that directory). The result (s, t) is such that join(s, t) yields the original argument.
[ "Split", "a", "pathname", "into", "two", "parts", ":", "the", "directory", "leading", "up", "to", "the", "final", "bit", "and", "the", "basename", "(", "the", "filename", "without", "colons", "in", "that", "directory", ")", ".", "The", "result", "(", "s"...
def split(s): """Split a pathname into two parts: the directory leading up to the final bit, and the basename (the filename, without colons, in that directory). The result (s, t) is such that join(s, t) yields the original argument.""" if ':' not in s: return '', s colon = 0 for i in range(len(s)): if s[i] == ':': colon = i + 1 path, file = s[:colon-1], s[colon:] if path and not ':' in path: path = path + ':' return path, file
[ "def", "split", "(", "s", ")", ":", "if", "':'", "not", "in", "s", ":", "return", "''", ",", "s", "colon", "=", "0", "for", "i", "in", "range", "(", "len", "(", "s", ")", ")", ":", "if", "s", "[", "i", "]", "==", "':'", ":", "colon", "=",...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/macpath.py#L58-L70
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_controls.py
python
ListEvent.GetKeyCode
(*args, **kwargs)
return _controls_.ListEvent_GetKeyCode(*args, **kwargs)
GetKeyCode(self) -> int
GetKeyCode(self) -> int
[ "GetKeyCode", "(", "self", ")", "-", ">", "int" ]
def GetKeyCode(*args, **kwargs): """GetKeyCode(self) -> int""" return _controls_.ListEvent_GetKeyCode(*args, **kwargs)
[ "def", "GetKeyCode", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ListEvent_GetKeyCode", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L4308-L4310
ValveSoftware/source-sdk-2013
0d8dceea4310fde5706b3ce1c70609d72a38efdf
sp/src/thirdparty/protobuf-2.3.0/python/mox.py
python
MockMethod.MultipleTimes
(self, group_name="default")
return self._CheckAndCreateNewGroup(group_name, MultipleTimesGroup)
Move this method into group of calls which may be called multiple times. A group of repeating calls must be defined together, and must be executed in full before the next expected mehtod can be called. Args: group_name: the name of the unordered group. Returns: self
Move this method into group of calls which may be called multiple times.
[ "Move", "this", "method", "into", "group", "of", "calls", "which", "may", "be", "called", "multiple", "times", "." ]
def MultipleTimes(self, group_name="default"): """Move this method into group of calls which may be called multiple times. A group of repeating calls must be defined together, and must be executed in full before the next expected mehtod can be called. Args: group_name: the name of the unordered group. Returns: self """ return self._CheckAndCreateNewGroup(group_name, MultipleTimesGroup)
[ "def", "MultipleTimes", "(", "self", ",", "group_name", "=", "\"default\"", ")", ":", "return", "self", ".", "_CheckAndCreateNewGroup", "(", "group_name", ",", "MultipleTimesGroup", ")" ]
https://github.com/ValveSoftware/source-sdk-2013/blob/0d8dceea4310fde5706b3ce1c70609d72a38efdf/sp/src/thirdparty/protobuf-2.3.0/python/mox.py#L704-L716
RamadhanAmizudin/malware
2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1
Fuzzbunch/fuzzbunch/pyreadline/rlmain.py
python
CTRL
(c)
return chr(ord(c) - ord('@'))
make a control character
make a control character
[ "make", "a", "control", "character" ]
def CTRL(c): '''make a control character''' assert '@' <= c <= '_' return chr(ord(c) - ord('@'))
[ "def", "CTRL", "(", "c", ")", ":", "assert", "'@'", "<=", "c", "<=", "'_'", "return", "chr", "(", "ord", "(", "c", ")", "-", "ord", "(", "'@'", ")", ")" ]
https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/Fuzzbunch/fuzzbunch/pyreadline/rlmain.py#L422-L425
psi4/psi4
be533f7f426b6ccc263904e55122899b16663395
psi4/driver/procrouting/diis.py
python
DIIS.adiis_gradient
(self, x)
return np.einsum("i,ij->j", dedc, dcdx)
Gradient of energy estimate w.r.t. input coefficient
Gradient of energy estimate w.r.t. input coefficient
[ "Gradient", "of", "energy", "estimate", "w", ".", "r", ".", "t", ".", "input", "coefficient" ]
def adiis_gradient(self, x): """ Gradient of energy estimate w.r.t. input coefficient """ c = normalize_input(x) dedc = self.adiis_linear + np.einsum("i,ij->j", c, self.adiis_quadratic) norm_sq = (x**2).sum() dcdx = np.diag(x) * norm_sq - np.einsum("i,j->ij", x ** 2, x) dcdx *= 2 / norm_sq**2 return np.einsum("i,ij->j", dedc, dcdx)
[ "def", "adiis_gradient", "(", "self", ",", "x", ")", ":", "c", "=", "normalize_input", "(", "x", ")", "dedc", "=", "self", ".", "adiis_linear", "+", "np", ".", "einsum", "(", "\"i,ij->j\"", ",", "c", ",", "self", ".", "adiis_quadratic", ")", "norm_sq",...
https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/procrouting/diis.py#L243-L252
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/libevent/event_rpcgen.py
python
Struct.EntryTagName
(self, entry)
return name.upper()
Creates the name inside an enumeration for distinguishing data types.
Creates the name inside an enumeration for distinguishing data types.
[ "Creates", "the", "name", "inside", "an", "enumeration", "for", "distinguishing", "data", "types", "." ]
def EntryTagName(self, entry): """Creates the name inside an enumeration for distinguishing data types.""" name = "%s_%s" % (self._name, entry.Name()) return name.upper()
[ "def", "EntryTagName", "(", "self", ",", "entry", ")", ":", "name", "=", "\"%s_%s\"", "%", "(", "self", ".", "_name", ",", "entry", ".", "Name", "(", ")", ")", "return", "name", ".", "upper", "(", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/libevent/event_rpcgen.py#L46-L50
gnuradio/gnuradio
09c3c4fa4bfb1a02caac74cb5334dfe065391e3b
gr-utils/modtool/templates/gr-newmod/docs/doxygen/other/doxypy.py
python
argParse
()
return parser.parse_args()
Parses commandline args.
Parses commandline args.
[ "Parses", "commandline", "args", "." ]
def argParse(): """Parses commandline args.""" parser = ArgumentParser(prog=__applicationName__) parser.add_argument("--version", action="version", version="%(prog)s " + __version__ ) parser.add_argument("--autobrief", action="store_true", help="use the docstring summary line as \\brief description" ) parser.add_argument("--debug", action="store_true", help="enable debug output on stderr" ) parser.add_argument("filename", metavar="FILENAME") return parser.parse_args()
[ "def", "argParse", "(", ")", ":", "parser", "=", "ArgumentParser", "(", "prog", "=", "__applicationName__", ")", "parser", ".", "add_argument", "(", "\"--version\"", ",", "action", "=", "\"version\"", ",", "version", "=", "\"%(prog)s \"", "+", "__version__", "...
https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gr-utils/modtool/templates/gr-newmod/docs/doxygen/other/doxypy.py#L417-L432
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/monotone-increasing-digits.py
python
Solution.monotoneIncreasingDigits
(self, N)
return int("".join(map(str, nums)))
:type N: int :rtype: int
:type N: int :rtype: int
[ ":", "type", "N", ":", "int", ":", "rtype", ":", "int" ]
def monotoneIncreasingDigits(self, N): """ :type N: int :rtype: int """ nums = map(int, list(str(N))) leftmost_inverted_idx = len(nums) for i in reversed(xrange(1, len(nums))): if nums[i-1] > nums[i]: leftmost_inverted_idx = i nums[i-1] -= 1 for i in xrange(leftmost_inverted_idx, len(nums)): nums[i] = 9 return int("".join(map(str, nums)))
[ "def", "monotoneIncreasingDigits", "(", "self", ",", "N", ")", ":", "nums", "=", "map", "(", "int", ",", "list", "(", "str", "(", "N", ")", ")", ")", "leftmost_inverted_idx", "=", "len", "(", "nums", ")", "for", "i", "in", "reversed", "(", "xrange", ...
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/monotone-increasing-digits.py#L5-L18
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/distlib/metadata.py
python
_get_name_and_version
(name, version, for_filename=False)
return '%s-%s' % (name, version)
Return the distribution name with version. If for_filename is true, return a filename-escaped form.
Return the distribution name with version.
[ "Return", "the", "distribution", "name", "with", "version", "." ]
def _get_name_and_version(name, version, for_filename=False): """Return the distribution name with version. If for_filename is true, return a filename-escaped form.""" if for_filename: # For both name and version any runs of non-alphanumeric or '.' # characters are replaced with a single '-'. Additionally any # spaces in the version string become '.' name = _FILESAFE.sub('-', name) version = _FILESAFE.sub('-', version.replace(' ', '.')) return '%s-%s' % (name, version)
[ "def", "_get_name_and_version", "(", "name", ",", "version", ",", "for_filename", "=", "False", ")", ":", "if", "for_filename", ":", "# For both name and version any runs of non-alphanumeric or '.'", "# characters are replaced with a single '-'. Additionally any", "# spaces in the...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/distlib/metadata.py#L223-L233
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_controls.py
python
Button_GetClassDefaultAttributes
(*args, **kwargs)
return _controls_.Button_GetClassDefaultAttributes(*args, **kwargs)
Button_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this.
Button_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
[ "Button_GetClassDefaultAttributes", "(", "int", "variant", "=", "WINDOW_VARIANT_NORMAL", ")", "-", ">", "VisualAttributes" ]
def Button_GetClassDefaultAttributes(*args, **kwargs): """ Button_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.Button_GetClassDefaultAttributes(*args, **kwargs)
[ "def", "Button_GetClassDefaultAttributes", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "Button_GetClassDefaultAttributes", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L269-L284
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/ndarray/ndarray.py
python
NDArray._slice
(self, start, stop)
return self.__class__(handle=handle, writable=self.writable)
Returns a sliced NDArray that shares memory with the current one. This is called through ``x[start:stop]``. Parameters ---------- start : int Starting inclusive index of slice in the first dim. stop : int Finishing exclusive index of slice in the first dim. Returns ------- `NDArray` sharing the memory with the current one sliced from start to stop in the first dim. Examples: >>> a = mx.nd.array([[1,2], [3, 4], [5, 6], [7, 8]]) >>> a[1:2].asnumpy() array([[ 3., 4.]], dtype=float32) >>> a[1:1].asnumpy() array([], shape=(0, 2), dtype=float32)
Returns a sliced NDArray that shares memory with the current one. This is called through ``x[start:stop]``.
[ "Returns", "a", "sliced", "NDArray", "that", "shares", "memory", "with", "the", "current", "one", ".", "This", "is", "called", "through", "x", "[", "start", ":", "stop", "]", "." ]
def _slice(self, start, stop): """Returns a sliced NDArray that shares memory with the current one. This is called through ``x[start:stop]``. Parameters ---------- start : int Starting inclusive index of slice in the first dim. stop : int Finishing exclusive index of slice in the first dim. Returns ------- `NDArray` sharing the memory with the current one sliced from start to stop in the first dim. Examples: >>> a = mx.nd.array([[1,2], [3, 4], [5, 6], [7, 8]]) >>> a[1:2].asnumpy() array([[ 3., 4.]], dtype=float32) >>> a[1:1].asnumpy() array([], shape=(0, 2), dtype=float32) """ handle = NDArrayHandle() start, stop, _ = _get_index_range(start, stop, self.shape[0]) check_call(_LIB.MXNDArraySlice( self.handle, mx_uint(start), mx_uint(stop), ctypes.byref(handle))) return self.__class__(handle=handle, writable=self.writable)
[ "def", "_slice", "(", "self", ",", "start", ",", "stop", ")", ":", "handle", "=", "NDArrayHandle", "(", ")", "start", ",", "stop", ",", "_", "=", "_get_index_range", "(", "start", ",", "stop", ",", "self", ".", "shape", "[", "0", "]", ")", "check_c...
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/ndarray/ndarray.py#L1370-L1398
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/plotting/_matplotlib/core.py
python
MPLPlot._has_plotted_object
(self, ax)
return len(ax.lines) != 0 or len(ax.artists) != 0 or len(ax.containers) != 0
check whether ax has data
check whether ax has data
[ "check", "whether", "ax", "has", "data" ]
def _has_plotted_object(self, ax): """check whether ax has data""" return len(ax.lines) != 0 or len(ax.artists) != 0 or len(ax.containers) != 0
[ "def", "_has_plotted_object", "(", "self", ",", "ax", ")", ":", "return", "len", "(", "ax", ".", "lines", ")", "!=", "0", "or", "len", "(", "ax", ".", "artists", ")", "!=", "0", "or", "len", "(", "ax", ".", "containers", ")", "!=", "0" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/plotting/_matplotlib/core.py#L275-L277
synfig/synfig
a5ec91db5b751dc12e4400ccfb5c063fd6d2d928
synfig-studio/plugins/lottie-exporter/layers/shape.py
python
gen_layer_shape
(lottie, layer, idx)
Generates the dictionary corresponding to layers/shape.json Args: lottie (dict) : Lottie generate shape stored here layer (common.Layer.Layer) : Synfig format shape layer idx (int) : Stores the index(number of) of shape layer Returns: (None)
Generates the dictionary corresponding to layers/shape.json
[ "Generates", "the", "dictionary", "corresponding", "to", "layers", "/", "shape", ".", "json" ]
def gen_layer_shape(lottie, layer, idx): """ Generates the dictionary corresponding to layers/shape.json Args: lottie (dict) : Lottie generate shape stored here layer (common.Layer.Layer) : Synfig format shape layer idx (int) : Stores the index(number of) of shape layer Returns: (None) """ if layer.get_type() in {"linear_gradient", "radial_gradient"}: # Create dummy point1 and point2 for linear/radial gradient to generate rectangle for it in lottie format # Will have to use add_offset() function inside after this generation gen_dummy_rectangle(layer) layer.add_offset() index = Count() lottie["ddd"] = settings.DEFAULT_3D lottie["ind"] = idx lottie["ty"] = settings.LAYER_SHAPE_TYPE lottie["nm"] = layer.get_description() lottie["sr"] = settings.LAYER_DEFAULT_STRETCH lottie["ks"] = {} # Transform properties to be filled gen_helpers_transform(lottie["ks"]) lottie["ao"] = settings.LAYER_DEFAULT_AUTO_ORIENT lottie["shapes"] = [] # Shapes to be filled yet lottie["shapes"].append({}) if layer.get_type() == "star": gen_shapes_star(lottie["shapes"][0], layer, index.inc()) elif layer.get_type() in {"circle", "simple_circle"}: gen_shapes_circle(lottie["shapes"][0], layer, index.inc()) elif layer.get_type() in {"filled_rectangle", "rectangle"}: gen_shapes_rectangle(lottie["shapes"][0], layer.get_layer(), index.inc()) elif layer.get_type() in {"linear_gradient", "radial_gradient"}: gen_shapes_shape(lottie["shapes"][0], layer, index.inc()) elif layer.get_type() in {"outline"}: settings.OUTLINE_FLAG = True gen_bline_outline_constant(lottie["shapes"][0],layer.get_param("bline"),layer,lottie["ks"],index.inc()) lottie["shapes"].append({}) # For the fill or color if layer.get_type() in {"linear_gradient"}: gen_linear_gradient(lottie["shapes"][1], layer, index.inc()) elif layer.get_type() in {"radial_gradient"}: gen_radial_gradient(lottie["shapes"][1], layer, index.inc()) elif layer.get_type() in {"outline"}: pass else: gen_shapes_fill(lottie["shapes"][1], layer) lottie["ip"] = settings.lottie_format["ip"] lottie["op"] = settings.lottie_format["op"] lottie["st"] = 0 # Don't know yet get_blend(lottie, layer)
[ "def", "gen_layer_shape", "(", "lottie", ",", "layer", ",", "idx", ")", ":", "if", "layer", ".", "get_type", "(", ")", "in", "{", "\"linear_gradient\"", ",", "\"radial_gradient\"", "}", ":", "# Create dummy point1 and point2 for linear/radial gradient to generate rectan...
https://github.com/synfig/synfig/blob/a5ec91db5b751dc12e4400ccfb5c063fd6d2d928/synfig-studio/plugins/lottie-exporter/layers/shape.py#L21-L79
wyrover/book-code
7f4883d9030d553bc6bcfa3da685e34789839900
3rdparty/protobuf/python/mox.py
python
Verify
(*args)
Verify mocks. Args: # args is any number of mocks to be verified.
Verify mocks.
[ "Verify", "mocks", "." ]
def Verify(*args): """Verify mocks. Args: # args is any number of mocks to be verified. """ for mock in args: mock._Verify()
[ "def", "Verify", "(", "*", "args", ")", ":", "for", "mock", "in", "args", ":", "mock", ".", "_Verify", "(", ")" ]
https://github.com/wyrover/book-code/blob/7f4883d9030d553bc6bcfa3da685e34789839900/3rdparty/protobuf/python/mox.py#L246-L254
llvm/llvm-project
ffa6262cb4e2a335d26416fad39a581b4f98c5f4
lldb/utils/lui/lldbutil.py
python
get_pc_addresses
(thread)
return [GetPCAddress(i) for i in range(thread.GetNumFrames())]
Returns a sequence of pc addresses for this thread.
Returns a sequence of pc addresses for this thread.
[ "Returns", "a", "sequence", "of", "pc", "addresses", "for", "this", "thread", "." ]
def get_pc_addresses(thread): """ Returns a sequence of pc addresses for this thread. """ def GetPCAddress(i): return thread.GetFrameAtIndex(i).GetPCAddress() return [GetPCAddress(i) for i in range(thread.GetNumFrames())]
[ "def", "get_pc_addresses", "(", "thread", ")", ":", "def", "GetPCAddress", "(", "i", ")", ":", "return", "thread", ".", "GetFrameAtIndex", "(", "i", ")", ".", "GetPCAddress", "(", ")", "return", "[", "GetPCAddress", "(", "i", ")", "for", "i", "in", "ra...
https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/lldb/utils/lui/lldbutil.py#L724-L731
NeoGeographyToolkit/StereoPipeline
eedf54a919fb5cce1ab0e280bb0df4050763aa11
src/asp/IceBridge/run_helper.py
python
RunHelper.checkForImages
(self, startFrame, stopFrame, logger)
return allGood
Return true if all the images have been converted from jpeg.
Return true if all the images have been converted from jpeg.
[ "Return", "true", "if", "all", "the", "images", "have", "been", "converted", "from", "jpeg", "." ]
def checkForImages(self, startFrame, stopFrame, logger): '''Return true if all the images have been converted from jpeg.''' logger.info("Checking if all jpegs have been converted.") jpegFolder = self.getJpegFolder() imageFolder = self.getImageFolder() orthoFolder = self.getOrthoFolder() if not os.path.exists(jpegFolder): logger.info("Missing: " + jpegFolder) return False if not os.path.exists(imageFolder): logger.info("Missing: " + imageFolder) return False jpegIndexPath = icebridge_common.csvIndexFile(jpegFolder) if not os.path.exists(jpegIndexPath): logger.info("Missing: " + jpegIndexPath) return False (jpegFrameDict, jpegUrlDict) = icebridge_common.readIndexFile(jpegIndexPath, prependFolder = True) # Need the orthos to get the timestamp orthoIndexPath = icebridge_common.csvIndexFile(orthoFolder) if not os.path.exists(orthoIndexPath): raise Exception("Error: Missing ortho index file: " + orthoIndexPath + ".") (orthoFrameDict, orthoUrlDict) = icebridge_common.readIndexFile(orthoIndexPath, prependFolder = True) # Thorough check for missing images. It is very slow. num = len(jpegFrameDict.keys()) allGood = True count = 0 for frame in sorted(jpegFrameDict.keys()): if frame < startFrame or frame > stopFrame: continue # Add the progress, as this operation can be terribly slow # when the filesystem is not doing too well, especially on mfe. count = count + 1 if (count - 1) % 1000 == 0: logger.info('Progress: ' + str(count) + '/' + str(num)) inputPath = jpegFrameDict[frame] if not frame in orthoFrameDict: logger.info("Missing ortho for frame: " + frame) continue # Make sure the timestamp and frame number are in the output file name try: outputPath = icebridge_common.jpegToImageFile(inputPath, orthoFrameDict[frame]) except Exception as e: logger.info(str(e)) logger.info("Removing bad file: " + inputPath) if os.path.exists(inputPath): os.remove(inputPath) allGood = False continue if not os.path.exists(outputPath): logger.info("Missing image file: " + outputPath) allGood = False return allGood
[ "def", "checkForImages", "(", "self", ",", "startFrame", ",", "stopFrame", ",", "logger", ")", ":", "logger", ".", "info", "(", "\"Checking if all jpegs have been converted.\"", ")", "jpegFolder", "=", "self", ".", "getJpegFolder", "(", ")", "imageFolder", "=", ...
https://github.com/NeoGeographyToolkit/StereoPipeline/blob/eedf54a919fb5cce1ab0e280bb0df4050763aa11/src/asp/IceBridge/run_helper.py#L361-L426
yue/yue
619d62c191b13c51c01be451dc48917c34a5aefc
building/tools/cpplint.py
python
_CppLintState.SetCountingStyle
(self, counting_style)
Sets the module's counting options.
Sets the module's counting options.
[ "Sets", "the", "module", "s", "counting", "options", "." ]
def SetCountingStyle(self, counting_style): """Sets the module's counting options.""" self.counting = counting_style
[ "def", "SetCountingStyle", "(", "self", ",", "counting_style", ")", ":", "self", ".", "counting", "=", "counting_style" ]
https://github.com/yue/yue/blob/619d62c191b13c51c01be451dc48917c34a5aefc/building/tools/cpplint.py#L891-L893
su2code/SU2
72b2fa977b64b9683a388920f05298a40d39e5c5
SU2_PY/FSI_tools/FSIInterface.py
python
Interface.connect
(self, FSI_config, FluidSolver, SolidSolver)
Connection between solvers. Creates the communication support between the two solvers. Gets information about f/s interfaces from the two solvers.
Connection between solvers. Creates the communication support between the two solvers. Gets information about f/s interfaces from the two solvers.
[ "Connection", "between", "solvers", ".", "Creates", "the", "communication", "support", "between", "the", "two", "solvers", ".", "Gets", "information", "about", "f", "/", "s", "interfaces", "from", "the", "two", "solvers", "." ]
def connect(self, FSI_config, FluidSolver, SolidSolver): """ Connection between solvers. Creates the communication support between the two solvers. Gets information about f/s interfaces from the two solvers. """ if self.have_MPI: myid = self.comm.Get_rank() MPIsize = self.comm.Get_size() else: myid = 0 MPIsize = 1 # --- Identify the fluid and solid interfaces and store the number of nodes on both sides (and for each partition) --- self.fluidInterfaceIdentifier = None self.nLocalFluidInterfaceNodes = 0 if FluidSolver is not None: print('Fluid solver is initialized on process {}'.format(myid)) self.haveFluidSolver = True allMovingMarkersTags = FluidSolver.GetAllDeformMeshMarkersTag() allMarkersID = FluidSolver.GetAllBoundaryMarkers() if not allMovingMarkersTags: raise Exception('No interface for FSI was defined.') else: if allMovingMarkersTags[0] in allMarkersID.keys(): self.fluidInterfaceIdentifier = allMarkersID[allMovingMarkersTags[0]] if self.fluidInterfaceIdentifier is not None: self.nLocalFluidInterfaceNodes = FluidSolver.GetNumberVertices(self.fluidInterfaceIdentifier) if self.nLocalFluidInterfaceNodes != 0: self.haveFluidInterface = True print('Number of interface fluid nodes (halo nodes included) on proccess {} : {}'.format(myid,self.nLocalFluidInterfaceNodes)) else: pass if SolidSolver is not None: print('Solid solver is initialized on process {}'.format(myid)) self.haveSolidSolver = True self.solidInterfaceIdentifier = SolidSolver.getFSIMarkerID() self.nLocalSolidInterfaceNodes = SolidSolver.getNumberOfSolidInterfaceNodes(self.solidInterfaceIdentifier) if self.nLocalSolidInterfaceNodes != 0: self.haveSolidInterface = True print('Number of interface solid nodes (halo nodes included) on proccess {} : {}'.format(myid,self.nLocalSolidInterfaceNodes)) else: pass # --- Exchange information about processors on which the solvers are defined and where the interface nodes are lying --- if self.have_MPI: if self.haveFluidSolver: sendBufFluid = np.array(int(1)) else: sendBufFluid = np.array(int(0)) if self.haveSolidSolver: sendBufSolid = np.array(int(1)) else: sendBufSolid = np.array(int(0)) if self.haveFluidInterface: sendBufFluidInterface = np.array(int(1)) else: sendBufFluidInterface = np.array(int(0)) if self.haveSolidInterface: sendBufSolidInterface = np.array(int(1)) else: sendBufSolidInterface = np.array(int(0)) rcvBufFluid = np.zeros(MPIsize, dtype = int) rcvBufSolid = np.zeros(MPIsize, dtype = int) rcvBufFluidInterface = np.zeros(MPIsize, dtype = int) rcvBufSolidInterface = np.zeros(MPIsize, dtype = int) self.comm.Allgather(sendBufFluid, rcvBufFluid) self.comm.Allgather(sendBufSolid, rcvBufSolid) self.comm.Allgather(sendBufFluidInterface, rcvBufFluidInterface) self.comm.Allgather(sendBufSolidInterface, rcvBufSolidInterface) for iProc in range(MPIsize): if rcvBufFluid[iProc] == 1: self.fluidSolverProcessors.append(iProc) if rcvBufSolid[iProc] == 1: self.solidSolverProcessors.append(iProc) if rcvBufFluidInterface[iProc] == 1: self.fluidInterfaceProcessors.append(iProc) if rcvBufSolidInterface[iProc] == 1: self.solidInterfaceProcessors.append(iProc) del sendBufFluid, sendBufSolid, rcvBufFluid, rcvBufSolid, sendBufFluidInterface, sendBufSolidInterface, rcvBufFluidInterface, rcvBufSolidInterface else: self.fluidSolverProcessors.append(0) self.solidSolverProcessors.append(0) self.fluidInterfaceProcessors.append(0) self.solidInterfaceProcessors.append(0) self.MPIBarrier() # --- Calculate the total number of nodes at the fluid interface (sum over all the partitions) --- # Calculate the number of halo nodes on each partition self.nLocalFluidInterfaceHaloNode = 0 for iVertex in range(self.nLocalFluidInterfaceNodes): if FluidSolver.IsAHaloNode(self.fluidInterfaceIdentifier, iVertex): GlobalIndex = FluidSolver.GetVertexGlobalIndex(self.fluidInterfaceIdentifier, iVertex) self.FluidHaloNodeList[GlobalIndex] = iVertex self.nLocalFluidInterfaceHaloNode += 1 # Calculate the number of physical (= not halo) nodes on each partition self.nLocalFluidInterfacePhysicalNodes = self.nLocalFluidInterfaceNodes - self.nLocalFluidInterfaceHaloNode if self.have_MPI: self.FluidHaloNodeList = self.comm.allgather(self.FluidHaloNodeList) else: self.FluidHaloNodeList = [{}] # Same thing for the solid part self.nLocalSolidInterfaceHaloNode = 0 for iVertex in range(self.nLocalSolidInterfaceNodes): if SolidSolver.IsAHaloNode(self.solidInterfaceIdentifier, iVertex): GlobalIndex = SolidSolver.getVertexGlobalIndex(self.solidInterfaceIdentifier, iVertex) self.SolidHaloNodeList[GlobalIndex] = iVertex self.nLocalSolidInterfaceHaloNode += 1 self.nLocalSolidInterfacePhysicalNodes = self.nLocalSolidInterfaceNodes - self.nLocalSolidInterfaceHaloNode if self.have_MPI: self.SolidHaloNodeList = self.comm.allgather(self.SolidHaloNodeList) else: self.SolidHaloNodeList = [{}] # --- Calculate the total number of nodes (with and without halo) at the fluid interface (sum over all the partitions) and broadcast the number accross all processors --- sendBuffTotal = np.array(int(self.nLocalFluidInterfaceNodes)) sendBuffPhysical = np.array(int(self.nLocalFluidInterfacePhysicalNodes)) rcvBuffTotal = np.zeros(1, dtype=int) rcvBuffPhysical = np.zeros(1, dtype=int) if self.have_MPI: self.comm.barrier() self.comm.Allreduce(sendBuffTotal, self.nFluidInterfaceNodes, op=self.MPI.SUM) self.comm.Allreduce(sendBuffPhysical, self.nFluidInterfacePhysicalNodes, op=self.MPI.SUM) else: self.nFluidInterfaceNodes = np.copy(sendBuffTotal) self.nFluidInterfacePhysicalNodes = np.copy(sendBuffPhysical) del sendBuffTotal, rcvBuffTotal, sendBuffPhysical, rcvBuffPhysical # Same thing for the solid part sendBuffTotal = np.array(int(self.nLocalSolidInterfaceNodes)) sendBuffPhysical = np.array(int(self.nLocalSolidInterfacePhysicalNodes)) rcvBuffTotal = np.zeros(1, dtype=int) rcvBuffPhysical = np.zeros(1, dtype=int) if self.have_MPI: self.comm.barrier() self.comm.Allreduce(sendBuffTotal, self.nSolidInterfaceNodes, op=self.MPI.SUM) self.comm.Allreduce(sendBuffPhysical, self.nSolidInterfacePhysicalNodes, op=self.MPI.SUM) else: self.nSolidInterfaceNodes = np.copy(sendBuffTotal) self.nSolidInterfacePhysicalNodes = np.copy(sendBuffPhysical) del sendBuffTotal, rcvBuffTotal, sendBuffPhysical, rcvBuffPhysical # --- Store the number of physical interface nodes on each processor and allgather the information --- self.fluidPhysicalInterfaceNodesDistribution = np.zeros(MPIsize, dtype=int) if self.have_MPI: sendBuffPhysical = np.array(int(self.nLocalFluidInterfacePhysicalNodes)) self.comm.Allgather(sendBuffPhysical,self.fluidPhysicalInterfaceNodesDistribution) del sendBuffPhysical else: self.fluidPhysicalInterfaceNodesDistribution[0] = self.nFluidInterfacePhysicalNodes # Same thing for the solid part self.solidPhysicalInterfaceNodesDistribution = np.zeros(MPIsize, dtype=int) if self.have_MPI: sendBuffPhysical = np.array(int(self.nLocalSolidInterfacePhysicalNodes)) self.comm.Allgather(sendBuffPhysical,self.solidPhysicalInterfaceNodesDistribution) del sendBuffPhysical else: self.solidPhysicalInterfaceNodesDistribution[0] = self.nSolidInterfacePhysicalNodes # --- Calculate and store the global indexing of interface physical nodes on each processor and allgather the information --- if self.have_MPI: if myid in self.fluidInterfaceProcessors: globalIndexStart = 0 for iProc in range(myid): globalIndexStart += self.fluidPhysicalInterfaceNodesDistribution[iProc] globalIndexStop = globalIndexStart + self.nLocalFluidInterfacePhysicalNodes-1 else: globalIndexStart = 0 globalIndexStop = 0 self.fluidGlobalIndexRange[myid] = [globalIndexStart,globalIndexStop] self.fluidGlobalIndexRange = self.comm.allgather(self.fluidGlobalIndexRange) else: temp = {} temp[0] = [0,self.nLocalFluidInterfacePhysicalNodes-1] self.fluidGlobalIndexRange = list() self.fluidGlobalIndexRange.append(temp) # Same thing for the solid part if self.have_MPI: if myid in self.solidInterfaceProcessors: globalIndexStart = 0 for iProc in range(myid): globalIndexStart += self.solidPhysicalInterfaceNodesDistribution[iProc] globalIndexStop = globalIndexStart + self.nLocalSolidInterfacePhysicalNodes-1 else: globalIndexStart = 0 globalIndexStop = 0 self.solidGlobalIndexRange[myid] = [globalIndexStart,globalIndexStop] self.solidGlobalIndexRange = self.comm.allgather(self.solidGlobalIndexRange) else: temp = {} temp[0] = [0,self.nSolidInterfacePhysicalNodes-1] self.solidGlobalIndexRange = list() self.solidGlobalIndexRange.append(temp) self.MPIPrint('Total number of fluid interface nodes (halo nodes included) : {}'.format(self.nFluidInterfaceNodes)) self.MPIPrint('Total number of solid interface nodes (halo nodes included) : {}'.format(self.nSolidInterfaceNodes)) self.MPIPrint('Total number of fluid interface nodes : {}'.format(self.nFluidInterfacePhysicalNodes)) self.MPIPrint('Total number of solid interface nodes : {}'.format(self.nSolidInterfacePhysicalNodes)) self.MPIBarrier() # --- Create all the PETSc vectors required for parallel communication and parallel mesh mapping/interpolation (working for serial too) --- if self.have_MPI: self.solidInterface_array_DispX = PETSc.Vec().create(self.comm) self.solidInterface_array_DispY = PETSc.Vec().create(self.comm) self.solidInterface_array_DispZ = PETSc.Vec().create(self.comm) self.solidInterface_array_DispX.setType('mpi') self.solidInterface_array_DispY.setType('mpi') self.solidInterface_array_DispZ.setType('mpi') else: self.solidInterface_array_DispX = PETSc.Vec().create() self.solidInterface_array_DispY = PETSc.Vec().create() self.solidInterface_array_DispZ = PETSc.Vec().create() self.solidInterface_array_DispX.setType('seq') self.solidInterface_array_DispY.setType('seq') self.solidInterface_array_DispZ.setType('seq') self.solidInterface_array_DispX.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) self.solidInterface_array_DispY.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) self.solidInterface_array_DispZ.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) self.solidInterface_array_DispX.set(0.0) self.solidInterface_array_DispY.set(0.0) self.solidInterface_array_DispZ.set(0.0) if self.have_MPI: self.fluidInterface_array_DispX = PETSc.Vec().create(self.comm) self.fluidInterface_array_DispY = PETSc.Vec().create(self.comm) self.fluidInterface_array_DispZ = PETSc.Vec().create(self.comm) self.fluidInterface_array_DispX.setType('mpi') self.fluidInterface_array_DispY.setType('mpi') self.fluidInterface_array_DispZ.setType('mpi') else: self.fluidInterface_array_DispX = PETSc.Vec().create() self.fluidInterface_array_DispY = PETSc.Vec().create() self.fluidInterface_array_DispZ = PETSc.Vec().create() self.fluidInterface_array_DispX.setType('seq') self.fluidInterface_array_DispY.setType('seq') self.fluidInterface_array_DispZ.setType('seq') self.fluidInterface_array_DispX.setSizes(self.nFluidInterfacePhysicalNodes) self.fluidInterface_array_DispY.setSizes(self.nFluidInterfacePhysicalNodes) self.fluidInterface_array_DispZ.setSizes(self.nFluidInterfacePhysicalNodes) self.fluidInterface_array_DispX.set(0.0) self.fluidInterface_array_DispY.set(0.0) self.fluidInterface_array_DispZ.set(0.0) if self.have_MPI: self.fluidLoads_array_X = PETSc.Vec().create(self.comm) self.fluidLoads_array_Y = PETSc.Vec().create(self.comm) self.fluidLoads_array_Z = PETSc.Vec().create(self.comm) self.fluidLoads_array_X.setType('mpi') self.fluidLoads_array_Y.setType('mpi') self.fluidLoads_array_Z.setType('mpi') else: self.fluidLoads_array_X = PETSc.Vec().create() self.fluidLoads_array_Y = PETSc.Vec().create() self.fluidLoads_array_Z = PETSc.Vec().create() self.fluidLoads_array_X.setType('seq') self.fluidLoads_array_Y.setType('seq') self.fluidLoads_array_Z.setType('seq') self.fluidLoads_array_X.setSizes(self.nFluidInterfacePhysicalNodes) self.fluidLoads_array_Y.setSizes(self.nFluidInterfacePhysicalNodes) self.fluidLoads_array_Z.setSizes(self.nFluidInterfacePhysicalNodes) self.fluidLoads_array_X.set(0.0) self.fluidLoads_array_Y.set(0.0) self.fluidLoads_array_Z.set(0.0) if self.have_MPI: self.solidLoads_array_X = PETSc.Vec().create(self.comm) self.solidLoads_array_Y = PETSc.Vec().create(self.comm) self.solidLoads_array_Z = PETSc.Vec().create(self.comm) self.solidLoads_array_X.setType('mpi') self.solidLoads_array_Y.setType('mpi') self.solidLoads_array_Z.setType('mpi') else: self.solidLoads_array_X = PETSc.Vec().create() self.solidLoads_array_Y = PETSc.Vec().create() self.solidLoads_array_Z = PETSc.Vec().create() self.solidLoads_array_X.setType('seq') self.solidLoads_array_Y.setType('seq') self.solidLoads_array_Z.setType('seq') self.solidLoads_array_X.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) self.solidLoads_array_Y.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) self.solidLoads_array_Z.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) self.solidLoads_array_X.set(0.0) self.solidLoads_array_Y.set(0.0) self.solidLoads_array_Z.set(0.0) # --- Create the PETSc vectors required for parallel relaxed BGS algo (working for serial too) --- if self.have_MPI: self.solidInterfaceResidual_array_X = PETSc.Vec().create(self.comm) self.solidInterfaceResidual_array_Y = PETSc.Vec().create(self.comm) self.solidInterfaceResidual_array_Z = PETSc.Vec().create(self.comm) self.solidInterfaceResidual_array_X.setType('mpi') self.solidInterfaceResidual_array_Y.setType('mpi') self.solidInterfaceResidual_array_Z.setType('mpi') else: self.solidInterfaceResidual_array_X = PETSc.Vec().create() self.solidInterfaceResidual_array_Y = PETSc.Vec().create() self.solidInterfaceResidual_array_Z = PETSc.Vec().create() self.solidInterfaceResidual_array_X.setType('seq') self.solidInterfaceResidual_array_Y.setType('seq') self.solidInterfaceResidual_array_Z.setType('seq') self.solidInterfaceResidual_array_X.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) self.solidInterfaceResidual_array_Y.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) self.solidInterfaceResidual_array_Z.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) self.solidInterfaceResidual_array_X.set(0.0) self.solidInterfaceResidual_array_Y.set(0.0) self.solidInterfaceResidual_array_Z.set(0.0) if self.have_MPI: self.solidInterfaceResidualnM1_array_X = PETSc.Vec().create(self.comm) self.solidInterfaceResidualnM1_array_Y = PETSc.Vec().create(self.comm) self.solidInterfaceResidualnM1_array_Z = PETSc.Vec().create(self.comm) self.solidInterfaceResidualnM1_array_X.setType('mpi') self.solidInterfaceResidualnM1_array_Y.setType('mpi') self.solidInterfaceResidualnM1_array_Z.setType('mpi') else: self.solidInterfaceResidualnM1_array_X = PETSc.Vec().create() self.solidInterfaceResidualnM1_array_Y = PETSc.Vec().create() self.solidInterfaceResidualnM1_array_Z = PETSc.Vec().create() self.solidInterfaceResidualnM1_array_X.setType('seq') self.solidInterfaceResidualnM1_array_Y.setType('seq') self.solidInterfaceResidualnM1_array_Z.setType('seq') self.solidInterfaceResidualnM1_array_X.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) self.solidInterfaceResidualnM1_array_Y.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) self.solidInterfaceResidualnM1_array_Z.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) self.solidInterfaceResidualnM1_array_X.set(0.0) self.solidInterfaceResidualnM1_array_Y.set(0.0) self.solidInterfaceResidualnM1_array_Z.set(0.0)
[ "def", "connect", "(", "self", ",", "FSI_config", ",", "FluidSolver", ",", "SolidSolver", ")", ":", "if", "self", ".", "have_MPI", ":", "myid", "=", "self", ".", "comm", ".", "Get_rank", "(", ")", "MPIsize", "=", "self", ".", "comm", ".", "Get_size", ...
https://github.com/su2code/SU2/blob/72b2fa977b64b9683a388920f05298a40d39e5c5/SU2_PY/FSI_tools/FSIInterface.py#L211-L543
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/tools/grit/grit/tool/interface.py
python
Tool.Run
(self, global_options, my_arguments)
Runs the tool. Args: global_options: object grit_runner.Options my_arguments: [arg1 arg2 ...] Return: 0 for success, non-0 for error
Runs the tool.
[ "Runs", "the", "tool", "." ]
def Run(self, global_options, my_arguments): '''Runs the tool. Args: global_options: object grit_runner.Options my_arguments: [arg1 arg2 ...] Return: 0 for success, non-0 for error ''' raise NotImplementedError()
[ "def", "Run", "(", "self", ",", "global_options", ",", "my_arguments", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/tools/grit/grit/tool/interface.py#L23-L33
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/EnggVanadiumCorrections.py
python
EnggVanadiumCorrections._prepare_curves_ws
(self, curves_dict)
return ws
Simply concantenates or appends fitting output workspaces as produced by the algorithm Fit (with 3 spectra each). The groups of 3 spectra are added sorted by the bank ID (number). This could also produce a workspace group with the individual workspaces in it, but the AppendSpectra solution seems simpler. @param curves_dict :: dictionary with fitting workspaces produced by 'Fit' @returns a workspace where all the input workspaces have been concatenated, with 3 spectra per workspace / bank
Simply concantenates or appends fitting output workspaces as produced by the algorithm Fit (with 3 spectra each). The groups of 3 spectra are added sorted by the bank ID (number). This could also produce a workspace group with the individual workspaces in it, but the AppendSpectra solution seems simpler.
[ "Simply", "concantenates", "or", "appends", "fitting", "output", "workspaces", "as", "produced", "by", "the", "algorithm", "Fit", "(", "with", "3", "spectra", "each", ")", ".", "The", "groups", "of", "3", "spectra", "are", "added", "sorted", "by", "the", "...
def _prepare_curves_ws(self, curves_dict): """ Simply concantenates or appends fitting output workspaces as produced by the algorithm Fit (with 3 spectra each). The groups of 3 spectra are added sorted by the bank ID (number). This could also produce a workspace group with the individual workspaces in it, but the AppendSpectra solution seems simpler. @param curves_dict :: dictionary with fitting workspaces produced by 'Fit' @returns a workspace where all the input workspaces have been concatenated, with 3 spectra per workspace / bank """ if 0 == len(curves_dict): raise RuntimeError("Expecting a dictionary with fitting workspaces from 'Fit' but got an " "empty dictionary") if 1 == len(curves_dict): return list(curves_dict.values())[0] keys = sorted(curves_dict) ws = curves_dict[keys[0]] for idx in range(1, len(keys)): next_ws = curves_dict[keys[idx]] ws = self._append_spectra(ws, next_ws) return ws
[ "def", "_prepare_curves_ws", "(", "self", ",", "curves_dict", ")", ":", "if", "0", "==", "len", "(", "curves_dict", ")", ":", "raise", "RuntimeError", "(", "\"Expecting a dictionary with fitting workspaces from 'Fit' but got an \"", "\"empty dictionary\"", ")", "if", "1...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/EnggVanadiumCorrections.py#L321-L345
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/formats/style.py
python
Styler.set_properties
(self, subset=None, **kwargs)
return self.applymap(f, subset=subset)
Method to set one or more non-data dependent properties or each cell. Parameters ---------- subset : IndexSlice A valid slice for ``data`` to limit the style application to. **kwargs : dict A dictionary of property, value pairs to be set for each cell. Returns ------- self : Styler Examples -------- >>> df = pd.DataFrame(np.random.randn(10, 4)) >>> df.style.set_properties(color="white", align="right") >>> df.style.set_properties(**{'background-color': 'yellow'})
Method to set one or more non-data dependent properties or each cell.
[ "Method", "to", "set", "one", "or", "more", "non", "-", "data", "dependent", "properties", "or", "each", "cell", "." ]
def set_properties(self, subset=None, **kwargs): """ Method to set one or more non-data dependent properties or each cell. Parameters ---------- subset : IndexSlice A valid slice for ``data`` to limit the style application to. **kwargs : dict A dictionary of property, value pairs to be set for each cell. Returns ------- self : Styler Examples -------- >>> df = pd.DataFrame(np.random.randn(10, 4)) >>> df.style.set_properties(color="white", align="right") >>> df.style.set_properties(**{'background-color': 'yellow'}) """ values = ";".join(f"{p}: {v}" for p, v in kwargs.items()) f = lambda x: values return self.applymap(f, subset=subset)
[ "def", "set_properties", "(", "self", ",", "subset", "=", "None", ",", "*", "*", "kwargs", ")", ":", "values", "=", "\";\"", ".", "join", "(", "f\"{p}: {v}\"", "for", "p", ",", "v", "in", "kwargs", ".", "items", "(", ")", ")", "f", "=", "lambda", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/formats/style.py#L1134-L1157
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/requests/requests/packages/urllib3/util/retry.py
python
Retry.get_backoff_time
(self)
return min(self.BACKOFF_MAX, backoff_value)
Formula for computing the current backoff :rtype: float
Formula for computing the current backoff
[ "Formula", "for", "computing", "the", "current", "backoff" ]
def get_backoff_time(self): """ Formula for computing the current backoff :rtype: float """ if self._observed_errors <= 1: return 0 backoff_value = self.backoff_factor * (2 ** (self._observed_errors - 1)) return min(self.BACKOFF_MAX, backoff_value)
[ "def", "get_backoff_time", "(", "self", ")", ":", "if", "self", ".", "_observed_errors", "<=", "1", ":", "return", "0", "backoff_value", "=", "self", ".", "backoff_factor", "*", "(", "2", "**", "(", "self", ".", "_observed_errors", "-", "1", ")", ")", ...
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/requests/requests/packages/urllib3/util/retry.py#L158-L167
facebook/fbthrift
fb9c8562aba04c4fd9b17716eb5d970cc88a75bb
thrift/lib/py/transport/TTransport.py
python
CReadableTransport.cstringio_refill
(self, partialread, reqlen)
Refills cstringio_buf. Returns the currently used buffer (which can but need not be the same as the old cstringio_buf). partialread is what the C code has read from the buffer, and should be inserted into the buffer before any more reads. The return value must be a new, not borrowed reference. Something along the lines of self._buf should be fine. If reqlen bytes can't be read, throw EOFError.
Refills cstringio_buf.
[ "Refills", "cstringio_buf", "." ]
def cstringio_refill(self, partialread, reqlen): """Refills cstringio_buf. Returns the currently used buffer (which can but need not be the same as the old cstringio_buf). partialread is what the C code has read from the buffer, and should be inserted into the buffer before any more reads. The return value must be a new, not borrowed reference. Something along the lines of self._buf should be fine. If reqlen bytes can't be read, throw EOFError. """ pass
[ "def", "cstringio_refill", "(", "self", ",", "partialread", ",", "reqlen", ")", ":", "pass" ]
https://github.com/facebook/fbthrift/blob/fb9c8562aba04c4fd9b17716eb5d970cc88a75bb/thrift/lib/py/transport/TTransport.py#L105-L116
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py
python
Entry.selection_range
(self, start, end)
Set the selection from START to END (not included).
Set the selection from START to END (not included).
[ "Set", "the", "selection", "from", "START", "to", "END", "(", "not", "included", ")", "." ]
def selection_range(self, start, end): """Set the selection from START to END (not included).""" self.tk.call(self._w, 'selection', 'range', start, end)
[ "def", "selection_range", "(", "self", ",", "start", ",", "end", ")", ":", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "'selection'", ",", "'range'", ",", "start", ",", "end", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py#L2719-L2721
PX4/PX4-Autopilot
0b9f60a0370be53d683352c63fd92db3d6586e18
Tools/mavlink_px4.py
python
MAVLink.optical_flow_send
(self, time_usec, sensor_id, flow_x, flow_y, flow_comp_m_x, flow_comp_m_y, quality, ground_distance)
return self.send(self.optical_flow_encode(time_usec, sensor_id, flow_x, flow_y, flow_comp_m_x, flow_comp_m_y, quality, ground_distance))
Optical flow from a flow sensor (e.g. optical mouse sensor) time_usec : Timestamp (UNIX) (uint64_t) sensor_id : Sensor ID (uint8_t) flow_x : Flow in pixels in x-sensor direction (int16_t) flow_y : Flow in pixels in y-sensor direction (int16_t) flow_comp_m_x : Flow in meters in x-sensor direction, angular-speed compensated (float) flow_comp_m_y : Flow in meters in y-sensor direction, angular-speed compensated (float) quality : Optical flow quality / confidence. 0: bad, 255: maximum quality (uint8_t) ground_distance : Ground distance in meters. Positive value: distance known. Negative value: Unknown distance (float)
Optical flow from a flow sensor (e.g. optical mouse sensor)
[ "Optical", "flow", "from", "a", "flow", "sensor", "(", "e", ".", "g", ".", "optical", "mouse", "sensor", ")" ]
def optical_flow_send(self, time_usec, sensor_id, flow_x, flow_y, flow_comp_m_x, flow_comp_m_y, quality, ground_distance): ''' Optical flow from a flow sensor (e.g. optical mouse sensor) time_usec : Timestamp (UNIX) (uint64_t) sensor_id : Sensor ID (uint8_t) flow_x : Flow in pixels in x-sensor direction (int16_t) flow_y : Flow in pixels in y-sensor direction (int16_t) flow_comp_m_x : Flow in meters in x-sensor direction, angular-speed compensated (float) flow_comp_m_y : Flow in meters in y-sensor direction, angular-speed compensated (float) quality : Optical flow quality / confidence. 0: bad, 255: maximum quality (uint8_t) ground_distance : Ground distance in meters. Positive value: distance known. Negative value: Unknown distance (float) ''' return self.send(self.optical_flow_encode(time_usec, sensor_id, flow_x, flow_y, flow_comp_m_x, flow_comp_m_y, quality, ground_distance))
[ "def", "optical_flow_send", "(", "self", ",", "time_usec", ",", "sensor_id", ",", "flow_x", ",", "flow_y", ",", "flow_comp_m_x", ",", "flow_comp_m_y", ",", "quality", ",", "ground_distance", ")", ":", "return", "self", ".", "send", "(", "self", ".", "optical...
https://github.com/PX4/PX4-Autopilot/blob/0b9f60a0370be53d683352c63fd92db3d6586e18/Tools/mavlink_px4.py#L4727-L4741
vslavik/poedit
f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a
deps/boost/libs/metaparse/tools/benchmark/generate.py
python
random_chars
(number)
return ( format_character(nth_char(char_map, random.randint(0, char_num - 1))) for _ in xrange(0, number) )
Generate random characters
Generate random characters
[ "Generate", "random", "characters" ]
def random_chars(number): """Generate random characters""" char_map = { k: v for k, v in chars.CHARS.iteritems() if not format_character(k).startswith('\\x') } char_num = sum(char_map.values()) return ( format_character(nth_char(char_map, random.randint(0, char_num - 1))) for _ in xrange(0, number) )
[ "def", "random_chars", "(", "number", ")", ":", "char_map", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "chars", ".", "CHARS", ".", "iteritems", "(", ")", "if", "not", "format_character", "(", "k", ")", ".", "startswith", "(", "'\\\\x'", "...
https://github.com/vslavik/poedit/blob/f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a/deps/boost/libs/metaparse/tools/benchmark/generate.py#L50-L61
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/masked/combobox.py
python
BaseMaskedComboBox._OnAutoSelect
(self, field, match_index=None)
Override mixin (empty) autocomplete handler, so that autocompletion causes combobox to update appropriately. Additionally allow items that aren't in the drop down.
Override mixin (empty) autocomplete handler, so that autocompletion causes combobox to update appropriately. Additionally allow items that aren't in the drop down.
[ "Override", "mixin", "(", "empty", ")", "autocomplete", "handler", "so", "that", "autocompletion", "causes", "combobox", "to", "update", "appropriately", ".", "Additionally", "allow", "items", "that", "aren", "t", "in", "the", "drop", "down", "." ]
def _OnAutoSelect(self, field, match_index=None): """ Override mixin (empty) autocomplete handler, so that autocompletion causes combobox to update appropriately. Additionally allow items that aren't in the drop down. """ ## dbg('MaskedComboBox::OnAutoSelect(%d, %s)' % (field._index, repr(match_index)), indent=1) ## field._autoCompleteIndex = match if isinstance(match_index, int): if field == self._ctrl_constraints: self.SetSelection(match_index) ## dbg('issuing combo selection event') self.GetEventHandler().ProcessEvent( MaskedComboBoxSelectEvent( self.GetId(), match_index, self ) ) self._CheckValid() ## dbg('field._autoCompleteIndex:', match) ## dbg('self.GetCurrentSelection():', self.GetCurrentSelection()) end = self._goEnd(getPosOnly=True) ## dbg('scheduling set of end position to:', end) # work around bug in wx 2.5 wx.CallAfter(self.SetInsertionPoint, 0) wx.CallAfter(self.SetInsertionPoint, end) elif isinstance(match_index, str) or isinstance(match_index, unicode): ## dbg('CallAfter SetValue') # Preserve the textbox contents # See commentary in _OnReturn docstring. wx.CallAfter(self.SetValue, match_index)
[ "def", "_OnAutoSelect", "(", "self", ",", "field", ",", "match_index", "=", "None", ")", ":", "## dbg('MaskedComboBox::OnAutoSelect(%d, %s)' % (field._index, repr(match_index)), indent=1)", "## field._autoCompleteIndex = match", "if", "isinstance", "(", "match_index",...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/masked/combobox.py#L666-L692
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/logging/__init__.py
python
Filter.__init__
(self, name='')
Initialize a filter. Initialize with the name of the logger which, together with its children, will have its events allowed through the filter. If no name is specified, allow every event.
Initialize a filter.
[ "Initialize", "a", "filter", "." ]
def __init__(self, name=''): """ Initialize a filter. Initialize with the name of the logger which, together with its children, will have its events allowed through the filter. If no name is specified, allow every event. """ self.name = name self.nlen = len(name)
[ "def", "__init__", "(", "self", ",", "name", "=", "''", ")", ":", "self", ".", "name", "=", "name", "self", ".", "nlen", "=", "len", "(", "name", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/logging/__init__.py#L547-L556
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/hyperlink.py
python
HyperLinkCtrl.UpdateLink
(self, OnRefresh=True)
Updates the link, changing text properties if: - User specific setting; - Link visited; - New link; :param `OnRefresh`: ``True`` to refresh the control, ``False`` otherwise.
Updates the link, changing text properties if:
[ "Updates", "the", "link", "changing", "text", "properties", "if", ":" ]
def UpdateLink(self, OnRefresh=True): """ Updates the link, changing text properties if: - User specific setting; - Link visited; - New link; :param `OnRefresh`: ``True`` to refresh the control, ``False`` otherwise. """ fontTemp = self.GetFont() if self._Visited: self.SetForegroundColour(self._VisitedColour) fontTemp.SetUnderlined(self._VisitedUnderline) else: self.SetForegroundColour(self._LinkColour) fontTemp.SetUnderlined(self._LinkUnderline) if self._Bold: fontTemp.SetWeight(wx.BOLD) if self.GetFont() != fontTemp: self.SetFont(fontTemp) self.Refresh(OnRefresh)
[ "def", "UpdateLink", "(", "self", ",", "OnRefresh", "=", "True", ")", ":", "fontTemp", "=", "self", ".", "GetFont", "(", ")", "if", "self", ".", "_Visited", ":", "self", ".", "SetForegroundColour", "(", "self", ".", "_VisitedColour", ")", "fontTemp", "."...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/hyperlink.py#L399-L428
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/distributed/elastic/rendezvous/etcd_rendezvous_backend.py
python
EtcdRendezvousBackend.name
(self)
return "etcd-v2"
See base class.
See base class.
[ "See", "base", "class", "." ]
def name(self) -> str: """See base class.""" return "etcd-v2"
[ "def", "name", "(", "self", ")", "->", "str", ":", "return", "\"etcd-v2\"" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributed/elastic/rendezvous/etcd_rendezvous_backend.py#L71-L73
papyrussolution/OpenPapyrus
bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91
Src/OSF/protobuf-3.19.1/python/google/protobuf/message.py
python
Message.SerializePartialToString
(self, **kwargs)
Serializes the protocol message to a binary string. This method is similar to SerializeToString but doesn't check if the message is initialized. Keyword Args: deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys. Returns: bytes: A serialized representation of the partial message.
Serializes the protocol message to a binary string.
[ "Serializes", "the", "protocol", "message", "to", "a", "binary", "string", "." ]
def SerializePartialToString(self, **kwargs): """Serializes the protocol message to a binary string. This method is similar to SerializeToString but doesn't check if the message is initialized. Keyword Args: deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys. Returns: bytes: A serialized representation of the partial message. """ raise NotImplementedError
[ "def", "SerializePartialToString", "(", "self", ",", "*", "*", "kwargs", ")", ":", "raise", "NotImplementedError" ]
https://github.com/papyrussolution/OpenPapyrus/blob/bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91/Src/OSF/protobuf-3.19.1/python/google/protobuf/message.py#L217-L230
openai/atari-py
b0117f704919ed4cbbd5addcec5ec1b0fb3bff99
atari_py/ale_python_interface.py
python
ALEInterface.getScreenDims
(self)
return (width, height)
returns a tuple that contains (screen_width, screen_height)
returns a tuple that contains (screen_width, screen_height)
[ "returns", "a", "tuple", "that", "contains", "(", "screen_width", "screen_height", ")" ]
def getScreenDims(self): """returns a tuple that contains (screen_width, screen_height) """ width = ale_lib.getScreenWidth(self.obj) height = ale_lib.getScreenHeight(self.obj) return (width, height)
[ "def", "getScreenDims", "(", "self", ")", ":", "width", "=", "ale_lib", ".", "getScreenWidth", "(", "self", ".", "obj", ")", "height", "=", "ale_lib", ".", "getScreenHeight", "(", "self", ".", "obj", ")", "return", "(", "width", ",", "height", ")" ]
https://github.com/openai/atari-py/blob/b0117f704919ed4cbbd5addcec5ec1b0fb3bff99/atari_py/ale_python_interface.py#L211-L216
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/requests/utils.py
python
is_ipv4_address
(string_ip)
return True
:rtype: bool
:rtype: bool
[ ":", "rtype", ":", "bool" ]
def is_ipv4_address(string_ip): """ :rtype: bool """ try: socket.inet_aton(string_ip) except socket.error: return False return True
[ "def", "is_ipv4_address", "(", "string_ip", ")", ":", "try", ":", "socket", ".", "inet_aton", "(", "string_ip", ")", "except", "socket", ".", "error", ":", "return", "False", "return", "True" ]
https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/requests/utils.py#L637-L645
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/python/google/path_utils.py
python
FindAncestor
(start_dir, ancestor)
Finds an ancestor dir in a path. For example, FindAncestor('c:\foo\bar\baz', 'bar') would return 'c:\foo\bar'. Unlike FindUpward*, this only looks at direct path ancestors.
Finds an ancestor dir in a path.
[ "Finds", "an", "ancestor", "dir", "in", "a", "path", "." ]
def FindAncestor(start_dir, ancestor): """Finds an ancestor dir in a path. For example, FindAncestor('c:\foo\bar\baz', 'bar') would return 'c:\foo\bar'. Unlike FindUpward*, this only looks at direct path ancestors. """ start_dir = os.path.abspath(start_dir) path = start_dir while True: (parent, tail) = os.path.split(path) if tail == ancestor: return path if not tail: break path = parent raise PathNotFound("Unable to find ancestor %s in %s" % (ancestor, start_dir))
[ "def", "FindAncestor", "(", "start_dir", ",", "ancestor", ")", ":", "start_dir", "=", "os", ".", "path", ".", "abspath", "(", "start_dir", ")", "path", "=", "start_dir", "while", "True", ":", "(", "parent", ",", "tail", ")", "=", "os", ".", "path", "...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/python/google/path_utils.py#L21-L36
eric612/MobileNet-YOLO
69b4441cb3ec8d553fbdef788ad033e246f901bd
scripts/cpp_lint.py
python
_NestingState.InNamespaceBody
(self)
return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
Check if we are currently one level inside a namespace body. Returns: True if top of the stack is a namespace block, False otherwise.
Check if we are currently one level inside a namespace body.
[ "Check", "if", "we", "are", "currently", "one", "level", "inside", "a", "namespace", "body", "." ]
def InNamespaceBody(self): """Check if we are currently one level inside a namespace body. Returns: True if top of the stack is a namespace block, False otherwise. """ return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
[ "def", "InNamespaceBody", "(", "self", ")", ":", "return", "self", ".", "stack", "and", "isinstance", "(", "self", ".", "stack", "[", "-", "1", "]", ",", "_NamespaceInfo", ")" ]
https://github.com/eric612/MobileNet-YOLO/blob/69b4441cb3ec8d553fbdef788ad033e246f901bd/scripts/cpp_lint.py#L1944-L1950
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/analysis.py
python
compute_dead_maps
(cfg, blocks, live_map, var_def_map)
return _dead_maps_result(internal=internal_dead_map, escaping=escaping_dead_map, combined=combined)
Compute the end-of-live information for variables. `live_map` contains a mapping of block offset to all the living variables at the ENTRY of the block.
Compute the end-of-live information for variables. `live_map` contains a mapping of block offset to all the living variables at the ENTRY of the block.
[ "Compute", "the", "end", "-", "of", "-", "live", "information", "for", "variables", ".", "live_map", "contains", "a", "mapping", "of", "block", "offset", "to", "all", "the", "living", "variables", "at", "the", "ENTRY", "of", "the", "block", "." ]
def compute_dead_maps(cfg, blocks, live_map, var_def_map): """ Compute the end-of-live information for variables. `live_map` contains a mapping of block offset to all the living variables at the ENTRY of the block. """ # The following three dictionaries will be # { block offset -> set of variables to delete } # all vars that should be deleted at the start of the successors escaping_dead_map = defaultdict(set) # all vars that should be deleted within this block internal_dead_map = defaultdict(set) # all vars that should be deleted after the function exit exit_dead_map = defaultdict(set) for offset, ir_block in blocks.items(): # live vars WITHIN the block will include all the locally # defined variables cur_live_set = live_map[offset] | var_def_map[offset] # vars alive in the outgoing blocks outgoing_live_map = dict((out_blk, live_map[out_blk]) for out_blk, _data in cfg.successors(offset)) # vars to keep alive for the terminator terminator_liveset = set(v.name for v in ir_block.terminator.list_vars()) # vars to keep alive in the successors combined_liveset = reduce(operator.or_, outgoing_live_map.values(), set()) # include variables used in terminator combined_liveset |= terminator_liveset # vars that are dead within the block because they are not # propagated to any outgoing blocks internal_set = cur_live_set - combined_liveset internal_dead_map[offset] = internal_set # vars that escape this block escaping_live_set = cur_live_set - internal_set for out_blk, new_live_set in outgoing_live_map.items(): # successor should delete the unused escaped vars new_live_set = new_live_set | var_def_map[out_blk] escaping_dead_map[out_blk] |= escaping_live_set - new_live_set # if no outgoing blocks if not outgoing_live_map: # insert var used by terminator exit_dead_map[offset] = terminator_liveset # Verify that the dead maps cover all live variables all_vars = reduce(operator.or_, live_map.values(), set()) internal_dead_vars = reduce(operator.or_, internal_dead_map.values(), set()) escaping_dead_vars = reduce(operator.or_, escaping_dead_map.values(), set()) exit_dead_vars = reduce(operator.or_, exit_dead_map.values(), set()) dead_vars = (internal_dead_vars | escaping_dead_vars | exit_dead_vars) missing_vars = all_vars - dead_vars if missing_vars: # There are no exit points if not cfg.exit_points(): # We won't be able to verify this pass else: msg = 'liveness info missing for vars: {0}'.format(missing_vars) raise RuntimeError(msg) combined = dict((k, internal_dead_map[k] | escaping_dead_map[k]) for k in blocks) return _dead_maps_result(internal=internal_dead_map, escaping=escaping_dead_map, combined=combined)
[ "def", "compute_dead_maps", "(", "cfg", ",", "blocks", ",", "live_map", ",", "var_def_map", ")", ":", "# The following three dictionaries will be", "# { block offset -> set of variables to delete }", "# all vars that should be deleted at the start of the successors", "escaping_dead_map...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/analysis.py#L118-L187
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/cr/cr/loader.py
python
Scan
()
Scans from the cr package down, loading modules as needed. This finds all packages and modules below the cr package, by scanning the file system. It imports all the packages, and then runs post import hooks on each module to do any automated work. One example of this is the hook that finds all classes that extend AutoExport and copies them up into the cr namespace directly. Modules are allowed to refer to each other, their import will be retried until it succeeds or no progress can be made on any module.
Scans from the cr package down, loading modules as needed.
[ "Scans", "from", "the", "cr", "package", "down", "loading", "modules", "as", "needed", "." ]
def Scan(): """Scans from the cr package down, loading modules as needed. This finds all packages and modules below the cr package, by scanning the file system. It imports all the packages, and then runs post import hooks on each module to do any automated work. One example of this is the hook that finds all classes that extend AutoExport and copies them up into the cr namespace directly. Modules are allowed to refer to each other, their import will be retried until it succeeds or no progress can be made on any module. """ modules = _ScanPackage(cr) # Now scan all the found modules one more time. # This happens after all imports, in case any imports register scan hooks. for module in modules: _ScanModule(module)
[ "def", "Scan", "(", ")", ":", "modules", "=", "_ScanPackage", "(", "cr", ")", "# Now scan all the found modules one more time.", "# This happens after all imports, in case any imports register scan hooks.", "for", "module", "in", "modules", ":", "_ScanModule", "(", "module", ...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/cr/cr/loader.py#L110-L126
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Tools/webchecker/tktools.py
python
make_canvas
(parent, width=0, height=0, hbar=1, vbar=1, fill=BOTH, expand=1, pack=1, class_=None, name=None, takefocus=None)
return widget, frame
Subroutine to create a canvas. Like make_text_box().
Subroutine to create a canvas.
[ "Subroutine", "to", "create", "a", "canvas", "." ]
def make_canvas(parent, width=0, height=0, hbar=1, vbar=1, fill=BOTH, expand=1, pack=1, class_=None, name=None, takefocus=None): """Subroutine to create a canvas. Like make_text_box(). """ hbar, vbar, frame = make_scrollbars(parent, hbar, vbar, pack, class_=class_, name=name, takefocus=takefocus) widget = Canvas(frame, scrollregion=(0, 0, width, height), name="canvas") if width: widget.config(width=width) if height: widget.config(height=height) widget.pack(expand=expand, fill=fill, side=LEFT) set_scroll_commands(widget, hbar, vbar) return widget, frame
[ "def", "make_canvas", "(", "parent", ",", "width", "=", "0", ",", "height", "=", "0", ",", "hbar", "=", "1", ",", "vbar", "=", "1", ",", "fill", "=", "BOTH", ",", "expand", "=", "1", ",", "pack", "=", "1", ",", "class_", "=", "None", ",", "na...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Tools/webchecker/tktools.py#L185-L206
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/formats/format.py
python
EngFormatter.__call__
(self, num: Union[int, float])
return formatted
Formats a number in engineering notation, appending a letter representing the power of 1000 of the original number. Some examples: >>> format_eng(0) # for self.accuracy = 0 ' 0' >>> format_eng(1000000) # for self.accuracy = 1, # self.use_eng_prefix = True ' 1.0M' >>> format_eng("-1e-6") # for self.accuracy = 2 # self.use_eng_prefix = False '-1.00E-06' @param num: the value to represent @type num: either a numeric value or a string that can be converted to a numeric value (as per decimal.Decimal constructor) @return: engineering formatted string
Formats a number in engineering notation, appending a letter representing the power of 1000 of the original number. Some examples:
[ "Formats", "a", "number", "in", "engineering", "notation", "appending", "a", "letter", "representing", "the", "power", "of", "1000", "of", "the", "original", "number", ".", "Some", "examples", ":" ]
def __call__(self, num: Union[int, float]) -> str: """ Formats a number in engineering notation, appending a letter representing the power of 1000 of the original number. Some examples: >>> format_eng(0) # for self.accuracy = 0 ' 0' >>> format_eng(1000000) # for self.accuracy = 1, # self.use_eng_prefix = True ' 1.0M' >>> format_eng("-1e-6") # for self.accuracy = 2 # self.use_eng_prefix = False '-1.00E-06' @param num: the value to represent @type num: either a numeric value or a string that can be converted to a numeric value (as per decimal.Decimal constructor) @return: engineering formatted string """ dnum = decimal.Decimal(str(num)) if decimal.Decimal.is_nan(dnum): return "NaN" if decimal.Decimal.is_infinite(dnum): return "inf" sign = 1 if dnum < 0: # pragma: no cover sign = -1 dnum = -dnum if dnum != 0: pow10 = decimal.Decimal(int(math.floor(dnum.log10() / 3) * 3)) else: pow10 = decimal.Decimal(0) pow10 = pow10.min(max(self.ENG_PREFIXES.keys())) pow10 = pow10.max(min(self.ENG_PREFIXES.keys())) int_pow10 = int(pow10) if self.use_eng_prefix: prefix = self.ENG_PREFIXES[int_pow10] else: if int_pow10 < 0: prefix = "E-{pow10:02d}".format(pow10=-int_pow10) else: prefix = "E+{pow10:02d}".format(pow10=int_pow10) mant = sign * dnum / (10 ** pow10) if self.accuracy is None: # pragma: no cover format_str = "{mant: g}{prefix}" else: format_str = "{{mant: .{acc:d}f}}{{prefix}}".format(acc=self.accuracy) formatted = format_str.format(mant=mant, prefix=prefix) return formatted
[ "def", "__call__", "(", "self", ",", "num", ":", "Union", "[", "int", ",", "float", "]", ")", "->", "str", ":", "dnum", "=", "decimal", ".", "Decimal", "(", "str", "(", "num", ")", ")", "if", "decimal", ".", "Decimal", ".", "is_nan", "(", "dnum",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/formats/format.py#L1840-L1901
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/io/netcdf.py
python
netcdf_file.__init__
(self, filename, mode='r', mmap=None, version=1, maskandscale=False)
Initialize netcdf_file from fileobj (str or file-like).
Initialize netcdf_file from fileobj (str or file-like).
[ "Initialize", "netcdf_file", "from", "fileobj", "(", "str", "or", "file", "-", "like", ")", "." ]
def __init__(self, filename, mode='r', mmap=None, version=1, maskandscale=False): """Initialize netcdf_file from fileobj (str or file-like).""" if mode not in 'rwa': raise ValueError("Mode must be either 'r', 'w' or 'a'.") if hasattr(filename, 'seek'): # file-like self.fp = filename self.filename = 'None' if mmap is None: mmap = False elif mmap and not hasattr(filename, 'fileno'): raise ValueError('Cannot use file object for mmap') else: # maybe it's a string self.filename = filename omode = 'r+' if mode == 'a' else mode self.fp = open(self.filename, '%sb' % omode) if mmap is None: # Mmapped files on PyPy cannot be usually closed # before the GC runs, so it's better to use mmap=False # as the default. mmap = (not IS_PYPY) if mode != 'r': # Cannot read write-only files mmap = False self.use_mmap = mmap self.mode = mode self.version_byte = version self.maskandscale = maskandscale self.dimensions = OrderedDict() self.variables = OrderedDict() self._dims = [] self._recs = 0 self._recsize = 0 self._mm = None self._mm_buf = None if self.use_mmap: self._mm = mm.mmap(self.fp.fileno(), 0, access=mm.ACCESS_READ) self._mm_buf = np.frombuffer(self._mm, dtype=np.int8) self._attributes = OrderedDict() if mode in 'ra': self._read()
[ "def", "__init__", "(", "self", ",", "filename", ",", "mode", "=", "'r'", ",", "mmap", "=", "None", ",", "version", "=", "1", ",", "maskandscale", "=", "False", ")", ":", "if", "mode", "not", "in", "'rwa'", ":", "raise", "ValueError", "(", "\"Mode mu...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/io/netcdf.py#L236-L284
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TStrPool.Cmp
(self, *args)
return _snap.TStrPool_Cmp(self, *args)
Cmp(TStrPool self, uint const & Offset, char const * Str) -> int Parameters: Offset: uint const & Str: char const *
Cmp(TStrPool self, uint const & Offset, char const * Str) -> int
[ "Cmp", "(", "TStrPool", "self", "uint", "const", "&", "Offset", "char", "const", "*", "Str", ")", "-", ">", "int" ]
def Cmp(self, *args): """ Cmp(TStrPool self, uint const & Offset, char const * Str) -> int Parameters: Offset: uint const & Str: char const * """ return _snap.TStrPool_Cmp(self, *args)
[ "def", "Cmp", "(", "self", ",", "*", "args", ")", ":", "return", "_snap", ".", "TStrPool_Cmp", "(", "self", ",", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L11699-L11708
PlatformLab/Arachne
e67391471007174dd4002dc2c160628e19c284e8
scripts/cpplint.py
python
_SetCountingStyle
(level)
Sets the module's counting options.
Sets the module's counting options.
[ "Sets", "the", "module", "s", "counting", "options", "." ]
def _SetCountingStyle(level): """Sets the module's counting options.""" _cpplint_state.SetCountingStyle(level)
[ "def", "_SetCountingStyle", "(", "level", ")", ":", "_cpplint_state", ".", "SetCountingStyle", "(", "level", ")" ]
https://github.com/PlatformLab/Arachne/blob/e67391471007174dd4002dc2c160628e19c284e8/scripts/cpplint.py#L964-L966
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py
python
CalculateGeneratorInputInfo
(params)
Called by __init__ to initialize generator values based on params.
Called by __init__ to initialize generator values based on params.
[ "Called", "by", "__init__", "to", "initialize", "generator", "values", "based", "on", "params", "." ]
def CalculateGeneratorInputInfo(params): """Called by __init__ to initialize generator values based on params.""" # E.g. "out/gypfiles" toplevel = params["options"].toplevel_dir qualified_out_dir = os.path.normpath( os.path.join(toplevel, ComputeOutputDir(params), "gypfiles") ) global generator_filelist_paths generator_filelist_paths = { "toplevel": toplevel, "qualified_out_dir": qualified_out_dir, }
[ "def", "CalculateGeneratorInputInfo", "(", "params", ")", ":", "# E.g. \"out/gypfiles\"", "toplevel", "=", "params", "[", "\"options\"", "]", ".", "toplevel_dir", "qualified_out_dir", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", ...
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py#L2060-L2072
christinaa/LLVM-VideoCore4
7773c3c9e5d22b785d4b96ed0acea37c8aa9c183
examples/Kaleidoscope/MCJIT/cached/genk-timing.py
python
TimingScriptGenerator.writeTimingCall
(self, filename, numFuncs, funcsCalled, totalCalls)
Echo some comments and invoke both versions of toy
Echo some comments and invoke both versions of toy
[ "Echo", "some", "comments", "and", "invoke", "both", "versions", "of", "toy" ]
def writeTimingCall(self, filename, numFuncs, funcsCalled, totalCalls): """Echo some comments and invoke both versions of toy""" rootname = filename if '.' in filename: rootname = filename[:filename.rfind('.')] self.shfile.write("echo \"%s: Calls %d of %d functions, %d total\" >> %s\n" % (filename, funcsCalled, numFuncs, totalCalls, self.timeFile)) self.shfile.write("echo \"\" >> %s\n" % self.timeFile) self.shfile.write("echo \"With MCJIT\" >> %s\n" % self.timeFile) self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"") self.shfile.write(" -o %s -a " % self.timeFile) self.shfile.write("./toy-mcjit < %s > %s-mcjit.out 2> %s-mcjit.err\n" % (filename, rootname, rootname)) self.shfile.write("echo \"\" >> %s\n" % self.timeFile) self.shfile.write("echo \"With JIT\" >> %s\n" % self.timeFile) self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"") self.shfile.write(" -o %s -a " % self.timeFile) self.shfile.write("./toy-jit < %s > %s-jit.out 2> %s-jit.err\n" % (filename, rootname, rootname)) self.shfile.write("echo \"\" >> %s\n" % self.timeFile) self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
[ "def", "writeTimingCall", "(", "self", ",", "filename", ",", "numFuncs", ",", "funcsCalled", ",", "totalCalls", ")", ":", "rootname", "=", "filename", "if", "'.'", "in", "filename", ":", "rootname", "=", "filename", "[", ":", "filename", ".", "rfind", "(",...
https://github.com/christinaa/LLVM-VideoCore4/blob/7773c3c9e5d22b785d4b96ed0acea37c8aa9c183/examples/Kaleidoscope/MCJIT/cached/genk-timing.py#L13-L30
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/resource_variable_ops.py
python
BaseResourceVariable.create
(self)
return self._initializer_op
The op responsible for initializing this variable.
The op responsible for initializing this variable.
[ "The", "op", "responsible", "for", "initializing", "this", "variable", "." ]
def create(self): """The op responsible for initializing this variable.""" if not self._in_graph_mode: raise RuntimeError("This operation is not supported " "when eager execution is enabled.") return self._initializer_op
[ "def", "create", "(", "self", ")", ":", "if", "not", "self", ".", "_in_graph_mode", ":", "raise", "RuntimeError", "(", "\"This operation is not supported \"", "\"when eager execution is enabled.\"", ")", "return", "self", ".", "_initializer_op" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/resource_variable_ops.py#L593-L598
cmu-sei/pharos
af54b6ada58d50c046fa899452addce80e9ce8da
tools/ooanalyzer/ida/OOAnalyzer.py
python
PyOOAnalyzer.parse
(self)
return [True, "OK"]
Parse the JSON object into a Python dictionary. Parse methods are responsible for properly setting the type of data. addresses are always base 16 and offsets are always in base 10
Parse the JSON object into a Python dictionary. Parse methods are responsible for properly setting the type of data. addresses are always base 16 and offsets are always in base 10
[ "Parse", "the", "JSON", "object", "into", "a", "Python", "dictionary", ".", "Parse", "methods", "are", "responsible", "for", "properly", "setting", "the", "type", "of", "data", ".", "addresses", "are", "always", "base", "16", "and", "offsets", "are", "always...
def parse(self): """ Parse the JSON object into a Python dictionary. Parse methods are responsible for properly setting the type of data. addresses are always base 16 and offsets are always in base 10 """ def _byteify(data): # if this is a unicode string, return its string representation if python_version_2: if isinstance(data, basestring): return str(data.encode('utf-8').decode()) else: if isinstance(data, str): return str(data.encode('utf-8').decode()) # if this is a list of values, return list of byteified values if isinstance(data, list): return [_byteify(item) for item in data] # if this is a dictionary, return dictionary of byteified keys and values # but only if we haven't already byteified it if isinstance(data, dict): if python_version_2: return { _byteify(key): _byteify(value) for key, value in data.iteritems() } else: return { _byteify(key): _byteify(value) for key, value in data.items() } # if it's anything else, return it in its original form return data if self.__json_data == None: return [False, "File not specified"] data = None try: data = json.loads(self.__json_data, object_hook=_byteify) except Exception as e: print("JSON parsing error: %s" % e) return [False, "JSON parsing error: %s" % e] file_version = data["version"] if "version" in data else "unknown" if file_version != EXPECTED_JSON_VERSION: return [False, "Expected JSON version '%s' but found '%s' instead. Aborting." % (EXPECTED_JSON_VERSION, file_version)] if "filemd5" in data: jsonMd5 = data["filemd5"] # Some IDA give a binary encoded version, and some give it in ascii already! idaMd5 = idautils.GetInputFileMD5() idaMd52 = codecs.encode(idaMd5, 'hex').decode("ascii") if jsonMd5.lower () != idaMd5.lower () and jsonMd5.lower () != idaMd52.lower (): print (jsonMd5, idaMd5) if ida_kernwin.ask_yn(ida_kernwin.ASKBTN_YES, "There was a hash mismatch. This JSON may be for a different file '%s'. Do you want to import anyway?" % data["filename"]) == ida_kernwin.ASKBTN_NO: return [False, "User aborted after hash mismatch"] print("Parsing JSON structures ...") self.__parse_structs(data["structures"]) print("Completed Parsing JSON structures file: %s classes found" % len(self.__classes)) self.__parse_vf_calls(data['vcalls']) print("Completed Parsing JSON class usages") self.__is_parsed = True return [True, "OK"]
[ "def", "parse", "(", "self", ")", ":", "def", "_byteify", "(", "data", ")", ":", "# if this is a unicode string, return its string representation", "if", "python_version_2", ":", "if", "isinstance", "(", "data", ",", "basestring", ")", ":", "return", "str", "(", ...
https://github.com/cmu-sei/pharos/blob/af54b6ada58d50c046fa899452addce80e9ce8da/tools/ooanalyzer/ida/OOAnalyzer.py#L212-L276
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_gdi.py
python
Locale.AddLanguage
(*args, **kwargs)
return _gdi_.Locale_AddLanguage(*args, **kwargs)
AddLanguage(LanguageInfo info)
AddLanguage(LanguageInfo info)
[ "AddLanguage", "(", "LanguageInfo", "info", ")" ]
def AddLanguage(*args, **kwargs): """AddLanguage(LanguageInfo info)""" return _gdi_.Locale_AddLanguage(*args, **kwargs)
[ "def", "AddLanguage", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "Locale_AddLanguage", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L3075-L3077
facebookresearch/habitat-sim
63b6c71d9ca8adaefb140b198196f5d0ca1f1e34
examples/viewer.py
python
HabitatSimInteractiveViewer.mouse_release_event
(self, event: Application.MouseEvent)
Release any existing constraints.
Release any existing constraints.
[ "Release", "any", "existing", "constraints", "." ]
def mouse_release_event(self, event: Application.MouseEvent) -> None: """ Release any existing constraints. """ del self.mouse_grabber self.mouse_grabber = None event.accepted = True
[ "def", "mouse_release_event", "(", "self", ",", "event", ":", "Application", ".", "MouseEvent", ")", "->", "None", ":", "del", "self", ".", "mouse_grabber", "self", ".", "mouse_grabber", "=", "None", "event", ".", "accepted", "=", "True" ]
https://github.com/facebookresearch/habitat-sim/blob/63b6c71d9ca8adaefb140b198196f5d0ca1f1e34/examples/viewer.py#L581-L587
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_internal/req/req_install.py
python
InstallRequirement.hashes
(self, trust_internet=True)
return Hashes(good_hashes)
Return a hash-comparer that considers my option- and URL-based hashes to be known-good. Hashes in URLs--ones embedded in the requirements file, not ones downloaded from an index server--are almost peers with ones from flags. They satisfy --require-hashes (whether it was implicitly or explicitly activated) but do not activate it. md5 and sha224 are not allowed in flags, which should nudge people toward good algos. We always OR all hashes together, even ones from URLs. :param trust_internet: Whether to trust URL-based (#md5=...) hashes downloaded from the internet, as by populate_link()
Return a hash-comparer that considers my option- and URL-based hashes to be known-good.
[ "Return", "a", "hash", "-", "comparer", "that", "considers", "my", "option", "-", "and", "URL", "-", "based", "hashes", "to", "be", "known", "-", "good", "." ]
def hashes(self, trust_internet=True): # type: (bool) -> Hashes """Return a hash-comparer that considers my option- and URL-based hashes to be known-good. Hashes in URLs--ones embedded in the requirements file, not ones downloaded from an index server--are almost peers with ones from flags. They satisfy --require-hashes (whether it was implicitly or explicitly activated) but do not activate it. md5 and sha224 are not allowed in flags, which should nudge people toward good algos. We always OR all hashes together, even ones from URLs. :param trust_internet: Whether to trust URL-based (#md5=...) hashes downloaded from the internet, as by populate_link() """ good_hashes = self.options.get('hashes', {}).copy() link = self.link if trust_internet else self.original_link if link and link.hash: good_hashes.setdefault(link.hash_name, []).append(link.hash) return Hashes(good_hashes)
[ "def", "hashes", "(", "self", ",", "trust_internet", "=", "True", ")", ":", "# type: (bool) -> Hashes", "good_hashes", "=", "self", ".", "options", ".", "get", "(", "'hashes'", ",", "{", "}", ")", ".", "copy", "(", ")", "link", "=", "self", ".", "link"...
https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_internal/req/req_install.py#L255-L275
KratosMultiphysics/Kratos
0000833054ed0503424eb28205d6508d9ca6cbbc
applications/MeshingApplication/python_scripts/mmg_process.py
python
MmgProcess.__list_extender
(self, values, repetition_list)
return aux_list
Extends the list depending of a repetition parameter
Extends the list depending of a repetition parameter
[ "Extends", "the", "list", "depending", "of", "a", "repetition", "parameter" ]
def __list_extender(self, values, repetition_list): '''Extends the list depending of a repetition parameter''' aux_list = [] for value, repetition in zip(values, repetition_list): for i in range(repetition): aux_list.append(value) return aux_list
[ "def", "__list_extender", "(", "self", ",", "values", ",", "repetition_list", ")", ":", "aux_list", "=", "[", "]", "for", "value", ",", "repetition", "in", "zip", "(", "values", ",", "repetition_list", ")", ":", "for", "i", "in", "range", "(", "repetitio...
https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/MeshingApplication/python_scripts/mmg_process.py#L805-L813
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/html.py
python
HtmlWinParser_AddTagHandler
(*args, **kwargs)
return _html.HtmlWinParser_AddTagHandler(*args, **kwargs)
HtmlWinParser_AddTagHandler(PyObject tagHandlerClass)
HtmlWinParser_AddTagHandler(PyObject tagHandlerClass)
[ "HtmlWinParser_AddTagHandler", "(", "PyObject", "tagHandlerClass", ")" ]
def HtmlWinParser_AddTagHandler(*args, **kwargs): """HtmlWinParser_AddTagHandler(PyObject tagHandlerClass)""" return _html.HtmlWinParser_AddTagHandler(*args, **kwargs)
[ "def", "HtmlWinParser_AddTagHandler", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_html", ".", "HtmlWinParser_AddTagHandler", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/html.py#L449-L451
yrnkrn/zapcc
c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50
tools/clang/bindings/python/clang/cindex.py
python
TranslationUnit.get_tokens
(self, locations=None, extent=None)
return TokenGroup.get_tokens(self, extent)
Obtain tokens in this translation unit. This is a generator for Token instances. The caller specifies a range of source code to obtain tokens for. The range can be specified as a 2-tuple of SourceLocation or as a SourceRange. If both are defined, behavior is undefined.
Obtain tokens in this translation unit.
[ "Obtain", "tokens", "in", "this", "translation", "unit", "." ]
def get_tokens(self, locations=None, extent=None): """Obtain tokens in this translation unit. This is a generator for Token instances. The caller specifies a range of source code to obtain tokens for. The range can be specified as a 2-tuple of SourceLocation or as a SourceRange. If both are defined, behavior is undefined. """ if locations is not None: extent = SourceRange(start=locations[0], end=locations[1]) return TokenGroup.get_tokens(self, extent)
[ "def", "get_tokens", "(", "self", ",", "locations", "=", "None", ",", "extent", "=", "None", ")", ":", "if", "locations", "is", "not", "None", ":", "extent", "=", "SourceRange", "(", "start", "=", "locations", "[", "0", "]", ",", "end", "=", "locatio...
https://github.com/yrnkrn/zapcc/blob/c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50/tools/clang/bindings/python/clang/cindex.py#L3047-L3058
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/lite/python/authoring/authoring.py
python
_Compatible._log
(self, message)
Log and print authoring warning / error message.
Log and print authoring warning / error message.
[ "Log", "and", "print", "authoring", "warning", "/", "error", "message", "." ]
def _log(self, message): """Log and print authoring warning / error message.""" self._log_messages.append(message) print(message)
[ "def", "_log", "(", "self", ",", "message", ")", ":", "self", ".", "_log_messages", ".", "append", "(", "message", ")", "print", "(", "message", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/lite/python/authoring/authoring.py#L248-L251
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tokenize.py
python
untokenize
(iterable)
return out
Transform tokens back into Python source code. It returns a bytes object, encoded using the ENCODING token, which is the first token sequence output by tokenize. Each element returned by the iterable must be a token sequence with at least two elements, a token number and token value. If only two tokens are passed, the resulting output is poor. Round-trip invariant for full input: Untokenized source will match input source exactly Round-trip invariant for limited input: # Output bytes will tokenize back to the input t1 = [tok[:2] for tok in tokenize(f.readline)] newcode = untokenize(t1) readline = BytesIO(newcode).readline t2 = [tok[:2] for tok in tokenize(readline)] assert t1 == t2
Transform tokens back into Python source code. It returns a bytes object, encoded using the ENCODING token, which is the first token sequence output by tokenize.
[ "Transform", "tokens", "back", "into", "Python", "source", "code", ".", "It", "returns", "a", "bytes", "object", "encoded", "using", "the", "ENCODING", "token", "which", "is", "the", "first", "token", "sequence", "output", "by", "tokenize", "." ]
def untokenize(iterable): """Transform tokens back into Python source code. It returns a bytes object, encoded using the ENCODING token, which is the first token sequence output by tokenize. Each element returned by the iterable must be a token sequence with at least two elements, a token number and token value. If only two tokens are passed, the resulting output is poor. Round-trip invariant for full input: Untokenized source will match input source exactly Round-trip invariant for limited input: # Output bytes will tokenize back to the input t1 = [tok[:2] for tok in tokenize(f.readline)] newcode = untokenize(t1) readline = BytesIO(newcode).readline t2 = [tok[:2] for tok in tokenize(readline)] assert t1 == t2 """ ut = Untokenizer() out = ut.untokenize(iterable) if ut.encoding is not None: out = out.encode(ut.encoding) return out
[ "def", "untokenize", "(", "iterable", ")", ":", "ut", "=", "Untokenizer", "(", ")", "out", "=", "ut", ".", "untokenize", "(", "iterable", ")", "if", "ut", ".", "encoding", "is", "not", "None", ":", "out", "=", "out", ".", "encode", "(", "ut", ".", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tokenize.py#L312-L336
seqan/seqan
f5f658343c366c9c3d44ba358ffc9317e78a09ed
util/py_lib/pyratemp.py
python
EvalPseudoSandbox.compile
(self, expr)
return self._compile_cache[expr]
Compile a python-eval-expression. - Use a compile-cache. - Raise a `NameError` if `expr` contains a name beginning with ``_``. :Returns: the compiled `expr` :Exceptions: - `SyntaxError`: for compile-errors - `NameError`: if expr contains a name beginning with ``_``
Compile a python-eval-expression.
[ "Compile", "a", "python", "-", "eval", "-", "expression", "." ]
def compile(self, expr): """Compile a python-eval-expression. - Use a compile-cache. - Raise a `NameError` if `expr` contains a name beginning with ``_``. :Returns: the compiled `expr` :Exceptions: - `SyntaxError`: for compile-errors - `NameError`: if expr contains a name beginning with ``_`` """ if expr not in self._compile_cache: c = compile(expr, "", "eval") # TODO(holtgrew): Disabling the breakout check here so our code works in Python 2.6. #for i in c.co_names: #prevent breakout via new-style-classes # if i[0] == '_': # raise NameError("Name '%s' is not allowed." %(i)) self._compile_cache[expr] = c return self._compile_cache[expr]
[ "def", "compile", "(", "self", ",", "expr", ")", ":", "if", "expr", "not", "in", "self", ".", "_compile_cache", ":", "c", "=", "compile", "(", "expr", ",", "\"\"", ",", "\"eval\"", ")", "# TODO(holtgrew): Disabling the breakout check here so our code works in Pyth...
https://github.com/seqan/seqan/blob/f5f658343c366c9c3d44ba358ffc9317e78a09ed/util/py_lib/pyratemp.py#L830-L848
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/_lobpcg.py
python
LOBPCG.run
(self)
Run LOBPCG iterations. Use this method as a template for implementing LOBPCG iteration scheme with custom tracker that is compatible with TorchScript.
Run LOBPCG iterations.
[ "Run", "LOBPCG", "iterations", "." ]
def run(self): """Run LOBPCG iterations. Use this method as a template for implementing LOBPCG iteration scheme with custom tracker that is compatible with TorchScript. """ self.update() if not torch.jit.is_scripting() and self.tracker is not None: self.call_tracker() while not self.stop_iteration(): self.update() if not torch.jit.is_scripting() and self.tracker is not None: self.call_tracker()
[ "def", "run", "(", "self", ")", ":", "self", ".", "update", "(", ")", "if", "not", "torch", ".", "jit", ".", "is_scripting", "(", ")", "and", "self", ".", "tracker", "is", "not", "None", ":", "self", ".", "call_tracker", "(", ")", "while", "not", ...
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/_lobpcg.py#L774-L791
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/device/cuda/__init__.py
python
_set_current_stream
(stream)
return core._set_current_stream(stream)
Set the current stream. Parameters: stream(paddle.device.cuda.Stream): The selected stream. Returns: CUDAStream: The previous stream.
Set the current stream.
[ "Set", "the", "current", "stream", "." ]
def _set_current_stream(stream): ''' Set the current stream. Parameters: stream(paddle.device.cuda.Stream): The selected stream. Returns: CUDAStream: The previous stream. ''' if not isinstance(stream, paddle.device.cuda.Stream): raise TypeError("stream type should be paddle.device.cuda.Stream") cur_stream = current_stream() if id(stream) == id(cur_stream): return stream return core._set_current_stream(stream)
[ "def", "_set_current_stream", "(", "stream", ")", ":", "if", "not", "isinstance", "(", "stream", ",", "paddle", ".", "device", ".", "cuda", ".", "Stream", ")", ":", "raise", "TypeError", "(", "\"stream type should be paddle.device.cuda.Stream\"", ")", "cur_stream"...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/device/cuda/__init__.py#L152-L170