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
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py3/setuptools/_distutils/command/install.py
python
install.finalize_unix
(self)
Finalizes options for posix platforms.
Finalizes options for posix platforms.
[ "Finalizes", "options", "for", "posix", "platforms", "." ]
def finalize_unix(self): """Finalizes options for posix platforms.""" if self.install_base is not None or self.install_platbase is not None: if ((self.install_lib is None and self.install_purelib is None and self.install_platlib is None) or self.install_headers is None or self.install_scripts is None or self.install_data is None): raise DistutilsOptionError( "install-base or install-platbase supplied, but " "installation scheme is incomplete") return if self.user: if self.install_userbase is None: raise DistutilsPlatformError( "User base directory is not specified") self.install_base = self.install_platbase = self.install_userbase self.select_scheme("posix_user") elif self.home is not None: self.install_base = self.install_platbase = self.home self.select_scheme("posix_home") else: if self.prefix is None: if self.exec_prefix is not None: raise DistutilsOptionError( "must not supply exec-prefix without prefix") # Allow Fedora to add components to the prefix _prefix_addition = getattr(sysconfig, '_prefix_addition', "") self.prefix = ( os.path.normpath(sys.prefix) + _prefix_addition) self.exec_prefix = ( os.path.normpath(sys.exec_prefix) + _prefix_addition) else: if self.exec_prefix is None: self.exec_prefix = self.prefix self.install_base = self.prefix self.install_platbase = self.exec_prefix self.select_scheme("posix_prefix")
[ "def", "finalize_unix", "(", "self", ")", ":", "if", "self", ".", "install_base", "is", "not", "None", "or", "self", ".", "install_platbase", "is", "not", "None", ":", "if", "(", "(", "self", ".", "install_lib", "is", "None", "and", "self", ".", "insta...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/_distutils/command/install.py#L445-L488
Slicer/SlicerGitSVNArchive
65e92bb16c2b32ea47a1a66bee71f238891ee1ca
Base/Python/slicer/util.py
python
saveScene
(filename, properties={})
return app.coreIOManager().saveNodes(filetype, properties)
Save the current scene. Based on the value of 'filename', the current scene is saved either as a MRML file, MRB file or directory. If filename ends with '.mrml', the scene is saved as a single file without associated data. If filename ends with '.mrb', the scene is saved as a MRML bundle (Zip archive with scene and data files). In every other case, the scene is saved in the directory specified by 'filename'. Both MRML scene file and data will be written to disk. If needed, directories and sub-directories will be created.
Save the current scene.
[ "Save", "the", "current", "scene", "." ]
def saveScene(filename, properties={}): """Save the current scene. Based on the value of 'filename', the current scene is saved either as a MRML file, MRB file or directory. If filename ends with '.mrml', the scene is saved as a single file without associated data. If filename ends with '.mrb', the scene is saved as a MRML bundle (Zip archive with scene and data files). In every other case, the scene is saved in the directory specified by 'filename'. Both MRML scene file and data will be written to disk. If needed, directories and sub-directories will be created. """ from slicer import app filetype = 'SceneFile' properties['fileName'] = filename return app.coreIOManager().saveNodes(filetype, properties)
[ "def", "saveScene", "(", "filename", ",", "properties", "=", "{", "}", ")", ":", "from", "slicer", "import", "app", "filetype", "=", "'SceneFile'", "properties", "[", "'fileName'", "]", "=", "filename", "return", "app", ".", "coreIOManager", "(", ")", ".",...
https://github.com/Slicer/SlicerGitSVNArchive/blob/65e92bb16c2b32ea47a1a66bee71f238891ee1ca/Base/Python/slicer/util.py#L668-L688
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/indexes/base.py
python
_maybe_cast_data_without_dtype
(subarr: np.ndarray)
return result
If we have an arraylike input but no passed dtype, try to infer a supported dtype. Parameters ---------- subarr : np.ndarray[object] Returns ------- np.ndarray or ExtensionArray
If we have an arraylike input but no passed dtype, try to infer a supported dtype.
[ "If", "we", "have", "an", "arraylike", "input", "but", "no", "passed", "dtype", "try", "to", "infer", "a", "supported", "dtype", "." ]
def _maybe_cast_data_without_dtype(subarr: np.ndarray) -> ArrayLike: """ If we have an arraylike input but no passed dtype, try to infer a supported dtype. Parameters ---------- subarr : np.ndarray[object] Returns ------- np.ndarray or ExtensionArray """ result = lib.maybe_convert_objects( subarr, convert_datetime=True, convert_timedelta=True, convert_period=True, convert_interval=True, dtype_if_all_nat=np.dtype("datetime64[ns]"), ) if result.dtype.kind in ["b", "c"]: return subarr result = ensure_wrapped_if_datetimelike(result) return result
[ "def", "_maybe_cast_data_without_dtype", "(", "subarr", ":", "np", ".", "ndarray", ")", "->", "ArrayLike", ":", "result", "=", "lib", ".", "maybe_convert_objects", "(", "subarr", ",", "convert_datetime", "=", "True", ",", "convert_timedelta", "=", "True", ",", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/indexes/base.py#L6397-L6422
cvxpy/cvxpy
5165b4fb750dfd237de8659383ef24b4b2e33aaf
cvxpy/atoms/elementwise/minimum.py
python
minimum.is_decr
(self, idx)
return False
Is the composition non-increasing in argument idx?
Is the composition non-increasing in argument idx?
[ "Is", "the", "composition", "non", "-", "increasing", "in", "argument", "idx?" ]
def is_decr(self, idx) -> bool: """Is the composition non-increasing in argument idx? """ return False
[ "def", "is_decr", "(", "self", ",", "idx", ")", "->", "bool", ":", "return", "False" ]
https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/atoms/elementwise/minimum.py#L74-L77
acbull/Unbiased_LambdaMart
7c39abe5caa18ca07df2d23c2db392916d92956c
Unbias_LightGBM/python-package/lightgbm/basic.py
python
_InnerPredictor.__get_num_preds
(self, num_iteration, nrow, predict_type)
return n_preds.value
Get size of prediction result
Get size of prediction result
[ "Get", "size", "of", "prediction", "result" ]
def __get_num_preds(self, num_iteration, nrow, predict_type): """ Get size of prediction result """ n_preds = ctypes.c_int64(0) _safe_call(_LIB.LGBM_BoosterCalcNumPredict( self.handle, ctypes.c_int(nrow), ctypes.c_int(predict_type), ctypes.c_int(num_iteration), ctypes.byref(n_preds))) return n_preds.value
[ "def", "__get_num_preds", "(", "self", ",", "num_iteration", ",", "nrow", ",", "predict_type", ")", ":", "n_preds", "=", "ctypes", ".", "c_int64", "(", "0", ")", "_safe_call", "(", "_LIB", ".", "LGBM_BoosterCalcNumPredict", "(", "self", ".", "handle", ",", ...
https://github.com/acbull/Unbiased_LambdaMart/blob/7c39abe5caa18ca07df2d23c2db392916d92956c/Unbias_LightGBM/python-package/lightgbm/basic.py#L464-L475
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/gestures.py
python
MouseGestures.OnMotion
(self, event)
Internal. Used if Start() has been run
Internal. Used if Start() has been run
[ "Internal", ".", "Used", "if", "Start", "()", "has", "been", "run" ]
def OnMotion(self, event): '''Internal. Used if Start() has been run''' if self.recording: currentposition = event.GetPosition() if self.lastposition != (-1, -1): self.rawgesture += self.GetDirection(self.lastposition, currentposition) if self.showgesture: #Draw it! px1, py1 = self.parent.ClientToScreen(self.lastposition) px2, py2 = self.parent.ClientToScreen(currentposition) self.dc.DrawLine(px1, py1, px2, py2) self.lastposition = currentposition event.Skip()
[ "def", "OnMotion", "(", "self", ",", "event", ")", ":", "if", "self", ".", "recording", ":", "currentposition", "=", "event", ".", "GetPosition", "(", ")", "if", "self", ".", "lastposition", "!=", "(", "-", "1", ",", "-", "1", ")", ":", "self", "."...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/gestures.py#L237-L251
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/stc.py
python
StyledTextCtrl.AutoCompSetMaxWidth
(*args, **kwargs)
return _stc.StyledTextCtrl_AutoCompSetMaxWidth(*args, **kwargs)
AutoCompSetMaxWidth(self, int characterCount) Set the maximum width, in characters, of auto-completion and user lists. Set to 0 to autosize to fit longest item, which is the default.
AutoCompSetMaxWidth(self, int characterCount)
[ "AutoCompSetMaxWidth", "(", "self", "int", "characterCount", ")" ]
def AutoCompSetMaxWidth(*args, **kwargs): """ AutoCompSetMaxWidth(self, int characterCount) Set the maximum width, in characters, of auto-completion and user lists. Set to 0 to autosize to fit longest item, which is the default. """ return _stc.StyledTextCtrl_AutoCompSetMaxWidth(*args, **kwargs)
[ "def", "AutoCompSetMaxWidth", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_AutoCompSetMaxWidth", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/stc.py#L3236-L3243
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
python/MooseDocs/extensions/bibtex.py
python
BibtexExtension.preRead
(self, page)
Initialize the page citations list.
Initialize the page citations list.
[ "Initialize", "the", "page", "citations", "list", "." ]
def preRead(self, page): """Initialize the page citations list.""" page['citations'] = list()
[ "def", "preRead", "(", "self", ",", "page", ")", ":", "page", "[", "'citations'", "]", "=", "list", "(", ")" ]
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/MooseDocs/extensions/bibtex.py#L82-L84
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/graph_editor/transform.py
python
Transformer._transform_sgv
(self, sgv)
return sgv_.remap(input_map_, output_map_)
Transform a subgraph view. For convenience, a transform operation returns a subgraph view of the transformed graph. Args: sgv: the subgraph to be transformed. Returns: The transformed subgraph.
Transform a subgraph view.
[ "Transform", "a", "subgraph", "view", "." ]
def _transform_sgv(self, sgv): """Transform a subgraph view. For convenience, a transform operation returns a subgraph view of the transformed graph. Args: sgv: the subgraph to be transformed. Returns: The transformed subgraph. """ ops_ = [op_ for _, op_ in iteritems(self._info.transformed_ops)] sgv_ = subgraph.SubGraphView(ops_) sgv_inputs_ = sgv_.inputs sgv_outputs_ = sgv_.outputs # re-order inputs input_map_ = [] for input_t in sgv.inputs: if input_t not in self._info.transformed_ts: continue input_t_ = self._info.transformed_ts[input_t] if input_t_ not in sgv_inputs_: continue input_t_index_ = sgv_.input_index(input_t_) input_map_.append(input_t_index_) # re-order outputs output_map_ = [] for output_t in sgv.outputs: if output_t not in self._info.transformed_ts: continue output_t_ = self._info.transformed_ts[output_t] if output_t_ not in sgv_outputs_: continue output_t_index_ = sgv_.output_index(output_t_) output_map_.append(output_t_index_) return sgv_.remap(input_map_, output_map_)
[ "def", "_transform_sgv", "(", "self", ",", "sgv", ")", ":", "ops_", "=", "[", "op_", "for", "_", ",", "op_", "in", "iteritems", "(", "self", ".", "_info", ".", "transformed_ops", ")", "]", "sgv_", "=", "subgraph", ".", "SubGraphView", "(", "ops_", ")...
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/graph_editor/transform.py#L270-L308
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/android/loading/cloud/frontend/clovis_frontend.py
python
Root
()
return flask.render_template('form.html')
Home page: show the new task form.
Home page: show the new task form.
[ "Home", "page", ":", "show", "the", "new", "task", "form", "." ]
def Root(): """Home page: show the new task form.""" return flask.render_template('form.html')
[ "def", "Root", "(", ")", ":", "return", "flask", ".", "render_template", "(", "'form.html'", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/android/loading/cloud/frontend/clovis_frontend.py#L518-L520
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/common/battor/battor/battor_wrapper.py
python
BattorWrapper._SendBattorCommandImpl
(self, cmd)
return self._battor_shell.stdout.readline()
Sends command to the BattOr.
Sends command to the BattOr.
[ "Sends", "command", "to", "the", "BattOr", "." ]
def _SendBattorCommandImpl(self, cmd): """Sends command to the BattOr.""" self._battor_shell.stdin.write('%s\n' % cmd) self._battor_shell.stdin.flush() return self._battor_shell.stdout.readline()
[ "def", "_SendBattorCommandImpl", "(", "self", ",", "cmd", ")", ":", "self", ".", "_battor_shell", ".", "stdin", ".", "write", "(", "'%s\\n'", "%", "cmd", ")", "self", ".", "_battor_shell", ".", "stdin", ".", "flush", "(", ")", "return", "self", ".", "_...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/common/battor/battor/battor_wrapper.py#L226-L230
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/webkit.py
python
WebKitNewWindowEvent.__init__
(self, *args, **kwargs)
__init__(self, Window win=None) -> WebKitNewWindowEvent
__init__(self, Window win=None) -> WebKitNewWindowEvent
[ "__init__", "(", "self", "Window", "win", "=", "None", ")", "-", ">", "WebKitNewWindowEvent" ]
def __init__(self, *args, **kwargs): """__init__(self, Window win=None) -> WebKitNewWindowEvent""" _webkit.WebKitNewWindowEvent_swiginit(self,_webkit.new_WebKitNewWindowEvent(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_webkit", ".", "WebKitNewWindowEvent_swiginit", "(", "self", ",", "_webkit", ".", "new_WebKitNewWindowEvent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/webkit.py#L278-L280
arangodb/arangodb
0d658689c7d1b721b314fa3ca27d38303e1570c8
3rdParty/V8/v7.9.317/third_party/jinja2/filters.py
python
do_unique
(environment, value, case_sensitive=False, attribute=None)
Returns a list of unique items from the the given iterable. .. sourcecode:: jinja {{ ['foo', 'bar', 'foobar', 'FooBar']|unique }} -> ['foo', 'bar', 'foobar'] The unique items are yielded in the same order as their first occurrence in the iterable passed to the filter. :param case_sensitive: Treat upper and lower case strings as distinct. :param attribute: Filter objects with unique values for this attribute.
Returns a list of unique items from the the given iterable.
[ "Returns", "a", "list", "of", "unique", "items", "from", "the", "the", "given", "iterable", "." ]
def do_unique(environment, value, case_sensitive=False, attribute=None): """Returns a list of unique items from the the given iterable. .. sourcecode:: jinja {{ ['foo', 'bar', 'foobar', 'FooBar']|unique }} -> ['foo', 'bar', 'foobar'] The unique items are yielded in the same order as their first occurrence in the iterable passed to the filter. :param case_sensitive: Treat upper and lower case strings as distinct. :param attribute: Filter objects with unique values for this attribute. """ getter = make_attrgetter( environment, attribute, postprocess=ignore_case if not case_sensitive else None ) seen = set() for item in value: key = getter(item) if key not in seen: seen.add(key) yield item
[ "def", "do_unique", "(", "environment", ",", "value", ",", "case_sensitive", "=", "False", ",", "attribute", "=", "None", ")", ":", "getter", "=", "make_attrgetter", "(", "environment", ",", "attribute", ",", "postprocess", "=", "ignore_case", "if", "not", "...
https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/v7.9.317/third_party/jinja2/filters.py#L282-L307
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/BeautifulSoup.py
python
Tag.__init__
(self, parser, name, attrs=None, parent=None, previous=None)
Basic constructor.
Basic constructor.
[ "Basic", "constructor", "." ]
def __init__(self, parser, name, attrs=None, parent=None, previous=None): "Basic constructor." # We don't actually store the parser object: that lets extracted # chunks be garbage-collected self.parserClass = parser.__class__ self.isSelfClosing = parser.isSelfClosingTag(name) self.name = name if attrs is None: attrs = [] elif isinstance(attrs, dict): attrs = attrs.items() self.attrs = attrs self.contents = [] self.setup(parent, previous) self.hidden = False self.containsSubstitutions = False self.convertHTMLEntities = parser.convertHTMLEntities self.convertXMLEntities = parser.convertXMLEntities self.escapeUnrecognizedEntities = parser.escapeUnrecognizedEntities # Convert any HTML, XML, or numeric entities in the attribute values. convert = lambda(k, val): (k, re.sub("&(#\d+|#x[0-9a-fA-F]+|\w+);", self._convertEntities, val)) self.attrs = map(convert, self.attrs)
[ "def", "__init__", "(", "self", ",", "parser", ",", "name", ",", "attrs", "=", "None", ",", "parent", "=", "None", ",", "previous", "=", "None", ")", ":", "# We don't actually store the parser object: that lets extracted", "# chunks be garbage-collected", "self", "....
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/BeautifulSoup.py#L523-L550
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/distlib/metadata.py
python
LegacyMetadata.write_file
(self, fileobject, skip_unknown=False)
Write the PKG-INFO format data to a file object.
Write the PKG-INFO format data to a file object.
[ "Write", "the", "PKG", "-", "INFO", "format", "data", "to", "a", "file", "object", "." ]
def write_file(self, fileobject, skip_unknown=False): """Write the PKG-INFO format data to a file object.""" self.set_metadata_version() for field in _version2fieldlist(self['Metadata-Version']): values = self.get(field) if skip_unknown and values in ('UNKNOWN', [], ['UNKNOWN']): continue if field in _ELEMENTSFIELD: self._write_field(fileobject, field, ','.join(values)) continue if field not in _LISTFIELDS: if field == 'Description': if self.metadata_version in ('1.0', '1.1'): values = values.replace('\n', '\n ') else: values = values.replace('\n', '\n |') values = [values] if field in _LISTTUPLEFIELDS: values = [','.join(value) for value in values] for value in values: self._write_field(fileobject, field, value)
[ "def", "write_file", "(", "self", ",", "fileobject", ",", "skip_unknown", "=", "False", ")", ":", "self", ".", "set_metadata_version", "(", ")", "for", "field", "in", "_version2fieldlist", "(", "self", "[", "'Metadata-Version'", "]", ")", ":", "values", "=",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/distlib/metadata.py#L374-L397
fifengine/fifengine
4b62c42e85bec19893cef8e63e6855927cff2c47
engine/python/fife/extensions/pychan/attrs.py
python
UnicodeAttr.parse
(self,value)
return str(value)
Parses a value and checks for errors. Override with specialiced behaviour.
Parses a value and checks for errors. Override with specialiced behaviour.
[ "Parses", "a", "value", "and", "checks", "for", "errors", ".", "Override", "with", "specialiced", "behaviour", "." ]
def parse(self,value): """ Parses a value and checks for errors. Override with specialiced behaviour. """ return str(value)
[ "def", "parse", "(", "self", ",", "value", ")", ":", "return", "str", "(", "value", ")" ]
https://github.com/fifengine/fifengine/blob/4b62c42e85bec19893cef8e63e6855927cff2c47/engine/python/fife/extensions/pychan/attrs.py#L73-L78
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/grid.py
python
GridCellTextEditor.GetValue
(*args, **kwargs)
return _grid.GridCellTextEditor_GetValue(*args, **kwargs)
GetValue(self) -> String
GetValue(self) -> String
[ "GetValue", "(", "self", ")", "-", ">", "String" ]
def GetValue(*args, **kwargs): """GetValue(self) -> String""" return _grid.GridCellTextEditor_GetValue(*args, **kwargs)
[ "def", "GetValue", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "GridCellTextEditor_GetValue", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/grid.py#L422-L424
v8mips/v8mips
f0c9cc0bbfd461c7f516799d9a58e9a7395f737e
tools/js2c.py
python
WriteStartupBlob
(sources, startup_blob)
Write a startup blob, as expected by V8 Initialize ... TODO(vogelheim): Add proper method name. Args: sources: A Sources instance with the prepared sources. startup_blob_file: Name of file to write the blob to.
Write a startup blob, as expected by V8 Initialize ... TODO(vogelheim): Add proper method name.
[ "Write", "a", "startup", "blob", "as", "expected", "by", "V8", "Initialize", "...", "TODO", "(", "vogelheim", ")", ":", "Add", "proper", "method", "name", "." ]
def WriteStartupBlob(sources, startup_blob): """Write a startup blob, as expected by V8 Initialize ... TODO(vogelheim): Add proper method name. Args: sources: A Sources instance with the prepared sources. startup_blob_file: Name of file to write the blob to. """ output = open(startup_blob, "wb") debug_sources = sum(sources.is_debugger_id); PutInt(output, debug_sources) for i in xrange(debug_sources): PutStr(output, sources.names[i]); PutStr(output, sources.modules[i]); PutInt(output, len(sources.names) - debug_sources) for i in xrange(debug_sources, len(sources.names)): PutStr(output, sources.names[i]); PutStr(output, sources.modules[i]); output.close()
[ "def", "WriteStartupBlob", "(", "sources", ",", "startup_blob", ")", ":", "output", "=", "open", "(", "startup_blob", ",", "\"wb\"", ")", "debug_sources", "=", "sum", "(", "sources", ".", "is_debugger_id", ")", "PutInt", "(", "output", ",", "debug_sources", ...
https://github.com/v8mips/v8mips/blob/f0c9cc0bbfd461c7f516799d9a58e9a7395f737e/tools/js2c.py#L524-L545
epam/Indigo
30e40b4b1eb9bae0207435a26cfcb81ddcc42be1
api/python/indigo/__init__.py
python
IndigoObject.smarts
(self)
return self.dispatcher._checkResultString( Indigo._lib.indigoSmarts(self.id) )
Molecule or reaction method calculates SMARTS for the structure Returns: str: smarts string
Molecule or reaction method calculates SMARTS for the structure
[ "Molecule", "or", "reaction", "method", "calculates", "SMARTS", "for", "the", "structure" ]
def smarts(self): """Molecule or reaction method calculates SMARTS for the structure Returns: str: smarts string """ self.dispatcher._setSessionId() return self.dispatcher._checkResultString( Indigo._lib.indigoSmarts(self.id) )
[ "def", "smarts", "(", "self", ")", ":", "self", ".", "dispatcher", ".", "_setSessionId", "(", ")", "return", "self", ".", "dispatcher", ".", "_checkResultString", "(", "Indigo", ".", "_lib", ".", "indigoSmarts", "(", "self", ".", "id", ")", ")" ]
https://github.com/epam/Indigo/blob/30e40b4b1eb9bae0207435a26cfcb81ddcc42be1/api/python/indigo/__init__.py#L3424-L3433
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
third_party/python_gflags/gflags.py
python
FlagValues._AssertValidators
(self, validators)
Assert if all validators in the list are satisfied. Asserts validators in the order they were created. Args: validators: Iterable(gflags_validators.Validator), validators to be verified Raises: AttributeError: if validators work with a non-existing flag. IllegalFlagValue: if validation fails for at least one validator
Assert if all validators in the list are satisfied.
[ "Assert", "if", "all", "validators", "in", "the", "list", "are", "satisfied", "." ]
def _AssertValidators(self, validators): """Assert if all validators in the list are satisfied. Asserts validators in the order they were created. Args: validators: Iterable(gflags_validators.Validator), validators to be verified Raises: AttributeError: if validators work with a non-existing flag. IllegalFlagValue: if validation fails for at least one validator """ for validator in sorted( validators, key=lambda validator: validator.insertion_index): try: validator.Verify(self) except gflags_validators.Error, e: message = validator.PrintFlagsWithValues(self) raise IllegalFlagValue('%s: %s' % (message, str(e)))
[ "def", "_AssertValidators", "(", "self", ",", "validators", ")", ":", "for", "validator", "in", "sorted", "(", "validators", ",", "key", "=", "lambda", "validator", ":", "validator", ".", "insertion_index", ")", ":", "try", ":", "validator", ".", "Verify", ...
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/python_gflags/gflags.py#L1076-L1093
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/wheel/vendored/packaging/tags.py
python
parse_tag
(tag)
return frozenset(tags)
Parses the provided tag (e.g. `py3-none-any`) into a frozenset of Tag instances. Returning a set is required due to the possibility that the tag is a compressed tag set.
Parses the provided tag (e.g. `py3-none-any`) into a frozenset of Tag instances.
[ "Parses", "the", "provided", "tag", "(", "e", ".", "g", ".", "py3", "-", "none", "-", "any", ")", "into", "a", "frozenset", "of", "Tag", "instances", "." ]
def parse_tag(tag): # type: (str) -> FrozenSet[Tag] """ Parses the provided tag (e.g. `py3-none-any`) into a frozenset of Tag instances. Returning a set is required due to the possibility that the tag is a compressed tag set. """ tags = set() interpreters, abis, platforms = tag.split("-") for interpreter in interpreters.split("."): for abi in abis.split("."): for platform_ in platforms.split("."): tags.add(Tag(interpreter, abi, platform_)) return frozenset(tags)
[ "def", "parse_tag", "(", "tag", ")", ":", "# type: (str) -> FrozenSet[Tag]", "tags", "=", "set", "(", ")", "interpreters", ",", "abis", ",", "platforms", "=", "tag", ".", "split", "(", "\"-\"", ")", "for", "interpreter", "in", "interpreters", ".", "split", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/wheel/vendored/packaging/tags.py#L140-L154
triton-inference-server/server
11a11d9cb1e9734ed9fd305e752da70f07d1992f
qa/python_models/fini_error/model.py
python
TritonPythonModel.execute
(self, requests)
return responses
The body of this model doesn't matter. The main purpose of this model is to test correct handling of Python errors in the `finalize` function.
The body of this model doesn't matter. The main purpose of this model is to test correct handling of Python errors in the `finalize` function.
[ "The", "body", "of", "this", "model", "doesn", "t", "matter", ".", "The", "main", "purpose", "of", "this", "model", "is", "to", "test", "correct", "handling", "of", "Python", "errors", "in", "the", "finalize", "function", "." ]
def execute(self, requests): """ The body of this model doesn't matter. The main purpose of this model is to test correct handling of Python errors in the `finalize` function. """ responses = [] for request in requests: input_tensor = pb_utils.get_input_tensor_by_name(request, "IN") out_tensor = pb_utils.Tensor("OUT", input_tensor.as_numpy()) responses.append(pb_utils.InferenceResponse([out_tensor], error)) return responses
[ "def", "execute", "(", "self", ",", "requests", ")", ":", "responses", "=", "[", "]", "for", "request", "in", "requests", ":", "input_tensor", "=", "pb_utils", ".", "get_input_tensor_by_name", "(", "request", ",", "\"IN\"", ")", "out_tensor", "=", "pb_utils"...
https://github.com/triton-inference-server/server/blob/11a11d9cb1e9734ed9fd305e752da70f07d1992f/qa/python_models/fini_error/model.py#L32-L42
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/tools/inspector_protocol/jinja2/filters.py
python
do_tojson
(eval_ctx, value, indent=None)
return htmlsafe_json_dumps(value, dumper=dumper, **options)
Dumps a structure to JSON so that it's safe to use in ``<script>`` tags. It accepts the same arguments and returns a JSON string. Note that this is available in templates through the ``|tojson`` filter which will also mark the result as safe. Due to how this function escapes certain characters this is safe even if used outside of ``<script>`` tags. The following characters are escaped in strings: - ``<`` - ``>`` - ``&`` - ``'`` This makes it safe to embed such strings in any place in HTML with the notable exception of double quoted attributes. In that case single quote your attributes or HTML escape it in addition. The indent parameter can be used to enable pretty printing. Set it to the number of spaces that the structures should be indented with. Note that this filter is for use in HTML contexts only. .. versionadded:: 2.9
Dumps a structure to JSON so that it's safe to use in ``<script>`` tags. It accepts the same arguments and returns a JSON string. Note that this is available in templates through the ``|tojson`` filter which will also mark the result as safe. Due to how this function escapes certain characters this is safe even if used outside of ``<script>`` tags.
[ "Dumps", "a", "structure", "to", "JSON", "so", "that", "it", "s", "safe", "to", "use", "in", "<script", ">", "tags", ".", "It", "accepts", "the", "same", "arguments", "and", "returns", "a", "JSON", "string", ".", "Note", "that", "this", "is", "availabl...
def do_tojson(eval_ctx, value, indent=None): """Dumps a structure to JSON so that it's safe to use in ``<script>`` tags. It accepts the same arguments and returns a JSON string. Note that this is available in templates through the ``|tojson`` filter which will also mark the result as safe. Due to how this function escapes certain characters this is safe even if used outside of ``<script>`` tags. The following characters are escaped in strings: - ``<`` - ``>`` - ``&`` - ``'`` This makes it safe to embed such strings in any place in HTML with the notable exception of double quoted attributes. In that case single quote your attributes or HTML escape it in addition. The indent parameter can be used to enable pretty printing. Set it to the number of spaces that the structures should be indented with. Note that this filter is for use in HTML contexts only. .. versionadded:: 2.9 """ policies = eval_ctx.environment.policies dumper = policies['json.dumps_function'] options = policies['json.dumps_kwargs'] if indent is not None: options = dict(options) options['indent'] = indent return htmlsafe_json_dumps(value, dumper=dumper, **options)
[ "def", "do_tojson", "(", "eval_ctx", ",", "value", ",", "indent", "=", "None", ")", ":", "policies", "=", "eval_ctx", ".", "environment", ".", "policies", "dumper", "=", "policies", "[", "'json.dumps_function'", "]", "options", "=", "policies", "[", "'json.d...
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/inspector_protocol/jinja2/filters.py#L1047-L1078
NVIDIA/DALI
bf16cc86ba8f091b145f91962f21fe1b6aff243d
dali/python/nvidia/dali/external_source.py
python
_ExternalSourceGroup.get_batch
(self, pipeline, batch_size, epoch_idx)
return _ExternalDataBatch(self, pipeline, callback_out, batch_size)
Call the source callback and feed the results to the ExternalSource nodes in `pipeline`. Used for the sequential ExternalSource variant.
Call the source callback and feed the results to the ExternalSource nodes in `pipeline`. Used for the sequential ExternalSource variant.
[ "Call", "the", "source", "callback", "and", "feed", "the", "results", "to", "the", "ExternalSource", "nodes", "in", "pipeline", ".", "Used", "for", "the", "sequential", "ExternalSource", "variant", "." ]
def get_batch(self, pipeline, batch_size, epoch_idx): """Call the source callback and feed the results to the ExternalSource nodes in `pipeline`. Used for the sequential ExternalSource variant.""" try: if self.batch: callback_out = self.callback(*self.callback_args(None, epoch_idx)) else: callback_out = [self.callback(*self.callback_args(i, epoch_idx)) for i in range(batch_size)] self.current_sample += batch_size self.current_iter += 1 except StopIteration: self.reset_indices() raise return _ExternalDataBatch(self, pipeline, callback_out, batch_size)
[ "def", "get_batch", "(", "self", ",", "pipeline", ",", "batch_size", ",", "epoch_idx", ")", ":", "try", ":", "if", "self", ".", "batch", ":", "callback_out", "=", "self", ".", "callback", "(", "*", "self", ".", "callback_args", "(", "None", ",", "epoch...
https://github.com/NVIDIA/DALI/blob/bf16cc86ba8f091b145f91962f21fe1b6aff243d/dali/python/nvidia/dali/external_source.py#L212-L225
microsoft/DirectXShaderCompiler
8348ff8d9e0287610ba05d3a828e10af981a1c05
tools/clang/utils/check_cfc/check_cfc.py
python
derive_output_file
(args)
Derive output file from the input file (if just one) or None otherwise.
Derive output file from the input file (if just one) or None otherwise.
[ "Derive", "output", "file", "from", "the", "input", "file", "(", "if", "just", "one", ")", "or", "None", "otherwise", "." ]
def derive_output_file(args): """Derive output file from the input file (if just one) or None otherwise.""" infile = get_input_file(args) if infile is None: return None else: return '{}.o'.format(os.path.splitext(infile)[0])
[ "def", "derive_output_file", "(", "args", ")", ":", "infile", "=", "get_input_file", "(", "args", ")", "if", "infile", "is", "None", ":", "return", "None", "else", ":", "return", "'{}.o'", ".", "format", "(", "os", ".", "path", ".", "splitext", "(", "i...
https://github.com/microsoft/DirectXShaderCompiler/blob/8348ff8d9e0287610ba05d3a828e10af981a1c05/tools/clang/utils/check_cfc/check_cfc.py#L118-L125
fengbingchun/NN_Test
d6305825d5273e4569ccd1eda9ffa2a9c72e18d2
src/tiny-dnn/third_party/cpplint.py
python
CheckPosixThreading
(filename, clean_lines, linenum, error)
Checks for calls to thread-unsafe functions. Much code has been originally written without consideration of multi-threading. Also, engineers are relying on their old experience; they have learned posix before threading extensions were added. These tests guide the engineers to use thread-safe functions (when using posix directly). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Checks for calls to thread-unsafe functions.
[ "Checks", "for", "calls", "to", "thread", "-", "unsafe", "functions", "." ]
def CheckPosixThreading(filename, clean_lines, linenum, error): """Checks for calls to thread-unsafe functions. Much code has been originally written without consideration of multi-threading. Also, engineers are relying on their old experience; they have learned posix before threading extensions were added. These tests guide the engineers to use thread-safe functions (when using posix directly). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] for single_thread_func, multithread_safe_func, pattern in _THREADING_LIST: # Additional pattern matching check to confirm that this is the # function we are looking for if Search(pattern, line): error(filename, linenum, 'runtime/threadsafe_fn', 2, 'Consider using ' + multithread_safe_func + '...) instead of ' + single_thread_func + '...) for improved thread safety.')
[ "def", "CheckPosixThreading", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "for", "single_thread_func", ",", "multithread_safe_func", ",", "pattern", "in", "_THREADIN...
https://github.com/fengbingchun/NN_Test/blob/d6305825d5273e4569ccd1eda9ffa2a9c72e18d2/src/tiny-dnn/third_party/cpplint.py#L2227-L2250
funnyzhou/Adaptive_Feeding
9c78182331d8c0ea28de47226e805776c638d46f
lib/fast_rcnn/nms_wrapper.py
python
nms
(dets, thresh, force_cpu=False)
Dispatch to either CPU or GPU NMS implementations.
Dispatch to either CPU or GPU NMS implementations.
[ "Dispatch", "to", "either", "CPU", "or", "GPU", "NMS", "implementations", "." ]
def nms(dets, thresh, force_cpu=False): """Dispatch to either CPU or GPU NMS implementations.""" if dets.shape[0] == 0: return [] if cfg.USE_GPU_NMS and not force_cpu: return gpu_nms(dets, thresh, device_id=cfg.GPU_ID) else: return cpu_nms(dets, thresh)
[ "def", "nms", "(", "dets", ",", "thresh", ",", "force_cpu", "=", "False", ")", ":", "if", "dets", ".", "shape", "[", "0", "]", "==", "0", ":", "return", "[", "]", "if", "cfg", ".", "USE_GPU_NMS", "and", "not", "force_cpu", ":", "return", "gpu_nms",...
https://github.com/funnyzhou/Adaptive_Feeding/blob/9c78182331d8c0ea28de47226e805776c638d46f/lib/fast_rcnn/nms_wrapper.py#L12-L20
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/contrib/distributions/python/ops/beta.py
python
Beta.dtype
(self)
return self._a_b_sum.dtype
dtype of samples from this distribution.
dtype of samples from this distribution.
[ "dtype", "of", "samples", "from", "this", "distribution", "." ]
def dtype(self): """dtype of samples from this distribution.""" return self._a_b_sum.dtype
[ "def", "dtype", "(", "self", ")", ":", "return", "self", ".", "_a_b_sum", ".", "dtype" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/beta.py#L169-L171
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_controls.py
python
ComboBox.SetMark
(*args, **kwargs)
return _controls_.ComboBox_SetMark(*args, **kwargs)
SetMark(self, long from, long to) Selects the text between the two positions in the combobox text field.
SetMark(self, long from, long to)
[ "SetMark", "(", "self", "long", "from", "long", "to", ")" ]
def SetMark(*args, **kwargs): """ SetMark(self, long from, long to) Selects the text between the two positions in the combobox text field. """ return _controls_.ComboBox_SetMark(*args, **kwargs)
[ "def", "SetMark", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ComboBox_SetMark", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L611-L617
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/incubate/fleet/base/role_maker.py
python
GeneralRoleMaker.is_worker
(self)
return self._role == Role.WORKER
whether current process is worker
whether current process is worker
[ "whether", "current", "process", "is", "worker" ]
def is_worker(self): """ whether current process is worker """ if not self._role_is_generated: self.generate_role() return self._role == Role.WORKER
[ "def", "is_worker", "(", "self", ")", ":", "if", "not", "self", ".", "_role_is_generated", ":", "self", ".", "generate_role", "(", ")", "return", "self", ".", "_role", "==", "Role", ".", "WORKER" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/incubate/fleet/base/role_maker.py#L802-L808
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
EvtHandler.Bind
(self, event, handler, source=None, id=wx.ID_ANY, id2=wx.ID_ANY)
Bind an event to an event handler. :param event: One of the EVT_* objects that specifies the type of event to bind, :param handler: A callable object to be invoked when the event is delivered to self. Pass None to disconnect an event handler. :param source: Sometimes the event originates from a different window than self, but you still want to catch it in self. (For example, a button event delivered to a frame.) By passing the source of the event, the event handling system is able to differentiate between the same event type from different controls. :param id: Used to spcify the event source by ID instead of instance. :param id2: Used when it is desirable to bind a handler to a range of IDs, such as with EVT_MENU_RANGE.
Bind an event to an event handler.
[ "Bind", "an", "event", "to", "an", "event", "handler", "." ]
def Bind(self, event, handler, source=None, id=wx.ID_ANY, id2=wx.ID_ANY): """ Bind an event to an event handler. :param event: One of the EVT_* objects that specifies the type of event to bind, :param handler: A callable object to be invoked when the event is delivered to self. Pass None to disconnect an event handler. :param source: Sometimes the event originates from a different window than self, but you still want to catch it in self. (For example, a button event delivered to a frame.) By passing the source of the event, the event handling system is able to differentiate between the same event type from different controls. :param id: Used to spcify the event source by ID instead of instance. :param id2: Used when it is desirable to bind a handler to a range of IDs, such as with EVT_MENU_RANGE. """ assert isinstance(event, wx.PyEventBinder) assert handler is None or callable(handler) assert source is None or hasattr(source, 'GetId') if source is not None: id = source.GetId() event.Bind(self, id, id2, handler)
[ "def", "Bind", "(", "self", ",", "event", ",", "handler", ",", "source", "=", "None", ",", "id", "=", "wx", ".", "ID_ANY", ",", "id2", "=", "wx", ".", "ID_ANY", ")", ":", "assert", "isinstance", "(", "event", ",", "wx", ".", "PyEventBinder", ")", ...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L4197-L4228
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/internals/blocks.py
python
Block.take_nd
(self, indexer, axis, new_mgr_locs=None, fill_tuple=None)
Take values according to indexer and return them as a block.bb
Take values according to indexer and return them as a block.bb
[ "Take", "values", "according", "to", "indexer", "and", "return", "them", "as", "a", "block", ".", "bb" ]
def take_nd(self, indexer, axis, new_mgr_locs=None, fill_tuple=None): """ Take values according to indexer and return them as a block.bb """ # algos.take_nd dispatches for DatetimeTZBlock, CategoricalBlock # so need to preserve types # sparse is treated like an ndarray, but needs .get_values() shaping values = self.values if fill_tuple is None: fill_value = self.fill_value allow_fill = False else: fill_value = fill_tuple[0] allow_fill = True new_values = algos.take_nd( values, indexer, axis=axis, allow_fill=allow_fill, fill_value=fill_value ) # Called from three places in managers, all of which satisfy # this assertion assert not (axis == 0 and new_mgr_locs is None) if new_mgr_locs is None: new_mgr_locs = self.mgr_locs if not is_dtype_equal(new_values.dtype, self.dtype): return self.make_block(new_values, new_mgr_locs) else: return self.make_block_same_class(new_values, new_mgr_locs)
[ "def", "take_nd", "(", "self", ",", "indexer", ",", "axis", ",", "new_mgr_locs", "=", "None", ",", "fill_tuple", "=", "None", ")", ":", "# algos.take_nd dispatches for DatetimeTZBlock, CategoricalBlock", "# so need to preserve types", "# sparse is treated like an ndarray, but...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/internals/blocks.py#L1271-L1303
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/input.py
python
RemoveSelfDependencies
(targets)
Remove self dependencies from targets that have the prune_self_dependency variable set.
Remove self dependencies from targets that have the prune_self_dependency variable set.
[ "Remove", "self", "dependencies", "from", "targets", "that", "have", "the", "prune_self_dependency", "variable", "set", "." ]
def RemoveSelfDependencies(targets): """Remove self dependencies from targets that have the prune_self_dependency variable set.""" for target_name, target_dict in targets.iteritems(): for dependency_key in dependency_sections: dependencies = target_dict.get(dependency_key, []) if dependencies: for t in dependencies: if t == target_name: if targets[t].get('variables', {}).get('prune_self_dependency', 0): target_dict[dependency_key] = Filter(dependencies, target_name)
[ "def", "RemoveSelfDependencies", "(", "targets", ")", ":", "for", "target_name", ",", "target_dict", "in", "targets", ".", "iteritems", "(", ")", ":", "for", "dependency_key", "in", "dependency_sections", ":", "dependencies", "=", "target_dict", ".", "get", "(",...
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/input.py#L1488-L1498
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/find-kth-largest-xor-coordinate-value.py
python
Solution.kthLargestValue
(self, matrix, k)
return vals[k-1]
:type matrix: List[List[int]] :type k: int :rtype: int
:type matrix: List[List[int]] :type k: int :rtype: int
[ ":", "type", "matrix", ":", "List", "[", "List", "[", "int", "]]", ":", "type", "k", ":", "int", ":", "rtype", ":", "int" ]
def kthLargestValue(self, matrix, k): """ :type matrix: List[List[int]] :type k: int :rtype: int """ def nth_element(nums, n, compare=lambda a, b: a < b): def tri_partition(nums, left, right, target, compare): mid = left while mid <= right: if nums[mid] == target: mid += 1 elif compare(nums[mid], target): nums[left], nums[mid] = nums[mid], nums[left] left += 1 mid += 1 else: nums[mid], nums[right] = nums[right], nums[mid] right -= 1 return left, right left, right = 0, len(nums)-1 while left <= right: pivot_idx = random.randint(left, right) pivot_left, pivot_right = tri_partition(nums, left, right, nums[pivot_idx], compare) if pivot_left <= n <= pivot_right: return elif pivot_left > n: right = pivot_left-1 else: # pivot_right < n. left = pivot_right+1 vals = [] for r in xrange(len(matrix)): curr = 0 for c in xrange(len(matrix[0])): curr = curr^matrix[r][c] if r == 0: matrix[r][c] = curr else: matrix[r][c] = curr^matrix[r-1][c] vals.append(matrix[r][c]) nth_element(vals, k-1, compare=lambda a, b: a > b) return vals[k-1]
[ "def", "kthLargestValue", "(", "self", ",", "matrix", ",", "k", ")", ":", "def", "nth_element", "(", "nums", ",", "n", ",", "compare", "=", "lambda", "a", ",", "b", ":", "a", "<", "b", ")", ":", "def", "tri_partition", "(", "nums", ",", "left", "...
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/find-kth-largest-xor-coordinate-value.py#L8-L52
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/ensemble/bagging.py
python
BaggingClassifier._validate_estimator
(self)
Check the estimator and set the base_estimator_ attribute.
Check the estimator and set the base_estimator_ attribute.
[ "Check", "the", "estimator", "and", "set", "the", "base_estimator_", "attribute", "." ]
def _validate_estimator(self): """Check the estimator and set the base_estimator_ attribute.""" super(BaggingClassifier, self)._validate_estimator( default=DecisionTreeClassifier())
[ "def", "_validate_estimator", "(", "self", ")", ":", "super", "(", "BaggingClassifier", ",", "self", ")", ".", "_validate_estimator", "(", "default", "=", "DecisionTreeClassifier", "(", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/ensemble/bagging.py#L571-L574
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/closure_linter/closure_linter/typeannotation.py
python
TypeAnnotation.GetNullability
(self, modifiers=True)
return TypeAnnotation.NULLABILITY_UNKNOWN
Computes whether the type may be null. Args: modifiers: Whether the modifiers ? and ! should be considered in the evaluation. Returns: True if the type allows null, False if the type is strictly non nullable and NULLABILITY_UNKNOWN if the nullability cannot be determined.
Computes whether the type may be null.
[ "Computes", "whether", "the", "type", "may", "be", "null", "." ]
def GetNullability(self, modifiers=True): """Computes whether the type may be null. Args: modifiers: Whether the modifiers ? and ! should be considered in the evaluation. Returns: True if the type allows null, False if the type is strictly non nullable and NULLABILITY_UNKNOWN if the nullability cannot be determined. """ # Explicitly marked nullable types or 'null' are nullable. if ((modifiers and self.or_null) or self.identifier == TypeAnnotation.NULL_TYPE): return True # Explicitly marked non-nullable types or non-nullable base types: if ((modifiers and self.not_null) or self.record_type or self.identifier in TypeAnnotation.NON_NULLABLE): return False # A type group is nullable if any of its elements are nullable. if self.type_group: maybe_nullable = False for sub_type in self.sub_types: nullability = sub_type.GetNullability() if nullability == self.NULLABILITY_UNKNOWN: maybe_nullable = nullability elif nullability: return True return maybe_nullable # Whitelisted types are nullable. if self.identifier.rstrip('.') in TypeAnnotation.NULLABLE_TYPE_WHITELIST: return True # All other types are unknown (most should be nullable, but # enums are not and typedefs might not be). return TypeAnnotation.NULLABILITY_UNKNOWN
[ "def", "GetNullability", "(", "self", ",", "modifiers", "=", "True", ")", ":", "# Explicitly marked nullable types or 'null' are nullable.", "if", "(", "(", "modifiers", "and", "self", ".", "or_null", ")", "or", "self", ".", "identifier", "==", "TypeAnnotation", "...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/closure_linter/closure_linter/typeannotation.py#L190-L228
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/ed_stc.py
python
EditraStc.GetBookmarks
(self)
return [line for line in range(self.GetLineCount()) if MarkIsSet(self, line)]
Gets a list of all lines containing bookmarks @return: list of line numbers
Gets a list of all lines containing bookmarks @return: list of line numbers
[ "Gets", "a", "list", "of", "all", "lines", "containing", "bookmarks", "@return", ":", "list", "of", "line", "numbers" ]
def GetBookmarks(self): """Gets a list of all lines containing bookmarks @return: list of line numbers """ MarkIsSet = ed_marker.Bookmark.IsSet return [line for line in range(self.GetLineCount()) if MarkIsSet(self, line)]
[ "def", "GetBookmarks", "(", "self", ")", ":", "MarkIsSet", "=", "ed_marker", ".", "Bookmark", ".", "IsSet", "return", "[", "line", "for", "line", "in", "range", "(", "self", ".", "GetLineCount", "(", ")", ")", "if", "MarkIsSet", "(", "self", ",", "line...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_stc.py#L343-L350
turi-code/SFrame
796b9bdfb2fa1b881d82080754643c7e68629cd2
oss_src/unity/python/sframe/data_structures/sframe.py
python
load_sframe
(filename)
return sf
Load an SFrame. The filename extension is used to determine the format automatically. This function is particularly useful for SFrames previously saved in binary format. For CSV imports the ``SFrame.read_csv`` function provides greater control. If the SFrame is in binary format, ``filename`` is actually a directory, created when the SFrame is saved. Parameters ---------- filename : string Location of the file to load. Can be a local path or a remote URL. Returns ------- out : SFrame See Also -------- SFrame.save, SFrame.read_csv Examples -------- >>> sf = graphlab.SFrame({'id':[1,2,3], 'val':['A','B','C']}) >>> sf.save('my_sframe') # 'my_sframe' is a directory >>> sf_loaded = graphlab.load_sframe('my_sframe')
Load an SFrame. The filename extension is used to determine the format automatically. This function is particularly useful for SFrames previously saved in binary format. For CSV imports the ``SFrame.read_csv`` function provides greater control. If the SFrame is in binary format, ``filename`` is actually a directory, created when the SFrame is saved.
[ "Load", "an", "SFrame", ".", "The", "filename", "extension", "is", "used", "to", "determine", "the", "format", "automatically", ".", "This", "function", "is", "particularly", "useful", "for", "SFrames", "previously", "saved", "in", "binary", "format", ".", "Fo...
def load_sframe(filename): """ Load an SFrame. The filename extension is used to determine the format automatically. This function is particularly useful for SFrames previously saved in binary format. For CSV imports the ``SFrame.read_csv`` function provides greater control. If the SFrame is in binary format, ``filename`` is actually a directory, created when the SFrame is saved. Parameters ---------- filename : string Location of the file to load. Can be a local path or a remote URL. Returns ------- out : SFrame See Also -------- SFrame.save, SFrame.read_csv Examples -------- >>> sf = graphlab.SFrame({'id':[1,2,3], 'val':['A','B','C']}) >>> sf.save('my_sframe') # 'my_sframe' is a directory >>> sf_loaded = graphlab.load_sframe('my_sframe') """ sf = SFrame(data=filename) return sf
[ "def", "load_sframe", "(", "filename", ")", ":", "sf", "=", "SFrame", "(", "data", "=", "filename", ")", "return", "sf" ]
https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/data_structures/sframe.py#L190-L218
sslab-gatech/qsym
78702ba8928519ffb9beb7859ec2f7ddce2b2fe4
third_party/pin-2.14-71313-gcc.4.4.7-linux/source/tools/Utils/and-launch.py
python
PrintDebugInfo
(params, cmd_list)
Print debug info @param params: Parameters. @type params: ScriptData. @param cmd_list: List of commands. @type cmd_list: list of strings.
Print debug info
[ "Print", "debug", "info" ]
def PrintDebugInfo(params, cmd_list): """ Print debug info @param params: Parameters. @type params: ScriptData. @param cmd_list: List of commands. @type cmd_list: list of strings. """ logging.debug('Remote working directory: %s', params.remote_dir) logging.debug('Path to android-install.tar.gz: %s', params.and_install) logging.debug('Path to busybox: %s', params.busybox) logging.debug('Path to pintool on host: %s', params.toolpath) logging.debug('Path to application: %s', params.app_path) c_list = 'List of commands:' for line in cmd_list: c_list += '\n ' + line logging.debug(c_list) logging.debug('Path to launch script: %s', params.launch_script_path) logging.debug('Launch script:\n%s', params.script)
[ "def", "PrintDebugInfo", "(", "params", ",", "cmd_list", ")", ":", "logging", ".", "debug", "(", "'Remote working directory: %s'", ",", "params", ".", "remote_dir", ")", "logging", ".", "debug", "(", "'Path to android-install.tar.gz: %s'", ",", "params", ".", ...
https://github.com/sslab-gatech/qsym/blob/78702ba8928519ffb9beb7859ec2f7ddce2b2fe4/third_party/pin-2.14-71313-gcc.4.4.7-linux/source/tools/Utils/and-launch.py#L248-L268
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/urllib3/contrib/_securetransport/low_level.py
python
_is_cert
(item)
return CoreFoundation.CFGetTypeID(item) == expected
Returns True if a given CFTypeRef is a certificate.
Returns True if a given CFTypeRef is a certificate.
[ "Returns", "True", "if", "a", "given", "CFTypeRef", "is", "a", "certificate", "." ]
def _is_cert(item): """ Returns True if a given CFTypeRef is a certificate. """ expected = Security.SecCertificateGetTypeID() return CoreFoundation.CFGetTypeID(item) == expected
[ "def", "_is_cert", "(", "item", ")", ":", "expected", "=", "Security", ".", "SecCertificateGetTypeID", "(", ")", "return", "CoreFoundation", ".", "CFGetTypeID", "(", "item", ")", "==", "expected" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/urllib3/contrib/_securetransport/low_level.py#L150-L155
Ewenwan/MVision
97b394dfa48cb21c82cd003b1a952745e413a17f
CNN/SSD/coco_vgg16-ssd-300-300/ssd_detect.py
python
CaffeDetection.detect
(self, image_file, conf_thresh=0.5, topn=5)
return result
SSD detection
SSD detection
[ "SSD", "detection" ]
def detect(self, image_file, conf_thresh=0.5, topn=5): ''' SSD detection ''' # set net to batch size of 1 # image_resize = 300 # 1张图片 3通道 300*300 self.net.blobs['data'].reshape(1, 3, self.image_resize, self.image_resize) image = caffe.io.load_image(image_file) # Run the net and examine the top_k results transformed_image = self.transformer.preprocess('data', image) self.net.blobs['data'].data[...] = transformed_image # 模型前向传播 并且获取 detection_out 层的输出 detections = self.net.forward()['detection_out'] # 模型输出 解码 det_label = detections[0,0,:,1]# 标签索引 det_conf = detections[0,0,:,2] # 可信度 det_xmin = detections[0,0,:,3] # 坐标 det_ymin = detections[0,0,:,4] det_xmax = detections[0,0,:,5] det_ymax = detections[0,0,:,6] # 获取可行度大于 0.5的索引 top_indices = [i for i, conf in enumerate(det_conf) if conf >= conf_thresh] top_conf = det_conf[top_indices]# 可信度 top_label_indices = det_label[top_indices].tolist()# 标签索引 top_labels = get_labelname(self.labelmap, top_label_indices)# 标签字符串 top_xmin = det_xmin[top_indices]# 坐标 0~1小数 top_ymin = det_ymin[top_indices] top_xmax = det_xmax[top_indices] top_ymax = det_ymax[top_indices] # 前5个 result = [] for i in xrange(min(topn, top_conf.shape[0])):# 前5个 xmin = top_xmin[i] # xmin = int(round(top_xmin[i] * image.shape[1])) ymin = top_ymin[i] # ymin = int(round(top_ymin[i] * image.shape[0])) xmax = top_xmax[i] # xmax = int(round(top_xmax[i] * image.shape[1])) ymax = top_ymax[i] # ymax = int(round(top_ymax[i] * image.shape[0])) score = top_conf[i]# 预测得分 label = int(top_label_indices[i])#标签id label_name = top_labels[i]#标签字符串 result.append([xmin, ymin, xmax, ymax, label, score, label_name]) # result[i][0] xmin # result[i][1] ymin # result[i][2] xmax # result[i][3] ymax # result[i][4] label # result[i][5] score # result[i][6] label_name return result
[ "def", "detect", "(", "self", ",", "image_file", ",", "conf_thresh", "=", "0.5", ",", "topn", "=", "5", ")", ":", "# set net to batch size of 1", "# image_resize = 300 # 1张图片 3通道 300*300", "self", ".", "net", ".", "blobs", "[", "'data'", "]", ".", "reshape", "...
https://github.com/Ewenwan/MVision/blob/97b394dfa48cb21c82cd003b1a952745e413a17f/CNN/SSD/coco_vgg16-ssd-300-300/ssd_detect.py#L70-L121
rapidsai/cudf
d5b2448fc69f17509304d594f029d0df56984962
python/cudf/cudf/core/indexed_frame.py
python
IndexedFrame.drop_duplicates
( self, subset=None, keep="first", nulls_are_equal=True, ignore_index=False, )
return self._from_columns_like_self( libcudf.stream_compaction.drop_duplicates( list(self._columns) if ignore_index else list(self._index._columns + self._columns), keys=keys, keep=keep, nulls_are_equal=nulls_are_equal, ), self._column_names, self._index.names if not ignore_index else None, )
Drop duplicate rows in frame. subset : list, optional List of columns to consider when dropping rows. keep : ["first", "last", False] "first" will keep the first duplicate entry, "last" will keep the last duplicate entry, and False will drop all duplicates. nulls_are_equal: bool, default True Null elements are considered equal to other null elements. ignore_index: bool, default False If True, the resulting axis will be labeled 0, 1, ..., n - 1.
Drop duplicate rows in frame.
[ "Drop", "duplicate", "rows", "in", "frame", "." ]
def drop_duplicates( self, subset=None, keep="first", nulls_are_equal=True, ignore_index=False, ): """ Drop duplicate rows in frame. subset : list, optional List of columns to consider when dropping rows. keep : ["first", "last", False] "first" will keep the first duplicate entry, "last" will keep the last duplicate entry, and False will drop all duplicates. nulls_are_equal: bool, default True Null elements are considered equal to other null elements. ignore_index: bool, default False If True, the resulting axis will be labeled 0, 1, ..., n - 1. """ if subset is None: subset = self._column_names elif ( not np.iterable(subset) or isinstance(subset, str) or isinstance(subset, tuple) and subset in self._data.names ): subset = (subset,) diff = set(subset) - set(self._data) if len(diff) != 0: raise KeyError(f"columns {diff} do not exist") subset_cols = [name for name in self._column_names if name in subset] if len(subset_cols) == 0: return self.copy(deep=True) keys = self._positions_from_column_names( subset, offset_by_index_columns=not ignore_index ) return self._from_columns_like_self( libcudf.stream_compaction.drop_duplicates( list(self._columns) if ignore_index else list(self._index._columns + self._columns), keys=keys, keep=keep, nulls_are_equal=nulls_are_equal, ), self._column_names, self._index.names if not ignore_index else None, )
[ "def", "drop_duplicates", "(", "self", ",", "subset", "=", "None", ",", "keep", "=", "\"first\"", ",", "nulls_are_equal", "=", "True", ",", "ignore_index", "=", "False", ",", ")", ":", "if", "subset", "is", "None", ":", "subset", "=", "self", ".", "_co...
https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/indexed_frame.py#L652-L702
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/ops/data_flow_ops.py
python
QueueBase.name
(self)
return self._queue_ref.op.name
The name of the underlying queue.
The name of the underlying queue.
[ "The", "name", "of", "the", "underlying", "queue", "." ]
def name(self): """The name of the underlying queue.""" return self._queue_ref.op.name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_queue_ref", ".", "op", ".", "name" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/data_flow_ops.py#L201-L203
tfwu/FaceDetection-ConvNet-3D
f9251c48eb40c5aec8fba7455115c355466555be
python/build/lib.linux-x86_64-2.7/mxnet/ndarray.py
python
NDArray.__setitem__
(self, in_slice, value)
Set ndarray value
Set ndarray value
[ "Set", "ndarray", "value" ]
def __setitem__(self, in_slice, value): """Set ndarray value""" if not self.writable: raise ValueError('trying to assign to a readonly NDArray') if not isinstance(in_slice, slice) or in_slice.step is not None: raise ValueError('NDArray only support continuous slicing on axis 0') if in_slice.start is not None or in_slice.stop is not None: sliced_arr = self._slice(in_slice.start, in_slice.stop) sliced_arr[:] = value return if isinstance(value, NDArray): if value.handle is not self.handle: value.copyto(self) elif isinstance(value, numeric_types): NDArray._set_value(float(value), out=self) elif isinstance(value, (np.ndarray, np.generic)): self._sync_copyfrom(value) else: raise TypeError('type %s not supported' % str(type(value)))
[ "def", "__setitem__", "(", "self", ",", "in_slice", ",", "value", ")", ":", "if", "not", "self", ".", "writable", ":", "raise", "ValueError", "(", "'trying to assign to a readonly NDArray'", ")", "if", "not", "isinstance", "(", "in_slice", ",", "slice", ")", ...
https://github.com/tfwu/FaceDetection-ConvNet-3D/blob/f9251c48eb40c5aec8fba7455115c355466555be/python/build/lib.linux-x86_64-2.7/mxnet/ndarray.py#L189-L207
balloonwj/TeamTalk
dc79c40687e4c9d7bec07ff5c9782be586fd9b41
win-client/3rdParty/src/json/devtools/batchbuild.py
python
BuildDesc.merged_with
( self, build_desc )
return BuildDesc( self.prepend_envs + build_desc.prepend_envs, self.variables + build_desc.variables, build_desc.build_type or self.build_type, build_desc.generator or self.generator )
Returns a new BuildDesc by merging field content. Prefer build_desc fields to self fields for single valued field.
Returns a new BuildDesc by merging field content. Prefer build_desc fields to self fields for single valued field.
[ "Returns", "a", "new", "BuildDesc", "by", "merging", "field", "content", ".", "Prefer", "build_desc", "fields", "to", "self", "fields", "for", "single", "valued", "field", "." ]
def merged_with( self, build_desc ): """Returns a new BuildDesc by merging field content. Prefer build_desc fields to self fields for single valued field. """ return BuildDesc( self.prepend_envs + build_desc.prepend_envs, self.variables + build_desc.variables, build_desc.build_type or self.build_type, build_desc.generator or self.generator )
[ "def", "merged_with", "(", "self", ",", "build_desc", ")", ":", "return", "BuildDesc", "(", "self", ".", "prepend_envs", "+", "build_desc", ".", "prepend_envs", ",", "self", ".", "variables", "+", "build_desc", ".", "variables", ",", "build_desc", ".", "buil...
https://github.com/balloonwj/TeamTalk/blob/dc79c40687e4c9d7bec07ff5c9782be586fd9b41/win-client/3rdParty/src/json/devtools/batchbuild.py#L20-L27
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/keras/_impl/keras/models.py
python
Sequential.get_layer
(self, name=None, index=None)
return self.model.get_layer(name, index)
Retrieve a layer that is part of the model. Returns a layer based on either its name (unique) or its index in the graph. Indices are based on order of horizontal graph traversal (bottom-up). Arguments: name: string, name of layer. index: integer, index of layer. Returns: A layer instance.
Retrieve a layer that is part of the model.
[ "Retrieve", "a", "layer", "that", "is", "part", "of", "the", "model", "." ]
def get_layer(self, name=None, index=None): """Retrieve a layer that is part of the model. Returns a layer based on either its name (unique) or its index in the graph. Indices are based on order of horizontal graph traversal (bottom-up). Arguments: name: string, name of layer. index: integer, index of layer. Returns: A layer instance. """ if not self.built: self.build() return self.model.get_layer(name, index)
[ "def", "get_layer", "(", "self", ",", "name", "=", "None", ",", "index", "=", "None", ")", ":", "if", "not", "self", ".", "built", ":", "self", ".", "build", "(", ")", "return", "self", ".", "model", ".", "get_layer", "(", "name", ",", "index", "...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/keras/_impl/keras/models.py#L539-L555
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/skia/bench/tile_analyze.py
python
main
()
Parses flags and outputs expected Skia picture bench results.
Parses flags and outputs expected Skia picture bench results.
[ "Parses", "flags", "and", "outputs", "expected", "Skia", "picture", "bench", "results", "." ]
def main(): """Parses flags and outputs expected Skia picture bench results.""" parser = optparse.OptionParser(USAGE_STRING % '%prog' + HELP_STRING) parser.add_option(OPTION_PLATFORM_SHORT, OPTION_PLATFORM, dest='plat', default=DEFAULT_PLATFORM, help='Platform to analyze. Set to DEFAULT_PLATFORM if not given.') parser.add_option(OPTION_REVISION_SHORT, OPTION_REVISION, dest='rev', help='(Mandatory) revision number to analyze.') parser.add_option(OPTION_DIR_SHORT, OPTION_DIR, dest='log_dir', default='', help=('(Optional) local directory where bench log files reside. If left ' 'empty (by default), will try to read from Google Storage.')) parser.add_option(OPTION_REPRESENTATION_ALG_SHORT, OPTION_REPRESENTATION_ALG, dest='alg', default=REPRESENTATION_ALG, help=('Bench representation algorithm. ' 'Default to "%s".' % REPRESENTATION_ALG)) (options, args) = parser.parse_args() if not (options.rev and options.rev.isdigit()): parser.error('Please provide correct mandatory flag %s' % OPTION_REVISION) return rev = int(options.rev) (js_codes, body_codes) = OutputTileAnalysis( rev, options.alg, options.log_dir, options.plat) print HTML_PREFIX + js_codes + body_codes + HTML_SUFFIX
[ "def", "main", "(", ")", ":", "parser", "=", "optparse", ".", "OptionParser", "(", "USAGE_STRING", "%", "'%prog'", "+", "HELP_STRING", ")", "parser", ".", "add_option", "(", "OPTION_PLATFORM_SHORT", ",", "OPTION_PLATFORM", ",", "dest", "=", "'plat'", ",", "d...
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/skia/bench/tile_analyze.py#L251-L275
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/WebKit/Source/bindings/scripts/v8_interface.py
python
common_key
(dicts, key)
return common(dicts, lambda d: key in d)
Returns common presence of a key across an iterable of dicts, or None. True if all dicts have the key, False if none of the dicts have the key, and None if some but not all dicts have the key.
Returns common presence of a key across an iterable of dicts, or None.
[ "Returns", "common", "presence", "of", "a", "key", "across", "an", "iterable", "of", "dicts", "or", "None", "." ]
def common_key(dicts, key): """Returns common presence of a key across an iterable of dicts, or None. True if all dicts have the key, False if none of the dicts have the key, and None if some but not all dicts have the key. """ return common(dicts, lambda d: key in d)
[ "def", "common_key", "(", "dicts", ",", "key", ")", ":", "return", "common", "(", "dicts", ",", "lambda", "d", ":", "key", "in", "d", ")" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Source/bindings/scripts/v8_interface.py#L1164-L1170
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/tools/docs/parser.py
python
ReferenceResolver._cc_link
(self, string, link_text, unused_manual_link_text, relative_path_to_root)
return '[`%s`](%s)' % (link_text, cc_relative_path)
Generate a link for a @{tensorflow::...} reference.
Generate a link for a
[ "Generate", "a", "link", "for", "a" ]
def _cc_link(self, string, link_text, unused_manual_link_text, relative_path_to_root): """Generate a link for a @{tensorflow::...} reference.""" # TODO(josh11b): Fix this hard-coding of paths. if string == 'tensorflow::ClientSession': ret = 'class/tensorflow/client-session.md' elif string == 'tensorflow::Scope': ret = 'class/tensorflow/scope.md' elif string == 'tensorflow::Status': ret = 'class/tensorflow/status.md' elif string == 'tensorflow::Tensor': ret = 'class/tensorflow/tensor.md' elif string == 'tensorflow::ops::Const': ret = 'namespace/tensorflow/ops.md#const' else: self.add_error('C++ reference not understood: "%s"' % string) return 'TODO_C++:%s' % string # relative_path_to_root gets you to api_docs/python, we go from there # to api_docs/cc, and then add ret. cc_relative_path = os.path.normpath(os.path.join( relative_path_to_root, '../cc', ret)) return '[`%s`](%s)' % (link_text, cc_relative_path)
[ "def", "_cc_link", "(", "self", ",", "string", ",", "link_text", ",", "unused_manual_link_text", ",", "relative_path_to_root", ")", ":", "# TODO(josh11b): Fix this hard-coding of paths.", "if", "string", "==", "'tensorflow::ClientSession'", ":", "ret", "=", "'class/tensor...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/tools/docs/parser.py#L374-L395
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/compiler/pycodegen.py
python
CodeGenerator._implicitNameOp
(self, prefix, name)
Emit name ops for names generated implicitly by for loops The interpreter generates names that start with a period or dollar sign. The symbol table ignores these names because they aren't present in the program text.
Emit name ops for names generated implicitly by for loops
[ "Emit", "name", "ops", "for", "names", "generated", "implicitly", "by", "for", "loops" ]
def _implicitNameOp(self, prefix, name): """Emit name ops for names generated implicitly by for loops The interpreter generates names that start with a period or dollar sign. The symbol table ignores these names because they aren't present in the program text. """ if self.optimized: self.emit(prefix + '_FAST', name) else: self.emit(prefix + '_NAME', name)
[ "def", "_implicitNameOp", "(", "self", ",", "prefix", ",", "name", ")", ":", "if", "self", ".", "optimized", ":", "self", ".", "emit", "(", "prefix", "+", "'_FAST'", ",", "name", ")", "else", ":", "self", ".", "emit", "(", "prefix", "+", "'_NAME'", ...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/compiler/pycodegen.py#L299-L309
msftguy/ssh-rd
a5f3a79daeac5844edebf01916c9613563f1c390
_3rd/boost_1_48_0/tools/build/v2/build/generators.py
python
Generator.run
(self, project, name, prop_set, sources)
Tries to invoke this generator on the given sources. Returns a list of generated targets (instances of 'virtual-target'). project: Project for which the targets are generated. name: Determines the name of 'name' attribute for all generated targets. See 'generated_targets' method. prop_set: Desired properties for generated targets. sources: Source targets.
Tries to invoke this generator on the given sources. Returns a list of generated targets (instances of 'virtual-target').
[ "Tries", "to", "invoke", "this", "generator", "on", "the", "given", "sources", ".", "Returns", "a", "list", "of", "generated", "targets", "(", "instances", "of", "virtual", "-", "target", ")", "." ]
def run (self, project, name, prop_set, sources): """ Tries to invoke this generator on the given sources. Returns a list of generated targets (instances of 'virtual-target'). project: Project for which the targets are generated. name: Determines the name of 'name' attribute for all generated targets. See 'generated_targets' method. prop_set: Desired properties for generated targets. sources: Source targets. """ if project.manager ().logger ().on (): project.manager ().logger ().log (__name__, " generator '%s'" % self.id_) project.manager ().logger ().log (__name__, " composing: '%s'" % self.composing_) if not self.composing_ and len (sources) > 1 and len (self.source_types_) > 1: raise BaseException ("Unsupported source/source_type combination") # We don't run composing generators if no name is specified. The reason # is that composing generator combines several targets, which can have # different names, and it cannot decide which name to give for produced # target. Therefore, the name must be passed. # # This in effect, means that composing generators are runnable only # at top-level of transofrmation graph, or if name is passed explicitly. # Thus, we dissallow composing generators in the middle. For example, the # transofrmation CPP -> OBJ -> STATIC_LIB -> RSP -> EXE won't be allowed # (the OBJ -> STATIC_LIB generator is composing) if not self.composing_ or name: return self.run_really (project, name, prop_set, sources) else: return []
[ "def", "run", "(", "self", ",", "project", ",", "name", ",", "prop_set", ",", "sources", ")", ":", "if", "project", ".", "manager", "(", ")", ".", "logger", "(", ")", ".", "on", "(", ")", ":", "project", ".", "manager", "(", ")", ".", "logger", ...
https://github.com/msftguy/ssh-rd/blob/a5f3a79daeac5844edebf01916c9613563f1c390/_3rd/boost_1_48_0/tools/build/v2/build/generators.py#L311-L345
scribusproject/scribus
41ec7c775a060912cf251682a8b1437f753f80f4
scribus/plugins/scripter/python/mikro.py
python
is_scripter_child
(qobj)
return found
walk up the object tree until Scripter or the root is found
walk up the object tree until Scripter or the root is found
[ "walk", "up", "the", "object", "tree", "until", "Scripter", "or", "the", "root", "is", "found" ]
def is_scripter_child(qobj): """ walk up the object tree until Scripter or the root is found """ found = False p = qobj.parent() while p and not found: if str(p.objectName()) == "Scripter": found = True break else: p = p.parent() return found
[ "def", "is_scripter_child", "(", "qobj", ")", ":", "found", "=", "False", "p", "=", "qobj", ".", "parent", "(", ")", "while", "p", "and", "not", "found", ":", "if", "str", "(", "p", ".", "objectName", "(", ")", ")", "==", "\"Scripter\"", ":", "foun...
https://github.com/scribusproject/scribus/blob/41ec7c775a060912cf251682a8b1437f753f80f4/scribus/plugins/scripter/python/mikro.py#L164-L176
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py3/prompt_toolkit/key_binding/bindings/emacs.py
python
load_emacs_shift_selection_bindings
()
return ConditionalKeyBindings(key_bindings, emacs_mode)
Bindings to select text with shift + cursor movements
Bindings to select text with shift + cursor movements
[ "Bindings", "to", "select", "text", "with", "shift", "+", "cursor", "movements" ]
def load_emacs_shift_selection_bindings() -> KeyBindingsBase: """ Bindings to select text with shift + cursor movements """ key_bindings = KeyBindings() handle = key_bindings.add def unshift_move(event: E) -> None: """ Used for the shift selection mode. When called with a shift + movement key press event, moves the cursor as if shift is not pressed. """ key = event.key_sequence[0].key if key == Keys.ShiftUp: event.current_buffer.auto_up(count=event.arg) return if key == Keys.ShiftDown: event.current_buffer.auto_down(count=event.arg) return # the other keys are handled through their readline command key_to_command: Dict[Union[Keys, str], str] = { Keys.ShiftLeft: "backward-char", Keys.ShiftRight: "forward-char", Keys.ShiftHome: "beginning-of-line", Keys.ShiftEnd: "end-of-line", Keys.ControlShiftLeft: "backward-word", Keys.ControlShiftRight: "forward-word", Keys.ControlShiftHome: "beginning-of-buffer", Keys.ControlShiftEnd: "end-of-buffer", } try: # Both the dict lookup and `get_by_name` can raise KeyError. binding = get_by_name(key_to_command[key]) except KeyError: pass else: # (`else` is not really needed here.) if isinstance(binding, Binding): # (It should always be a binding here) binding.call(event) @handle("s-left", filter=~has_selection) @handle("s-right", filter=~has_selection) @handle("s-up", filter=~has_selection) @handle("s-down", filter=~has_selection) @handle("s-home", filter=~has_selection) @handle("s-end", filter=~has_selection) @handle("c-s-left", filter=~has_selection) @handle("c-s-right", filter=~has_selection) @handle("c-s-home", filter=~has_selection) @handle("c-s-end", filter=~has_selection) def _start_selection(event: E) -> None: """ Start selection with shift + movement. """ # Take the current cursor position as the start of this selection. buff = event.current_buffer if buff.text: buff.start_selection(selection_type=SelectionType.CHARACTERS) if buff.selection_state is not None: # (`selection_state` should never be `None`, it is created by # `start_selection`.) buff.selection_state.enter_shift_mode() # Then move the cursor original_position = buff.cursor_position unshift_move(event) if buff.cursor_position == original_position: # Cursor didn't actually move - so cancel selection # to avoid having an empty selection buff.exit_selection() @handle("s-left", filter=shift_selection_mode) @handle("s-right", filter=shift_selection_mode) @handle("s-up", filter=shift_selection_mode) @handle("s-down", filter=shift_selection_mode) @handle("s-home", filter=shift_selection_mode) @handle("s-end", filter=shift_selection_mode) @handle("c-s-left", filter=shift_selection_mode) @handle("c-s-right", filter=shift_selection_mode) @handle("c-s-home", filter=shift_selection_mode) @handle("c-s-end", filter=shift_selection_mode) def _extend_selection(event: E) -> None: """ Extend the selection """ # Just move the cursor, like shift was not pressed unshift_move(event) buff = event.current_buffer if buff.selection_state is not None: if buff.cursor_position == buff.selection_state.original_cursor_position: # selection is now empty, so cancel selection buff.exit_selection() @handle(Keys.Any, filter=shift_selection_mode) def _replace_selection(event: E) -> None: """ Replace selection by what is typed """ event.current_buffer.cut_selection() get_by_name("self-insert").call(event) @handle("enter", filter=shift_selection_mode & is_multiline) def _newline(event: E) -> None: """ A newline replaces the selection """ event.current_buffer.cut_selection() event.current_buffer.newline(copy_margin=not in_paste_mode()) @handle("backspace", filter=shift_selection_mode) def _delete(event: E) -> None: """ Delete selection. """ event.current_buffer.cut_selection() @handle("c-y", filter=shift_selection_mode) def _yank(event: E) -> None: """ In shift selection mode, yanking (pasting) replace the selection. """ buff = event.current_buffer if buff.selection_state: buff.cut_selection() get_by_name("yank").call(event) # moving the cursor in shift selection mode cancels the selection @handle("left", filter=shift_selection_mode) @handle("right", filter=shift_selection_mode) @handle("up", filter=shift_selection_mode) @handle("down", filter=shift_selection_mode) @handle("home", filter=shift_selection_mode) @handle("end", filter=shift_selection_mode) @handle("c-left", filter=shift_selection_mode) @handle("c-right", filter=shift_selection_mode) @handle("c-home", filter=shift_selection_mode) @handle("c-end", filter=shift_selection_mode) def _cancel(event: E) -> None: """ Cancel selection. """ event.current_buffer.exit_selection() # we then process the cursor movement key_press = event.key_sequence[0] event.key_processor.feed(key_press, first=True) return ConditionalKeyBindings(key_bindings, emacs_mode)
[ "def", "load_emacs_shift_selection_bindings", "(", ")", "->", "KeyBindingsBase", ":", "key_bindings", "=", "KeyBindings", "(", ")", "handle", "=", "key_bindings", ".", "add", "def", "unshift_move", "(", "event", ":", "E", ")", "->", "None", ":", "\"\"\"\n ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/key_binding/bindings/emacs.py#L404-L557
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/corrections_tab_widget/background_corrections_model.py
python
BackgroundCorrectionsModel.__init__
(self, corrections_model: CorrectionsModel, context: MuonContext)
Initialize the BackgroundCorrectionsModel with empty data.
Initialize the BackgroundCorrectionsModel with empty data.
[ "Initialize", "the", "BackgroundCorrectionsModel", "with", "empty", "data", "." ]
def __init__(self, corrections_model: CorrectionsModel, context: MuonContext): """Initialize the BackgroundCorrectionsModel with empty data.""" self._corrections_model = corrections_model self._context = context self._corrections_context = context.corrections_context
[ "def", "__init__", "(", "self", ",", "corrections_model", ":", "CorrectionsModel", ",", "context", ":", "MuonContext", ")", ":", "self", ".", "_corrections_model", "=", "corrections_model", "self", ".", "_context", "=", "context", "self", ".", "_corrections_contex...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/corrections_tab_widget/background_corrections_model.py#L182-L186
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/platform.py
python
_node
(default='')
Helper to determine the node name of this machine.
Helper to determine the node name of this machine.
[ "Helper", "to", "determine", "the", "node", "name", "of", "this", "machine", "." ]
def _node(default=''): """ Helper to determine the node name of this machine. """ try: import socket except ImportError: # No sockets... return default try: return socket.gethostname() except OSError: # Still not working... return default
[ "def", "_node", "(", "default", "=", "''", ")", ":", "try", ":", "import", "socket", "except", "ImportError", ":", "# No sockets...", "return", "default", "try", ":", "return", "socket", ".", "gethostname", "(", ")", "except", "OSError", ":", "# Still not wo...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/platform.py#L754-L767
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/boost/grad_freeze.py
python
GradientFreeze.freeze_generate
(self, network, optimizer)
return network, optimizer
r""" Generate freeze network and optimizer. Args: network (Cell): The training network. optimizer (Cell): Optimizer for updating the weights.
r""" Generate freeze network and optimizer.
[ "r", "Generate", "freeze", "network", "and", "optimizer", "." ]
def freeze_generate(self, network, optimizer): r""" Generate freeze network and optimizer. Args: network (Cell): The training network. optimizer (Cell): Optimizer for updating the weights. """ train_para_groups = self.split_parameters_groups( network, self._param_groups) for i in range(self._param_groups): train_para_groups[i] = self._param_processer.generate_group_params(train_para_groups[i], optimizer.init_params['params']) train_strategy = self.generate_freeze_index_sequence( self._param_groups, self._freeze_type, self._freeze_p, self._total_steps) optimizer = FreezeOpt(optimizer, train_para_groups, train_strategy) return network, optimizer
[ "def", "freeze_generate", "(", "self", ",", "network", ",", "optimizer", ")", ":", "train_para_groups", "=", "self", ".", "split_parameters_groups", "(", "network", ",", "self", ".", "_param_groups", ")", "for", "i", "in", "range", "(", "self", ".", "_param_...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/boost/grad_freeze.py#L251-L268
taskflow/taskflow
f423a100a70b275f6e7331bc96537a3fe172e8d7
3rd-party/tbb/python/tbb/pool.py
python
Pool.close
(self)
Prevents any more tasks from being submitted to the pool. Once all the tasks have been completed the worker processes will exit.
Prevents any more tasks from being submitted to the pool. Once all the tasks have been completed the worker processes will exit.
[ "Prevents", "any", "more", "tasks", "from", "being", "submitted", "to", "the", "pool", ".", "Once", "all", "the", "tasks", "have", "been", "completed", "the", "worker", "processes", "will", "exit", "." ]
def close(self): """Prevents any more tasks from being submitted to the pool. Once all the tasks have been completed the worker processes will exit.""" # No lock here. We assume it's sufficiently atomic... self._closed = True
[ "def", "close", "(", "self", ")", ":", "# No lock here. We assume it's sufficiently atomic...", "self", ".", "_closed", "=", "True" ]
https://github.com/taskflow/taskflow/blob/f423a100a70b275f6e7331bc96537a3fe172e8d7/3rd-party/tbb/python/tbb/pool.py#L206-L211
gimli-org/gimli
17aa2160de9b15ababd9ef99e89b1bc3277bbb23
pygimli/solver/solver.py
python
parseArgToArray
(arg, nDof, mesh=None, userData={})
Parse array related arguments to create a valid value array. Parameters ---------- arg : float | int | iterable | callable The target array value that will be converted to an array. If arg is a callable with it must fulfill: :: arg(cell|node|boundary, userData={}) Where MeshEntity is one of :gimliapi:`GIMLI::Cell` , :gimliapi:`GIMLI::Node` or :gimliapi:`GIMLI::Boundary` depending on nDof, where nDof is mesh.cellCount(), mesh.nodeCount() or mesh.boundaryCount(), respectively. nDof : int | [int] Desired array size. mesh : :gimliapi:`GIMLI::Mesh` Used if arg is callable userData : class Used if arg is callable Returns ------- ret : :gimliapi:`GIMLI::RVector` Array of desired length filled with the appropriate values.
Parse array related arguments to create a valid value array.
[ "Parse", "array", "related", "arguments", "to", "create", "a", "valid", "value", "array", "." ]
def parseArgToArray(arg, nDof, mesh=None, userData={}): """ Parse array related arguments to create a valid value array. Parameters ---------- arg : float | int | iterable | callable The target array value that will be converted to an array. If arg is a callable with it must fulfill: :: arg(cell|node|boundary, userData={}) Where MeshEntity is one of :gimliapi:`GIMLI::Cell` , :gimliapi:`GIMLI::Node` or :gimliapi:`GIMLI::Boundary` depending on nDof, where nDof is mesh.cellCount(), mesh.nodeCount() or mesh.boundaryCount(), respectively. nDof : int | [int] Desired array size. mesh : :gimliapi:`GIMLI::Mesh` Used if arg is callable userData : class Used if arg is callable Returns ------- ret : :gimliapi:`GIMLI::RVector` Array of desired length filled with the appropriate values. """ #pg.warn('check if obsolete: parseArgToArray') if not hasattr(nDof, '__len__'): nDof = [nDof] try: return pg.Vector(nDof[0], float(arg)) except BaseException as _: pass if hasattr(arg, '__len__'): if isinstance(arg, np.ndarray): if len(arg) == nDof[0]: return arg else: raise Exception('Given array does not have requested (' + str(nDof) + ') size (' + str(len(arg)) + ')') for n in nDof: if len(arg) == n: return arg try: # [marker, val] || [[marker, val]] return parseMapToCellArray(arg, mesh) except: raise Exception("Array 'arg' has the wrong size: " + str(len(arg)) + " != " + str(nDof)) elif hasattr(arg, '__call__'): ret = pg.Vector(nDof[0], 0.0) if not mesh: raise Exception("Please provide a mesh for the callable" "argument to parse ") if nDof[0] == mesh.nodeCount(): for n in mesh.nodes(): if userData: ret[n.id()] = arg(node=n, userData=userData) else: ret[n.id()] = arg(node=n) elif nDof[0] == mesh.cellCount(): for c in mesh.cells(): if userData: ret[c.id()] = arg(cell=c, userData=userData) else: ret[c.id()] = arg(cell=c) elif nDof[0] == mesh.boundaryCount(): for b in mesh.boundaries(): if userData: ret[b.id()] = arg(boundary=b, userData=userData) else: ret[b.id()] = arg(boundary=b) else: raise Exception("Cannot parse callable argument " + str(nDof) + " nodes: " + str(mesh.nodeCount()) + " cells: " + str(mesh.cellCount())) return ret raise Exception("Cannot parse argument type " + str(type(arg)))
[ "def", "parseArgToArray", "(", "arg", ",", "nDof", ",", "mesh", "=", "None", ",", "userData", "=", "{", "}", ")", ":", "#pg.warn('check if obsolete: parseArgToArray')", "if", "not", "hasattr", "(", "nDof", ",", "'__len__'", ")", ":", "nDof", "=", "[", "nDo...
https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/solver/solver.py#L233-L328
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/nntplib.py
python
NNTP.stat
(self, id)
return self.statcmd('STAT ' + id)
Process a STAT command. Argument: - id: article number or message id Returns: - resp: server response if successful - nr: the article number - id: the message id
Process a STAT command. Argument: - id: article number or message id Returns: - resp: server response if successful - nr: the article number - id: the message id
[ "Process", "a", "STAT", "command", ".", "Argument", ":", "-", "id", ":", "article", "number", "or", "message", "id", "Returns", ":", "-", "resp", ":", "server", "response", "if", "successful", "-", "nr", ":", "the", "article", "number", "-", "id", ":",...
def stat(self, id): """Process a STAT command. Argument: - id: article number or message id Returns: - resp: server response if successful - nr: the article number - id: the message id""" return self.statcmd('STAT ' + id)
[ "def", "stat", "(", "self", ",", "id", ")", ":", "return", "self", ".", "statcmd", "(", "'STAT '", "+", "id", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/nntplib.py#L387-L395
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/agilepy/lib_wx/objpanel.py
python
ObjPanelMixin.on_restore
(self, event)
Copy object values to widget contents
Copy object values to widget contents
[ "Copy", "object", "values", "to", "widget", "contents" ]
def on_restore(self, event): """ Copy object values to widget contents """ self.restore()
[ "def", "on_restore", "(", "self", ",", "event", ")", ":", "self", ".", "restore", "(", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/agilepy/lib_wx/objpanel.py#L3632-L3636
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py
python
Misc.unbind_all
(self, sequence)
Unbind for all widgets for event SEQUENCE all functions.
Unbind for all widgets for event SEQUENCE all functions.
[ "Unbind", "for", "all", "widgets", "for", "event", "SEQUENCE", "all", "functions", "." ]
def unbind_all(self, sequence): """Unbind for all widgets for event SEQUENCE all functions.""" self.tk.call('bind', 'all' , sequence, '')
[ "def", "unbind_all", "(", "self", ",", "sequence", ")", ":", "self", ".", "tk", ".", "call", "(", "'bind'", ",", "'all'", ",", "sequence", ",", "''", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py#L1264-L1266
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/lib/arrayterator.py
python
Arrayterator.flat
(self)
A 1-D flat iterator for Arrayterator objects. This iterator returns elements of the array to be iterated over in `Arrayterator` one by one. It is similar to `flatiter`. See Also -------- `Arrayterator` flatiter Examples -------- >>> a = np.arange(3 * 4 * 5 * 6).reshape(3, 4, 5, 6) >>> a_itor = np.lib.arrayterator.Arrayterator(a, 2) >>> for subarr in a_itor.flat: ... if not subarr: ... print subarr, type(subarr) ... 0 <type 'numpy.int32'>
A 1-D flat iterator for Arrayterator objects.
[ "A", "1", "-", "D", "flat", "iterator", "for", "Arrayterator", "objects", "." ]
def flat(self): """ A 1-D flat iterator for Arrayterator objects. This iterator returns elements of the array to be iterated over in `Arrayterator` one by one. It is similar to `flatiter`. See Also -------- `Arrayterator` flatiter Examples -------- >>> a = np.arange(3 * 4 * 5 * 6).reshape(3, 4, 5, 6) >>> a_itor = np.lib.arrayterator.Arrayterator(a, 2) >>> for subarr in a_itor.flat: ... if not subarr: ... print subarr, type(subarr) ... 0 <type 'numpy.int32'> """ for block in self: for value in block.flat: yield value
[ "def", "flat", "(", "self", ")", ":", "for", "block", "in", "self", ":", "for", "value", "in", "block", ".", "flat", ":", "yield", "value" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/lib/arrayterator.py#L143-L169
apiaryio/snowcrash
b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3
tools/gyp/pylib/gyp/generator/eclipse.py
python
WriteIncludePaths
(out, eclipse_langs, include_dirs)
Write the includes section of a CDT settings export file.
Write the includes section of a CDT settings export file.
[ "Write", "the", "includes", "section", "of", "a", "CDT", "settings", "export", "file", "." ]
def WriteIncludePaths(out, eclipse_langs, include_dirs): """Write the includes section of a CDT settings export file.""" out.write(' <section name="org.eclipse.cdt.internal.ui.wizards.' \ 'settingswizards.IncludePaths">\n') out.write(' <language name="holder for library settings"></language>\n') for lang in eclipse_langs: out.write(' <language name="%s">\n' % lang) for include_dir in include_dirs: out.write(' <includepath workspace_path="false">%s</includepath>\n' % include_dir) out.write(' </language>\n') out.write(' </section>\n')
[ "def", "WriteIncludePaths", "(", "out", ",", "eclipse_langs", ",", "include_dirs", ")", ":", "out", ".", "write", "(", "' <section name=\"org.eclipse.cdt.internal.ui.wizards.'", "'settingswizards.IncludePaths\">\\n'", ")", "out", ".", "write", "(", "' <language name=\"h...
https://github.com/apiaryio/snowcrash/blob/b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3/tools/gyp/pylib/gyp/generator/eclipse.py#L252-L264
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/distributions/python/ops/mixture_same_family.py
python
MixtureSameFamily.__init__
(self, mixture_distribution, components_distribution, validate_args=False, allow_nan_stats=True, name="MixtureSameFamily")
Construct a `MixtureSameFamily` distribution. Args: mixture_distribution: `tfp.distributions.Categorical`-like instance. Manages the probability of selecting components. The number of categories must match the rightmost batch dimension of the `components_distribution`. Must have either scalar `batch_shape` or `batch_shape` matching `components_distribution.batch_shape[:-1]`. components_distribution: `tfp.distributions.Distribution`-like instance. Right-most batch dimension indexes components. validate_args: Python `bool`, default `False`. When `True` distribution parameters are checked for validity despite possibly degrading runtime performance. When `False` invalid inputs may silently render incorrect outputs. allow_nan_stats: Python `bool`, default `True`. When `True`, statistics (e.g., mean, mode, variance) use the value "`NaN`" to indicate the result is undefined. When `False`, an exception is raised if one or more of the statistic's batch members are undefined. name: Python `str` name prefixed to Ops created by this class. Raises: ValueError: `if not mixture_distribution.dtype.is_integer`. ValueError: if mixture_distribution does not have scalar `event_shape`. ValueError: if `mixture_distribution.batch_shape` and `components_distribution.batch_shape[:-1]` are both fully defined and the former is neither scalar nor equal to the latter. ValueError: if `mixture_distribution` categories does not equal `components_distribution` rightmost batch shape.
Construct a `MixtureSameFamily` distribution.
[ "Construct", "a", "MixtureSameFamily", "distribution", "." ]
def __init__(self, mixture_distribution, components_distribution, validate_args=False, allow_nan_stats=True, name="MixtureSameFamily"): """Construct a `MixtureSameFamily` distribution. Args: mixture_distribution: `tfp.distributions.Categorical`-like instance. Manages the probability of selecting components. The number of categories must match the rightmost batch dimension of the `components_distribution`. Must have either scalar `batch_shape` or `batch_shape` matching `components_distribution.batch_shape[:-1]`. components_distribution: `tfp.distributions.Distribution`-like instance. Right-most batch dimension indexes components. validate_args: Python `bool`, default `False`. When `True` distribution parameters are checked for validity despite possibly degrading runtime performance. When `False` invalid inputs may silently render incorrect outputs. allow_nan_stats: Python `bool`, default `True`. When `True`, statistics (e.g., mean, mode, variance) use the value "`NaN`" to indicate the result is undefined. When `False`, an exception is raised if one or more of the statistic's batch members are undefined. name: Python `str` name prefixed to Ops created by this class. Raises: ValueError: `if not mixture_distribution.dtype.is_integer`. ValueError: if mixture_distribution does not have scalar `event_shape`. ValueError: if `mixture_distribution.batch_shape` and `components_distribution.batch_shape[:-1]` are both fully defined and the former is neither scalar nor equal to the latter. ValueError: if `mixture_distribution` categories does not equal `components_distribution` rightmost batch shape. """ parameters = dict(locals()) with ops.name_scope(name) as name: self._mixture_distribution = mixture_distribution self._components_distribution = components_distribution self._runtime_assertions = [] s = components_distribution.event_shape_tensor() s_dim0 = tensor_shape.dimension_value(s.shape[0]) self._event_ndims = (s_dim0 if s_dim0 is not None else array_ops.shape(s)[0]) if not mixture_distribution.dtype.is_integer: raise ValueError( "`mixture_distribution.dtype` ({}) is not over integers".format( mixture_distribution.dtype.name)) if (mixture_distribution.event_shape.ndims is not None and mixture_distribution.event_shape.ndims != 0): raise ValueError("`mixture_distribution` must have scalar `event_dim`s") elif validate_args: self._runtime_assertions += [ control_flow_ops.assert_has_rank( mixture_distribution.event_shape_tensor(), 0, message="`mixture_distribution` must have scalar `event_dim`s"), ] mdbs = mixture_distribution.batch_shape cdbs = components_distribution.batch_shape.with_rank_at_least(1)[:-1] if mdbs.is_fully_defined() and cdbs.is_fully_defined(): if mdbs.ndims != 0 and mdbs != cdbs: raise ValueError( "`mixture_distribution.batch_shape` (`{}`) is not " "compatible with `components_distribution.batch_shape` " "(`{}`)".format(mdbs.as_list(), cdbs.as_list())) elif validate_args: mdbs = mixture_distribution.batch_shape_tensor() cdbs = components_distribution.batch_shape_tensor()[:-1] self._runtime_assertions += [ control_flow_ops.assert_equal( distribution_util.pick_vector( mixture_distribution.is_scalar_batch(), cdbs, mdbs), cdbs, message=( "`mixture_distribution.batch_shape` is not " "compatible with `components_distribution.batch_shape`"))] km = tensor_shape.dimension_value( mixture_distribution.logits.shape.with_rank_at_least(1)[-1]) kc = tensor_shape.dimension_value( components_distribution.batch_shape.with_rank_at_least(1)[-1]) if km is not None and kc is not None and km != kc: raise ValueError("`mixture_distribution components` ({}) does not " "equal `components_distribution.batch_shape[-1]` " "({})".format(km, kc)) elif validate_args: km = array_ops.shape(mixture_distribution.logits)[-1] kc = components_distribution.batch_shape_tensor()[-1] self._runtime_assertions += [ control_flow_ops.assert_equal( km, kc, message=("`mixture_distribution components` does not equal " "`components_distribution.batch_shape[-1:]`")), ] elif km is None: km = array_ops.shape(mixture_distribution.logits)[-1] self._num_components = km super(MixtureSameFamily, self).__init__( dtype=self._components_distribution.dtype, reparameterization_type=distribution.NOT_REPARAMETERIZED, validate_args=validate_args, allow_nan_stats=allow_nan_stats, parameters=parameters, graph_parents=( self._mixture_distribution._graph_parents # pylint: disable=protected-access + self._components_distribution._graph_parents), # pylint: disable=protected-access name=name)
[ "def", "__init__", "(", "self", ",", "mixture_distribution", ",", "components_distribution", ",", "validate_args", "=", "False", ",", "allow_nan_stats", "=", "True", ",", "name", "=", "\"MixtureSameFamily\"", ")", ":", "parameters", "=", "dict", "(", "locals", "...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/distributions/python/ops/mixture_same_family.py#L109-L222
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/autograd/gradcheck.py
python
_get_analytical_jacobian_forward_ad
(fn, inputs, outputs, *, check_grad_dtypes=False, all_u=None)
return jacobians
Computes the analytical Jacobian using forward mode AD of `fn(inputs)` using forward mode AD with respect to `target`. Returns N * M Jacobians where N is the number of tensors in target that require grad and M is the number of non-integral outputs. Contrary to other functions here, this function requires "inputs" to actually be used by the function. The computed value is expected to be wrong if the function captures the inputs by side effect instead of using the passed ones (many torch.nn tests do this). Args: fn: the function to compute the jacobian for inputs: inputs to `fn` outputs: provide precomputed outputs to avoid one extra invocation of fn check_grad_dtypes: if True, will check that the gradient dtype are valid all_u (optional): if provided, the Jacobian will be right multiplied with this vector Returns: A tuple of M N-tuples of tensors
Computes the analytical Jacobian using forward mode AD of `fn(inputs)` using forward mode AD with respect to `target`. Returns N * M Jacobians where N is the number of tensors in target that require grad and M is the number of non-integral outputs. Contrary to other functions here, this function requires "inputs" to actually be used by the function. The computed value is expected to be wrong if the function captures the inputs by side effect instead of using the passed ones (many torch.nn tests do this).
[ "Computes", "the", "analytical", "Jacobian", "using", "forward", "mode", "AD", "of", "fn", "(", "inputs", ")", "using", "forward", "mode", "AD", "with", "respect", "to", "target", ".", "Returns", "N", "*", "M", "Jacobians", "where", "N", "is", "the", "nu...
def _get_analytical_jacobian_forward_ad(fn, inputs, outputs, *, check_grad_dtypes=False, all_u=None) -> Tuple[Tuple[torch.Tensor, ...], ...]: """Computes the analytical Jacobian using forward mode AD of `fn(inputs)` using forward mode AD with respect to `target`. Returns N * M Jacobians where N is the number of tensors in target that require grad and M is the number of non-integral outputs. Contrary to other functions here, this function requires "inputs" to actually be used by the function. The computed value is expected to be wrong if the function captures the inputs by side effect instead of using the passed ones (many torch.nn tests do this). Args: fn: the function to compute the jacobian for inputs: inputs to `fn` outputs: provide precomputed outputs to avoid one extra invocation of fn check_grad_dtypes: if True, will check that the gradient dtype are valid all_u (optional): if provided, the Jacobian will be right multiplied with this vector Returns: A tuple of M N-tuples of tensors """ # To avoid early import issues fwAD = torch.autograd.forward_ad tensor_inputs = tuple(i for i in inputs if is_tensor_like(i) and i.requires_grad) if any(i.is_complex() for i in tensor_inputs): raise ValueError("Expected inputs to be non-complex for _get_analytical_jacobian_forward_ad.") if all_u: jacobians = tuple(_allocate_jacobians_with_outputs(outputs, 1) for i in tensor_inputs) else: jacobians = tuple(_allocate_jacobians_with_outputs(outputs, i.numel()) for i in tensor_inputs) with fwAD.dual_level(): fw_grads = [] dual_inputs = [] for i, inp in enumerate(inputs): if is_tensor_like(inp) and inp.requires_grad: if inp.layout == torch._mkldnn: # type: ignore[attr-defined] raise ValueError("MKLDNN inputs are not support for forward AD gradcheck.") inp = fwAD.make_dual(inp, torch.zeros_like(inp)) # If inp is a differentiable view, the dual might not be the tangent given to # make_dual, so read it explicitly from the dual tensor fw_grads.append(fwAD.unpack_dual(inp)[1]) dual_inputs.append(inp) if all_u: # Do the full reduction in one pass # To be consistent with numerical evaluation, we actually compute one reduction per input for i, (fw_grad, u) in enumerate(zip(fw_grads, all_u)): fw_grad.copy_(u.view_as(fw_grad)) raw_outputs = _as_tuple(fn(*dual_inputs)) dual_outputs = filter(_is_float_or_complex_tensor, raw_outputs) for index_o, d_o in enumerate(dual_outputs): val, res = fwAD.unpack_dual(d_o) if check_grad_dtypes and res is not None and val.is_complex() != res.is_complex(): raise GradcheckError('Forward AD gradient has dtype mismatch.') # Remove extra dimension of size 1 corresponding to the reduced input jacobians[i][index_o].squeeze_(0) if res is None: jacobians[i][index_o].zero_() else: jacobians[i][index_o].copy_(res.reshape(-1)) fw_grad.zero_() else: # Reconstruct the full Jacobian column by column for i, fw_grad in enumerate(fw_grads): for lin_idx, grad_idx in enumerate(product(*[range(m) for m in fw_grad.size()])): fw_grad[grad_idx] = 1. raw_outputs = _as_tuple(fn(*dual_inputs)) dual_outputs = filter(_is_float_or_complex_tensor, raw_outputs) for index_o, d_o in enumerate(dual_outputs): val, res = fwAD.unpack_dual(d_o) if check_grad_dtypes and val.is_complex() != res.is_complex(): raise GradcheckError('Forward AD gradient has dtype mismatch.') if res is None: jacobians[i][index_o][lin_idx].zero_() else: jacobians[i][index_o][lin_idx].copy_(res.reshape(-1)) fw_grad[grad_idx] = 0. return jacobians
[ "def", "_get_analytical_jacobian_forward_ad", "(", "fn", ",", "inputs", ",", "outputs", ",", "*", ",", "check_grad_dtypes", "=", "False", ",", "all_u", "=", "None", ")", "->", "Tuple", "[", "Tuple", "[", "torch", ".", "Tensor", ",", "...", "]", ",", "......
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/autograd/gradcheck.py#L292-L375
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/LoadCIF.py
python
LoadCIF._data_with_space_group_keys
(self, cif_file)
Returns the cif data which contains at least one of the required SpaceGroupBuilder keys. :param cif_file: The parsed cif file to check for keys. :return: The Data section containing at least one of the required SpaceGroupBuilder keys.
Returns the cif data which contains at least one of the required SpaceGroupBuilder keys. :param cif_file: The parsed cif file to check for keys. :return: The Data section containing at least one of the required SpaceGroupBuilder keys.
[ "Returns", "the", "cif", "data", "which", "contains", "at", "least", "one", "of", "the", "required", "SpaceGroupBuilder", "keys", ".", ":", "param", "cif_file", ":", "The", "parsed", "cif", "file", "to", "check", "for", "keys", ".", ":", "return", ":", "...
def _data_with_space_group_keys(self, cif_file): """ Returns the cif data which contains at least one of the required SpaceGroupBuilder keys. :param cif_file: The parsed cif file to check for keys. :return: The Data section containing at least one of the required SpaceGroupBuilder keys. """ for data_key in cif_file.keys(): cif_data = cif_file[data_key] if self._has_a_space_group_key(cif_data): return cif_data raise RuntimeError(f"Could not find any Space Group keys. Missing one of the following: " f"{str(SpaceGroupBuilder.string_keys + SpaceGroupBuilder.number_keys)}")
[ "def", "_data_with_space_group_keys", "(", "self", ",", "cif_file", ")", ":", "for", "data_key", "in", "cif_file", ".", "keys", "(", ")", ":", "cif_data", "=", "cif_file", "[", "data_key", "]", "if", "self", ".", "_has_a_space_group_key", "(", "cif_data", ")...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/LoadCIF.py#L404-L416
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/indexes/multi.py
python
MultiIndex.nlevels
(self)
return len(self._levels)
Integer number of levels in this MultiIndex.
Integer number of levels in this MultiIndex.
[ "Integer", "number", "of", "levels", "in", "this", "MultiIndex", "." ]
def nlevels(self) -> int: """ Integer number of levels in this MultiIndex. """ return len(self._levels)
[ "def", "nlevels", "(", "self", ")", "->", "int", ":", "return", "len", "(", "self", ".", "_levels", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/indexes/multi.py#L1882-L1886
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftguitools/gui_draft2sketch.py
python
Draft2Sketch.GetResources
(self)
return {'Pixmap': 'Draft_Draft2Sketch', 'MenuText': QT_TRANSLATE_NOOP("Draft_Draft2Sketch", "Draft to Sketch"), 'ToolTip': QT_TRANSLATE_NOOP("Draft_Draft2Sketch", "Convert bidirectionally between Draft objects and Sketches.\nMany Draft objects will be converted into a single non-constrained Sketch.\nHowever, a single sketch with disconnected traces will be converted into several individual Draft objects.")}
Set icon, menu and tooltip.
Set icon, menu and tooltip.
[ "Set", "icon", "menu", "and", "tooltip", "." ]
def GetResources(self): """Set icon, menu and tooltip.""" return {'Pixmap': 'Draft_Draft2Sketch', 'MenuText': QT_TRANSLATE_NOOP("Draft_Draft2Sketch", "Draft to Sketch"), 'ToolTip': QT_TRANSLATE_NOOP("Draft_Draft2Sketch", "Convert bidirectionally between Draft objects and Sketches.\nMany Draft objects will be converted into a single non-constrained Sketch.\nHowever, a single sketch with disconnected traces will be converted into several individual Draft objects.")}
[ "def", "GetResources", "(", "self", ")", ":", "return", "{", "'Pixmap'", ":", "'Draft_Draft2Sketch'", ",", "'MenuText'", ":", "QT_TRANSLATE_NOOP", "(", "\"Draft_Draft2Sketch\"", ",", "\"Draft to Sketch\"", ")", ",", "'ToolTip'", ":", "QT_TRANSLATE_NOOP", "(", "\"Dra...
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_draft2sketch.py#L53-L58
facebookincubator/fizz
bd0ba1b80f72023cb7ede671a4caa85f6664d3f6
build/fbcode_builder/getdeps/fetcher.py
python
ChangeStatus.__init__
(self, all_changed=False)
Construct a ChangeStatus object. The default is to create a status that indicates no changes, but passing all_changed=True will create one that indicates that everything changed
Construct a ChangeStatus object. The default is to create a status that indicates no changes, but passing all_changed=True will create one that indicates that everything changed
[ "Construct", "a", "ChangeStatus", "object", ".", "The", "default", "is", "to", "create", "a", "status", "that", "indicates", "no", "changes", "but", "passing", "all_changed", "=", "True", "will", "create", "one", "that", "indicates", "that", "everything", "cha...
def __init__(self, all_changed=False): """Construct a ChangeStatus object. The default is to create a status that indicates no changes, but passing all_changed=True will create one that indicates that everything changed""" if all_changed: self.source_files = 1 self.make_files = 1 else: self.source_files = 0 self.make_files = 0
[ "def", "__init__", "(", "self", ",", "all_changed", "=", "False", ")", ":", "if", "all_changed", ":", "self", ".", "source_files", "=", "1", "self", ".", "make_files", "=", "1", "else", ":", "self", ".", "source_files", "=", "0", "self", ".", "make_fil...
https://github.com/facebookincubator/fizz/blob/bd0ba1b80f72023cb7ede671a4caa85f6664d3f6/build/fbcode_builder/getdeps/fetcher.py#L53-L62
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Node/FS.py
python
File._add_strings_to_dependency_map
(self, dmap)
return dmap
In the case comparing node objects isn't sufficient, we'll add the strings for the nodes to the dependency map :return:
In the case comparing node objects isn't sufficient, we'll add the strings for the nodes to the dependency map :return:
[ "In", "the", "case", "comparing", "node", "objects", "isn", "t", "sufficient", "we", "ll", "add", "the", "strings", "for", "the", "nodes", "to", "the", "dependency", "map", ":", "return", ":" ]
def _add_strings_to_dependency_map(self, dmap): """ In the case comparing node objects isn't sufficient, we'll add the strings for the nodes to the dependency map :return: """ first_string = str(next(iter(dmap))) # print("DMAP:%s"%id(dmap)) if first_string not in dmap: string_dict = {str(child): signature for child, signature in dmap.items()} dmap.update(string_dict) return dmap
[ "def", "_add_strings_to_dependency_map", "(", "self", ",", "dmap", ")", ":", "first_string", "=", "str", "(", "next", "(", "iter", "(", "dmap", ")", ")", ")", "# print(\"DMAP:%s\"%id(dmap))", "if", "first_string", "not", "in", "dmap", ":", "string_dict", "=", ...
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Node/FS.py#L3325-L3337
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/debug/lib/grpc_debug_server.py
python
EventListenerBaseServicer.run_server
(self, blocking=True)
Start running the server. Args: blocking: If `True`, block until `stop_server()` is invoked. Raises: ValueError: If server stop has already been requested, or if the server has already started running.
Start running the server.
[ "Start", "running", "the", "server", "." ]
def run_server(self, blocking=True): """Start running the server. Args: blocking: If `True`, block until `stop_server()` is invoked. Raises: ValueError: If server stop has already been requested, or if the server has already started running. """ self._server_lock.acquire() try: if self._stop_requested: raise ValueError("Server has already stopped") if self._server_started: raise ValueError("Server has already started running") no_max_message_sizes = [("grpc.max_receive_message_length", -1), ("grpc.max_send_message_length", -1)] self.server = grpc.server(futures.ThreadPoolExecutor(max_workers=10), options=no_max_message_sizes) debug_service_pb2_grpc.add_EventListenerServicer_to_server(self, self.server) self.server.add_insecure_port("[::]:%d" % self._server_port) self.server.start() self._server_started = True finally: self._server_lock.release() if blocking: while not self._stop_requested: time.sleep(1.0)
[ "def", "run_server", "(", "self", ",", "blocking", "=", "True", ")", ":", "self", ".", "_server_lock", ".", "acquire", "(", ")", "try", ":", "if", "self", ".", "_stop_requested", ":", "raise", "ValueError", "(", "\"Server has already stopped\"", ")", "if", ...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/debug/lib/grpc_debug_server.py#L328-L359
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
commonTools/build_stats/wrapper/WrapperOpTimer.py
python
WrapperOpTimer.time_op
(wcp)
return (csv_row, returncode)
evaluate 'op' with 'op_args', and gather stats into output_stats_file
evaluate 'op' with 'op_args', and gather stats into output_stats_file
[ "evaluate", "op", "with", "op_args", "and", "gather", "stats", "into", "output_stats_file" ]
def time_op(wcp): """ evaluate 'op' with 'op_args', and gather stats into output_stats_file """ # if os.path.exists(output_stats_file) and os.path.getsize(output_stats_file) > 0: # print("WARNING: File '"+output_stats_file+"' exists and will be overwritten") # print("op='"+op+"'") # print("op_args='"+str(op_args)+"'") # print("op_output_file='"+op_output_file+"'") # initializing the titles and rows list fields = [] csv_row = {} cmdcount = 0 returncode = 0 for cmd in wcp.commands: if cmdcount == 0: cmd = [ wcp.time_cmd, # '--append', '--output=' + wcp.output_stats_file, field_arg, ] + cmd cmdcount += 1 returncode |= WrapperOpTimer.run_cmd(cmd) # reading csv file with open(wcp.output_stats_file, 'r') as csvfile: # creating a csv reader object csvreader = csv.reader(csvfile) # extracting field names through first row fields = next(csvreader) # extracting each data row one by one # we effectively retain only the last row. # it isn't clear if we should expect multiple rows per file # # In the bash version of this I was able to handle multiple rows per file # We could do that here, but it would require returning a list of csv maps # On the system side of things, it is very murky. We would need to ensure # file integrity (concurrent reads/writes). For now, it's # best to enforce 1 file per operation performed. (which should happen if we # name things correctly) - That is invalid is there is a cycle in the Build graph, # but that is a larger problem. for row in csvreader: csv_row = dict(zip(fields, row)) # FileSize csv_row['FileSize'] = WrapperOpTimer.get_file_size(wcp.op_output_file) # add a field with the short op csv_row['op'] = os.path.basename(wcp.op) # FileName if wcp.base_build_dir: abs_base_build_dir = os.path.abspath(wcp.base_build_dir) current_working_dir = os.path.abspath(os.getcwd()) rel_path_to_base_build_dir = os.path.relpath( current_working_dir, start=abs_base_build_dir) rel_op_output_file = os.path.join(rel_path_to_base_build_dir, wcp.op_output_file) else: rel_op_output_file = wcp.op_output_file csv_row['FileName'] = rel_op_output_file # Remove the build stats output file if the build failed if returncode != 0 and os.path.exists(wcp.output_stats_file): os.remove(wcp.output_stats_file) return (csv_row, returncode)
[ "def", "time_op", "(", "wcp", ")", ":", "# if os.path.exists(output_stats_file) and os.path.getsize(output_stats_file) > 0:", "# print(\"WARNING: File '\"+output_stats_file+\"' exists and will be overwritten\")", "# print(\"op='\"+op+\"'\")", "# print(\"op_args='\"+str(op_args)+\"'\")", "#...
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/commonTools/build_stats/wrapper/WrapperOpTimer.py#L145-L214
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py3/setuptools/command/easy_install.py
python
easy_install._set_fetcher_options
(self, base)
When easy_install is about to run bdist_egg on a source dist, that source dist might have 'setup_requires' directives, requiring additional fetching. Ensure the fetcher options given to easy_install are available to that command as well.
When easy_install is about to run bdist_egg on a source dist, that source dist might have 'setup_requires' directives, requiring additional fetching. Ensure the fetcher options given to easy_install are available to that command as well.
[ "When", "easy_install", "is", "about", "to", "run", "bdist_egg", "on", "a", "source", "dist", "that", "source", "dist", "might", "have", "setup_requires", "directives", "requiring", "additional", "fetching", ".", "Ensure", "the", "fetcher", "options", "given", "...
def _set_fetcher_options(self, base): """ When easy_install is about to run bdist_egg on a source dist, that source dist might have 'setup_requires' directives, requiring additional fetching. Ensure the fetcher options given to easy_install are available to that command as well. """ # find the fetch options from easy_install and write them out # to the setup.cfg file. ei_opts = self.distribution.get_option_dict('easy_install').copy() fetch_directives = ( 'find_links', 'site_dirs', 'index_url', 'optimize', 'allow_hosts', ) fetch_options = {} for key, val in ei_opts.items(): if key not in fetch_directives: continue fetch_options[key] = val[1] # create a settings dictionary suitable for `edit_config` settings = dict(easy_install=fetch_options) cfg_filename = os.path.join(base, 'setup.cfg') setopt.edit_config(cfg_filename, settings)
[ "def", "_set_fetcher_options", "(", "self", ",", "base", ")", ":", "# find the fetch options from easy_install and write them out", "# to the setup.cfg file.", "ei_opts", "=", "self", ".", "distribution", ".", "get_option_dict", "(", "'easy_install'", ")", ".", "copy", "(...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/command/easy_install.py#L1182-L1203
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/math_ops.py
python
to_int32
(x, name="ToInt32")
return cast(x, dtypes.int32, name=name)
Casts a tensor to type `int32`. Args: x: A `Tensor` or `SparseTensor` or `IndexedSlices`. name: A name for the operation (optional). Returns: A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with type `int32`. Raises: TypeError: If `x` cannot be cast to the `int32`. @compatibility(TF2) This name was deprecated and removed in TF2, but has an exact replacement `tf.cast(..., tf.int32)`. There are no further issues with eager execution or tf.function. Before: >>> tf.compat.v1.to_int32(tf.constant(1, dtype=tf.int64)) <tf.Tensor: shape=(), dtype=int32, numpy=1> After: >>> tf.cast(tf.constant(1, dtype=tf.int64), tf.int32) <tf.Tensor: shape=(), dtype=int32, numpy=1> @end_compatibility
Casts a tensor to type `int32`.
[ "Casts", "a", "tensor", "to", "type", "int32", "." ]
def to_int32(x, name="ToInt32"): """Casts a tensor to type `int32`. Args: x: A `Tensor` or `SparseTensor` or `IndexedSlices`. name: A name for the operation (optional). Returns: A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with type `int32`. Raises: TypeError: If `x` cannot be cast to the `int32`. @compatibility(TF2) This name was deprecated and removed in TF2, but has an exact replacement `tf.cast(..., tf.int32)`. There are no further issues with eager execution or tf.function. Before: >>> tf.compat.v1.to_int32(tf.constant(1, dtype=tf.int64)) <tf.Tensor: shape=(), dtype=int32, numpy=1> After: >>> tf.cast(tf.constant(1, dtype=tf.int64), tf.int32) <tf.Tensor: shape=(), dtype=int32, numpy=1> @end_compatibility """ return cast(x, dtypes.int32, name=name)
[ "def", "to_int32", "(", "x", ",", "name", "=", "\"ToInt32\"", ")", ":", "return", "cast", "(", "x", ",", "dtypes", ".", "int32", ",", "name", "=", "name", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/math_ops.py#L1126-L1159
GJDuck/LowFat
ecf6a0f0fa1b73a27a626cf493cc39e477b6faea
llvm-4.0.0.src/projects/compiler-rt/lib/sanitizer_common/scripts/cpplint.py
python
CheckMakePairUsesDeduction
(filename, clean_lines, linenum, error)
Check that make_pair's template arguments are deduced. G++ 4.6 in C++0x mode fails badly if make_pair's template arguments are specified explicitly, and such use isn't intended in any case. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Check that make_pair's template arguments are deduced.
[ "Check", "that", "make_pair", "s", "template", "arguments", "are", "deduced", "." ]
def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error): """Check that make_pair's template arguments are deduced. G++ 4.6 in C++0x mode fails badly if make_pair's template arguments are specified explicitly, and such use isn't intended in any case. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ raw = clean_lines.raw_lines line = raw[linenum] match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line) if match: error(filename, linenum, 'build/explicit_make_pair', 4, # 4 = high confidence 'For C++11-compatibility, omit template arguments from make_pair' ' OR use pair directly OR if appropriate, construct a pair directly')
[ "def", "CheckMakePairUsesDeduction", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "raw", "=", "clean_lines", ".", "raw_lines", "line", "=", "raw", "[", "linenum", "]", "match", "=", "_RE_PATTERN_EXPLICIT_MAKEPAIR", ".", "search", ...
https://github.com/GJDuck/LowFat/blob/ecf6a0f0fa1b73a27a626cf493cc39e477b6faea/llvm-4.0.0.src/projects/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L3753-L3772
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py
python
Misc.colormodel
(self, value=None)
return self.tk.call('tk', 'colormodel', self._w, value)
Useless. Not implemented in Tk.
Useless. Not implemented in Tk.
[ "Useless", ".", "Not", "implemented", "in", "Tk", "." ]
def colormodel(self, value=None): """Useless. Not implemented in Tk.""" return self.tk.call('tk', 'colormodel', self._w, value)
[ "def", "colormodel", "(", "self", ",", "value", "=", "None", ")", ":", "return", "self", ".", "tk", ".", "call", "(", "'tk'", ",", "'colormodel'", ",", "self", ".", "_w", ",", "value", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py#L721-L723
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pathlib.py
python
Path.read_text
(self, encoding=None, errors=None)
Open the file in text mode, read it, and close the file.
Open the file in text mode, read it, and close the file.
[ "Open", "the", "file", "in", "text", "mode", "read", "it", "and", "close", "the", "file", "." ]
def read_text(self, encoding=None, errors=None): """ Open the file in text mode, read it, and close the file. """ with self.open(mode='r', encoding=encoding, errors=errors) as f: return f.read()
[ "def", "read_text", "(", "self", ",", "encoding", "=", "None", ",", "errors", "=", "None", ")", ":", "with", "self", ".", "open", "(", "mode", "=", "'r'", ",", "encoding", "=", "encoding", ",", "errors", "=", "errors", ")", "as", "f", ":", "return"...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pathlib.py#L1217-L1222
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/enum.py
python
_is_sunder
(name)
return (len(name) > 2 and name[0] == name[-1] == '_' and name[1:2] != '_' and name[-2:-1] != '_')
Returns True if a _sunder_ name, False otherwise.
Returns True if a _sunder_ name, False otherwise.
[ "Returns", "True", "if", "a", "_sunder_", "name", "False", "otherwise", "." ]
def _is_sunder(name): """Returns True if a _sunder_ name, False otherwise.""" return (len(name) > 2 and name[0] == name[-1] == '_' and name[1:2] != '_' and name[-2:-1] != '_')
[ "def", "_is_sunder", "(", "name", ")", ":", "return", "(", "len", "(", "name", ")", ">", "2", "and", "name", "[", "0", "]", "==", "name", "[", "-", "1", "]", "==", "'_'", "and", "name", "[", "1", ":", "2", "]", "!=", "'_'", "and", "name", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/enum.py#L34-L39
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_misc.py
python
TimeSpan_Second
(*args)
return _misc_.TimeSpan_Second(*args)
TimeSpan_Second() -> TimeSpan
TimeSpan_Second() -> TimeSpan
[ "TimeSpan_Second", "()", "-", ">", "TimeSpan" ]
def TimeSpan_Second(*args): """TimeSpan_Second() -> TimeSpan""" return _misc_.TimeSpan_Second(*args)
[ "def", "TimeSpan_Second", "(", "*", "args", ")", ":", "return", "_misc_", ".", "TimeSpan_Second", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L4568-L4570
wujian16/Cornell-MOE
df299d1be882d2af9796d7a68b3f9505cac7a53e
moe/optimal_learning/python/data_containers.py
python
HistoricalData.validate_historical_data
(dim, points_sampled, points_sampled_value, points_sampled_noise_variance)
Check that the historical data components (dim, coordinates, values, noises) are consistent in dimension and all have finite values. :param dim: number of (expected) spatial dimensions :type dim: int > 0 :param points_sampled: already-sampled points :type points_sampled: array of float64 with shape (num_sampled, dim) :param points_sampled_value: function value measured at each point :type points_sampled_value: array of float64 with shape (num_sampled) :param points_sampled_noise_variance: noise variance associated with ``points_sampled_value`` :type points_sampled_noise_variance: array of float64 with shape (num_sampled) :return: True if inputs are valid :rtype: boolean
Check that the historical data components (dim, coordinates, values, noises) are consistent in dimension and all have finite values.
[ "Check", "that", "the", "historical", "data", "components", "(", "dim", "coordinates", "values", "noises", ")", "are", "consistent", "in", "dimension", "and", "all", "have", "finite", "values", "." ]
def validate_historical_data(dim, points_sampled, points_sampled_value, points_sampled_noise_variance): """Check that the historical data components (dim, coordinates, values, noises) are consistent in dimension and all have finite values. :param dim: number of (expected) spatial dimensions :type dim: int > 0 :param points_sampled: already-sampled points :type points_sampled: array of float64 with shape (num_sampled, dim) :param points_sampled_value: function value measured at each point :type points_sampled_value: array of float64 with shape (num_sampled) :param points_sampled_noise_variance: noise variance associated with ``points_sampled_value`` :type points_sampled_noise_variance: array of float64 with shape (num_sampled) :return: True if inputs are valid :rtype: boolean """ if dim <= 0: raise ValueError('Input dim = {0:d} is non-positive.'.format(dim)) # Check that all array leading dimensions are the same if points_sampled.shape[0] != points_sampled_value.shape[0] or points_sampled.shape[0] != points_sampled_noise_variance.size: raise ValueError('Input arrays do not have the same leading dimension: (points_sampled, value, noise) = ({0:d}, {1:d}, {2:d})'.format(points_sampled.shape[0], points_sampled_value.size, points_sampled_noise_variance.size)) if points_sampled.shape[0] > 0: for i in range(points_sampled.shape[0]): temp = SamplePoint(points_sampled[i], points_sampled_value[i], points_sampled_noise_variance[i]) temp.validate(dim=dim)
[ "def", "validate_historical_data", "(", "dim", ",", "points_sampled", ",", "points_sampled_value", ",", "points_sampled_noise_variance", ")", ":", "if", "dim", "<=", "0", ":", "raise", "ValueError", "(", "'Input dim = {0:d} is non-positive.'", ".", "format", "(", "dim...
https://github.com/wujian16/Cornell-MOE/blob/df299d1be882d2af9796d7a68b3f9505cac7a53e/moe/optimal_learning/python/data_containers.py#L182-L207
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/dataset/engine/offload.py
python
check_concat_zip_dataset
(dataset)
Check if dataset is concatenated or zipped.
Check if dataset is concatenated or zipped.
[ "Check", "if", "dataset", "is", "concatenated", "or", "zipped", "." ]
def check_concat_zip_dataset(dataset): """ Check if dataset is concatenated or zipped. """ while dataset: if len(dataset.children) > 1: raise RuntimeError("Offload module currently does not support concatenated or zipped datasets.") if dataset.children: dataset = dataset.children[0] continue dataset = dataset.children
[ "def", "check_concat_zip_dataset", "(", "dataset", ")", ":", "while", "dataset", ":", "if", "len", "(", "dataset", ".", "children", ")", ">", "1", ":", "raise", "RuntimeError", "(", "\"Offload module currently does not support concatenated or zipped datasets.\"", ")", ...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/dataset/engine/offload.py#L28-L38
rdkit/rdkit
ede860ae316d12d8568daf5ee800921c3389c84e
rdkit/ML/DecTree/Tree.py
python
TreeNode.GetLevel
(self)
return self.level
Returns the level of this node
Returns the level of this node
[ "Returns", "the", "level", "of", "this", "node" ]
def GetLevel(self): """ Returns the level of this node """ return self.level
[ "def", "GetLevel", "(", "self", ")", ":", "return", "self", ".", "level" ]
https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/ML/DecTree/Tree.py#L199-L203
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_controls.py
python
TreeEvent.GetKeyEvent
(*args, **kwargs)
return _controls_.TreeEvent_GetKeyEvent(*args, **kwargs)
GetKeyEvent(self) -> KeyEvent
GetKeyEvent(self) -> KeyEvent
[ "GetKeyEvent", "(", "self", ")", "-", ">", "KeyEvent" ]
def GetKeyEvent(*args, **kwargs): """GetKeyEvent(self) -> KeyEvent""" return _controls_.TreeEvent_GetKeyEvent(*args, **kwargs)
[ "def", "GetKeyEvent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "TreeEvent_GetKeyEvent", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L5139-L5141
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py
python
IMetadataProvider.has_metadata
(name)
Does the package's distribution contain the named metadata?
Does the package's distribution contain the named metadata?
[ "Does", "the", "package", "s", "distribution", "contain", "the", "named", "metadata?" ]
def has_metadata(name): """Does the package's distribution contain the named metadata?"""
[ "def", "has_metadata", "(", "name", ")", ":" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py#L553-L554
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/runpy.py
python
_run_code
(code, run_globals, init_globals=None, mod_name=None, mod_fname=None, mod_loader=None, pkg_name=None)
return run_globals
Helper to run code in nominated namespace
Helper to run code in nominated namespace
[ "Helper", "to", "run", "code", "in", "nominated", "namespace" ]
def _run_code(code, run_globals, init_globals=None, mod_name=None, mod_fname=None, mod_loader=None, pkg_name=None): """Helper to run code in nominated namespace""" if init_globals is not None: run_globals.update(init_globals) run_globals.update(__name__ = mod_name, __file__ = mod_fname, __loader__ = mod_loader, __package__ = pkg_name) exec code in run_globals return run_globals
[ "def", "_run_code", "(", "code", ",", "run_globals", ",", "init_globals", "=", "None", ",", "mod_name", "=", "None", ",", "mod_fname", "=", "None", ",", "mod_loader", "=", "None", ",", "pkg_name", "=", "None", ")", ":", "if", "init_globals", "is", "not",...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/runpy.py#L62-L73
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
packages/seacas/libraries/ioss/src/visualization/catalyst/phactori/PhactoriDriver.py
python
QuadInfoGQC.AddToInfoArrays
(self, outDoubleArray, outIntegerArray)
add the quad points, point average, and cellId to the argument arrays\n for purspose of doing mpi broadcast/reduce work
add the quad points, point average, and cellId to the argument arrays\n for purspose of doing mpi broadcast/reduce work
[ "add", "the", "quad", "points", "point", "average", "and", "cellId", "to", "the", "argument", "arrays", "\\", "n", "for", "purspose", "of", "doing", "mpi", "broadcast", "/", "reduce", "work" ]
def AddToInfoArrays(self, outDoubleArray, outIntegerArray): "add the quad points, point average, and cellId to the argument arrays\n for purspose of doing mpi broadcast/reduce work" outDoubleArray.append(self.ptA[0]) outDoubleArray.append(self.ptA[1]) outDoubleArray.append(self.ptA[2]) outDoubleArray.append(self.ptB[0]) outDoubleArray.append(self.ptB[1]) outDoubleArray.append(self.ptB[2]) outDoubleArray.append(self.ptC[0]) outDoubleArray.append(self.ptC[1]) outDoubleArray.append(self.ptC[2]) outDoubleArray.append(self.ptD[0]) outDoubleArray.append(self.ptD[1]) outDoubleArray.append(self.ptD[2]) outDoubleArray.append(self.ptAverage[0]) outDoubleArray.append(self.ptAverage[1]) outDoubleArray.append(self.ptAverage[2]) outIntegerArray.append(self.cellId)
[ "def", "AddToInfoArrays", "(", "self", ",", "outDoubleArray", ",", "outIntegerArray", ")", ":", "outDoubleArray", ".", "append", "(", "self", ".", "ptA", "[", "0", "]", ")", "outDoubleArray", ".", "append", "(", "self", ".", "ptA", "[", "1", "]", ")", ...
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/libraries/ioss/src/visualization/catalyst/phactori/PhactoriDriver.py#L16029-L16046
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/fsspec/spec.py
python
AbstractFileSystem.delete
(self, path, recursive=False, maxdepth=None)
return self.rm(path, recursive=recursive, maxdepth=maxdepth)
Alias of :ref:`FilesystemSpec.rm`.
Alias of :ref:`FilesystemSpec.rm`.
[ "Alias", "of", ":", "ref", ":", "FilesystemSpec", ".", "rm", "." ]
def delete(self, path, recursive=False, maxdepth=None): """Alias of :ref:`FilesystemSpec.rm`.""" return self.rm(path, recursive=recursive, maxdepth=maxdepth)
[ "def", "delete", "(", "self", ",", "path", ",", "recursive", "=", "False", ",", "maxdepth", "=", "None", ")", ":", "return", "self", ".", "rm", "(", "path", ",", "recursive", "=", "recursive", ",", "maxdepth", "=", "maxdepth", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/fsspec/spec.py#L966-L968
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/ribbon/toolbar.py
python
RibbonToolBar.SetToolDisabledBitmap
(self, tool_id, bitmap)
Sets the bitmap to be used by the tool with the given ID when the tool is in a disabled state. :param `tool_id`: id of the tool in question, as passed to :meth:`~RibbonToolBar.AddTool`; :param `bitmap`: an instance of :class:`Bitmap`. .. versionadded:: 0.9.5
Sets the bitmap to be used by the tool with the given ID when the tool is in a disabled state.
[ "Sets", "the", "bitmap", "to", "be", "used", "by", "the", "tool", "with", "the", "given", "ID", "when", "the", "tool", "is", "in", "a", "disabled", "state", "." ]
def SetToolDisabledBitmap(self, tool_id, bitmap): """ Sets the bitmap to be used by the tool with the given ID when the tool is in a disabled state. :param `tool_id`: id of the tool in question, as passed to :meth:`~RibbonToolBar.AddTool`; :param `bitmap`: an instance of :class:`Bitmap`. .. versionadded:: 0.9.5 """ tool = self.FindById(tool_id) if tool is None: raise Exception("Invalid tool id") tool.bitmap_disabled = bitmap
[ "def", "SetToolDisabledBitmap", "(", "self", ",", "tool_id", ",", "bitmap", ")", ":", "tool", "=", "self", ".", "FindById", "(", "tool_id", ")", "if", "tool", "is", "None", ":", "raise", "Exception", "(", "\"Invalid tool id\"", ")", "tool", ".", "bitmap_di...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ribbon/toolbar.py#L759-L773
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_controls.py
python
GenericDirCtrl.GetTreeCtrl
(*args, **kwargs)
return _controls_.GenericDirCtrl_GetTreeCtrl(*args, **kwargs)
GetTreeCtrl(self) -> TreeCtrl
GetTreeCtrl(self) -> TreeCtrl
[ "GetTreeCtrl", "(", "self", ")", "-", ">", "TreeCtrl" ]
def GetTreeCtrl(*args, **kwargs): """GetTreeCtrl(self) -> TreeCtrl""" return _controls_.GenericDirCtrl_GetTreeCtrl(*args, **kwargs)
[ "def", "GetTreeCtrl", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "GenericDirCtrl_GetTreeCtrl", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L5737-L5739
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/drill/model/DrillSampleGroup.py
python
DrillSampleGroup.getSampleIndex
(self, sample)
return self._samples.index(sample)
Get the index of a sample in the group. Sample has to be in the group. Args: sample (DrillSample): sample Returns: int: index
Get the index of a sample in the group. Sample has to be in the group.
[ "Get", "the", "index", "of", "a", "sample", "in", "the", "group", ".", "Sample", "has", "to", "be", "in", "the", "group", "." ]
def getSampleIndex(self, sample): """ Get the index of a sample in the group. Sample has to be in the group. Args: sample (DrillSample): sample Returns: int: index """ return self._samples.index(sample)
[ "def", "getSampleIndex", "(", "self", ",", "sample", ")", ":", "return", "self", ".", "_samples", ".", "index", "(", "sample", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/drill/model/DrillSampleGroup.py#L82-L92
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/external/bazel_tools/third_party/py/gflags/gflags_validators.py
python
Validator.GetFlagsNames
(self)
Return the names of the flags checked by this validator. Returns: [string], names of the flags
Return the names of the flags checked by this validator.
[ "Return", "the", "names", "of", "the", "flags", "checked", "by", "this", "validator", "." ]
def GetFlagsNames(self): """Return the names of the flags checked by this validator. Returns: [string], names of the flags """ raise NotImplementedError('This method should be overloaded')
[ "def", "GetFlagsNames", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "'This method should be overloaded'", ")" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/external/bazel_tools/third_party/py/gflags/gflags_validators.py#L83-L89
Netflix/NfWebCrypto
499faf4eb9f9ccf0b21dc728e974970f54bd6c52
plugin/ppapi/ppapi/generators/idl_parser.py
python
IDLParser.p_typedef_array
(self, p)
typedef_decl : modifiers TYPEDEF SYMBOL arrays SYMBOL ';'
typedef_decl : modifiers TYPEDEF SYMBOL arrays SYMBOL ';'
[ "typedef_decl", ":", "modifiers", "TYPEDEF", "SYMBOL", "arrays", "SYMBOL", ";" ]
def p_typedef_array(self, p): """typedef_decl : modifiers TYPEDEF SYMBOL arrays SYMBOL ';' """ typeref = self.BuildAttribute('TYPEREF', p[3]) children = ListFromConcat(p[1], typeref, p[4]) p[0] = self.BuildNamed('Typedef', p, 5, children) if self.parse_debug: DumpReduction('typedef_array', p)
[ "def", "p_typedef_array", "(", "self", ",", "p", ")", ":", "typeref", "=", "self", ".", "BuildAttribute", "(", "'TYPEREF'", ",", "p", "[", "3", "]", ")", "children", "=", "ListFromConcat", "(", "p", "[", "1", "]", ",", "typeref", ",", "p", "[", "4"...
https://github.com/Netflix/NfWebCrypto/blob/499faf4eb9f9ccf0b21dc728e974970f54bd6c52/plugin/ppapi/ppapi/generators/idl_parser.py#L634-L639
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
python/peacock/PostprocessorViewer/plugins/PostprocessorSelectPlugin.py
python
PostprocessorSelectPlugin.onSetData
(self, data)
Called when new data is being supplied to the widget. Args: data[list]: A list of PostprocessorDataWidget files.
Called when new data is being supplied to the widget.
[ "Called", "when", "new", "data", "is", "being", "supplied", "to", "the", "widget", "." ]
def onSetData(self, data): """ Called when new data is being supplied to the widget. Args: data[list]: A list of PostprocessorDataWidget files. """ # Remove existing widgets current_groups = {} filenames = [d.filename() for d in data] for group in self._groups: group.clear() if group.filename() not in filenames: self.LineGroupsLayout.removeWidget(group) group.setParent(None) group.disconnect() else: current_groups[group.filename()] = group self._groups = [] self.color_cycle = itertools.product(['-', '--', '-.', ':'], plt.cm.Paired(np.linspace(0, 1, 11))) # Create the group widgets for each available variable for d in data: if d.filename() in current_groups and not current_groups[d.filename()].sameData(d): group = current_groups[d.filename()] self.LineGroupsLayout.removeWidget(group) group.setParent(None) group.disconnect() self._newGroup(d) elif d.filename() in current_groups: group = current_groups[d.filename()] group.setData(self.axes(), d) self._groups.append(group) self.updateVariables() else: self._newGroup(d) self.updateGeometry()
[ "def", "onSetData", "(", "self", ",", "data", ")", ":", "# Remove existing widgets", "current_groups", "=", "{", "}", "filenames", "=", "[", "d", ".", "filename", "(", ")", "for", "d", "in", "data", "]", "for", "group", "in", "self", ".", "_groups", ":...
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/PostprocessorViewer/plugins/PostprocessorSelectPlugin.py#L69-L107
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/skia/tools/buildbot_spec.py
python
build_targets_from_builder_dict
(builder_dict)
Return a list of targets to build, depending on the builder type.
Return a list of targets to build, depending on the builder type.
[ "Return", "a", "list", "of", "targets", "to", "build", "depending", "on", "the", "builder", "type", "." ]
def build_targets_from_builder_dict(builder_dict): """Return a list of targets to build, depending on the builder type.""" if builder_dict['role'] in ('Test', 'Perf') and builder_dict['os'] == 'iOS': return ['iOSShell'] elif builder_dict['role'] == builder_name_schema.BUILDER_ROLE_TEST: t = ['dm'] if builder_dict.get('configuration') == 'Debug': t.append('nanobench') return t elif builder_dict['role'] == builder_name_schema.BUILDER_ROLE_PERF: return ['nanobench'] else: return ['most']
[ "def", "build_targets_from_builder_dict", "(", "builder_dict", ")", ":", "if", "builder_dict", "[", "'role'", "]", "in", "(", "'Test'", ",", "'Perf'", ")", "and", "builder_dict", "[", "'os'", "]", "==", "'iOS'", ":", "return", "[", "'iOSShell'", "]", "elif",...
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/skia/tools/buildbot_spec.py#L172-L184
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/pydoc.py
python
isdata
(object)
return not (inspect.ismodule(object) or inspect.isclass(object) or inspect.isroutine(object) or inspect.isframe(object) or inspect.istraceback(object) or inspect.iscode(object))
Check if an object is of a type that probably means it's data.
Check if an object is of a type that probably means it's data.
[ "Check", "if", "an", "object", "is", "of", "a", "type", "that", "probably", "means", "it", "s", "data", "." ]
def isdata(object): """Check if an object is of a type that probably means it's data.""" return not (inspect.ismodule(object) or inspect.isclass(object) or inspect.isroutine(object) or inspect.isframe(object) or inspect.istraceback(object) or inspect.iscode(object))
[ "def", "isdata", "(", "object", ")", ":", "return", "not", "(", "inspect", ".", "ismodule", "(", "object", ")", "or", "inspect", ".", "isclass", "(", "object", ")", "or", "inspect", ".", "isroutine", "(", "object", ")", "or", "inspect", ".", "isframe",...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/pydoc.py#L102-L106
shader-slang/slang
b8982fcf43b86c1e39dcc3dd19bff2821633eda6
external/vulkan/registry/conventions.py
python
ConventionsBase._implMakeProseList
(self, elements, fmt, with_verb, comma_for_two_elts=False, serial_comma=True)
return ''.join(parts)
Internal-use implementation to make a (comma-separated) list for use in prose. Adds a connective (by default, 'and') before the last element if there are more than 1, and only includes commas if there are more than 2 (if comma_for_two_elts is False). Adds the right one of "is" or "are" to the end if with_verb is true. Optionally adds a quantifier (like 'any') before a list of 2 or more, if specified by fmt. Don't edit these defaults, override self.makeProseList().
Internal-use implementation to make a (comma-separated) list for use in prose.
[ "Internal", "-", "use", "implementation", "to", "make", "a", "(", "comma", "-", "separated", ")", "list", "for", "use", "in", "prose", "." ]
def _implMakeProseList(self, elements, fmt, with_verb, comma_for_two_elts=False, serial_comma=True): """Internal-use implementation to make a (comma-separated) list for use in prose. Adds a connective (by default, 'and') before the last element if there are more than 1, and only includes commas if there are more than 2 (if comma_for_two_elts is False). Adds the right one of "is" or "are" to the end if with_verb is true. Optionally adds a quantifier (like 'any') before a list of 2 or more, if specified by fmt. Don't edit these defaults, override self.makeProseList(). """ assert(serial_comma) # didn't implement what we didn't need if isinstance(fmt, str): fmt = ProseListFormats.from_string(fmt) my_elts = list(elements) if len(my_elts) > 1: my_elts[-1] = '{} {}'.format(fmt.connective, my_elts[-1]) if not comma_for_two_elts and len(my_elts) <= 2: prose = ' '.join(my_elts) else: prose = ', '.join(my_elts) quantifier = fmt.quantifier(len(my_elts)) parts = [quantifier, prose] if with_verb: if len(my_elts) > 1: parts.append(' are') else: parts.append(' is') return ''.join(parts)
[ "def", "_implMakeProseList", "(", "self", ",", "elements", ",", "fmt", ",", "with_verb", ",", "comma_for_two_elts", "=", "False", ",", "serial_comma", "=", "True", ")", ":", "assert", "(", "serial_comma", ")", "# didn't implement what we didn't need", "if", "isins...
https://github.com/shader-slang/slang/blob/b8982fcf43b86c1e39dcc3dd19bff2821633eda6/external/vulkan/registry/conventions.py#L129-L166
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/_vendor/requests/cookies.py
python
RequestsCookieJar.items
(self)
return list(self.iteritems())
Dict-like items() that returns a list of name-value tuples from the jar. See keys() and values(). Allows client-code to call ``dict(RequestsCookieJar)`` and get a vanilla python dict of key value pairs.
Dict-like items() that returns a list of name-value tuples from the jar. See keys() and values(). Allows client-code to call ``dict(RequestsCookieJar)`` and get a vanilla python dict of key value pairs.
[ "Dict", "-", "like", "items", "()", "that", "returns", "a", "list", "of", "name", "-", "value", "tuples", "from", "the", "jar", ".", "See", "keys", "()", "and", "values", "()", ".", "Allows", "client", "-", "code", "to", "call", "dict", "(", "Request...
def items(self): """Dict-like items() that returns a list of name-value tuples from the jar. See keys() and values(). Allows client-code to call ``dict(RequestsCookieJar)`` and get a vanilla python dict of key value pairs.""" return list(self.iteritems())
[ "def", "items", "(", "self", ")", ":", "return", "list", "(", "self", ".", "iteritems", "(", ")", ")" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/requests/cookies.py#L232-L237
forkineye/ESPixelStick
22926f1c0d1131f1369fc7cad405689a095ae3cb
dist/bin/esptool/serial/serialposix.py
python
Serial._update_rts_state
(self)
Set terminal status line: Request To Send
Set terminal status line: Request To Send
[ "Set", "terminal", "status", "line", ":", "Request", "To", "Send" ]
def _update_rts_state(self): """Set terminal status line: Request To Send""" if self._rts_state: fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_RTS_str) else: fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_RTS_str)
[ "def", "_update_rts_state", "(", "self", ")", ":", "if", "self", ".", "_rts_state", ":", "fcntl", ".", "ioctl", "(", "self", ".", "fd", ",", "TIOCMBIS", ",", "TIOCM_RTS_str", ")", "else", ":", "fcntl", ".", "ioctl", "(", "self", ".", "fd", ",", "TIOC...
https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/esptool/serial/serialposix.py#L624-L629
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemWebCommunicator/AWS/common-code/lib/AWSIoTPythonSDK/core/protocol/paho/client.py
python
Client.want_write
(self)
Call to determine if there is network data waiting to be written. Useful if you are calling select() yourself rather than using loop().
Call to determine if there is network data waiting to be written. Useful if you are calling select() yourself rather than using loop().
[ "Call", "to", "determine", "if", "there", "is", "network", "data", "waiting", "to", "be", "written", ".", "Useful", "if", "you", "are", "calling", "select", "()", "yourself", "rather", "than", "using", "loop", "()", "." ]
def want_write(self): """Call to determine if there is network data waiting to be written. Useful if you are calling select() yourself rather than using loop(). """ if self._current_out_packet or len(self._out_packet) > 0: return True else: return False
[ "def", "want_write", "(", "self", ")", ":", "if", "self", ".", "_current_out_packet", "or", "len", "(", "self", ".", "_out_packet", ")", ">", "0", ":", "return", "True", "else", ":", "return", "False" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemWebCommunicator/AWS/common-code/lib/AWSIoTPythonSDK/core/protocol/paho/client.py#L1201-L1208
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/turtle.py
python
TNavigator.goto
(self, x, y=None)
Move turtle to an absolute position. Aliases: setpos | setposition | goto: Arguments: x -- a number or a pair/vector of numbers y -- a number None call: goto(x, y) # two coordinates --or: goto((x, y)) # a pair (tuple) of coordinates --or: goto(vec) # e.g. as returned by pos() Move turtle to an absolute position. If the pen is down, a line will be drawn. The turtle's orientation does not change. Example (for a Turtle instance named turtle): >>> tp = turtle.pos() >>> tp (0.00, 0.00) >>> turtle.setpos(60,30) >>> turtle.pos() (60.00,30.00) >>> turtle.setpos((20,80)) >>> turtle.pos() (20.00,80.00) >>> turtle.setpos(tp) >>> turtle.pos() (0.00,0.00)
Move turtle to an absolute position.
[ "Move", "turtle", "to", "an", "absolute", "position", "." ]
def goto(self, x, y=None): """Move turtle to an absolute position. Aliases: setpos | setposition | goto: Arguments: x -- a number or a pair/vector of numbers y -- a number None call: goto(x, y) # two coordinates --or: goto((x, y)) # a pair (tuple) of coordinates --or: goto(vec) # e.g. as returned by pos() Move turtle to an absolute position. If the pen is down, a line will be drawn. The turtle's orientation does not change. Example (for a Turtle instance named turtle): >>> tp = turtle.pos() >>> tp (0.00, 0.00) >>> turtle.setpos(60,30) >>> turtle.pos() (60.00,30.00) >>> turtle.setpos((20,80)) >>> turtle.pos() (20.00,80.00) >>> turtle.setpos(tp) >>> turtle.pos() (0.00,0.00) """ if y is None: self._goto(Vec2D(*x)) else: self._goto(Vec2D(x, y))
[ "def", "goto", "(", "self", ",", "x", ",", "y", "=", "None", ")", ":", "if", "y", "is", "None", ":", "self", ".", "_goto", "(", "Vec2D", "(", "*", "x", ")", ")", "else", ":", "self", ".", "_goto", "(", "Vec2D", "(", "x", ",", "y", ")", ")...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/turtle.py#L1658-L1691