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
ablab/quast
5f6709528129a6ad266a6b24ef3f40b88f0fe04b
quast_libs/site_packages/simplejson/encoder.py
python
encode_basestring
(s)
return u'"' + ESCAPE.sub(replace, s) + u'"'
Return a JSON representation of a Python string
Return a JSON representation of a Python string
[ "Return", "a", "JSON", "representation", "of", "a", "Python", "string" ]
def encode_basestring(s): """Return a JSON representation of a Python string """ if isinstance(s, str) and HAS_UTF8.search(s) is not None: s = s.decode('utf-8') def replace(match): return ESCAPE_DCT[match.group(0)] return u'"' + ESCAPE.sub(replace, s) + u'"'
[ "def", "encode_basestring", "(", "s", ")", ":", "if", "isinstance", "(", "s", ",", "str", ")", "and", "HAS_UTF8", ".", "search", "(", "s", ")", "is", "not", "None", ":", "s", "=", "s", ".", "decode", "(", "'utf-8'", ")", "def", "replace", "(", "m...
https://github.com/ablab/quast/blob/5f6709528129a6ad266a6b24ef3f40b88f0fe04b/quast_libs/site_packages/simplejson/encoder.py#L36-L44
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/tools/gyp/pylib/gyp/generator/ninja.py
python
NinjaWriter.GetPostbuildCommand
(self, spec, output, output_binary, is_command_start)
Returns a shell command that runs all the postbuilds, and removes |output| if any of them fails. If |is_command_start| is False, then the returned string will start with ' && '.
Returns a shell command that runs all the postbuilds, and removes |output| if any of them fails. If |is_command_start| is False, then the returned string will start with ' && '.
[ "Returns", "a", "shell", "command", "that", "runs", "all", "the", "postbuilds", "and", "removes", "|output|", "if", "any", "of", "them", "fails", ".", "If", "|is_command_start|", "is", "False", "then", "the", "returned", "string", "will", "start", "with", "&...
def GetPostbuildCommand(self, spec, output, output_binary, is_command_start): """Returns a shell command that runs all the postbuilds, and removes |output| if any of them fails. If |is_command_start| is False, then the returned string will start with ' && '.""" if not self.xcode_settings or spec['type'] == 'none' or not output: return '' output = QuoteShellArgument(output, self.flavor) postbuilds = gyp.xcode_emulation.GetSpecPostbuildCommands(spec, quiet=True) if output_binary is not None: postbuilds = self.xcode_settings.AddImplicitPostbuilds( self.config_name, os.path.normpath(os.path.join(self.base_to_build, output)), QuoteShellArgument( os.path.normpath(os.path.join(self.base_to_build, output_binary)), self.flavor), postbuilds, quiet=True) if not postbuilds: return '' # Postbuilds expect to be run in the gyp file's directory, so insert an # implicit postbuild to cd to there. postbuilds.insert(0, gyp.common.EncodePOSIXShellList( ['cd', self.build_to_base])) env = self.ComputeExportEnvString(self.GetSortedXcodePostbuildEnv()) # G will be non-null if any postbuild fails. Run all postbuilds in a # subshell. commands = env + ' (' + \ ' && '.join([ninja_syntax.escape(command) for command in postbuilds]) command_string = (commands + '); G=$$?; ' # Remove the final output if any postbuild failed. '((exit $$G) || rm -rf %s) ' % output + '&& exit $$G)') if is_command_start: return '(' + command_string + ' && ' else: return '$ && (' + command_string
[ "def", "GetPostbuildCommand", "(", "self", ",", "spec", ",", "output", ",", "output_binary", ",", "is_command_start", ")", ":", "if", "not", "self", ".", "xcode_settings", "or", "spec", "[", "'type'", "]", "==", "'none'", "or", "not", "output", ":", "retur...
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/gyp/pylib/gyp/generator/ninja.py#L1436-L1470
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/aui/framemanager.py
python
AuiManager.SetFrame
(self, managed_window)
return self.SetManagedWindow(managed_window)
Called to specify the frame or window which is to be managed by :class:`AuiManager`. Frame management is not restricted to just frames. Child windows or custom controls are also allowed. :param Window `managed_window`: specifies the window which should be managed by the AUI manager. .. deprecated:: 0.6 This method is now deprecated, use :meth:`SetManagedWindow` instead.
Called to specify the frame or window which is to be managed by :class:`AuiManager`. Frame management is not restricted to just frames. Child windows or custom controls are also allowed.
[ "Called", "to", "specify", "the", "frame", "or", "window", "which", "is", "to", "be", "managed", "by", ":", "class", ":", "AuiManager", ".", "Frame", "management", "is", "not", "restricted", "to", "just", "frames", ".", "Child", "windows", "or", "custom", ...
def SetFrame(self, managed_window): """ Called to specify the frame or window which is to be managed by :class:`AuiManager`. Frame management is not restricted to just frames. Child windows or custom controls are also allowed. :param Window `managed_window`: specifies the window which should be managed by the AUI manager. .. deprecated:: 0.6 This method is now deprecated, use :meth:`SetManagedWindow` instead. """ DeprecationWarning("This method is deprecated, use SetManagedWindow instead.") return self.SetManagedWindow(managed_window)
[ "def", "SetFrame", "(", "self", ",", "managed_window", ")", ":", "DeprecationWarning", "(", "\"This method is deprecated, use SetManagedWindow instead.\"", ")", "return", "self", ".", "SetManagedWindow", "(", "managed_window", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/framemanager.py#L4502-L4516
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/aui.py
python
AuiTabContainer.DoShowHide
(*args, **kwargs)
return _aui.AuiTabContainer_DoShowHide(*args, **kwargs)
DoShowHide(self)
DoShowHide(self)
[ "DoShowHide", "(", "self", ")" ]
def DoShowHide(*args, **kwargs): """DoShowHide(self)""" return _aui.AuiTabContainer_DoShowHide(*args, **kwargs)
[ "def", "DoShowHide", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "AuiTabContainer_DoShowHide", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/aui.py#L1224-L1226
liulei01/DRBox
b5c76e033c555c9009590ab384e1f7bd3c66c237
scripts/cpp_lint.py
python
_IncludeState.CheckNextIncludeOrder
(self, header_type)
return ''
Returns a non-empty error message if the next header is out of order. This function also updates the internal state to be ready to check the next include. Args: header_type: One of the _XXX_HEADER constants defined above. Returns: The empty string if the header is in the right order, or an error message describing what's wrong.
Returns a non-empty error message if the next header is out of order.
[ "Returns", "a", "non", "-", "empty", "error", "message", "if", "the", "next", "header", "is", "out", "of", "order", "." ]
def CheckNextIncludeOrder(self, header_type): """Returns a non-empty error message if the next header is out of order. This function also updates the internal state to be ready to check the next include. Args: header_type: One of the _XXX_HEADER constants defined above. Returns: The empty string if the header is in the right order, or an error message describing what's wrong. """ error_message = ('Found %s after %s' % (self._TYPE_NAMES[header_type], self._SECTION_NAMES[self._section])) last_section = self._section if header_type == _C_SYS_HEADER: if self._section <= self._C_SECTION: self._section = self._C_SECTION else: self._last_header = '' return error_message elif header_type == _CPP_SYS_HEADER: if self._section <= self._CPP_SECTION: self._section = self._CPP_SECTION else: self._last_header = '' return error_message elif header_type == _LIKELY_MY_HEADER: if self._section <= self._MY_H_SECTION: self._section = self._MY_H_SECTION else: self._section = self._OTHER_H_SECTION elif header_type == _POSSIBLE_MY_HEADER: if self._section <= self._MY_H_SECTION: self._section = self._MY_H_SECTION else: # This will always be the fallback because we're not sure # enough that the header is associated with this file. self._section = self._OTHER_H_SECTION else: assert header_type == _OTHER_HEADER self._section = self._OTHER_H_SECTION if last_section != self._section: self._last_header = '' return ''
[ "def", "CheckNextIncludeOrder", "(", "self", ",", "header_type", ")", ":", "error_message", "=", "(", "'Found %s after %s'", "%", "(", "self", ".", "_TYPE_NAMES", "[", "header_type", "]", ",", "self", ".", "_SECTION_NAMES", "[", "self", ".", "_section", "]", ...
https://github.com/liulei01/DRBox/blob/b5c76e033c555c9009590ab384e1f7bd3c66c237/scripts/cpp_lint.py#L633-L684
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Path/PathScripts/PathPocketBase.py
python
ObjectPocket.areaOpAreaParams
(self, obj, isHole)
return params
areaOpAreaParams(obj, isHole) ... return dictionary with pocket's area parameters
areaOpAreaParams(obj, isHole) ... return dictionary with pocket's area parameters
[ "areaOpAreaParams", "(", "obj", "isHole", ")", "...", "return", "dictionary", "with", "pocket", "s", "area", "parameters" ]
def areaOpAreaParams(self, obj, isHole): """areaOpAreaParams(obj, isHole) ... return dictionary with pocket's area parameters""" params = {} params["Fill"] = 0 params["Coplanar"] = 0 params["PocketMode"] = 1 params["SectionCount"] = -1 params["Angle"] = obj.ZigZagAngle params["FromCenter"] = obj.StartAt == "Center" params["PocketStepover"] = (self.radius * 2) * (float(obj.StepOver) / 100) extraOffset = obj.ExtraOffset.Value if self.pocketInvertExtraOffset(): extraOffset = 0 - extraOffset params["PocketExtraOffset"] = extraOffset params["ToolRadius"] = self.radius Pattern = [ "ZigZag", "Offset", "Spiral", "ZigZagOffset", "Line", "Grid", "Triangle", ] params["PocketMode"] = Pattern.index(obj.OffsetPattern) + 1 if obj.SplitArcs: params["Explode"] = True params["FitArcs"] = False return params
[ "def", "areaOpAreaParams", "(", "self", ",", "obj", ",", "isHole", ")", ":", "params", "=", "{", "}", "params", "[", "\"Fill\"", "]", "=", "0", "params", "[", "\"Coplanar\"", "]", "=", "0", "params", "[", "\"PocketMode\"", "]", "=", "1", "params", "[...
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathPocketBase.py#L193-L224
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/richtext.py
python
RichTextObject.HitTest
(*args, **kwargs)
return _richtext.RichTextObject_HitTest(*args, **kwargs)
HitTest(self, DC dc, RichTextDrawingContext context, Point pt, long OUTPUT, RichTextObject obj, RichTextObject contextObj, int flags=0) -> int
HitTest(self, DC dc, RichTextDrawingContext context, Point pt, long OUTPUT, RichTextObject obj, RichTextObject contextObj, int flags=0) -> int
[ "HitTest", "(", "self", "DC", "dc", "RichTextDrawingContext", "context", "Point", "pt", "long", "OUTPUT", "RichTextObject", "obj", "RichTextObject", "contextObj", "int", "flags", "=", "0", ")", "-", ">", "int" ]
def HitTest(*args, **kwargs): """ HitTest(self, DC dc, RichTextDrawingContext context, Point pt, long OUTPUT, RichTextObject obj, RichTextObject contextObj, int flags=0) -> int """ return _richtext.RichTextObject_HitTest(*args, **kwargs)
[ "def", "HitTest", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextObject_HitTest", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/richtext.py#L1179-L1185
funnyzhou/Adaptive_Feeding
9c78182331d8c0ea28de47226e805776c638d46f
lib/pycocotools/cocoeval.py
python
COCOeval.evaluate
(self)
Run per image evaluation on given images and store results (a list of dict) in self.evalImgs :return: None
Run per image evaluation on given images and store results (a list of dict) in self.evalImgs :return: None
[ "Run", "per", "image", "evaluation", "on", "given", "images", "and", "store", "results", "(", "a", "list", "of", "dict", ")", "in", "self", ".", "evalImgs", ":", "return", ":", "None" ]
def evaluate(self): ''' Run per image evaluation on given images and store results (a list of dict) in self.evalImgs :return: None ''' tic = time.time() print 'Running per image evaluation... ' p = self.params p.imgIds = list(np.unique(p.imgIds)) if p.useCats: p.catIds = list(np.unique(p.catIds)) p.maxDets = sorted(p.maxDets) self.params=p self._prepare() # loop through images, area range, max detection number catIds = p.catIds if p.useCats else [-1] computeIoU = self.computeIoU self.ious = {(imgId, catId): computeIoU(imgId, catId) \ for imgId in p.imgIds for catId in catIds} evaluateImg = self.evaluateImg maxDet = p.maxDets[-1] self.evalImgs = [evaluateImg(imgId, catId, areaRng, maxDet) for catId in catIds for areaRng in p.areaRng for imgId in p.imgIds ] self._paramsEval = copy.deepcopy(self.params) toc = time.time() print 'DONE (t=%0.2fs).'%(toc-tic)
[ "def", "evaluate", "(", "self", ")", ":", "tic", "=", "time", ".", "time", "(", ")", "print", "'Running per image evaluation... '", "p", "=", "self", ".", "params", "p", ".", "imgIds", "=", "list", "(", "np", ".", "unique", "(", "p", ".", "imgIds"...
https://github.com/funnyzhou/Adaptive_Feeding/blob/9c78182331d8c0ea28de47226e805776c638d46f/lib/pycocotools/cocoeval.py#L129-L161
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/collections.py
python
OrderedDict.viewvalues
(self)
return ValuesView(self)
od.viewvalues() -> an object providing a view on od's values
od.viewvalues() -> an object providing a view on od's values
[ "od", ".", "viewvalues", "()", "-", ">", "an", "object", "providing", "a", "view", "on", "od", "s", "values" ]
def viewvalues(self): "od.viewvalues() -> an object providing a view on od's values" return ValuesView(self)
[ "def", "viewvalues", "(", "self", ")", ":", "return", "ValuesView", "(", "self", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/collections.py#L238-L240
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
Image.SetOption
(*args, **kwargs)
return _core_.Image_SetOption(*args, **kwargs)
SetOption(self, String name, String value) Sets an image handler defined option. For example, when saving as a JPEG file, the option ``wx.IMAGE_OPTION_QUALITY`` is used, which is a number between 0 and 100 (0 is terrible, 100 is very good).
SetOption(self, String name, String value)
[ "SetOption", "(", "self", "String", "name", "String", "value", ")" ]
def SetOption(*args, **kwargs): """ SetOption(self, String name, String value) Sets an image handler defined option. For example, when saving as a JPEG file, the option ``wx.IMAGE_OPTION_QUALITY`` is used, which is a number between 0 and 100 (0 is terrible, 100 is very good). """ return _core_.Image_SetOption(*args, **kwargs)
[ "def", "SetOption", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Image_SetOption", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L3562-L3570
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/dtypes/inference.py
python
is_dict_like
(obj)
return ( all(hasattr(obj, attr) for attr in dict_like_attrs) # [GH 25196] exclude classes and not isinstance(obj, type) )
Check if the object is dict-like. Parameters ---------- obj : The object to check Returns ------- is_dict_like : bool Whether `obj` has dict-like properties. Examples -------- >>> is_dict_like({1: 2}) True >>> is_dict_like([1, 2, 3]) False >>> is_dict_like(dict) False >>> is_dict_like(dict()) True
Check if the object is dict-like.
[ "Check", "if", "the", "object", "is", "dict", "-", "like", "." ]
def is_dict_like(obj) -> bool: """ Check if the object is dict-like. Parameters ---------- obj : The object to check Returns ------- is_dict_like : bool Whether `obj` has dict-like properties. Examples -------- >>> is_dict_like({1: 2}) True >>> is_dict_like([1, 2, 3]) False >>> is_dict_like(dict) False >>> is_dict_like(dict()) True """ dict_like_attrs = ("__getitem__", "keys", "__contains__") return ( all(hasattr(obj, attr) for attr in dict_like_attrs) # [GH 25196] exclude classes and not isinstance(obj, type) )
[ "def", "is_dict_like", "(", "obj", ")", "->", "bool", ":", "dict_like_attrs", "=", "(", "\"__getitem__\"", ",", "\"keys\"", ",", "\"__contains__\"", ")", "return", "(", "all", "(", "hasattr", "(", "obj", ",", "attr", ")", "for", "attr", "in", "dict_like_at...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/dtypes/inference.py#L299-L328
google/skia
82d65d0487bd72f5f7332d002429ec2dc61d2463
infra/bots/assets/bazel/create.py
python
create_asset
(target_dir)
Create the asset.
Create the asset.
[ "Create", "the", "asset", "." ]
def create_asset(target_dir): """Create the asset.""" with utils.tmp_dir(): subprocess.call(['wget', URL]) subprocess.call(['sh', INSTALLER_SCRIPT, '--prefix=' + target_dir])
[ "def", "create_asset", "(", "target_dir", ")", ":", "with", "utils", ".", "tmp_dir", "(", ")", ":", "subprocess", ".", "call", "(", "[", "'wget'", ",", "URL", "]", ")", "subprocess", ".", "call", "(", "[", "'sh'", ",", "INSTALLER_SCRIPT", ",", "'--pref...
https://github.com/google/skia/blob/82d65d0487bd72f5f7332d002429ec2dc61d2463/infra/bots/assets/bazel/create.py#L25-L29
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
configs/learning_gem5/part1/caches.py
python
L1Cache.connectBus
(self, bus)
Connect this cache to a memory-side bus
Connect this cache to a memory-side bus
[ "Connect", "this", "cache", "to", "a", "memory", "-", "side", "bus" ]
def connectBus(self, bus): """Connect this cache to a memory-side bus""" self.mem_side = bus.cpu_side_ports
[ "def", "connectBus", "(", "self", ",", "bus", ")", ":", "self", ".", "mem_side", "=", "bus", ".", "cpu_side_ports" ]
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/configs/learning_gem5/part1/caches.py#L60-L62
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/lib2to3/pgen2/parse.py
python
Parser.setup
(self, start=None)
Prepare for parsing. This *must* be called before starting to parse. The optional argument is an alternative start symbol; it defaults to the grammar's start symbol. You can use a Parser instance to parse any number of programs; each time you call setup() the parser is reset to an initial state determined by the (implicit or explicit) start symbol.
Prepare for parsing.
[ "Prepare", "for", "parsing", "." ]
def setup(self, start=None): """Prepare for parsing. This *must* be called before starting to parse. The optional argument is an alternative start symbol; it defaults to the grammar's start symbol. You can use a Parser instance to parse any number of programs; each time you call setup() the parser is reset to an initial state determined by the (implicit or explicit) start symbol. """ if start is None: start = self.grammar.start # Each stack entry is a tuple: (dfa, state, node). # A node is a tuple: (type, value, context, children), # where children is a list of nodes or None, and context may be None. newnode = (start, None, None, []) stackentry = (self.grammar.dfas[start], 0, newnode) self.stack = [stackentry] self.rootnode = None self.used_names = set()
[ "def", "setup", "(", "self", ",", "start", "=", "None", ")", ":", "if", "start", "is", "None", ":", "start", "=", "self", ".", "grammar", ".", "start", "# Each stack entry is a tuple: (dfa, state, node).", "# A node is a tuple: (type, value, context, children),", "# w...
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/lib2to3/pgen2/parse.py#L89-L111
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/op_callbacks.py
python
invoke_op_callbacks
(op_type, inputs, attrs, outputs, op_name=None, graph=None)
r"""Invoke the callbacks that exist in the current scope (if any). If no callbacks are present in the current scope, this method returns immediately. Args: op_type: Type of the operation (e.g., "MatMul"). inputs: Input tensors to the op. These are `EagerTensor`s in the case of eager execution of ops or `FuncGraph`s, and are non-eager `Tensor`s in the case of graph construction. attrs: Attributes of the op, as `tuple` of alternating keys and values. outputs: Output tensors from the op. These are `EagerTensor`s in the case of eager execution and are non-eager `Tensor`s in the case of graph construction. op_name: Name of the op. Applicable if and only if this method is invoked due to the graph construction of an op or the eager execution of of a `FuncGraph`. graph: The graph involved (if any). - In the case if the eager execution of an op or FuncGraph, this is `None`. - In the case of the graph construction of an op, this is the `tf.Graph` object being built. Returns: `None`, or a `list` or `tuple` of output tenors that will override the original (input) `outputs`.
r"""Invoke the callbacks that exist in the current scope (if any).
[ "r", "Invoke", "the", "callbacks", "that", "exist", "in", "the", "current", "scope", "(", "if", "any", ")", "." ]
def invoke_op_callbacks(op_type, inputs, attrs, outputs, op_name=None, graph=None): r"""Invoke the callbacks that exist in the current scope (if any). If no callbacks are present in the current scope, this method returns immediately. Args: op_type: Type of the operation (e.g., "MatMul"). inputs: Input tensors to the op. These are `EagerTensor`s in the case of eager execution of ops or `FuncGraph`s, and are non-eager `Tensor`s in the case of graph construction. attrs: Attributes of the op, as `tuple` of alternating keys and values. outputs: Output tensors from the op. These are `EagerTensor`s in the case of eager execution and are non-eager `Tensor`s in the case of graph construction. op_name: Name of the op. Applicable if and only if this method is invoked due to the graph construction of an op or the eager execution of of a `FuncGraph`. graph: The graph involved (if any). - In the case if the eager execution of an op or FuncGraph, this is `None`. - In the case of the graph construction of an op, this is the `tf.Graph` object being built. Returns: `None`, or a `list` or `tuple` of output tenors that will override the original (input) `outputs`. """ if _state.callback_stack: # Guards against stack overflow that can result from recursive invocation # due to op constructions inside client-supplied op callbacks. _state.invoking_callbacks = True try: if isinstance(attrs, dict): attrs_list = [] for key in attrs: attrs_list.append(key) attrs_list.append(attrs[key]) attrs_tuple = tuple(attrs_list) else: attrs_tuple = attrs new_outputs = outputs for callback in reversed(_state.callback_stack): new_outputs = callback( op_type, inputs, attrs_tuple, new_outputs, op_name=op_name, graph=graph) if new_outputs is not None and len(new_outputs) != len(outputs): raise ValueError( "The op callback returned %s tensors, which does not match the " "original number of outputs of op %s (%d)." % (len(new_outputs), op_name, len(outputs))) return new_outputs finally: _state.invoking_callbacks = False else: return outputs
[ "def", "invoke_op_callbacks", "(", "op_type", ",", "inputs", ",", "attrs", ",", "outputs", ",", "op_name", "=", "None", ",", "graph", "=", "None", ")", ":", "if", "_state", ".", "callback_stack", ":", "# Guards against stack overflow that can result from recursive i...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/op_callbacks.py#L156-L221
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/html.py
python
HtmlCell.GetFirstTerminal
(*args, **kwargs)
return _html.HtmlCell_GetFirstTerminal(*args, **kwargs)
GetFirstTerminal(self) -> HtmlCell
GetFirstTerminal(self) -> HtmlCell
[ "GetFirstTerminal", "(", "self", ")", "-", ">", "HtmlCell" ]
def GetFirstTerminal(*args, **kwargs): """GetFirstTerminal(self) -> HtmlCell""" return _html.HtmlCell_GetFirstTerminal(*args, **kwargs)
[ "def", "GetFirstTerminal", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_html", ".", "HtmlCell_GetFirstTerminal", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/html.py#L726-L728
generalized-intelligence/GAAS
29ab17d3e8a4ba18edef3a57c36d8db6329fac73
algorithms/src/SystemManagement/json_request_response_lib/src/third_party/nlohmann_json/third_party/cpplint/cpplint.py
python
FindCheckMacro
(line)
return (None, -1)
Find a replaceable CHECK-like macro. Args: line: line to search on. Returns: (macro name, start position), or (None, -1) if no replaceable macro is found.
Find a replaceable CHECK-like macro.
[ "Find", "a", "replaceable", "CHECK", "-", "like", "macro", "." ]
def FindCheckMacro(line): """Find a replaceable CHECK-like macro. Args: line: line to search on. Returns: (macro name, start position), or (None, -1) if no replaceable macro is found. """ for macro in _CHECK_MACROS: i = line.find(macro) if i >= 0: # Find opening parenthesis. Do a regular expression match here # to make sure that we are matching the expected CHECK macro, as # opposed to some other macro that happens to contain the CHECK # substring. matched = Match(r'^(.*\b' + macro + r'\s*)\(', line) if not matched: continue return (macro, len(matched.group(1))) return (None, -1)
[ "def", "FindCheckMacro", "(", "line", ")", ":", "for", "macro", "in", "_CHECK_MACROS", ":", "i", "=", "line", ".", "find", "(", "macro", ")", "if", "i", ">=", "0", ":", "# Find opening parenthesis. Do a regular expression match here", "# to make sure that we are ma...
https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/algorithms/src/SystemManagement/json_request_response_lib/src/third_party/nlohmann_json/third_party/cpplint/cpplint.py#L4332-L4352
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/ops/rnn.py
python
bidirectional_rnn
(cell_fw, cell_bw, inputs, initial_state_fw=None, initial_state_bw=None, dtype=None, sequence_length=None, scope=None)
return (outputs, output_state_fw, output_state_bw)
Creates a bidirectional recurrent neural network. Similar to the unidirectional case above (rnn) but takes input and builds independent forward and backward RNNs with the final forward and backward outputs depth-concatenated, such that the output will have the format [time][batch][cell_fw.output_size + cell_bw.output_size]. The input_size of forward and backward cell must match. The initial state for both directions is zero by default (but can be set optionally) and no intermediate states are ever returned -- the network is fully unrolled for the given (passed in) length(s) of the sequence(s) or completely unrolled if length(s) is not given. Args: cell_fw: An instance of RNNCell, to be used for forward direction. cell_bw: An instance of RNNCell, to be used for backward direction. inputs: A length T list of inputs, each a tensor of shape [batch_size, input_size], or a nested tuple of such elements. initial_state_fw: (optional) An initial state for the forward RNN. This must be a tensor of appropriate type and shape `[batch_size x cell_fw.state_size]`. If `cell_fw.state_size` is a tuple, this should be a tuple of tensors having shapes `[batch_size, s] for s in cell_fw.state_size`. initial_state_bw: (optional) Same as for `initial_state_fw`, but using the corresponding properties of `cell_bw`. dtype: (optional) The data type for the initial state. Required if either of the initial states are not provided. sequence_length: (optional) An int32/int64 vector, size `[batch_size]`, containing the actual lengths for each of the sequences. scope: VariableScope for the created subgraph; defaults to "BiRNN" Returns: A tuple (outputs, output_state_fw, output_state_bw) where: outputs is a length `T` list of outputs (one for each input), which are depth-concatenated forward and backward outputs. output_state_fw is the final state of the forward rnn. output_state_bw is the final state of the backward rnn. Raises: TypeError: If `cell_fw` or `cell_bw` is not an instance of `RNNCell`. ValueError: If inputs is None or an empty list.
Creates a bidirectional recurrent neural network.
[ "Creates", "a", "bidirectional", "recurrent", "neural", "network", "." ]
def bidirectional_rnn(cell_fw, cell_bw, inputs, initial_state_fw=None, initial_state_bw=None, dtype=None, sequence_length=None, scope=None): """Creates a bidirectional recurrent neural network. Similar to the unidirectional case above (rnn) but takes input and builds independent forward and backward RNNs with the final forward and backward outputs depth-concatenated, such that the output will have the format [time][batch][cell_fw.output_size + cell_bw.output_size]. The input_size of forward and backward cell must match. The initial state for both directions is zero by default (but can be set optionally) and no intermediate states are ever returned -- the network is fully unrolled for the given (passed in) length(s) of the sequence(s) or completely unrolled if length(s) is not given. Args: cell_fw: An instance of RNNCell, to be used for forward direction. cell_bw: An instance of RNNCell, to be used for backward direction. inputs: A length T list of inputs, each a tensor of shape [batch_size, input_size], or a nested tuple of such elements. initial_state_fw: (optional) An initial state for the forward RNN. This must be a tensor of appropriate type and shape `[batch_size x cell_fw.state_size]`. If `cell_fw.state_size` is a tuple, this should be a tuple of tensors having shapes `[batch_size, s] for s in cell_fw.state_size`. initial_state_bw: (optional) Same as for `initial_state_fw`, but using the corresponding properties of `cell_bw`. dtype: (optional) The data type for the initial state. Required if either of the initial states are not provided. sequence_length: (optional) An int32/int64 vector, size `[batch_size]`, containing the actual lengths for each of the sequences. scope: VariableScope for the created subgraph; defaults to "BiRNN" Returns: A tuple (outputs, output_state_fw, output_state_bw) where: outputs is a length `T` list of outputs (one for each input), which are depth-concatenated forward and backward outputs. output_state_fw is the final state of the forward rnn. output_state_bw is the final state of the backward rnn. Raises: TypeError: If `cell_fw` or `cell_bw` is not an instance of `RNNCell`. ValueError: If inputs is None or an empty list. """ if not isinstance(cell_fw, rnn_cell.RNNCell): raise TypeError("cell_fw must be an instance of RNNCell") if not isinstance(cell_bw, rnn_cell.RNNCell): raise TypeError("cell_bw must be an instance of RNNCell") if not nest.is_sequence(inputs): raise TypeError("inputs must be a sequence") if not inputs: raise ValueError("inputs must not be empty") if scope is None: name = "BiRNN" elif isinstance(scope, six.string_types): name = scope elif isinstance(scope, vs.VariableScope): name = scope.name else: raise TypeError("scope must be a string or an instance of VariableScope") # Forward direction with vs.variable_scope(name + "_FW") as fw_scope: output_fw, output_state_fw = rnn(cell_fw, inputs, initial_state_fw, dtype, sequence_length, scope=fw_scope) # Backward direction with vs.variable_scope(name + "_BW") as bw_scope: reversed_inputs = _reverse_seq(inputs, sequence_length) tmp, output_state_bw = rnn(cell_bw, reversed_inputs, initial_state_bw, dtype, sequence_length, scope=bw_scope) output_bw = _reverse_seq(tmp, sequence_length) # Concat each of the forward/backward outputs flat_output_fw = nest.flatten(output_fw) flat_output_bw = nest.flatten(output_bw) flat_outputs = tuple(array_ops.concat(1, [fw, bw]) for fw, bw in zip(flat_output_fw, flat_output_bw)) outputs = nest.pack_sequence_as(structure=output_fw, flat_sequence=flat_outputs) return (outputs, output_state_fw, output_state_bw)
[ "def", "bidirectional_rnn", "(", "cell_fw", ",", "cell_bw", ",", "inputs", ",", "initial_state_fw", "=", "None", ",", "initial_state_bw", "=", "None", ",", "dtype", "=", "None", ",", "sequence_length", "=", "None", ",", "scope", "=", "None", ")", ":", "if"...
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/rnn.py#L474-L557
apiaryio/snowcrash
b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3
tools/gyp/pylib/gyp/input.py
python
QualifyDependencies
(targets)
Make dependency links fully-qualified relative to the current directory. |targets| is a dict mapping fully-qualified target names to their target dicts. For each target in this dict, keys known to contain dependency links are examined, and any dependencies referenced will be rewritten so that they are fully-qualified and relative to the current directory. All rewritten dependencies are suitable for use as keys to |targets| or a similar dict.
Make dependency links fully-qualified relative to the current directory.
[ "Make", "dependency", "links", "fully", "-", "qualified", "relative", "to", "the", "current", "directory", "." ]
def QualifyDependencies(targets): """Make dependency links fully-qualified relative to the current directory. |targets| is a dict mapping fully-qualified target names to their target dicts. For each target in this dict, keys known to contain dependency links are examined, and any dependencies referenced will be rewritten so that they are fully-qualified and relative to the current directory. All rewritten dependencies are suitable for use as keys to |targets| or a similar dict. """ all_dependency_sections = [dep + op for dep in dependency_sections for op in ('', '!', '/')] for target, target_dict in targets.iteritems(): target_build_file = gyp.common.BuildFile(target) toolset = target_dict['toolset'] for dependency_key in all_dependency_sections: dependencies = target_dict.get(dependency_key, []) for index in xrange(0, len(dependencies)): dep_file, dep_target, dep_toolset = gyp.common.ResolveTarget( target_build_file, dependencies[index], toolset) if not multiple_toolsets: # Ignore toolset specification in the dependency if it is specified. dep_toolset = toolset dependency = gyp.common.QualifiedTarget(dep_file, dep_target, dep_toolset) dependencies[index] = dependency # Make sure anything appearing in a list other than "dependencies" also # appears in the "dependencies" list. if dependency_key != 'dependencies' and \ dependency not in target_dict['dependencies']: raise GypError('Found ' + dependency + ' in ' + dependency_key + ' of ' + target + ', but not in dependencies')
[ "def", "QualifyDependencies", "(", "targets", ")", ":", "all_dependency_sections", "=", "[", "dep", "+", "op", "for", "dep", "in", "dependency_sections", "for", "op", "in", "(", "''", ",", "'!'", ",", "'/'", ")", "]", "for", "target", ",", "target_dict", ...
https://github.com/apiaryio/snowcrash/blob/b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3/tools/gyp/pylib/gyp/input.py#L1358-L1394
google/llvm-propeller
45c226984fe8377ebfb2ad7713c680d652ba678d
clang-tools-extra/clang-include-fixer/find-all-symbols/tool/run-find-all-symbols.py
python
run_find_all_symbols
(args, tmpdir, build_path, queue)
Takes filenames out of queue and runs find-all-symbols on them.
Takes filenames out of queue and runs find-all-symbols on them.
[ "Takes", "filenames", "out", "of", "queue", "and", "runs", "find", "-", "all", "-", "symbols", "on", "them", "." ]
def run_find_all_symbols(args, tmpdir, build_path, queue): """Takes filenames out of queue and runs find-all-symbols on them.""" while True: name = queue.get() invocation = [args.binary, name, '-output-dir='+tmpdir, '-p='+build_path] sys.stdout.write(' '.join(invocation) + '\n') subprocess.call(invocation) queue.task_done()
[ "def", "run_find_all_symbols", "(", "args", ",", "tmpdir", ",", "build_path", ",", "queue", ")", ":", "while", "True", ":", "name", "=", "queue", ".", "get", "(", ")", "invocation", "=", "[", "args", ".", "binary", ",", "name", ",", "'-output-dir='", "...
https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/clang-tools-extra/clang-include-fixer/find-all-symbols/tool/run-find-all-symbols.py#L55-L62
commaai/openpilot
4416c21b1e738ab7d04147c5ae52b5135e0cdb40
pyextra/acados_template/acados_ocp.py
python
AcadosOcpOptions.nlp_solver_tol_comp
(self)
return self.__nlp_solver_tol_comp
NLP solver complementarity tolerance
NLP solver complementarity tolerance
[ "NLP", "solver", "complementarity", "tolerance" ]
def nlp_solver_tol_comp(self): """NLP solver complementarity tolerance""" return self.__nlp_solver_tol_comp
[ "def", "nlp_solver_tol_comp", "(", "self", ")", ":", "return", "self", ".", "__nlp_solver_tol_comp" ]
https://github.com/commaai/openpilot/blob/4416c21b1e738ab7d04147c5ae52b5135e0cdb40/pyextra/acados_template/acados_ocp.py#L2376-L2378
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/contrib/distributions/python/ops/dirichlet.py
python
Dirichlet.entropy
(self, name="entropy")
Entropy of the distribution in nats.
Entropy of the distribution in nats.
[ "Entropy", "of", "the", "distribution", "in", "nats", "." ]
def entropy(self, name="entropy"): """Entropy of the distribution in nats.""" with ops.name_scope(self.name): with ops.op_scope([self._alpha, self._alpha_0], name): alpha = self._alpha alpha_0 = self._alpha_0 entropy = special_math_ops.lbeta(alpha) entropy += (alpha_0 - math_ops.cast( self.event_shape()[0], self.dtype)) * math_ops.digamma( alpha_0) entropy += -math_ops.reduce_sum( (alpha - 1) * math_ops.digamma(alpha), reduction_indices=[-1], keep_dims=False) return entropy
[ "def", "entropy", "(", "self", ",", "name", "=", "\"entropy\"", ")", ":", "with", "ops", ".", "name_scope", "(", "self", ".", "name", ")", ":", "with", "ops", ".", "op_scope", "(", "[", "self", ".", "_alpha", ",", "self", ".", "_alpha_0", "]", ",",...
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/dirichlet.py#L292-L307
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/fx/experimental/fx_acc/acc_tracer.py
python
trace
( mod: nn.Module, sample_inputs: List[torch.Tensor], remove_assertions: bool = True, remove_exceptions: bool = True, use_acc_normalization: bool = True, ast_rewriter_allow_list: Optional[Set[Type[nn.Module]]] = None, leaf_module_list: Optional[Set[Type[nn.Module]]] = None, )
return traced
Performs tracing and arg normalization specialized for accelerator lowering. It first rewrites the AST of the module's methods (and all attr methods recursively) to transform un-tracable parts of the module to make them traceable. It then traces to the functional level so that optimizations and backend accelerator importers have the ability to see and/or change inputs to each op. It then removes assertions and exception wrappers found during symbolic tracing if requested based on remove_assertions and remove_exceptions Dead code is then eliminated, which will e.g. remove any nodes that were only used by assertions or exceptions if they were removed. It then performs normalization on args/kwargs, aligning any arg that can be moved to kwarg to be so, and then making default values explicit. Args: mod (Module): The module to transform and trace. sample_inputs (Tuple[Union[torch.Tensor, List[torch.Tensor]]]): Sample inputs with which to run shape prop. remove_assertions (bool): Whether to remove assertion nodes from the graph after symbolic tracing. remove_exceptions (bool): Whether to remove exception wrapper nodes from the graph after symbolic tracing. use_acc_normalization (bool): Whether to use acc-specific normalization to all acc_ops. ast_rewriter_allow_list (Optional[Set[nn.Module]]): Optional allow list of modules that need AST rewriting. leaf_module_list (Optional[Set[nn.Module]]): Optional leaf module list where modules will not be traced into.
Performs tracing and arg normalization specialized for accelerator lowering.
[ "Performs", "tracing", "and", "arg", "normalization", "specialized", "for", "accelerator", "lowering", "." ]
def trace( mod: nn.Module, sample_inputs: List[torch.Tensor], remove_assertions: bool = True, remove_exceptions: bool = True, use_acc_normalization: bool = True, ast_rewriter_allow_list: Optional[Set[Type[nn.Module]]] = None, leaf_module_list: Optional[Set[Type[nn.Module]]] = None, ) -> torch.fx.GraphModule: """ Performs tracing and arg normalization specialized for accelerator lowering. It first rewrites the AST of the module's methods (and all attr methods recursively) to transform un-tracable parts of the module to make them traceable. It then traces to the functional level so that optimizations and backend accelerator importers have the ability to see and/or change inputs to each op. It then removes assertions and exception wrappers found during symbolic tracing if requested based on remove_assertions and remove_exceptions Dead code is then eliminated, which will e.g. remove any nodes that were only used by assertions or exceptions if they were removed. It then performs normalization on args/kwargs, aligning any arg that can be moved to kwarg to be so, and then making default values explicit. Args: mod (Module): The module to transform and trace. sample_inputs (Tuple[Union[torch.Tensor, List[torch.Tensor]]]): Sample inputs with which to run shape prop. remove_assertions (bool): Whether to remove assertion nodes from the graph after symbolic tracing. remove_exceptions (bool): Whether to remove exception wrapper nodes from the graph after symbolic tracing. use_acc_normalization (bool): Whether to use acc-specific normalization to all acc_ops. ast_rewriter_allow_list (Optional[Set[nn.Module]]): Optional allow list of modules that need AST rewriting. leaf_module_list (Optional[Set[nn.Module]]): Optional leaf module list where modules will not be traced into. """ if mod.training: warnings.warn( "acc_tracer does not support currently support models for training." " Calling eval on model before tracing." ) mod.eval() # Rewrite the module to make it symbolic traceable, and then trace it. rewritten_graph, rewritten_mod = AccRewritingTracer().trace( mod, ast_rewriter_allow_list=ast_rewriter_allow_list, leaf_module_list=leaf_module_list, ) assert isinstance(rewritten_mod, nn.Module) # Note: use the rewritten_mod here as the root. This is necessary because # RewrittenModule includes a new module for the ConditionalExceptionWrapper. traced = torch.fx.GraphModule(rewritten_mod, rewritten_graph) # Now remove all assertions and exceptions if requested. if remove_assertions: _remove_assertions(traced) if remove_exceptions: _remove_exceptions(traced) # Cleanup any dead code from the original module as well as resulting dead # nodes after removing assertions and exceptions. traced.graph.eliminate_dead_code() # Now normalize args/kwargs to make default values visible. Leave args/kwargs as # they were, since all-kwarg normalization is broken, and we don't need it anyway. shape_prop.ShapeProp(traced).propagate(*sample_inputs) traced = NormalizeArgs(traced, normalize_to_only_use_kwargs=False).transform() # Normalize to acc-specialized wrappers for consistency across op naming and # ensuring all kwarg usage. if use_acc_normalization: acc_normalizer.normalize(traced) traced.recompile() return traced
[ "def", "trace", "(", "mod", ":", "nn", ".", "Module", ",", "sample_inputs", ":", "List", "[", "torch", ".", "Tensor", "]", ",", "remove_assertions", ":", "bool", "=", "True", ",", "remove_exceptions", ":", "bool", "=", "True", ",", "use_acc_normalization",...
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/fx/experimental/fx_acc/acc_tracer.py#L369-L462
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/reduction_workflow/find_data.py
python
find_data
(file, instrument='', allow_multiple=False)
Finds a file path for the specified data set, which can either be: - a run number - an absolute path - a file name @param file: file name or part of a file name @param instrument: if supplied, FindNeXus will be tried as a last resort
Finds a file path for the specified data set, which can either be: - a run number - an absolute path - a file name
[ "Finds", "a", "file", "path", "for", "the", "specified", "data", "set", "which", "can", "either", "be", ":", "-", "a", "run", "number", "-", "an", "absolute", "path", "-", "a", "file", "name" ]
def find_data(file, instrument='', allow_multiple=False): """ Finds a file path for the specified data set, which can either be: - a run number - an absolute path - a file name @param file: file name or part of a file name @param instrument: if supplied, FindNeXus will be tried as a last resort """ # First, assume a file name file = str(file).strip() # If we allow multiple files, users may use ; as a separator, # which is incompatible with the FileFinder n_files = 1 if allow_multiple: file=file.replace(';',',') toks = file.split(',') n_files = len(toks) instrument = str(instrument) file_path = FileFinder.getFullPath(file) if os.path.isfile(file_path): return file_path # Second, assume a run number and pass the instrument name as a hint try: # FileFinder doesn't like dashes... instrument=instrument.replace('-','') f = FileFinder.findRuns(instrument+file) if os.path.isfile(f[0]): if allow_multiple: # Mantid returns its own list object type, so make a real list out if it if len(f)==n_files: return [i for i in f] else: return f[0] except: # FileFinder couldn't make sense of the the supplied information pass # Third, assume a run number, without instrument name to take care of list of full paths try: f = FileFinder.findRuns(file) if os.path.isfile(f[0]): if allow_multiple: # Mantid returns its own list object type, so make a real list out if it if len(f)==n_files: return [i for i in f] else: return f[0] except: # FileFinder couldn't make sense of the the supplied information pass # If we didn't find anything, raise an exception Logger('find_data').error("\n\nCould not find a file for %s: check your reduction parameters\n\n" % str(file)) raise RuntimeError("Could not find a file for %s" % str(file))
[ "def", "find_data", "(", "file", ",", "instrument", "=", "''", ",", "allow_multiple", "=", "False", ")", ":", "# First, assume a file name", "file", "=", "str", "(", "file", ")", ".", "strip", "(", ")", "# If we allow multiple files, users may use ; as a separator,"...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/reduction_workflow/find_data.py#L61-L118
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
RecoMET/METFilters/python/GenerateHcalLaserBadRunList.py
python
ReadNewList
(newlist)
return outDict
Read a new list of bad runs from an input file, and creates a new list of output keys for the bad run/events.
Read a new list of bad runs from an input file, and creates a new list of output keys for the bad run/events.
[ "Read", "a", "new", "list", "of", "bad", "runs", "from", "an", "input", "file", "and", "creates", "a", "new", "list", "of", "output", "keys", "for", "the", "bad", "run", "/", "events", "." ]
def ReadNewList(newlist): ''' Read a new list of bad runs from an input file, and creates a new list of output keys for the bad run/events. ''' outlist=[] for i in newlist: temp=string.strip(i) # Input is comma-separated if temp.find(",")>-1: temp=string.split(temp,",") # Input is space-separated else: temp=string.split(temp) # Case 1: new input presented as "run lumi event" list if len(temp)==3: try: run=string.atoi(temp[0]) evt=string.atoi(temp[2]) except: print("Could not parse line '%s'"%i) # Case 2: new input presented as "run event" list elif len(temp)==2: try: run=string.atoi(temp[0]) evt=string.atoi(temp[1]) except: print("Could not parse line '%s'"%i) else: print("Cannot parse line! ('%s')"%i) continue outlist.append(run) outlist.append(evt) outDict=MakePair(outlist) return outDict
[ "def", "ReadNewList", "(", "newlist", ")", ":", "outlist", "=", "[", "]", "for", "i", "in", "newlist", ":", "temp", "=", "string", ".", "strip", "(", "i", ")", "# Input is comma-separated", "if", "temp", ".", "find", "(", "\",\"", ")", ">", "-", "1",...
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/RecoMET/METFilters/python/GenerateHcalLaserBadRunList.py#L27-L61
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/debug/lib/stepper.py
python
_flatten_fetches
(fetches)
return flattened
Flatten list, tuple of fetches, or a single fetch into a list of fetches. Args: fetches: The fetches to flatten: Can be a single Tensor, Op, or a potentially nested list, tuple or dict of such individual fetches. Returns: The fetches flattened to a list.
Flatten list, tuple of fetches, or a single fetch into a list of fetches.
[ "Flatten", "list", "tuple", "of", "fetches", "or", "a", "single", "fetch", "into", "a", "list", "of", "fetches", "." ]
def _flatten_fetches(fetches): """Flatten list, tuple of fetches, or a single fetch into a list of fetches. Args: fetches: The fetches to flatten: Can be a single Tensor, Op, or a potentially nested list, tuple or dict of such individual fetches. Returns: The fetches flattened to a list. """ flattened = [] if isinstance(fetches, (list, tuple)): for fetch in fetches: flattened.extend(_flatten_fetches(fetch)) elif isinstance(fetches, dict): for key in fetches: flattened.extend(_flatten_fetches(fetches[key])) else: flattened.append(fetches) return flattened
[ "def", "_flatten_fetches", "(", "fetches", ")", ":", "flattened", "=", "[", "]", "if", "isinstance", "(", "fetches", ",", "(", "list", ",", "tuple", ")", ")", ":", "for", "fetch", "in", "fetches", ":", "flattened", ".", "extend", "(", "_flatten_fetches",...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/debug/lib/stepper.py#L37-L58
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/gslib/command.py
python
Command._SetUpPerCallerState
(self)
return caller_id
Set up the state for a caller id, corresponding to one Apply call.
Set up the state for a caller id, corresponding to one Apply call.
[ "Set", "up", "the", "state", "for", "a", "caller", "id", "corresponding", "to", "one", "Apply", "call", "." ]
def _SetUpPerCallerState(self): """Set up the state for a caller id, corresponding to one Apply call.""" # pylint: disable=global-variable-undefined,global-variable-not-assigned # These variables are initialized in InitializeMultiprocessingVariables or # InitializeThreadingVariables global global_return_values_map, shared_vars_map, failure_count global caller_id_finished_count, shared_vars_list_map, total_tasks global need_pool_or_done_cond, call_completed_map, class_map global task_queues, caller_id_lock, caller_id_counter # Get a new caller ID. with caller_id_lock: if isinstance(caller_id_counter, int): caller_id_counter += 1 caller_id = caller_id_counter else: caller_id_counter.value += 1 caller_id = caller_id_counter.value # Create a copy of self with an incremented recursive level. This allows # the class to report its level correctly if the function called from it # also needs to call Apply. cls = copy.copy(self) cls.recursive_apply_level += 1 # Thread-safe loggers can't be pickled, so we will remove it here and # recreate it later in the WorkerThread. This is not a problem since any # logger with the same name will be treated as a singleton. cls.logger = None # Likewise, the default API connection can't be pickled, but it is unused # anyway as each thread gets its own API delegator. cls.gsutil_api = None class_map[caller_id] = cls total_tasks[caller_id] = -1 # -1 => the producer hasn't finished yet. call_completed_map[caller_id] = False caller_id_finished_count[caller_id] = 0 global_return_values_map[caller_id] = [] return caller_id
[ "def", "_SetUpPerCallerState", "(", "self", ")", ":", "# pylint: disable=global-variable-undefined,global-variable-not-assigned", "# These variables are initialized in InitializeMultiprocessingVariables or", "# InitializeThreadingVariables", "global", "global_return_values_map", ",", "shared...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/gslib/command.py#L1030-L1068
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py3/IPython/core/inputsplitter.py
python
IPythonInputSplitter.transforms_in_use
(self)
return t + [self.assemble_python_lines] + self.python_line_transforms
Transformers, excluding logical line transformers if we're in a Python line.
Transformers, excluding logical line transformers if we're in a Python line.
[ "Transformers", "excluding", "logical", "line", "transformers", "if", "we", "re", "in", "a", "Python", "line", "." ]
def transforms_in_use(self): """Transformers, excluding logical line transformers if we're in a Python line.""" t = self.physical_line_transforms[:] if not self.within_python_line: t += [self.assemble_logical_lines] + self.logical_line_transforms return t + [self.assemble_python_lines] + self.python_line_transforms
[ "def", "transforms_in_use", "(", "self", ")", ":", "t", "=", "self", ".", "physical_line_transforms", "[", ":", "]", "if", "not", "self", ".", "within_python_line", ":", "t", "+=", "[", "self", ".", "assemble_logical_lines", "]", "+", "self", ".", "logical...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/core/inputsplitter.py#L594-L600
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/nn/probability/distribution/gumbel.py
python
Gumbel.extend_repr
(self)
return str_info
Display instance object as string.
Display instance object as string.
[ "Display", "instance", "object", "as", "string", "." ]
def extend_repr(self): """Display instance object as string.""" if self.is_scalar_batch: str_info = 'loc = {}, scale = {}'.format(self._loc, self._scale) else: str_info = 'batch_shape = {}'.format(self._broadcast_shape) return str_info
[ "def", "extend_repr", "(", "self", ")", ":", "if", "self", ".", "is_scalar_batch", ":", "str_info", "=", "'loc = {}, scale = {}'", ".", "format", "(", "self", ".", "_loc", ",", "self", ".", "_scale", ")", "else", ":", "str_info", "=", "'batch_shape = {}'", ...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/probability/distribution/gumbel.py#L140-L146
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/summary_ops_v2.py
python
create_noop_writer
()
return NoopSummaryWriter()
Returns a summary writer that does nothing. This is useful as a placeholder in code that expects a context manager.
Returns a summary writer that does nothing.
[ "Returns", "a", "summary", "writer", "that", "does", "nothing", "." ]
def create_noop_writer(): """Returns a summary writer that does nothing. This is useful as a placeholder in code that expects a context manager. """ return NoopSummaryWriter()
[ "def", "create_noop_writer", "(", ")", ":", "return", "NoopSummaryWriter", "(", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/summary_ops_v2.py#L494-L499
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/lib/utils.py
python
get_include
()
return d
Return the directory that contains the NumPy \\*.h header files. Extension modules that need to compile against NumPy should use this function to locate the appropriate include directory. Notes ----- When using ``distutils``, for example in ``setup.py``. :: import numpy as np ... Extension('extension_name', ... include_dirs=[np.get_include()]) ...
Return the directory that contains the NumPy \\*.h header files.
[ "Return", "the", "directory", "that", "contains", "the", "NumPy", "\\\\", "*", ".", "h", "header", "files", "." ]
def get_include(): """ Return the directory that contains the NumPy \\*.h header files. Extension modules that need to compile against NumPy should use this function to locate the appropriate include directory. Notes ----- When using ``distutils``, for example in ``setup.py``. :: import numpy as np ... Extension('extension_name', ... include_dirs=[np.get_include()]) ... """ import numpy if numpy.show_config is None: # running from numpy source directory d = os.path.join(os.path.dirname(numpy.__file__), 'core', 'include') else: # using installed numpy core headers import numpy.core as core d = os.path.join(os.path.dirname(core.__file__), 'include') return d
[ "def", "get_include", "(", ")", ":", "import", "numpy", "if", "numpy", ".", "show_config", "is", "None", ":", "# running from numpy source directory", "d", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "numpy", ".", "_...
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/lib/utils.py#L16-L43
facebook/fboss
60063db1df37c2ec0e7dcd0955c54885ea9bf7f0
fboss/py/fboss/cli/cli.py
python
LldpCli.lldp
(cli_opts, port, verbose)
Show LLDP neighbors
Show LLDP neighbors
[ "Show", "LLDP", "neighbors" ]
def lldp(cli_opts, port, verbose): """Show LLDP neighbors""" lldp.LldpCmd(cli_opts).run(port, verbose)
[ "def", "lldp", "(", "cli_opts", ",", "port", ",", "verbose", ")", ":", "lldp", ".", "LldpCmd", "(", "cli_opts", ")", ".", "run", "(", "port", ",", "verbose", ")" ]
https://github.com/facebook/fboss/blob/60063db1df37c2ec0e7dcd0955c54885ea9bf7f0/fboss/py/fboss/cli/cli.py#L212-L214
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/numpy/files/numpy/polynomial/hermite.py
python
hermsub
(c1, c2)
return pu.trimseq(ret)
Subtract one Hermite series from another. Returns the difference of two Hermite series `c1` - `c2`. The sequences of coefficients are from lowest order term to highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``. Parameters ---------- c1, c2 : array_like 1-d arrays of Hermite series coefficients ordered from low to high. Returns ------- out : ndarray Of Hermite series coefficients representing their difference. See Also -------- hermadd, hermmul, hermdiv, hermpow Notes ----- Unlike multiplication, division, etc., the difference of two Hermite series is a Hermite series (without having to "reproject" the result onto the basis set) so subtraction, just like that of "standard" polynomials, is simply "component-wise." Examples -------- >>> from numpy.polynomial.hermite import hermsub >>> hermsub([1, 2, 3, 4], [1, 2, 3]) array([ 0., 0., 0., 4.])
Subtract one Hermite series from another.
[ "Subtract", "one", "Hermite", "series", "from", "another", "." ]
def hermsub(c1, c2): """ Subtract one Hermite series from another. Returns the difference of two Hermite series `c1` - `c2`. The sequences of coefficients are from lowest order term to highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``. Parameters ---------- c1, c2 : array_like 1-d arrays of Hermite series coefficients ordered from low to high. Returns ------- out : ndarray Of Hermite series coefficients representing their difference. See Also -------- hermadd, hermmul, hermdiv, hermpow Notes ----- Unlike multiplication, division, etc., the difference of two Hermite series is a Hermite series (without having to "reproject" the result onto the basis set) so subtraction, just like that of "standard" polynomials, is simply "component-wise." Examples -------- >>> from numpy.polynomial.hermite import hermsub >>> hermsub([1, 2, 3, 4], [1, 2, 3]) array([ 0., 0., 0., 4.]) """ # c1, c2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) if len(c1) > len(c2) : c1[:c2.size] -= c2 ret = c1 else : c2 = -c2 c2[:c1.size] += c1 ret = c2 return pu.trimseq(ret)
[ "def", "hermsub", "(", "c1", ",", "c2", ")", ":", "# c1, c2 are trimmed copies", "[", "c1", ",", "c2", "]", "=", "pu", ".", "as_series", "(", "[", "c1", ",", "c2", "]", ")", "if", "len", "(", "c1", ")", ">", "len", "(", "c2", ")", ":", "c1", ...
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/polynomial/hermite.py#L334-L380
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/tempfile.py
python
mkstemp
(suffix=None, prefix=None, dir=None, text=False)
return _mkstemp_inner(dir, prefix, suffix, flags, output_type)
User-callable function to create and return a unique temporary file. The return value is a pair (fd, name) where fd is the file descriptor returned by os.open, and name is the filename. If 'suffix' is not None, the file name will end with that suffix, otherwise there will be no suffix. If 'prefix' is not None, the file name will begin with that prefix, otherwise a default prefix is used. If 'dir' is not None, the file will be created in that directory, otherwise a default directory is used. If 'text' is specified and true, the file is opened in text mode. Else (the default) the file is opened in binary mode. If any of 'suffix', 'prefix' and 'dir' are not None, they must be the same type. If they are bytes, the returned name will be bytes; str otherwise. The file is readable and writable only by the creating user ID. If the operating system uses permission bits to indicate whether a file is executable, the file is executable by no one. The file descriptor is not inherited by children of this process. Caller is responsible for deleting the file when done with it.
User-callable function to create and return a unique temporary file. The return value is a pair (fd, name) where fd is the file descriptor returned by os.open, and name is the filename.
[ "User", "-", "callable", "function", "to", "create", "and", "return", "a", "unique", "temporary", "file", ".", "The", "return", "value", "is", "a", "pair", "(", "fd", "name", ")", "where", "fd", "is", "the", "file", "descriptor", "returned", "by", "os", ...
def mkstemp(suffix=None, prefix=None, dir=None, text=False): """User-callable function to create and return a unique temporary file. The return value is a pair (fd, name) where fd is the file descriptor returned by os.open, and name is the filename. If 'suffix' is not None, the file name will end with that suffix, otherwise there will be no suffix. If 'prefix' is not None, the file name will begin with that prefix, otherwise a default prefix is used. If 'dir' is not None, the file will be created in that directory, otherwise a default directory is used. If 'text' is specified and true, the file is opened in text mode. Else (the default) the file is opened in binary mode. If any of 'suffix', 'prefix' and 'dir' are not None, they must be the same type. If they are bytes, the returned name will be bytes; str otherwise. The file is readable and writable only by the creating user ID. If the operating system uses permission bits to indicate whether a file is executable, the file is executable by no one. The file descriptor is not inherited by children of this process. Caller is responsible for deleting the file when done with it. """ prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir) if text: flags = _text_openflags else: flags = _bin_openflags return _mkstemp_inner(dir, prefix, suffix, flags, output_type)
[ "def", "mkstemp", "(", "suffix", "=", "None", ",", "prefix", "=", "None", ",", "dir", "=", "None", ",", "text", "=", "False", ")", ":", "prefix", ",", "suffix", ",", "dir", ",", "output_type", "=", "_sanitize_params", "(", "prefix", ",", "suffix", ",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/tempfile.py#L300-L336
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/configservice/layer1.py
python
ConfigServiceConnection.start_configuration_recorder
(self, configuration_recorder_name)
return self.make_request(action='StartConfigurationRecorder', body=json.dumps(params))
Starts recording configurations of all the resources associated with the account. You must have created at least one delivery channel to successfully start the configuration recorder. :type configuration_recorder_name: string :param configuration_recorder_name: The name of the recorder object that records each configuration change made to the resources.
Starts recording configurations of all the resources associated with the account.
[ "Starts", "recording", "configurations", "of", "all", "the", "resources", "associated", "with", "the", "account", "." ]
def start_configuration_recorder(self, configuration_recorder_name): """ Starts recording configurations of all the resources associated with the account. You must have created at least one delivery channel to successfully start the configuration recorder. :type configuration_recorder_name: string :param configuration_recorder_name: The name of the recorder object that records each configuration change made to the resources. """ params = { 'ConfigurationRecorderName': configuration_recorder_name, } return self.make_request(action='StartConfigurationRecorder', body=json.dumps(params))
[ "def", "start_configuration_recorder", "(", "self", ",", "configuration_recorder_name", ")", ":", "params", "=", "{", "'ConfigurationRecorderName'", ":", "configuration_recorder_name", ",", "}", "return", "self", ".", "make_request", "(", "action", "=", "'StartConfigura...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/configservice/layer1.py#L323-L340
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/nn/layer/embedding.py
python
EmbeddingLookup._process_vocab_cache
(self, slice_mode)
PS embeddingLookup cache check and process.
PS embeddingLookup cache check and process.
[ "PS", "embeddingLookup", "cache", "check", "and", "process", "." ]
def _process_vocab_cache(self, slice_mode): """PS embeddingLookup cache check and process.""" self.cache_enable = False if self.vocab_cache_size > 0: if self.target == 'CPU': logger.warning("The configuration of 'vocab_cache_size' is valid only in 'DEVICE' target, " "current target is CPU, so it will be ignored.") return enable_ps = _get_ps_context("enable_ps") if not enable_ps: logger.warning("The configuration of 'vocab_cache_size' is valid only in parameter server training " "mode, current mode is not parameter server trainning mode, so it will be ignored.") return parallel_mode = _get_parallel_mode() is_auto_parallel = parallel_mode in (ParallelMode.SEMI_AUTO_PARALLEL, ParallelMode.AUTO_PARALLEL) if is_auto_parallel: rank_size = get_group_size() rank_id = get_rank() full_batch = _get_full_batch() if rank_size > 1 and not (full_batch and slice_mode == "table_row_slice"): raise ValueError(f"For '{self.cls_name}', the cache of parameter server parallel should only be " f"used in \"full_batch\" and the value of \"full_batch\" should be True. " f"Meanwhile, the value of 'slice_mode' should be \"table_row_slice\"." f"But got full_batch: {full_batch} and 'slice_mode': \"{slice_mode}\".") self.vocab_cache_size = self.vocab_cache_size * rank_size _set_rank_id(rank_id) self.cache_enable = True if _is_role_worker(): self.vocab_size = self.vocab_cache_size if context.get_context("enable_sparse") != self.sparse: raise ValueError(f"For '{self.cls_name}', the value of parameter 'sparse' must be same for all " f"kernels and equal the value of 'enable_sparse' in context setting in " f"parameter server cache mode, but got value of parameter 'sparse': {self.sparse}" f" and the 'enable_sparse' in context setting: " f"{context.get_context('enable_sparse')}.")
[ "def", "_process_vocab_cache", "(", "self", ",", "slice_mode", ")", ":", "self", ".", "cache_enable", "=", "False", "if", "self", ".", "vocab_cache_size", ">", "0", ":", "if", "self", ".", "target", "==", "'CPU'", ":", "logger", ".", "warning", "(", "\"T...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/layer/embedding.py#L313-L347
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/optimizer.py
python
PipelineOptimizer._insert_sendrecv_ops_for_boundaries
(self, block)
Insert a pair of send and recv ops for every two consecutive ops on different devices.
Insert a pair of send and recv ops for every two consecutive ops on different devices.
[ "Insert", "a", "pair", "of", "send", "and", "recv", "ops", "for", "every", "two", "consecutive", "ops", "on", "different", "devices", "." ]
def _insert_sendrecv_ops_for_boundaries(self, block): """ Insert a pair of send and recv ops for every two consecutive ops on different devices. """ # A map from var to device where op takes it as input, # avoiding multiple send and recv ops. input_var_to_device = dict() # bugfix hybrid parallelism first_optimize_index = None for index, op in enumerate(list(block.ops)): if self._is_optimize_op(op): first_optimize_index = index break extra_index_info = { 'index': 0, 'first_optimize_index': first_optimize_index } for index, op in enumerate(list(block.ops)): cur_device = op.attr(self._op_device_key) if cur_device == f"{self._device}:all": continue for var_name in op.input_arg_names: var = block.var(var_name) # skip data var if var.is_data: continue prev_device = None prev_op = self._find_prev_op(index, var_name) if prev_op is None: if var_name not in self._param_device_map: continue prev_device = self._param_device_map[var_name] if not prev_device: prev_device = prev_op.attr(self._op_device_key) \ if prev_op else None if prev_device is None or prev_device == f"{self._device}:all": continue if prev_device == cur_device: continue if var_name not in input_var_to_device: input_var_to_device[var_name] = [] if (cur_device, prev_device) in input_var_to_device[var_name]: continue device_type = cur_device.split(':')[0] + ':' def _check_stage(cur_id, prev_id): # check send/recv stage valid is_forward = self._is_forward_op(op) is_backward = self._is_backward_op(op) assert is_forward or is_backward, \ 'send/recv in pipeline should only be inserted in forward or backward,' \ 'please check the op_role of op={}'.format(op) if is_forward: assert prev_id < cur_id, \ "In forward, send/recv can only be passed forward, but now " \ "prev_stage={} great than cur_stage={}, please check op_device of op={}".format( prev_id, cur_id, op) elif is_backward: assert prev_id > cur_id, \ "In backward, send/recv can only be passed backward, but now " \ "prev_stage={} less than cur_stage={}, please check op_device of op={}".format( prev_id, cur_id, op) def _insert_send_recv(cur_id, prev_id): cur_dev = device_type + str(cur_id) prev_dev = device_type + str(prev_id) if (cur_dev, prev_dev) in input_var_to_device[var_name]: return if cur_id - prev_id > 1: _insert_send_recv(cur_id - 1, prev_id) _insert_send_recv(cur_id, cur_id - 1) input_var_to_device[var_name].append( (cur_dev, prev_dev)) return elif cur_id - prev_id < -1: _insert_send_recv(cur_id + 1, prev_id) _insert_send_recv(cur_id, cur_id + 1) input_var_to_device[var_name].append( (cur_dev, prev_dev)) return assert abs(cur_id - prev_id) == 1 input_var_to_device[var_name].append((cur_dev, prev_dev)) op_role = op.attr(self._op_role_key) var = block.vars[var_name] pair = (prev_id, cur_id) # 1000 is just a magic number pair_key = prev_id * 1000 + cur_id if pair not in self._pipeline_pair: self._pipeline_pair.append(pair) self._pp_ring_map[pair_key] = self.ring_id ring_id = self.ring_id self.ring_id += 1 else: ring_id = self._pp_ring_map[pair_key] if self.schedule_mode == 'F-then-B': # F-then-B block._insert_op_without_sync( index=index + extra_index_info['index'], type='send_v2', inputs={'X': var}, attrs={ self._op_device_key: prev_dev, self._op_role_key: op_role, 'use_calc_stream': True, 'peer': 1, 'ring_id': ring_id }) extra_index_info['index'] += 1 var_shape = list(var.shape) var_shape[0] = self.micro_batch_size if var_shape[ 0] < 0 else var_shape[0] block._insert_op_without_sync( index=index + extra_index_info['index'], type='recv_v2', outputs={'Out': [var]}, attrs={ 'out_shape': var_shape, 'dtype': var.dtype, self._op_device_key: cur_dev, self._op_role_key: op_role, 'use_calc_stream': True, 'peer': 0, 'ring_id': ring_id }) extra_index_info['index'] += 1 elif self.schedule_mode == '1F1B': # 1F1B var_shape = list(var.shape) var_shape[0] = self.micro_batch_size if var_shape[ 0] < 0 else var_shape[0] numel = np.prod(var_shape) use_mp = (self.mp_degree > 1) and ( numel % self.mp_degree == 0) if 'subprog' in var.name: # For recompute, if the checkpoints var is layer_norm_6.tmp_2 # this var will be sent twice, layer_norm_6.tmp_2 for forward pass, # layer_norm_6.tmp_2.subprog_* for recompute pass. # We can store the first sent var and copy the value to the # second one to reduce one send/recv op. # The origin_ckpt_name is layer_norm_6.tmp_2, which will be used # to find the stored var for the forward pass. origin_name = var.name.split('subprog')[0][0:-1] associate_var = block.var(origin_name) block._insert_op_without_sync( index=index + extra_index_info['index'], type='assign', inputs={'X': [associate_var]}, outputs={'Out': [var]}, attrs={ 'out_shape': var_shape, 'dtype': var.dtype, self._op_device_key: cur_dev, self._op_role_key: op_role, 'use_calc_stream': True, }) extra_index_info['index'] += 1 return _check_stage(cur_id, prev_id) block._insert_op_without_sync( index=index + extra_index_info['index'], type='c_sync_calc_stream', inputs={'X': [var]}, outputs={'Out': [var]}, attrs={ self._op_device_key: prev_dev, self._op_role_key: op_role, }) extra_index_info['index'] += 1 prefix_name = var.name.split('@')[0] prefix_var = block.var(prefix_name) is_param = True if isinstance(prefix_var, Parameter) else False block._insert_op_without_sync( index=index + extra_index_info['index'], type='send_v2' if not use_mp or is_param else 'partial_send', inputs={'X': var}, attrs={ self._op_device_key: prev_dev, self._op_role_key: op_role, 'use_calc_stream': False, 'ring_id': ring_id, 'peer': 1, # if send_v2, num&id attr is not in op_attrs, will not insert 'num': self.mp_degree, 'id': self.mp_rank, }) extra_index_info['index'] += 1 insert_index = None if int(op_role) == int(self._op_role.Backward): insert_index = extra_index_info[ 'first_optimize_index'] new_op_role = self._op_role.Optimize else: insert_index = index new_op_role = self._op_role.Backward sync_comm_op = block._insert_op_without_sync( index=insert_index + extra_index_info['index'], type='c_sync_comm_stream', inputs={'X': [var]}, outputs={'Out': [var]}, attrs={ self._op_device_key: prev_dev, self._op_role_key: new_op_role, 'ring_id': ring_id, }) if int(op_role) == int(self._op_role.Forward): sync_comm_op._set_attr('pipeline_flag', '') extra_index_info['index'] += 1 block._insert_op_without_sync( index=index + extra_index_info['index'], type='recv_v2' if not use_mp or is_param else 'partial_recv', outputs={'Out': [var]}, attrs={ 'out_shape': var_shape, 'dtype': var.dtype, self._op_device_key: cur_dev, self._op_role_key: op_role, 'use_calc_stream': True, 'peer': 0, 'ring_id': ring_id, # if recv_v2, num&id attr is not in op_attrs, will not insert 'num': self.mp_degree, 'id': self.mp_rank, }) extra_index_info['index'] += 1 if use_mp and not is_param: block._insert_op_without_sync( index=index + extra_index_info['index'], type='partial_allgather', inputs={'X': [var]}, outputs={'Out': [var]}, attrs={ self._op_device_key: cur_dev, self._op_role_key: op_role, 'use_calc_stream': True, 'ring_id': 0, # if recv_v2, num&id attr is not in op_attrs, will not insert 'nranks': self.mp_degree, 'rank': self.mp_rank, }) extra_index_info['index'] += 1 else: raise ValueError( "Now only 'F-then-B' and '1F1B' are supported." "The given value is {}.".format(self.schedule_mode)) _insert_send_recv( int(cur_device.split(':')[1]), int(prev_device.split(':')[1])) block._sync_with_cpp()
[ "def", "_insert_sendrecv_ops_for_boundaries", "(", "self", ",", "block", ")", ":", "# A map from var to device where op takes it as input,", "# avoiding multiple send and recv ops.", "input_var_to_device", "=", "dict", "(", ")", "# bugfix hybrid parallelism", "first_optimize_index", ...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/optimizer.py#L4920-L5183
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/jira/resources.py
python
Resource.update
(self, fields=None, async=None, jira=None, notify=True, **kwargs)
Update this resource on the server. Keyword arguments are marshalled into a dict before being sent. If this resource doesn't support ``PUT``, a :py:exc:`.JIRAError` will be raised; subclasses that specialize this method will only raise errors in case of user error. :param async: if true the request will be added to the queue so it can be executed later using async_run()
Update this resource on the server.
[ "Update", "this", "resource", "on", "the", "server", "." ]
def update(self, fields=None, async=None, jira=None, notify=True, **kwargs): """Update this resource on the server. Keyword arguments are marshalled into a dict before being sent. If this resource doesn't support ``PUT``, a :py:exc:`.JIRAError` will be raised; subclasses that specialize this method will only raise errors in case of user error. :param async: if true the request will be added to the queue so it can be executed later using async_run() """ if async is None: async = self._options['async'] data = {} if fields is not None: data.update(fields) data.update(kwargs) data = json.dumps(data) if not notify: querystring = "?notifyUsers=false" else: querystring = "" r = self._session.put( self.self + querystring, data=data) if 'autofix' in self._options and \ r.status_code == 400: user = None error_list = get_error_list(r) logging.error(error_list) if "The reporter specified is not a user." in error_list: if 'reporter' not in data['fields']: logging.warning( "autofix: setting reporter to '%s' and retrying the update." % self._options['autofix']) data['fields']['reporter'] = { 'name': self._options['autofix']} if "Issues must be assigned." in error_list: if 'assignee' not in data['fields']: logging.warning("autofix: setting assignee to '%s' for %s and retrying the update." % ( self._options['autofix'], self.key)) data['fields']['assignee'] = { 'name': self._options['autofix']} # for some reason the above approach fails on Jira 5.2.11 # so we need to change the assignee before if "Issue type is a sub-task but parent issue key or id not specified." in error_list: logging.warning( "autofix: trying to fix sub-task without parent by converting to it to bug") data['fields']['issuetype'] = {"name": "Bug"} if "The summary is invalid because it contains newline characters." in error_list: logging.warning("autofix: trying to fix newline in summary") data['fields'][ 'summary'] = self.fields.summary.replace("/n", "") for error in error_list: if re.search(u"^User '(.*)' was not found in the system\.", error, re.U): m = re.search( u"^User '(.*)' was not found in the system\.", error, re.U) if m: user = m.groups()[0] else: raise NotImplemented() if re.search("^User '(.*)' does not exist\.", error): m = re.search("^User '(.*)' does not exist\.", error) if m: user = m.groups()[0] else: raise NotImplemented() if user: logging.warning( "Trying to add missing orphan user '%s' in order to complete the previous failed operation." % user) jira.add_user(user, 'noreply@example.com', 10100, active=False) # if 'assignee' not in data['fields']: # logging.warning("autofix: setting assignee to '%s' and retrying the update." % self._options['autofix']) # data['fields']['assignee'] = {'name': self._options['autofix']} # EXPERIMENTAL ---> # import grequests if async: if not hasattr(self._session, '_async_jobs'): self._session._async_jobs = set() self._session._async_jobs.add(threaded_requests.put( self.self, data=json.dumps(data))) else: r = self._session.put( self.self, data=json.dumps(data)) # TODO(ssbarnea): compare loaded data in order to verify if resource was updated indeed # we had random test failures (probably) due to caching time.sleep(4) self._load(self.self)
[ "def", "update", "(", "self", ",", "fields", "=", "None", ",", "async", "=", "None", ",", "jira", "=", "None", ",", "notify", "=", "True", ",", "*", "*", "kwargs", ")", ":", "if", "async", "is", "None", ":", "async", "=", "self", ".", "_options",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/jira/resources.py#L207-L298
zhaoweicai/hwgq
ebc706bee3e2d145de1da4be446ce8de8740738f
python/caffe/coord_map.py
python
crop
(top_from, top_to)
return L.Crop(top_from, top_to, crop_param=dict(axis=ax + 1, # +1 for first cropping dim. offset=list(-np.round(b).astype(int))))
Define a Crop layer to crop a top (from) to another top (to) by determining the coordinate mapping between the two and net spec'ing the axis and shift parameters of the crop.
Define a Crop layer to crop a top (from) to another top (to) by determining the coordinate mapping between the two and net spec'ing the axis and shift parameters of the crop.
[ "Define", "a", "Crop", "layer", "to", "crop", "a", "top", "(", "from", ")", "to", "another", "top", "(", "to", ")", "by", "determining", "the", "coordinate", "mapping", "between", "the", "two", "and", "net", "spec", "ing", "the", "axis", "and", "shift"...
def crop(top_from, top_to): """ Define a Crop layer to crop a top (from) to another top (to) by determining the coordinate mapping between the two and net spec'ing the axis and shift parameters of the crop. """ ax, a, b = coord_map_from_to(top_from, top_to) assert (a == 1).all(), 'scale mismatch on crop (a = {})'.format(a) assert (b <= 0).all(), 'cannot crop negative offset (b = {})'.format(b) assert (np.round(b) == b).all(), 'cannot crop noninteger offset ' \ '(b = {})'.format(b) return L.Crop(top_from, top_to, crop_param=dict(axis=ax + 1, # +1 for first cropping dim. offset=list(-np.round(b).astype(int))))
[ "def", "crop", "(", "top_from", ",", "top_to", ")", ":", "ax", ",", "a", ",", "b", "=", "coord_map_from_to", "(", "top_from", ",", "top_to", ")", "assert", "(", "a", "==", "1", ")", ".", "all", "(", ")", ",", "'scale mismatch on crop (a = {})'", ".", ...
https://github.com/zhaoweicai/hwgq/blob/ebc706bee3e2d145de1da4be446ce8de8740738f/python/caffe/coord_map.py#L172-L185
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/stc.py
python
StyledTextCtrl.BackTab
(*args, **kwargs)
return _stc.StyledTextCtrl_BackTab(*args, **kwargs)
BackTab(self) Dedent the selected lines.
BackTab(self)
[ "BackTab", "(", "self", ")" ]
def BackTab(*args, **kwargs): """ BackTab(self) Dedent the selected lines. """ return _stc.StyledTextCtrl_BackTab(*args, **kwargs)
[ "def", "BackTab", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_BackTab", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L4555-L4561
OSGeo/gdal
3748fc4ba4fba727492774b2b908a2130c864a83
swig/python/osgeo/gnm.py
python
Network.CreateLayer
(self, *args, **kwargs)
return _gnm.Network_CreateLayer(self, *args, **kwargs)
r"""CreateLayer(Network self, char const * name, SpatialReference srs=None, OGRwkbGeometryType geom_type=wkbUnknown, char ** options=None) -> Layer
r"""CreateLayer(Network self, char const * name, SpatialReference srs=None, OGRwkbGeometryType geom_type=wkbUnknown, char ** options=None) -> Layer
[ "r", "CreateLayer", "(", "Network", "self", "char", "const", "*", "name", "SpatialReference", "srs", "=", "None", "OGRwkbGeometryType", "geom_type", "=", "wkbUnknown", "char", "**", "options", "=", "None", ")", "-", ">", "Layer" ]
def CreateLayer(self, *args, **kwargs): r"""CreateLayer(Network self, char const * name, SpatialReference srs=None, OGRwkbGeometryType geom_type=wkbUnknown, char ** options=None) -> Layer""" return _gnm.Network_CreateLayer(self, *args, **kwargs)
[ "def", "CreateLayer", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gnm", ".", "Network_CreateLayer", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/gnm.py#L144-L146
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
python/mxnet/ndarray/ndarray.py
python
NDArray.__hash__
(self)
return id(self)//16
Default hash function.
Default hash function.
[ "Default", "hash", "function", "." ]
def __hash__(self): """Default hash function.""" return id(self)//16
[ "def", "__hash__", "(", "self", ")", ":", "return", "id", "(", "self", ")", "//", "16" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/ndarray/ndarray.py#L326-L328
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py3/numpy/polynomial/chebyshev.py
python
chebmul
(c1, c2)
return pu.trimseq(ret)
Multiply one Chebyshev series by another. Returns the product of two Chebyshev series `c1` * `c2`. The arguments are sequences of coefficients, from lowest order "term" to highest, e.g., [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Chebyshev series coefficients ordered from low to high. Returns ------- out : ndarray Of Chebyshev series coefficients representing their product. See Also -------- chebadd, chebsub, chebmulx, chebdiv, chebpow Notes ----- In general, the (polynomial) product of two C-series results in terms that are not in the Chebyshev polynomial basis set. Thus, to express the product as a C-series, it is typically necessary to "reproject" the product onto said basis set, which typically produces "unintuitive live" (but correct) results; see Examples section below. Examples -------- >>> from numpy.polynomial import chebyshev as C >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> C.chebmul(c1,c2) # multiplication requires "reprojection" array([ 6.5, 12. , 12. , 4. , 1.5])
Multiply one Chebyshev series by another.
[ "Multiply", "one", "Chebyshev", "series", "by", "another", "." ]
def chebmul(c1, c2): """ Multiply one Chebyshev series by another. Returns the product of two Chebyshev series `c1` * `c2`. The arguments are sequences of coefficients, from lowest order "term" to highest, e.g., [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Chebyshev series coefficients ordered from low to high. Returns ------- out : ndarray Of Chebyshev series coefficients representing their product. See Also -------- chebadd, chebsub, chebmulx, chebdiv, chebpow Notes ----- In general, the (polynomial) product of two C-series results in terms that are not in the Chebyshev polynomial basis set. Thus, to express the product as a C-series, it is typically necessary to "reproject" the product onto said basis set, which typically produces "unintuitive live" (but correct) results; see Examples section below. Examples -------- >>> from numpy.polynomial import chebyshev as C >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> C.chebmul(c1,c2) # multiplication requires "reprojection" array([ 6.5, 12. , 12. , 4. , 1.5]) """ # c1, c2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) z1 = _cseries_to_zseries(c1) z2 = _cseries_to_zseries(c2) prd = _zseries_mul(z1, z2) ret = _zseries_to_cseries(prd) return pu.trimseq(ret)
[ "def", "chebmul", "(", "c1", ",", "c2", ")", ":", "# c1, c2 are trimmed copies", "[", "c1", ",", "c2", "]", "=", "pu", ".", "as_series", "(", "[", "c1", ",", "c2", "]", ")", "z1", "=", "_cseries_to_zseries", "(", "c1", ")", "z2", "=", "_cseries_to_zs...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/polynomial/chebyshev.py#L701-L747
vslavik/poedit
f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a
deps/boost/tools/build/src/build/configure.py
python
log_component_configuration
(component, message)
Report something about component configuration that the user should better know.
Report something about component configuration that the user should better know.
[ "Report", "something", "about", "component", "configuration", "that", "the", "user", "should", "better", "know", "." ]
def log_component_configuration(component, message): """Report something about component configuration that the user should better know.""" assert isinstance(component, basestring) assert isinstance(message, basestring) __component_logs.setdefault(component, []).append(message)
[ "def", "log_component_configuration", "(", "component", ",", "message", ")", ":", "assert", "isinstance", "(", "component", ",", "basestring", ")", "assert", "isinstance", "(", "message", ",", "basestring", ")", "__component_logs", ".", "setdefault", "(", "compone...
https://github.com/vslavik/poedit/blob/f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a/deps/boost/tools/build/src/build/configure.py#L52-L56
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
python/contrib/dag/__init__.py
python
DAG.delete_edge_if_exists
(self, ind_node, dep_node, graph=None)
Delete an edge from the graph.
Delete an edge from the graph.
[ "Delete", "an", "edge", "from", "the", "graph", "." ]
def delete_edge_if_exists(self, ind_node, dep_node, graph=None): """ Delete an edge from the graph. """ if not graph: graph = self.graph if dep_node not in graph.get(ind_node, []): return graph[ind_node].remove(dep_node)
[ "def", "delete_edge_if_exists", "(", "self", ",", "ind_node", ",", "dep_node", ",", "graph", "=", "None", ")", ":", "if", "not", "graph", ":", "graph", "=", "self", ".", "graph", "if", "dep_node", "not", "in", "graph", ".", "get", "(", "ind_node", ",",...
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/contrib/dag/__init__.py#L311-L318
balloonwj/TeamTalk
dc79c40687e4c9d7bec07ff5c9782be586fd9b41
win-client/3rdParty/src/json/devtools/licenseupdater.py
python
update_license
( path, dry_run, show_diff )
return False
Update the license statement in the specified file. Parameters: path: path of the C++ source file to update. dry_run: if True, just print the path of the file that would be updated, but don't change it. show_diff: if True, print the path of the file that would be modified, as well as the change made to the file.
Update the license statement in the specified file. Parameters: path: path of the C++ source file to update. dry_run: if True, just print the path of the file that would be updated, but don't change it. show_diff: if True, print the path of the file that would be modified, as well as the change made to the file.
[ "Update", "the", "license", "statement", "in", "the", "specified", "file", ".", "Parameters", ":", "path", ":", "path", "of", "the", "C", "++", "source", "file", "to", "update", ".", "dry_run", ":", "if", "True", "just", "print", "the", "path", "of", "...
def update_license( path, dry_run, show_diff ): """Update the license statement in the specified file. Parameters: path: path of the C++ source file to update. dry_run: if True, just print the path of the file that would be updated, but don't change it. show_diff: if True, print the path of the file that would be modified, as well as the change made to the file. """ with open( path, 'rt' ) as fin: original_text = fin.read().replace('\r\n','\n') newline = fin.newlines and fin.newlines[0] or '\n' if not original_text.startswith( LICENSE_BEGIN ): # No existing license found => prepend it new_text = BRIEF_LICENSE + original_text else: license_end_index = original_text.index( '\n\n' ) # search first blank line new_text = BRIEF_LICENSE + original_text[license_end_index+2:] if original_text != new_text: if not dry_run: with open( path, 'wb' ) as fout: fout.write( new_text.replace('\n', newline ) ) print 'Updated', path if show_diff: import difflib print '\n'.join( difflib.unified_diff( original_text.split('\n'), new_text.split('\n') ) ) return True return False
[ "def", "update_license", "(", "path", ",", "dry_run", ",", "show_diff", ")", ":", "with", "open", "(", "path", ",", "'rt'", ")", "as", "fin", ":", "original_text", "=", "fin", ".", "read", "(", ")", ".", "replace", "(", "'\\r\\n'", ",", "'\\n'", ")",...
https://github.com/balloonwj/TeamTalk/blob/dc79c40687e4c9d7bec07ff5c9782be586fd9b41/win-client/3rdParty/src/json/devtools/licenseupdater.py#L15-L43
ROCmSoftwarePlatform/hipCaffe
4ec5d482515cce532348553b6db6d00d015675d5
scripts/cpp_lint.py
python
RemoveMultiLineComments
(filename, lines, error)
Removes multiline (c-style) comments from lines.
Removes multiline (c-style) comments from lines.
[ "Removes", "multiline", "(", "c", "-", "style", ")", "comments", "from", "lines", "." ]
def RemoveMultiLineComments(filename, lines, error): """Removes multiline (c-style) comments from lines.""" lineix = 0 while lineix < len(lines): lineix_begin = FindNextMultiLineCommentStart(lines, lineix) if lineix_begin >= len(lines): return lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin) if lineix_end >= len(lines): error(filename, lineix_begin + 1, 'readability/multiline_comment', 5, 'Could not find end of multi-line comment') return RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1) lineix = lineix_end + 1
[ "def", "RemoveMultiLineComments", "(", "filename", ",", "lines", ",", "error", ")", ":", "lineix", "=", "0", "while", "lineix", "<", "len", "(", "lines", ")", ":", "lineix_begin", "=", "FindNextMultiLineCommentStart", "(", "lines", ",", "lineix", ")", "if", ...
https://github.com/ROCmSoftwarePlatform/hipCaffe/blob/4ec5d482515cce532348553b6db6d00d015675d5/scripts/cpp_lint.py#L1151-L1164
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/build/print_python_deps.py
python
_GetTargetPythonVersion
(module)
return default_version
Heuristically determines the target module's Python version.
Heuristically determines the target module's Python version.
[ "Heuristically", "determines", "the", "target", "module", "s", "Python", "version", "." ]
def _GetTargetPythonVersion(module): """Heuristically determines the target module's Python version.""" with open(module) as f: shebang = f.readline().strip() default_version = 2 if shebang.startswith('#!'): # Examples: # '#!/usr/bin/python' # '#!/usr/bin/python2.7' # '#!/usr/bin/python3' # '#!/usr/bin/env python3' # '#!/usr/bin/env vpython' # '#!/usr/bin/env vpython3' exec_name = os.path.basename(shebang[2:].split(' ')[-1]) for python_prefix in ['python', 'vpython']: if exec_name.startswith(python_prefix): version_string = exec_name[len(python_prefix):] break else: raise ValueError('Invalid shebang: ' + shebang) if version_string: return int(float(version_string)) return default_version
[ "def", "_GetTargetPythonVersion", "(", "module", ")", ":", "with", "open", "(", "module", ")", "as", "f", ":", "shebang", "=", "f", ".", "readline", "(", ")", ".", "strip", "(", ")", "default_version", "=", "2", "if", "shebang", ".", "startswith", "(",...
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/print_python_deps.py#L77-L99
llvm/llvm-project
ffa6262cb4e2a335d26416fad39a581b4f98c5f4
llvm/utils/lit/lit/util.py
python
killProcessAndChildrenIsSupported
()
Returns a tuple (<supported> , <error message>) where `<supported>` is True if `killProcessAndChildren()` is supported on the current host, returns False otherwise. `<error message>` is an empty string if `<supported>` is True, otherwise is contains a string describing why the function is not supported.
Returns a tuple (<supported> , <error message>) where `<supported>` is True if `killProcessAndChildren()` is supported on the current host, returns False otherwise. `<error message>` is an empty string if `<supported>` is True, otherwise is contains a string describing why the function is not supported.
[ "Returns", "a", "tuple", "(", "<supported", ">", "<error", "message", ">", ")", "where", "<supported", ">", "is", "True", "if", "killProcessAndChildren", "()", "is", "supported", "on", "the", "current", "host", "returns", "False", "otherwise", ".", "<error", ...
def killProcessAndChildrenIsSupported(): """ Returns a tuple (<supported> , <error message>) where `<supported>` is True if `killProcessAndChildren()` is supported on the current host, returns False otherwise. `<error message>` is an empty string if `<supported>` is True, otherwise is contains a string describing why the function is not supported. """ if platform.system() == 'AIX': return (True, "") try: import psutil # noqa: F401 return (True, "") except ImportError: return (False, "Requires the Python psutil module but it could" " not be found. Try installing it via pip or via" " your operating system's package manager.")
[ "def", "killProcessAndChildrenIsSupported", "(", ")", ":", "if", "platform", ".", "system", "(", ")", "==", "'AIX'", ":", "return", "(", "True", ",", "\"\"", ")", "try", ":", "import", "psutil", "# noqa: F401", "return", "(", "True", ",", "\"\"", ")", "e...
https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/llvm/utils/lit/lit/util.py#L417-L435
google/mysql-protobuf
467cda676afaa49e762c5c9164a43f6ad31a1fbf
protobuf/python/google/protobuf/text_format.py
python
_Tokenizer.ConsumeUint32
(self)
return result
Consumes an unsigned 32bit integer number. Returns: The integer parsed. Raises: ParseError: If an unsigned 32bit integer couldn't be consumed.
Consumes an unsigned 32bit integer number.
[ "Consumes", "an", "unsigned", "32bit", "integer", "number", "." ]
def ConsumeUint32(self): """Consumes an unsigned 32bit integer number. Returns: The integer parsed. Raises: ParseError: If an unsigned 32bit integer couldn't be consumed. """ try: result = ParseInteger(self.token, is_signed=False, is_long=False) except ValueError, e: raise self._ParseError(str(e)) self.NextToken() return result
[ "def", "ConsumeUint32", "(", "self", ")", ":", "try", ":", "result", "=", "ParseInteger", "(", "self", ".", "token", ",", "is_signed", "=", "False", ",", "is_long", "=", "False", ")", "except", "ValueError", ",", "e", ":", "raise", "self", ".", "_Parse...
https://github.com/google/mysql-protobuf/blob/467cda676afaa49e762c5c9164a43f6ad31a1fbf/protobuf/python/google/protobuf/text_format.py#L615-L629
vmtk/vmtk
927331ad752265199390eabbbf2e07cdc2b4bcc6
PypeS/pype.py
python
Pype.SetArgumentsString
(self,argumentsString)
Splits an input string into a list containing the class name and arguments. sets the class attribute "Arguments". Args: argumentsString (string): the input argument string
Splits an input string into a list containing the class name and arguments.
[ "Splits", "an", "input", "string", "into", "a", "list", "containing", "the", "class", "name", "and", "arguments", "." ]
def SetArgumentsString(self,argumentsString): ''' Splits an input string into a list containing the class name and arguments. sets the class attribute "Arguments". Args: argumentsString (string): the input argument string ''' if '"' not in argumentsString: self.Arguments = argumentsString.split() import re quoteRe = re.compile('(\".*?\")') splitArguments = quoteRe.split(argumentsString) arguments = [] for splitArgument in splitArguments: arg = splitArgument if splitArgument.startswith('"') and splitArgument.endswith('"'): arg = splitArgument[1:-1] arguments.append(arg) else: arguments.extend(arg.strip().split()) if '"' in arg: self.PrintError('Error: non-matching quote found') self.Arguments = arguments
[ "def", "SetArgumentsString", "(", "self", ",", "argumentsString", ")", ":", "if", "'\"'", "not", "in", "argumentsString", ":", "self", ".", "Arguments", "=", "argumentsString", ".", "split", "(", ")", "import", "re", "quoteRe", "=", "re", ".", "compile", "...
https://github.com/vmtk/vmtk/blob/927331ad752265199390eabbbf2e07cdc2b4bcc6/PypeS/pype.py#L104-L127
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/robotsim.py
python
PointCloud.setPoints
(self, np_array2: Vector)
return _robotsim.PointCloud_setPoints(self, np_array2)
r""" Sets all the points to the given nx3 Numpy array. Args: np_array2 (:obj:`2D Numpy array of floats`)
r""" Sets all the points to the given nx3 Numpy array.
[ "r", "Sets", "all", "the", "points", "to", "the", "given", "nx3", "Numpy", "array", "." ]
def setPoints(self, np_array2: Vector) ->None: r""" Sets all the points to the given nx3 Numpy array. Args: np_array2 (:obj:`2D Numpy array of floats`) """ return _robotsim.PointCloud_setPoints(self, np_array2)
[ "def", "setPoints", "(", "self", ",", "np_array2", ":", "Vector", ")", "->", "None", ":", "return", "_robotsim", ".", "PointCloud_setPoints", "(", "self", ",", "np_array2", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/robotsim.py#L1177-L1184
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/cachecontrol/heuristics.py
python
BaseHeuristic.warning
(self, response)
return '110 - "Response is Stale"'
Return a valid 1xx warning header value describing the cache adjustments. The response is provided too allow warnings like 113 http://tools.ietf.org/html/rfc7234#section-5.5.4 where we need to explicitly say response is over 24 hours old.
[]
def warning(self, response): """ Return a valid 1xx warning header value describing the cache adjustments. The response is provided too allow warnings like 113 http://tools.ietf.org/html/rfc7234#section-5.5.4 where we need to explicitly say response is over 24 hours old. """ return '110 - "Response is Stale"'
[ "def", "warning", "(", "self", ",", "response", ")", ":", "return", "'110 - \"Response is Stale\"'" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/cachecontrol/heuristics.py#L43-L61
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/io/formats/format.py
python
_get_format_timedelta64
(values, nat_rep='NaT', box=False)
return _formatter
Return a formatter function for a range of timedeltas. These will all have the same format argument If box, then show the return in quotes
Return a formatter function for a range of timedeltas. These will all have the same format argument
[ "Return", "a", "formatter", "function", "for", "a", "range", "of", "timedeltas", ".", "These", "will", "all", "have", "the", "same", "format", "argument" ]
def _get_format_timedelta64(values, nat_rep='NaT', box=False): """ Return a formatter function for a range of timedeltas. These will all have the same format argument If box, then show the return in quotes """ values_int = values.astype(np.int64) consider_values = values_int != iNaT one_day_nanos = (86400 * 1e9) even_days = np.logical_and(consider_values, values_int % one_day_nanos != 0).sum() == 0 all_sub_day = np.logical_and( consider_values, np.abs(values_int) >= one_day_nanos).sum() == 0 if even_days: format = None elif all_sub_day: format = 'sub_day' else: format = 'long' def _formatter(x): if x is None or (is_scalar(x) and isna(x)): return nat_rep if not isinstance(x, Timedelta): x = Timedelta(x) result = x._repr_base(format=format) if box: result = "'{res}'".format(res=result) return result return _formatter
[ "def", "_get_format_timedelta64", "(", "values", ",", "nat_rep", "=", "'NaT'", ",", "box", "=", "False", ")", ":", "values_int", "=", "values", ".", "astype", "(", "np", ".", "int64", ")", "consider_values", "=", "values_int", "!=", "iNaT", "one_day_nanos", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/io/formats/format.py#L1345-L1381
JoseExposito/touchegg
1f3fda214358d071c05da4bf17c070c33d67b5eb
cmake/cpplint.py
python
NestingState.InTemplateArgumentList
(self, clean_lines, linenum, pos)
return False
Check if current position is inside template argument list. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: position just after the suspected template argument. Returns: True if (linenum, pos) is inside template arguments.
Check if current position is inside template argument list.
[ "Check", "if", "current", "position", "is", "inside", "template", "argument", "list", "." ]
def InTemplateArgumentList(self, clean_lines, linenum, pos): """Check if current position is inside template argument list. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: position just after the suspected template argument. Returns: True if (linenum, pos) is inside template arguments. """ while linenum < clean_lines.NumLines(): # Find the earliest character that might indicate a template argument line = clean_lines.elided[linenum] match = Match(r'^[^{};=\[\]\.<>]*(.)', line[pos:]) if not match: linenum += 1 pos = 0 continue token = match.group(1) pos += len(match.group(0)) # These things do not look like template argument list: # class Suspect { # class Suspect x; } if token in ('{', '}', ';'): return False # These things look like template argument list: # template <class Suspect> # template <class Suspect = default_value> # template <class Suspect[]> # template <class Suspect...> if token in ('>', '=', '[', ']', '.'): return True # Check if token is an unmatched '<'. # If not, move on to the next character. if token != '<': pos += 1 if pos >= len(line): linenum += 1 pos = 0 continue # We can't be sure if we just find a single '<', and need to # find the matching '>'. (_, end_line, end_pos) = CloseExpression(clean_lines, linenum, pos - 1) if end_pos < 0: # Not sure if template argument list or syntax error in file return False linenum = end_line pos = end_pos return False
[ "def", "InTemplateArgumentList", "(", "self", ",", "clean_lines", ",", "linenum", ",", "pos", ")", ":", "while", "linenum", "<", "clean_lines", ".", "NumLines", "(", ")", ":", "# Find the earliest character that might indicate a template argument", "line", "=", "clean...
https://github.com/JoseExposito/touchegg/blob/1f3fda214358d071c05da4bf17c070c33d67b5eb/cmake/cpplint.py#L2473-L2523
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/ed_tab.py
python
EdTabBase.GetTabIndex
(self)
return self._idx
Return the index of the tab in the notebook @return: int
Return the index of the tab in the notebook @return: int
[ "Return", "the", "index", "of", "the", "tab", "in", "the", "notebook", "@return", ":", "int" ]
def GetTabIndex(self): """Return the index of the tab in the notebook @return: int """ return self._idx
[ "def", "GetTabIndex", "(", "self", ")", ":", "return", "self", ".", "_idx" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_tab.py#L115-L120
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/flatmenu.py
python
FlatToolbarItem.IsSelected
(self)
return self._selected
Returns whether the tool is selected or checked.
Returns whether the tool is selected or checked.
[ "Returns", "whether", "the", "tool", "is", "selected", "or", "checked", "." ]
def IsSelected(self): """ Returns whether the tool is selected or checked.""" return self._selected
[ "def", "IsSelected", "(", "self", ")", ":", "return", "self", ".", "_selected" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatmenu.py#L4690-L4693
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/distributed/elastic/multiprocessing/errors/error_handler.py
python
ErrorHandler.dump_error_file
(self, rootcause_error_file: str, error_code: int = 0)
Dumps parent error file from child process's root cause error and error code.
Dumps parent error file from child process's root cause error and error code.
[ "Dumps", "parent", "error", "file", "from", "child", "process", "s", "root", "cause", "error", "and", "error", "code", "." ]
def dump_error_file(self, rootcause_error_file: str, error_code: int = 0): """ Dumps parent error file from child process's root cause error and error code. """ with open(rootcause_error_file, "r") as fp: rootcause_error = json.load(fp) # Override error code since the child process cannot capture the error code if it # is terminated by singals like SIGSEGV. if error_code: if "message" not in rootcause_error: log.warning( f"child error file ({rootcause_error_file}) does not have field `message`. \n" f"cannot override error code: {error_code}" ) elif isinstance(rootcause_error["message"], str): log.warning( f"child error file ({rootcause_error_file}) has a new message format. \n" f"skipping error code override" ) else: rootcause_error["message"]["errorCode"] = error_code log.debug( f"child error file ({rootcause_error_file}) contents:\n" f"{json.dumps(rootcause_error, indent=2)}" ) my_error_file = self._get_error_file_path() if my_error_file: # Guard against existing error files # This can happen when the child is created using multiprocessing # and the same env var (TORCHELASTIC_ERROR_FILE) is used on the # parent and child to specify the error files (respectively) # because the env vars on the child is set in the wrapper function # and by default the child inherits the parent's env vars, if the child # process receives a signal before the wrapper function kicks in # and the signal handler writes to the error file, then the child # will write to the parent's error file. In this case just log the # original error file contents and overwrite the error file. self._rm(my_error_file) self._write_error_file(my_error_file, json.dumps(rootcause_error)) log.info(f"dumped error file to parent's {my_error_file}") else: log.error( f"no error file defined for parent, to copy child error file ({rootcause_error_file})" )
[ "def", "dump_error_file", "(", "self", ",", "rootcause_error_file", ":", "str", ",", "error_code", ":", "int", "=", "0", ")", ":", "with", "open", "(", "rootcause_error_file", ",", "\"r\"", ")", "as", "fp", ":", "rootcause_error", "=", "json", ".", "load",...
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributed/elastic/multiprocessing/errors/error_handler.py#L88-L133
synfig/synfig
a5ec91db5b751dc12e4400ccfb5c063fd6d2d928
synfig-studio/plugins/lottie-exporter/common/Param.py
python
Param.get
(self)
return self.param
Returns the original param
Returns the original param
[ "Returns", "the", "original", "param" ]
def get(self): """ Returns the original param """ return self.param
[ "def", "get", "(", "self", ")", ":", "return", "self", ".", "param" ]
https://github.com/synfig/synfig/blob/a5ec91db5b751dc12e4400ccfb5c063fd6d2d928/synfig-studio/plugins/lottie-exporter/common/Param.py#L87-L91
twtygqyy/caffe-augmentation
c76600d247e5132fa5bd89d87bb5df458341fa84
scripts/cpp_lint.py
python
FindNextMatchingAngleBracket
(clean_lines, linenum, init_suffix)
return True
Find the corresponding > to close a template. Args: clean_lines: A CleansedLines instance containing the file. linenum: Current line number. init_suffix: Remainder of the current line after the initial <. Returns: True if a matching bracket exists.
Find the corresponding > to close a template.
[ "Find", "the", "corresponding", ">", "to", "close", "a", "template", "." ]
def FindNextMatchingAngleBracket(clean_lines, linenum, init_suffix): """Find the corresponding > to close a template. Args: clean_lines: A CleansedLines instance containing the file. linenum: Current line number. init_suffix: Remainder of the current line after the initial <. Returns: True if a matching bracket exists. """ line = init_suffix nesting_stack = ['<'] while True: # Find the next operator that can tell us whether < is used as an # opening bracket or as a less-than operator. We only want to # warn on the latter case. # # We could also check all other operators and terminate the search # early, e.g. if we got something like this "a<b+c", the "<" is # most likely a less-than operator, but then we will get false # positives for default arguments and other template expressions. match = Search(r'^[^<>(),;\[\]]*([<>(),;\[\]])(.*)$', line) if match: # Found an operator, update nesting stack operator = match.group(1) line = match.group(2) if nesting_stack[-1] == '<': # Expecting closing angle bracket if operator in ('<', '(', '['): nesting_stack.append(operator) elif operator == '>': nesting_stack.pop() if not nesting_stack: # Found matching angle bracket return True elif operator == ',': # Got a comma after a bracket, this is most likely a template # argument. We have not seen a closing angle bracket yet, but # it's probably a few lines later if we look for it, so just # return early here. return True else: # Got some other operator. return False else: # Expecting closing parenthesis or closing bracket if operator in ('<', '(', '['): nesting_stack.append(operator) elif operator in (')', ']'): # We don't bother checking for matching () or []. If we got # something like (] or [), it would have been a syntax error. nesting_stack.pop() else: # Scan the next line linenum += 1 if linenum >= len(clean_lines.elided): break line = clean_lines.elided[linenum] # Exhausted all remaining lines and still no matching angle bracket. # Most likely the input was incomplete, otherwise we should have # seen a semicolon and returned early. return True
[ "def", "FindNextMatchingAngleBracket", "(", "clean_lines", ",", "linenum", ",", "init_suffix", ")", ":", "line", "=", "init_suffix", "nesting_stack", "=", "[", "'<'", "]", "while", "True", ":", "# Find the next operator that can tell us whether < is used as an", "# openin...
https://github.com/twtygqyy/caffe-augmentation/blob/c76600d247e5132fa5bd89d87bb5df458341fa84/scripts/cpp_lint.py#L2521-L2587
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_windows.py
python
ScrolledWindow_GetClassDefaultAttributes
(*args, **kwargs)
return _windows_.ScrolledWindow_GetClassDefaultAttributes(*args, **kwargs)
ScrolledWindow_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this.
ScrolledWindow_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
[ "ScrolledWindow_GetClassDefaultAttributes", "(", "int", "variant", "=", "WINDOW_VARIANT_NORMAL", ")", "-", ">", "VisualAttributes" ]
def ScrolledWindow_GetClassDefaultAttributes(*args, **kwargs): """ ScrolledWindow_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _windows_.ScrolledWindow_GetClassDefaultAttributes(*args, **kwargs)
[ "def", "ScrolledWindow_GetClassDefaultAttributes", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "ScrolledWindow_GetClassDefaultAttributes", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L334-L349
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
DQM/Integration/scripts/harvesting_tools/cmsHarvester.py
python
CMSHarvester.build_dataset_use_list
(self)
Build a list of datasets to process.
Build a list of datasets to process.
[ "Build", "a", "list", "of", "datasets", "to", "process", "." ]
def build_dataset_use_list(self): """Build a list of datasets to process. """ self.logger.info("Building list of datasets to consider...") input_method = self.input_method["datasets"]["use"] input_name = self.input_name["datasets"]["use"] dataset_names = self.build_dataset_list(input_method, input_name) self.datasets_to_use = dict(list(zip(dataset_names, [None] * len(dataset_names)))) self.logger.info(" found %d dataset(s) to process:" % \ len(dataset_names)) for dataset in dataset_names: self.logger.info(" `%s'" % dataset)
[ "def", "build_dataset_use_list", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Building list of datasets to consider...\"", ")", "input_method", "=", "self", ".", "input_method", "[", "\"datasets\"", "]", "[", "\"use\"", "]", "input_name", "="...
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/DQM/Integration/scripts/harvesting_tools/cmsHarvester.py#L3420-L3437
lighttransport/nanort
74063967336311f54ede5dffdfa242123825033b
deps/cpplint.py
python
CheckForHeaderGuard
(filename, clean_lines, error)
Checks that the file contains a header guard. Logs an error if no #ifndef header guard is present. For other headers, checks that the full pathname is used. Args: filename: The name of the C++ header file. clean_lines: A CleansedLines instance containing the file. error: The function to call with any errors found.
Checks that the file contains a header guard.
[ "Checks", "that", "the", "file", "contains", "a", "header", "guard", "." ]
def CheckForHeaderGuard(filename, clean_lines, error): """Checks that the file contains a header guard. Logs an error if no #ifndef header guard is present. For other headers, checks that the full pathname is used. Args: filename: The name of the C++ header file. clean_lines: A CleansedLines instance containing the file. error: The function to call with any errors found. """ # Don't check for header guards if there are error suppression # comments somewhere in this file. # # Because this is silencing a warning for a nonexistent line, we # only support the very specific NOLINT(build/header_guard) syntax, # and not the general NOLINT or NOLINT(*) syntax. raw_lines = clean_lines.lines_without_raw_strings for i in raw_lines: if Search(r'//\s*NOLINT\(build/header_guard\)', i): return cppvar = GetHeaderGuardCPPVariable(filename) ifndef = '' ifndef_linenum = 0 define = '' endif = '' endif_linenum = 0 for linenum, line in enumerate(raw_lines): linesplit = line.split() if len(linesplit) >= 2: # find the first occurrence of #ifndef and #define, save arg if not ifndef and linesplit[0] == '#ifndef': # set ifndef to the header guard presented on the #ifndef line. ifndef = linesplit[1] ifndef_linenum = linenum if not define and linesplit[0] == '#define': define = linesplit[1] # find the last occurrence of #endif, save entire line if line.startswith('#endif'): endif = line endif_linenum = linenum if not ifndef or not define or ifndef != define: error(filename, 0, 'build/header_guard', 5, 'No #ifndef header guard found, suggested CPP variable is: %s' % cppvar) return # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__ # for backward compatibility. if ifndef != cppvar: error_level = 0 if ifndef != cppvar + '_': error_level = 5 ParseNolintSuppressions(filename, raw_lines[ifndef_linenum], ifndef_linenum, error) error(filename, ifndef_linenum, 'build/header_guard', error_level, '#ifndef header guard has wrong style, please use: %s' % cppvar) # Check for "//" comments on endif line. ParseNolintSuppressions(filename, raw_lines[endif_linenum], endif_linenum, error) match = Match(r'#endif\s*//\s*' + cppvar + r'(_)?\b', endif) if match: if match.group(1) == '_': # Issue low severity warning for deprecated double trailing underscore error(filename, endif_linenum, 'build/header_guard', 0, '#endif line should be "#endif // %s"' % cppvar) return # Didn't find the corresponding "//" comment. If this file does not # contain any "//" comments at all, it could be that the compiler # only wants "/**/" comments, look for those instead. no_single_line_comments = True for i in xrange(1, len(raw_lines) - 1): line = raw_lines[i] if Match(r'^(?:(?:\'(?:\.|[^\'])*\')|(?:"(?:\.|[^"])*")|[^\'"])*//', line): no_single_line_comments = False break if no_single_line_comments: match = Match(r'#endif\s*/\*\s*' + cppvar + r'(_)?\s*\*/', endif) if match: if match.group(1) == '_': # Low severity warning for double trailing underscore error(filename, endif_linenum, 'build/header_guard', 0, '#endif line should be "#endif /* %s */"' % cppvar) return # Didn't find anything error(filename, endif_linenum, 'build/header_guard', 5, '#endif line should be "#endif // %s"' % cppvar)
[ "def", "CheckForHeaderGuard", "(", "filename", ",", "clean_lines", ",", "error", ")", ":", "# Don't check for header guards if there are error suppression", "# comments somewhere in this file.", "#", "# Because this is silencing a warning for a nonexistent line, we", "# only support the ...
https://github.com/lighttransport/nanort/blob/74063967336311f54ede5dffdfa242123825033b/deps/cpplint.py#L1677-L1772
OSGeo/gdal
3748fc4ba4fba727492774b2b908a2130c864a83
swig/python/osgeo/osr.py
python
SpatialReference.SetTMG
(self, *args, **kwargs)
return _osr.SpatialReference_SetTMG(self, *args, **kwargs)
r"""SetTMG(SpatialReference self, double clat, double clong, double fe, double fn) -> OGRErr
r"""SetTMG(SpatialReference self, double clat, double clong, double fe, double fn) -> OGRErr
[ "r", "SetTMG", "(", "SpatialReference", "self", "double", "clat", "double", "clong", "double", "fe", "double", "fn", ")", "-", ">", "OGRErr" ]
def SetTMG(self, *args, **kwargs): r"""SetTMG(SpatialReference self, double clat, double clong, double fe, double fn) -> OGRErr""" return _osr.SpatialReference_SetTMG(self, *args, **kwargs)
[ "def", "SetTMG", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_osr", ".", "SpatialReference_SetTMG", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/osr.py#L686-L688
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/tools/configure.d/nodedownload.py
python
findHash
(dict)
return (None, None, availAlgos)
Find an available hash type.
Find an available hash type.
[ "Find", "an", "available", "hash", "type", "." ]
def findHash(dict): """Find an available hash type.""" # choose from one of these availAlgos = hashlib.algorithms_guaranteed for hashAlgo in availAlgos: if hashAlgo in dict: return (dict[hashAlgo], hashAlgo, availAlgos) # error return (None, None, availAlgos)
[ "def", "findHash", "(", "dict", ")", ":", "# choose from one of these", "availAlgos", "=", "hashlib", ".", "algorithms_guaranteed", "for", "hashAlgo", "in", "availAlgos", ":", "if", "hashAlgo", "in", "dict", ":", "return", "(", "dict", "[", "hashAlgo", "]", ",...
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/configure.d/nodedownload.py#L51-L59
bundy-dns/bundy
3d41934996b82b0cd2fe22dd74d2abc1daba835d
src/bin/bundyctl/bindcmd.py
python
BindCmdInterpreter._get_session_id
(self)
return digest
Generate one session id for the connection.
Generate one session id for the connection.
[ "Generate", "one", "session", "id", "for", "the", "connection", "." ]
def _get_session_id(self): '''Generate one session id for the connection. ''' rand = os.urandom(16) now = time.time() session_id = sha1(("%s%s%s" %(rand, now, socket.gethostname())).encode()) digest = session_id.hexdigest() return digest
[ "def", "_get_session_id", "(", "self", ")", ":", "rand", "=", "os", ".", "urandom", "(", "16", ")", "now", "=", "time", ".", "time", "(", ")", "session_id", "=", "sha1", "(", "(", "\"%s%s%s\"", "%", "(", "rand", ",", "now", ",", "socket", ".", "g...
https://github.com/bundy-dns/bundy/blob/3d41934996b82b0cd2fe22dd74d2abc1daba835d/src/bin/bundyctl/bindcmd.py#L133-L140
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
PyOnDemandOutputWindow.write
(self, text)
Create the output window if needed and write the string to it. If not called in the context of the gui thread then uses CallAfter to do the work there.
Create the output window if needed and write the string to it. If not called in the context of the gui thread then uses CallAfter to do the work there.
[ "Create", "the", "output", "window", "if", "needed", "and", "write", "the", "string", "to", "it", ".", "If", "not", "called", "in", "the", "context", "of", "the", "gui", "thread", "then", "uses", "CallAfter", "to", "do", "the", "work", "there", "." ]
def write(self, text): """ Create the output window if needed and write the string to it. If not called in the context of the gui thread then uses CallAfter to do the work there. """ if self.frame is None: if not wx.Thread_IsMain(): wx.CallAfter(self.CreateOutputWindow, text) else: self.CreateOutputWindow(text) else: if not wx.Thread_IsMain(): wx.CallAfter(self.text.AppendText, text) else: self.text.AppendText(text)
[ "def", "write", "(", "self", ",", "text", ")", ":", "if", "self", ".", "frame", "is", "None", ":", "if", "not", "wx", ".", "Thread_IsMain", "(", ")", ":", "wx", ".", "CallAfter", "(", "self", ".", "CreateOutputWindow", ",", "text", ")", "else", ":"...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L8492-L8507
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/traci/_vehicletype.py
python
VehicleTypeDomain.getSpeedFactor
(self, typeID)
return self._getUniversal(tc.VAR_SPEED_FACTOR, typeID)
getSpeedFactor(string) -> double Returns the speed factor of vehicles of this type.
getSpeedFactor(string) -> double
[ "getSpeedFactor", "(", "string", ")", "-", ">", "double" ]
def getSpeedFactor(self, typeID): """getSpeedFactor(string) -> double Returns the speed factor of vehicles of this type. """ return self._getUniversal(tc.VAR_SPEED_FACTOR, typeID)
[ "def", "getSpeedFactor", "(", "self", ",", "typeID", ")", ":", "return", "self", ".", "_getUniversal", "(", "tc", ".", "VAR_SPEED_FACTOR", ",", "typeID", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_vehicletype.py#L46-L51
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
SizerItem.SetDimension
(*args, **kwargs)
return _core_.SizerItem_SetDimension(*args, **kwargs)
SetDimension(self, Point pos, Size size) Set the position and size of the space allocated for this item by the sizer, and adjust the position and size of the item (window or subsizer) to be within that space taking alignment and borders into account.
SetDimension(self, Point pos, Size size)
[ "SetDimension", "(", "self", "Point", "pos", "Size", "size", ")" ]
def SetDimension(*args, **kwargs): """ SetDimension(self, Point pos, Size size) Set the position and size of the space allocated for this item by the sizer, and adjust the position and size of the item (window or subsizer) to be within that space taking alignment and borders into account. """ return _core_.SizerItem_SetDimension(*args, **kwargs)
[ "def", "SetDimension", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "SizerItem_SetDimension", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L14077-L14086
microsoft/ELL
a1d6bacc37a14879cc025d9be2ba40b1a0632315
tools/utilities/pythonlibs/audio/training/dataset.py
python
Dataset.save
(self, filename)
Save the dataset fo a numpy .npz file
Save the dataset fo a numpy .npz file
[ "Save", "the", "dataset", "fo", "a", "numpy", ".", "npz", "file" ]
def save(self, filename): """ Save the dataset fo a numpy .npz file """ self.file_name = filename np.savez(filename, features=self.features, labels=self.label_names, valid_classes=self.valid_classes, parameters=self.parameters)
[ "def", "save", "(", "self", ",", "filename", ")", ":", "self", ".", "file_name", "=", "filename", "np", ".", "savez", "(", "filename", ",", "features", "=", "self", ".", "features", ",", "labels", "=", "self", ".", "label_names", ",", "valid_classes", ...
https://github.com/microsoft/ELL/blob/a1d6bacc37a14879cc025d9be2ba40b1a0632315/tools/utilities/pythonlibs/audio/training/dataset.py#L74-L78
msftguy/ssh-rd
a5f3a79daeac5844edebf01916c9613563f1c390
_3rd/boost_1_48_0/tools/build/v2/build/feature.py
python
minimize
(properties)
return result
Given an expanded property set, eliminate all redundancy: properties which are elements of other (composite) properties in the set will be eliminated. Non-symmetric properties equal to default values will be eliminated, unless the override a value from some composite property. Implicit properties will be expressed without feature grist, and sub-property values will be expressed as elements joined to the corresponding main property.
Given an expanded property set, eliminate all redundancy: properties which are elements of other (composite) properties in the set will be eliminated. Non-symmetric properties equal to default values will be eliminated, unless the override a value from some composite property. Implicit properties will be expressed without feature grist, and sub-property values will be expressed as elements joined to the corresponding main property.
[ "Given", "an", "expanded", "property", "set", "eliminate", "all", "redundancy", ":", "properties", "which", "are", "elements", "of", "other", "(", "composite", ")", "properties", "in", "the", "set", "will", "be", "eliminated", ".", "Non", "-", "symmetric", "...
def minimize (properties): """ Given an expanded property set, eliminate all redundancy: properties which are elements of other (composite) properties in the set will be eliminated. Non-symmetric properties equal to default values will be eliminated, unless the override a value from some composite property. Implicit properties will be expressed without feature grist, and sub-property values will be expressed as elements joined to the corresponding main property. """ # remove properties implied by composite features components = [] for property in properties: if __composite_properties.has_key (property): components.extend(__composite_properties[property]) properties = b2.util.set.difference (properties, components) # handle subfeatures and implicit features # move subfeatures to the end of the list properties = [p for p in properties if not p.feature().subfeature()] +\ [p for p in properties if p.feature().subfeature()] result = [] while properties: p = properties[0] f = p.feature() # locate all subproperties of $(x[1]) in the property set subproperties = __select_subproperties (p, properties) if subproperties: # reconstitute the joined property name subproperties.sort () joined = b2.build.property.Property(p.feature(), p.value() + '-' + '-'.join ([sp.value() for sp in subproperties])) result.append(joined) properties = b2.util.set.difference(properties[1:], subproperties) else: # eliminate properties whose value is equal to feature's # default and which are not symmetric and which do not # contradict values implied by composite properties. # since all component properties of composites in the set # have been eliminated, any remaining property whose # feature is the same as a component of a composite in the # set must have a non-redundant value. if p.value() != f.default() or f.symmetric(): result.append (p) #\ #or get_grist (fullp) in get_grist (components): # FIXME: restore above properties = properties[1:] return result
[ "def", "minimize", "(", "properties", ")", ":", "# remove properties implied by composite features", "components", "=", "[", "]", "for", "property", "in", "properties", ":", "if", "__composite_properties", ".", "has_key", "(", "property", ")", ":", "components", "."...
https://github.com/msftguy/ssh-rd/blob/a5f3a79daeac5844edebf01916c9613563f1c390/_3rd/boost_1_48_0/tools/build/v2/build/feature.py#L732-L789
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/src/robotsim.py
python
RobotModel.__init__
(self)
__init__(RobotModel self) -> RobotModel
__init__(RobotModel self) -> RobotModel
[ "__init__", "(", "RobotModel", "self", ")", "-", ">", "RobotModel" ]
def __init__(self): """ __init__(RobotModel self) -> RobotModel """ this = _robotsim.new_RobotModel() try: self.this.append(this) except Exception: self.this = this
[ "def", "__init__", "(", "self", ")", ":", "this", "=", "_robotsim", ".", "new_RobotModel", "(", ")", "try", ":", "self", ".", "this", ".", "append", "(", "this", ")", "except", "Exception", ":", "self", ".", "this", "=", "this" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/src/robotsim.py#L4489-L4500
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/pkgutil.py
python
iter_modules
(path=None, prefix='')
Yields (module_loader, name, ispkg) for all submodules on path, or, if path is None, all top-level modules on sys.path. 'path' should be either None or a list of paths to look for modules in. 'prefix' is a string to output on the front of every module name on output.
Yields (module_loader, name, ispkg) for all submodules on path, or, if path is None, all top-level modules on sys.path.
[ "Yields", "(", "module_loader", "name", "ispkg", ")", "for", "all", "submodules", "on", "path", "or", "if", "path", "is", "None", "all", "top", "-", "level", "modules", "on", "sys", ".", "path", "." ]
def iter_modules(path=None, prefix=''): """Yields (module_loader, name, ispkg) for all submodules on path, or, if path is None, all top-level modules on sys.path. 'path' should be either None or a list of paths to look for modules in. 'prefix' is a string to output on the front of every module name on output. """ if path is None: importers = iter_importers() else: importers = map(get_importer, path) yielded = {} for i in importers: for name, ispkg in iter_importer_modules(i, prefix): if name not in yielded: yielded[name] = 1 yield i, name, ispkg
[ "def", "iter_modules", "(", "path", "=", "None", ",", "prefix", "=", "''", ")", ":", "if", "path", "is", "None", ":", "importers", "=", "iter_importers", "(", ")", "else", ":", "importers", "=", "map", "(", "get_importer", ",", "path", ")", "yielded", ...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/pkgutil.py#L129-L150
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/query.py
python
HelpSource.__init__
(self, parent, title, *, menuitem='', filepath='', used_names={}, _htest=False, _utest=False)
Get menu entry and url/local file for Additional Help. User enters a name for the Help resource and a web url or file name. The user can browse for the file.
Get menu entry and url/local file for Additional Help.
[ "Get", "menu", "entry", "and", "url", "/", "local", "file", "for", "Additional", "Help", "." ]
def __init__(self, parent, title, *, menuitem='', filepath='', used_names={}, _htest=False, _utest=False): """Get menu entry and url/local file for Additional Help. User enters a name for the Help resource and a web url or file name. The user can browse for the file. """ self.filepath = filepath message = 'Name for item on Help menu:' super().__init__( parent, title, message, text0=menuitem, used_names=used_names, _htest=_htest, _utest=_utest)
[ "def", "__init__", "(", "self", ",", "parent", ",", "title", ",", "*", ",", "menuitem", "=", "''", ",", "filepath", "=", "''", ",", "used_names", "=", "{", "}", ",", "_htest", "=", "False", ",", "_utest", "=", "False", ")", ":", "self", ".", "fil...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/query.py#L246-L257
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/pyyaml/examples/pygments-lexer/yaml.py
python
set_block_scalar_indent
(TokenClass)
return callback
Set an explicit indentation level for a block scalar.
Set an explicit indentation level for a block scalar.
[ "Set", "an", "explicit", "indentation", "level", "for", "a", "block", "scalar", "." ]
def set_block_scalar_indent(TokenClass): """Set an explicit indentation level for a block scalar.""" def callback(lexer, match, context): text = match.group() context.block_scalar_indent = None if not text: return increment = match.group(1) if increment: current_indent = max(context.indent, 0) increment = int(increment) context.block_scalar_indent = current_indent + increment if text: yield match.start(), TokenClass, text context.pos = match.end() return callback
[ "def", "set_block_scalar_indent", "(", "TokenClass", ")", ":", "def", "callback", "(", "lexer", ",", "match", ",", "context", ")", ":", "text", "=", "match", ".", "group", "(", ")", "context", ".", "block_scalar_indent", "=", "None", "if", "not", "text", ...
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/pyyaml/examples/pygments-lexer/yaml.py#L89-L104
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/dataview.py
python
DataViewCtrl.PrependProgressColumn
(*args, **kwargs)
return _dataview.DataViewCtrl_PrependProgressColumn(*args, **kwargs)
PrependProgressColumn(self, PyObject label_or_bitmap, unsigned int model_column, int mode=DATAVIEW_CELL_INERT, int width=DVC_DEFAULT_WIDTH, int align=ALIGN_CENTER, int flags=DATAVIEW_COL_RESIZABLE) -> DataViewColumn
PrependProgressColumn(self, PyObject label_or_bitmap, unsigned int model_column, int mode=DATAVIEW_CELL_INERT, int width=DVC_DEFAULT_WIDTH, int align=ALIGN_CENTER, int flags=DATAVIEW_COL_RESIZABLE) -> DataViewColumn
[ "PrependProgressColumn", "(", "self", "PyObject", "label_or_bitmap", "unsigned", "int", "model_column", "int", "mode", "=", "DATAVIEW_CELL_INERT", "int", "width", "=", "DVC_DEFAULT_WIDTH", "int", "align", "=", "ALIGN_CENTER", "int", "flags", "=", "DATAVIEW_COL_RESIZABLE...
def PrependProgressColumn(*args, **kwargs): """ PrependProgressColumn(self, PyObject label_or_bitmap, unsigned int model_column, int mode=DATAVIEW_CELL_INERT, int width=DVC_DEFAULT_WIDTH, int align=ALIGN_CENTER, int flags=DATAVIEW_COL_RESIZABLE) -> DataViewColumn """ return _dataview.DataViewCtrl_PrependProgressColumn(*args, **kwargs)
[ "def", "PrependProgressColumn", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_dataview", ".", "DataViewCtrl_PrependProgressColumn", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/dataview.py#L1615-L1621
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/coremodules/simulation/result_oglviewer.py
python
ResultSelectTool.get_optionspanel
(self, parent, size=(200, -1))
return self._optionspanel
Return tool option widgets on given parent
Return tool option widgets on given parent
[ "Return", "tool", "option", "widgets", "on", "given", "parent" ]
def get_optionspanel(self, parent, size=(200, -1)): """ Return tool option widgets on given parent """ # opject panel shows always the option of this tool self._optionspanel = ObjPanel(parent, obj=self, id=None, attrconfigs=None, #tables = None, # table = None, id=None, ids=None, groupnames=['options'], func_change_obj=None, show_groupnames=False, show_title=True, is_modal=False, mainframe=self.parent.get_mainframe(), pos=wx.DefaultPosition, size=size, style=wx.MAXIMIZE_BOX | wx.RESIZE_BORDER, func_apply=self.on_apply_option, immediate_apply=False, panelstyle='default', # 'instrumental' standartbuttons=['apply', 'restore']) return self._optionspanel
[ "def", "get_optionspanel", "(", "self", ",", "parent", ",", "size", "=", "(", "200", ",", "-", "1", ")", ")", ":", "# opject panel shows always the option of this tool", "self", ".", "_optionspanel", "=", "ObjPanel", "(", "parent", ",", "obj", "=", "self", "...
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/coremodules/simulation/result_oglviewer.py#L407-L426
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_misc.py
python
ToolTip_SetReshow
(*args, **kwargs)
return _misc_.ToolTip_SetReshow(*args, **kwargs)
ToolTip_SetReshow(long milliseconds)
ToolTip_SetReshow(long milliseconds)
[ "ToolTip_SetReshow", "(", "long", "milliseconds", ")" ]
def ToolTip_SetReshow(*args, **kwargs): """ToolTip_SetReshow(long milliseconds)""" return _misc_.ToolTip_SetReshow(*args, **kwargs)
[ "def", "ToolTip_SetReshow", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "ToolTip_SetReshow", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L720-L722
rethinkdb/rethinkdb_rebirth
54a76551512bebfe1ab1071d9b19dec2cd9c40e6
packaging/osx/ds_store/store.py
python
DSStore.open
(cls, file_or_name, mode='r+', initial_entries=None)
return DSStore(store)
Open a ``.DS_Store`` file; pass either a Python file object, or a filename in the ``file_or_name`` argument and a file access mode in the ``mode`` argument. If you are creating a new file using the "w" or "w+" modes, you may also specify a list of entries with which to initialise the file.
Open a ``.DS_Store`` file; pass either a Python file object, or a filename in the ``file_or_name`` argument and a file access mode in the ``mode`` argument. If you are creating a new file using the "w" or "w+" modes, you may also specify a list of entries with which to initialise the file.
[ "Open", "a", ".", "DS_Store", "file", ";", "pass", "either", "a", "Python", "file", "object", "or", "a", "filename", "in", "the", "file_or_name", "argument", "and", "a", "file", "access", "mode", "in", "the", "mode", "argument", ".", "If", "you", "are", ...
def open(cls, file_or_name, mode='r+', initial_entries=None): """Open a ``.DS_Store`` file; pass either a Python file object, or a filename in the ``file_or_name`` argument and a file access mode in the ``mode`` argument. If you are creating a new file using the "w" or "w+" modes, you may also specify a list of entries with which to initialise the file.""" store = buddy.Allocator.open(file_or_name, mode) if mode == 'w' or mode == 'w+': superblk = store.allocate(20) store['DSDB'] = superblk page_size = 4096 if not initial_entries: root = store.allocate(page_size) with store.get_block(root) as rootblk: rootblk.zero_fill() with store.get_block(superblk) as s: s.write(b'>IIIII', root, 0, 0, 1, page_size) else: # Make sure they're in sorted order initial_entries = list(initial_entries) initial_entries.sort() # Construct the tree current_level = initial_entries next_level = [] levels = [] ptr_size = 0 node_count = 0 while True: total = 8 nodes = [] node = [] for e in current_level: new_total = total + ptr_size + e.byte_length() if new_total > page_size: nodes.append(node) next_level.append(e) total = 8 node = [] else: total = new_total node.append(e) if node: nodes.append(node) node_count += len(nodes) levels.append(nodes) if len(nodes) == 1: break current_level = next_level next_level = [] ptr_size = 4 # Allocate nodes ptrs = [store.allocate(page_size) for n in range(node_count)] # Generate nodes pointers = [] prev_pointers = None for level in levels: ppndx = 0 lptrs = ptrs[-len(level):] del ptrs[-len(level):] for node in level: ndx = lptrs.pop(0) if prev_pointers is None: with store.get_block(ndx) as block: block.write(b'>II', 0, len(node)) for e in node: e.write(block) else: next_node = prev_pointers[ppndx + len(node)] node_ptrs = prev_pointers[ppndx:ppndx+len(node)] with store.get_block(ndx) as block: block.write(b'>II', next_node, len(node)) for ptr, e in zip(node_ptrs, node): block.write(b'>I', ptr) e.write(block) pointers.append(ndx) prev_pointers = pointers pointers = [] root = prev_pointers[0] with store.get_block(superblk) as s: s.write(b'>IIIII', root, len(levels), len(initial_entries), node_count, page_size) return DSStore(store)
[ "def", "open", "(", "cls", ",", "file_or_name", ",", "mode", "=", "'r+'", ",", "initial_entries", "=", "None", ")", ":", "store", "=", "buddy", ".", "Allocator", ".", "open", "(", "file_or_name", ",", "mode", ")", "if", "mode", "==", "'w'", "or", "mo...
https://github.com/rethinkdb/rethinkdb_rebirth/blob/54a76551512bebfe1ab1071d9b19dec2cd9c40e6/packaging/osx/ds_store/store.py#L283-L379
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
build/toolchain/win/setup_toolchain.py
python
_LoadToolchainEnv
(cpu, sdk_dir)
return _ExtractImportantEnvironment(variables)
Returns a dictionary with environment variables that must be set while running binaries from the toolchain (e.g. INCLUDE and PATH for cl.exe).
Returns a dictionary with environment variables that must be set while running binaries from the toolchain (e.g. INCLUDE and PATH for cl.exe).
[ "Returns", "a", "dictionary", "with", "environment", "variables", "that", "must", "be", "set", "while", "running", "binaries", "from", "the", "toolchain", "(", "e", ".", "g", ".", "INCLUDE", "and", "PATH", "for", "cl", ".", "exe", ")", "." ]
def _LoadToolchainEnv(cpu, sdk_dir): """Returns a dictionary with environment variables that must be set while running binaries from the toolchain (e.g. INCLUDE and PATH for cl.exe).""" # Check if we are running in the SDK command line environment and use # the setup script from the SDK if so. |cpu| should be either # 'x86' or 'x64'. assert cpu in ('x86', 'x64') if bool(int(os.environ.get('DEPOT_TOOLS_WIN_TOOLCHAIN', 1))) and sdk_dir: # Load environment from json file. env = os.path.normpath(os.path.join(sdk_dir, 'bin/SetEnv.%s.json' % cpu)) env = json.load(open(env))['env'] for k in env: entries = [os.path.join(*([os.path.join(sdk_dir, 'bin')] + e)) for e in env[k]] # clang-cl wants INCLUDE to be ;-separated even on non-Windows, # lld-link wants LIB to be ;-separated even on non-Windows. Path gets :. # The separator for INCLUDE here must match the one used in main() below. sep = os.pathsep if k == 'PATH' else ';' env[k] = sep.join(entries) # PATH is a bit of a special case, it's in addition to the current PATH. env['PATH'] = env['PATH'] + os.pathsep + os.environ['PATH'] # Augment with the current env to pick up TEMP and friends. for k in os.environ: if k not in env: env[k] = os.environ[k] varlines = [] for k in sorted(env.keys()): varlines.append('%s=%s' % (str(k), str(env[k]))) variables = '\n'.join(varlines) # Check that the json file contained the same environment as the .cmd file. if sys.platform in ('win32', 'cygwin'): script = os.path.normpath(os.path.join(sdk_dir, 'Bin/SetEnv.cmd')) assert _ExtractImportantEnvironment(variables) == \ _ExtractImportantEnvironment(_LoadEnvFromBat([script, '/' + cpu])) else: if 'GYP_MSVS_OVERRIDE_PATH' not in os.environ: os.environ['GYP_MSVS_OVERRIDE_PATH'] = _DetectVisualStudioPath() # We only support x64-hosted tools. script_path = os.path.normpath(os.path.join( os.environ['GYP_MSVS_OVERRIDE_PATH'], 'VC/vcvarsall.bat')) if not os.path.exists(script_path): raise Exception('%s is missing - make sure VC++ tools are installed.' % script_path) args = [script_path, 'amd64_x86' if cpu == 'x86' else 'amd64'] variables = _LoadEnvFromBat(args) return _ExtractImportantEnvironment(variables)
[ "def", "_LoadToolchainEnv", "(", "cpu", ",", "sdk_dir", ")", ":", "# Check if we are running in the SDK command line environment and use", "# the setup script from the SDK if so. |cpu| should be either", "# 'x86' or 'x64'.", "assert", "cpu", "in", "(", "'x86'", ",", "'x64'", ")",...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/build/toolchain/win/setup_toolchain.py#L84-L132
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/layers/rnn.py
python
TrainingHelper.next_inputs
(self, time, outputs, states, sample_ids)
return finished, next_inputs, states
r""" Generate inputs for the next decoding step by slicing at corresponding step of the full sequence inputs. Simultaneously, produce the states for next time step by directly using the input `states` and emit status telling whether each minibatch entry reaches to the corresponding length. Parameters: time(Variable): An `int64` tensor with shape `[1]` provided by the caller, representing the current time step number of decoding. outputs(Variable): A tensor variable. Usually it's data type is float32 or float64, and it's shape is `[batch_size, vocabulary_size]`, representing the predicted logits of current step. It is same as `outputs` returned by `BasicDecoder.output_fn(BasicDecoder.cell.call())`. states(Variable): A (possibly nested structure of) tensor variable[s]. It is same as `new_states` returned by `BasicDecoder.cell.call()`. sample_ids(Variable): An `int64` tensor variable shaped `[batch_size]`. It is same as `sample_ids` returned by `sample()`. Returns: tuple: A tuple( :code:`(finished, next_inputs, next_states)` ). \ `next_inputs` and `next_states` both are a (possibly nested \ structure of) tensor variable[s], and the tensor's shape is \ `[batch_size, ...]`. `next_states` is identical to the input \ argument `states`. `finished` is a `bool` Tensor with \ shape `[batch_size]`.
r""" Generate inputs for the next decoding step by slicing at corresponding step of the full sequence inputs. Simultaneously, produce the states for next time step by directly using the input `states` and emit status telling whether each minibatch entry reaches to the corresponding length.
[ "r", "Generate", "inputs", "for", "the", "next", "decoding", "step", "by", "slicing", "at", "corresponding", "step", "of", "the", "full", "sequence", "inputs", ".", "Simultaneously", "produce", "the", "states", "for", "next", "time", "step", "by", "directly", ...
def next_inputs(self, time, outputs, states, sample_ids): r""" Generate inputs for the next decoding step by slicing at corresponding step of the full sequence inputs. Simultaneously, produce the states for next time step by directly using the input `states` and emit status telling whether each minibatch entry reaches to the corresponding length. Parameters: time(Variable): An `int64` tensor with shape `[1]` provided by the caller, representing the current time step number of decoding. outputs(Variable): A tensor variable. Usually it's data type is float32 or float64, and it's shape is `[batch_size, vocabulary_size]`, representing the predicted logits of current step. It is same as `outputs` returned by `BasicDecoder.output_fn(BasicDecoder.cell.call())`. states(Variable): A (possibly nested structure of) tensor variable[s]. It is same as `new_states` returned by `BasicDecoder.cell.call()`. sample_ids(Variable): An `int64` tensor variable shaped `[batch_size]`. It is same as `sample_ids` returned by `sample()`. Returns: tuple: A tuple( :code:`(finished, next_inputs, next_states)` ). \ `next_inputs` and `next_states` both are a (possibly nested \ structure of) tensor variable[s], and the tensor's shape is \ `[batch_size, ...]`. `next_states` is identical to the input \ argument `states`. `finished` is a `bool` Tensor with \ shape `[batch_size]`. """ # TODO: compatibility of int32 and int64 time = tensor.cast( time, "int32") if convert_dtype(time.dtype) not in ["int32"] else time if self.sequence_length.dtype != time.dtype: self.sequence_length = tensor.cast(self.sequence_length, time.dtype) next_time = time + 1 finished = control_flow.less_equal(self.sequence_length, next_time) def _slice(x): # TODO: use Variable.__getitem__ axes = [0 if self.time_major else 1] return nn.squeeze( nn.slice( x, axes=axes, starts=[next_time], ends=[next_time + 1]), axes=axes) next_inputs = map_structure(_slice, self.inputs_) return finished, next_inputs, states
[ "def", "next_inputs", "(", "self", ",", "time", ",", "outputs", ",", "states", ",", "sample_ids", ")", ":", "# TODO: compatibility of int32 and int64", "time", "=", "tensor", ".", "cast", "(", "time", ",", "\"int32\"", ")", "if", "convert_dtype", "(", "time", ...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/layers/rnn.py#L1850-L1894
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBThread.GetStopReasonDataAtIndex
(self, idx)
return _lldb.SBThread_GetStopReasonDataAtIndex(self, idx)
GetStopReasonDataAtIndex(SBThread self, uint32_t idx) -> uint64_t Get information associated with a stop reason. Breakpoint stop reasons will have data that consists of pairs of breakpoint IDs followed by the breakpoint location IDs (they always come in pairs). Stop Reason Count Data Type ======================== ===== ========================================= eStopReasonNone 0 eStopReasonTrace 0 eStopReasonBreakpoint N duple: {breakpoint id, location id} eStopReasonWatchpoint 1 watchpoint id eStopReasonSignal 1 unix signal number eStopReasonException N exception data eStopReasonExec 0 eStopReasonPlanComplete 0
GetStopReasonDataAtIndex(SBThread self, uint32_t idx) -> uint64_t
[ "GetStopReasonDataAtIndex", "(", "SBThread", "self", "uint32_t", "idx", ")", "-", ">", "uint64_t" ]
def GetStopReasonDataAtIndex(self, idx): """ GetStopReasonDataAtIndex(SBThread self, uint32_t idx) -> uint64_t Get information associated with a stop reason. Breakpoint stop reasons will have data that consists of pairs of breakpoint IDs followed by the breakpoint location IDs (they always come in pairs). Stop Reason Count Data Type ======================== ===== ========================================= eStopReasonNone 0 eStopReasonTrace 0 eStopReasonBreakpoint N duple: {breakpoint id, location id} eStopReasonWatchpoint 1 watchpoint id eStopReasonSignal 1 unix signal number eStopReasonException N exception data eStopReasonExec 0 eStopReasonPlanComplete 0 """ return _lldb.SBThread_GetStopReasonDataAtIndex(self, idx)
[ "def", "GetStopReasonDataAtIndex", "(", "self", ",", "idx", ")", ":", "return", "_lldb", ".", "SBThread_GetStopReasonDataAtIndex", "(", "self", ",", "idx", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L11532-L11554
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/decimal.py
python
Context.max
(self, a, b)
return a.max(b, context=self)
max compares two values numerically and returns the maximum. If either operand is a NaN then the general rules apply. Otherwise, the operands are compared as though by the compare operation. If they are numerically equal then the left-hand operand is chosen as the result. Otherwise the maximum (closer to positive infinity) of the two operands is chosen as the result. >>> ExtendedContext.max(Decimal('3'), Decimal('2')) Decimal('3') >>> ExtendedContext.max(Decimal('-10'), Decimal('3')) Decimal('3') >>> ExtendedContext.max(Decimal('1.0'), Decimal('1')) Decimal('1') >>> ExtendedContext.max(Decimal('7'), Decimal('NaN')) Decimal('7') >>> ExtendedContext.max(1, 2) Decimal('2') >>> ExtendedContext.max(Decimal(1), 2) Decimal('2') >>> ExtendedContext.max(1, Decimal(2)) Decimal('2')
max compares two values numerically and returns the maximum.
[ "max", "compares", "two", "values", "numerically", "and", "returns", "the", "maximum", "." ]
def max(self, a, b): """max compares two values numerically and returns the maximum. If either operand is a NaN then the general rules apply. Otherwise, the operands are compared as though by the compare operation. If they are numerically equal then the left-hand operand is chosen as the result. Otherwise the maximum (closer to positive infinity) of the two operands is chosen as the result. >>> ExtendedContext.max(Decimal('3'), Decimal('2')) Decimal('3') >>> ExtendedContext.max(Decimal('-10'), Decimal('3')) Decimal('3') >>> ExtendedContext.max(Decimal('1.0'), Decimal('1')) Decimal('1') >>> ExtendedContext.max(Decimal('7'), Decimal('NaN')) Decimal('7') >>> ExtendedContext.max(1, 2) Decimal('2') >>> ExtendedContext.max(Decimal(1), 2) Decimal('2') >>> ExtendedContext.max(1, Decimal(2)) Decimal('2') """ a = _convert_other(a, raiseit=True) return a.max(b, context=self)
[ "def", "max", "(", "self", ",", "a", ",", "b", ")", ":", "a", "=", "_convert_other", "(", "a", ",", "raiseit", "=", "True", ")", "return", "a", ".", "max", "(", "b", ",", "context", "=", "self", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/decimal.py#L4662-L4687
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/deps/v8/tools/clusterfuzz/js_fuzzer/tools/run_one.py
python
list_tests
()
Iterates all fuzz tests and corresponding flags in the given base dir.
Iterates all fuzz tests and corresponding flags in the given base dir.
[ "Iterates", "all", "fuzz", "tests", "and", "corresponding", "flags", "in", "the", "given", "base", "dir", "." ]
def list_tests(): """Iterates all fuzz tests and corresponding flags in the given base dir.""" for f in os.listdir(test_dir): if f.startswith('fuzz'): n = int(re.match(r'fuzz-(\d+)\.js', f).group(1)) ff = 'flags-%d.js' % n yield (os.path.join(test_dir, f), os.path.join(test_dir, ff))
[ "def", "list_tests", "(", ")", ":", "for", "f", "in", "os", ".", "listdir", "(", "test_dir", ")", ":", "if", "f", ".", "startswith", "(", "'fuzz'", ")", ":", "n", "=", "int", "(", "re", ".", "match", "(", "r'fuzz-(\\d+)\\.js'", ",", "f", ")", "."...
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/v8/tools/clusterfuzz/js_fuzzer/tools/run_one.py#L63-L69
facebook/ThreatExchange
31914a51820c73c8a0daffe62ccca29a6e3d359e
python-threatexchange/threatexchange/cli/tag_fetch.py
python
TagFetchCommand.__init__
( self, sample: bool, clear: bool = False, until_timestamp: int = 0, full: bool = False, only_signals: t.Collection[str] = (), not_signals: t.Collection[str] = (), )
Has default arguments because it's called by match command
Has default arguments because it's called by match command
[ "Has", "default", "arguments", "because", "it", "s", "called", "by", "match", "command" ]
def __init__( self, sample: bool, clear: bool = False, until_timestamp: int = 0, full: bool = False, only_signals: t.Collection[str] = (), not_signals: t.Collection[str] = (), ) -> None: """Has default arguments because it's called by match command""" self.sample = sample self.clear = clear now = time.time() self.until_timestamp = min(float(until_timestamp or now), now) self.force_full = full self.force_incremental = bool(until_timestamp) and not full # Cause first print to be after ~5 seconds self.last_update_printed = now - self.PROGRESS_PRINT_INTERVAL_SEC + 5 if only_signals or not_signals: # TODO - this is fixable by storing checkpoints per signal type self.stderr( "Ignoring some signal types will lead to only part of", "the dataset being fetched until fixed with --full.", ) only_signals = only_signals or meta.get_signal_types_by_name() not_signals = not_signals or () self.signal_types_by_name = { name: signal() for name, signal in meta.get_signal_types_by_name().items() if name in only_signals and name not in not_signals }
[ "def", "__init__", "(", "self", ",", "sample", ":", "bool", ",", "clear", ":", "bool", "=", "False", ",", "until_timestamp", ":", "int", "=", "0", ",", "full", ":", "bool", "=", "False", ",", "only_signals", ":", "t", ".", "Collection", "[", "str", ...
https://github.com/facebook/ThreatExchange/blob/31914a51820c73c8a0daffe62ccca29a6e3d359e/python-threatexchange/threatexchange/cli/tag_fetch.py#L116-L149
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/distutils/command/check.py
python
check._check_rst_data
(self, data)
return reporter.messages
Returns warnings when the provided data doesn't compile.
Returns warnings when the provided data doesn't compile.
[ "Returns", "warnings", "when", "the", "provided", "data", "doesn", "t", "compile", "." ]
def _check_rst_data(self, data): """Returns warnings when the provided data doesn't compile.""" source_path = StringIO() parser = Parser() settings = frontend.OptionParser(components=(Parser,)).get_default_values() settings.tab_width = 4 settings.pep_references = None settings.rfc_references = None reporter = SilentReporter(source_path, settings.report_level, settings.halt_level, stream=settings.warning_stream, debug=settings.debug, encoding=settings.error_encoding, error_handler=settings.error_encoding_error_handler) document = nodes.document(settings, reporter, source=source_path) document.note_source(source_path, -1) try: parser.parse(data, document) except AttributeError as e: reporter.messages.append( (-1, 'Could not finish the parsing: %s.' % e, '', {})) return reporter.messages
[ "def", "_check_rst_data", "(", "self", ",", "data", ")", ":", "source_path", "=", "StringIO", "(", ")", "parser", "=", "Parser", "(", ")", "settings", "=", "frontend", ".", "OptionParser", "(", "components", "=", "(", "Parser", ",", ")", ")", ".", "get...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/distutils/command/check.py#L125-L149
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftguitools/gui_trimex.py
python
Trimex.extrude
(self, shift=False, real=False)
return delta.Length
Redraw the ghost in extrude mode.
Redraw the ghost in extrude mode.
[ "Redraw", "the", "ghost", "in", "extrude", "mode", "." ]
def extrude(self, shift=False, real=False): """Redraw the ghost in extrude mode.""" self.newpoint = self.obj.Shape.Faces[0].CenterOfMass dvec = self.point.sub(self.newpoint) if not shift: delta = DraftVecUtils.project(dvec, self.normal) else: delta = dvec if self.force and delta.Length: ratio = self.force/delta.Length delta.multiply(ratio) if real: return delta self.ghost[0].trans.translation.setValue([delta.x, delta.y, delta.z]) for i in range(1, len(self.ghost)): base = self.obj.Shape.Vertexes[i-1].Point self.ghost[i].p1(base) self.ghost[i].p2(base.add(delta)) return delta.Length
[ "def", "extrude", "(", "self", ",", "shift", "=", "False", ",", "real", "=", "False", ")", ":", "self", ".", "newpoint", "=", "self", ".", "obj", ".", "Shape", ".", "Faces", "[", "0", "]", ".", "CenterOfMass", "dvec", "=", "self", ".", "point", "...
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_trimex.py#L242-L260
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
build/android/gyp/util/md5_check.py
python
_Metadata.StringsMd5
(self)
return self._strings_md5
Lazily computes and returns the aggregate md5 of input strings.
Lazily computes and returns the aggregate md5 of input strings.
[ "Lazily", "computes", "and", "returns", "the", "aggregate", "md5", "of", "input", "strings", "." ]
def StringsMd5(self): """Lazily computes and returns the aggregate md5 of input strings.""" if self._strings_md5 is None: self._strings_md5 = _ComputeInlineMd5(self._strings) return self._strings_md5
[ "def", "StringsMd5", "(", "self", ")", ":", "if", "self", ".", "_strings_md5", "is", "None", ":", "self", ".", "_strings_md5", "=", "_ComputeInlineMd5", "(", "self", ".", "_strings", ")", "return", "self", ".", "_strings_md5" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/build/android/gyp/util/md5_check.py#L323-L327
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/aui.py
python
AuiManager.OnHintActivate
(*args, **kwargs)
return _aui.AuiManager_OnHintActivate(*args, **kwargs)
OnHintActivate(self, ActivateEvent event)
OnHintActivate(self, ActivateEvent event)
[ "OnHintActivate", "(", "self", "ActivateEvent", "event", ")" ]
def OnHintActivate(*args, **kwargs): """OnHintActivate(self, ActivateEvent event)""" return _aui.AuiManager_OnHintActivate(*args, **kwargs)
[ "def", "OnHintActivate", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "AuiManager_OnHintActivate", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/aui.py#L731-L733
h0x91b/redis-v8
ac8b9d49701d75bcee3719892a2a6a50b437e47a
redis/deps/v8/tools/grokdump.py
python
InspectionShell.do_lm
(self, arg)
List details for all loaded modules in the minidump. An argument can be passed to limit the output to only those modules that contain the argument as a substring (case insensitive match).
List details for all loaded modules in the minidump. An argument can be passed to limit the output to only those modules that contain the argument as a substring (case insensitive match).
[ "List", "details", "for", "all", "loaded", "modules", "in", "the", "minidump", ".", "An", "argument", "can", "be", "passed", "to", "limit", "the", "output", "to", "only", "those", "modules", "that", "contain", "the", "argument", "as", "a", "substring", "("...
def do_lm(self, arg): """ List details for all loaded modules in the minidump. An argument can be passed to limit the output to only those modules that contain the argument as a substring (case insensitive match). """ for module in self.reader.module_list.modules: if arg: name = GetModuleName(self.reader, module).lower() if name.find(arg.lower()) >= 0: PrintModuleDetails(self.reader, module) else: PrintModuleDetails(self.reader, module) print
[ "def", "do_lm", "(", "self", ",", "arg", ")", ":", "for", "module", "in", "self", ".", "reader", ".", "module_list", ".", "modules", ":", "if", "arg", ":", "name", "=", "GetModuleName", "(", "self", ".", "reader", ",", "module", ")", ".", "lower", ...
https://github.com/h0x91b/redis-v8/blob/ac8b9d49701d75bcee3719892a2a6a50b437e47a/redis/deps/v8/tools/grokdump.py#L1791-L1804
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/llvmlite/ir/builder.py
python
IRBuilder.sub
(self, lhs, rhs, name='')
Integer subtraction: name = lhs - rhs
Integer subtraction: name = lhs - rhs
[ "Integer", "subtraction", ":", "name", "=", "lhs", "-", "rhs" ]
def sub(self, lhs, rhs, name=''): """ Integer subtraction: name = lhs - rhs """
[ "def", "sub", "(", "self", ",", "lhs", ",", "rhs", ",", "name", "=", "''", ")", ":" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/llvmlite/ir/builder.py#L374-L378
intel/llvm
e6d0547e9d99b5a56430c4749f6c7e328bf221ab
libcxx/utils/gdb/libcxx/printers.py
python
StdDequePrinter._calculate_block_size
(self, element_type)
return 4096 / size if size < 256 else 16
Calculates the number of elements in a full block.
Calculates the number of elements in a full block.
[ "Calculates", "the", "number", "of", "elements", "in", "a", "full", "block", "." ]
def _calculate_block_size(self, element_type): """Calculates the number of elements in a full block.""" size = element_type.sizeof # Copied from struct __deque_block_size implementation of libcxx. return 4096 / size if size < 256 else 16
[ "def", "_calculate_block_size", "(", "self", ",", "element_type", ")", ":", "size", "=", "element_type", ".", "sizeof", "# Copied from struct __deque_block_size implementation of libcxx.", "return", "4096", "/", "size", "if", "size", "<", "256", "else", "16" ]
https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/libcxx/utils/gdb/libcxx/printers.py#L459-L463
NVIDIA/DALI
bf16cc86ba8f091b145f91962f21fe1b6aff243d
docs/examples/use_cases/tensorflow/efficientdet/model/utils/postprocess.py
python
batch_map_fn
(map_fn, inputs, *args)
return [tf.stack(y) for y in zip(*outputs)]
Apply map_fn at batch dimension.
Apply map_fn at batch dimension.
[ "Apply", "map_fn", "at", "batch", "dimension", "." ]
def batch_map_fn(map_fn, inputs, *args): """Apply map_fn at batch dimension.""" if isinstance(inputs[0], (list, tuple)): batch_size = len(inputs[0]) else: batch_size = inputs[0].shape.as_list()[0] if not batch_size: # handle dynamic batch size: tf.vectorized_map is faster than tf.map_fn. return tf.vectorized_map(map_fn, inputs, *args) outputs = [] for i in range(batch_size): outputs.append(map_fn([x[i] for x in inputs])) return [tf.stack(y) for y in zip(*outputs)]
[ "def", "batch_map_fn", "(", "map_fn", ",", "inputs", ",", "*", "args", ")", ":", "if", "isinstance", "(", "inputs", "[", "0", "]", ",", "(", "list", ",", "tuple", ")", ")", ":", "batch_size", "=", "len", "(", "inputs", "[", "0", "]", ")", "else",...
https://github.com/NVIDIA/DALI/blob/bf16cc86ba8f091b145f91962f21fe1b6aff243d/docs/examples/use_cases/tensorflow/efficientdet/model/utils/postprocess.py#L35-L49
fatih/subvim
241b6d170597857105da219c9b7d36059e9f11fb
vim/base/YouCompleteMe/third_party/requests/requests/packages/urllib3/connectionpool.py
python
connection_from_url
(url, **kw)
Given a url, return an :class:`.ConnectionPool` instance of its host. This is a shortcut for not having to parse out the scheme, host, and port of the url before creating an :class:`.ConnectionPool` instance. :param url: Absolute URL string that must include the scheme. Port is optional. :param \**kw: Passes additional parameters to the constructor of the appropriate :class:`.ConnectionPool`. Useful for specifying things like timeout, maxsize, headers, etc. Example: :: >>> conn = connection_from_url('http://google.com/') >>> r = conn.request('GET', '/')
Given a url, return an :class:`.ConnectionPool` instance of its host.
[ "Given", "a", "url", "return", "an", ":", "class", ":", ".", "ConnectionPool", "instance", "of", "its", "host", "." ]
def connection_from_url(url, **kw): """ Given a url, return an :class:`.ConnectionPool` instance of its host. This is a shortcut for not having to parse out the scheme, host, and port of the url before creating an :class:`.ConnectionPool` instance. :param url: Absolute URL string that must include the scheme. Port is optional. :param \**kw: Passes additional parameters to the constructor of the appropriate :class:`.ConnectionPool`. Useful for specifying things like timeout, maxsize, headers, etc. Example: :: >>> conn = connection_from_url('http://google.com/') >>> r = conn.request('GET', '/') """ scheme, host, port = get_host(url) if scheme == 'https': return HTTPSConnectionPool(host, port=port, **kw) else: return HTTPConnectionPool(host, port=port, **kw)
[ "def", "connection_from_url", "(", "url", ",", "*", "*", "kw", ")", ":", "scheme", ",", "host", ",", "port", "=", "get_host", "(", "url", ")", "if", "scheme", "==", "'https'", ":", "return", "HTTPSConnectionPool", "(", "host", ",", "port", "=", "port",...
https://github.com/fatih/subvim/blob/241b6d170597857105da219c9b7d36059e9f11fb/vim/base/YouCompleteMe/third_party/requests/requests/packages/urllib3/connectionpool.py#L721-L745
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/llvmlite/six.py
python
_SixMetaPathImporter.get_code
(self, fullname)
return None
Return None Required, if is_package is implemented
Return None
[ "Return", "None" ]
def get_code(self, fullname): """Return None Required, if is_package is implemented""" self.__get_module(fullname) # eventually raises ImportError return None
[ "def", "get_code", "(", "self", ",", "fullname", ")", ":", "self", ".", "__get_module", "(", "fullname", ")", "# eventually raises ImportError", "return", "None" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/llvmlite/six.py#L214-L219
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
SizerFlags.FixedMinSize
(*args, **kwargs)
return _core_.SizerFlags_FixedMinSize(*args, **kwargs)
FixedMinSize(self) -> SizerFlags Sets the wx.FIXED_MINSIZE flag.
FixedMinSize(self) -> SizerFlags
[ "FixedMinSize", "(", "self", ")", "-", ">", "SizerFlags" ]
def FixedMinSize(*args, **kwargs): """ FixedMinSize(self) -> SizerFlags Sets the wx.FIXED_MINSIZE flag. """ return _core_.SizerFlags_FixedMinSize(*args, **kwargs)
[ "def", "FixedMinSize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "SizerFlags_FixedMinSize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L13858-L13864
panda3d/panda3d
833ad89ebad58395d0af0b7ec08538e5e4308265
direct/src/actor/Actor.py
python
Actor.loadModel
(self, modelPath, partName="modelRoot", lodName="lodRoot", copy = True, okMissing = None, autoBindAnims = True)
Actor model loader. Takes a model name (ie file path), a part name(defaults to "modelRoot") and an lod name(defaults to "lodRoot").
Actor model loader. Takes a model name (ie file path), a part name(defaults to "modelRoot") and an lod name(defaults to "lodRoot").
[ "Actor", "model", "loader", ".", "Takes", "a", "model", "name", "(", "ie", "file", "path", ")", "a", "part", "name", "(", "defaults", "to", "modelRoot", ")", "and", "an", "lod", "name", "(", "defaults", "to", "lodRoot", ")", "." ]
def loadModel(self, modelPath, partName="modelRoot", lodName="lodRoot", copy = True, okMissing = None, autoBindAnims = True): """Actor model loader. Takes a model name (ie file path), a part name(defaults to "modelRoot") and an lod name(defaults to "lodRoot"). """ assert partName not in self.__subpartDict assert Actor.notify.debug("in loadModel: %s, part: %s, lod: %s, copy: %s" % \ (modelPath, partName, lodName, copy)) if isinstance(modelPath, NodePath): # If we got a NodePath instead of a string, use *that* as # the model directly. if copy: model = modelPath.copyTo(NodePath()) else: model = modelPath else: # otherwise, we got the name of the model to load. loaderOptions = self.modelLoaderOptions if not copy: # If copy = 0, then we should always hit the disk. loaderOptions = LoaderOptions(loaderOptions) loaderOptions.setFlags(loaderOptions.getFlags() & ~LoaderOptions.LFNoRamCache) if okMissing is not None: if okMissing: loaderOptions.setFlags(loaderOptions.getFlags() & ~LoaderOptions.LFReportErrors) else: loaderOptions.setFlags(loaderOptions.getFlags() | LoaderOptions.LFReportErrors) # Ensure that custom Python loader hooks are initialized. Loader._loadPythonFileTypes() # Pass loaderOptions to specify that we want to # get the skeleton model. This only matters to model # files (like .mb) for which we can choose to extract # either the skeleton or animation, or neither. model = self.loader.loadSync(Filename(modelPath), loaderOptions) if model is not None: model = NodePath(model) if model is None: raise IOError("Could not load Actor model %s" % (modelPath)) if model.node().isOfType(Character.getClassType()): bundleNP = model else: bundleNP = model.find("**/+Character") if bundleNP.isEmpty(): Actor.notify.warning("%s is not a character!" % (modelPath)) model.reparentTo(self.__geomNode) else: # Maybe the model file also included some animations. If # so, try to bind them immediately and put them into the # animControlDict. if autoBindAnims: acc = AnimControlCollection() autoBind(model.node(), acc, ~0) numAnims = acc.getNumAnims() else: numAnims = 0 # Now extract out the Character and integrate it with # the Actor. if lodName != "lodRoot": # parent to appropriate node under LOD switch bundleNP.reparentTo(self.__LODNode.find(str(lodName))) else: bundleNP.reparentTo(self.__geomNode) self.__prepareBundle(bundleNP, model.node(), partName, lodName) # we rename this node to make Actor copying easier bundleNP.node().setName("%s%s"%(Actor.partPrefix,partName)) if numAnims != 0: # If the model had some animations, store them in the # dict so they can be played. Actor.notify.info("model contains %s animations." % (numAnims)) # make sure this lod is in anim control dict if self.mergeLODBundles: lodName = 'common' self.__animControlDict.setdefault(lodName, {}) self.__animControlDict[lodName].setdefault(partName, {}) for i in range(numAnims): animControl = acc.getAnim(i) animName = acc.getAnimName(i) animDef = Actor.AnimDef() animDef.animBundle = animControl.getAnim() animDef.animControl = animControl self.__animControlDict[lodName][partName][animName] = animDef
[ "def", "loadModel", "(", "self", ",", "modelPath", ",", "partName", "=", "\"modelRoot\"", ",", "lodName", "=", "\"lodRoot\"", ",", "copy", "=", "True", ",", "okMissing", "=", "None", ",", "autoBindAnims", "=", "True", ")", ":", "assert", "partName", "not",...
https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/actor/Actor.py#L1877-L1972
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
Image.CanReadStream
(*args, **kwargs)
return _core_.Image_CanReadStream(*args, **kwargs)
CanReadStream(InputStream stream) -> bool Returns True if the image handlers can read an image file from the data currently on the input stream, or a readable Python file-like object.
CanReadStream(InputStream stream) -> bool
[ "CanReadStream", "(", "InputStream", "stream", ")", "-", ">", "bool" ]
def CanReadStream(*args, **kwargs): """ CanReadStream(InputStream stream) -> bool Returns True if the image handlers can read an image file from the data currently on the input stream, or a readable Python file-like object. """ return _core_.Image_CanReadStream(*args, **kwargs)
[ "def", "CanReadStream", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Image_CanReadStream", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L3227-L3235
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/Jinja2/py3/jinja2/compiler.py
python
generate
( node: nodes.Template, environment: "Environment", name: t.Optional[str], filename: t.Optional[str], stream: t.Optional[t.TextIO] = None, defer_init: bool = False, optimized: bool = True, )
return None
Generate the python source for a node tree.
Generate the python source for a node tree.
[ "Generate", "the", "python", "source", "for", "a", "node", "tree", "." ]
def generate( node: nodes.Template, environment: "Environment", name: t.Optional[str], filename: t.Optional[str], stream: t.Optional[t.TextIO] = None, defer_init: bool = False, optimized: bool = True, ) -> t.Optional[str]: """Generate the python source for a node tree.""" if not isinstance(node, nodes.Template): raise TypeError("Can't compile non template nodes") generator = environment.code_generator_class( environment, name, filename, stream, defer_init, optimized ) generator.visit(node) if stream is None: return generator.stream.getvalue() # type: ignore return None
[ "def", "generate", "(", "node", ":", "nodes", ".", "Template", ",", "environment", ":", "\"Environment\"", ",", "name", ":", "t", ".", "Optional", "[", "str", "]", ",", "filename", ":", "t", ".", "Optional", "[", "str", "]", ",", "stream", ":", "t", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py3/jinja2/compiler.py#L101-L122
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TChRet.GetCh
(self)
return _snap.TChRet_GetCh(self)
GetCh(TChRet self) -> char Parameters: self: TChRet *
GetCh(TChRet self) -> char
[ "GetCh", "(", "TChRet", "self", ")", "-", ">", "char" ]
def GetCh(self): """ GetCh(TChRet self) -> char Parameters: self: TChRet * """ return _snap.TChRet_GetCh(self)
[ "def", "GetCh", "(", "self", ")", ":", "return", "_snap", ".", "TChRet_GetCh", "(", "self", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L3206-L3214