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
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/graph_editor/util.py
python
make_placeholder_from_dtype_and_shape
(dtype, shape=None, scope=None, prefix=_DEFAULT_PLACEHOLDER_PREFIX)
return tf_array_ops.placeholder( dtype=dtype, shape=shape, name=placeholder_name(scope=scope, prefix=prefix))
Create a tf.compat.v1.placeholder for the Graph Editor. Note that the correct graph scope must be set by the calling function. The placeholder is named using the function placeholder_name (with no tensor argument). Args: dtype: the tensor type. shape: the tensor shape (optional). scope: absolute scope within which to create the placeholder. None means that the scope of t is preserved. "" means the root scope. prefix: placeholder name prefix. Returns: A newly created tf.placeholder.
Create a tf.compat.v1.placeholder for the Graph Editor.
[ "Create", "a", "tf", ".", "compat", ".", "v1", ".", "placeholder", "for", "the", "Graph", "Editor", "." ]
def make_placeholder_from_dtype_and_shape(dtype, shape=None, scope=None, prefix=_DEFAULT_PLACEHOLDER_PREFIX): """Create a tf.compat.v1.placeholder for the Graph Editor. Note that the correct graph scope must be set by the calling function. The placeholder is named using the function placeholder_name (with no tensor argument). Args: dtype: the tensor type. shape: the tensor shape (optional). scope: absolute scope within which to create the placeholder. None means that the scope of t is preserved. "" means the root scope. prefix: placeholder name prefix. Returns: A newly created tf.placeholder. """ return tf_array_ops.placeholder( dtype=dtype, shape=shape, name=placeholder_name(scope=scope, prefix=prefix))
[ "def", "make_placeholder_from_dtype_and_shape", "(", "dtype", ",", "shape", "=", "None", ",", "scope", "=", "None", ",", "prefix", "=", "_DEFAULT_PLACEHOLDER_PREFIX", ")", ":", "return", "tf_array_ops", ".", "placeholder", "(", "dtype", "=", "dtype", ",", "shape", "=", "shape", ",", "name", "=", "placeholder_name", "(", "scope", "=", "scope", ",", "prefix", "=", "prefix", ")", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/graph_editor/util.py#L474-L494
r-barnes/richdem
9e2646153c5b96cb4e6802a5a0c484b72ff9e622
wrappers/pyrichdem/richdem/__init__.py
python
FillDepressions
( dem, epsilon = False, in_place = False, topology = 'D8' )
Fills all depressions in a DEM. Args: dem (rdarray): An elevation model epsilon (float): If True, an epsilon gradient is imposed to all flat regions. This ensures that there is always a local gradient. in_place (bool): If True, the DEM is modified in place and there is no return; otherwise, a new, altered DEM is returned. topology (string): A topology indicator Returns: DEM without depressions.
Fills all depressions in a DEM.
[ "Fills", "all", "depressions", "in", "a", "DEM", "." ]
def FillDepressions( dem, epsilon = False, in_place = False, topology = 'D8' ): """Fills all depressions in a DEM. Args: dem (rdarray): An elevation model epsilon (float): If True, an epsilon gradient is imposed to all flat regions. This ensures that there is always a local gradient. in_place (bool): If True, the DEM is modified in place and there is no return; otherwise, a new, altered DEM is returned. topology (string): A topology indicator Returns: DEM without depressions. """ if type(dem) is not rdarray: raise Exception("A richdem.rdarray or numpy.ndarray is required!") if topology not in ['D8','D4']: raise Exception("Unknown topology!") if not in_place: dem = dem.copy() _AddAnalysis(dem, "FillDepressions(dem, epsilon={0})".format(epsilon)) demw = dem.wrap() if epsilon: if topology=='D8': _richdem.rdPFepsilonD8(demw) elif topology=='D4': _richdem.rdPFepsilonD4(demw) else: if topology=='D8': _richdem.rdFillDepressionsD8(demw) elif topology=='D4': _richdem.rdFillDepressionsD4(demw) dem.copyFromWrapped(demw) if not in_place: return dem
[ "def", "FillDepressions", "(", "dem", ",", "epsilon", "=", "False", ",", "in_place", "=", "False", ",", "topology", "=", "'D8'", ")", ":", "if", "type", "(", "dem", ")", "is", "not", "rdarray", ":", "raise", "Exception", "(", "\"A richdem.rdarray or numpy.ndarray is required!\"", ")", "if", "topology", "not", "in", "[", "'D8'", ",", "'D4'", "]", ":", "raise", "Exception", "(", "\"Unknown topology!\"", ")", "if", "not", "in_place", ":", "dem", "=", "dem", ".", "copy", "(", ")", "_AddAnalysis", "(", "dem", ",", "\"FillDepressions(dem, epsilon={0})\"", ".", "format", "(", "epsilon", ")", ")", "demw", "=", "dem", ".", "wrap", "(", ")", "if", "epsilon", ":", "if", "topology", "==", "'D8'", ":", "_richdem", ".", "rdPFepsilonD8", "(", "demw", ")", "elif", "topology", "==", "'D4'", ":", "_richdem", ".", "rdPFepsilonD4", "(", "demw", ")", "else", ":", "if", "topology", "==", "'D8'", ":", "_richdem", ".", "rdFillDepressionsD8", "(", "demw", ")", "elif", "topology", "==", "'D4'", ":", "_richdem", ".", "rdFillDepressionsD4", "(", "demw", ")", "dem", ".", "copyFromWrapped", "(", "demw", ")", "if", "not", "in_place", ":", "return", "dem" ]
https://github.com/r-barnes/richdem/blob/9e2646153c5b96cb4e6802a5a0c484b72ff9e622/wrappers/pyrichdem/richdem/__init__.py#L323-L369
dicecco1/fpga_caffe
7a191704efd7873071cfef35772d7e7bf3e3cfd6
scripts/cpp_lint.py
python
IsCppString
(line)
return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
Does line terminate so, that the next symbol is in string constant. This function does not consider single-line nor multi-line comments. Args: line: is a partial line of code starting from the 0..n. Returns: True, if next character appended to 'line' is inside a string constant.
Does line terminate so, that the next symbol is in string constant.
[ "Does", "line", "terminate", "so", "that", "the", "next", "symbol", "is", "in", "string", "constant", "." ]
def IsCppString(line): """Does line terminate so, that the next symbol is in string constant. This function does not consider single-line nor multi-line comments. Args: line: is a partial line of code starting from the 0..n. Returns: True, if next character appended to 'line' is inside a string constant. """ line = line.replace(r'\\', 'XX') # after this, \\" does not match to \" return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
[ "def", "IsCppString", "(", "line", ")", ":", "line", "=", "line", ".", "replace", "(", "r'\\\\'", ",", "'XX'", ")", "# after this, \\\\\" does not match to \\\"", "return", "(", "(", "line", ".", "count", "(", "'\"'", ")", "-", "line", ".", "count", "(", "r'\\\"'", ")", "-", "line", ".", "count", "(", "\"'\\\"'\"", ")", ")", "&", "1", ")", "==", "1" ]
https://github.com/dicecco1/fpga_caffe/blob/7a191704efd7873071cfef35772d7e7bf3e3cfd6/scripts/cpp_lint.py#L1049-L1063
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/wsgiref/handlers.py
python
BaseHandler._flush
(self)
Override in subclass to force sending of recent '_write()' calls It's okay if this method is a no-op (i.e., if '_write()' actually sends the data.
Override in subclass to force sending of recent '_write()' calls
[ "Override", "in", "subclass", "to", "force", "sending", "of", "recent", "_write", "()", "calls" ]
def _flush(self): """Override in subclass to force sending of recent '_write()' calls It's okay if this method is a no-op (i.e., if '_write()' actually sends the data. """ raise NotImplementedError
[ "def", "_flush", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/wsgiref/handlers.py#L341-L347
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/decimal.py
python
Decimal.__nonzero__
(self)
return self._is_special or self._int != '0'
Return True if self is nonzero; otherwise return False. NaNs and infinities are considered nonzero.
Return True if self is nonzero; otherwise return False.
[ "Return", "True", "if", "self", "is", "nonzero", ";", "otherwise", "return", "False", "." ]
def __nonzero__(self): """Return True if self is nonzero; otherwise return False. NaNs and infinities are considered nonzero. """ return self._is_special or self._int != '0'
[ "def", "__nonzero__", "(", "self", ")", ":", "return", "self", ".", "_is_special", "or", "self", ".", "_int", "!=", "'0'" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/decimal.py#L793-L798
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
GBSpan.GetColspan
(*args, **kwargs)
return _core_.GBSpan_GetColspan(*args, **kwargs)
GetColspan(self) -> int
GetColspan(self) -> int
[ "GetColspan", "(", "self", ")", "-", ">", "int" ]
def GetColspan(*args, **kwargs): """GetColspan(self) -> int""" return _core_.GBSpan_GetColspan(*args, **kwargs)
[ "def", "GetColspan", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "GBSpan_GetColspan", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L15660-L15662
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/graph_editor/reroute.py
python
reroute_b2a
(sgv0, sgv1)
return _reroute_sgv(sgv0, sgv1, _RerouteMode.b2a)
Re-route the inputs and outputs of sgv1 to sgv0 (see _reroute).
Re-route the inputs and outputs of sgv1 to sgv0 (see _reroute).
[ "Re", "-", "route", "the", "inputs", "and", "outputs", "of", "sgv1", "to", "sgv0", "(", "see", "_reroute", ")", "." ]
def reroute_b2a(sgv0, sgv1): """Re-route the inputs and outputs of sgv1 to sgv0 (see _reroute).""" return _reroute_sgv(sgv0, sgv1, _RerouteMode.b2a)
[ "def", "reroute_b2a", "(", "sgv0", ",", "sgv1", ")", ":", "return", "_reroute_sgv", "(", "sgv0", ",", "sgv1", ",", "_RerouteMode", ".", "b2a", ")" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/graph_editor/reroute.py#L438-L440
apache/madlib
be297fe6beada0640f93317e8948834032718e32
src/madpack/upgrade_util.py
python
ScriptCleaner._get_existing_udo
(self)
@brief Get the existing UDOs in the current version
[]
def _get_existing_udo(self): """ @brief Get the existing UDOs in the current version """ rows = self._run_sql(""" SELECT oprname, oprleft::regtype, oprright::regtype FROM pg_operator AS o, pg_namespace AS ns WHERE o.oprnamespace = ns.oid AND ns.nspname = '{schema}' """.format(schema=self._schema.lower())) self._existing_udo = defaultdict(list) for row in rows: self._existing_udo[row['oprname']].append( {'leftarg': row['oprleft'], 'rightarg': row['oprright']})
[ "def", "_get_existing_udo", "(", "self", ")", ":", "rows", "=", "self", ".", "_run_sql", "(", "\"\"\"\n SELECT\n oprname, oprleft::regtype, oprright::regtype\n FROM\n pg_operator AS o, pg_namespace AS ns\n WHERE\n o.oprnamespace = ns.oid AND\n ns.nspname = '{schema}'\n \"\"\"", ".", "format", "(", "schema", "=", "self", ".", "_schema", ".", "lower", "(", ")", ")", ")", "self", ".", "_existing_udo", "=", "defaultdict", "(", "list", ")", "for", "row", "in", "rows", ":", "self", ".", "_existing_udo", "[", "row", "[", "'oprname'", "]", "]", ".", "append", "(", "{", "'leftarg'", ":", "row", "[", "'oprleft'", "]", ",", "'rightarg'", ":", "row", "[", "'oprright'", "]", "}", ")" ]
https://github.com/apache/madlib/blob/be297fe6beada0640f93317e8948834032718e32/src/madpack/upgrade_util.py#L1003-L1020
infinisql/infinisql
6e858e142196e20b6779e1ee84c4a501e246c1f8
manager/infinisqlmgr/management/whisper.py
python
fetch
(path,fromTime,untilTime=None)
return file_fetch(fh, fromTime, untilTime)
fetch(path,fromTime,untilTime=None) path is a string fromTime is an epoch time untilTime is also an epoch time, but defaults to now. Returns a tuple of (timeInfo, valueList) where timeInfo is itself a tuple of (fromTime, untilTime, step) Returns None if no data can be returned
fetch(path,fromTime,untilTime=None)
[ "fetch", "(", "path", "fromTime", "untilTime", "=", "None", ")" ]
def fetch(path,fromTime,untilTime=None): """fetch(path,fromTime,untilTime=None) path is a string fromTime is an epoch time untilTime is also an epoch time, but defaults to now. Returns a tuple of (timeInfo, valueList) where timeInfo is itself a tuple of (fromTime, untilTime, step) Returns None if no data can be returned """ fh = open(path,'rb') return file_fetch(fh, fromTime, untilTime)
[ "def", "fetch", "(", "path", ",", "fromTime", ",", "untilTime", "=", "None", ")", ":", "fh", "=", "open", "(", "path", ",", "'rb'", ")", "return", "file_fetch", "(", "fh", ",", "fromTime", ",", "untilTime", ")" ]
https://github.com/infinisql/infinisql/blob/6e858e142196e20b6779e1ee84c4a501e246c1f8/manager/infinisqlmgr/management/whisper.py#L686-L699
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
tools/fast_nvcc/fast_nvcc.py
python
run_graph
( *, env: Dict[str, str], commands: List[str], graph: Graph, gather_data: bool = False, save: Optional[str] = None, )
return [await task for task in tasks]
Return outputs/errors (and optionally time/file info) from commands.
Return outputs/errors (and optionally time/file info) from commands.
[ "Return", "outputs", "/", "errors", "(", "and", "optionally", "time", "/", "file", "info", ")", "from", "commands", "." ]
async def run_graph( *, env: Dict[str, str], commands: List[str], graph: Graph, gather_data: bool = False, save: Optional[str] = None, ) -> List[Result]: """ Return outputs/errors (and optionally time/file info) from commands. """ tasks: List[Awaitable[Result]] = [] for i, (command, indices) in enumerate(zip(commands, graph)): deps = {tasks[j] for j in indices} tasks.append(asyncio.create_task(run_command( # type: ignore[attr-defined] command, env=env, deps=deps, gather_data=gather_data, i=i, save=save, ))) return [await task for task in tasks]
[ "async", "def", "run_graph", "(", "*", ",", "env", ":", "Dict", "[", "str", ",", "str", "]", ",", "commands", ":", "List", "[", "str", "]", ",", "graph", ":", "Graph", ",", "gather_data", ":", "bool", "=", "False", ",", "save", ":", "Optional", "[", "str", "]", "=", "None", ",", ")", "->", "List", "[", "Result", "]", ":", "tasks", ":", "List", "[", "Awaitable", "[", "Result", "]", "]", "=", "[", "]", "for", "i", ",", "(", "command", ",", "indices", ")", "in", "enumerate", "(", "zip", "(", "commands", ",", "graph", ")", ")", ":", "deps", "=", "{", "tasks", "[", "j", "]", "for", "j", "in", "indices", "}", "tasks", ".", "append", "(", "asyncio", ".", "create_task", "(", "run_command", "(", "# type: ignore[attr-defined]", "command", ",", "env", "=", "env", ",", "deps", "=", "deps", ",", "gather_data", "=", "gather_data", ",", "i", "=", "i", ",", "save", "=", "save", ",", ")", ")", ")", "return", "[", "await", "task", "for", "task", "in", "tasks", "]" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/tools/fast_nvcc/fast_nvcc.py#L413-L435
Slicer/Slicer
ba9fadf332cb0303515b68d8d06a344c82e3e3e5
Base/Python/slicer/util.py
python
findChildren
(widget=None, name="", text="", title="", className="")
return children
Return a list of child widgets that meet all the given criteria. If no criteria are provided, the function will return all widgets descendants. If no widget is provided, slicer.util.mainWindow() is used. :param widget: parent widget where the widgets will be searched :param name: name attribute of the widget :param text: text attribute of the widget :param title: title attribute of the widget :param className: className() attribute of the widget :return: list with all the widgets that meet all the given criteria.
Return a list of child widgets that meet all the given criteria.
[ "Return", "a", "list", "of", "child", "widgets", "that", "meet", "all", "the", "given", "criteria", "." ]
def findChildren(widget=None, name="", text="", title="", className=""): """ Return a list of child widgets that meet all the given criteria. If no criteria are provided, the function will return all widgets descendants. If no widget is provided, slicer.util.mainWindow() is used. :param widget: parent widget where the widgets will be searched :param name: name attribute of the widget :param text: text attribute of the widget :param title: title attribute of the widget :param className: className() attribute of the widget :return: list with all the widgets that meet all the given criteria. """ # TODO: figure out why the native QWidget.findChildren method does not seem to work from PythonQt import slicer, fnmatch if not widget: widget = mainWindow() if not widget: return [] children = [] parents = [widget] kwargs = {'name': name, 'text': text, 'title': title, 'className': className} expected_matches = [] for kwarg in kwargs.keys(): if kwargs[kwarg]: expected_matches.append(kwarg) while parents: p = parents.pop() # sometimes, p is null, f.e. when using --python-script or --python-code if not p: continue if not hasattr(p,'children'): continue parents += p.children() matched_filter_criteria = 0 for attribute in expected_matches: if hasattr(p, attribute): attr_name = getattr(p, attribute) if attribute == 'className': # className is a method, not a direct attribute. Invoke the method attr_name = attr_name() # Objects may have text attributes with non-string value (for example, # QUndoStack objects have text attribute of 'builtin_qt_slot' type. # We only consider string type attributes. if isinstance(attr_name, str): if fnmatch.fnmatchcase(attr_name, kwargs[attribute]): matched_filter_criteria = matched_filter_criteria + 1 if matched_filter_criteria == len(expected_matches): children.append(p) return children
[ "def", "findChildren", "(", "widget", "=", "None", ",", "name", "=", "\"\"", ",", "text", "=", "\"\"", ",", "title", "=", "\"\"", ",", "className", "=", "\"\"", ")", ":", "# TODO: figure out why the native QWidget.findChildren method does not seem to work from PythonQt", "import", "slicer", ",", "fnmatch", "if", "not", "widget", ":", "widget", "=", "mainWindow", "(", ")", "if", "not", "widget", ":", "return", "[", "]", "children", "=", "[", "]", "parents", "=", "[", "widget", "]", "kwargs", "=", "{", "'name'", ":", "name", ",", "'text'", ":", "text", ",", "'title'", ":", "title", ",", "'className'", ":", "className", "}", "expected_matches", "=", "[", "]", "for", "kwarg", "in", "kwargs", ".", "keys", "(", ")", ":", "if", "kwargs", "[", "kwarg", "]", ":", "expected_matches", ".", "append", "(", "kwarg", ")", "while", "parents", ":", "p", "=", "parents", ".", "pop", "(", ")", "# sometimes, p is null, f.e. when using --python-script or --python-code", "if", "not", "p", ":", "continue", "if", "not", "hasattr", "(", "p", ",", "'children'", ")", ":", "continue", "parents", "+=", "p", ".", "children", "(", ")", "matched_filter_criteria", "=", "0", "for", "attribute", "in", "expected_matches", ":", "if", "hasattr", "(", "p", ",", "attribute", ")", ":", "attr_name", "=", "getattr", "(", "p", ",", "attribute", ")", "if", "attribute", "==", "'className'", ":", "# className is a method, not a direct attribute. Invoke the method", "attr_name", "=", "attr_name", "(", ")", "# Objects may have text attributes with non-string value (for example,", "# QUndoStack objects have text attribute of 'builtin_qt_slot' type.", "# We only consider string type attributes.", "if", "isinstance", "(", "attr_name", ",", "str", ")", ":", "if", "fnmatch", ".", "fnmatchcase", "(", "attr_name", ",", "kwargs", "[", "attribute", "]", ")", ":", "matched_filter_criteria", "=", "matched_filter_criteria", "+", "1", "if", "matched_filter_criteria", "==", "len", "(", "expected_matches", ")", ":", "children", ".", "append", "(", "p", ")", "return", "children" ]
https://github.com/Slicer/Slicer/blob/ba9fadf332cb0303515b68d8d06a344c82e3e3e5/Base/Python/slicer/util.py#L239-L287
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/stc.py
python
StyledTextCtrl.__init__
(self, *args, **kwargs)
__init__(self, Window parent, int id=ID_ANY, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, String name=STCNameStr) -> StyledTextCtrl
__init__(self, Window parent, int id=ID_ANY, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, String name=STCNameStr) -> StyledTextCtrl
[ "__init__", "(", "self", "Window", "parent", "int", "id", "=", "ID_ANY", "Point", "pos", "=", "DefaultPosition", "Size", "size", "=", "DefaultSize", "long", "style", "=", "0", "String", "name", "=", "STCNameStr", ")", "-", ">", "StyledTextCtrl" ]
def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=ID_ANY, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, String name=STCNameStr) -> StyledTextCtrl """ _stc.StyledTextCtrl_swiginit(self,_stc.new_StyledTextCtrl(*args, **kwargs)) self._setOORInfo(self)
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_stc", ".", "StyledTextCtrl_swiginit", "(", "self", ",", "_stc", ".", "new_StyledTextCtrl", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "self", ".", "_setOORInfo", "(", "self", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L2020-L2026
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/json_schema_compiler/dart_generator.py
python
_Generator._NeedsProxy
(self, f)
return any(not self._IsBaseType(p.type_) for p in f.params)
Given a function, returns True if it needs to be proxied, False if not. A function needs to be proxied if any of its members are non-base types. This means that, when the function object is passed to Javascript, it needs to be wrapped in a "proxied" call that converts the JS inputs to Dart objects explicitly, before calling the real function with these new objects.
Given a function, returns True if it needs to be proxied, False if not.
[ "Given", "a", "function", "returns", "True", "if", "it", "needs", "to", "be", "proxied", "False", "if", "not", "." ]
def _NeedsProxy(self, f): """Given a function, returns True if it needs to be proxied, False if not. A function needs to be proxied if any of its members are non-base types. This means that, when the function object is passed to Javascript, it needs to be wrapped in a "proxied" call that converts the JS inputs to Dart objects explicitly, before calling the real function with these new objects. """ return any(not self._IsBaseType(p.type_) for p in f.params)
[ "def", "_NeedsProxy", "(", "self", ",", "f", ")", ":", "return", "any", "(", "not", "self", ".", "_IsBaseType", "(", "p", ".", "type_", ")", "for", "p", "in", "f", ".", "params", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/json_schema_compiler/dart_generator.py#L359-L367
koth/kcws
88efbd36a7022de4e6e90f5a1fb880cf87cfae9f
third_party/setuptools/pkg_resources.py
python
IMetadataProvider.metadata_listdir
(name)
List of metadata names in the directory (like ``os.listdir()``)
List of metadata names in the directory (like ``os.listdir()``)
[ "List", "of", "metadata", "names", "in", "the", "directory", "(", "like", "os", ".", "listdir", "()", ")" ]
def metadata_listdir(name): """List of metadata names in the directory (like ``os.listdir()``)"""
[ "def", "metadata_listdir", "(", "name", ")", ":" ]
https://github.com/koth/kcws/blob/88efbd36a7022de4e6e90f5a1fb880cf87cfae9f/third_party/setuptools/pkg_resources.py#L384-L385
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/model/trajectory.py
python
HermiteTrajectory.makeBezier
(self, times: List[float], controlPoints: List[Vector])
Sets up this spline to perform Bezier interpolation of the given control points, with segment 0 a Bezier curve on cps[0:3], segment 1 a Bezier curve on cps[3:6], etc.
Sets up this spline to perform Bezier interpolation of the given control points, with segment 0 a Bezier curve on cps[0:3], segment 1 a Bezier curve on cps[3:6], etc.
[ "Sets", "up", "this", "spline", "to", "perform", "Bezier", "interpolation", "of", "the", "given", "control", "points", "with", "segment", "0", "a", "Bezier", "curve", "on", "cps", "[", "0", ":", "3", "]", "segment", "1", "a", "Bezier", "curve", "on", "cps", "[", "3", ":", "6", "]", "etc", "." ]
def makeBezier(self, times: List[float], controlPoints: List[Vector]) -> None: """Sets up this spline to perform Bezier interpolation of the given control points, with segment 0 a Bezier curve on cps[0:3], segment 1 a Bezier curve on cps[3:6], etc. """ nsegs = len(times)-1 if nsegs*3+1 != len(controlPoints): raise ValueError("To perform Bezier interpolation, need # of controlPoints to be 3*Nsegs+1") newtimes = [] milestones = [] outgoingVelocities = [] for i in range(0,len(times)-1): a,b,c,d = controlPoints[i*3:i*3+4] dt = times[i+1]-times[i] if dt <= 0: raise ValueError("Times must be strictly monotonically increasing") lieDeriv0 = vectorops.mul(vectorops.sub(b,a),3/dt) lieDeriv1 = vectorops.mul(vectorops.sub(c,d),-3/dt) if i > 0: if vectorops.distance(lieDeriv0,outgoingVelocities[-1]) > 1e-4: #need to double up knot point newtimes.append(newtimes[-1]) milestones.append(milestones[-1]) outgoingVelocities.append(lieDeriv0) else: newtimes.append(times[i]) milestones.append(a) outgoingVelocities.append(lieDeriv0) newtimes.append(times[i+1]) milestones.append(d) outgoingVelocities.append(lieDeriv1) self.__init__(newtimes,milestones,outgoingVelocities)
[ "def", "makeBezier", "(", "self", ",", "times", ":", "List", "[", "float", "]", ",", "controlPoints", ":", "List", "[", "Vector", "]", ")", "->", "None", ":", "nsegs", "=", "len", "(", "times", ")", "-", "1", "if", "nsegs", "*", "3", "+", "1", "!=", "len", "(", "controlPoints", ")", ":", "raise", "ValueError", "(", "\"To perform Bezier interpolation, need # of controlPoints to be 3*Nsegs+1\"", ")", "newtimes", "=", "[", "]", "milestones", "=", "[", "]", "outgoingVelocities", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "times", ")", "-", "1", ")", ":", "a", ",", "b", ",", "c", ",", "d", "=", "controlPoints", "[", "i", "*", "3", ":", "i", "*", "3", "+", "4", "]", "dt", "=", "times", "[", "i", "+", "1", "]", "-", "times", "[", "i", "]", "if", "dt", "<=", "0", ":", "raise", "ValueError", "(", "\"Times must be strictly monotonically increasing\"", ")", "lieDeriv0", "=", "vectorops", ".", "mul", "(", "vectorops", ".", "sub", "(", "b", ",", "a", ")", ",", "3", "/", "dt", ")", "lieDeriv1", "=", "vectorops", ".", "mul", "(", "vectorops", ".", "sub", "(", "c", ",", "d", ")", ",", "-", "3", "/", "dt", ")", "if", "i", ">", "0", ":", "if", "vectorops", ".", "distance", "(", "lieDeriv0", ",", "outgoingVelocities", "[", "-", "1", "]", ")", ">", "1e-4", ":", "#need to double up knot point", "newtimes", ".", "append", "(", "newtimes", "[", "-", "1", "]", ")", "milestones", ".", "append", "(", "milestones", "[", "-", "1", "]", ")", "outgoingVelocities", ".", "append", "(", "lieDeriv0", ")", "else", ":", "newtimes", ".", "append", "(", "times", "[", "i", "]", ")", "milestones", ".", "append", "(", "a", ")", "outgoingVelocities", ".", "append", "(", "lieDeriv0", ")", "newtimes", ".", "append", "(", "times", "[", "i", "+", "1", "]", ")", "milestones", ".", "append", "(", "d", ")", "outgoingVelocities", ".", "append", "(", "lieDeriv1", ")", "self", ".", "__init__", "(", "newtimes", ",", "milestones", ",", "outgoingVelocities", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/model/trajectory.py#L886-L916
hfinkel/llvm-project-cxxjit
91084ef018240bbb8e24235ff5cd8c355a9c1a1e
compiler-rt/lib/sanitizer_common/scripts/cpplint.py
python
_SetCountingStyle
(level)
Sets the module's counting options.
Sets the module's counting options.
[ "Sets", "the", "module", "s", "counting", "options", "." ]
def _SetCountingStyle(level): """Sets the module's counting options.""" _cpplint_state.SetCountingStyle(level)
[ "def", "_SetCountingStyle", "(", "level", ")", ":", "_cpplint_state", ".", "SetCountingStyle", "(", "level", ")" ]
https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L651-L653
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/kms/layer1.py
python
KMSConnection.create_alias
(self, alias_name, target_key_id)
return self.make_request(action='CreateAlias', body=json.dumps(params))
Creates a display name for a customer master key. An alias can be used to identify a key and should be unique. The console enforces a one-to-one mapping between the alias and a key. An alias name can contain only alphanumeric characters, forward slashes (/), underscores (_), and dashes (-). An alias must start with the word "alias" followed by a forward slash (alias/). An alias that begins with "aws" after the forward slash (alias/aws...) is reserved by Amazon Web Services (AWS). :type alias_name: string :param alias_name: String that contains the display name. Aliases that begin with AWS are reserved. :type target_key_id: string :param target_key_id: An identifier of the key for which you are creating the alias. This value cannot be another alias.
Creates a display name for a customer master key. An alias can be used to identify a key and should be unique. The console enforces a one-to-one mapping between the alias and a key. An alias name can contain only alphanumeric characters, forward slashes (/), underscores (_), and dashes (-). An alias must start with the word "alias" followed by a forward slash (alias/). An alias that begins with "aws" after the forward slash (alias/aws...) is reserved by Amazon Web Services (AWS).
[ "Creates", "a", "display", "name", "for", "a", "customer", "master", "key", ".", "An", "alias", "can", "be", "used", "to", "identify", "a", "key", "and", "should", "be", "unique", ".", "The", "console", "enforces", "a", "one", "-", "to", "-", "one", "mapping", "between", "the", "alias", "and", "a", "key", ".", "An", "alias", "name", "can", "contain", "only", "alphanumeric", "characters", "forward", "slashes", "(", "/", ")", "underscores", "(", "_", ")", "and", "dashes", "(", "-", ")", ".", "An", "alias", "must", "start", "with", "the", "word", "alias", "followed", "by", "a", "forward", "slash", "(", "alias", "/", ")", ".", "An", "alias", "that", "begins", "with", "aws", "after", "the", "forward", "slash", "(", "alias", "/", "aws", "...", ")", "is", "reserved", "by", "Amazon", "Web", "Services", "(", "AWS", ")", "." ]
def create_alias(self, alias_name, target_key_id): """ Creates a display name for a customer master key. An alias can be used to identify a key and should be unique. The console enforces a one-to-one mapping between the alias and a key. An alias name can contain only alphanumeric characters, forward slashes (/), underscores (_), and dashes (-). An alias must start with the word "alias" followed by a forward slash (alias/). An alias that begins with "aws" after the forward slash (alias/aws...) is reserved by Amazon Web Services (AWS). :type alias_name: string :param alias_name: String that contains the display name. Aliases that begin with AWS are reserved. :type target_key_id: string :param target_key_id: An identifier of the key for which you are creating the alias. This value cannot be another alias. """ params = { 'AliasName': alias_name, 'TargetKeyId': target_key_id, } return self.make_request(action='CreateAlias', body=json.dumps(params))
[ "def", "create_alias", "(", "self", ",", "alias_name", ",", "target_key_id", ")", ":", "params", "=", "{", "'AliasName'", ":", "alias_name", ",", "'TargetKeyId'", ":", "target_key_id", ",", "}", "return", "self", ".", "make_request", "(", "action", "=", "'CreateAlias'", ",", "body", "=", "json", ".", "dumps", "(", "params", ")", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/kms/layer1.py#L131-L156
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/list_ops.py
python
_TensorListFromTensorGrad
(op, dlist)
return tensor_grad, shape_grad
Gradient for TensorListFromTensor.
Gradient for TensorListFromTensor.
[ "Gradient", "for", "TensorListFromTensor", "." ]
def _TensorListFromTensorGrad(op, dlist): """Gradient for TensorListFromTensor.""" t = op.inputs[0] if t.shape.dims and t.shape.dims[0].value is not None: num_elements = t.shape.dims[0].value else: num_elements = None if dlist is None: dlist = empty_tensor_list( element_dtype=t.dtype, element_shape=gen_list_ops.tensor_list_element_shape( op.outputs[0], shape_type=dtypes.int32)) tensor_grad = gen_list_ops.tensor_list_stack( dlist, element_shape=array_ops.slice(array_ops.shape(t), [1], [-1]), element_dtype=t.dtype, num_elements=num_elements) shape_grad = None return tensor_grad, shape_grad
[ "def", "_TensorListFromTensorGrad", "(", "op", ",", "dlist", ")", ":", "t", "=", "op", ".", "inputs", "[", "0", "]", "if", "t", ".", "shape", ".", "dims", "and", "t", ".", "shape", ".", "dims", "[", "0", "]", ".", "value", "is", "not", "None", ":", "num_elements", "=", "t", ".", "shape", ".", "dims", "[", "0", "]", ".", "value", "else", ":", "num_elements", "=", "None", "if", "dlist", "is", "None", ":", "dlist", "=", "empty_tensor_list", "(", "element_dtype", "=", "t", ".", "dtype", ",", "element_shape", "=", "gen_list_ops", ".", "tensor_list_element_shape", "(", "op", ".", "outputs", "[", "0", "]", ",", "shape_type", "=", "dtypes", ".", "int32", ")", ")", "tensor_grad", "=", "gen_list_ops", ".", "tensor_list_stack", "(", "dlist", ",", "element_shape", "=", "array_ops", ".", "slice", "(", "array_ops", ".", "shape", "(", "t", ")", ",", "[", "1", "]", ",", "[", "-", "1", "]", ")", ",", "element_dtype", "=", "t", ".", "dtype", ",", "num_elements", "=", "num_elements", ")", "shape_grad", "=", "None", "return", "tensor_grad", ",", "shape_grad" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/list_ops.py#L264-L282
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/server/wsgi/common/utils.py
python
GetPostgresHost
()
return None
Get postgres host for remote connections Returns: Host name of remote database to connect to or None.
Get postgres host for remote connections
[ "Get", "postgres", "host", "for", "remote", "connections" ]
def GetPostgresHost(): """Get postgres host for remote connections Returns: Host name of remote database to connect to or None. """ pattern = r"^\s*host\s*=\s*(\d{4,})\s*" match = MatchPattern(POSTGRES_PROPERTIES_PATH, pattern) if match: host = match[0] return host return None
[ "def", "GetPostgresHost", "(", ")", ":", "pattern", "=", "r\"^\\s*host\\s*=\\s*(\\d{4,})\\s*\"", "match", "=", "MatchPattern", "(", "POSTGRES_PROPERTIES_PATH", ",", "pattern", ")", "if", "match", ":", "host", "=", "match", "[", "0", "]", "return", "host", "return", "None" ]
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/server/wsgi/common/utils.py#L278-L291
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
models/AI-Model-Zoo/caffe-xilinx/examples/pycaffe/tools.py
python
SimpleTransformer.deprocess
(self, im)
return np.uint8(im)
inverse of preprocess()
inverse of preprocess()
[ "inverse", "of", "preprocess", "()" ]
def deprocess(self, im): """ inverse of preprocess() """ im = im.transpose(1, 2, 0) im /= self.scale im += self.mean im = im[:, :, ::-1] # change to RGB return np.uint8(im)
[ "def", "deprocess", "(", "self", ",", "im", ")", ":", "im", "=", "im", ".", "transpose", "(", "1", ",", "2", ",", "0", ")", "im", "/=", "self", ".", "scale", "im", "+=", "self", ".", "mean", "im", "=", "im", "[", ":", ",", ":", ",", ":", ":", "-", "1", "]", "# change to RGB", "return", "np", ".", "uint8", "(", "im", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/models/AI-Model-Zoo/caffe-xilinx/examples/pycaffe/tools.py#L41-L50
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/tools/gyp/pylib/gyp/generator/make.py
python
MakefileWriter.WriteSources
(self, configs, deps, sources, extra_outputs, extra_link_deps, part_of_all, precompiled_header)
Write Makefile code for any 'sources' from the gyp input. These are source files necessary to build the current target. configs, deps, sources: input from gyp. extra_outputs: a list of extra outputs this action should be dependent on; used to serialize action/rules before compilation extra_link_deps: a list that will be filled in with any outputs of compilation (to be used in link lines) part_of_all: flag indicating this target is part of 'all'
Write Makefile code for any 'sources' from the gyp input. These are source files necessary to build the current target.
[ "Write", "Makefile", "code", "for", "any", "sources", "from", "the", "gyp", "input", ".", "These", "are", "source", "files", "necessary", "to", "build", "the", "current", "target", "." ]
def WriteSources(self, configs, deps, sources, extra_outputs, extra_link_deps, part_of_all, precompiled_header): """Write Makefile code for any 'sources' from the gyp input. These are source files necessary to build the current target. configs, deps, sources: input from gyp. extra_outputs: a list of extra outputs this action should be dependent on; used to serialize action/rules before compilation extra_link_deps: a list that will be filled in with any outputs of compilation (to be used in link lines) part_of_all: flag indicating this target is part of 'all' """ # Write configuration-specific variables for CFLAGS, etc. for configname in sorted(configs.keys()): config = configs[configname] self.WriteList(config.get('defines'), 'DEFS_%s' % configname, prefix='-D', quoter=EscapeCppDefine) if self.flavor == 'mac': cflags = self.xcode_settings.GetCflags(configname) cflags_c = self.xcode_settings.GetCflagsC(configname) cflags_cc = self.xcode_settings.GetCflagsCC(configname) cflags_objc = self.xcode_settings.GetCflagsObjC(configname) cflags_objcc = self.xcode_settings.GetCflagsObjCC(configname) else: cflags = config.get('cflags') cflags_c = config.get('cflags_c') cflags_cc = config.get('cflags_cc') self.WriteLn("# Flags passed to all source files.") self.WriteList(cflags, 'CFLAGS_%s' % configname) self.WriteLn("# Flags passed to only C files.") self.WriteList(cflags_c, 'CFLAGS_C_%s' % configname) self.WriteLn("# Flags passed to only C++ files.") self.WriteList(cflags_cc, 'CFLAGS_CC_%s' % configname) if self.flavor == 'mac': self.WriteLn("# Flags passed to only ObjC files.") self.WriteList(cflags_objc, 'CFLAGS_OBJC_%s' % configname) self.WriteLn("# Flags passed to only ObjC++ files.") self.WriteList(cflags_objcc, 'CFLAGS_OBJCC_%s' % configname) includes = config.get('include_dirs') if includes: includes = [Sourceify(self.Absolutify(i)) for i in includes] self.WriteList(includes, 'INCS_%s' % configname, prefix='-I') compilable = list(filter(Compilable, sources)) objs = [self.Objectify(self.Absolutify(Target(c))) for c in compilable] self.WriteList(objs, 'OBJS') for obj in objs: assert ' ' not in obj, ( "Spaces in object filenames not supported (%s)" % obj) self.WriteLn('# Add to the list of files we specially track ' 'dependencies for.') self.WriteLn('all_deps += $(OBJS)') self.WriteLn() # Make sure our dependencies are built first. if deps: self.WriteMakeRule(['$(OBJS)'], deps, comment = 'Make sure our dependencies are built ' 'before any of us.', order_only = True) # Make sure the actions and rules run first. # If they generate any extra headers etc., the per-.o file dep tracking # will catch the proper rebuilds, so order only is still ok here. if extra_outputs: self.WriteMakeRule(['$(OBJS)'], extra_outputs, comment = 'Make sure our actions/rules run ' 'before any of us.', order_only = True) pchdeps = precompiled_header.GetObjDependencies(compilable, objs ) if pchdeps: self.WriteLn('# Dependencies from obj files to their precompiled headers') for source, obj, gch in pchdeps: self.WriteLn('%s: %s' % (obj, gch)) self.WriteLn('# End precompiled header dependencies') if objs: extra_link_deps.append('$(OBJS)') self.WriteLn("""\ # CFLAGS et al overrides must be target-local. # See "Target-specific Variable Values" in the GNU Make manual.""") self.WriteLn("$(OBJS): TOOLSET := $(TOOLSET)") self.WriteLn("$(OBJS): GYP_CFLAGS := " "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " "%s " % precompiled_header.GetInclude('c') + "$(CFLAGS_$(BUILDTYPE)) " "$(CFLAGS_C_$(BUILDTYPE))") self.WriteLn("$(OBJS): GYP_CXXFLAGS := " "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " "%s " % precompiled_header.GetInclude('cc') + "$(CFLAGS_$(BUILDTYPE)) " "$(CFLAGS_CC_$(BUILDTYPE))") if self.flavor == 'mac': self.WriteLn("$(OBJS): GYP_OBJCFLAGS := " "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " "%s " % precompiled_header.GetInclude('m') + "$(CFLAGS_$(BUILDTYPE)) " "$(CFLAGS_C_$(BUILDTYPE)) " "$(CFLAGS_OBJC_$(BUILDTYPE))") self.WriteLn("$(OBJS): GYP_OBJCXXFLAGS := " "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " "%s " % precompiled_header.GetInclude('mm') + "$(CFLAGS_$(BUILDTYPE)) " "$(CFLAGS_CC_$(BUILDTYPE)) " "$(CFLAGS_OBJCC_$(BUILDTYPE))") self.WritePchTargets(precompiled_header.GetPchBuildCommands()) # If there are any object files in our input file list, link them into our # output. extra_link_deps += list(filter(Linkable, sources)) self.WriteLn()
[ "def", "WriteSources", "(", "self", ",", "configs", ",", "deps", ",", "sources", ",", "extra_outputs", ",", "extra_link_deps", ",", "part_of_all", ",", "precompiled_header", ")", ":", "# Write configuration-specific variables for CFLAGS, etc.", "for", "configname", "in", "sorted", "(", "configs", ".", "keys", "(", ")", ")", ":", "config", "=", "configs", "[", "configname", "]", "self", ".", "WriteList", "(", "config", ".", "get", "(", "'defines'", ")", ",", "'DEFS_%s'", "%", "configname", ",", "prefix", "=", "'-D'", ",", "quoter", "=", "EscapeCppDefine", ")", "if", "self", ".", "flavor", "==", "'mac'", ":", "cflags", "=", "self", ".", "xcode_settings", ".", "GetCflags", "(", "configname", ")", "cflags_c", "=", "self", ".", "xcode_settings", ".", "GetCflagsC", "(", "configname", ")", "cflags_cc", "=", "self", ".", "xcode_settings", ".", "GetCflagsCC", "(", "configname", ")", "cflags_objc", "=", "self", ".", "xcode_settings", ".", "GetCflagsObjC", "(", "configname", ")", "cflags_objcc", "=", "self", ".", "xcode_settings", ".", "GetCflagsObjCC", "(", "configname", ")", "else", ":", "cflags", "=", "config", ".", "get", "(", "'cflags'", ")", "cflags_c", "=", "config", ".", "get", "(", "'cflags_c'", ")", "cflags_cc", "=", "config", ".", "get", "(", "'cflags_cc'", ")", "self", ".", "WriteLn", "(", "\"# Flags passed to all source files.\"", ")", "self", ".", "WriteList", "(", "cflags", ",", "'CFLAGS_%s'", "%", "configname", ")", "self", ".", "WriteLn", "(", "\"# Flags passed to only C files.\"", ")", "self", ".", "WriteList", "(", "cflags_c", ",", "'CFLAGS_C_%s'", "%", "configname", ")", "self", ".", "WriteLn", "(", "\"# Flags passed to only C++ files.\"", ")", "self", ".", "WriteList", "(", "cflags_cc", ",", "'CFLAGS_CC_%s'", "%", "configname", ")", "if", "self", ".", "flavor", "==", "'mac'", ":", "self", ".", "WriteLn", "(", "\"# Flags passed to only ObjC files.\"", ")", "self", ".", "WriteList", "(", "cflags_objc", ",", "'CFLAGS_OBJC_%s'", "%", "configname", ")", "self", ".", "WriteLn", "(", "\"# Flags passed to only ObjC++ files.\"", ")", "self", ".", "WriteList", "(", "cflags_objcc", ",", "'CFLAGS_OBJCC_%s'", "%", "configname", ")", "includes", "=", "config", ".", "get", "(", "'include_dirs'", ")", "if", "includes", ":", "includes", "=", "[", "Sourceify", "(", "self", ".", "Absolutify", "(", "i", ")", ")", "for", "i", "in", "includes", "]", "self", ".", "WriteList", "(", "includes", ",", "'INCS_%s'", "%", "configname", ",", "prefix", "=", "'-I'", ")", "compilable", "=", "list", "(", "filter", "(", "Compilable", ",", "sources", ")", ")", "objs", "=", "[", "self", ".", "Objectify", "(", "self", ".", "Absolutify", "(", "Target", "(", "c", ")", ")", ")", "for", "c", "in", "compilable", "]", "self", ".", "WriteList", "(", "objs", ",", "'OBJS'", ")", "for", "obj", "in", "objs", ":", "assert", "' '", "not", "in", "obj", ",", "(", "\"Spaces in object filenames not supported (%s)\"", "%", "obj", ")", "self", ".", "WriteLn", "(", "'# Add to the list of files we specially track '", "'dependencies for.'", ")", "self", ".", "WriteLn", "(", "'all_deps += $(OBJS)'", ")", "self", ".", "WriteLn", "(", ")", "# Make sure our dependencies are built first.", "if", "deps", ":", "self", ".", "WriteMakeRule", "(", "[", "'$(OBJS)'", "]", ",", "deps", ",", "comment", "=", "'Make sure our dependencies are built '", "'before any of us.'", ",", "order_only", "=", "True", ")", "# Make sure the actions and rules run first.", "# If they generate any extra headers etc., the per-.o file dep tracking", "# will catch the proper rebuilds, so order only is still ok here.", "if", "extra_outputs", ":", "self", ".", "WriteMakeRule", "(", "[", "'$(OBJS)'", "]", ",", "extra_outputs", ",", "comment", "=", "'Make sure our actions/rules run '", "'before any of us.'", ",", "order_only", "=", "True", ")", "pchdeps", "=", "precompiled_header", ".", "GetObjDependencies", "(", "compilable", ",", "objs", ")", "if", "pchdeps", ":", "self", ".", "WriteLn", "(", "'# Dependencies from obj files to their precompiled headers'", ")", "for", "source", ",", "obj", ",", "gch", "in", "pchdeps", ":", "self", ".", "WriteLn", "(", "'%s: %s'", "%", "(", "obj", ",", "gch", ")", ")", "self", ".", "WriteLn", "(", "'# End precompiled header dependencies'", ")", "if", "objs", ":", "extra_link_deps", ".", "append", "(", "'$(OBJS)'", ")", "self", ".", "WriteLn", "(", "\"\"\"\\\n# CFLAGS et al overrides must be target-local.\n# See \"Target-specific Variable Values\" in the GNU Make manual.\"\"\"", ")", "self", ".", "WriteLn", "(", "\"$(OBJS): TOOLSET := $(TOOLSET)\"", ")", "self", ".", "WriteLn", "(", "\"$(OBJS): GYP_CFLAGS := \"", "\"$(DEFS_$(BUILDTYPE)) \"", "\"$(INCS_$(BUILDTYPE)) \"", "\"%s \"", "%", "precompiled_header", ".", "GetInclude", "(", "'c'", ")", "+", "\"$(CFLAGS_$(BUILDTYPE)) \"", "\"$(CFLAGS_C_$(BUILDTYPE))\"", ")", "self", ".", "WriteLn", "(", "\"$(OBJS): GYP_CXXFLAGS := \"", "\"$(DEFS_$(BUILDTYPE)) \"", "\"$(INCS_$(BUILDTYPE)) \"", "\"%s \"", "%", "precompiled_header", ".", "GetInclude", "(", "'cc'", ")", "+", "\"$(CFLAGS_$(BUILDTYPE)) \"", "\"$(CFLAGS_CC_$(BUILDTYPE))\"", ")", "if", "self", ".", "flavor", "==", "'mac'", ":", "self", ".", "WriteLn", "(", "\"$(OBJS): GYP_OBJCFLAGS := \"", "\"$(DEFS_$(BUILDTYPE)) \"", "\"$(INCS_$(BUILDTYPE)) \"", "\"%s \"", "%", "precompiled_header", ".", "GetInclude", "(", "'m'", ")", "+", "\"$(CFLAGS_$(BUILDTYPE)) \"", "\"$(CFLAGS_C_$(BUILDTYPE)) \"", "\"$(CFLAGS_OBJC_$(BUILDTYPE))\"", ")", "self", ".", "WriteLn", "(", "\"$(OBJS): GYP_OBJCXXFLAGS := \"", "\"$(DEFS_$(BUILDTYPE)) \"", "\"$(INCS_$(BUILDTYPE)) \"", "\"%s \"", "%", "precompiled_header", ".", "GetInclude", "(", "'mm'", ")", "+", "\"$(CFLAGS_$(BUILDTYPE)) \"", "\"$(CFLAGS_CC_$(BUILDTYPE)) \"", "\"$(CFLAGS_OBJCC_$(BUILDTYPE))\"", ")", "self", ".", "WritePchTargets", "(", "precompiled_header", ".", "GetPchBuildCommands", "(", ")", ")", "# If there are any object files in our input file list, link them into our", "# output.", "extra_link_deps", "+=", "list", "(", "filter", "(", "Linkable", ",", "sources", ")", ")", "self", ".", "WriteLn", "(", ")" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/gyp/pylib/gyp/generator/make.py#L1197-L1319
quantOS-org/DataCore
e2ef9bd2c22ee9e2845675b6435a14fa607f3551
mdlink/deps/windows/protobuf-2.5.0/python/google/protobuf/internal/containers.py
python
BaseContainer.__getitem__
(self, key)
return self._values[key]
Retrieves item by the specified key.
Retrieves item by the specified key.
[ "Retrieves", "item", "by", "the", "specified", "key", "." ]
def __getitem__(self, key): """Retrieves item by the specified key.""" return self._values[key]
[ "def", "__getitem__", "(", "self", ",", "key", ")", ":", "return", "self", ".", "_values", "[", "key", "]" ]
https://github.com/quantOS-org/DataCore/blob/e2ef9bd2c22ee9e2845675b6435a14fa607f3551/mdlink/deps/windows/protobuf-2.5.0/python/google/protobuf/internal/containers.py#L62-L64
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
third_party/closure_linter/closure_linter/requireprovidesorter.py
python
RequireProvideSorter._GetRequireOrProvideTokens
(self, token, token_string)
return tokens
Gets all goog.provide or goog.require tokens in the given token stream. Args: token: The first token in the token stream. token_string: One of 'goog.provide' or 'goog.require' to indicate which tokens to find. Returns: A list of goog.provide or goog.require tokens in the order they appear in the token stream.
Gets all goog.provide or goog.require tokens in the given token stream.
[ "Gets", "all", "goog", ".", "provide", "or", "goog", ".", "require", "tokens", "in", "the", "given", "token", "stream", "." ]
def _GetRequireOrProvideTokens(self, token, token_string): """Gets all goog.provide or goog.require tokens in the given token stream. Args: token: The first token in the token stream. token_string: One of 'goog.provide' or 'goog.require' to indicate which tokens to find. Returns: A list of goog.provide or goog.require tokens in the order they appear in the token stream. """ tokens = [] while token: if token.type == Type.IDENTIFIER: if token.string == token_string: tokens.append(token) elif token.string not in ['goog.require', 'goog.provide']: # The goog.provide and goog.require identifiers are at the top of the # file. So if any other identifier is encountered, return. break token = token.next return tokens
[ "def", "_GetRequireOrProvideTokens", "(", "self", ",", "token", ",", "token_string", ")", ":", "tokens", "=", "[", "]", "while", "token", ":", "if", "token", ".", "type", "==", "Type", ".", "IDENTIFIER", ":", "if", "token", ".", "string", "==", "token_string", ":", "tokens", ".", "append", "(", "token", ")", "elif", "token", ".", "string", "not", "in", "[", "'goog.require'", ",", "'goog.provide'", "]", ":", "# The goog.provide and goog.require identifiers are at the top of the", "# file. So if any other identifier is encountered, return.", "break", "token", "=", "token", ".", "next", "return", "tokens" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/closure_linter/closure_linter/requireprovidesorter.py#L153-L176
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/json_schema_compiler/cc_generator.py
python
_Generator._GenerateFunction
(self, function)
return c
Generates the definitions for function structs.
Generates the definitions for function structs.
[ "Generates", "the", "definitions", "for", "function", "structs", "." ]
def _GenerateFunction(self, function): """Generates the definitions for function structs. """ c = Code() # TODO(kalman): use function.unix_name not Classname. function_namespace = cpp_util.Classname(function.name) # Windows has a #define for SendMessage, so to avoid any issues, we need # to not use the name. if function_namespace == 'SendMessage': function_namespace = 'PassMessage' (c.Append('namespace %s {' % function_namespace) .Append() ) # Params::Populate function if function.params: c.Concat(self._GeneratePropertyFunctions('Params', function.params)) (c.Append('Params::Params() {}') .Append('Params::~Params() {}') .Append() .Cblock(self._GenerateFunctionParamsCreate(function)) ) # Results::Create function if function.callback: c.Concat(self._GenerateCreateCallbackArguments('Results', function.callback)) c.Append('} // namespace %s' % function_namespace) return c
[ "def", "_GenerateFunction", "(", "self", ",", "function", ")", ":", "c", "=", "Code", "(", ")", "# TODO(kalman): use function.unix_name not Classname.", "function_namespace", "=", "cpp_util", ".", "Classname", "(", "function", ".", "name", ")", "# Windows has a #define for SendMessage, so to avoid any issues, we need", "# to not use the name.", "if", "function_namespace", "==", "'SendMessage'", ":", "function_namespace", "=", "'PassMessage'", "(", "c", ".", "Append", "(", "'namespace %s {'", "%", "function_namespace", ")", ".", "Append", "(", ")", ")", "# Params::Populate function", "if", "function", ".", "params", ":", "c", ".", "Concat", "(", "self", ".", "_GeneratePropertyFunctions", "(", "'Params'", ",", "function", ".", "params", ")", ")", "(", "c", ".", "Append", "(", "'Params::Params() {}'", ")", ".", "Append", "(", "'Params::~Params() {}'", ")", ".", "Append", "(", ")", ".", "Cblock", "(", "self", ".", "_GenerateFunctionParamsCreate", "(", "function", ")", ")", ")", "# Results::Create function", "if", "function", ".", "callback", ":", "c", ".", "Concat", "(", "self", ".", "_GenerateCreateCallbackArguments", "(", "'Results'", ",", "function", ".", "callback", ")", ")", "c", ".", "Append", "(", "'} // namespace %s'", "%", "function_namespace", ")", "return", "c" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/json_schema_compiler/cc_generator.py#L402-L432
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/autoscale/__init__.py
python
AutoScaleConnection.get_termination_policies
(self)
return self.get_object('DescribeTerminationPolicyTypes', {}, TerminationPolicies)
Gets all valid termination policies. These values can then be used as the termination_policies arg when creating and updating autoscale groups.
Gets all valid termination policies.
[ "Gets", "all", "valid", "termination", "policies", "." ]
def get_termination_policies(self): """Gets all valid termination policies. These values can then be used as the termination_policies arg when creating and updating autoscale groups. """ return self.get_object('DescribeTerminationPolicyTypes', {}, TerminationPolicies)
[ "def", "get_termination_policies", "(", "self", ")", ":", "return", "self", ".", "get_object", "(", "'DescribeTerminationPolicyTypes'", ",", "{", "}", ",", "TerminationPolicies", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/autoscale/__init__.py#L434-L441
wyrover/book-code
7f4883d9030d553bc6bcfa3da685e34789839900
3rdparty/protobuf/objectivec/DevTools/pddm.py
python
MacroCollection.ParseInput
(self, a_file)
Consumes input extracting definitions. Args: a_file: The file like stream to parse. Raises: PDDMError if there are any issues.
Consumes input extracting definitions.
[ "Consumes", "input", "extracting", "definitions", "." ]
def ParseInput(self, a_file): """Consumes input extracting definitions. Args: a_file: The file like stream to parse. Raises: PDDMError if there are any issues. """ input_lines = a_file.read().splitlines() self.ParseLines(input_lines)
[ "def", "ParseInput", "(", "self", ",", "a_file", ")", ":", "input_lines", "=", "a_file", ".", "read", "(", ")", ".", "splitlines", "(", ")", "self", ".", "ParseLines", "(", "input_lines", ")" ]
https://github.com/wyrover/book-code/blob/7f4883d9030d553bc6bcfa3da685e34789839900/3rdparty/protobuf/objectivec/DevTools/pddm.py#L182-L192
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/tree.py
python
TreeItem.IsEditable
(self)
Return whether the item's text may be edited.
Return whether the item's text may be edited.
[ "Return", "whether", "the", "item", "s", "text", "may", "be", "edited", "." ]
def IsEditable(self): """Return whether the item's text may be edited."""
[ "def", "IsEditable", "(", "self", ")", ":" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/tree.py#L372-L373
ablab/quast
5f6709528129a6ad266a6b24ef3f40b88f0fe04b
quast_libs/site_packages/joblib2/numpy_pickle.py
python
NumpyPickler.save
(self, obj)
return pickle.Pickler.save(self, obj)
Subclass the save method, to save ndarray subclasses in npy files, rather than pickling them. Of course, this is a total abuse of the Pickler class.
Subclass the save method, to save ndarray subclasses in npy files, rather than pickling them. Of course, this is a total abuse of the Pickler class.
[ "Subclass", "the", "save", "method", "to", "save", "ndarray", "subclasses", "in", "npy", "files", "rather", "than", "pickling", "them", ".", "Of", "course", "this", "is", "a", "total", "abuse", "of", "the", "Pickler", "class", "." ]
def save(self, obj): """ Subclass the save method, to save ndarray subclasses in npy files, rather than pickling them. Of course, this is a total abuse of the Pickler class. """ if self.np is not None and type(obj) in (self.np.ndarray, self.np.matrix, self.np.memmap): size = obj.size * obj.itemsize if self.compress and size < self.cache_size * _MEGA: # When compressing, as we are not writing directly to the # disk, it is more efficient to use standard pickling if type(obj) is self.np.memmap: # Pickling doesn't work with memmaped arrays obj = self.np.asarray(obj) return pickle.Pickler.save(self, obj) self._npy_counter += 1 try: filename = '%s_%02i.npy' % (self._filename, self._npy_counter) # This converts the array in a container obj, filename = self._write_array(obj, filename) self._filenames.append(filename) except: self._npy_counter -= 1 # XXX: We should have a logging mechanism print 'Failed to save %s to .npy file:\n%s' % ( type(obj), traceback.format_exc()) return pickle.Pickler.save(self, obj)
[ "def", "save", "(", "self", ",", "obj", ")", ":", "if", "self", ".", "np", "is", "not", "None", "and", "type", "(", "obj", ")", "in", "(", "self", ".", "np", ".", "ndarray", ",", "self", ".", "np", ".", "matrix", ",", "self", ".", "np", ".", "memmap", ")", ":", "size", "=", "obj", ".", "size", "*", "obj", ".", "itemsize", "if", "self", ".", "compress", "and", "size", "<", "self", ".", "cache_size", "*", "_MEGA", ":", "# When compressing, as we are not writing directly to the", "# disk, it is more efficient to use standard pickling", "if", "type", "(", "obj", ")", "is", "self", ".", "np", ".", "memmap", ":", "# Pickling doesn't work with memmaped arrays", "obj", "=", "self", ".", "np", ".", "asarray", "(", "obj", ")", "return", "pickle", ".", "Pickler", ".", "save", "(", "self", ",", "obj", ")", "self", ".", "_npy_counter", "+=", "1", "try", ":", "filename", "=", "'%s_%02i.npy'", "%", "(", "self", ".", "_filename", ",", "self", ".", "_npy_counter", ")", "# This converts the array in a container", "obj", ",", "filename", "=", "self", ".", "_write_array", "(", "obj", ",", "filename", ")", "self", ".", "_filenames", ".", "append", "(", "filename", ")", "except", ":", "self", ".", "_npy_counter", "-=", "1", "# XXX: We should have a logging mechanism", "print", "'Failed to save %s to .npy file:\\n%s'", "%", "(", "type", "(", "obj", ")", ",", "traceback", ".", "format_exc", "(", ")", ")", "return", "pickle", ".", "Pickler", ".", "save", "(", "self", ",", "obj", ")" ]
https://github.com/ablab/quast/blob/5f6709528129a6ad266a6b24ef3f40b88f0fe04b/quast_libs/site_packages/joblib2/numpy_pickle.py#L218-L246
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/genericpath.py
python
getctime
(filename)
return os.stat(filename).st_ctime
Return the metadata change time of a file, reported by os.stat().
Return the metadata change time of a file, reported by os.stat().
[ "Return", "the", "metadata", "change", "time", "of", "a", "file", "reported", "by", "os", ".", "stat", "()", "." ]
def getctime(filename): """Return the metadata change time of a file, reported by os.stat().""" return os.stat(filename).st_ctime
[ "def", "getctime", "(", "filename", ")", ":", "return", "os", ".", "stat", "(", "filename", ")", ".", "st_ctime" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/genericpath.py#L62-L64
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/ops/batch_norm_benchmark.py
python
batch_norm_py
(tensor, mean, variance, beta, gamma, scale)
return tf.nn.batch_normalization( tensor, mean, variance, beta, gamma if scale else None, 0.001)
Python implementation of batch normalization.
Python implementation of batch normalization.
[ "Python", "implementation", "of", "batch", "normalization", "." ]
def batch_norm_py(tensor, mean, variance, beta, gamma, scale): """Python implementation of batch normalization.""" return tf.nn.batch_normalization( tensor, mean, variance, beta, gamma if scale else None, 0.001)
[ "def", "batch_norm_py", "(", "tensor", ",", "mean", ",", "variance", ",", "beta", ",", "gamma", ",", "scale", ")", ":", "return", "tf", ".", "nn", ".", "batch_normalization", "(", "tensor", ",", "mean", ",", "variance", ",", "beta", ",", "gamma", "if", "scale", "else", "None", ",", "0.001", ")" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/batch_norm_benchmark.py#L45-L48
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/src/robotsim.py
python
TransformPoser.enableTranslationAxes
(self, x: "bool", y: "bool", z: "bool")
return _robotsim.TransformPoser_enableTranslationAxes(self, x, y, z)
r""" enableTranslationAxes(TransformPoser self, bool x, bool y, bool z)
r""" enableTranslationAxes(TransformPoser self, bool x, bool y, bool z)
[ "r", "enableTranslationAxes", "(", "TransformPoser", "self", "bool", "x", "bool", "y", "bool", "z", ")" ]
def enableTranslationAxes(self, x: "bool", y: "bool", z: "bool") -> "void": r""" enableTranslationAxes(TransformPoser self, bool x, bool y, bool z) """ return _robotsim.TransformPoser_enableTranslationAxes(self, x, y, z)
[ "def", "enableTranslationAxes", "(", "self", ",", "x", ":", "\"bool\"", ",", "y", ":", "\"bool\"", ",", "z", ":", "\"bool\"", ")", "->", "\"void\"", ":", "return", "_robotsim", ".", "TransformPoser_enableTranslationAxes", "(", "self", ",", "x", ",", "y", ",", "z", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/robotsim.py#L3584-L3590
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/training/training_ops.py
python
_SparseApplyFtrlShape
(op)
return [linear_shape]
Shape function for the SparseApplyFtrl op.
Shape function for the SparseApplyFtrl op.
[ "Shape", "function", "for", "the", "SparseApplyFtrl", "op", "." ]
def _SparseApplyFtrlShape(op): """Shape function for the SparseApplyFtrl op.""" var_shape = op.inputs[0].get_shape() accum_shape = op.inputs[1].get_shape().merge_with(var_shape) linear_shape = op.inputs[2].get_shape().merge_with(accum_shape) grad_shape = op.inputs[3].get_shape().merge_with( tensor_shape.TensorShape([None]).concatenate(linear_shape[1:])) unused_indices_shape = op.inputs[4].get_shape().merge_with( tensor_shape.vector(grad_shape[0])) _AssertInputIsScalar(op, 5) # lr _AssertInputIsScalar(op, 6) # l1 _AssertInputIsScalar(op, 7) # l2 _AssertInputIsScalar(op, 8) # lr_power return [linear_shape]
[ "def", "_SparseApplyFtrlShape", "(", "op", ")", ":", "var_shape", "=", "op", ".", "inputs", "[", "0", "]", ".", "get_shape", "(", ")", "accum_shape", "=", "op", ".", "inputs", "[", "1", "]", ".", "get_shape", "(", ")", ".", "merge_with", "(", "var_shape", ")", "linear_shape", "=", "op", ".", "inputs", "[", "2", "]", ".", "get_shape", "(", ")", ".", "merge_with", "(", "accum_shape", ")", "grad_shape", "=", "op", ".", "inputs", "[", "3", "]", ".", "get_shape", "(", ")", ".", "merge_with", "(", "tensor_shape", ".", "TensorShape", "(", "[", "None", "]", ")", ".", "concatenate", "(", "linear_shape", "[", "1", ":", "]", ")", ")", "unused_indices_shape", "=", "op", ".", "inputs", "[", "4", "]", ".", "get_shape", "(", ")", ".", "merge_with", "(", "tensor_shape", ".", "vector", "(", "grad_shape", "[", "0", "]", ")", ")", "_AssertInputIsScalar", "(", "op", ",", "5", ")", "# lr", "_AssertInputIsScalar", "(", "op", ",", "6", ")", "# l1", "_AssertInputIsScalar", "(", "op", ",", "7", ")", "# l2", "_AssertInputIsScalar", "(", "op", ",", "8", ")", "# lr_power", "return", "[", "linear_shape", "]" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/training/training_ops.py#L235-L248
apache/arrow
af33dd1157eb8d7d9bfac25ebf61445b793b7943
dev/archery/archery/crossbow/core.py
python
Queue.jobs
(self, pattern)
Return jobs sorted by its identifier in reverse order
Return jobs sorted by its identifier in reverse order
[ "Return", "jobs", "sorted", "by", "its", "identifier", "in", "reverse", "order" ]
def jobs(self, pattern): """Return jobs sorted by its identifier in reverse order""" job_names = [] for name in self.repo.branches.remote: origin, name = name.split('/', 1) result = re.match(pattern, name) if result: job_names.append(name) for name in sorted(job_names, reverse=True): yield self.get(name)
[ "def", "jobs", "(", "self", ",", "pattern", ")", ":", "job_names", "=", "[", "]", "for", "name", "in", "self", ".", "repo", ".", "branches", ".", "remote", ":", "origin", ",", "name", "=", "name", ".", "split", "(", "'/'", ",", "1", ")", "result", "=", "re", ".", "match", "(", "pattern", ",", "name", ")", "if", "result", ":", "job_names", ".", "append", "(", "name", ")", "for", "name", "in", "sorted", "(", "job_names", ",", "reverse", "=", "True", ")", ":", "yield", "self", ".", "get", "(", "name", ")" ]
https://github.com/apache/arrow/blob/af33dd1157eb8d7d9bfac25ebf61445b793b7943/dev/archery/archery/crossbow/core.py#L586-L596
swift/swift
12d031cf8177fdec0137f9aa7e2912fa23c4416b
3rdParty/SCons/scons-3.0.1/engine/SCons/Variables/__init__.py
python
Variables.GenerateHelpText
(self, env, sort=None)
return ''.join(lines)
Generate the help text for the options. env - an environment that is used to get the current values of the options. cmp - Either a function as follows: The specific sort function should take two arguments and return -1, 0 or 1 or a boolean to indicate if it should be sorted.
Generate the help text for the options.
[ "Generate", "the", "help", "text", "for", "the", "options", "." ]
def GenerateHelpText(self, env, sort=None): """ Generate the help text for the options. env - an environment that is used to get the current values of the options. cmp - Either a function as follows: The specific sort function should take two arguments and return -1, 0 or 1 or a boolean to indicate if it should be sorted. """ if callable(sort): options = sorted(self.options, key=cmp_to_key(lambda x,y: sort(x.key,y.key))) elif sort is True: options = sorted(self.options, key=lambda x: x.key) else: options = self.options def format(opt, self=self, env=env): if opt.key in env: actual = env.subst('${%s}' % opt.key) else: actual = None return self.FormatVariableHelpText(env, opt.key, opt.help, opt.default, actual, opt.aliases) lines = [_f for _f in map(format, options) if _f] return ''.join(lines)
[ "def", "GenerateHelpText", "(", "self", ",", "env", ",", "sort", "=", "None", ")", ":", "if", "callable", "(", "sort", ")", ":", "options", "=", "sorted", "(", "self", ".", "options", ",", "key", "=", "cmp_to_key", "(", "lambda", "x", ",", "y", ":", "sort", "(", "x", ".", "key", ",", "y", ".", "key", ")", ")", ")", "elif", "sort", "is", "True", ":", "options", "=", "sorted", "(", "self", ".", "options", ",", "key", "=", "lambda", "x", ":", "x", ".", "key", ")", "else", ":", "options", "=", "self", ".", "options", "def", "format", "(", "opt", ",", "self", "=", "self", ",", "env", "=", "env", ")", ":", "if", "opt", ".", "key", "in", "env", ":", "actual", "=", "env", ".", "subst", "(", "'${%s}'", "%", "opt", ".", "key", ")", "else", ":", "actual", "=", "None", "return", "self", ".", "FormatVariableHelpText", "(", "env", ",", "opt", ".", "key", ",", "opt", ".", "help", ",", "opt", ".", "default", ",", "actual", ",", "opt", ".", "aliases", ")", "lines", "=", "[", "_f", "for", "_f", "in", "map", "(", "format", ",", "options", ")", "if", "_f", "]", "return", "''", ".", "join", "(", "lines", ")" ]
https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/3rdParty/SCons/scons-3.0.1/engine/SCons/Variables/__init__.py#L285-L310
NASA-SW-VnV/ikos
71325dfb94737332542caa708d7537752021522d
analyzer/python/ikos/output_db.py
python
CallContext.parent
(self)
return self.db.call_contexts[self.parent_id]
Return the parent calling context
Return the parent calling context
[ "Return", "the", "parent", "calling", "context" ]
def parent(self): ''' Return the parent calling context ''' assert self.parent_id is not None return self.db.call_contexts[self.parent_id]
[ "def", "parent", "(", "self", ")", ":", "assert", "self", ".", "parent_id", "is", "not", "None", "return", "self", ".", "db", ".", "call_contexts", "[", "self", ".", "parent_id", "]" ]
https://github.com/NASA-SW-VnV/ikos/blob/71325dfb94737332542caa708d7537752021522d/analyzer/python/ikos/output_db.py#L300-L303
google/clif
cab24d6a105609a65c95a36a1712ae3c20c7b5df
clif/python/pyext.py
python
Module.WrapCapsule
(self, p, unused_ln, ns, unused_class_ns='')
return []
Process AST.ForwardDecl p.
Process AST.ForwardDecl p.
[ "Process", "AST", ".", "ForwardDecl", "p", "." ]
def WrapCapsule(self, p, unused_ln, ns, unused_class_ns=''): """Process AST.ForwardDecl p.""" self.types.append(types.CapsuleType(p.name.cpp_name, p.name.native, ns)) return []
[ "def", "WrapCapsule", "(", "self", ",", "p", ",", "unused_ln", ",", "ns", ",", "unused_class_ns", "=", "''", ")", ":", "self", ".", "types", ".", "append", "(", "types", ".", "CapsuleType", "(", "p", ".", "name", ".", "cpp_name", ",", "p", ".", "name", ".", "native", ",", "ns", ")", ")", "return", "[", "]" ]
https://github.com/google/clif/blob/cab24d6a105609a65c95a36a1712ae3c20c7b5df/clif/python/pyext.py#L654-L657
google/tink
59bb34495d1cb8f9d9dbc0f0a52c4f9e21491a14
python/tink/core/_registry.py
python
Registry._key_manager_internal
( cls, type_url: str)
return cls._key_managers[type_url]
Returns a key manager, new_key_allowed pair for the given type_url.
Returns a key manager, new_key_allowed pair for the given type_url.
[ "Returns", "a", "key", "manager", "new_key_allowed", "pair", "for", "the", "given", "type_url", "." ]
def _key_manager_internal( cls, type_url: str) -> Tuple[_key_manager.KeyManager, bool]: """Returns a key manager, new_key_allowed pair for the given type_url.""" if type_url not in cls._key_managers: raise _tink_error.TinkError( 'No manager for type {} has been registered.'.format(type_url)) return cls._key_managers[type_url]
[ "def", "_key_manager_internal", "(", "cls", ",", "type_url", ":", "str", ")", "->", "Tuple", "[", "_key_manager", ".", "KeyManager", ",", "bool", "]", ":", "if", "type_url", "not", "in", "cls", ".", "_key_managers", ":", "raise", "_tink_error", ".", "TinkError", "(", "'No manager for type {} has been registered.'", ".", "format", "(", "type_url", ")", ")", "return", "cls", ".", "_key_managers", "[", "type_url", "]" ]
https://github.com/google/tink/blob/59bb34495d1cb8f9d9dbc0f0a52c4f9e21491a14/python/tink/core/_registry.py#L53-L59
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/zipfile.py
python
ZipFile.write
(self, filename, arcname=None, compress_type=None)
Put the bytes from filename into the archive under the name arcname.
Put the bytes from filename into the archive under the name arcname.
[ "Put", "the", "bytes", "from", "filename", "into", "the", "archive", "under", "the", "name", "arcname", "." ]
def write(self, filename, arcname=None, compress_type=None): """Put the bytes from filename into the archive under the name arcname.""" if not self.fp: raise RuntimeError( "Attempt to write to ZIP archive that was already closed") st = os.stat(filename) isdir = stat.S_ISDIR(st.st_mode) mtime = time.localtime(st.st_mtime) date_time = mtime[0:6] # Create ZipInfo instance to store file information if arcname is None: arcname = filename arcname = os.path.normpath(os.path.splitdrive(arcname)[1]) while arcname[0] in (os.sep, os.altsep): arcname = arcname[1:] if isdir: arcname += '/' zinfo = ZipInfo(arcname, date_time) zinfo.external_attr = (st[0] & 0xFFFF) << 16L # Unix attributes if compress_type is None: zinfo.compress_type = self.compression else: zinfo.compress_type = compress_type zinfo.file_size = st.st_size zinfo.flag_bits = 0x00 zinfo.header_offset = self.fp.tell() # Start of header bytes self._writecheck(zinfo) self._didModify = True if isdir: zinfo.file_size = 0 zinfo.compress_size = 0 zinfo.CRC = 0 self.filelist.append(zinfo) self.NameToInfo[zinfo.filename] = zinfo self.fp.write(zinfo.FileHeader(False)) return with open(filename, "rb") as fp: # Must overwrite CRC and sizes with correct data later zinfo.CRC = CRC = 0 zinfo.compress_size = compress_size = 0 # Compressed size can be larger than uncompressed size zip64 = self._allowZip64 and \ zinfo.file_size * 1.05 > ZIP64_LIMIT self.fp.write(zinfo.FileHeader(zip64)) if zinfo.compress_type == ZIP_DEFLATED: cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -15) else: cmpr = None file_size = 0 while 1: buf = fp.read(1024 * 8) if not buf: break file_size = file_size + len(buf) CRC = crc32(buf, CRC) & 0xffffffff if cmpr: buf = cmpr.compress(buf) compress_size = compress_size + len(buf) self.fp.write(buf) if cmpr: buf = cmpr.flush() compress_size = compress_size + len(buf) self.fp.write(buf) zinfo.compress_size = compress_size else: zinfo.compress_size = file_size zinfo.CRC = CRC zinfo.file_size = file_size if not zip64 and self._allowZip64: if file_size > ZIP64_LIMIT: raise RuntimeError('File size has increased during compressing') if compress_size > ZIP64_LIMIT: raise RuntimeError('Compressed size larger than uncompressed size') # Seek backwards and write file header (which will now include # correct CRC and file sizes) position = self.fp.tell() # Preserve current position in file self.fp.seek(zinfo.header_offset, 0) self.fp.write(zinfo.FileHeader(zip64)) self.fp.seek(position, 0) self.filelist.append(zinfo) self.NameToInfo[zinfo.filename] = zinfo
[ "def", "write", "(", "self", ",", "filename", ",", "arcname", "=", "None", ",", "compress_type", "=", "None", ")", ":", "if", "not", "self", ".", "fp", ":", "raise", "RuntimeError", "(", "\"Attempt to write to ZIP archive that was already closed\"", ")", "st", "=", "os", ".", "stat", "(", "filename", ")", "isdir", "=", "stat", ".", "S_ISDIR", "(", "st", ".", "st_mode", ")", "mtime", "=", "time", ".", "localtime", "(", "st", ".", "st_mtime", ")", "date_time", "=", "mtime", "[", "0", ":", "6", "]", "# Create ZipInfo instance to store file information", "if", "arcname", "is", "None", ":", "arcname", "=", "filename", "arcname", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "splitdrive", "(", "arcname", ")", "[", "1", "]", ")", "while", "arcname", "[", "0", "]", "in", "(", "os", ".", "sep", ",", "os", ".", "altsep", ")", ":", "arcname", "=", "arcname", "[", "1", ":", "]", "if", "isdir", ":", "arcname", "+=", "'/'", "zinfo", "=", "ZipInfo", "(", "arcname", ",", "date_time", ")", "zinfo", ".", "external_attr", "=", "(", "st", "[", "0", "]", "&", "0xFFFF", ")", "<<", "16L", "# Unix attributes", "if", "compress_type", "is", "None", ":", "zinfo", ".", "compress_type", "=", "self", ".", "compression", "else", ":", "zinfo", ".", "compress_type", "=", "compress_type", "zinfo", ".", "file_size", "=", "st", ".", "st_size", "zinfo", ".", "flag_bits", "=", "0x00", "zinfo", ".", "header_offset", "=", "self", ".", "fp", ".", "tell", "(", ")", "# Start of header bytes", "self", ".", "_writecheck", "(", "zinfo", ")", "self", ".", "_didModify", "=", "True", "if", "isdir", ":", "zinfo", ".", "file_size", "=", "0", "zinfo", ".", "compress_size", "=", "0", "zinfo", ".", "CRC", "=", "0", "self", ".", "filelist", ".", "append", "(", "zinfo", ")", "self", ".", "NameToInfo", "[", "zinfo", ".", "filename", "]", "=", "zinfo", "self", ".", "fp", ".", "write", "(", "zinfo", ".", "FileHeader", "(", "False", ")", ")", "return", "with", "open", "(", "filename", ",", "\"rb\"", ")", "as", "fp", ":", "# Must overwrite CRC and sizes with correct data later", "zinfo", ".", "CRC", "=", "CRC", "=", "0", "zinfo", ".", "compress_size", "=", "compress_size", "=", "0", "# Compressed size can be larger than uncompressed size", "zip64", "=", "self", ".", "_allowZip64", "and", "zinfo", ".", "file_size", "*", "1.05", ">", "ZIP64_LIMIT", "self", ".", "fp", ".", "write", "(", "zinfo", ".", "FileHeader", "(", "zip64", ")", ")", "if", "zinfo", ".", "compress_type", "==", "ZIP_DEFLATED", ":", "cmpr", "=", "zlib", ".", "compressobj", "(", "zlib", ".", "Z_DEFAULT_COMPRESSION", ",", "zlib", ".", "DEFLATED", ",", "-", "15", ")", "else", ":", "cmpr", "=", "None", "file_size", "=", "0", "while", "1", ":", "buf", "=", "fp", ".", "read", "(", "1024", "*", "8", ")", "if", "not", "buf", ":", "break", "file_size", "=", "file_size", "+", "len", "(", "buf", ")", "CRC", "=", "crc32", "(", "buf", ",", "CRC", ")", "&", "0xffffffff", "if", "cmpr", ":", "buf", "=", "cmpr", ".", "compress", "(", "buf", ")", "compress_size", "=", "compress_size", "+", "len", "(", "buf", ")", "self", ".", "fp", ".", "write", "(", "buf", ")", "if", "cmpr", ":", "buf", "=", "cmpr", ".", "flush", "(", ")", "compress_size", "=", "compress_size", "+", "len", "(", "buf", ")", "self", ".", "fp", ".", "write", "(", "buf", ")", "zinfo", ".", "compress_size", "=", "compress_size", "else", ":", "zinfo", ".", "compress_size", "=", "file_size", "zinfo", ".", "CRC", "=", "CRC", "zinfo", ".", "file_size", "=", "file_size", "if", "not", "zip64", "and", "self", ".", "_allowZip64", ":", "if", "file_size", ">", "ZIP64_LIMIT", ":", "raise", "RuntimeError", "(", "'File size has increased during compressing'", ")", "if", "compress_size", ">", "ZIP64_LIMIT", ":", "raise", "RuntimeError", "(", "'Compressed size larger than uncompressed size'", ")", "# Seek backwards and write file header (which will now include", "# correct CRC and file sizes)", "position", "=", "self", ".", "fp", ".", "tell", "(", ")", "# Preserve current position in file", "self", ".", "fp", ".", "seek", "(", "zinfo", ".", "header_offset", ",", "0", ")", "self", ".", "fp", ".", "write", "(", "zinfo", ".", "FileHeader", "(", "zip64", ")", ")", "self", ".", "fp", ".", "seek", "(", "position", ",", "0", ")", "self", ".", "filelist", ".", "append", "(", "zinfo", ")", "self", ".", "NameToInfo", "[", "zinfo", ".", "filename", "]", "=", "zinfo" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/zipfile.py#L1107-L1194
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml.py
python
SAXCallback.internalSubset
(self, name, externalID, systemID)
called when a DOCTYPE declaration has been found, name is the DTD name and externalID, systemID are the DTD public and system identifier for that DTD if available
called when a DOCTYPE declaration has been found, name is the DTD name and externalID, systemID are the DTD public and system identifier for that DTD if available
[ "called", "when", "a", "DOCTYPE", "declaration", "has", "been", "found", "name", "is", "the", "DTD", "name", "and", "externalID", "systemID", "are", "the", "DTD", "public", "and", "system", "identifier", "for", "that", "DTD", "if", "available" ]
def internalSubset(self, name, externalID, systemID): """called when a DOCTYPE declaration has been found, name is the DTD name and externalID, systemID are the DTD public and system identifier for that DTD if available""" pass
[ "def", "internalSubset", "(", "self", ",", "name", ",", "externalID", ",", "systemID", ")", ":", "pass" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml.py#L217-L221
aimerykong/Low-Rank-Bilinear-Pooling
487eb2c857fd9c95357a5166b0c15ad0fe135b28
demo3_modelVisualization/vlfeat/docsrc/webdoc.py
python
DocHandler.setDocumentLocator
(self, locator)
SAX interface: This is called when a new file is parsed to set the locator object.
SAX interface: This is called when a new file is parsed to set the locator object.
[ "SAX", "interface", ":", "This", "is", "called", "when", "a", "new", "file", "is", "parsed", "to", "set", "the", "locator", "object", "." ]
def setDocumentLocator(self, locator): """SAX interface: This is called when a new file is parsed to set the locator object.""" self.locatorStack.append(locator)
[ "def", "setDocumentLocator", "(", "self", ",", "locator", ")", ":", "self", ".", "locatorStack", ".", "append", "(", "locator", ")" ]
https://github.com/aimerykong/Low-Rank-Bilinear-Pooling/blob/487eb2c857fd9c95357a5166b0c15ad0fe135b28/demo3_modelVisualization/vlfeat/docsrc/webdoc.py#L1143-L1145
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_misc.py
python
NotificationMessage.Show
(*args, **kwargs)
return _misc_.NotificationMessage_Show(*args, **kwargs)
Show(self, int timeout=Timeout_Auto) -> bool
Show(self, int timeout=Timeout_Auto) -> bool
[ "Show", "(", "self", "int", "timeout", "=", "Timeout_Auto", ")", "-", ">", "bool" ]
def Show(*args, **kwargs): """Show(self, int timeout=Timeout_Auto) -> bool""" return _misc_.NotificationMessage_Show(*args, **kwargs)
[ "def", "Show", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "NotificationMessage_Show", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L1236-L1238
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/irc/irclib.py
python
IRC.server
(self)
return c
Creates and returns a ServerConnection object.
Creates and returns a ServerConnection object.
[ "Creates", "and", "returns", "a", "ServerConnection", "object", "." ]
def server(self): """Creates and returns a ServerConnection object.""" c = ServerConnection(self) self.connections.append(c) return c
[ "def", "server", "(", "self", ")", ":", "c", "=", "ServerConnection", "(", "self", ")", "self", ".", "connections", ".", "append", "(", "c", ")", "return", "c" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/irc/irclib.py#L164-L169
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/lib/shape_base.py
python
dstack
(tup)
return _nx.concatenate(arrs, 2)
Stack arrays in sequence depth wise (along third axis). This is equivalent to concatenation along the third axis after 2-D arrays of shape `(M,N)` have been reshaped to `(M,N,1)` and 1-D arrays of shape `(N,)` have been reshaped to `(1,N,1)`. Rebuilds arrays divided by `dsplit`. This function makes most sense for arrays with up to 3 dimensions. For instance, for pixel-data with a height (first axis), width (second axis), and r/g/b channels (third axis). The functions `concatenate`, `stack` and `block` provide more general stacking and concatenation operations. Parameters ---------- tup : sequence of arrays The arrays must have the same shape along all but the third axis. 1-D or 2-D arrays must have the same shape. Returns ------- stacked : ndarray The array formed by stacking the given arrays, will be at least 3-D. See Also -------- stack : Join a sequence of arrays along a new axis. vstack : Stack along first axis. hstack : Stack along second axis. concatenate : Join a sequence of arrays along an existing axis. dsplit : Split array along third axis. Examples -------- >>> a = np.array((1,2,3)) >>> b = np.array((2,3,4)) >>> np.dstack((a,b)) array([[[1, 2], [2, 3], [3, 4]]]) >>> a = np.array([[1],[2],[3]]) >>> b = np.array([[2],[3],[4]]) >>> np.dstack((a,b)) array([[[1, 2]], [[2, 3]], [[3, 4]]])
Stack arrays in sequence depth wise (along third axis).
[ "Stack", "arrays", "in", "sequence", "depth", "wise", "(", "along", "third", "axis", ")", "." ]
def dstack(tup): """ Stack arrays in sequence depth wise (along third axis). This is equivalent to concatenation along the third axis after 2-D arrays of shape `(M,N)` have been reshaped to `(M,N,1)` and 1-D arrays of shape `(N,)` have been reshaped to `(1,N,1)`. Rebuilds arrays divided by `dsplit`. This function makes most sense for arrays with up to 3 dimensions. For instance, for pixel-data with a height (first axis), width (second axis), and r/g/b channels (third axis). The functions `concatenate`, `stack` and `block` provide more general stacking and concatenation operations. Parameters ---------- tup : sequence of arrays The arrays must have the same shape along all but the third axis. 1-D or 2-D arrays must have the same shape. Returns ------- stacked : ndarray The array formed by stacking the given arrays, will be at least 3-D. See Also -------- stack : Join a sequence of arrays along a new axis. vstack : Stack along first axis. hstack : Stack along second axis. concatenate : Join a sequence of arrays along an existing axis. dsplit : Split array along third axis. Examples -------- >>> a = np.array((1,2,3)) >>> b = np.array((2,3,4)) >>> np.dstack((a,b)) array([[[1, 2], [2, 3], [3, 4]]]) >>> a = np.array([[1],[2],[3]]) >>> b = np.array([[2],[3],[4]]) >>> np.dstack((a,b)) array([[[1, 2]], [[2, 3]], [[3, 4]]]) """ if not overrides.ARRAY_FUNCTION_ENABLED: # raise warning if necessary _arrays_for_stack_dispatcher(tup, stacklevel=2) arrs = atleast_3d(*tup) if not isinstance(arrs, list): arrs = [arrs] return _nx.concatenate(arrs, 2)
[ "def", "dstack", "(", "tup", ")", ":", "if", "not", "overrides", ".", "ARRAY_FUNCTION_ENABLED", ":", "# raise warning if necessary", "_arrays_for_stack_dispatcher", "(", "tup", ",", "stacklevel", "=", "2", ")", "arrs", "=", "atleast_3d", "(", "*", "tup", ")", "if", "not", "isinstance", "(", "arrs", ",", "list", ")", ":", "arrs", "=", "[", "arrs", "]", "return", "_nx", ".", "concatenate", "(", "arrs", ",", "2", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/lib/shape_base.py#L664-L721
baoboa/pyqt5
11d5f43bc6f213d9d60272f3954a0048569cfc7c
pyuic/uic/driver.py
python
Driver._preview
(self)
return app.exec_()
Preview the .ui file. Return the exit status to be passed back to the parent process.
Preview the .ui file. Return the exit status to be passed back to the parent process.
[ "Preview", "the", ".", "ui", "file", ".", "Return", "the", "exit", "status", "to", "be", "passed", "back", "to", "the", "parent", "process", "." ]
def _preview(self): """ Preview the .ui file. Return the exit status to be passed back to the parent process. """ from PyQt5 import QtWidgets app = QtWidgets.QApplication([self._ui_file]) widget = loadUi(self._ui_file) widget.show() return app.exec_()
[ "def", "_preview", "(", "self", ")", ":", "from", "PyQt5", "import", "QtWidgets", "app", "=", "QtWidgets", ".", "QApplication", "(", "[", "self", ".", "_ui_file", "]", ")", "widget", "=", "loadUi", "(", "self", ".", "_ui_file", ")", "widget", ".", "show", "(", ")", "return", "app", ".", "exec_", "(", ")" ]
https://github.com/baoboa/pyqt5/blob/11d5f43bc6f213d9d60272f3954a0048569cfc7c/pyuic/uic/driver.py#L63-L74
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/glcanvas.py
python
GLCanvas.SwapBuffers
(*args, **kwargs)
return _glcanvas.GLCanvas_SwapBuffers(*args, **kwargs)
SwapBuffers(self) -> bool
SwapBuffers(self) -> bool
[ "SwapBuffers", "(", "self", ")", "-", ">", "bool" ]
def SwapBuffers(*args, **kwargs): """SwapBuffers(self) -> bool""" return _glcanvas.GLCanvas_SwapBuffers(*args, **kwargs)
[ "def", "SwapBuffers", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_glcanvas", ".", "GLCanvas_SwapBuffers", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/glcanvas.py#L122-L124
forkineye/ESPixelStick
22926f1c0d1131f1369fc7cad405689a095ae3cb
dist/bin/esptool/pyaes/aes.py
python
AES.decrypt
(self, ciphertext)
return result
Decrypt a block of cipher text using the AES block cipher.
Decrypt a block of cipher text using the AES block cipher.
[ "Decrypt", "a", "block", "of", "cipher", "text", "using", "the", "AES", "block", "cipher", "." ]
def decrypt(self, ciphertext): 'Decrypt a block of cipher text using the AES block cipher.' if len(ciphertext) != 16: raise ValueError('wrong block length') rounds = len(self._Kd) - 1 (s1, s2, s3) = [3, 2, 1] a = [0, 0, 0, 0] # Convert ciphertext to (ints ^ key) t = [(_compact_word(ciphertext[4 * i:4 * i + 4]) ^ self._Kd[0][i]) for i in xrange(0, 4)] # Apply round transforms for r in xrange(1, rounds): for i in xrange(0, 4): a[i] = (self.T5[(t[ i ] >> 24) & 0xFF] ^ self.T6[(t[(i + s1) % 4] >> 16) & 0xFF] ^ self.T7[(t[(i + s2) % 4] >> 8) & 0xFF] ^ self.T8[ t[(i + s3) % 4] & 0xFF] ^ self._Kd[r][i]) t = copy.copy(a) # The last round is special result = [ ] for i in xrange(0, 4): tt = self._Kd[rounds][i] result.append((self.Si[(t[ i ] >> 24) & 0xFF] ^ (tt >> 24)) & 0xFF) result.append((self.Si[(t[(i + s1) % 4] >> 16) & 0xFF] ^ (tt >> 16)) & 0xFF) result.append((self.Si[(t[(i + s2) % 4] >> 8) & 0xFF] ^ (tt >> 8)) & 0xFF) result.append((self.Si[ t[(i + s3) % 4] & 0xFF] ^ tt ) & 0xFF) return result
[ "def", "decrypt", "(", "self", ",", "ciphertext", ")", ":", "if", "len", "(", "ciphertext", ")", "!=", "16", ":", "raise", "ValueError", "(", "'wrong block length'", ")", "rounds", "=", "len", "(", "self", ".", "_Kd", ")", "-", "1", "(", "s1", ",", "s2", ",", "s3", ")", "=", "[", "3", ",", "2", ",", "1", "]", "a", "=", "[", "0", ",", "0", ",", "0", ",", "0", "]", "# Convert ciphertext to (ints ^ key)", "t", "=", "[", "(", "_compact_word", "(", "ciphertext", "[", "4", "*", "i", ":", "4", "*", "i", "+", "4", "]", ")", "^", "self", ".", "_Kd", "[", "0", "]", "[", "i", "]", ")", "for", "i", "in", "xrange", "(", "0", ",", "4", ")", "]", "# Apply round transforms", "for", "r", "in", "xrange", "(", "1", ",", "rounds", ")", ":", "for", "i", "in", "xrange", "(", "0", ",", "4", ")", ":", "a", "[", "i", "]", "=", "(", "self", ".", "T5", "[", "(", "t", "[", "i", "]", ">>", "24", ")", "&", "0xFF", "]", "^", "self", ".", "T6", "[", "(", "t", "[", "(", "i", "+", "s1", ")", "%", "4", "]", ">>", "16", ")", "&", "0xFF", "]", "^", "self", ".", "T7", "[", "(", "t", "[", "(", "i", "+", "s2", ")", "%", "4", "]", ">>", "8", ")", "&", "0xFF", "]", "^", "self", ".", "T8", "[", "t", "[", "(", "i", "+", "s3", ")", "%", "4", "]", "&", "0xFF", "]", "^", "self", ".", "_Kd", "[", "r", "]", "[", "i", "]", ")", "t", "=", "copy", ".", "copy", "(", "a", ")", "# The last round is special", "result", "=", "[", "]", "for", "i", "in", "xrange", "(", "0", ",", "4", ")", ":", "tt", "=", "self", ".", "_Kd", "[", "rounds", "]", "[", "i", "]", "result", ".", "append", "(", "(", "self", ".", "Si", "[", "(", "t", "[", "i", "]", ">>", "24", ")", "&", "0xFF", "]", "^", "(", "tt", ">>", "24", ")", ")", "&", "0xFF", ")", "result", ".", "append", "(", "(", "self", ".", "Si", "[", "(", "t", "[", "(", "i", "+", "s1", ")", "%", "4", "]", ">>", "16", ")", "&", "0xFF", "]", "^", "(", "tt", ">>", "16", ")", ")", "&", "0xFF", ")", "result", ".", "append", "(", "(", "self", ".", "Si", "[", "(", "t", "[", "(", "i", "+", "s2", ")", "%", "4", "]", ">>", "8", ")", "&", "0xFF", "]", "^", "(", "tt", ">>", "8", ")", ")", "&", "0xFF", ")", "result", ".", "append", "(", "(", "self", ".", "Si", "[", "t", "[", "(", "i", "+", "s3", ")", "%", "4", "]", "&", "0xFF", "]", "^", "tt", ")", "&", "0xFF", ")", "return", "result" ]
https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/esptool/pyaes/aes.py#L237-L269
HackWebRTC/webrtc
7abfc990c00ab35090fff285fcf635d1d7892433
tools_webrtc/android/release_aar.py
python
_TestAAR
(tmp_dir, username, password, version)
Runs AppRTCMobile tests using the AAR. Returns true if the tests pass.
Runs AppRTCMobile tests using the AAR. Returns true if the tests pass.
[ "Runs", "AppRTCMobile", "tests", "using", "the", "AAR", ".", "Returns", "true", "if", "the", "tests", "pass", "." ]
def _TestAAR(tmp_dir, username, password, version): """Runs AppRTCMobile tests using the AAR. Returns true if the tests pass.""" logging.info('Testing library.') env = jinja2.Environment( loader=jinja2.PackageLoader('release_aar'), ) gradle_backup = os.path.join(tmp_dir, 'build.gradle.backup') app_gradle_backup = os.path.join(tmp_dir, 'app-build.gradle.backup') # Make backup copies of the project files before modifying them. shutil.copy2(AAR_PROJECT_GRADLE, gradle_backup) shutil.copy2(AAR_PROJECT_APP_GRADLE, app_gradle_backup) try: maven_repository_template = env.get_template('maven-repository.jinja') maven_repository = maven_repository_template.render( url=MAVEN_REPOSITORY, username=username, password=password) # Append Maven repository to build file to download unpublished files. with open(AAR_PROJECT_GRADLE, 'a') as gradle_file: gradle_file.write(maven_repository) # Read app build file. with open(AAR_PROJECT_APP_GRADLE, 'r') as gradle_app_file: gradle_app = gradle_app_file.read() if AAR_PROJECT_DEPENDENCY not in gradle_app: raise Exception( '%s not found in the build file.' % AAR_PROJECT_DEPENDENCY) # Set version to the version to be tested. target_dependency = AAR_PROJECT_VERSION_DEPENDENCY % version gradle_app = gradle_app.replace(AAR_PROJECT_DEPENDENCY, target_dependency) # Write back. with open(AAR_PROJECT_APP_GRADLE, 'w') as gradle_app_file: gradle_app_file.write(gradle_app) # Uninstall any existing version of AppRTCMobile. logging.info('Uninstalling previous AppRTCMobile versions. It is okay for ' 'these commands to fail if AppRTCMobile is not installed.') subprocess.call([ADB_BIN, 'uninstall', 'org.appspot.apprtc']) subprocess.call([ADB_BIN, 'uninstall', 'org.appspot.apprtc.test']) # Run tests. try: # First clean the project. subprocess.check_call([GRADLEW_BIN, 'clean'], cwd=AAR_PROJECT_DIR) # Then run the tests. subprocess.check_call([GRADLEW_BIN, 'connectedDebugAndroidTest'], cwd=AAR_PROJECT_DIR) except subprocess.CalledProcessError: logging.exception('Test failure.') return False # Clean or tests failed return True # Tests pass finally: # Restore backups. shutil.copy2(gradle_backup, AAR_PROJECT_GRADLE) shutil.copy2(app_gradle_backup, AAR_PROJECT_APP_GRADLE)
[ "def", "_TestAAR", "(", "tmp_dir", ",", "username", ",", "password", ",", "version", ")", ":", "logging", ".", "info", "(", "'Testing library.'", ")", "env", "=", "jinja2", ".", "Environment", "(", "loader", "=", "jinja2", ".", "PackageLoader", "(", "'release_aar'", ")", ",", ")", "gradle_backup", "=", "os", ".", "path", ".", "join", "(", "tmp_dir", ",", "'build.gradle.backup'", ")", "app_gradle_backup", "=", "os", ".", "path", ".", "join", "(", "tmp_dir", ",", "'app-build.gradle.backup'", ")", "# Make backup copies of the project files before modifying them.", "shutil", ".", "copy2", "(", "AAR_PROJECT_GRADLE", ",", "gradle_backup", ")", "shutil", ".", "copy2", "(", "AAR_PROJECT_APP_GRADLE", ",", "app_gradle_backup", ")", "try", ":", "maven_repository_template", "=", "env", ".", "get_template", "(", "'maven-repository.jinja'", ")", "maven_repository", "=", "maven_repository_template", ".", "render", "(", "url", "=", "MAVEN_REPOSITORY", ",", "username", "=", "username", ",", "password", "=", "password", ")", "# Append Maven repository to build file to download unpublished files.", "with", "open", "(", "AAR_PROJECT_GRADLE", ",", "'a'", ")", "as", "gradle_file", ":", "gradle_file", ".", "write", "(", "maven_repository", ")", "# Read app build file.", "with", "open", "(", "AAR_PROJECT_APP_GRADLE", ",", "'r'", ")", "as", "gradle_app_file", ":", "gradle_app", "=", "gradle_app_file", ".", "read", "(", ")", "if", "AAR_PROJECT_DEPENDENCY", "not", "in", "gradle_app", ":", "raise", "Exception", "(", "'%s not found in the build file.'", "%", "AAR_PROJECT_DEPENDENCY", ")", "# Set version to the version to be tested.", "target_dependency", "=", "AAR_PROJECT_VERSION_DEPENDENCY", "%", "version", "gradle_app", "=", "gradle_app", ".", "replace", "(", "AAR_PROJECT_DEPENDENCY", ",", "target_dependency", ")", "# Write back.", "with", "open", "(", "AAR_PROJECT_APP_GRADLE", ",", "'w'", ")", "as", "gradle_app_file", ":", "gradle_app_file", ".", "write", "(", "gradle_app", ")", "# Uninstall any existing version of AppRTCMobile.", "logging", ".", "info", "(", "'Uninstalling previous AppRTCMobile versions. It is okay for '", "'these commands to fail if AppRTCMobile is not installed.'", ")", "subprocess", ".", "call", "(", "[", "ADB_BIN", ",", "'uninstall'", ",", "'org.appspot.apprtc'", "]", ")", "subprocess", ".", "call", "(", "[", "ADB_BIN", ",", "'uninstall'", ",", "'org.appspot.apprtc.test'", "]", ")", "# Run tests.", "try", ":", "# First clean the project.", "subprocess", ".", "check_call", "(", "[", "GRADLEW_BIN", ",", "'clean'", "]", ",", "cwd", "=", "AAR_PROJECT_DIR", ")", "# Then run the tests.", "subprocess", ".", "check_call", "(", "[", "GRADLEW_BIN", ",", "'connectedDebugAndroidTest'", "]", ",", "cwd", "=", "AAR_PROJECT_DIR", ")", "except", "subprocess", ".", "CalledProcessError", ":", "logging", ".", "exception", "(", "'Test failure.'", ")", "return", "False", "# Clean or tests failed", "return", "True", "# Tests pass", "finally", ":", "# Restore backups.", "shutil", ".", "copy2", "(", "gradle_backup", ",", "AAR_PROJECT_GRADLE", ")", "shutil", ".", "copy2", "(", "app_gradle_backup", ",", "AAR_PROJECT_APP_GRADLE", ")" ]
https://github.com/HackWebRTC/webrtc/blob/7abfc990c00ab35090fff285fcf635d1d7892433/tools_webrtc/android/release_aar.py#L138-L197
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/ed_keyh.py
python
ViKeyHandler._ProcessKey
(self, key_code)
The real processing of keys
The real processing of keys
[ "The", "real", "processing", "of", "keys" ]
def _ProcessKey(self, key_code): """The real processing of keys""" char = unichr(key_code) if self.IsNormalMode() or self.IsVisualMode(): self.buffer += char if ed_vim.Parse(self.buffer, self.commander): # command was handled (or invalid) so clear buffer self.buffer = u'' if self.IsVisualMode(): self.commander.ExtendSelection() elif self.IsInsertMode(): self.buffer += char
[ "def", "_ProcessKey", "(", "self", ",", "key_code", ")", ":", "char", "=", "unichr", "(", "key_code", ")", "if", "self", ".", "IsNormalMode", "(", ")", "or", "self", ".", "IsVisualMode", "(", ")", ":", "self", ".", "buffer", "+=", "char", "if", "ed_vim", ".", "Parse", "(", "self", ".", "buffer", ",", "self", ".", "commander", ")", ":", "# command was handled (or invalid) so clear buffer", "self", ".", "buffer", "=", "u''", "if", "self", ".", "IsVisualMode", "(", ")", ":", "self", ".", "commander", ".", "ExtendSelection", "(", ")", "elif", "self", ".", "IsInsertMode", "(", ")", ":", "self", ".", "buffer", "+=", "char" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_keyh.py#L264-L277
OpenLightingProject/ola
d1433a1bed73276fbe55ce18c03b1c208237decc
python/ola/PidStore.py
python
Group.__init__
(self, name, atoms, **kwargs)
Create a group of atoms. Args: name: The name of the group atoms: The list of atoms the group contains Raises: PidStructureException: if the structure of this group is invalid.
Create a group of atoms.
[ "Create", "a", "group", "of", "atoms", "." ]
def __init__(self, name, atoms, **kwargs): """Create a group of atoms. Args: name: The name of the group atoms: The list of atoms the group contains Raises: PidStructureException: if the structure of this group is invalid. """ super(Group, self).__init__(name) self._atoms = atoms self._min = kwargs.get('min_size') self._max = kwargs.get('max_size') # None for variable sized groups self._group_size = self._VerifyStructure()
[ "def", "__init__", "(", "self", ",", "name", ",", "atoms", ",", "*", "*", "kwargs", ")", ":", "super", "(", "Group", ",", "self", ")", ".", "__init__", "(", "name", ")", "self", ".", "_atoms", "=", "atoms", "self", ".", "_min", "=", "kwargs", ".", "get", "(", "'min_size'", ")", "self", ".", "_max", "=", "kwargs", ".", "get", "(", "'max_size'", ")", "# None for variable sized groups", "self", ".", "_group_size", "=", "self", ".", "_VerifyStructure", "(", ")" ]
https://github.com/OpenLightingProject/ola/blob/d1433a1bed73276fbe55ce18c03b1c208237decc/python/ola/PidStore.py#L700-L716
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/keras/mixed_precision/autocast_variable.py
python
AutoCastVariable._dense_var_to_tensor
(self, dtype=None, name=None, as_ref=False)
return math_ops.cast(val, self._cast_dtype)
Converts this variable to a tensor.
Converts this variable to a tensor.
[ "Converts", "this", "variable", "to", "a", "tensor", "." ]
def _dense_var_to_tensor(self, dtype=None, name=None, as_ref=False): """Converts this variable to a tensor.""" if as_ref: # This ValueError should not occur in practice since it is impossible to # pass as_ref=True using public APIs. raise ValueError('Cannot convert AutoCastVariable to a tensor if ' 'as_ref=True is passed to convert_to_tensor') if not self._should_cast(): return ops.convert_to_tensor_v2_with_dispatch(self._variable, dtype=dtype, name=name) if dtype is not None and not dtype.is_compatible_with(self._cast_dtype): raise ValueError( 'Incompatible type conversion requested to type {!r} for ' 'AutoCastVariable which is casted to type {!r}'.format( dtype.name, self._cast_dtype.name)) val = ops.convert_to_tensor_v2_with_dispatch( self._variable, dtype=self._variable.dtype, name=name) return math_ops.cast(val, self._cast_dtype)
[ "def", "_dense_var_to_tensor", "(", "self", ",", "dtype", "=", "None", ",", "name", "=", "None", ",", "as_ref", "=", "False", ")", ":", "if", "as_ref", ":", "# This ValueError should not occur in practice since it is impossible to", "# pass as_ref=True using public APIs.", "raise", "ValueError", "(", "'Cannot convert AutoCastVariable to a tensor if '", "'as_ref=True is passed to convert_to_tensor'", ")", "if", "not", "self", ".", "_should_cast", "(", ")", ":", "return", "ops", ".", "convert_to_tensor_v2_with_dispatch", "(", "self", ".", "_variable", ",", "dtype", "=", "dtype", ",", "name", "=", "name", ")", "if", "dtype", "is", "not", "None", "and", "not", "dtype", ".", "is_compatible_with", "(", "self", ".", "_cast_dtype", ")", ":", "raise", "ValueError", "(", "'Incompatible type conversion requested to type {!r} for '", "'AutoCastVariable which is casted to type {!r}'", ".", "format", "(", "dtype", ".", "name", ",", "self", ".", "_cast_dtype", ".", "name", ")", ")", "val", "=", "ops", ".", "convert_to_tensor_v2_with_dispatch", "(", "self", ".", "_variable", ",", "dtype", "=", "self", ".", "_variable", ".", "dtype", ",", "name", "=", "name", ")", "return", "math_ops", ".", "cast", "(", "val", ",", "self", ".", "_cast_dtype", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/mixed_precision/autocast_variable.py#L133-L150
mapnik/mapnik
f3da900c355e1d15059c4a91b00203dcc9d9f0ef
scons/scons-local-4.1.0/SCons/Tool/GettextCommon.py
python
_translate
(env, target=None, source=SCons.Environment._null, *args, **kw)
return po
Function for `Translate()` pseudo-builder
Function for `Translate()` pseudo-builder
[ "Function", "for", "Translate", "()", "pseudo", "-", "builder" ]
def _translate(env, target=None, source=SCons.Environment._null, *args, **kw): """ Function for `Translate()` pseudo-builder """ if target is None: target = [] pot = env.POTUpdate(None, source, *args, **kw) po = env.POUpdate(target, pot, *args, **kw) return po
[ "def", "_translate", "(", "env", ",", "target", "=", "None", ",", "source", "=", "SCons", ".", "Environment", ".", "_null", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "if", "target", "is", "None", ":", "target", "=", "[", "]", "pot", "=", "env", ".", "POTUpdate", "(", "None", ",", "source", ",", "*", "args", ",", "*", "*", "kw", ")", "po", "=", "env", ".", "POUpdate", "(", "target", ",", "pot", ",", "*", "args", ",", "*", "*", "kw", ")", "return", "po" ]
https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Tool/GettextCommon.py#L261-L266
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/html.py
python
HtmlWindow.OnOpeningURL
(*args, **kwargs)
return _html.HtmlWindow_OnOpeningURL(*args, **kwargs)
OnOpeningURL(self, int type, String url, String redirect) -> int
OnOpeningURL(self, int type, String url, String redirect) -> int
[ "OnOpeningURL", "(", "self", "int", "type", "String", "url", "String", "redirect", ")", "-", ">", "int" ]
def OnOpeningURL(*args, **kwargs): """OnOpeningURL(self, int type, String url, String redirect) -> int""" return _html.HtmlWindow_OnOpeningURL(*args, **kwargs)
[ "def", "OnOpeningURL", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_html", ".", "HtmlWindow_OnOpeningURL", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/html.py#L1130-L1132
flexflow/FlexFlow
581fad8ba8d10a16a3102ee2b406b0319586df24
examples/python/keras/candle_uno/default_utils.py
python
finalize_parameters
(bmk)
return gParameters
Utility to parse parameters in common as well as parameters particular to each benchmark. Parameters ---------- bmk : benchmark object Object that has benchmark filepaths and specifications Return ---------- gParameters : python dictionary Dictionary with all the parameters necessary to run the benchmark. Command line overwrites config file specifications
Utility to parse parameters in common as well as parameters particular to each benchmark.
[ "Utility", "to", "parse", "parameters", "in", "common", "as", "well", "as", "parameters", "particular", "to", "each", "benchmark", "." ]
def finalize_parameters(bmk): """Utility to parse parameters in common as well as parameters particular to each benchmark. Parameters ---------- bmk : benchmark object Object that has benchmark filepaths and specifications Return ---------- gParameters : python dictionary Dictionary with all the parameters necessary to run the benchmark. Command line overwrites config file specifications """ # Parse common parameters bmk.parse_from_common() # Parse parameters that are applicable just to benchmark bmk.parse_from_benchmark() #print('Args:', args) # Get parameters from configuration file # Reads parameter subset, just checking if a config_file has been set # by comand line (the parse_known_args() function allows a partial # parsing) aux = bmk.parser.parse_known_args() try : # Try to get the 'config_file' option conffile_txt = aux[0].config_file except AttributeError: # The 'config_file' option was not set by command-line conffile = bmk.conffile # use default file else: # a 'config_file' has been set --> use this file conffile = os.path.join(bmk.file_path, conffile_txt) #print("Configuration file: ", conffile) fileParameters = bmk.read_config_file(conffile)#aux.config_file)#args.config_file) # Get command-line parameters args, unkown = bmk.parser.parse_known_args() print(unkown) #print ('Params:', fileParameters) # Check keywords from file against CANDLE common and module definitions bmk_dict = bmk.additional_definitions check_file_parameters_exists(args, bmk_dict, fileParameters) # Consolidate parameter set. Command-line parameters overwrite file configuration gParameters = args_overwrite_config(args, fileParameters) # Check that required set of parameters has been defined bmk.check_required_exists(gParameters) print ('Params:') pprint(gParameters) # Check that no keywords conflict check_flag_conflicts(gParameters) return gParameters
[ "def", "finalize_parameters", "(", "bmk", ")", ":", "# Parse common parameters", "bmk", ".", "parse_from_common", "(", ")", "# Parse parameters that are applicable just to benchmark", "bmk", ".", "parse_from_benchmark", "(", ")", "#print('Args:', args)", "# Get parameters from configuration file", "# Reads parameter subset, just checking if a config_file has been set", "# by comand line (the parse_known_args() function allows a partial", "# parsing)", "aux", "=", "bmk", ".", "parser", ".", "parse_known_args", "(", ")", "try", ":", "# Try to get the 'config_file' option", "conffile_txt", "=", "aux", "[", "0", "]", ".", "config_file", "except", "AttributeError", ":", "# The 'config_file' option was not set by command-line", "conffile", "=", "bmk", ".", "conffile", "# use default file", "else", ":", "# a 'config_file' has been set --> use this file", "conffile", "=", "os", ".", "path", ".", "join", "(", "bmk", ".", "file_path", ",", "conffile_txt", ")", "#print(\"Configuration file: \", conffile)", "fileParameters", "=", "bmk", ".", "read_config_file", "(", "conffile", ")", "#aux.config_file)#args.config_file)", "# Get command-line parameters", "args", ",", "unkown", "=", "bmk", ".", "parser", ".", "parse_known_args", "(", ")", "print", "(", "unkown", ")", "#print ('Params:', fileParameters)", "# Check keywords from file against CANDLE common and module definitions", "bmk_dict", "=", "bmk", ".", "additional_definitions", "check_file_parameters_exists", "(", "args", ",", "bmk_dict", ",", "fileParameters", ")", "# Consolidate parameter set. Command-line parameters overwrite file configuration", "gParameters", "=", "args_overwrite_config", "(", "args", ",", "fileParameters", ")", "# Check that required set of parameters has been defined", "bmk", ".", "check_required_exists", "(", "gParameters", ")", "print", "(", "'Params:'", ")", "pprint", "(", "gParameters", ")", "# Check that no keywords conflict", "check_flag_conflicts", "(", "gParameters", ")", "return", "gParameters" ]
https://github.com/flexflow/FlexFlow/blob/581fad8ba8d10a16a3102ee2b406b0319586df24/examples/python/keras/candle_uno/default_utils.py#L411-L463
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/data/benchmarks/interleave_benchmark.py
python
_make_fake_dataset_fn
(initial_delay_us, remainder_delay_us)
return fake_dataset_fn
Returns a dataset that emulates a remote storage data source. Returns a dataset factory which creates a dataset with 100 elements that emulates the performance characteristic of a file-based dataset stored in a remote storage. In particular, the first element will take an order of magnitude longer to produce than the remaining elements (100ms vs. 1ms). Args: initial_delay_us: How long to wait before producing the first element. remainder_delay_us: How long to wait before producing subsequent elements.
Returns a dataset that emulates a remote storage data source.
[ "Returns", "a", "dataset", "that", "emulates", "a", "remote", "storage", "data", "source", "." ]
def _make_fake_dataset_fn(initial_delay_us, remainder_delay_us): """Returns a dataset that emulates a remote storage data source. Returns a dataset factory which creates a dataset with 100 elements that emulates the performance characteristic of a file-based dataset stored in a remote storage. In particular, the first element will take an order of magnitude longer to produce than the remaining elements (100ms vs. 1ms). Args: initial_delay_us: How long to wait before producing the first element. remainder_delay_us: How long to wait before producing subsequent elements. """ def fake_dataset_fn(unused): """Returns a function that creates a dataset with the specified delays.""" del unused def make_dataset(time_us, num_elements): dataset = dataset_ops.Dataset.range(num_elements) if time_us > 0: dataset = dataset.apply(testing.sleep(time_us)) return dataset if not initial_delay_us: return make_dataset(remainder_delay_us, 100) return make_dataset(initial_delay_us, 0).concatenate(make_dataset(remainder_delay_us, 100)) return fake_dataset_fn
[ "def", "_make_fake_dataset_fn", "(", "initial_delay_us", ",", "remainder_delay_us", ")", ":", "def", "fake_dataset_fn", "(", "unused", ")", ":", "\"\"\"Returns a function that creates a dataset with the specified delays.\"\"\"", "del", "unused", "def", "make_dataset", "(", "time_us", ",", "num_elements", ")", ":", "dataset", "=", "dataset_ops", ".", "Dataset", ".", "range", "(", "num_elements", ")", "if", "time_us", ">", "0", ":", "dataset", "=", "dataset", ".", "apply", "(", "testing", ".", "sleep", "(", "time_us", ")", ")", "return", "dataset", "if", "not", "initial_delay_us", ":", "return", "make_dataset", "(", "remainder_delay_us", ",", "100", ")", "return", "make_dataset", "(", "initial_delay_us", ",", "0", ")", ".", "concatenate", "(", "make_dataset", "(", "remainder_delay_us", ",", "100", ")", ")", "return", "fake_dataset_fn" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/data/benchmarks/interleave_benchmark.py#L27-L56
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/mac_tool.py
python
MacTool._CommandifyName
(self, name_string)
return name_string.title().replace("-", "")
Transforms a tool name like copy-info-plist to CopyInfoPlist
Transforms a tool name like copy-info-plist to CopyInfoPlist
[ "Transforms", "a", "tool", "name", "like", "copy", "-", "info", "-", "plist", "to", "CopyInfoPlist" ]
def _CommandifyName(self, name_string): """Transforms a tool name like copy-info-plist to CopyInfoPlist""" return name_string.title().replace("-", "")
[ "def", "_CommandifyName", "(", "self", ",", "name_string", ")", ":", "return", "name_string", ".", "title", "(", ")", ".", "replace", "(", "\"-\"", ",", "\"\"", ")" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/mac_tool.py#L45-L47
nasa/fprime
595cf3682d8365943d86c1a6fe7c78f0a116acf0
Autocoders/Python/src/fprime_ac/utils/XmlParser.py
python
Element.getAttr
(self, key=None)
Get an attribute value.
Get an attribute value.
[ "Get", "an", "attribute", "value", "." ]
def getAttr(self, key=None): """ Get an attribute value. """ if key is None: return self.attribute else: return self.attribute.get(key)
[ "def", "getAttr", "(", "self", ",", "key", "=", "None", ")", ":", "if", "key", "is", "None", ":", "return", "self", ".", "attribute", "else", ":", "return", "self", ".", "attribute", ".", "get", "(", "key", ")" ]
https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/utils/XmlParser.py#L453-L460
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
python/MooseDocs/extensions/pdf.py
python
PDFExtension._processPages
(self, root)
return main
Build a main latex file that includes the others.
Build a main latex file that includes the others.
[ "Build", "a", "main", "latex", "file", "that", "includes", "the", "others", "." ]
def _processPages(self, root): """ Build a main latex file that includes the others. """ main = base.NodeBase(None, None) latex.Command(main, 'documentclass', string='report', end='') for package, options in self.translator.renderer.getPackages().items(): args = [] if options[0] or options[1]: args = [self._getOptions(*options)] latex.Command(main, 'usepackage', args=args, string=package, start='\n', end='') latex.String(main, content='\\setlength{\\parindent}{0pt}', start='\n', escape=False) for preamble in self.translator.renderer.getPreamble(): latex.String(main, content='\n' + preamble, escape=False) # New Commands for cmd in self.translator.renderer.getNewCommands().values(): cmd.parent = main doc = latex.Environment(main, 'document', end='\n') for node in moosetree.iterate(root, lambda n: 'page' in n): page = node['page'] if page.get('active', True): cmd = latex.Command(doc, 'input', start='\n') latex.String(cmd, content=str(page.destination), escape=False) # BibTeX bib_files = [n.source for n in self.translator.getPages() if n.source.endswith('.bib')] if bib_files: latex.Command(doc, 'bibliographystyle', start='\n', string='unsrtnat') latex.Command(doc, 'bibliography', string=','.join(bib_files), start='\n', escape=False) return main
[ "def", "_processPages", "(", "self", ",", "root", ")", ":", "main", "=", "base", ".", "NodeBase", "(", "None", ",", "None", ")", "latex", ".", "Command", "(", "main", ",", "'documentclass'", ",", "string", "=", "'report'", ",", "end", "=", "''", ")", "for", "package", ",", "options", "in", "self", ".", "translator", ".", "renderer", ".", "getPackages", "(", ")", ".", "items", "(", ")", ":", "args", "=", "[", "]", "if", "options", "[", "0", "]", "or", "options", "[", "1", "]", ":", "args", "=", "[", "self", ".", "_getOptions", "(", "*", "options", ")", "]", "latex", ".", "Command", "(", "main", ",", "'usepackage'", ",", "args", "=", "args", ",", "string", "=", "package", ",", "start", "=", "'\\n'", ",", "end", "=", "''", ")", "latex", ".", "String", "(", "main", ",", "content", "=", "'\\\\setlength{\\\\parindent}{0pt}'", ",", "start", "=", "'\\n'", ",", "escape", "=", "False", ")", "for", "preamble", "in", "self", ".", "translator", ".", "renderer", ".", "getPreamble", "(", ")", ":", "latex", ".", "String", "(", "main", ",", "content", "=", "'\\n'", "+", "preamble", ",", "escape", "=", "False", ")", "# New Commands", "for", "cmd", "in", "self", ".", "translator", ".", "renderer", ".", "getNewCommands", "(", ")", ".", "values", "(", ")", ":", "cmd", ".", "parent", "=", "main", "doc", "=", "latex", ".", "Environment", "(", "main", ",", "'document'", ",", "end", "=", "'\\n'", ")", "for", "node", "in", "moosetree", ".", "iterate", "(", "root", ",", "lambda", "n", ":", "'page'", "in", "n", ")", ":", "page", "=", "node", "[", "'page'", "]", "if", "page", ".", "get", "(", "'active'", ",", "True", ")", ":", "cmd", "=", "latex", ".", "Command", "(", "doc", ",", "'input'", ",", "start", "=", "'\\n'", ")", "latex", ".", "String", "(", "cmd", ",", "content", "=", "str", "(", "page", ".", "destination", ")", ",", "escape", "=", "False", ")", "# BibTeX", "bib_files", "=", "[", "n", ".", "source", "for", "n", "in", "self", ".", "translator", ".", "getPages", "(", ")", "if", "n", ".", "source", ".", "endswith", "(", "'.bib'", ")", "]", "if", "bib_files", ":", "latex", ".", "Command", "(", "doc", ",", "'bibliographystyle'", ",", "start", "=", "'\\n'", ",", "string", "=", "'unsrtnat'", ")", "latex", ".", "Command", "(", "doc", ",", "'bibliography'", ",", "string", "=", "','", ".", "join", "(", "bib_files", ")", ",", "start", "=", "'\\n'", ",", "escape", "=", "False", ")", "return", "main" ]
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/MooseDocs/extensions/pdf.py#L107-L144
nnrg/opennero
43e12a1bcba6e228639db3886fec1dc47ddc24cb
mods/TowerofHanoi/tree_viewer.py
python
TreeViewer.add_completed_index
(self, index_to_add, viewer_index)
adds the given item index to the list of items to mark completed, then updates the display. Makes sure the index isn't alreay there first
adds the given item index to the list of items to mark completed, then updates the display. Makes sure the index isn't alreay there first
[ "adds", "the", "given", "item", "index", "to", "the", "list", "of", "items", "to", "mark", "completed", "then", "updates", "the", "display", ".", "Makes", "sure", "the", "index", "isn", "t", "alreay", "there", "first" ]
def add_completed_index(self, index_to_add, viewer_index): """adds the given item index to the list of items to mark completed, then updates the display. Makes sure the index isn't alreay there first""" if (viewer_index < self.MAX_ITEM_VIEWERS): self.item_viewers[viewer_index].addCompletedIndex(index_to_add)
[ "def", "add_completed_index", "(", "self", ",", "index_to_add", ",", "viewer_index", ")", ":", "if", "(", "viewer_index", "<", "self", ".", "MAX_ITEM_VIEWERS", ")", ":", "self", ".", "item_viewers", "[", "viewer_index", "]", ".", "addCompletedIndex", "(", "index_to_add", ")" ]
https://github.com/nnrg/opennero/blob/43e12a1bcba6e228639db3886fec1dc47ddc24cb/mods/TowerofHanoi/tree_viewer.py#L242-L245
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/ops/partitioned_variables.py
python
create_partitioned_variables
( shape, slicing, initializer, dtype=dtypes.float32, trainable=True, collections=None, name=None, reuse=None)
Create a list of partitioned variables according to the given `slicing`. Currently only one dimension of the full variable can be sliced, and the full variable can be reconstructed by the concatenation of the returned list along that dimension. Args: shape: List of integers. The shape of the full variable. slicing: List of integers. How to partition the variable. Must be of the same length as `shape`. Each value indicate how many slices to create in the corresponding dimension. Presently only one of the values can be more than 1; that is, the variable can only be sliced along one dimension. For convenience, The requested number of partitions does not have to divide the corresponding dimension evenly. If it does not, the shapes of the partitions are incremented by 1 starting from partition 0 until all slack is absorbed. The adjustment rules may change in the future, but as you can save/restore these variables with different slicing specifications this should not be a problem. initializer: A `Tensor` of shape `shape` or a variable initializer function. If a function, it will be called once for each slice, passing the shape and data type of the slice as parameters. The function must return a tensor with the same shape as the slice. dtype: Type of the variables. Ignored if `initializer` is a `Tensor`. trainable: If True also add all the variables to the graph collection `GraphKeys.TRAINABLE_VARIABLES`. collections: List of graph collections keys to add the variables to. Defaults to `[GraphKeys.VARIABLES]`. name: Optional name for the full variable. Defaults to `"PartitionedVariable"` and gets uniquified automatically. reuse: Boolean or `None`; if `True` and name is set, it would reuse previously created variables. if `False` it will create new variables. if `None`, it would inherit the parent scope reuse. Returns: A list of Variables corresponding to the slicing. Raises: ValueError: If any of the arguments is malformed.
Create a list of partitioned variables according to the given `slicing`.
[ "Create", "a", "list", "of", "partitioned", "variables", "according", "to", "the", "given", "slicing", "." ]
def create_partitioned_variables( shape, slicing, initializer, dtype=dtypes.float32, trainable=True, collections=None, name=None, reuse=None): """Create a list of partitioned variables according to the given `slicing`. Currently only one dimension of the full variable can be sliced, and the full variable can be reconstructed by the concatenation of the returned list along that dimension. Args: shape: List of integers. The shape of the full variable. slicing: List of integers. How to partition the variable. Must be of the same length as `shape`. Each value indicate how many slices to create in the corresponding dimension. Presently only one of the values can be more than 1; that is, the variable can only be sliced along one dimension. For convenience, The requested number of partitions does not have to divide the corresponding dimension evenly. If it does not, the shapes of the partitions are incremented by 1 starting from partition 0 until all slack is absorbed. The adjustment rules may change in the future, but as you can save/restore these variables with different slicing specifications this should not be a problem. initializer: A `Tensor` of shape `shape` or a variable initializer function. If a function, it will be called once for each slice, passing the shape and data type of the slice as parameters. The function must return a tensor with the same shape as the slice. dtype: Type of the variables. Ignored if `initializer` is a `Tensor`. trainable: If True also add all the variables to the graph collection `GraphKeys.TRAINABLE_VARIABLES`. collections: List of graph collections keys to add the variables to. Defaults to `[GraphKeys.VARIABLES]`. name: Optional name for the full variable. Defaults to `"PartitionedVariable"` and gets uniquified automatically. reuse: Boolean or `None`; if `True` and name is set, it would reuse previously created variables. if `False` it will create new variables. if `None`, it would inherit the parent scope reuse. Returns: A list of Variables corresponding to the slicing. Raises: ValueError: If any of the arguments is malformed. """ logging.warn( "create_partitioned_variables is deprecated. Use " "tf.get_variable with a partitioner set, or " "tf.get_partitioned_variable_list, instead.") if len(shape) != len(slicing): raise ValueError("The 'shape' and 'slicing' of a partitioned Variable " "must have the length: shape: %s, slicing: %s" % (shape, slicing)) if len(shape) < 1: raise ValueError("A partitioned Variable must have rank at least 1: " "shape: %s" % shape) # Legacy: we are provided the slicing directly, so just pass it to # the partitioner. partitioner = lambda **unused_kwargs: slicing with variable_scope.variable_op_scope( [], name, "PartitionedVariable", reuse=reuse): # pylint: disable=protected-access partitioned_var = variable_scope._get_partitioned_variable( name=None, shape=shape, dtype=dtype, initializer=initializer, trainable=trainable, partitioner=partitioner, collections=collections) return partitioned_var._get_variable_list()
[ "def", "create_partitioned_variables", "(", "shape", ",", "slicing", ",", "initializer", ",", "dtype", "=", "dtypes", ".", "float32", ",", "trainable", "=", "True", ",", "collections", "=", "None", ",", "name", "=", "None", ",", "reuse", "=", "None", ")", ":", "logging", ".", "warn", "(", "\"create_partitioned_variables is deprecated. Use \"", "\"tf.get_variable with a partitioner set, or \"", "\"tf.get_partitioned_variable_list, instead.\"", ")", "if", "len", "(", "shape", ")", "!=", "len", "(", "slicing", ")", ":", "raise", "ValueError", "(", "\"The 'shape' and 'slicing' of a partitioned Variable \"", "\"must have the length: shape: %s, slicing: %s\"", "%", "(", "shape", ",", "slicing", ")", ")", "if", "len", "(", "shape", ")", "<", "1", ":", "raise", "ValueError", "(", "\"A partitioned Variable must have rank at least 1: \"", "\"shape: %s\"", "%", "shape", ")", "# Legacy: we are provided the slicing directly, so just pass it to", "# the partitioner.", "partitioner", "=", "lambda", "*", "*", "unused_kwargs", ":", "slicing", "with", "variable_scope", ".", "variable_op_scope", "(", "[", "]", ",", "name", ",", "\"PartitionedVariable\"", ",", "reuse", "=", "reuse", ")", ":", "# pylint: disable=protected-access", "partitioned_var", "=", "variable_scope", ".", "_get_partitioned_variable", "(", "name", "=", "None", ",", "shape", "=", "shape", ",", "dtype", "=", "dtype", ",", "initializer", "=", "initializer", ",", "trainable", "=", "trainable", ",", "partitioner", "=", "partitioner", ",", "collections", "=", "collections", ")", "return", "partitioned_var", ".", "_get_variable_list", "(", ")" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/partitioned_variables.py#L218-L290
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_misc.py
python
DataObjectComposite.GetReceivedFormat
(*args, **kwargs)
return _misc_.DataObjectComposite_GetReceivedFormat(*args, **kwargs)
GetReceivedFormat(self) -> DataFormat Report the format passed to the `SetData` method. This should be the format of the data object within the composite that recieved data from the clipboard or the DnD operation. You can use this method to find out what kind of data object was recieved.
GetReceivedFormat(self) -> DataFormat
[ "GetReceivedFormat", "(", "self", ")", "-", ">", "DataFormat" ]
def GetReceivedFormat(*args, **kwargs): """ GetReceivedFormat(self) -> DataFormat Report the format passed to the `SetData` method. This should be the format of the data object within the composite that recieved data from the clipboard or the DnD operation. You can use this method to find out what kind of data object was recieved. """ return _misc_.DataObjectComposite_GetReceivedFormat(*args, **kwargs)
[ "def", "GetReceivedFormat", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "DataObjectComposite_GetReceivedFormat", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L5142-L5151
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/ResourceManager/resource_manager/security.py
python
IdentityPoolUtils.add_pool_to_assume_role_policy
(identity_pool_id, policy_document)
return policy_document, update
Add an identity pool to an AssumeRolePolicy statement - Only adds the pool if the role federates to Cognito identities via AssumeRoleWithWebIdentity - Ensures that the pool identity is only added if its not in the standard aud condition :param identity_pool_id: The pool_id to add :param policy_document: Policy document to update :return: The new document, boolean to see if it requires update
Add an identity pool to an AssumeRolePolicy statement - Only adds the pool if the role federates to Cognito identities via AssumeRoleWithWebIdentity - Ensures that the pool identity is only added if its not in the standard aud condition
[ "Add", "an", "identity", "pool", "to", "an", "AssumeRolePolicy", "statement", "-", "Only", "adds", "the", "pool", "if", "the", "role", "federates", "to", "Cognito", "identities", "via", "AssumeRoleWithWebIdentity", "-", "Ensures", "that", "the", "pool", "identity", "is", "only", "added", "if", "its", "not", "in", "the", "standard", "aud", "condition" ]
def add_pool_to_assume_role_policy(identity_pool_id, policy_document): """ Add an identity pool to an AssumeRolePolicy statement - Only adds the pool if the role federates to Cognito identities via AssumeRoleWithWebIdentity - Ensures that the pool identity is only added if its not in the standard aud condition :param identity_pool_id: The pool_id to add :param policy_document: Policy document to update :return: The new document, boolean to see if it requires update """ existing_pool_ids, cognito_federation_statement, cognito_aud_condition = \ IdentityPoolUtils.find_existing_pool_ids_references_in_assume_role_policy(policy_document) update = False # Is there a Cognito federation statement? if cognito_federation_statement: permission = cognito_federation_statement.get('Effect') # Enable Cognito role permissions that may have been denied during project update # Assumes all roles should be active (either attached to pool or in AdditionalAssumableRoles) if permission == 'Deny': cognito_federation_statement['Effect'] = 'Allow' update = True # No existing aud statement, so add one if cognito_aud_condition is None: new_condition = IdentityPoolUtils.generate_cognito_identity_condition_statement(identity_pool_id) if cognito_federation_statement.get('Condition') is None: cognito_federation_statement['Condition'] = {} cognito_federation_statement.get('Condition')['StringEquals'] = new_condition update = True # Else check to see if pool_id is not in Condition elif identity_pool_id not in existing_pool_ids: new_ids = [identity_pool_id] # See if we have an array or a string in condition if type(existing_pool_ids) is list: new_ids.extend(existing_pool_ids) else: new_ids.append(existing_pool_ids) cognito_aud_condition[IdentityPoolUtils.COGNITO_AUD_CONDITION_KEY] = new_ids update = True return policy_document, update
[ "def", "add_pool_to_assume_role_policy", "(", "identity_pool_id", ",", "policy_document", ")", ":", "existing_pool_ids", ",", "cognito_federation_statement", ",", "cognito_aud_condition", "=", "IdentityPoolUtils", ".", "find_existing_pool_ids_references_in_assume_role_policy", "(", "policy_document", ")", "update", "=", "False", "# Is there a Cognito federation statement?", "if", "cognito_federation_statement", ":", "permission", "=", "cognito_federation_statement", ".", "get", "(", "'Effect'", ")", "# Enable Cognito role permissions that may have been denied during project update", "# Assumes all roles should be active (either attached to pool or in AdditionalAssumableRoles)", "if", "permission", "==", "'Deny'", ":", "cognito_federation_statement", "[", "'Effect'", "]", "=", "'Allow'", "update", "=", "True", "# No existing aud statement, so add one", "if", "cognito_aud_condition", "is", "None", ":", "new_condition", "=", "IdentityPoolUtils", ".", "generate_cognito_identity_condition_statement", "(", "identity_pool_id", ")", "if", "cognito_federation_statement", ".", "get", "(", "'Condition'", ")", "is", "None", ":", "cognito_federation_statement", "[", "'Condition'", "]", "=", "{", "}", "cognito_federation_statement", ".", "get", "(", "'Condition'", ")", "[", "'StringEquals'", "]", "=", "new_condition", "update", "=", "True", "# Else check to see if pool_id is not in Condition", "elif", "identity_pool_id", "not", "in", "existing_pool_ids", ":", "new_ids", "=", "[", "identity_pool_id", "]", "# See if we have an array or a string in condition", "if", "type", "(", "existing_pool_ids", ")", "is", "list", ":", "new_ids", ".", "extend", "(", "existing_pool_ids", ")", "else", ":", "new_ids", ".", "append", "(", "existing_pool_ids", ")", "cognito_aud_condition", "[", "IdentityPoolUtils", ".", "COGNITO_AUD_CONDITION_KEY", "]", "=", "new_ids", "update", "=", "True", "return", "policy_document", ",", "update" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/ResourceManager/resource_manager/security.py#L940-L984
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_aarch64/python2.7/dist-packages/geographic_msgs/srv/_GetGeographicMap.py
python
GetGeographicMapResponse._get_types
(self)
return self._slot_types
internal API method
internal API method
[ "internal", "API", "method" ]
def _get_types(self): """ internal API method """ return self._slot_types
[ "def", "_get_types", "(", "self", ")", ":", "return", "self", ".", "_slot_types" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_aarch64/python2.7/dist-packages/geographic_msgs/srv/_GetGeographicMap.py#L347-L351
SFTtech/openage
d6a08c53c48dc1e157807471df92197f6ca9e04d
openage/convert/processor/conversion/aoc/media_subprocessor.py
python
AoCMediaSubprocessor.convert
(cls, full_data_set)
Create all export requests for the dataset.
Create all export requests for the dataset.
[ "Create", "all", "export", "requests", "for", "the", "dataset", "." ]
def convert(cls, full_data_set): """ Create all export requests for the dataset. """ cls.create_graphics_requests(full_data_set) # cls.create_blend_requests(full_data_set) cls.create_sound_requests(full_data_set)
[ "def", "convert", "(", "cls", ",", "full_data_set", ")", ":", "cls", ".", "create_graphics_requests", "(", "full_data_set", ")", "# cls.create_blend_requests(full_data_set)", "cls", ".", "create_sound_requests", "(", "full_data_set", ")" ]
https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/convert/processor/conversion/aoc/media_subprocessor.py#L21-L27
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/distribute/multi_worker_util.py
python
has_worker_context
()
return dc_context.get_current_worker_context() is not None
Returns whether a worker context has been entered.
Returns whether a worker context has been entered.
[ "Returns", "whether", "a", "worker", "context", "has", "been", "entered", "." ]
def has_worker_context(): """Returns whether a worker context has been entered.""" return dc_context.get_current_worker_context() is not None
[ "def", "has_worker_context", "(", ")", ":", "return", "dc_context", ".", "get_current_worker_context", "(", ")", "is", "not", "None" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/distribute/multi_worker_util.py#L257-L259
SpenceKonde/megaTinyCore
1c4a70b18a149fe6bcb551dfa6db11ca50b8997b
megaavr/tools/libs/serial/serialwin32.py
python
Serial.cd
(self)
return win32.MS_RLSD_ON & self._GetCommModemStatus() != 0
Read terminal status line: Carrier Detect
Read terminal status line: Carrier Detect
[ "Read", "terminal", "status", "line", ":", "Carrier", "Detect" ]
def cd(self): """Read terminal status line: Carrier Detect""" return win32.MS_RLSD_ON & self._GetCommModemStatus() != 0
[ "def", "cd", "(", "self", ")", ":", "return", "win32", ".", "MS_RLSD_ON", "&", "self", ".", "_GetCommModemStatus", "(", ")", "!=", "0" ]
https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/serial/serialwin32.py#L410-L412
baidu/tera
dbcd28af792d879d961bf9fc7eb60de81b437646
src/sdk/python/TeraSdk.py
python
RowMutation.DeleteColumn
(self, cf, qu)
删除这一行上 ColumnFamily为<cf>, Qualifier为<qu>的cell Args: cf(string): ColumnFamily名 qu(string): Qualifier名
删除这一行上 ColumnFamily为<cf>, Qualifier为<qu>的cell
[ "删除这一行上", "ColumnFamily为<cf", ">", "Qualifier为<qu", ">", "的cell" ]
def DeleteColumn(self, cf, qu): """ 删除这一行上 ColumnFamily为<cf>, Qualifier为<qu>的cell Args: cf(string): ColumnFamily名 qu(string): Qualifier名 """ lib.tera_row_mutation_delete_column(self.mutation, cf, qu, c_uint64(len(qu)))
[ "def", "DeleteColumn", "(", "self", ",", "cf", ",", "qu", ")", ":", "lib", ".", "tera_row_mutation_delete_column", "(", "self", ".", "mutation", ",", "cf", ",", "qu", ",", "c_uint64", "(", "len", "(", "qu", ")", ")", ")" ]
https://github.com/baidu/tera/blob/dbcd28af792d879d961bf9fc7eb60de81b437646/src/sdk/python/TeraSdk.py#L421-L430
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/MSVSProject.py
python
Writer.AddFileConfig
(self, path, config, attrs=None, tools=None)
Adds a configuration to a file. Args: path: Relative path to the file. config: Name of configuration to add. attrs: Dict of configuration attributes; may be None. tools: List of tools (strings or Tool objects); may be None. Raises: ValueError: Relative path does not match any file added via AddFiles().
Adds a configuration to a file.
[ "Adds", "a", "configuration", "to", "a", "file", "." ]
def AddFileConfig(self, path, config, attrs=None, tools=None): """Adds a configuration to a file. Args: path: Relative path to the file. config: Name of configuration to add. attrs: Dict of configuration attributes; may be None. tools: List of tools (strings or Tool objects); may be None. Raises: ValueError: Relative path does not match any file added via AddFiles(). """ # Find the file node with the right relative path parent = self.files_dict.get(path) if not parent: raise ValueError('AddFileConfig: file "%s" not in project.' % path) # Add the config to the file node spec = self._GetSpecForConfiguration('FileConfiguration', config, attrs, tools) parent.append(spec)
[ "def", "AddFileConfig", "(", "self", ",", "path", ",", "config", ",", "attrs", "=", "None", ",", "tools", "=", "None", ")", ":", "# Find the file node with the right relative path", "parent", "=", "self", ".", "files_dict", ".", "get", "(", "path", ")", "if", "not", "parent", ":", "raise", "ValueError", "(", "'AddFileConfig: file \"%s\" not in project.'", "%", "path", ")", "# Add the config to the file node", "spec", "=", "self", ".", "_GetSpecForConfiguration", "(", "'FileConfiguration'", ",", "config", ",", "attrs", ",", "tools", ")", "parent", ".", "append", "(", "spec", ")" ]
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/MSVSProject.py#L166-L186
alibaba/weex_js_engine
2bdf4b6f020c1fc99c63f649718f6faf7e27fdde
jni/v8core/v8/build/gyp/pylib/gyp/generator/ninja.py
python
CalculateVariables
(default_variables, params)
Calculate additional variables for use in the build (called by gyp).
Calculate additional variables for use in the build (called by gyp).
[ "Calculate", "additional", "variables", "for", "use", "in", "the", "build", "(", "called", "by", "gyp", ")", "." ]
def CalculateVariables(default_variables, params): """Calculate additional variables for use in the build (called by gyp).""" global generator_additional_non_configuration_keys global generator_additional_path_sections flavor = gyp.common.GetFlavor(params) if flavor == 'mac': default_variables.setdefault('OS', 'mac') default_variables.setdefault('SHARED_LIB_SUFFIX', '.dylib') default_variables.setdefault('SHARED_LIB_DIR', generator_default_variables['PRODUCT_DIR']) default_variables.setdefault('LIB_DIR', generator_default_variables['PRODUCT_DIR']) # Copy additional generator configuration data from Xcode, which is shared # by the Mac Ninja generator. import gyp.generator.xcode as xcode_generator generator_additional_non_configuration_keys = getattr(xcode_generator, 'generator_additional_non_configuration_keys', []) generator_additional_path_sections = getattr(xcode_generator, 'generator_additional_path_sections', []) global generator_extra_sources_for_rules generator_extra_sources_for_rules = getattr(xcode_generator, 'generator_extra_sources_for_rules', []) elif flavor == 'win': default_variables.setdefault('OS', 'win') default_variables['EXECUTABLE_SUFFIX'] = '.exe' default_variables['STATIC_LIB_PREFIX'] = '' default_variables['STATIC_LIB_SUFFIX'] = '.lib' default_variables['SHARED_LIB_PREFIX'] = '' default_variables['SHARED_LIB_SUFFIX'] = '.dll' generator_flags = params.get('generator_flags', {}) # Copy additional generator configuration data from VS, which is shared # by the Windows Ninja generator. import gyp.generator.msvs as msvs_generator generator_additional_non_configuration_keys = getattr(msvs_generator, 'generator_additional_non_configuration_keys', []) generator_additional_path_sections = getattr(msvs_generator, 'generator_additional_path_sections', []) # Set a variable so conditions can be based on msvs_version. msvs_version = gyp.msvs_emulation.GetVSVersion(generator_flags) default_variables['MSVS_VERSION'] = msvs_version.ShortName() # To determine processor word size on Windows, in addition to checking # PROCESSOR_ARCHITECTURE (which reflects the word size of the current # process), it is also necessary to check PROCESSOR_ARCHITEW6432 (which # contains the actual word size of the system when running thru WOW64). if ('64' in os.environ.get('PROCESSOR_ARCHITECTURE', '') or '64' in os.environ.get('PROCESSOR_ARCHITEW6432', '')): default_variables['MSVS_OS_BITS'] = 64 else: default_variables['MSVS_OS_BITS'] = 32 else: operating_system = flavor if flavor == 'android': operating_system = 'linux' # Keep this legacy behavior for now. default_variables.setdefault('OS', operating_system) default_variables.setdefault('SHARED_LIB_SUFFIX', '.so') default_variables.setdefault('SHARED_LIB_DIR', os.path.join('$!PRODUCT_DIR', 'lib')) default_variables.setdefault('LIB_DIR', os.path.join('$!PRODUCT_DIR', 'obj'))
[ "def", "CalculateVariables", "(", "default_variables", ",", "params", ")", ":", "global", "generator_additional_non_configuration_keys", "global", "generator_additional_path_sections", "flavor", "=", "gyp", ".", "common", ".", "GetFlavor", "(", "params", ")", "if", "flavor", "==", "'mac'", ":", "default_variables", ".", "setdefault", "(", "'OS'", ",", "'mac'", ")", "default_variables", ".", "setdefault", "(", "'SHARED_LIB_SUFFIX'", ",", "'.dylib'", ")", "default_variables", ".", "setdefault", "(", "'SHARED_LIB_DIR'", ",", "generator_default_variables", "[", "'PRODUCT_DIR'", "]", ")", "default_variables", ".", "setdefault", "(", "'LIB_DIR'", ",", "generator_default_variables", "[", "'PRODUCT_DIR'", "]", ")", "# Copy additional generator configuration data from Xcode, which is shared", "# by the Mac Ninja generator.", "import", "gyp", ".", "generator", ".", "xcode", "as", "xcode_generator", "generator_additional_non_configuration_keys", "=", "getattr", "(", "xcode_generator", ",", "'generator_additional_non_configuration_keys'", ",", "[", "]", ")", "generator_additional_path_sections", "=", "getattr", "(", "xcode_generator", ",", "'generator_additional_path_sections'", ",", "[", "]", ")", "global", "generator_extra_sources_for_rules", "generator_extra_sources_for_rules", "=", "getattr", "(", "xcode_generator", ",", "'generator_extra_sources_for_rules'", ",", "[", "]", ")", "elif", "flavor", "==", "'win'", ":", "default_variables", ".", "setdefault", "(", "'OS'", ",", "'win'", ")", "default_variables", "[", "'EXECUTABLE_SUFFIX'", "]", "=", "'.exe'", "default_variables", "[", "'STATIC_LIB_PREFIX'", "]", "=", "''", "default_variables", "[", "'STATIC_LIB_SUFFIX'", "]", "=", "'.lib'", "default_variables", "[", "'SHARED_LIB_PREFIX'", "]", "=", "''", "default_variables", "[", "'SHARED_LIB_SUFFIX'", "]", "=", "'.dll'", "generator_flags", "=", "params", ".", "get", "(", "'generator_flags'", ",", "{", "}", ")", "# Copy additional generator configuration data from VS, which is shared", "# by the Windows Ninja generator.", "import", "gyp", ".", "generator", ".", "msvs", "as", "msvs_generator", "generator_additional_non_configuration_keys", "=", "getattr", "(", "msvs_generator", ",", "'generator_additional_non_configuration_keys'", ",", "[", "]", ")", "generator_additional_path_sections", "=", "getattr", "(", "msvs_generator", ",", "'generator_additional_path_sections'", ",", "[", "]", ")", "# Set a variable so conditions can be based on msvs_version.", "msvs_version", "=", "gyp", ".", "msvs_emulation", ".", "GetVSVersion", "(", "generator_flags", ")", "default_variables", "[", "'MSVS_VERSION'", "]", "=", "msvs_version", ".", "ShortName", "(", ")", "# To determine processor word size on Windows, in addition to checking", "# PROCESSOR_ARCHITECTURE (which reflects the word size of the current", "# process), it is also necessary to check PROCESSOR_ARCHITEW6432 (which", "# contains the actual word size of the system when running thru WOW64).", "if", "(", "'64'", "in", "os", ".", "environ", ".", "get", "(", "'PROCESSOR_ARCHITECTURE'", ",", "''", ")", "or", "'64'", "in", "os", ".", "environ", ".", "get", "(", "'PROCESSOR_ARCHITEW6432'", ",", "''", ")", ")", ":", "default_variables", "[", "'MSVS_OS_BITS'", "]", "=", "64", "else", ":", "default_variables", "[", "'MSVS_OS_BITS'", "]", "=", "32", "else", ":", "operating_system", "=", "flavor", "if", "flavor", "==", "'android'", ":", "operating_system", "=", "'linux'", "# Keep this legacy behavior for now.", "default_variables", ".", "setdefault", "(", "'OS'", ",", "operating_system", ")", "default_variables", ".", "setdefault", "(", "'SHARED_LIB_SUFFIX'", ",", "'.so'", ")", "default_variables", ".", "setdefault", "(", "'SHARED_LIB_DIR'", ",", "os", ".", "path", ".", "join", "(", "'$!PRODUCT_DIR'", ",", "'lib'", ")", ")", "default_variables", ".", "setdefault", "(", "'LIB_DIR'", ",", "os", ".", "path", ".", "join", "(", "'$!PRODUCT_DIR'", ",", "'obj'", ")", ")" ]
https://github.com/alibaba/weex_js_engine/blob/2bdf4b6f020c1fc99c63f649718f6faf7e27fdde/jni/v8core/v8/build/gyp/pylib/gyp/generator/ninja.py#L1222-L1284
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBData.Append
(self, rhs)
return _lldb.SBData_Append(self, rhs)
Append(SBData self, SBData rhs) -> bool
Append(SBData self, SBData rhs) -> bool
[ "Append", "(", "SBData", "self", "SBData", "rhs", ")", "-", ">", "bool" ]
def Append(self, rhs): """Append(SBData self, SBData rhs) -> bool""" return _lldb.SBData_Append(self, rhs)
[ "def", "Append", "(", "self", ",", "rhs", ")", ":", "return", "_lldb", ".", "SBData_Append", "(", "self", ",", "rhs", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L3422-L3424
bumptop/BumpTop
466d23597a07ae738f4265262fa01087fc6e257c
trunk/win/Source/bin/jinja2/parser.py
python
Parser.parse_assign_target
(self, with_tuple=True, name_only=False, extra_end_rules=None)
return target
Parse an assignment target. As Jinja2 allows assignments to tuples, this function can parse all allowed assignment targets. Per default assignments to tuples are parsed, that can be disable however by setting `with_tuple` to `False`. If only assignments to names are wanted `name_only` can be set to `True`. The `extra_end_rules` parameter is forwarded to the tuple parsing function.
Parse an assignment target. As Jinja2 allows assignments to tuples, this function can parse all allowed assignment targets. Per default assignments to tuples are parsed, that can be disable however by setting `with_tuple` to `False`. If only assignments to names are wanted `name_only` can be set to `True`. The `extra_end_rules` parameter is forwarded to the tuple parsing function.
[ "Parse", "an", "assignment", "target", ".", "As", "Jinja2", "allows", "assignments", "to", "tuples", "this", "function", "can", "parse", "all", "allowed", "assignment", "targets", ".", "Per", "default", "assignments", "to", "tuples", "are", "parsed", "that", "can", "be", "disable", "however", "by", "setting", "with_tuple", "to", "False", ".", "If", "only", "assignments", "to", "names", "are", "wanted", "name_only", "can", "be", "set", "to", "True", ".", "The", "extra_end_rules", "parameter", "is", "forwarded", "to", "the", "tuple", "parsing", "function", "." ]
def parse_assign_target(self, with_tuple=True, name_only=False, extra_end_rules=None): """Parse an assignment target. As Jinja2 allows assignments to tuples, this function can parse all allowed assignment targets. Per default assignments to tuples are parsed, that can be disable however by setting `with_tuple` to `False`. If only assignments to names are wanted `name_only` can be set to `True`. The `extra_end_rules` parameter is forwarded to the tuple parsing function. """ if name_only: token = self.stream.expect('name') target = nodes.Name(token.value, 'store', lineno=token.lineno) else: if with_tuple: target = self.parse_tuple(simplified=True, extra_end_rules=extra_end_rules) else: target = self.parse_primary(with_postfix=False) target.set_ctx('store') if not target.can_assign(): self.fail('can\'t assign to %r' % target.__class__. __name__.lower(), target.lineno) return target
[ "def", "parse_assign_target", "(", "self", ",", "with_tuple", "=", "True", ",", "name_only", "=", "False", ",", "extra_end_rules", "=", "None", ")", ":", "if", "name_only", ":", "token", "=", "self", ".", "stream", ".", "expect", "(", "'name'", ")", "target", "=", "nodes", ".", "Name", "(", "token", ".", "value", ",", "'store'", ",", "lineno", "=", "token", ".", "lineno", ")", "else", ":", "if", "with_tuple", ":", "target", "=", "self", ".", "parse_tuple", "(", "simplified", "=", "True", ",", "extra_end_rules", "=", "extra_end_rules", ")", "else", ":", "target", "=", "self", ".", "parse_primary", "(", "with_postfix", "=", "False", ")", "target", ".", "set_ctx", "(", "'store'", ")", "if", "not", "target", ".", "can_assign", "(", ")", ":", "self", ".", "fail", "(", "'can\\'t assign to %r'", "%", "target", ".", "__class__", ".", "__name__", ".", "lower", "(", ")", ",", "target", ".", "lineno", ")", "return", "target" ]
https://github.com/bumptop/BumpTop/blob/466d23597a07ae738f4265262fa01087fc6e257c/trunk/win/Source/bin/jinja2/parser.py#L281-L303
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/distributed/passes/auto_parallel_recompute.py
python
_get_stop_gradients
(program, no_grad_set)
return no_grad_set_name
get no grad var
get no grad var
[ "get", "no", "grad", "var" ]
def _get_stop_gradients(program, no_grad_set): """ get no grad var """ if no_grad_set is None: no_grad_set = set() else: no_grad_set = _get_no_grad_set_name(no_grad_set) no_grad_set_name = set() for var in program.list_vars(): assert isinstance(var, Variable) if "@GRAD" in var.name: break if var.stop_gradient: no_grad_set_name.add(_append_grad_suffix_(var.name)) no_grad_set_name.update(list(map(_append_grad_suffix_, no_grad_set))) return no_grad_set_name
[ "def", "_get_stop_gradients", "(", "program", ",", "no_grad_set", ")", ":", "if", "no_grad_set", "is", "None", ":", "no_grad_set", "=", "set", "(", ")", "else", ":", "no_grad_set", "=", "_get_no_grad_set_name", "(", "no_grad_set", ")", "no_grad_set_name", "=", "set", "(", ")", "for", "var", "in", "program", ".", "list_vars", "(", ")", ":", "assert", "isinstance", "(", "var", ",", "Variable", ")", "if", "\"@GRAD\"", "in", "var", ".", "name", ":", "break", "if", "var", ".", "stop_gradient", ":", "no_grad_set_name", ".", "add", "(", "_append_grad_suffix_", "(", "var", ".", "name", ")", ")", "no_grad_set_name", ".", "update", "(", "list", "(", "map", "(", "_append_grad_suffix_", ",", "no_grad_set", ")", ")", ")", "return", "no_grad_set_name" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/distributed/passes/auto_parallel_recompute.py#L162-L177
cmu-db/bustub
fe1b9e984bd2967997b52df872c873d80f71cf7d
build_support/cpplint.py
python
CheckForIncludeWhatYouUse
(filename, clean_lines, include_state, error, io=codecs)
Reports for missing stl includes. This function will output warnings to make sure you are including the headers necessary for the stl containers and functions that you use. We only give one reason to include a header. For example, if you use both equal_to<> and less<> in a .h file, only one (the latter in the file) of these will be reported as a reason to include the <functional>. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. include_state: An _IncludeState instance. error: The function to call with any errors found. io: The IO factory to use to read the header file. Provided for unittest injection.
Reports for missing stl includes.
[ "Reports", "for", "missing", "stl", "includes", "." ]
def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error, io=codecs): """Reports for missing stl includes. This function will output warnings to make sure you are including the headers necessary for the stl containers and functions that you use. We only give one reason to include a header. For example, if you use both equal_to<> and less<> in a .h file, only one (the latter in the file) of these will be reported as a reason to include the <functional>. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. include_state: An _IncludeState instance. error: The function to call with any errors found. io: The IO factory to use to read the header file. Provided for unittest injection. """ required = {} # A map of header name to linenumber and the template entity. # Example of required: { '<functional>': (1219, 'less<>') } for linenum in xrange(clean_lines.NumLines()): line = clean_lines.elided[linenum] if not line or line[0] == '#': continue # String is special -- it is a non-templatized type in STL. matched = _RE_PATTERN_STRING.search(line) if matched: # Don't warn about strings in non-STL namespaces: # (We check only the first match per line; good enough.) prefix = line[:matched.start()] if prefix.endswith('std::') or not prefix.endswith('::'): required['<string>'] = (linenum, 'string') for pattern, template, header in _re_pattern_headers_maybe_templates: if pattern.search(line): required[header] = (linenum, template) # The following function is just a speed up, no semantics are changed. if not '<' in line: # Reduces the cpu time usage by skipping lines. continue for pattern, template, header in _re_pattern_templates: matched = pattern.search(line) if matched: # Don't warn about IWYU in non-STL namespaces: # (We check only the first match per line; good enough.) prefix = line[:matched.start()] if prefix.endswith('std::') or not prefix.endswith('::'): required[header] = (linenum, template) # The policy is that if you #include something in foo.h you don't need to # include it again in foo.cc. Here, we will look at possible includes. # Let's flatten the include_state include_list and copy it into a dictionary. include_dict = dict([item for sublist in include_state.include_list for item in sublist]) # Did we find the header for this file (if any) and successfully load it? header_found = False # Use the absolute path so that matching works properly. abs_filename = FileInfo(filename).FullName() # For Emacs's flymake. # If cpplint is invoked from Emacs's flymake, a temporary file is generated # by flymake and that file name might end with '_flymake.cc'. In that case, # restore original file name here so that the corresponding header file can be # found. # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h' # instead of 'foo_flymake.h' abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename) # include_dict is modified during iteration, so we iterate over a copy of # the keys. header_keys = list(include_dict.keys()) for header in header_keys: (same_module, common_path) = FilesBelongToSameModule(abs_filename, header) fullpath = common_path + header if same_module and UpdateIncludeState(fullpath, include_dict, io): header_found = True # If we can't find the header file for a .cc, assume it's because we don't # know where to look. In that case we'll give up as we're not sure they # didn't include it in the .h file. # TODO(unknown): Do a better job of finding .h files so we are confident that # not having the .h file means there isn't one. if not header_found: for extension in GetNonHeaderExtensions(): if filename.endswith('.' + extension): return # All the lines have been processed, report the errors found. for required_header_unstripped in sorted(required, key=required.__getitem__): template = required[required_header_unstripped][1] if required_header_unstripped.strip('<>"') not in include_dict: error(filename, required[required_header_unstripped][0], 'build/include_what_you_use', 4, 'Add #include ' + required_header_unstripped + ' for ' + template)
[ "def", "CheckForIncludeWhatYouUse", "(", "filename", ",", "clean_lines", ",", "include_state", ",", "error", ",", "io", "=", "codecs", ")", ":", "required", "=", "{", "}", "# A map of header name to linenumber and the template entity.", "# Example of required: { '<functional>': (1219, 'less<>') }", "for", "linenum", "in", "xrange", "(", "clean_lines", ".", "NumLines", "(", ")", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "not", "line", "or", "line", "[", "0", "]", "==", "'#'", ":", "continue", "# String is special -- it is a non-templatized type in STL.", "matched", "=", "_RE_PATTERN_STRING", ".", "search", "(", "line", ")", "if", "matched", ":", "# Don't warn about strings in non-STL namespaces:", "# (We check only the first match per line; good enough.)", "prefix", "=", "line", "[", ":", "matched", ".", "start", "(", ")", "]", "if", "prefix", ".", "endswith", "(", "'std::'", ")", "or", "not", "prefix", ".", "endswith", "(", "'::'", ")", ":", "required", "[", "'<string>'", "]", "=", "(", "linenum", ",", "'string'", ")", "for", "pattern", ",", "template", ",", "header", "in", "_re_pattern_headers_maybe_templates", ":", "if", "pattern", ".", "search", "(", "line", ")", ":", "required", "[", "header", "]", "=", "(", "linenum", ",", "template", ")", "# The following function is just a speed up, no semantics are changed.", "if", "not", "'<'", "in", "line", ":", "# Reduces the cpu time usage by skipping lines.", "continue", "for", "pattern", ",", "template", ",", "header", "in", "_re_pattern_templates", ":", "matched", "=", "pattern", ".", "search", "(", "line", ")", "if", "matched", ":", "# Don't warn about IWYU in non-STL namespaces:", "# (We check only the first match per line; good enough.)", "prefix", "=", "line", "[", ":", "matched", ".", "start", "(", ")", "]", "if", "prefix", ".", "endswith", "(", "'std::'", ")", "or", "not", "prefix", ".", "endswith", "(", "'::'", ")", ":", "required", "[", "header", "]", "=", "(", "linenum", ",", "template", ")", "# The policy is that if you #include something in foo.h you don't need to", "# include it again in foo.cc. Here, we will look at possible includes.", "# Let's flatten the include_state include_list and copy it into a dictionary.", "include_dict", "=", "dict", "(", "[", "item", "for", "sublist", "in", "include_state", ".", "include_list", "for", "item", "in", "sublist", "]", ")", "# Did we find the header for this file (if any) and successfully load it?", "header_found", "=", "False", "# Use the absolute path so that matching works properly.", "abs_filename", "=", "FileInfo", "(", "filename", ")", ".", "FullName", "(", ")", "# For Emacs's flymake.", "# If cpplint is invoked from Emacs's flymake, a temporary file is generated", "# by flymake and that file name might end with '_flymake.cc'. In that case,", "# restore original file name here so that the corresponding header file can be", "# found.", "# e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h'", "# instead of 'foo_flymake.h'", "abs_filename", "=", "re", ".", "sub", "(", "r'_flymake\\.cc$'", ",", "'.cc'", ",", "abs_filename", ")", "# include_dict is modified during iteration, so we iterate over a copy of", "# the keys.", "header_keys", "=", "list", "(", "include_dict", ".", "keys", "(", ")", ")", "for", "header", "in", "header_keys", ":", "(", "same_module", ",", "common_path", ")", "=", "FilesBelongToSameModule", "(", "abs_filename", ",", "header", ")", "fullpath", "=", "common_path", "+", "header", "if", "same_module", "and", "UpdateIncludeState", "(", "fullpath", ",", "include_dict", ",", "io", ")", ":", "header_found", "=", "True", "# If we can't find the header file for a .cc, assume it's because we don't", "# know where to look. In that case we'll give up as we're not sure they", "# didn't include it in the .h file.", "# TODO(unknown): Do a better job of finding .h files so we are confident that", "# not having the .h file means there isn't one.", "if", "not", "header_found", ":", "for", "extension", "in", "GetNonHeaderExtensions", "(", ")", ":", "if", "filename", ".", "endswith", "(", "'.'", "+", "extension", ")", ":", "return", "# All the lines have been processed, report the errors found.", "for", "required_header_unstripped", "in", "sorted", "(", "required", ",", "key", "=", "required", ".", "__getitem__", ")", ":", "template", "=", "required", "[", "required_header_unstripped", "]", "[", "1", "]", "if", "required_header_unstripped", ".", "strip", "(", "'<>\"'", ")", "not", "in", "include_dict", ":", "error", "(", "filename", ",", "required", "[", "required_header_unstripped", "]", "[", "0", "]", ",", "'build/include_what_you_use'", ",", "4", ",", "'Add #include '", "+", "required_header_unstripped", "+", "' for '", "+", "template", ")" ]
https://github.com/cmu-db/bustub/blob/fe1b9e984bd2967997b52df872c873d80f71cf7d/build_support/cpplint.py#L5782-L5880
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/posixpath.py
python
abspath
(path)
return normpath(path)
Return an absolute path.
Return an absolute path.
[ "Return", "an", "absolute", "path", "." ]
def abspath(path): """Return an absolute path.""" path = os.fspath(path) if not isabs(path): if isinstance(path, bytes): cwd = os.getcwdb() else: cwd = os.getcwd() path = join(cwd, path) return normpath(path)
[ "def", "abspath", "(", "path", ")", ":", "path", "=", "os", ".", "fspath", "(", "path", ")", "if", "not", "isabs", "(", "path", ")", ":", "if", "isinstance", "(", "path", ",", "bytes", ")", ":", "cwd", "=", "os", ".", "getcwdb", "(", ")", "else", ":", "cwd", "=", "os", ".", "getcwd", "(", ")", "path", "=", "join", "(", "cwd", ",", "path", ")", "return", "normpath", "(", "path", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/posixpath.py#L373-L382
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/zoombar.py
python
ImageBar.SetSize
(self, xSize, ySize)
Sets the size of :class:`ImageBar`. :param `xSize`: the width of the bar, in pixels; :param `ySize`: the height of the bar, in pixels.
Sets the size of :class:`ImageBar`.
[ "Sets", "the", "size", "of", ":", "class", ":", "ImageBar", "." ]
def SetSize(self, xSize, ySize): """ Sets the size of :class:`ImageBar`. :param `xSize`: the width of the bar, in pixels; :param `ySize`: the height of the bar, in pixels. """ self.SetBarColour(self._startColour, xSize, ySize)
[ "def", "SetSize", "(", "self", ",", "xSize", ",", "ySize", ")", ":", "self", ".", "SetBarColour", "(", "self", ".", "_startColour", ",", "xSize", ",", "ySize", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/zoombar.py#L610-L618
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/DNSFlippingRatioCorr.py
python
DNSFlippingRatioCorr.__init__
(self)
Init
Init
[ "Init" ]
def __init__(self): """ Init """ PythonAlgorithm.__init__(self) self.input_workspaces = {} self.sf_outws_name = None self.nsf_outws_name = None
[ "def", "__init__", "(", "self", ")", ":", "PythonAlgorithm", ".", "__init__", "(", "self", ")", "self", ".", "input_workspaces", "=", "{", "}", "self", ".", "sf_outws_name", "=", "None", "self", ".", "nsf_outws_name", "=", "None" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/DNSFlippingRatioCorr.py#L25-L32
lammps/lammps
b75c3065430a75b1b5543a10e10f46d9b4c91913
tools/i-pi/ipi/utils/io/io_xml.py
python
xml_handler.__init__
(self)
Initializes xml_handler.
Initializes xml_handler.
[ "Initializes", "xml_handler", "." ]
def __init__(self): """Initializes xml_handler.""" #root xml node with all the data self.root = xml_node(name="root", fields=[]) self.open = [self.root] #current level of the hierarchy self.level = 0 #Holds all the data between each of the tags. #If level = 1, then buffer[0] holds all the data collected between the #root tags, and buffer[1] holds all the data collected between the #first child tag. self.buffer = [[""]]
[ "def", "__init__", "(", "self", ")", ":", "#root xml node with all the data", "self", ".", "root", "=", "xml_node", "(", "name", "=", "\"root\"", ",", "fields", "=", "[", "]", ")", "self", ".", "open", "=", "[", "self", ".", "root", "]", "#current level of the hierarchy", "self", ".", "level", "=", "0", "#Holds all the data between each of the tags.", "#If level = 1, then buffer[0] holds all the data collected between the ", "#root tags, and buffer[1] holds all the data collected between the ", "#first child tag.", "self", ".", "buffer", "=", "[", "[", "\"\"", "]", "]" ]
https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/tools/i-pi/ipi/utils/io/io_xml.py#L103-L115
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
Rect2D.SetTop
(*args, **kwargs)
return _core_.Rect2D_SetTop(*args, **kwargs)
SetTop(self, Double n)
SetTop(self, Double n)
[ "SetTop", "(", "self", "Double", "n", ")" ]
def SetTop(*args, **kwargs): """SetTop(self, Double n)""" return _core_.Rect2D_SetTop(*args, **kwargs)
[ "def", "SetTop", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Rect2D_SetTop", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L1871-L1873
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/ed_search.py
python
SearchResultList.ApplyStyles
(self, start, txt)
Set a hotspot for each search result Search matches strings should be formatted as follows /file/name (line) match string @param start: long @param txt: string
Set a hotspot for each search result Search matches strings should be formatted as follows /file/name (line) match string @param start: long @param txt: string
[ "Set", "a", "hotspot", "for", "each", "search", "result", "Search", "matches", "strings", "should", "be", "formatted", "as", "follows", "/", "file", "/", "name", "(", "line", ")", "match", "string", "@param", "start", ":", "long", "@param", "txt", ":", "string" ]
def ApplyStyles(self, start, txt): """Set a hotspot for each search result Search matches strings should be formatted as follows /file/name (line) match string @param start: long @param txt: string """ self.StartStyling(start, 0x1f) if re.match(SearchResultList.RE_FIND_MATCH, txt): self.SetStyling(len(txt), SearchResultList.STY_SEARCH_MATCH) else: self.SetStyling(len(txt), eclib.OPB_STYLE_DEFAULT)
[ "def", "ApplyStyles", "(", "self", ",", "start", ",", "txt", ")", ":", "self", ".", "StartStyling", "(", "start", ",", "0x1f", ")", "if", "re", ".", "match", "(", "SearchResultList", ".", "RE_FIND_MATCH", ",", "txt", ")", ":", "self", ".", "SetStyling", "(", "len", "(", "txt", ")", ",", "SearchResultList", ".", "STY_SEARCH_MATCH", ")", "else", ":", "self", ".", "SetStyling", "(", "len", "(", "txt", ")", ",", "eclib", ".", "OPB_STYLE_DEFAULT", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_search.py#L1471-L1483
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/command/bdist_egg.py
python
bdist_egg.call_command
(self, cmdname, **kw)
return cmd
Invoke reinitialized command `cmdname` with keyword args
Invoke reinitialized command `cmdname` with keyword args
[ "Invoke", "reinitialized", "command", "cmdname", "with", "keyword", "args" ]
def call_command(self, cmdname, **kw): """Invoke reinitialized command `cmdname` with keyword args""" for dirname in INSTALL_DIRECTORY_ATTRS: kw.setdefault(dirname, self.bdist_dir) kw.setdefault('skip_build', self.skip_build) kw.setdefault('dry_run', self.dry_run) cmd = self.reinitialize_command(cmdname, **kw) self.run_command(cmdname) return cmd
[ "def", "call_command", "(", "self", ",", "cmdname", ",", "*", "*", "kw", ")", ":", "for", "dirname", "in", "INSTALL_DIRECTORY_ATTRS", ":", "kw", ".", "setdefault", "(", "dirname", ",", "self", ".", "bdist_dir", ")", "kw", ".", "setdefault", "(", "'skip_build'", ",", "self", ".", "skip_build", ")", "kw", ".", "setdefault", "(", "'dry_run'", ",", "self", ".", "dry_run", ")", "cmd", "=", "self", ".", "reinitialize_command", "(", "cmdname", ",", "*", "*", "kw", ")", "self", ".", "run_command", "(", "cmdname", ")", "return", "cmd" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/command/bdist_egg.py#L152-L160
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/idlelib/TreeWidget.py
python
TreeItem.GetSubList
(self)
Return list of items forming sublist.
Return list of items forming sublist.
[ "Return", "list", "of", "items", "forming", "sublist", "." ]
def GetSubList(self): """Return list of items forming sublist."""
[ "def", "GetSubList", "(", "self", ")", ":" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/idlelib/TreeWidget.py#L356-L357
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/tools/docs/parser.py
python
_ModulePageInfo.collect_docs_for_module
(self, parser_config)
Collect information necessary specifically for a module's doc page. Mainly this is information about the members of the module. Args: parser_config: An instance of ParserConfig.
Collect information necessary specifically for a module's doc page.
[ "Collect", "information", "necessary", "specifically", "for", "a", "module", "s", "doc", "page", "." ]
def collect_docs_for_module(self, parser_config): """Collect information necessary specifically for a module's doc page. Mainly this is information about the members of the module. Args: parser_config: An instance of ParserConfig. """ relative_path = os.path.relpath( path='.', start=os.path.dirname(documentation_path(self.full_name)) or '.') member_names = parser_config.tree.get(self.full_name, []) for name in member_names: if name in ['__builtins__', '__doc__', '__file__', '__name__', '__path__', '__package__', '__cached__', '__loader__', '__spec__']: continue member_full_name = self.full_name + '.' + name if self.full_name else name member = parser_config.py_name_to_object(member_full_name) member_doc = _parse_md_docstring(member, relative_path, parser_config.reference_resolver) url = parser_config.reference_resolver.reference_to_url( member_full_name, relative_path) if tf_inspect.ismodule(member): self._add_module(name, member_full_name, member, member_doc, url) elif tf_inspect.isclass(member): self._add_class(name, member_full_name, member, member_doc, url) elif tf_inspect.isfunction(member): self._add_function(name, member_full_name, member, member_doc, url) else: self._add_other_member(name, member_full_name, member, member_doc)
[ "def", "collect_docs_for_module", "(", "self", ",", "parser_config", ")", ":", "relative_path", "=", "os", ".", "path", ".", "relpath", "(", "path", "=", "'.'", ",", "start", "=", "os", ".", "path", ".", "dirname", "(", "documentation_path", "(", "self", ".", "full_name", ")", ")", "or", "'.'", ")", "member_names", "=", "parser_config", ".", "tree", ".", "get", "(", "self", ".", "full_name", ",", "[", "]", ")", "for", "name", "in", "member_names", ":", "if", "name", "in", "[", "'__builtins__'", ",", "'__doc__'", ",", "'__file__'", ",", "'__name__'", ",", "'__path__'", ",", "'__package__'", ",", "'__cached__'", ",", "'__loader__'", ",", "'__spec__'", "]", ":", "continue", "member_full_name", "=", "self", ".", "full_name", "+", "'.'", "+", "name", "if", "self", ".", "full_name", "else", "name", "member", "=", "parser_config", ".", "py_name_to_object", "(", "member_full_name", ")", "member_doc", "=", "_parse_md_docstring", "(", "member", ",", "relative_path", ",", "parser_config", ".", "reference_resolver", ")", "url", "=", "parser_config", ".", "reference_resolver", ".", "reference_to_url", "(", "member_full_name", ",", "relative_path", ")", "if", "tf_inspect", ".", "ismodule", "(", "member", ")", ":", "self", ".", "_add_module", "(", "name", ",", "member_full_name", ",", "member", ",", "member_doc", ",", "url", ")", "elif", "tf_inspect", ".", "isclass", "(", "member", ")", ":", "self", ".", "_add_class", "(", "name", ",", "member_full_name", ",", "member", ",", "member_doc", ",", "url", ")", "elif", "tf_inspect", ".", "isfunction", "(", "member", ")", ":", "self", ".", "_add_function", "(", "name", ",", "member_full_name", ",", "member", ",", "member_doc", ",", "url", ")", "else", ":", "self", ".", "_add_other_member", "(", "name", ",", "member_full_name", ",", "member", ",", "member_doc", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/tools/docs/parser.py#L1408-L1447
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/richtext.py
python
RichTextFileHandlerList.__iter__
(*args, **kwargs)
return _richtext.RichTextFileHandlerList___iter__(*args, **kwargs)
__iter__(self) -> RichTextFileHandlerList_iterator
__iter__(self) -> RichTextFileHandlerList_iterator
[ "__iter__", "(", "self", ")", "-", ">", "RichTextFileHandlerList_iterator" ]
def __iter__(*args, **kwargs): """__iter__(self) -> RichTextFileHandlerList_iterator""" return _richtext.RichTextFileHandlerList___iter__(*args, **kwargs)
[ "def", "__iter__", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextFileHandlerList___iter__", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L2187-L2189
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
benchmarks/operator_benchmark/benchmark_caffe2.py
python
generate_c2_test
(configs, c2_bench_op)
return _register_test(configs, c2_bench_op, create_caffe2_op_test_case, False)
This function creates Caffe2 op test based on the given operator
This function creates Caffe2 op test based on the given operator
[ "This", "function", "creates", "Caffe2", "op", "test", "based", "on", "the", "given", "operator" ]
def generate_c2_test(configs, c2_bench_op): """ This function creates Caffe2 op test based on the given operator """ return _register_test(configs, c2_bench_op, create_caffe2_op_test_case, False)
[ "def", "generate_c2_test", "(", "configs", ",", "c2_bench_op", ")", ":", "return", "_register_test", "(", "configs", ",", "c2_bench_op", ",", "create_caffe2_op_test_case", ",", "False", ")" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/benchmarks/operator_benchmark/benchmark_caffe2.py#L194-L198
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/tools/inspector_protocol/jinja2/debug.py
python
ProcessedTraceback.exc_info
(self)
return self.exc_type, self.exc_value, self.frames[0]
Exception info tuple with a proxy around the frame objects.
Exception info tuple with a proxy around the frame objects.
[ "Exception", "info", "tuple", "with", "a", "proxy", "around", "the", "frame", "objects", "." ]
def exc_info(self): """Exception info tuple with a proxy around the frame objects.""" return self.exc_type, self.exc_value, self.frames[0]
[ "def", "exc_info", "(", "self", ")", ":", "return", "self", ".", "exc_type", ",", "self", ".", "exc_value", ",", "self", ".", "frames", "[", "0", "]" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/inspector_protocol/jinja2/debug.py#L117-L119
PixarAnimationStudios/USD
faed18ce62c8736b02413635b584a2f637156bad
pxr/usdImaging/usdviewq/appController.py
python
AppController._setFrameIndex
(self, frameIndex)
Set the `frameIndex`. Args: frameIndex (int): The new frame index value.
Set the `frameIndex`.
[ "Set", "the", "frameIndex", "." ]
def _setFrameIndex(self, frameIndex): """Set the `frameIndex`. Args: frameIndex (int): The new frame index value. """ # Ensure the frameIndex exists, if not, return. try: frame = self._timeSamples[frameIndex] except IndexError: return currentFrame = Usd.TimeCode(frame) if self._dataModel.currentFrame != currentFrame: self._dataModel.currentFrame = currentFrame self._ui.frameSlider.setValue(frameIndex) self._updateOnFrameChange() self.setFrameField(self._dataModel.currentFrame.GetValue())
[ "def", "_setFrameIndex", "(", "self", ",", "frameIndex", ")", ":", "# Ensure the frameIndex exists, if not, return.", "try", ":", "frame", "=", "self", ".", "_timeSamples", "[", "frameIndex", "]", "except", "IndexError", ":", "return", "currentFrame", "=", "Usd", ".", "TimeCode", "(", "frame", ")", "if", "self", ".", "_dataModel", ".", "currentFrame", "!=", "currentFrame", ":", "self", ".", "_dataModel", ".", "currentFrame", "=", "currentFrame", "self", ".", "_ui", ".", "frameSlider", ".", "setValue", "(", "frameIndex", ")", "self", ".", "_updateOnFrameChange", "(", ")", "self", ".", "setFrameField", "(", "self", ".", "_dataModel", ".", "currentFrame", ".", "GetValue", "(", ")", ")" ]
https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/pxr/usdImaging/usdviewq/appController.py#L3451-L3471
mapnik/mapnik
f3da900c355e1d15059c4a91b00203dcc9d9f0ef
scons/scons-local-4.1.0/SCons/Taskmaster.py
python
Taskmaster.stop
(self)
Stops the current build completely.
Stops the current build completely.
[ "Stops", "the", "current", "build", "completely", "." ]
def stop(self): """ Stops the current build completely. """ self.next_candidate = self.no_next_candidate
[ "def", "stop", "(", "self", ")", ":", "self", ".", "next_candidate", "=", "self", ".", "no_next_candidate" ]
https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Taskmaster.py#L1020-L1024
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/utils/vim-lldb/python-vim-lldb/vim_panes.py
python
VimPane.get_content
(self, target, controller)
subclasses implement this to provide pane content
subclasses implement this to provide pane content
[ "subclasses", "implement", "this", "to", "provide", "pane", "content" ]
def get_content(self, target, controller): """ subclasses implement this to provide pane content """ assert(0 and "pane subclass must implement this") pass
[ "def", "get_content", "(", "self", ",", "target", ",", "controller", ")", ":", "assert", "(", "0", "and", "\"pane subclass must implement this\"", ")", "pass" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/utils/vim-lldb/python-vim-lldb/vim_panes.py#L388-L391
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/compat/numpy/function.py
python
validate_take_with_convert
(convert, args, kwargs)
return convert
If this function is called via the 'numpy' library, the third parameter in its signature is 'axis', which takes either an ndarray or 'None', so check if the 'convert' parameter is either an instance of ndarray or is None
If this function is called via the 'numpy' library, the third parameter in its signature is 'axis', which takes either an ndarray or 'None', so check if the 'convert' parameter is either an instance of ndarray or is None
[ "If", "this", "function", "is", "called", "via", "the", "numpy", "library", "the", "third", "parameter", "in", "its", "signature", "is", "axis", "which", "takes", "either", "an", "ndarray", "or", "None", "so", "check", "if", "the", "convert", "parameter", "is", "either", "an", "instance", "of", "ndarray", "or", "is", "None" ]
def validate_take_with_convert(convert, args, kwargs): """ If this function is called via the 'numpy' library, the third parameter in its signature is 'axis', which takes either an ndarray or 'None', so check if the 'convert' parameter is either an instance of ndarray or is None """ if isinstance(convert, ndarray) or convert is None: args = (convert,) + args convert = True validate_take(args, kwargs, max_fname_arg_count=3, method="both") return convert
[ "def", "validate_take_with_convert", "(", "convert", ",", "args", ",", "kwargs", ")", ":", "if", "isinstance", "(", "convert", ",", "ndarray", ")", "or", "convert", "is", "None", ":", "args", "=", "(", "convert", ",", ")", "+", "args", "convert", "=", "True", "validate_take", "(", "args", ",", "kwargs", ",", "max_fname_arg_count", "=", "3", ",", "method", "=", "\"both\"", ")", "return", "convert" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/compat/numpy/function.py#L281-L294
bitcoinx-project/bitcoinx
d422a992e7efee1ea1fb82cf7a1e81e04ca716c0
contrib/linearize/linearize-data.py
python
hex_switchEndian
(s)
return b''.join(pairList[::-1]).decode()
Switches the endianness of a hex string (in pairs of hex chars)
Switches the endianness of a hex string (in pairs of hex chars)
[ "Switches", "the", "endianness", "of", "a", "hex", "string", "(", "in", "pairs", "of", "hex", "chars", ")" ]
def hex_switchEndian(s): """ Switches the endianness of a hex string (in pairs of hex chars) """ pairList = [s[i:i+2].encode() for i in range(0, len(s), 2)] return b''.join(pairList[::-1]).decode()
[ "def", "hex_switchEndian", "(", "s", ")", ":", "pairList", "=", "[", "s", "[", "i", ":", "i", "+", "2", "]", ".", "encode", "(", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "s", ")", ",", "2", ")", "]", "return", "b''", ".", "join", "(", "pairList", "[", ":", ":", "-", "1", "]", ")", ".", "decode", "(", ")" ]
https://github.com/bitcoinx-project/bitcoinx/blob/d422a992e7efee1ea1fb82cf7a1e81e04ca716c0/contrib/linearize/linearize-data.py#L25-L28
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBProcess.ReadMemory
(self, addr, buf, error)
return _lldb.SBProcess_ReadMemory(self, addr, buf, error)
Reads memory from the current process's address space and removes any traps that may have been inserted into the memory. It returns the byte buffer in a Python string. Example: # Read 4 bytes from address 'addr' and assume error.Success() is True. content = process.ReadMemory(addr, 4, error) new_bytes = bytearray(content)
[]
def ReadMemory(self, addr, buf, error): """ Reads memory from the current process's address space and removes any traps that may have been inserted into the memory. It returns the byte buffer in a Python string. Example: # Read 4 bytes from address 'addr' and assume error.Success() is True. content = process.ReadMemory(addr, 4, error) new_bytes = bytearray(content) """ return _lldb.SBProcess_ReadMemory(self, addr, buf, error)
[ "def", "ReadMemory", "(", "self", ",", "addr", ",", "buf", ",", "error", ")", ":", "return", "_lldb", ".", "SBProcess_ReadMemory", "(", "self", ",", "addr", ",", "buf", ",", "error", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L8567-L8578
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/xml/etree/ElementTree.py
python
XMLPullParser.feed
(self, data)
Feed encoded data to parser.
Feed encoded data to parser.
[ "Feed", "encoded", "data", "to", "parser", "." ]
def feed(self, data): """Feed encoded data to parser.""" if self._parser is None: raise ValueError("feed() called after end of stream") if data: try: self._parser.feed(data) except SyntaxError as exc: self._events_queue.append(exc)
[ "def", "feed", "(", "self", ",", "data", ")", ":", "if", "self", ".", "_parser", "is", "None", ":", "raise", "ValueError", "(", "\"feed() called after end of stream\"", ")", "if", "data", ":", "try", ":", "self", ".", "_parser", ".", "feed", "(", "data", ")", "except", "SyntaxError", "as", "exc", ":", "self", ".", "_events_queue", ".", "append", "(", "exc", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/xml/etree/ElementTree.py#L1295-L1303
sigmaai/self-driving-golf-cart
8d891600af3d851add27a10ae45cf3c2108bb87c
ros/src/detection/object_detection/scripts/yolo3/model.py
python
tiny_yolo_body
(inputs, num_anchors, num_classes)
return Model(inputs, [y1,y2])
Create Tiny YOLO_v3 model CNN body in keras.
Create Tiny YOLO_v3 model CNN body in keras.
[ "Create", "Tiny", "YOLO_v3", "model", "CNN", "body", "in", "keras", "." ]
def tiny_yolo_body(inputs, num_anchors, num_classes): """Create Tiny YOLO_v3 model CNN body in keras.""" x1 = compose( DarknetConv2D_BN_Leaky(16, (3,3)), MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'), DarknetConv2D_BN_Leaky(32, (3,3)), MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'), DarknetConv2D_BN_Leaky(64, (3,3)), MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'), DarknetConv2D_BN_Leaky(128, (3,3)), MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'), DarknetConv2D_BN_Leaky(256, (3,3)))(inputs) x2 = compose( MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'), DarknetConv2D_BN_Leaky(512, (3,3)), MaxPooling2D(pool_size=(2,2), strides=(1,1), padding='same'), DarknetConv2D_BN_Leaky(1024, (3,3)), DarknetConv2D_BN_Leaky(256, (1,1)))(x1) y1 = compose( DarknetConv2D_BN_Leaky(512, (3,3)), DarknetConv2D(num_anchors*(num_classes+5), (1,1)))(x2) x2 = compose( DarknetConv2D_BN_Leaky(128, (1,1)), UpSampling2D(2))(x2) y2 = compose( Concatenate(), DarknetConv2D_BN_Leaky(256, (3,3)), DarknetConv2D(num_anchors*(num_classes+5), (1,1)))([x2,x1]) return Model(inputs, [y1,y2])
[ "def", "tiny_yolo_body", "(", "inputs", ",", "num_anchors", ",", "num_classes", ")", ":", "x1", "=", "compose", "(", "DarknetConv2D_BN_Leaky", "(", "16", ",", "(", "3", ",", "3", ")", ")", ",", "MaxPooling2D", "(", "pool_size", "=", "(", "2", ",", "2", ")", ",", "strides", "=", "(", "2", ",", "2", ")", ",", "padding", "=", "'same'", ")", ",", "DarknetConv2D_BN_Leaky", "(", "32", ",", "(", "3", ",", "3", ")", ")", ",", "MaxPooling2D", "(", "pool_size", "=", "(", "2", ",", "2", ")", ",", "strides", "=", "(", "2", ",", "2", ")", ",", "padding", "=", "'same'", ")", ",", "DarknetConv2D_BN_Leaky", "(", "64", ",", "(", "3", ",", "3", ")", ")", ",", "MaxPooling2D", "(", "pool_size", "=", "(", "2", ",", "2", ")", ",", "strides", "=", "(", "2", ",", "2", ")", ",", "padding", "=", "'same'", ")", ",", "DarknetConv2D_BN_Leaky", "(", "128", ",", "(", "3", ",", "3", ")", ")", ",", "MaxPooling2D", "(", "pool_size", "=", "(", "2", ",", "2", ")", ",", "strides", "=", "(", "2", ",", "2", ")", ",", "padding", "=", "'same'", ")", ",", "DarknetConv2D_BN_Leaky", "(", "256", ",", "(", "3", ",", "3", ")", ")", ")", "(", "inputs", ")", "x2", "=", "compose", "(", "MaxPooling2D", "(", "pool_size", "=", "(", "2", ",", "2", ")", ",", "strides", "=", "(", "2", ",", "2", ")", ",", "padding", "=", "'same'", ")", ",", "DarknetConv2D_BN_Leaky", "(", "512", ",", "(", "3", ",", "3", ")", ")", ",", "MaxPooling2D", "(", "pool_size", "=", "(", "2", ",", "2", ")", ",", "strides", "=", "(", "1", ",", "1", ")", ",", "padding", "=", "'same'", ")", ",", "DarknetConv2D_BN_Leaky", "(", "1024", ",", "(", "3", ",", "3", ")", ")", ",", "DarknetConv2D_BN_Leaky", "(", "256", ",", "(", "1", ",", "1", ")", ")", ")", "(", "x1", ")", "y1", "=", "compose", "(", "DarknetConv2D_BN_Leaky", "(", "512", ",", "(", "3", ",", "3", ")", ")", ",", "DarknetConv2D", "(", "num_anchors", "*", "(", "num_classes", "+", "5", ")", ",", "(", "1", ",", "1", ")", ")", ")", "(", "x2", ")", "x2", "=", "compose", "(", "DarknetConv2D_BN_Leaky", "(", "128", ",", "(", "1", ",", "1", ")", ")", ",", "UpSampling2D", "(", "2", ")", ")", "(", "x2", ")", "y2", "=", "compose", "(", "Concatenate", "(", ")", ",", "DarknetConv2D_BN_Leaky", "(", "256", ",", "(", "3", ",", "3", ")", ")", ",", "DarknetConv2D", "(", "num_anchors", "*", "(", "num_classes", "+", "5", ")", ",", "(", "1", ",", "1", ")", ")", ")", "(", "[", "x2", ",", "x1", "]", ")", "return", "Model", "(", "inputs", ",", "[", "y1", ",", "y2", "]", ")" ]
https://github.com/sigmaai/self-driving-golf-cart/blob/8d891600af3d851add27a10ae45cf3c2108bb87c/ros/src/detection/object_detection/scripts/yolo3/model.py#L102-L132
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pkg_resources/__init__.py
python
ResourceManager.cleanup_resources
(self, force=False)
Delete all extracted resource files and directories, returning a list of the file and directory names that could not be successfully removed. This function does not have any concurrency protection, so it should generally only be called when the extraction path is a temporary directory exclusive to a single process. This method is not automatically called; you must call it explicitly or register it as an ``atexit`` function if you wish to ensure cleanup of a temporary directory used for extractions.
Delete all extracted resource files and directories, returning a list of the file and directory names that could not be successfully removed. This function does not have any concurrency protection, so it should generally only be called when the extraction path is a temporary directory exclusive to a single process. This method is not automatically called; you must call it explicitly or register it as an ``atexit`` function if you wish to ensure cleanup of a temporary directory used for extractions.
[ "Delete", "all", "extracted", "resource", "files", "and", "directories", "returning", "a", "list", "of", "the", "file", "and", "directory", "names", "that", "could", "not", "be", "successfully", "removed", ".", "This", "function", "does", "not", "have", "any", "concurrency", "protection", "so", "it", "should", "generally", "only", "be", "called", "when", "the", "extraction", "path", "is", "a", "temporary", "directory", "exclusive", "to", "a", "single", "process", ".", "This", "method", "is", "not", "automatically", "called", ";", "you", "must", "call", "it", "explicitly", "or", "register", "it", "as", "an", "atexit", "function", "if", "you", "wish", "to", "ensure", "cleanup", "of", "a", "temporary", "directory", "used", "for", "extractions", "." ]
def cleanup_resources(self, force=False): """ Delete all extracted resource files and directories, returning a list of the file and directory names that could not be successfully removed. This function does not have any concurrency protection, so it should generally only be called when the extraction path is a temporary directory exclusive to a single process. This method is not automatically called; you must call it explicitly or register it as an ``atexit`` function if you wish to ensure cleanup of a temporary directory used for extractions. """
[ "def", "cleanup_resources", "(", "self", ",", "force", "=", "False", ")", ":" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pkg_resources/__init__.py#L1291-L1301
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/layers/python/layers/regularizers.py
python
sum_regularizer
(regularizer_list, scope=None)
return sum_reg
Returns a function that applies the sum of multiple regularizers. Args: regularizer_list: A list of regularizers to apply. scope: An optional scope name Returns: A function with signature `sum_reg(weights)` that applies the sum of all the input regularizers.
Returns a function that applies the sum of multiple regularizers.
[ "Returns", "a", "function", "that", "applies", "the", "sum", "of", "multiple", "regularizers", "." ]
def sum_regularizer(regularizer_list, scope=None): """Returns a function that applies the sum of multiple regularizers. Args: regularizer_list: A list of regularizers to apply. scope: An optional scope name Returns: A function with signature `sum_reg(weights)` that applies the sum of all the input regularizers. """ regularizer_list = [reg for reg in regularizer_list if reg is not None] if not regularizer_list: return None def sum_reg(weights): """Applies the sum of all the input regularizers.""" with ops.name_scope(scope, 'sum_regularizer', [weights]) as name: regularizer_tensors = [] for reg in regularizer_list: tensor = reg(weights) if tensor is not None: regularizer_tensors.append(tensor) return math_ops.add_n( regularizer_tensors, name=name) if regularizer_tensors else None return sum_reg
[ "def", "sum_regularizer", "(", "regularizer_list", ",", "scope", "=", "None", ")", ":", "regularizer_list", "=", "[", "reg", "for", "reg", "in", "regularizer_list", "if", "reg", "is", "not", "None", "]", "if", "not", "regularizer_list", ":", "return", "None", "def", "sum_reg", "(", "weights", ")", ":", "\"\"\"Applies the sum of all the input regularizers.\"\"\"", "with", "ops", ".", "name_scope", "(", "scope", ",", "'sum_regularizer'", ",", "[", "weights", "]", ")", "as", "name", ":", "regularizer_tensors", "=", "[", "]", "for", "reg", "in", "regularizer_list", ":", "tensor", "=", "reg", "(", "weights", ")", "if", "tensor", "is", "not", "None", ":", "regularizer_tensors", ".", "append", "(", "tensor", ")", "return", "math_ops", ".", "add_n", "(", "regularizer_tensors", ",", "name", "=", "name", ")", "if", "regularizer_tensors", "else", "None", "return", "sum_reg" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/layers/python/layers/regularizers.py#L141-L167
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
caffe2/python/muji.py
python
OnGPU
(gpu_id)
return device_option
A utility function that returns a device option protobuf of the specified gpu id.
A utility function that returns a device option protobuf of the specified gpu id.
[ "A", "utility", "function", "that", "returns", "a", "device", "option", "protobuf", "of", "the", "specified", "gpu", "id", "." ]
def OnGPU(gpu_id): """A utility function that returns a device option protobuf of the specified gpu id. """ device_option = caffe2_pb2.DeviceOption() device_option.device_type = workspace.GpuDeviceType device_option.device_id = gpu_id return device_option
[ "def", "OnGPU", "(", "gpu_id", ")", ":", "device_option", "=", "caffe2_pb2", ".", "DeviceOption", "(", ")", "device_option", ".", "device_type", "=", "workspace", ".", "GpuDeviceType", "device_option", ".", "device_id", "=", "gpu_id", "return", "device_option" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/caffe2/python/muji.py#L23-L30
MythTV/mythtv
d282a209cb8be85d036f85a62a8ec971b67d45f4
mythtv/contrib/imports/mirobridge/mirobridge/mirobridge_interpreter_4_0_2.py
python
MiroInterpreter.do_mythtv_item_remove
(self, args)
Removes an item from Miro by file name or Channel and title
Removes an item from Miro by file name or Channel and title
[ "Removes", "an", "item", "from", "Miro", "by", "file", "name", "or", "Channel", "and", "title" ]
def do_mythtv_item_remove(self, args): """Removes an item from Miro by file name or Channel and title""" for it in item.Item.downloaded_view(): if isinstance(args, list): if not args[0] or not args[1]: continue if filter(self.is_not_punct_char, it.get_channel_title(True).lower()) == filter(self.is_not_punct_char, args[0].lower()) and (filter(self.is_not_punct_char, it.get_title().lower())).startswith(filter(self.is_not_punct_char, args[1].lower())): break elif args: if filter(self.is_not_punct_char, it.get_filename().lower()) == filter(self.is_not_punct_char, args.lower()): break else: logging.info(u"No item named %s" % args) return if it.is_downloaded(): if self.simulation: logging.info(u"Simulation: Item (%s - %s) has been removed from Miro" % (it.get_channel_title(True), it.get_title())) else: it.expire() self.statistics[u'Miro_videos_deleted']+=1 logging.info(u'%s has been removed from Miro' % it.get_title()) else: logging.info(u'%s is not downloaded' % it.get_title())
[ "def", "do_mythtv_item_remove", "(", "self", ",", "args", ")", ":", "for", "it", "in", "item", ".", "Item", ".", "downloaded_view", "(", ")", ":", "if", "isinstance", "(", "args", ",", "list", ")", ":", "if", "not", "args", "[", "0", "]", "or", "not", "args", "[", "1", "]", ":", "continue", "if", "filter", "(", "self", ".", "is_not_punct_char", ",", "it", ".", "get_channel_title", "(", "True", ")", ".", "lower", "(", ")", ")", "==", "filter", "(", "self", ".", "is_not_punct_char", ",", "args", "[", "0", "]", ".", "lower", "(", ")", ")", "and", "(", "filter", "(", "self", ".", "is_not_punct_char", ",", "it", ".", "get_title", "(", ")", ".", "lower", "(", ")", ")", ")", ".", "startswith", "(", "filter", "(", "self", ".", "is_not_punct_char", ",", "args", "[", "1", "]", ".", "lower", "(", ")", ")", ")", ":", "break", "elif", "args", ":", "if", "filter", "(", "self", ".", "is_not_punct_char", ",", "it", ".", "get_filename", "(", ")", ".", "lower", "(", ")", ")", "==", "filter", "(", "self", ".", "is_not_punct_char", ",", "args", ".", "lower", "(", ")", ")", ":", "break", "else", ":", "logging", ".", "info", "(", "u\"No item named %s\"", "%", "args", ")", "return", "if", "it", ".", "is_downloaded", "(", ")", ":", "if", "self", ".", "simulation", ":", "logging", ".", "info", "(", "u\"Simulation: Item (%s - %s) has been removed from Miro\"", "%", "(", "it", ".", "get_channel_title", "(", "True", ")", ",", "it", ".", "get_title", "(", ")", ")", ")", "else", ":", "it", ".", "expire", "(", ")", "self", ".", "statistics", "[", "u'Miro_videos_deleted'", "]", "+=", "1", "logging", ".", "info", "(", "u'%s has been removed from Miro'", "%", "it", ".", "get_title", "(", ")", ")", "else", ":", "logging", ".", "info", "(", "u'%s is not downloaded'", "%", "it", ".", "get_title", "(", ")", ")" ]
https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/contrib/imports/mirobridge/mirobridge/mirobridge_interpreter_4_0_2.py#L372-L394
metashell/metashell
f4177e4854ea00c8dbc722cadab26ef413d798ea
3rd/templight/clang/tools/scan-build-py/libscanbuild/intercept.py
python
entry_hash
(entry)
return '<>'.join([filename, directory, command])
Implement unique hash method for compilation database entries.
Implement unique hash method for compilation database entries.
[ "Implement", "unique", "hash", "method", "for", "compilation", "database", "entries", "." ]
def entry_hash(entry): """ Implement unique hash method for compilation database entries. """ # For faster lookup in set filename is reverted filename = entry['file'][::-1] # For faster lookup in set directory is reverted directory = entry['directory'][::-1] # On OS X the 'cc' and 'c++' compilers are wrappers for # 'clang' therefore both call would be logged. To avoid # this the hash does not contain the first word of the # command. command = ' '.join(decode(entry['command'])[1:]) return '<>'.join([filename, directory, command])
[ "def", "entry_hash", "(", "entry", ")", ":", "# For faster lookup in set filename is reverted", "filename", "=", "entry", "[", "'file'", "]", "[", ":", ":", "-", "1", "]", "# For faster lookup in set directory is reverted", "directory", "=", "entry", "[", "'directory'", "]", "[", ":", ":", "-", "1", "]", "# On OS X the 'cc' and 'c++' compilers are wrappers for", "# 'clang' therefore both call would be logged. To avoid", "# this the hash does not contain the first word of the", "# command.", "command", "=", "' '", ".", "join", "(", "decode", "(", "entry", "[", "'command'", "]", ")", "[", "1", ":", "]", ")", "return", "'<>'", ".", "join", "(", "[", "filename", ",", "directory", ",", "command", "]", ")" ]
https://github.com/metashell/metashell/blob/f4177e4854ea00c8dbc722cadab26ef413d798ea/3rd/templight/clang/tools/scan-build-py/libscanbuild/intercept.py#L249-L262
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cuda/api.py
python
pinned
(*arylist)
A context manager for temporary pinning a sequence of host ndarrays.
A context manager for temporary pinning a sequence of host ndarrays.
[ "A", "context", "manager", "for", "temporary", "pinning", "a", "sequence", "of", "host", "ndarrays", "." ]
def pinned(*arylist): """A context manager for temporary pinning a sequence of host ndarrays. """ pmlist = [] for ary in arylist: pm = current_context().mempin(ary, driver.host_pointer(ary), driver.host_memory_size(ary), mapped=False) pmlist.append(pm) yield
[ "def", "pinned", "(", "*", "arylist", ")", ":", "pmlist", "=", "[", "]", "for", "ary", "in", "arylist", ":", "pm", "=", "current_context", "(", ")", ".", "mempin", "(", "ary", ",", "driver", ".", "host_pointer", "(", "ary", ")", ",", "driver", ".", "host_memory_size", "(", "ary", ")", ",", "mapped", "=", "False", ")", "pmlist", ".", "append", "(", "pm", ")", "yield" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cuda/api.py#L276-L285
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/ultimatelistctrl.py
python
UltimateListItemData.SetBackgroundColour
(self, colour)
Sets the background colour for the item. :param `colour`: an instance of :class:`Colour`.
Sets the background colour for the item.
[ "Sets", "the", "background", "colour", "for", "the", "item", "." ]
def SetBackgroundColour(self, colour): """ Sets the background colour for the item. :param `colour`: an instance of :class:`Colour`. """ if colour == wx.NullColour: self._hasBackColour = False del self._backColour return self._hasBackColour = True self._backColour = colour
[ "def", "SetBackgroundColour", "(", "self", ",", "colour", ")", ":", "if", "colour", "==", "wx", ".", "NullColour", ":", "self", ".", "_hasBackColour", "=", "False", "del", "self", ".", "_backColour", "return", "self", ".", "_hasBackColour", "=", "True", "self", ".", "_backColour", "=", "colour" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L2667-L2680
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/feature_extraction/text.py
python
strip_accents_unicode
(s)
Transform accentuated unicode symbols into their simple counterpart Warning: the python-level loop and join operations make this implementation 20 times slower than the strip_accents_ascii basic normalization. See also -------- strip_accents_ascii Remove accentuated char for any unicode symbol that has a direct ASCII equivalent.
Transform accentuated unicode symbols into their simple counterpart
[ "Transform", "accentuated", "unicode", "symbols", "into", "their", "simple", "counterpart" ]
def strip_accents_unicode(s): """Transform accentuated unicode symbols into their simple counterpart Warning: the python-level loop and join operations make this implementation 20 times slower than the strip_accents_ascii basic normalization. See also -------- strip_accents_ascii Remove accentuated char for any unicode symbol that has a direct ASCII equivalent. """ normalized = unicodedata.normalize('NFKD', s) if normalized == s: return s else: return ''.join([c for c in normalized if not unicodedata.combining(c)])
[ "def", "strip_accents_unicode", "(", "s", ")", ":", "normalized", "=", "unicodedata", ".", "normalize", "(", "'NFKD'", ",", "s", ")", "if", "normalized", "==", "s", ":", "return", "s", "else", ":", "return", "''", ".", "join", "(", "[", "c", "for", "c", "in", "normalized", "if", "not", "unicodedata", ".", "combining", "(", "c", ")", "]", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/feature_extraction/text.py#L45-L62