nwo
stringlengths
5
86
sha
stringlengths
40
40
path
stringlengths
4
189
language
stringclasses
1 value
identifier
stringlengths
1
94
parameters
stringlengths
2
4.03k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
11.5k
docstring
stringlengths
1
33.2k
docstring_summary
stringlengths
0
5.15k
docstring_tokens
list
function
stringlengths
34
151k
function_tokens
list
url
stringlengths
90
278
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
docs/bin/simplify.py
python
processInsert
(parentNode, insertNode)
Check for pythoncode
Check for pythoncode
[ "Check", "for", "pythoncode" ]
def processInsert(parentNode, insertNode): """ Check for pythoncode """ if getAttr(insertNode, "section") == "python": code = getAttr(insertNode, "code") node = libxml2.newNode("pythoncode") node.addChild(libxml2.newText(code)) parentNode.addChild(node)
[ "def", "processInsert", "(", "parentNode", ",", "insertNode", ")", ":", "if", "getAttr", "(", "insertNode", ",", "\"section\"", ")", "==", "\"python\"", ":", "code", "=", "getAttr", "(", "insertNode", ",", "\"code\"", ")", "node", "=", "libxml2", ".", "new...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/docs/bin/simplify.py#L129-L137
OGRECave/ogre-next
287307980e6de8910f04f3cc0994451b075071fd
Tools/Wings3DExporter/pgon.py
python
Triangulator.find_and_clip_earx
(self)
find clip one ear
find clip one ear
[ "find", "clip", "one", "ear" ]
def find_and_clip_earx(self): "find clip one ear" print self.indices for vert in self.indices: # check if point is convex if self.is_convex(vert): self.dump("%s is convex" % repr(vert)) # check if this vertex is an ear if self.is_ear(vert): self.dump("%s is an ear" % repr(vert)) # found an eartip, remove it self.clip_ear(vert) return else: self.dump("%s is reflex" % repr(vert)) raise ValueError("failed!")
[ "def", "find_and_clip_earx", "(", "self", ")", ":", "print", "self", ".", "indices", "for", "vert", "in", "self", ".", "indices", ":", "# check if point is convex", "if", "self", ".", "is_convex", "(", "vert", ")", ":", "self", ".", "dump", "(", "\"%s is c...
https://github.com/OGRECave/ogre-next/blob/287307980e6de8910f04f3cc0994451b075071fd/Tools/Wings3DExporter/pgon.py#L164-L183
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/client/timeline.py
python
_ChromeTraceFormatter._create_event
(self, ph, category, name, pid, tid, timestamp)
return event
Creates a new Chrome Trace event. For details of the file format, see: https://github.com/catapult-project/catapult/blob/master/tracing/README.md Args: ph: The type of event - usually a single character. category: The event category as a string. name: The event name as a string. pid: Identifier of the process generating this event as an integer. tid: Identifier of the thread generating this event as an integer. timestamp: The timestamp of this event as a long integer. Returns: A JSON compatible event object.
Creates a new Chrome Trace event.
[ "Creates", "a", "new", "Chrome", "Trace", "event", "." ]
def _create_event(self, ph, category, name, pid, tid, timestamp): """Creates a new Chrome Trace event. For details of the file format, see: https://github.com/catapult-project/catapult/blob/master/tracing/README.md Args: ph: The type of event - usually a single character. category: The event category as a string. name: The event name as a string. pid: Identifier of the process generating this event as an integer. tid: Identifier of the thread generating this event as an integer. timestamp: The timestamp of this event as a long integer. Returns: A JSON compatible event object. """ event = {} event['ph'] = ph event['cat'] = category event['name'] = name event['pid'] = pid event['tid'] = tid event['ts'] = timestamp return event
[ "def", "_create_event", "(", "self", ",", "ph", ",", "category", ",", "name", ",", "pid", ",", "tid", ",", "timestamp", ")", ":", "event", "=", "{", "}", "event", "[", "'ph'", "]", "=", "ph", "event", "[", "'cat'", "]", "=", "category", "event", ...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/client/timeline.py#L64-L88
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/saved_model/loader_impl.py
python
SavedModelLoader.get_meta_graph_def_from_tags
(self, tags)
return meta_graph_def_to_load
Return MetaGraphDef with the exact specified tags. Args: tags: A list or set of string tags that identify the MetaGraphDef. Returns: MetaGraphDef with the same tags. Raises: RuntimeError: if no metagraphs were found with the associated tags.
Return MetaGraphDef with the exact specified tags.
[ "Return", "MetaGraphDef", "with", "the", "exact", "specified", "tags", "." ]
def get_meta_graph_def_from_tags(self, tags): """Return MetaGraphDef with the exact specified tags. Args: tags: A list or set of string tags that identify the MetaGraphDef. Returns: MetaGraphDef with the same tags. Raises: RuntimeError: if no metagraphs were found with the associated tags. """ found_match = False available_tags = [] for meta_graph_def in self._saved_model.meta_graphs: available_tags.append(set(meta_graph_def.meta_info_def.tags)) if set(meta_graph_def.meta_info_def.tags) == set(tags): meta_graph_def_to_load = meta_graph_def found_match = True break if not found_match: raise RuntimeError( f"MetaGraphDef associated with tags {str(tags).strip('[]')} " "could not be found in SavedModel, with available tags " f"'{available_tags}'. To inspect available tag-sets in" " the SavedModel, please use the SavedModel CLI: `saved_model_cli`.") return meta_graph_def_to_load
[ "def", "get_meta_graph_def_from_tags", "(", "self", ",", "tags", ")", ":", "found_match", "=", "False", "available_tags", "=", "[", "]", "for", "meta_graph_def", "in", "self", ".", "_saved_model", ".", "meta_graphs", ":", "available_tags", ".", "append", "(", ...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/saved_model/loader_impl.py#L370-L397
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/training/moving_averages.py
python
assign_moving_average
(variable, value, decay, name=None)
Compute the moving average of a variable. The moving average of 'variable' updated with 'value' is: variable * decay + value * (1 - decay) The returned Operation sets 'variable' to the newly computed moving average. The new value of 'variable' can be set with the 'AssignSub' op as: variable -= (1 - decay) * (variable - value) Args: variable: A Variable. value: A tensor with the same shape as 'variable' decay: A float Tensor or float value. The moving average decay. name: Optional name of the returned operation. Returns: An Operation that updates 'variable' with the newly computed moving average.
Compute the moving average of a variable.
[ "Compute", "the", "moving", "average", "of", "a", "variable", "." ]
def assign_moving_average(variable, value, decay, name=None): """Compute the moving average of a variable. The moving average of 'variable' updated with 'value' is: variable * decay + value * (1 - decay) The returned Operation sets 'variable' to the newly computed moving average. The new value of 'variable' can be set with the 'AssignSub' op as: variable -= (1 - decay) * (variable - value) Args: variable: A Variable. value: A tensor with the same shape as 'variable' decay: A float Tensor or float value. The moving average decay. name: Optional name of the returned operation. Returns: An Operation that updates 'variable' with the newly computed moving average. """ with ops.op_scope([variable, value, decay], name, "AssignMovingAvg") as scope: with ops.colocate_with(variable): decay = ops.convert_to_tensor(1.0 - decay, name="decay") if decay.dtype != variable.dtype.base_dtype: decay = math_ops.cast(decay, variable.dtype.base_dtype) return state_ops.assign_sub(variable, (variable - value) * decay, name=scope)
[ "def", "assign_moving_average", "(", "variable", ",", "value", ",", "decay", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "op_scope", "(", "[", "variable", ",", "value", ",", "decay", "]", ",", "name", ",", "\"AssignMovingAvg\"", ")", "as", ...
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/training/moving_averages.py#L32-L60
Tencent/mars
54969ba56b402a622db123e780a4f760b38c5c36
mars/lint/cpplint.py
python
CheckForNonStandardConstructs
(filename, clean_lines, linenum, nesting_state, error)
r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2. Complain about several constructs which gcc-2 accepts, but which are not standard C++. Warning about these in lint is one way to ease the transition to new compilers. - put storage class first (e.g. "static const" instead of "const static"). - "%lld" instead of %qd" in printf-type functions. - "%1$d" is non-standard in printf-type functions. - "\%" is an undefined character escape sequence. - text after #endif is not allowed. - invalid inner-style forward declaration. - >? and <? operators, and their >?= and <?= cousins. Additionally, check for constructor/destructor style violations and reference members, as it is very convenient to do so while checking for gcc-2 compliance. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message
r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
[ "r", "Logs", "an", "error", "if", "we", "see", "certain", "non", "-", "ANSI", "constructs", "ignored", "by", "gcc", "-", "2", "." ]
def CheckForNonStandardConstructs(filename, clean_lines, linenum, nesting_state, error): r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2. Complain about several constructs which gcc-2 accepts, but which are not standard C++. Warning about these in lint is one way to ease the transition to new compilers. - put storage class first (e.g. "static const" instead of "const static"). - "%lld" instead of %qd" in printf-type functions. - "%1$d" is non-standard in printf-type functions. - "\%" is an undefined character escape sequence. - text after #endif is not allowed. - invalid inner-style forward declaration. - >? and <? operators, and their >?= and <?= cousins. Additionally, check for constructor/destructor style violations and reference members, as it is very convenient to do so while checking for gcc-2 compliance. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message """ # Remove comments from the line, but leave in strings for now. line = clean_lines.lines[linenum] if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line): error(filename, linenum, 'runtime/printf_format', 3, '%q in format strings is deprecated. Use %ll instead.') if Search(r'printf\s*\(.*".*%\d+\$', line): error(filename, linenum, 'runtime/printf_format', 2, '%N$ formats are unconventional. Try rewriting to avoid them.') # Remove escaped backslashes before looking for undefined escapes. line = line.replace('\\\\', '') if Search(r'("|\').*\\(%|\[|\(|{)', line): error(filename, linenum, 'build/printf_format', 3, '%, [, (, and { are undefined character escapes. Unescape them.') # For the rest, work with both comments and strings removed. line = clean_lines.elided[linenum] if Search(r'\b(const|volatile|void|char|short|int|long' r'|float|double|signed|unsigned' r'|schar|u?int8|u?int16|u?int32|u?int64)' r'\s+(register|static|extern|typedef)\b', line): error(filename, linenum, 'build/storage_class', 5, 'Storage class (static, extern, typedef, etc) should be first.') if Match(r'\s*#\s*endif\s*[^/\s]+', line): error(filename, linenum, 'build/endif_comment', 5, 'Uncommented text after #endif is non-standard. Use a comment.') if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line): error(filename, linenum, 'build/forward_decl', 5, 'Inner-style forward declarations are invalid. Remove this line.') if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?', line): error(filename, linenum, 'build/deprecated', 3, '>? and <? (max and min) operators are non-standard and deprecated.') if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line): # TODO(unknown): Could it be expanded safely to arbitrary references, # without triggering too many false positives? The first # attempt triggered 5 warnings for mostly benign code in the regtest, hence # the restriction. # Here's the original regexp, for the reference: # type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?' # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;' error(filename, linenum, 'runtime/member_string_references', 2, 'const string& members are dangerous. It is much better to use ' 'alternatives, such as pointers or simple constants.') # Everything else in this function operates on class declarations. # Return early if the top of the nesting stack is not a class, or if # the class head is not completed yet. classinfo = nesting_state.InnermostClass() if not classinfo or not classinfo.seen_open_brace: return # The class may have been declared with namespace or classname qualifiers. # The constructor and destructor will not have those qualifiers. base_classname = classinfo.name.split('::')[-1] # Look for single-argument constructors that aren't marked explicit. # Technically a valid construct, but against style. Also look for # non-single-argument constructors which are also technically valid, but # strongly suggest something is wrong. explicit_constructor_match = Match( r'\s+(?:inline\s+)?(explicit\s+)?(?:inline\s+)?%s\s*' r'\(((?:[^()]|\([^()]*\))*)\)' % re.escape(base_classname), line) if explicit_constructor_match: is_marked_explicit = explicit_constructor_match.group(1) if not explicit_constructor_match.group(2): constructor_args = [] else: constructor_args = explicit_constructor_match.group(2).split(',') # collapse arguments so that commas in template parameter lists and function # argument parameter lists don't split arguments in two i = 0 while i < len(constructor_args): constructor_arg = constructor_args[i] while (constructor_arg.count('<') > constructor_arg.count('>') or constructor_arg.count('(') > constructor_arg.count(')')): constructor_arg += ',' + constructor_args[i + 1] del constructor_args[i + 1] constructor_args[i] = constructor_arg i += 1 defaulted_args = [arg for arg in constructor_args if '=' in arg] noarg_constructor = (not constructor_args or # empty arg list # 'void' arg specifier (len(constructor_args) == 1 and constructor_args[0].strip() == 'void')) onearg_constructor = ((len(constructor_args) == 1 and # exactly one arg not noarg_constructor) or # all but at most one arg defaulted (len(constructor_args) >= 1 and not noarg_constructor and len(defaulted_args) >= len(constructor_args) - 1)) initializer_list_constructor = bool( onearg_constructor and Search(r'\bstd\s*::\s*initializer_list\b', constructor_args[0])) copy_constructor = bool( onearg_constructor and Match(r'(const\s+)?%s(\s*<[^>]*>)?(\s+const)?\s*(?:<\w+>\s*)?&' % re.escape(base_classname), constructor_args[0].strip())) if (not is_marked_explicit and onearg_constructor and not initializer_list_constructor and not copy_constructor): if defaulted_args: error(filename, linenum, 'runtime/explicit', 5, 'Constructors callable with one argument ' 'should be marked explicit.') else: error(filename, linenum, 'runtime/explicit', 5, 'Single-parameter constructors should be marked explicit.') elif is_marked_explicit and not onearg_constructor: if noarg_constructor: error(filename, linenum, 'runtime/explicit', 5, 'Zero-parameter constructors should not be marked explicit.') else: error(filename, linenum, 'runtime/explicit', 0, 'Constructors that require multiple arguments ' 'should not be marked explicit.')
[ "def", "CheckForNonStandardConstructs", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "nesting_state", ",", "error", ")", ":", "# Remove comments from the line, but leave in strings for now.", "line", "=", "clean_lines", ".", "lines", "[", "linenum", "]", "i...
https://github.com/Tencent/mars/blob/54969ba56b402a622db123e780a4f760b38c5c36/mars/lint/cpplint.py#L2578-L2739
luliyucoordinate/Leetcode
96afcdc54807d1d184e881a075d1dbf3371e31fb
src/0349-Intersection-of-Two-Arrays/0349.py
python
Solution.intersection
(self, nums1, nums2)
return list(result)
:type nums1: List[int] :type nums2: List[int] :rtype: List[int]
:type nums1: List[int] :type nums2: List[int] :rtype: List[int]
[ ":", "type", "nums1", ":", "List", "[", "int", "]", ":", "type", "nums2", ":", "List", "[", "int", "]", ":", "rtype", ":", "List", "[", "int", "]" ]
def intersection(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ result = set([i for i in nums1 if i in nums2]) return list(result)
[ "def", "intersection", "(", "self", ",", "nums1", ",", "nums2", ")", ":", "result", "=", "set", "(", "[", "i", "for", "i", "in", "nums1", "if", "i", "in", "nums2", "]", ")", "return", "list", "(", "result", ")" ]
https://github.com/luliyucoordinate/Leetcode/blob/96afcdc54807d1d184e881a075d1dbf3371e31fb/src/0349-Intersection-of-Two-Arrays/0349.py#L2-L9
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/android/loading/controller.py
python
RemoteChromeController.ResetBrowserState
(self)
Override resetting Chrome local state.
Override resetting Chrome local state.
[ "Override", "resetting", "Chrome", "local", "state", "." ]
def ResetBrowserState(self): """Override resetting Chrome local state.""" logging.info('Resetting Chrome local state') package = OPTIONS.ChromePackage().package # Remove the Chrome Profile and the various disk caches. Other parts # theoretically should not affect loading performance. Also remove the tab # state to prevent it from growing infinitely. [:D] for directory in ['app_chrome/Default', 'cache', 'app_chrome/ShaderCache', 'app_tabs']: cmd = ['rm', '-rf', '/data/data/{}/{}'.format(package, directory)] self._device.adb.Shell(subprocess.list2cmdline(cmd))
[ "def", "ResetBrowserState", "(", "self", ")", ":", "logging", ".", "info", "(", "'Resetting Chrome local state'", ")", "package", "=", "OPTIONS", ".", "ChromePackage", "(", ")", ".", "package", "# Remove the Chrome Profile and the various disk caches. Other parts", "# the...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/android/loading/controller.py#L406-L416
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/browser.py
python
transform_children
(child_dict, modname=None)
return obs
Transform a child dictionary to an ordered sequence of objects. The dictionary maps names to pyclbr information objects. Filter out imported objects. Augment class names with bases. The insertion order of the dictionary is assumed to have been in line number order, so sorting is not necessary. The current tree only calls this once per child_dict as it saves TreeItems once created. A future tree and tests might violate this, so a check prevents multiple in-place augmentations.
Transform a child dictionary to an ordered sequence of objects.
[ "Transform", "a", "child", "dictionary", "to", "an", "ordered", "sequence", "of", "objects", "." ]
def transform_children(child_dict, modname=None): """Transform a child dictionary to an ordered sequence of objects. The dictionary maps names to pyclbr information objects. Filter out imported objects. Augment class names with bases. The insertion order of the dictionary is assumed to have been in line number order, so sorting is not necessary. The current tree only calls this once per child_dict as it saves TreeItems once created. A future tree and tests might violate this, so a check prevents multiple in-place augmentations. """ obs = [] # Use list since values should already be sorted. for key, obj in child_dict.items(): if modname is None or obj.module == modname: if hasattr(obj, 'super') and obj.super and obj.name == key: # If obj.name != key, it has already been suffixed. supers = [] for sup in obj.super: if type(sup) is type(''): sname = sup else: sname = sup.name if sup.module != obj.module: sname = f'{sup.module}.{sname}' supers.append(sname) obj.name += '({})'.format(', '.join(supers)) obs.append(obj) return obs
[ "def", "transform_children", "(", "child_dict", ",", "modname", "=", "None", ")", ":", "obs", "=", "[", "]", "# Use list since values should already be sorted.", "for", "key", ",", "obj", "in", "child_dict", ".", "items", "(", ")", ":", "if", "modname", "is", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/browser.py#L26-L55
SequoiaDB/SequoiaDB
2894ed7e5bd6fe57330afc900cf76d0ff0df9f64
tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py
python
xmlNode.xincludeProcessTreeFlags
(self, flags)
return ret
Implement the XInclude substitution for the given subtree
Implement the XInclude substitution for the given subtree
[ "Implement", "the", "XInclude", "substitution", "for", "the", "given", "subtree" ]
def xincludeProcessTreeFlags(self, flags): """Implement the XInclude substitution for the given subtree """ ret = libxml2mod.xmlXIncludeProcessTreeFlags(self._o, flags) return ret
[ "def", "xincludeProcessTreeFlags", "(", "self", ",", "flags", ")", ":", "ret", "=", "libxml2mod", ".", "xmlXIncludeProcessTreeFlags", "(", "self", ".", "_o", ",", "flags", ")", "return", "ret" ]
https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L3637-L3640
facebookresearch/ELF
1f790173095cd910976d9f651b80beb872ec5d12
rts/engine/.ropeproject/config.py
python
project_opened
(project)
This function is called after opening the project
This function is called after opening the project
[ "This", "function", "is", "called", "after", "opening", "the", "project" ]
def project_opened(project): """This function is called after opening the project"""
[ "def", "project_opened", "(", "project", ")", ":" ]
https://github.com/facebookresearch/ELF/blob/1f790173095cd910976d9f651b80beb872ec5d12/rts/engine/.ropeproject/config.py#L101-L102
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/site_compare/operators/equals_with_mask.py
python
Compare
(file1, file2, **kwargs)
Compares two images to see if they're identical subject to a mask. An optional directory containing masks is supplied. If a mask exists which matches file1's name, areas under the mask where it's black are ignored. Args: file1: path to first image to compare file2: path to second image to compare kwargs: ["maskdir"] contains the directory holding the masks Returns: None if the images are identical A tuple of (errorstring, image) if they're not
Compares two images to see if they're identical subject to a mask.
[ "Compares", "two", "images", "to", "see", "if", "they", "re", "identical", "subject", "to", "a", "mask", "." ]
def Compare(file1, file2, **kwargs): """Compares two images to see if they're identical subject to a mask. An optional directory containing masks is supplied. If a mask exists which matches file1's name, areas under the mask where it's black are ignored. Args: file1: path to first image to compare file2: path to second image to compare kwargs: ["maskdir"] contains the directory holding the masks Returns: None if the images are identical A tuple of (errorstring, image) if they're not """ maskdir = None if "maskdir" in kwargs: maskdir = kwargs["maskdir"] im1 = Image.open(file1) im2 = Image.open(file2) if im1.size != im2.size: return ("The images are of different size (%r vs %r)" % (im1.size, im2.size), im1) diff = ImageChops.difference(im1, im2) if maskdir: maskfile = os.path.join(maskdir, os.path.basename(file1)) if os.path.exists(maskfile): mask = Image.open(maskfile) if mask.size != im1.size: return ("The mask is of a different size than the images (%r vs %r)" % (mask.size, im1.size), mask) diff = ImageChops.multiply(diff, mask.convert(diff.mode)) if max(diff.getextrema()) != (0, 0): return ("The images differ", diff) else: return None
[ "def", "Compare", "(", "file1", ",", "file2", ",", "*", "*", "kwargs", ")", ":", "maskdir", "=", "None", "if", "\"maskdir\"", "in", "kwargs", ":", "maskdir", "=", "kwargs", "[", "\"maskdir\"", "]", "im1", "=", "Image", ".", "open", "(", "file1", ")",...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/site_compare/operators/equals_with_mask.py#L13-L57
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/sql.py
python
_wrap_result
(data, columns, index_col=None, coerce_float=True, parse_dates=None)
return frame
Wrap result set of query in a DataFrame.
Wrap result set of query in a DataFrame.
[ "Wrap", "result", "set", "of", "query", "in", "a", "DataFrame", "." ]
def _wrap_result(data, columns, index_col=None, coerce_float=True, parse_dates=None): """Wrap result set of query in a DataFrame.""" frame = DataFrame.from_records(data, columns=columns, coerce_float=coerce_float) frame = _parse_date_columns(frame, parse_dates) if index_col is not None: frame.set_index(index_col, inplace=True) return frame
[ "def", "_wrap_result", "(", "data", ",", "columns", ",", "index_col", "=", "None", ",", "coerce_float", "=", "True", ",", "parse_dates", "=", "None", ")", ":", "frame", "=", "DataFrame", ".", "from_records", "(", "data", ",", "columns", "=", "columns", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/sql.py#L121-L131
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/distribute/input_lib.py
python
MultiStepContext.__init__
(self)
Initialize an output context. Returns: A context object.
Initialize an output context.
[ "Initialize", "an", "output", "context", "." ]
def __init__(self): """Initialize an output context. Returns: A context object. """ self._last_step_outputs = {} self._last_step_outputs_reduce_ops = {} self._non_tensor_outputs = {}
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "_last_step_outputs", "=", "{", "}", "self", ".", "_last_step_outputs_reduce_ops", "=", "{", "}", "self", ".", "_non_tensor_outputs", "=", "{", "}" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/distribute/input_lib.py#L1927-L1935
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/profiler/parser/memory_usage_parser.py
python
MemoryUsageParser.write_memory_files
(self)
Write memory files.
Write memory files.
[ "Write", "memory", "files", "." ]
def write_memory_files(self): """Write memory files.""" logger.info('Start recording memory data into files...') # write memory summary to json file summary_filename = self._summary_filename.format(self._device_id) self._write_memory_files(summary_filename, self._mem_summary) # write memory details to json file details_filename = self._details_filename.format(self._device_id) self._write_memory_files(details_filename, self._graphs_dict) logger.info('Successfully write memory data into files.')
[ "def", "write_memory_files", "(", "self", ")", ":", "logger", ".", "info", "(", "'Start recording memory data into files...'", ")", "# write memory summary to json file", "summary_filename", "=", "self", ".", "_summary_filename", ".", "format", "(", "self", ".", "_devic...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/profiler/parser/memory_usage_parser.py#L145-L155
JarveeLee/SynthText_Chinese_version
4b2cbc7d14741f21d0bb17966a339ab3574b09a8
poisson_reconstruct.py
python
get_laplacian
(Dx,Dy)
return Dxx+Dyy
return the laplacian
return the laplacian
[ "return", "the", "laplacian" ]
def get_laplacian(Dx,Dy): """ return the laplacian """ [H,W] = Dx.shape Dxx, Dyy = np.zeros((H,W)), np.zeros((H,W)) j,k = np.atleast_2d(np.arange(0,H-1)).T, np.arange(0,W-1) Dxx[j,k+1] = Dx[j,k+1] - Dx[j,k] Dyy[j+1,k] = Dy[j+1,k] - Dy[j,k] return Dxx+Dyy
[ "def", "get_laplacian", "(", "Dx", ",", "Dy", ")", ":", "[", "H", ",", "W", "]", "=", "Dx", ".", "shape", "Dxx", ",", "Dyy", "=", "np", ".", "zeros", "(", "(", "H", ",", "W", ")", ")", ",", "np", ".", "zeros", "(", "(", "H", ",", "W", "...
https://github.com/JarveeLee/SynthText_Chinese_version/blob/4b2cbc7d14741f21d0bb17966a339ab3574b09a8/poisson_reconstruct.py#L44-L53
esphome/esphome
40e06c9819f17409615d4f4eec5cfe4dc9a3776d
esphome/config_validation.py
python
subscribe_topic
(value)
return value
Validate that we can subscribe using this MQTT topic.
Validate that we can subscribe using this MQTT topic.
[ "Validate", "that", "we", "can", "subscribe", "using", "this", "MQTT", "topic", "." ]
def subscribe_topic(value): """Validate that we can subscribe using this MQTT topic.""" value = _valid_topic(value) for i in (i for i, c in enumerate(value) if c == "+"): if (i > 0 and value[i - 1] != "/") or ( i < len(value) - 1 and value[i + 1] != "/" ): raise Invalid( "Single-level wildcard must occupy an entire " "level of the filter" ) index = value.find("#") if index != -1: if index != len(value) - 1: # If there are multiple wildcards, this will also trigger raise Invalid( "Multi-level wildcard must be the last " "character in the topic filter." ) if len(value) > 1 and value[index - 1] != "/": raise Invalid( "Multi-level wildcard must be after a topic " "level separator." ) return value
[ "def", "subscribe_topic", "(", "value", ")", ":", "value", "=", "_valid_topic", "(", "value", ")", "for", "i", "in", "(", "i", "for", "i", ",", "c", "in", "enumerate", "(", "value", ")", "if", "c", "==", "\"+\"", ")", ":", "if", "(", "i", ">", ...
https://github.com/esphome/esphome/blob/40e06c9819f17409615d4f4eec5cfe4dc9a3776d/esphome/config_validation.py#L991-L1015
ispc/ispc
0a7ee59b6ec50e54d545eb2a31056e54c4891d51
utils/lit/lit/util.py
python
listdir_files
(dirname, suffixes=None, exclude_filenames=None)
Yields files in a directory. Filenames that are not excluded by rules below are yielded one at a time, as basenames (i.e., without dirname). Files starting with '.' are always skipped. If 'suffixes' is not None, then only filenames ending with one of its members will be yielded. These can be extensions, like '.exe', or strings, like 'Test'. (It is a lexicographic check; so an empty sequence will yield nothing, but a single empty string will yield all filenames.) If 'exclude_filenames' is not None, then none of the file basenames in it will be yielded. If specified, the containers for 'suffixes' and 'exclude_filenames' must support membership checking for strs. Args: dirname: a directory path. suffixes: (optional) a sequence of strings (set, list, etc.). exclude_filenames: (optional) a sequence of strings. Yields: Filenames as returned by os.listdir (generally, str).
Yields files in a directory.
[ "Yields", "files", "in", "a", "directory", "." ]
def listdir_files(dirname, suffixes=None, exclude_filenames=None): """Yields files in a directory. Filenames that are not excluded by rules below are yielded one at a time, as basenames (i.e., without dirname). Files starting with '.' are always skipped. If 'suffixes' is not None, then only filenames ending with one of its members will be yielded. These can be extensions, like '.exe', or strings, like 'Test'. (It is a lexicographic check; so an empty sequence will yield nothing, but a single empty string will yield all filenames.) If 'exclude_filenames' is not None, then none of the file basenames in it will be yielded. If specified, the containers for 'suffixes' and 'exclude_filenames' must support membership checking for strs. Args: dirname: a directory path. suffixes: (optional) a sequence of strings (set, list, etc.). exclude_filenames: (optional) a sequence of strings. Yields: Filenames as returned by os.listdir (generally, str). """ if exclude_filenames is None: exclude_filenames = set() if suffixes is None: suffixes = {''} for filename in os.listdir(dirname): if (os.path.isdir(os.path.join(dirname, filename)) or filename.startswith('.') or filename in exclude_filenames or not any(filename.endswith(sfx) for sfx in suffixes)): continue yield filename
[ "def", "listdir_files", "(", "dirname", ",", "suffixes", "=", "None", ",", "exclude_filenames", "=", "None", ")", ":", "if", "exclude_filenames", "is", "None", ":", "exclude_filenames", "=", "set", "(", ")", "if", "suffixes", "is", "None", ":", "suffixes", ...
https://github.com/ispc/ispc/blob/0a7ee59b6ec50e54d545eb2a31056e54c4891d51/utils/lit/lit/util.py#L148-L186
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/linalg_grad.py
python
_EigGrad
(op, grad_e, grad_v)
Gradient for Eig. Based on eq. 4.77 from paper by Christoph Boeddeker et al. https://arxiv.org/abs/1701.00392 See also "Computation of eigenvalue and eigenvector derivatives for a general complex-valued eigensystem" by Nico van der Aa. As for now only distinct eigenvalue case is considered.
Gradient for Eig.
[ "Gradient", "for", "Eig", "." ]
def _EigGrad(op, grad_e, grad_v): """Gradient for Eig. Based on eq. 4.77 from paper by Christoph Boeddeker et al. https://arxiv.org/abs/1701.00392 See also "Computation of eigenvalue and eigenvector derivatives for a general complex-valued eigensystem" by Nico van der Aa. As for now only distinct eigenvalue case is considered. """ e = op.outputs[0] compute_v = op.get_attr("compute_v") # a = op.inputs[0], which satisfies # a[...,:,:] * v[...,:,i] = e[...,i] * v[...,i] with ops.control_dependencies([grad_e, grad_v]): if compute_v: v = op.outputs[1] vt = _linalg.adjoint(v) # Construct the matrix f(i,j) = (i != j ? 1 / (e_i - e_j) : 0). # Notice that because of the term involving f, the gradient becomes # infinite (or NaN in practice) when eigenvalues are not unique. # Mathematically this should not be surprising, since for (k-fold) # degenerate eigenvalues, the corresponding eigenvectors are only defined # up to arbitrary rotation in a (k-dimensional) subspace. f = array_ops.matrix_set_diag( _SafeReciprocal( array_ops.expand_dims(e, -2) - array_ops.expand_dims(e, -1)), array_ops.zeros_like(e)) f = math_ops.conj(f) vgv = math_ops.matmul(vt, grad_v) mid = array_ops.matrix_diag(grad_e) diag_grad_part = array_ops.matrix_diag( array_ops.matrix_diag_part( math_ops.cast(math_ops.real(vgv), vgv.dtype))) mid += f * (vgv - math_ops.matmul(math_ops.matmul(vt, v), diag_grad_part)) # vt is formally invertible as long as the original matrix is # diagonalizable. However, in practice, vt may # be ill-conditioned when matrix original matrix is close to # non-diagonalizable one grad_a = linalg_ops.matrix_solve(vt, math_ops.matmul(mid, vt)) else: _, v = linalg_ops.eig(op.inputs[0]) vt = _linalg.adjoint(v) # vt is formally invertible as long as the original matrix is # diagonalizable. However, in practice, vt may # be ill-conditioned when matrix original matrix is close to # non-diagonalizable one grad_a = linalg_ops.matrix_solve( vt, math_ops.matmul(array_ops.matrix_diag(grad_e), vt)) return math_ops.cast(grad_a, op.inputs[0].dtype)
[ "def", "_EigGrad", "(", "op", ",", "grad_e", ",", "grad_v", ")", ":", "e", "=", "op", ".", "outputs", "[", "0", "]", "compute_v", "=", "op", ".", "get_attr", "(", "\"compute_v\"", ")", "# a = op.inputs[0], which satisfies", "# a[...,:,:] * v[...,:,i] = e[...,i] ...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/linalg_grad.py#L717-L767
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/oldnumeric/ma.py
python
masked_inside
(x, v1, v2, copy=1)
return array(d, mask = m, copy=copy)
x with mask of all values of x that are inside [v1,v2] v1 and v2 can be given in either order.
x with mask of all values of x that are inside [v1,v2] v1 and v2 can be given in either order.
[ "x", "with", "mask", "of", "all", "values", "of", "x", "that", "are", "inside", "[", "v1", "v2", "]", "v1", "and", "v2", "can", "be", "given", "in", "either", "order", "." ]
def masked_inside(x, v1, v2, copy=1): """x with mask of all values of x that are inside [v1,v2] v1 and v2 can be given in either order. """ if v2 < v1: t = v2 v2 = v1 v1 = t d = filled(x, 0) c = umath.logical_and(umath.less_equal(d, v2), umath.greater_equal(d, v1)) m = mask_or(c, getmask(x)) return array(d, mask = m, copy=copy)
[ "def", "masked_inside", "(", "x", ",", "v1", ",", "v2", ",", "copy", "=", "1", ")", ":", "if", "v2", "<", "v1", ":", "t", "=", "v2", "v2", "=", "v1", "v1", "=", "t", "d", "=", "filled", "(", "x", ",", "0", ")", "c", "=", "umath", ".", "...
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/oldnumeric/ma.py#L1811-L1822
OpenChemistry/tomviz
0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a
tomviz/python/tomviz/io/ser.py
python
read_emi
(filename)
return _emi
Read the meta data from an emi file. Parameters ---------- filename: str or pathlib.Path Path to the emi file. Returns ------- : dict Dictionary of experimental metadata stored in the EMI file.
Read the meta data from an emi file.
[ "Read", "the", "meta", "data", "from", "an", "emi", "file", "." ]
def read_emi(filename): """Read the meta data from an emi file. Parameters ---------- filename: str or pathlib.Path Path to the emi file. Returns ------- : dict Dictionary of experimental metadata stored in the EMI file. """ # check filename type if isinstance(filename, str): pass elif isinstance(filename, Path): filename = str(filename) else: raise TypeError('Filename is supposed to be a string or pathlib.Path') # try opening the file try: # open file for reading bytes, as binary and text are intermixed with open(filename, 'rb') as f_emi: emi_data = f_emi.read() except IOError: print('Error reading file: "{}"'.format(filename)) raise except Exception: raise # dict to store _emi stuff _emi = {} # need anything readable from <ObjectInfo> to </ObjectInfo> # collect = False # data = b'' # for line in f_emi: # if b'<ObjectInfo>' in line: # collect = True # if collect: # data += line.strip() # if b'</ObjectInfo>' in line: # collect = False # close the file # f_emi.close() metaStart = emi_data.find(b'<ObjectInfo>') metaEnd = emi_data.find(b'</ObjectInfo>') # need to add len('</ObjectInfo>') = 13 to encompass this final tag root = ET.fromstring(emi_data[metaStart:metaEnd + 13]) # strip of binary stuff still around # data = data.decode('ascii', errors='ignore') # matchObj = re.search('<ObjectInfo>(.+?)</ObjectInfo', data) # try: # data = matchObj.group(1) # except: # raise RuntimeError('Could not find _emi metadata in specified file.') # parse metadata as xml # root = ET.fromstring('<_emi>' + data + '</_emi>') # single items _emi['Uuid'] = root.findtext('Uuid') _emi['AcquireDate'] = root.findtext('AcquireDate') _emi['Manufacturer'] = root.findtext('Manufacturer') _emi['DetectorPixelHeight'] = root.findtext('DetectorPixelHeight') _emi['DetectorPixelWidth'] = root.findtext('DetectorPixelWidth') # Microscope Conditions grp = root.find('ExperimentalConditions/MicroscopeConditions') for elem in grp: _emi[elem.tag] = _parseEntry_emi(elem.text) # Experimental Description grp = root.find('ExperimentalDescription/Root') for elem in grp: _emi['{} [{}]'.format(elem.findtext('Label'), elem.findtext('Unit'))] = _parseEntry_emi( elem.findtext('Value')) # AcquireInfo grp = root.find('AcquireInfo') for elem in grp: _emi[elem.tag] = _parseEntry_emi(elem.text) # DetectorRange grp = root.find('DetectorRange') for elem in grp: _emi['DetectorRange_' + elem.tag] = _parseEntry_emi(elem.text) return _emi
[ "def", "read_emi", "(", "filename", ")", ":", "# check filename type", "if", "isinstance", "(", "filename", ",", "str", ")", ":", "pass", "elif", "isinstance", "(", "filename", ",", "Path", ")", ":", "filename", "=", "str", "(", "filename", ")", "else", ...
https://github.com/OpenChemistry/tomviz/blob/0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a/tomviz/python/tomviz/io/ser.py#L585-L685
abforce/xposed_art_n
ec3fbe417d74d4664cec053d91dd4e3881176374
tools/cpplint.py
python
CheckSpacing
(filename, clean_lines, linenum, nesting_state, error)
Checks for the correctness of various spacing issues in the code. Things we check for: spaces around operators, spaces after if/for/while/switch, no spaces around parens in function calls, two spaces between code and comment, don't start a block with a blank line, don't end a function with a blank line, don't add a blank line after public/protected/private, don't have too many blank lines in a row. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found.
Checks for the correctness of various spacing issues in the code.
[ "Checks", "for", "the", "correctness", "of", "various", "spacing", "issues", "in", "the", "code", "." ]
def CheckSpacing(filename, clean_lines, linenum, nesting_state, error): """Checks for the correctness of various spacing issues in the code. Things we check for: spaces around operators, spaces after if/for/while/switch, no spaces around parens in function calls, two spaces between code and comment, don't start a block with a blank line, don't end a function with a blank line, don't add a blank line after public/protected/private, don't have too many blank lines in a row. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ raw = clean_lines.raw_lines line = raw[linenum] # Before nixing comments, check if the line is blank for no good # reason. This includes the first line after a block is opened, and # blank lines at the end of a function (ie, right before a line like '}' # # Skip all the blank line checks if we are immediately inside a # namespace body. In other words, don't issue blank line warnings # for this block: # namespace { # # } # # A warning about missing end of namespace comments will be issued instead. if IsBlankLine(line) and not nesting_state.InNamespaceBody(): elided = clean_lines.elided prev_line = elided[linenum - 1] prevbrace = prev_line.rfind('{') # TODO(unknown): Don't complain if line before blank line, and line after, # both start with alnums and are indented the same amount. # This ignores whitespace at the start of a namespace block # because those are not usually indented. if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1: # OK, we have a blank line at the start of a code block. Before we # complain, we check if it is an exception to the rule: The previous # non-empty line has the parameters of a function header that are indented # 4 spaces (because they did not fit in a 80 column line when placed on # the same line as the function name). We also check for the case where # the previous line is indented 6 spaces, which may happen when the # initializers of a constructor do not fit into a 80 column line. exception = False if Match(r' {6}\w', prev_line): # Initializer list? # We are looking for the opening column of initializer list, which # should be indented 4 spaces to cause 6 space indentation afterwards. search_position = linenum-2 while (search_position >= 0 and Match(r' {6}\w', elided[search_position])): search_position -= 1 exception = (search_position >= 0 and elided[search_position][:5] == ' :') else: # Search for the function arguments or an initializer list. We use a # simple heuristic here: If the line is indented 4 spaces; and we have a # closing paren, without the opening paren, followed by an opening brace # or colon (for initializer lists) we assume that it is the last line of # a function header. If we have a colon indented 4 spaces, it is an # initializer list. exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)', prev_line) or Match(r' {4}:', prev_line)) if not exception: error(filename, linenum, 'whitespace/blank_line', 2, 'Blank line at the start of a code block. Is this needed?') # Ignore blank lines at the end of a block in a long if-else # chain, like this: # if (condition1) { # // Something followed by a blank line # # } else if (condition2) { # // Something else # } if linenum + 1 < clean_lines.NumLines(): next_line = raw[linenum + 1] if (next_line and Match(r'\s*}', next_line) and next_line.find('} else ') == -1): error(filename, linenum, 'whitespace/blank_line', 3, 'Blank line at the end of a code block. Is this needed?') matched = Match(r'\s*(public|protected|private):', prev_line) if matched: error(filename, linenum, 'whitespace/blank_line', 3, 'Do not leave a blank line after "%s:"' % matched.group(1)) # Next, we complain if there's a comment too near the text commentpos = line.find('//') if commentpos != -1: # Check if the // may be in quotes. If so, ignore it # Comparisons made explicit for clarity -- pylint: disable-msg=C6403 if (line.count('"', 0, commentpos) - line.count('\\"', 0, commentpos)) % 2 == 0: # not in quotes # Allow one space for new scopes, two spaces otherwise: if (not Match(r'^\s*{ //', line) and ((commentpos >= 1 and line[commentpos-1] not in string.whitespace) or (commentpos >= 2 and line[commentpos-2] not in string.whitespace))): error(filename, linenum, 'whitespace/comments', 2, 'At least two spaces is best between code and comments') # There should always be a space between the // and the comment commentend = commentpos + 2 if commentend < len(line) and not line[commentend] == ' ': # but some lines are exceptions -- e.g. if they're big # comment delimiters like: # //---------------------------------------------------------- # or are an empty C++ style Doxygen comment, like: # /// # or they begin with multiple slashes followed by a space: # //////// Header comment match = (Search(r'[=/-]{4,}\s*$', line[commentend:]) or Search(r'^/$', line[commentend:]) or Search(r'^/+ ', line[commentend:])) if not match: error(filename, linenum, 'whitespace/comments', 4, 'Should have a space between // and comment') CheckComment(line[commentpos:], filename, linenum, error) line = clean_lines.elided[linenum] # get rid of comments and strings # Don't try to do spacing checks for operator methods line = re.sub(r'operator(==|!=|<|<<|<=|>=|>>|>)\(', 'operator\(', line) # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )". # Otherwise not. Note we only check for non-spaces on *both* sides; # sometimes people put non-spaces on one side when aligning ='s among # many lines (not that this is behavior that I approve of...) if Search(r'[\w.]=[\w.]', line) and not Search(r'\b(if|while) ', line): error(filename, linenum, 'whitespace/operators', 4, 'Missing spaces around =') # It's ok not to have spaces around binary operators like + - * /, but if # there's too little whitespace, we get concerned. It's hard to tell, # though, so we punt on this one for now. TODO. # You should always have whitespace around binary operators. # # Check <= and >= first to avoid false positives with < and >, then # check non-include lines for spacing around < and >. match = Search(r'[^<>=!\s](==|!=|<=|>=)[^<>=!\s]', line) if match: error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around %s' % match.group(1)) # We allow no-spaces around << when used like this: 10<<20, but # not otherwise (particularly, not when used as streams) match = Search(r'(\S)(?:L|UL|ULL|l|ul|ull)?<<(\S)', line) if match and not (match.group(1).isdigit() and match.group(2).isdigit()): error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around <<') elif not Match(r'#.*include', line): # Avoid false positives on -> reduced_line = line.replace('->', '') # Look for < that is not surrounded by spaces. This is only # triggered if both sides are missing spaces, even though # technically should should flag if at least one side is missing a # space. This is done to avoid some false positives with shifts. match = Search(r'[^\s<]<([^\s=<].*)', reduced_line) if (match and not FindNextMatchingAngleBracket(clean_lines, linenum, match.group(1))): error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around <') # Look for > that is not surrounded by spaces. Similar to the # above, we only trigger if both sides are missing spaces to avoid # false positives with shifts. match = Search(r'^(.*[^\s>])>[^\s=>]', reduced_line) if (match and not FindPreviousMatchingAngleBracket(clean_lines, linenum, match.group(1))): error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around >') # We allow no-spaces around >> for almost anything. This is because # C++11 allows ">>" to close nested templates, which accounts for # most cases when ">>" is not followed by a space. # # We still warn on ">>" followed by alpha character, because that is # likely due to ">>" being used for right shifts, e.g.: # value >> alpha # # When ">>" is used to close templates, the alphanumeric letter that # follows would be part of an identifier, and there should still be # a space separating the template type and the identifier. # type<type<type>> alpha match = Search(r'>>[a-zA-Z_]', line) if match: error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around >>') # There shouldn't be space around unary operators match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line) if match: error(filename, linenum, 'whitespace/operators', 4, 'Extra space for operator %s' % match.group(1)) # A pet peeve of mine: no spaces after an if, while, switch, or for match = Search(r' (if\(|for\(|while\(|switch\()', line) if match: error(filename, linenum, 'whitespace/parens', 5, 'Missing space before ( in %s' % match.group(1)) # For if/for/while/switch, the left and right parens should be # consistent about how many spaces are inside the parens, and # there should either be zero or one spaces inside the parens. # We don't want: "if ( foo)" or "if ( foo )". # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed. match = Search(r'\b(if|for|while|switch)\s*' r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$', line) if match: if len(match.group(2)) != len(match.group(4)): if not (match.group(3) == ';' and len(match.group(2)) == 1 + len(match.group(4)) or not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)): error(filename, linenum, 'whitespace/parens', 5, 'Mismatching spaces inside () in %s' % match.group(1)) if not len(match.group(2)) in [0, 1]: error(filename, linenum, 'whitespace/parens', 5, 'Should have zero or one spaces inside ( and ) in %s' % match.group(1)) # You should always have a space after a comma (either as fn arg or operator) if Search(r',[^\s]', line): error(filename, linenum, 'whitespace/comma', 3, 'Missing space after ,') # You should always have a space after a semicolon # except for few corner cases # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more # space after ; if Search(r';[^\s};\\)/]', line): error(filename, linenum, 'whitespace/semicolon', 3, 'Missing space after ;') # Next we will look for issues with function calls. CheckSpacingForFunctionCall(filename, line, linenum, error) # Except after an opening paren, or after another opening brace (in case of # an initializer list, for instance), you should have spaces before your # braces. And since you should never have braces at the beginning of a line, # this is an easy test. if Search(r'[^ ({]{', line): error(filename, linenum, 'whitespace/braces', 5, 'Missing space before {') # Make sure '} else {' has spaces. if Search(r'}else', line): error(filename, linenum, 'whitespace/braces', 5, 'Missing space before else') # You shouldn't have spaces before your brackets, except maybe after # 'delete []' or 'new char * []'. if Search(r'\w\s+\[', line) and not Search(r'delete\s+\[', line): error(filename, linenum, 'whitespace/braces', 5, 'Extra space before [') # You shouldn't have a space before a semicolon at the end of the line. # There's a special case for "for" since the style guide allows space before # the semicolon there. if Search(r':\s*;\s*$', line): error(filename, linenum, 'whitespace/semicolon', 5, 'Semicolon defining empty statement. Use {} instead.') elif Search(r'^\s*;\s*$', line): error(filename, linenum, 'whitespace/semicolon', 5, 'Line contains only semicolon. If this should be an empty statement, ' 'use {} instead.') elif (Search(r'\s+;\s*$', line) and not Search(r'\bfor\b', line)): error(filename, linenum, 'whitespace/semicolon', 5, 'Extra space before last semicolon. If this should be an empty ' 'statement, use {} instead.') # In range-based for, we wanted spaces before and after the colon, but # not around "::" tokens that might appear. if (Search('for *\(.*[^:]:[^: ]', line) or Search('for *\(.*[^: ]:[^:]', line)): error(filename, linenum, 'whitespace/forcolon', 2, 'Missing space around colon in range-based for loop')
[ "def", "CheckSpacing", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "nesting_state", ",", "error", ")", ":", "raw", "=", "clean_lines", ".", "raw_lines", "line", "=", "raw", "[", "linenum", "]", "# Before nixing comments, check if the line is blank for ...
https://github.com/abforce/xposed_art_n/blob/ec3fbe417d74d4664cec053d91dd4e3881176374/tools/cpplint.py#L2235-L2522
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/autograph/operators/data_structures.py
python
_py_list_stack
(list_, opts)
return opts.original_call(list_)
Overload of list_stack that executes a Python list append.
Overload of list_stack that executes a Python list append.
[ "Overload", "of", "list_stack", "that", "executes", "a", "Python", "list", "append", "." ]
def _py_list_stack(list_, opts): """Overload of list_stack that executes a Python list append.""" # Revert to the original call. return opts.original_call(list_)
[ "def", "_py_list_stack", "(", "list_", ",", "opts", ")", ":", "# Revert to the original call.", "return", "opts", ".", "original_call", "(", "list_", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/autograph/operators/data_structures.py#L344-L347
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/fastparquet/util.py
python
check_column_names
(columns, *args)
Ensure that parameters listing column names have corresponding columns
Ensure that parameters listing column names have corresponding columns
[ "Ensure", "that", "parameters", "listing", "column", "names", "have", "corresponding", "columns" ]
def check_column_names(columns, *args): """Ensure that parameters listing column names have corresponding columns""" for arg in args: if isinstance(arg, (tuple, list)): missing = set(arg) - set(columns) if missing: raise ValueError("Following columns were requested but are " "not available: %s.\n" "All requested columns: %s\n" "Available columns: %s" "" % (missing, arg, columns))
[ "def", "check_column_names", "(", "columns", ",", "*", "args", ")", ":", "for", "arg", "in", "args", ":", "if", "isinstance", "(", "arg", ",", "(", "tuple", ",", "list", ")", ")", ":", "missing", "=", "set", "(", "arg", ")", "-", "set", "(", "col...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/fastparquet/util.py#L84-L94
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py3/IPython/__init__.py
python
start_kernel
(argv=None, **kwargs)
return launch_new_instance(argv=argv, **kwargs)
Launch a normal IPython kernel instance (as opposed to embedded) `IPython.embed_kernel()` puts a shell in a particular calling scope, such as a function or method for debugging purposes, which is often not desirable. `start_kernel()` does full, regular IPython initialization, including loading startup files, configuration, etc. much of which is skipped by `embed()`. Parameters ---------- argv : list or None, optional If unspecified or None, IPython will parse command-line options from sys.argv. To prevent any command-line parsing, pass an empty list: `argv=[]`. user_ns : dict, optional specify this dictionary to initialize the IPython user namespace with particular values. kwargs : various, optional Any other kwargs will be passed to the Application constructor, such as `config`.
Launch a normal IPython kernel instance (as opposed to embedded) `IPython.embed_kernel()` puts a shell in a particular calling scope, such as a function or method for debugging purposes, which is often not desirable. `start_kernel()` does full, regular IPython initialization, including loading startup files, configuration, etc. much of which is skipped by `embed()`. Parameters ---------- argv : list or None, optional If unspecified or None, IPython will parse command-line options from sys.argv. To prevent any command-line parsing, pass an empty list: `argv=[]`. user_ns : dict, optional specify this dictionary to initialize the IPython user namespace with particular values. kwargs : various, optional Any other kwargs will be passed to the Application constructor, such as `config`.
[ "Launch", "a", "normal", "IPython", "kernel", "instance", "(", "as", "opposed", "to", "embedded", ")", "IPython", ".", "embed_kernel", "()", "puts", "a", "shell", "in", "a", "particular", "calling", "scope", "such", "as", "a", "function", "or", "method", "...
def start_kernel(argv=None, **kwargs): """Launch a normal IPython kernel instance (as opposed to embedded) `IPython.embed_kernel()` puts a shell in a particular calling scope, such as a function or method for debugging purposes, which is often not desirable. `start_kernel()` does full, regular IPython initialization, including loading startup files, configuration, etc. much of which is skipped by `embed()`. Parameters ---------- argv : list or None, optional If unspecified or None, IPython will parse command-line options from sys.argv. To prevent any command-line parsing, pass an empty list: `argv=[]`. user_ns : dict, optional specify this dictionary to initialize the IPython user namespace with particular values. kwargs : various, optional Any other kwargs will be passed to the Application constructor, such as `config`. """ from IPython.kernel.zmq.kernelapp import launch_new_instance return launch_new_instance(argv=argv, **kwargs)
[ "def", "start_kernel", "(", "argv", "=", "None", ",", "*", "*", "kwargs", ")", ":", "from", "IPython", ".", "kernel", ".", "zmq", ".", "kernelapp", "import", "launch_new_instance", "return", "launch_new_instance", "(", "argv", "=", "argv", ",", "*", "*", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/__init__.py#L132-L156
Tau-Coin/tautcoin
b40dd5ebae49ccecbbf77cc0289b747fd1764219
contrib/devtools/security-check.py
python
check_ELF_NX
(executable)
return have_gnu_stack and not have_wx
Check that no sections are writable and executable (including the stack)
Check that no sections are writable and executable (including the stack)
[ "Check", "that", "no", "sections", "are", "writable", "and", "executable", "(", "including", "the", "stack", ")" ]
def check_ELF_NX(executable): ''' Check that no sections are writable and executable (including the stack) ''' have_wx = False have_gnu_stack = False for (typ, flags) in get_ELF_program_headers(executable): if typ == b'GNU_STACK': have_gnu_stack = True if b'W' in flags and b'E' in flags: # section is both writable and executable have_wx = True return have_gnu_stack and not have_wx
[ "def", "check_ELF_NX", "(", "executable", ")", ":", "have_wx", "=", "False", "have_gnu_stack", "=", "False", "for", "(", "typ", ",", "flags", ")", "in", "get_ELF_program_headers", "(", "executable", ")", ":", "if", "typ", "==", "b'GNU_STACK'", ":", "have_gnu...
https://github.com/Tau-Coin/tautcoin/blob/b40dd5ebae49ccecbbf77cc0289b747fd1764219/contrib/devtools/security-check.py#L61-L72
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBModule.GetNumSymbols
(self)
return _lldb.SBModule_GetNumSymbols(self)
GetNumSymbols(self) -> size_t
GetNumSymbols(self) -> size_t
[ "GetNumSymbols", "(", "self", ")", "-", ">", "size_t" ]
def GetNumSymbols(self): """GetNumSymbols(self) -> size_t""" return _lldb.SBModule_GetNumSymbols(self)
[ "def", "GetNumSymbols", "(", "self", ")", ":", "return", "_lldb", ".", "SBModule_GetNumSymbols", "(", "self", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L6113-L6115
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/richtext.py
python
TextBoxAttr.GetFloatMode
(*args, **kwargs)
return _richtext.TextBoxAttr_GetFloatMode(*args, **kwargs)
GetFloatMode(self) -> int
GetFloatMode(self) -> int
[ "GetFloatMode", "(", "self", ")", "-", ">", "int" ]
def GetFloatMode(*args, **kwargs): """GetFloatMode(self) -> int""" return _richtext.TextBoxAttr_GetFloatMode(*args, **kwargs)
[ "def", "GetFloatMode", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "TextBoxAttr_GetFloatMode", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L576-L578
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/closure_linter/closure_linter/ecmametadatapass.py
python
EcmaContext.GetRoot
(self)
Get the root context that contains this context, if any.
Get the root context that contains this context, if any.
[ "Get", "the", "root", "context", "that", "contains", "this", "context", "if", "any", "." ]
def GetRoot(self): """Get the root context that contains this context, if any.""" context = self while context: if context.type is EcmaContext.ROOT: return context context = context.parent
[ "def", "GetRoot", "(", "self", ")", ":", "context", "=", "self", "while", "context", ":", "if", "context", ".", "type", "is", "EcmaContext", ".", "ROOT", ":", "return", "context", "context", "=", "context", ".", "parent" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/closure_linter/closure_linter/ecmametadatapass.py#L165-L171
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/requests/cookies.py
python
RequestsCookieJar.__getitem__
(self, name)
return self._find_no_duplicates(name)
Dict-like __getitem__() for compatibility with client code. Throws exception if there are more than one cookie with name. In that case, use the more explicit get() method instead. .. warning:: operation is O(n), not O(1).
Dict-like __getitem__() for compatibility with client code. Throws exception if there are more than one cookie with name. In that case, use the more explicit get() method instead.
[ "Dict", "-", "like", "__getitem__", "()", "for", "compatibility", "with", "client", "code", ".", "Throws", "exception", "if", "there", "are", "more", "than", "one", "cookie", "with", "name", ".", "In", "that", "case", "use", "the", "more", "explicit", "get...
def __getitem__(self, name): """Dict-like __getitem__() for compatibility with client code. Throws exception if there are more than one cookie with name. In that case, use the more explicit get() method instead. .. warning:: operation is O(n), not O(1). """ return self._find_no_duplicates(name)
[ "def", "__getitem__", "(", "self", ",", "name", ")", ":", "return", "self", ".", "_find_no_duplicates", "(", "name", ")" ]
https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/requests/cookies.py#L321-L328
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/io/pytables.py
python
SparseFixed.validate_read
(self, kwargs)
return kwargs
we don't support start, stop kwds in Sparse
we don't support start, stop kwds in Sparse
[ "we", "don", "t", "support", "start", "stop", "kwds", "in", "Sparse" ]
def validate_read(self, kwargs): """ we don't support start, stop kwds in Sparse """ kwargs = super(SparseFixed, self).validate_read(kwargs) if 'start' in kwargs or 'stop' in kwargs: raise NotImplementedError("start and/or stop are not supported " "in fixed Sparse reading") return kwargs
[ "def", "validate_read", "(", "self", ",", "kwargs", ")", ":", "kwargs", "=", "super", "(", "SparseFixed", ",", "self", ")", ".", "validate_read", "(", "kwargs", ")", "if", "'start'", "in", "kwargs", "or", "'stop'", "in", "kwargs", ":", "raise", "NotImple...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/io/pytables.py#L2872-L2880
naver/sling
5671cd445a2caae0b4dd0332299e4cfede05062c
webkit/Tools/Scripts/webkitpy/common/system/filesystem.py
python
FileSystem.mkdtemp
(self, **kwargs)
return TemporaryDirectory(**kwargs)
Create and return a uniquely named directory. This is like tempfile.mkdtemp, but if used in a with statement the directory will self-delete at the end of the block (if the directory is empty; non-empty directories raise errors). The directory can be safely deleted inside the block as well, if so desired. Note that the object returned is not a string and does not support all of the string methods. If you need a string, coerce the object to a string and go from there.
Create and return a uniquely named directory.
[ "Create", "and", "return", "a", "uniquely", "named", "directory", "." ]
def mkdtemp(self, **kwargs): """Create and return a uniquely named directory. This is like tempfile.mkdtemp, but if used in a with statement the directory will self-delete at the end of the block (if the directory is empty; non-empty directories raise errors). The directory can be safely deleted inside the block as well, if so desired. Note that the object returned is not a string and does not support all of the string methods. If you need a string, coerce the object to a string and go from there. """ class TemporaryDirectory(object): def __init__(self, **kwargs): self._kwargs = kwargs self._directory_path = tempfile.mkdtemp(**self._kwargs) def __str__(self): return self._directory_path def __enter__(self): return self._directory_path def __exit__(self, type, value, traceback): # Only self-delete if necessary. # FIXME: Should we delete non-empty directories? if os.path.exists(self._directory_path): os.rmdir(self._directory_path) return TemporaryDirectory(**kwargs)
[ "def", "mkdtemp", "(", "self", ",", "*", "*", "kwargs", ")", ":", "class", "TemporaryDirectory", "(", "object", ")", ":", "def", "__init__", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_kwargs", "=", "kwargs", "self", ".", "_directo...
https://github.com/naver/sling/blob/5671cd445a2caae0b4dd0332299e4cfede05062c/webkit/Tools/Scripts/webkitpy/common/system/filesystem.py#L166-L196
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/profile.py
python
run
(statement, filename=None, sort=-1)
Run statement under profiler optionally saving results in filename This function takes a single argument that can be passed to the "exec" statement, and an optional file name. In all cases this routine attempts to "exec" its first argument and gather profiling statistics from the execution. If no file name is present, then this function automatically prints a simple profiling report, sorted by the standard name string (file/line/function-name) that is presented in each line.
Run statement under profiler optionally saving results in filename
[ "Run", "statement", "under", "profiler", "optionally", "saving", "results", "in", "filename" ]
def run(statement, filename=None, sort=-1): """Run statement under profiler optionally saving results in filename This function takes a single argument that can be passed to the "exec" statement, and an optional file name. In all cases this routine attempts to "exec" its first argument and gather profiling statistics from the execution. If no file name is present, then this function automatically prints a simple profiling report, sorted by the standard name string (file/line/function-name) that is presented in each line. """ prof = Profile() try: prof = prof.run(statement) except SystemExit: pass if filename is not None: prof.dump_stats(filename) else: return prof.print_stats(sort)
[ "def", "run", "(", "statement", ",", "filename", "=", "None", ",", "sort", "=", "-", "1", ")", ":", "prof", "=", "Profile", "(", ")", "try", ":", "prof", "=", "prof", ".", "run", "(", "statement", ")", "except", "SystemExit", ":", "pass", "if", "...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/profile.py#L48-L67
jackaudio/jack2
21b293dbc37d42446141a08922cdec0d2550c6a0
waflib/Scripting.py
python
Dist.get_files
(self)
return files
Files to package are searched automatically by :py:func:`waflib.Node.Node.ant_glob`. Set *files* to prevent this behaviour:: def dist(ctx): ctx.files = ctx.path.find_node('wscript') Files are also searched from the directory 'base_path', to change it, set:: def dist(ctx): ctx.base_path = path :rtype: list of :py:class:`waflib.Node.Node`
Files to package are searched automatically by :py:func:`waflib.Node.Node.ant_glob`. Set *files* to prevent this behaviour::
[ "Files", "to", "package", "are", "searched", "automatically", "by", ":", "py", ":", "func", ":", "waflib", ".", "Node", ".", "Node", ".", "ant_glob", ".", "Set", "*", "files", "*", "to", "prevent", "this", "behaviour", "::" ]
def get_files(self): """ Files to package are searched automatically by :py:func:`waflib.Node.Node.ant_glob`. Set *files* to prevent this behaviour:: def dist(ctx): ctx.files = ctx.path.find_node('wscript') Files are also searched from the directory 'base_path', to change it, set:: def dist(ctx): ctx.base_path = path :rtype: list of :py:class:`waflib.Node.Node` """ try: files = self.files except AttributeError: files = self.base_path.ant_glob('**/*', excl=self.get_excl()) return files
[ "def", "get_files", "(", "self", ")", ":", "try", ":", "files", "=", "self", ".", "files", "except", "AttributeError", ":", "files", "=", "self", ".", "base_path", ".", "ant_glob", "(", "'**/*'", ",", "excl", "=", "self", ".", "get_excl", "(", ")", "...
https://github.com/jackaudio/jack2/blob/21b293dbc37d42446141a08922cdec0d2550c6a0/waflib/Scripting.py#L492-L511
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/platform/gfile.py
python
Remove
(path)
Delete the (non-directory) file "path". Args: path: The file to remove. Raises: OSError: If "path" does not exist, is a directory, or cannot be deleted.
Delete the (non-directory) file "path".
[ "Delete", "the", "(", "non", "-", "directory", ")", "file", "path", "." ]
def Remove(path): # pylint: disable=invalid-name """Delete the (non-directory) file "path". Args: path: The file to remove. Raises: OSError: If "path" does not exist, is a directory, or cannot be deleted. """ os.remove(path)
[ "def", "Remove", "(", "path", ")", ":", "# pylint: disable=invalid-name", "os", ".", "remove", "(", "path", ")" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/platform/gfile.py#L313-L322
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/closure_linter/closure_linter/statetracker.py
python
StateTracker.IsFunctionOpen
(self)
return (self._functions and self._functions[-1].block_depth == self._block_depth - 1)
Returns true if the current token is a function block open. Returns: True if the current token is a function block open.
Returns true if the current token is a function block open.
[ "Returns", "true", "if", "the", "current", "token", "is", "a", "function", "block", "open", "." ]
def IsFunctionOpen(self): """Returns true if the current token is a function block open. Returns: True if the current token is a function block open. """ return (self._functions and self._functions[-1].block_depth == self._block_depth - 1)
[ "def", "IsFunctionOpen", "(", "self", ")", ":", "return", "(", "self", ".", "_functions", "and", "self", ".", "_functions", "[", "-", "1", "]", ".", "block_depth", "==", "self", ".", "_block_depth", "-", "1", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/closure_linter/closure_linter/statetracker.py#L643-L650
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/indexes/multi.py
python
MultiIndex.set_codes
(self, codes, level=None, inplace=False, verify_integrity=True)
Set new codes on MultiIndex. Defaults to returning new index. .. versionadded:: 0.24.0 New name for deprecated method `set_labels`. Parameters ---------- codes : sequence or list of sequence new codes to apply level : int, level name, or sequence of int/level names (default None) level(s) to set (None for all levels) inplace : bool if True, mutates in place verify_integrity : bool (default True) if True, checks that levels and codes are compatible Returns ------- new index (of same type and class...etc) Examples -------- >>> idx = pd.MultiIndex.from_tuples([(1, u'one'), (1, u'two'), (2, u'one'), (2, u'two')], names=['foo', 'bar']) >>> idx.set_codes([[1,0,1,0], [0,0,1,1]]) MultiIndex(levels=[[1, 2], [u'one', u'two']], codes=[[1, 0, 1, 0], [0, 0, 1, 1]], names=[u'foo', u'bar']) >>> idx.set_codes([1,0,1,0], level=0) MultiIndex(levels=[[1, 2], [u'one', u'two']], codes=[[1, 0, 1, 0], [0, 1, 0, 1]], names=[u'foo', u'bar']) >>> idx.set_codes([0,0,1,1], level='bar') MultiIndex(levels=[[1, 2], [u'one', u'two']], codes=[[0, 0, 1, 1], [0, 0, 1, 1]], names=[u'foo', u'bar']) >>> idx.set_codes([[1,0,1,0], [0,0,1,1]], level=[0,1]) MultiIndex(levels=[[1, 2], [u'one', u'two']], codes=[[1, 0, 1, 0], [0, 0, 1, 1]], names=[u'foo', u'bar'])
Set new codes on MultiIndex. Defaults to returning new index.
[ "Set", "new", "codes", "on", "MultiIndex", ".", "Defaults", "to", "returning", "new", "index", "." ]
def set_codes(self, codes, level=None, inplace=False, verify_integrity=True): """ Set new codes on MultiIndex. Defaults to returning new index. .. versionadded:: 0.24.0 New name for deprecated method `set_labels`. Parameters ---------- codes : sequence or list of sequence new codes to apply level : int, level name, or sequence of int/level names (default None) level(s) to set (None for all levels) inplace : bool if True, mutates in place verify_integrity : bool (default True) if True, checks that levels and codes are compatible Returns ------- new index (of same type and class...etc) Examples -------- >>> idx = pd.MultiIndex.from_tuples([(1, u'one'), (1, u'two'), (2, u'one'), (2, u'two')], names=['foo', 'bar']) >>> idx.set_codes([[1,0,1,0], [0,0,1,1]]) MultiIndex(levels=[[1, 2], [u'one', u'two']], codes=[[1, 0, 1, 0], [0, 0, 1, 1]], names=[u'foo', u'bar']) >>> idx.set_codes([1,0,1,0], level=0) MultiIndex(levels=[[1, 2], [u'one', u'two']], codes=[[1, 0, 1, 0], [0, 1, 0, 1]], names=[u'foo', u'bar']) >>> idx.set_codes([0,0,1,1], level='bar') MultiIndex(levels=[[1, 2], [u'one', u'two']], codes=[[0, 0, 1, 1], [0, 0, 1, 1]], names=[u'foo', u'bar']) >>> idx.set_codes([[1,0,1,0], [0,0,1,1]], level=[0,1]) MultiIndex(levels=[[1, 2], [u'one', u'two']], codes=[[1, 0, 1, 0], [0, 0, 1, 1]], names=[u'foo', u'bar']) """ if level is not None and not is_list_like(level): if not is_list_like(codes): raise TypeError("Codes must be list-like") if is_list_like(codes[0]): raise TypeError("Codes must be list-like") level = [level] codes = [codes] elif level is None or is_list_like(level): if not is_list_like(codes) or not is_list_like(codes[0]): raise TypeError("Codes must be list of lists-like") if inplace: idx = self else: idx = self._shallow_copy() idx._reset_identity() idx._set_codes(codes, level=level, verify_integrity=verify_integrity) if not inplace: return idx
[ "def", "set_codes", "(", "self", ",", "codes", ",", "level", "=", "None", ",", "inplace", "=", "False", ",", "verify_integrity", "=", "True", ")", ":", "if", "level", "is", "not", "None", "and", "not", "is_list_like", "(", "level", ")", ":", "if", "n...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/indexes/multi.py#L709-L774
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/telemetry/internal/backends/chrome/android_browser_finder.py
python
FindAllAvailableBrowsers
(finder_options, device)
return _FindAllPossibleBrowsers(finder_options, android_platform)
Finds all the possible browsers on one device. The device is either the only device on the host platform, or |finder_options| specifies a particular device.
Finds all the possible browsers on one device.
[ "Finds", "all", "the", "possible", "browsers", "on", "one", "device", "." ]
def FindAllAvailableBrowsers(finder_options, device): """Finds all the possible browsers on one device. The device is either the only device on the host platform, or |finder_options| specifies a particular device. """ if not isinstance(device, android_device.AndroidDevice): return [] android_platform = platform.GetPlatformForDevice(device, finder_options) return _FindAllPossibleBrowsers(finder_options, android_platform)
[ "def", "FindAllAvailableBrowsers", "(", "finder_options", ",", "device", ")", ":", "if", "not", "isinstance", "(", "device", ",", "android_device", ".", "AndroidDevice", ")", ":", "return", "[", "]", "android_platform", "=", "platform", ".", "GetPlatformForDevice"...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/internal/backends/chrome/android_browser_finder.py#L250-L259
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/math_ops.py
python
_div_python2
(x, y, name=None)
Divide two values using Python 2 semantics. Used for Tensor.__div__. Args: x: `Tensor` numerator of real numeric type. y: `Tensor` denominator of real numeric type. name: A name for the operation (optional). Returns: `x / y` returns the quotient of x and y.
Divide two values using Python 2 semantics.
[ "Divide", "two", "values", "using", "Python", "2", "semantics", "." ]
def _div_python2(x, y, name=None): """Divide two values using Python 2 semantics. Used for Tensor.__div__. Args: x: `Tensor` numerator of real numeric type. y: `Tensor` denominator of real numeric type. name: A name for the operation (optional). Returns: `x / y` returns the quotient of x and y. """ with ops.name_scope(name, "div", [x, y]) as name: x = ops.convert_to_tensor(x, name="x") y = ops.convert_to_tensor(y, name="y", dtype=x.dtype.base_dtype) x_dtype = x.dtype.base_dtype y_dtype = y.dtype.base_dtype if x_dtype != y_dtype: raise TypeError("x and y must have the same dtype, got %r != %r" % (x_dtype, y_dtype)) if x_dtype.is_floating or x_dtype.is_complex: return gen_math_ops.real_div(x, y, name=name) else: return gen_math_ops.floor_div(x, y, name=name)
[ "def", "_div_python2", "(", "x", ",", "y", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "name_scope", "(", "name", ",", "\"div\"", ",", "[", "x", ",", "y", "]", ")", "as", "name", ":", "x", "=", "ops", ".", "convert_to_tensor", "(", ...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/math_ops.py#L1008-L1033
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/StdSuites/Standard_Suite.py
python
Standard_Suite_Events.count
(self, _object, _attributes={}, **_arguments)
count: Return the number of elements of an object Required argument: the object whose elements are to be counted Keyword argument each: if specified, restricts counting to objects of this class Keyword argument _attributes: AppleEvent attribute dictionary Returns: the number of elements
count: Return the number of elements of an object Required argument: the object whose elements are to be counted Keyword argument each: if specified, restricts counting to objects of this class Keyword argument _attributes: AppleEvent attribute dictionary Returns: the number of elements
[ "count", ":", "Return", "the", "number", "of", "elements", "of", "an", "object", "Required", "argument", ":", "the", "object", "whose", "elements", "are", "to", "be", "counted", "Keyword", "argument", "each", ":", "if", "specified", "restricts", "counting", ...
def count(self, _object, _attributes={}, **_arguments): """count: Return the number of elements of an object Required argument: the object whose elements are to be counted Keyword argument each: if specified, restricts counting to objects of this class Keyword argument _attributes: AppleEvent attribute dictionary Returns: the number of elements """ _code = 'core' _subcode = 'cnte' aetools.keysubst(_arguments, self._argmap_count) _arguments['----'] = _object _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.get('errn', 0): raise aetools.Error, aetools.decodeerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----']
[ "def", "count", "(", "self", ",", "_object", ",", "_attributes", "=", "{", "}", ",", "*", "*", "_arguments", ")", ":", "_code", "=", "'core'", "_subcode", "=", "'cnte'", "aetools", ".", "keysubst", "(", "_arguments", ",", "self", ".", "_argmap_count", ...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/StdSuites/Standard_Suite.py#L74-L94
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/contrib/layers/python/layers/regularizers.py
python
apply_regularization
(regularizer, weights_list=None)
Returns the summed penalty by applying `regularizer` to the `weights_list`. Adding a regularization penalty over the layer weights and embedding weights can help prevent overfitting the training data. Regularization over layer biases is less common/useful, but assuming proper data preprocessing/mean subtraction, it usually shouldn't hurt much either. Args: regularizer: A function that takes a single `Tensor` argument and returns a scalar `Tensor` output. weights_list: List of weights `Tensors` or `Variables` to apply `regularizer` over. Defaults to the `GraphKeys.WEIGHTS` collection if `None`. Returns: A scalar representing the overall regularization penalty. Raises: ValueError: If `regularizer` does not return a scalar output, or if we find no weights.
Returns the summed penalty by applying `regularizer` to the `weights_list`.
[ "Returns", "the", "summed", "penalty", "by", "applying", "regularizer", "to", "the", "weights_list", "." ]
def apply_regularization(regularizer, weights_list=None): """Returns the summed penalty by applying `regularizer` to the `weights_list`. Adding a regularization penalty over the layer weights and embedding weights can help prevent overfitting the training data. Regularization over layer biases is less common/useful, but assuming proper data preprocessing/mean subtraction, it usually shouldn't hurt much either. Args: regularizer: A function that takes a single `Tensor` argument and returns a scalar `Tensor` output. weights_list: List of weights `Tensors` or `Variables` to apply `regularizer` over. Defaults to the `GraphKeys.WEIGHTS` collection if `None`. Returns: A scalar representing the overall regularization penalty. Raises: ValueError: If `regularizer` does not return a scalar output, or if we find no weights. """ if not weights_list: weights_list = ops.get_collection(ops.GraphKeys.WEIGHTS) if not weights_list: raise ValueError('No weights to regularize.') with ops.name_scope('get_regularization_penalty', values=weights_list) as scope: penalties = [regularizer(w) for w in weights_list] penalties = [ p if p is not None else constant_op.constant(0.0) for p in penalties ] for p in penalties: if p.get_shape().ndims != 0: raise ValueError('regularizer must return a scalar Tensor instead of a ' 'Tensor with rank %d.' % p.get_shape().ndims) summed_penalty = math_ops.add_n(penalties, name=scope) ops.add_to_collection(ops.GraphKeys.REGULARIZATION_LOSSES, summed_penalty) return summed_penalty
[ "def", "apply_regularization", "(", "regularizer", ",", "weights_list", "=", "None", ")", ":", "if", "not", "weights_list", ":", "weights_list", "=", "ops", ".", "get_collection", "(", "ops", ".", "GraphKeys", ".", "WEIGHTS", ")", "if", "not", "weights_list", ...
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/layers/python/layers/regularizers.py#L157-L196
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/distributed/fleet/meta_optimizers/sharding/utils.py
python
insert_sync_comm_ops
(block, insert_idx, ring_id, comm_dep_vars)
return 1
insert sync_comm_op for vars
insert sync_comm_op for vars
[ "insert", "sync_comm_op", "for", "vars" ]
def insert_sync_comm_ops(block, insert_idx, ring_id, comm_dep_vars): """ insert sync_comm_op for vars """ # NOTE (JZ-LIANG) to be check, may result undefined case if len(comm_dep_vars) == 0: return 0 op_role = get_valid_op_role(block, insert_idx) block._insert_op_without_sync( insert_idx, type='c_sync_comm_stream', inputs={'X': comm_dep_vars}, outputs={'Out': comm_dep_vars}, attrs={'ring_id': int(ring_id), OP_ROLE_KEY: op_role}) return 1
[ "def", "insert_sync_comm_ops", "(", "block", ",", "insert_idx", ",", "ring_id", ",", "comm_dep_vars", ")", ":", "# NOTE (JZ-LIANG) to be check, may result undefined case ", "if", "len", "(", "comm_dep_vars", ")", "==", "0", ":", "return", "0", "op_role", "=", "get_v...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/distributed/fleet/meta_optimizers/sharding/utils.py#L273-L289
sdhash/sdhash
b9eff63e4e5867e910f41fd69032bbb1c94a2a5e
sdhash-ui/cherrypy/wsgiserver/wsgiserver2.py
python
plat_specific_errors
(*errnames)
return list(dict.fromkeys(nums).keys())
Return error numbers for all errors in errnames on this platform. The 'errno' module contains different global constants depending on the specific platform (OS). This function will return the list of numeric values for a given list of potential names.
Return error numbers for all errors in errnames on this platform. The 'errno' module contains different global constants depending on the specific platform (OS). This function will return the list of numeric values for a given list of potential names.
[ "Return", "error", "numbers", "for", "all", "errors", "in", "errnames", "on", "this", "platform", ".", "The", "errno", "module", "contains", "different", "global", "constants", "depending", "on", "the", "specific", "platform", "(", "OS", ")", ".", "This", "f...
def plat_specific_errors(*errnames): """Return error numbers for all errors in errnames on this platform. The 'errno' module contains different global constants depending on the specific platform (OS). This function will return the list of numeric values for a given list of potential names. """ errno_names = dir(errno) nums = [getattr(errno, k) for k in errnames if k in errno_names] # de-dupe the list return list(dict.fromkeys(nums).keys())
[ "def", "plat_specific_errors", "(", "*", "errnames", ")", ":", "errno_names", "=", "dir", "(", "errno", ")", "nums", "=", "[", "getattr", "(", "errno", ",", "k", ")", "for", "k", "in", "errnames", "if", "k", "in", "errno_names", "]", "# de-dupe the list"...
https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/cherrypy/wsgiserver/wsgiserver2.py#L149-L159
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/setuptools/_vendor/pyparsing.py
python
ParserElement.addCondition
(self, *fns, **kwargs)
return self
Add a boolean predicate function to expression's list of parse actions. See L{I{setParseAction}<setParseAction>} for function call signatures. Unlike C{setParseAction}, functions passed to C{addCondition} need to return boolean success/fail of the condition. Optional keyword arguments: - message = define a custom message to be used in the raised exception - fatal = if True, will raise ParseFatalException to stop parsing immediately; otherwise will raise ParseException Example:: integer = Word(nums).setParseAction(lambda toks: int(toks[0])) year_int = integer.copy() year_int.addCondition(lambda toks: toks[0] >= 2000, message="Only support years 2000 and later") date_str = year_int + '/' + integer + '/' + integer result = date_str.parseString("1999/12/31") # -> Exception: Only support years 2000 and later (at char 0), (line:1, col:1)
Add a boolean predicate function to expression's list of parse actions. See L{I{setParseAction}<setParseAction>} for function call signatures. Unlike C{setParseAction}, functions passed to C{addCondition} need to return boolean success/fail of the condition.
[ "Add", "a", "boolean", "predicate", "function", "to", "expression", "s", "list", "of", "parse", "actions", ".", "See", "L", "{", "I", "{", "setParseAction", "}", "<setParseAction", ">", "}", "for", "function", "call", "signatures", ".", "Unlike", "C", "{",...
def addCondition(self, *fns, **kwargs): """Add a boolean predicate function to expression's list of parse actions. See L{I{setParseAction}<setParseAction>} for function call signatures. Unlike C{setParseAction}, functions passed to C{addCondition} need to return boolean success/fail of the condition. Optional keyword arguments: - message = define a custom message to be used in the raised exception - fatal = if True, will raise ParseFatalException to stop parsing immediately; otherwise will raise ParseException Example:: integer = Word(nums).setParseAction(lambda toks: int(toks[0])) year_int = integer.copy() year_int.addCondition(lambda toks: toks[0] >= 2000, message="Only support years 2000 and later") date_str = year_int + '/' + integer + '/' + integer result = date_str.parseString("1999/12/31") # -> Exception: Only support years 2000 and later (at char 0), (line:1, col:1) """ msg = kwargs.get("message", "failed user-defined condition") exc_type = ParseFatalException if kwargs.get("fatal", False) else ParseException for fn in fns: def pa(s,l,t): if not bool(_trim_arity(fn)(s,l,t)): raise exc_type(s,l,msg) self.parseAction.append(pa) self.callDuringTry = self.callDuringTry or kwargs.get("callDuringTry", False) return self
[ "def", "addCondition", "(", "self", ",", "*", "fns", ",", "*", "*", "kwargs", ")", ":", "msg", "=", "kwargs", ".", "get", "(", "\"message\"", ",", "\"failed user-defined condition\"", ")", "exc_type", "=", "ParseFatalException", "if", "kwargs", ".", "get", ...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/setuptools/_vendor/pyparsing.py#L1298-L1323
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/signal/window_ops.py
python
hann_window
(window_length, periodic=True, dtype=dtypes.float32, name=None)
return _raised_cosine_window(name, 'hann_window', window_length, periodic, dtype, 0.5, 0.5)
Generate a [Hann window][hann]. Args: window_length: A scalar `Tensor` indicating the window length to generate. periodic: A bool `Tensor` indicating whether to generate a periodic or symmetric window. Periodic windows are typically used for spectral analysis while symmetric windows are typically used for digital filter design. dtype: The data type to produce. Must be a floating point type. name: An optional name for the operation. Returns: A `Tensor` of shape `[window_length]` of type `dtype`. Raises: ValueError: If `dtype` is not a floating point type. [hann]: https://en.wikipedia.org/wiki/Window_function#Hann_and_Hamming_windows
Generate a [Hann window][hann].
[ "Generate", "a", "[", "Hann", "window", "]", "[", "hann", "]", "." ]
def hann_window(window_length, periodic=True, dtype=dtypes.float32, name=None): """Generate a [Hann window][hann]. Args: window_length: A scalar `Tensor` indicating the window length to generate. periodic: A bool `Tensor` indicating whether to generate a periodic or symmetric window. Periodic windows are typically used for spectral analysis while symmetric windows are typically used for digital filter design. dtype: The data type to produce. Must be a floating point type. name: An optional name for the operation. Returns: A `Tensor` of shape `[window_length]` of type `dtype`. Raises: ValueError: If `dtype` is not a floating point type. [hann]: https://en.wikipedia.org/wiki/Window_function#Hann_and_Hamming_windows """ return _raised_cosine_window(name, 'hann_window', window_length, periodic, dtype, 0.5, 0.5)
[ "def", "hann_window", "(", "window_length", ",", "periodic", "=", "True", ",", "dtype", "=", "dtypes", ".", "float32", ",", "name", "=", "None", ")", ":", "return", "_raised_cosine_window", "(", "name", ",", "'hann_window'", ",", "window_length", ",", "perio...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/signal/window_ops.py#L34-L55
Cisco-Talos/moflow
ed71dfb0540d9e0d7a4c72f0881b58958d573728
BAP-0.7-moflow/libtracewrap/libtrace/protobuf/python/google/protobuf/descriptor.py
python
FieldDescriptor.__init__
(self, name, full_name, index, number, type, cpp_type, label, default_value, message_type, enum_type, containing_type, is_extension, extension_scope, options=None, has_default_value=True)
The arguments are as described in the description of FieldDescriptor attributes above. Note that containing_type may be None, and may be set later if necessary (to deal with circular references between message types, for example). Likewise for extension_scope.
The arguments are as described in the description of FieldDescriptor attributes above.
[ "The", "arguments", "are", "as", "described", "in", "the", "description", "of", "FieldDescriptor", "attributes", "above", "." ]
def __init__(self, name, full_name, index, number, type, cpp_type, label, default_value, message_type, enum_type, containing_type, is_extension, extension_scope, options=None, has_default_value=True): """The arguments are as described in the description of FieldDescriptor attributes above. Note that containing_type may be None, and may be set later if necessary (to deal with circular references between message types, for example). Likewise for extension_scope. """ super(FieldDescriptor, self).__init__(options, 'FieldOptions') self.name = name self.full_name = full_name self.index = index self.number = number self.type = type self.cpp_type = cpp_type self.label = label self.has_default_value = has_default_value self.default_value = default_value self.containing_type = containing_type self.message_type = message_type self.enum_type = enum_type self.is_extension = is_extension self.extension_scope = extension_scope if api_implementation.Type() == 'cpp': if is_extension: self._cdescriptor = cpp_message.GetExtensionDescriptor(full_name) else: self._cdescriptor = cpp_message.GetFieldDescriptor(full_name) else: self._cdescriptor = None
[ "def", "__init__", "(", "self", ",", "name", ",", "full_name", ",", "index", ",", "number", ",", "type", ",", "cpp_type", ",", "label", ",", "default_value", ",", "message_type", ",", "enum_type", ",", "containing_type", ",", "is_extension", ",", "extension_...
https://github.com/Cisco-Talos/moflow/blob/ed71dfb0540d9e0d7a4c72f0881b58958d573728/BAP-0.7-moflow/libtracewrap/libtrace/protobuf/python/google/protobuf/descriptor.py#L370-L402
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/py/crustslices.py
python
CrustSlicesFrame.updateNamespace
(self)
Update the buffer namespace for autocompletion and calltips.
Update the buffer namespace for autocompletion and calltips.
[ "Update", "the", "buffer", "namespace", "for", "autocompletion", "and", "calltips", "." ]
def updateNamespace(self): """Update the buffer namespace for autocompletion and calltips.""" if self.buffer.updateNamespace(): self.SetStatusText('Namespace updated') else: self.SetStatusText('Error executing, unable to update namespace')
[ "def", "updateNamespace", "(", "self", ")", ":", "if", "self", ".", "buffer", ".", "updateNamespace", "(", ")", ":", "self", ".", "SetStatusText", "(", "'Namespace updated'", ")", "else", ":", "self", ".", "SetStatusText", "(", "'Error executing, unable to updat...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/py/crustslices.py#L411-L416
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/gettext.py
python
GNUTranslations._parse
(self, fp)
Override this method to support alternative .mo formats.
Override this method to support alternative .mo formats.
[ "Override", "this", "method", "to", "support", "alternative", ".", "mo", "formats", "." ]
def _parse(self, fp): """Override this method to support alternative .mo formats.""" unpack = struct.unpack filename = getattr(fp, 'name', '') # Parse the .mo file header, which consists of 5 little endian 32 # bit words. self._catalog = catalog = {} self.plural = lambda n: int(n != 1) # germanic plural by default buf = fp.read() buflen = len(buf) # Are we big endian or little endian? magic = unpack('<I', buf[:4])[0] if magic == self.LE_MAGIC: version, msgcount, masteridx, transidx = unpack('<4I', buf[4:20]) ii = '<II' elif magic == self.BE_MAGIC: version, msgcount, masteridx, transidx = unpack('>4I', buf[4:20]) ii = '>II' else: raise IOError(0, 'Bad magic number', filename) # Now put all messages from the .mo file buffer into the catalog # dictionary. for i in xrange(0, msgcount): mlen, moff = unpack(ii, buf[masteridx:masteridx+8]) mend = moff + mlen tlen, toff = unpack(ii, buf[transidx:transidx+8]) tend = toff + tlen if mend < buflen and tend < buflen: msg = buf[moff:mend] tmsg = buf[toff:tend] else: raise IOError(0, 'File is corrupt', filename) # See if we're looking at GNU .mo conventions for metadata if mlen == 0: # Catalog description lastk = k = None for item in tmsg.splitlines(): item = item.strip() if not item: continue if ':' in item: k, v = item.split(':', 1) k = k.strip().lower() v = v.strip() self._info[k] = v lastk = k elif lastk: self._info[lastk] += '\n' + item if k == 'content-type': self._charset = v.split('charset=')[1] elif k == 'plural-forms': v = v.split(';') plural = v[1].split('plural=')[1] self.plural = c2py(plural) # Note: we unconditionally convert both msgids and msgstrs to # Unicode using the character encoding specified in the charset # parameter of the Content-Type header. The gettext documentation # strongly encourages msgids to be us-ascii, but some applications # require alternative encodings (e.g. Zope's ZCML and ZPT). For # traditional gettext applications, the msgid conversion will # cause no problems since us-ascii should always be a subset of # the charset encoding. We may want to fall back to 8-bit msgids # if the Unicode conversion fails. if '\x00' in msg: # Plural forms msgid1, msgid2 = msg.split('\x00') tmsg = tmsg.split('\x00') if self._charset: msgid1 = unicode(msgid1, self._charset) tmsg = [unicode(x, self._charset) for x in tmsg] for i in range(len(tmsg)): catalog[(msgid1, i)] = tmsg[i] else: if self._charset: msg = unicode(msg, self._charset) tmsg = unicode(tmsg, self._charset) catalog[msg] = tmsg # advance to next entry in the seek tables masteridx += 8 transidx += 8
[ "def", "_parse", "(", "self", ",", "fp", ")", ":", "unpack", "=", "struct", ".", "unpack", "filename", "=", "getattr", "(", "fp", ",", "'name'", ",", "''", ")", "# Parse the .mo file header, which consists of 5 little endian 32", "# bit words.", "self", ".", "_c...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/gettext.py#L262-L341
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros/roscreate/src/roscreate/core.py
python
read_template
(tmplf)
return t
Read resource template from egg installation, or fallback on rospkg otherwise. :returns: text of template file
Read resource template from egg installation, or fallback on rospkg otherwise.
[ "Read", "resource", "template", "from", "egg", "installation", "or", "fallback", "on", "rospkg", "otherwise", "." ]
def read_template(tmplf): """ Read resource template from egg installation, or fallback on rospkg otherwise. :returns: text of template file """ if pkg_resources.resource_exists('roscreate', tmplf): f = pkg_resources.resource_stream('roscreate', tmplf) t = f.read() else: # fallback on rospkg r = rospkg.RosPack() with open(os.path.join(r.get_path('roscreate'), 'templates', tmplf)) as f: t = f.read() try: t = t.decode('utf-8') except AttributeError: pass return t
[ "def", "read_template", "(", "tmplf", ")", ":", "if", "pkg_resources", ".", "resource_exists", "(", "'roscreate'", ",", "tmplf", ")", ":", "f", "=", "pkg_resources", ".", "resource_stream", "(", "'roscreate'", ",", "tmplf", ")", "t", "=", "f", ".", "read",...
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros/roscreate/src/roscreate/core.py#L71-L89
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/baseparser.py
python
ConfigOptionParser.normalize_keys
(self, items)
return normalized
Return a config dictionary with normalized keys regardless of whether the keys were specified in environment variables or in config files
Return a config dictionary with normalized keys regardless of whether the keys were specified in environment variables or in config files
[ "Return", "a", "config", "dictionary", "with", "normalized", "keys", "regardless", "of", "whether", "the", "keys", "were", "specified", "in", "environment", "variables", "or", "in", "config", "files" ]
def normalize_keys(self, items): """Return a config dictionary with normalized keys regardless of whether the keys were specified in environment variables or in config files""" normalized = {} for key, val in items: key = key.replace('_', '-') if not key.startswith('--'): key = '--%s' % key # only prefer long opts normalized[key] = val return normalized
[ "def", "normalize_keys", "(", "self", ",", "items", ")", ":", "normalized", "=", "{", "}", "for", "key", ",", "val", "in", "items", ":", "key", "=", "key", ".", "replace", "(", "'_'", ",", "'-'", ")", "if", "not", "key", ".", "startswith", "(", "...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/baseparser.py#L228-L238
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/numpy_extension/utils.py
python
load
(file)
Load arrays from ``.npy``, ``.npz`` or legacy MXNet file format. See more details in ``save``. Parameters ---------- file : str The filename. Returns ------- result : list of ndarrays or dict of str -> ndarray Data stored in the file. Notes ----- This function can only be called within numpy semantics, i.e., `npx.is_np_shape()` and `npx.is_np_array()` must both return true.
Load arrays from ``.npy``, ``.npz`` or legacy MXNet file format.
[ "Load", "arrays", "from", ".", "npy", ".", "npz", "or", "legacy", "MXNet", "file", "format", "." ]
def load(file): """Load arrays from ``.npy``, ``.npz`` or legacy MXNet file format. See more details in ``save``. Parameters ---------- file : str The filename. Returns ------- result : list of ndarrays or dict of str -> ndarray Data stored in the file. Notes ----- This function can only be called within numpy semantics, i.e., `npx.is_np_shape()` and `npx.is_np_array()` must both return true. """ if not (is_np_shape() and is_np_array()): raise ValueError('Cannot load `mxnet.numpy.ndarray` in legacy mode. Please activate' ' numpy semantics by calling `npx.set_np()` in the global scope' ' before calling this function.') if not isinstance(file, string_types): raise TypeError('file required to be a string') out_size = mx_uint() out_name_size = mx_uint() handles = ctypes.POINTER(NDArrayHandle)() names = ctypes.POINTER(ctypes.c_char_p)() check_call(_LIB.MXNDArrayLoad(c_str(file), ctypes.byref(out_size), ctypes.byref(handles), ctypes.byref(out_name_size), ctypes.byref(names))) if out_name_size.value == 0: if out_size.value != 1: return [ndarray(NDArrayHandle(handles[i])) for i in range(out_size.value)] return ndarray(NDArrayHandle(handles[0])) else: assert out_name_size.value == out_size.value return dict( (py_str(names[i]), ndarray(NDArrayHandle(handles[i]))) for i in range(out_size.value))
[ "def", "load", "(", "file", ")", ":", "if", "not", "(", "is_np_shape", "(", ")", "and", "is_np_array", "(", ")", ")", ":", "raise", "ValueError", "(", "'Cannot load `mxnet.numpy.ndarray` in legacy mode. Please activate'", "' numpy semantics by calling `npx.set_np()` in th...
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/numpy_extension/utils.py#L124-L167
ndrplz/self-driving-car
2bdcc7c822e8f03adc0a7490f1ae29a658720713
project_4_advanced_lane_finding/main.py
python
process_pipeline
(frame, keep_state=True)
return blend_output
Apply whole lane detection pipeline to an input color frame. :param frame: input color frame :param keep_state: if True, lane-line state is conserved (this permits to average results) :return: output blend with detected lane overlaid
Apply whole lane detection pipeline to an input color frame. :param frame: input color frame :param keep_state: if True, lane-line state is conserved (this permits to average results) :return: output blend with detected lane overlaid
[ "Apply", "whole", "lane", "detection", "pipeline", "to", "an", "input", "color", "frame", ".", ":", "param", "frame", ":", "input", "color", "frame", ":", "param", "keep_state", ":", "if", "True", "lane", "-", "line", "state", "is", "conserved", "(", "th...
def process_pipeline(frame, keep_state=True): """ Apply whole lane detection pipeline to an input color frame. :param frame: input color frame :param keep_state: if True, lane-line state is conserved (this permits to average results) :return: output blend with detected lane overlaid """ global line_lt, line_rt, processed_frames # undistort the image using coefficients found in calibration img_undistorted = undistort(frame, mtx, dist, verbose=False) # binarize the frame s.t. lane lines are highlighted as much as possible img_binary = binarize(img_undistorted, verbose=False) # compute perspective transform to obtain bird's eye view img_birdeye, M, Minv = birdeye(img_binary, verbose=False) # fit 2-degree polynomial curve onto lane lines found if processed_frames > 0 and keep_state and line_lt.detected and line_rt.detected: line_lt, line_rt, img_fit = get_fits_by_previous_fits(img_birdeye, line_lt, line_rt, verbose=False) else: line_lt, line_rt, img_fit = get_fits_by_sliding_windows(img_birdeye, line_lt, line_rt, n_windows=9, verbose=False) # compute offset in meter from center of the lane offset_meter = compute_offset_from_center(line_lt, line_rt, frame_width=frame.shape[1]) # draw the surface enclosed by lane lines back onto the original frame blend_on_road = draw_back_onto_the_road(img_undistorted, Minv, line_lt, line_rt, keep_state) # stitch on the top of final output images from different steps of the pipeline blend_output = prepare_out_blend_frame(blend_on_road, img_binary, img_birdeye, img_fit, line_lt, line_rt, offset_meter) processed_frames += 1 return blend_output
[ "def", "process_pipeline", "(", "frame", ",", "keep_state", "=", "True", ")", ":", "global", "line_lt", ",", "line_rt", ",", "processed_frames", "# undistort the image using coefficients found in calibration", "img_undistorted", "=", "undistort", "(", "frame", ",", "mtx...
https://github.com/ndrplz/self-driving-car/blob/2bdcc7c822e8f03adc0a7490f1ae29a658720713/project_4_advanced_lane_finding/main.py#L92-L128
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py
python
ArgumentParser.Parse
(self, argument)
return argument
Default implementation: always returns its argument unmodified.
Default implementation: always returns its argument unmodified.
[ "Default", "implementation", ":", "always", "returns", "its", "argument", "unmodified", "." ]
def Parse(self, argument): """Default implementation: always returns its argument unmodified.""" return argument
[ "def", "Parse", "(", "self", ",", "argument", ")", ":", "return", "argument" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py#L2052-L2054
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/third_party/mox3/mox3/mox.py
python
IsAlmost.equals
(self, rhs)
Check to see if RHS is almost equal to float_value Args: rhs: the value to compare to float_value Returns: bool
Check to see if RHS is almost equal to float_value
[ "Check", "to", "see", "if", "RHS", "is", "almost", "equal", "to", "float_value" ]
def equals(self, rhs): """Check to see if RHS is almost equal to float_value Args: rhs: the value to compare to float_value Returns: bool """ try: return round(rhs - self._float_value, self._places) == 0 except Exception: # Probably because either float_value or rhs is not a number. return False
[ "def", "equals", "(", "self", ",", "rhs", ")", ":", "try", ":", "return", "round", "(", "rhs", "-", "self", ".", "_float_value", ",", "self", ".", "_places", ")", "==", "0", "except", "Exception", ":", "# Probably because either float_value or rhs is not a num...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/mox3/mox3/mox.py#L1453-L1467
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/lib/utils.py
python
who
(vardict=None)
return
Print the Numpy arrays in the given dictionary. If there is no dictionary passed in or `vardict` is None then returns Numpy arrays in the globals() dictionary (all Numpy arrays in the namespace). Parameters ---------- vardict : dict, optional A dictionary possibly containing ndarrays. Default is globals(). Returns ------- out : None Returns 'None'. Notes ----- Prints out the name, shape, bytes and type of all of the ndarrays present in `vardict`. Examples -------- >>> a = np.arange(10) >>> b = np.ones(20) >>> np.who() Name Shape Bytes Type =========================================================== a 10 40 int32 b 20 160 float64 Upper bound on total bytes = 200 >>> d = {'x': np.arange(2.0), 'y': np.arange(3.0), 'txt': 'Some str', ... 'idx':5} >>> np.who(d) Name Shape Bytes Type =========================================================== y 3 24 float64 x 2 16 float64 Upper bound on total bytes = 40
Print the Numpy arrays in the given dictionary.
[ "Print", "the", "Numpy", "arrays", "in", "the", "given", "dictionary", "." ]
def who(vardict=None): """ Print the Numpy arrays in the given dictionary. If there is no dictionary passed in or `vardict` is None then returns Numpy arrays in the globals() dictionary (all Numpy arrays in the namespace). Parameters ---------- vardict : dict, optional A dictionary possibly containing ndarrays. Default is globals(). Returns ------- out : None Returns 'None'. Notes ----- Prints out the name, shape, bytes and type of all of the ndarrays present in `vardict`. Examples -------- >>> a = np.arange(10) >>> b = np.ones(20) >>> np.who() Name Shape Bytes Type =========================================================== a 10 40 int32 b 20 160 float64 Upper bound on total bytes = 200 >>> d = {'x': np.arange(2.0), 'y': np.arange(3.0), 'txt': 'Some str', ... 'idx':5} >>> np.who(d) Name Shape Bytes Type =========================================================== y 3 24 float64 x 2 16 float64 Upper bound on total bytes = 40 """ if vardict is None: frame = sys._getframe().f_back vardict = frame.f_globals sta = [] cache = {} for name in vardict.keys(): if isinstance(vardict[name], ndarray): var = vardict[name] idv = id(var) if idv in cache.keys(): namestr = name + " (%s)" % cache[idv] original=0 else: cache[idv] = name namestr = name original=1 shapestr = " x ".join(map(str, var.shape)) bytestr = str(var.nbytes) sta.append([namestr, shapestr, bytestr, var.dtype.name, original]) maxname = 0 maxshape = 0 maxbyte = 0 totalbytes = 0 for k in range(len(sta)): val = sta[k] if maxname < len(val[0]): maxname = len(val[0]) if maxshape < len(val[1]): maxshape = len(val[1]) if maxbyte < len(val[2]): maxbyte = len(val[2]) if val[4]: totalbytes += int(val[2]) if len(sta) > 0: sp1 = max(10, maxname) sp2 = max(10, maxshape) sp3 = max(10, maxbyte) prval = "Name %s Shape %s Bytes %s Type" % (sp1*' ', sp2*' ', sp3*' ') print(prval + "\n" + "="*(len(prval)+5) + "\n") for k in range(len(sta)): val = sta[k] print("%s %s %s %s %s %s %s" % (val[0], ' '*(sp1-len(val[0])+4), val[1], ' '*(sp2-len(val[1])+5), val[2], ' '*(sp3-len(val[2])+5), val[3])) print("\nUpper bound on total bytes = %d" % totalbytes) return
[ "def", "who", "(", "vardict", "=", "None", ")", ":", "if", "vardict", "is", "None", ":", "frame", "=", "sys", ".", "_getframe", "(", ")", ".", "f_back", "vardict", "=", "frame", ".", "f_globals", "sta", "=", "[", "]", "cache", "=", "{", "}", "for...
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/lib/utils.py#L274-L368
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/distutils/command/build_ext.py
python
build_ext.check_extensions_list
(self, extensions)
Ensure that the list of extensions (presumably provided as a command option 'extensions') is valid, i.e. it is a list of Extension objects. We also support the old-style list of 2-tuples, where the tuples are (ext_name, build_info), which are converted to Extension instances here. Raise DistutilsSetupError if the structure is invalid anywhere; just returns otherwise.
Ensure that the list of extensions (presumably provided as a command option 'extensions') is valid, i.e. it is a list of Extension objects. We also support the old-style list of 2-tuples, where the tuples are (ext_name, build_info), which are converted to Extension instances here.
[ "Ensure", "that", "the", "list", "of", "extensions", "(", "presumably", "provided", "as", "a", "command", "option", "extensions", ")", "is", "valid", "i", ".", "e", ".", "it", "is", "a", "list", "of", "Extension", "objects", ".", "We", "also", "support",...
def check_extensions_list(self, extensions): """Ensure that the list of extensions (presumably provided as a command option 'extensions') is valid, i.e. it is a list of Extension objects. We also support the old-style list of 2-tuples, where the tuples are (ext_name, build_info), which are converted to Extension instances here. Raise DistutilsSetupError if the structure is invalid anywhere; just returns otherwise. """ if not isinstance(extensions, list): raise DistutilsSetupError, \ "'ext_modules' option must be a list of Extension instances" for i, ext in enumerate(extensions): if isinstance(ext, Extension): continue # OK! (assume type-checking done # by Extension constructor) if not isinstance(ext, tuple) or len(ext) != 2: raise DistutilsSetupError, \ ("each element of 'ext_modules' option must be an " "Extension instance or 2-tuple") ext_name, build_info = ext log.warn(("old-style (ext_name, build_info) tuple found in " "ext_modules for extension '%s' " "-- please convert to Extension instance" % ext_name)) if not (isinstance(ext_name, str) and extension_name_re.match(ext_name)): raise DistutilsSetupError, \ ("first element of each tuple in 'ext_modules' " "must be the extension name (a string)") if not isinstance(build_info, dict): raise DistutilsSetupError, \ ("second element of each tuple in 'ext_modules' " "must be a dictionary (build info)") # OK, the (ext_name, build_info) dict is type-safe: convert it # to an Extension instance. ext = Extension(ext_name, build_info['sources']) # Easy stuff: one-to-one mapping from dict elements to # instance attributes. for key in ('include_dirs', 'library_dirs', 'libraries', 'extra_objects', 'extra_compile_args', 'extra_link_args'): val = build_info.get(key) if val is not None: setattr(ext, key, val) # Medium-easy stuff: same syntax/semantics, different names. ext.runtime_library_dirs = build_info.get('rpath') if 'def_file' in build_info: log.warn("'def_file' element of build info dict " "no longer supported") # Non-trivial stuff: 'macros' split into 'define_macros' # and 'undef_macros'. macros = build_info.get('macros') if macros: ext.define_macros = [] ext.undef_macros = [] for macro in macros: if not (isinstance(macro, tuple) and len(macro) in (1, 2)): raise DistutilsSetupError, \ ("'macros' element of build info dict " "must be 1- or 2-tuple") if len(macro) == 1: ext.undef_macros.append(macro[0]) elif len(macro) == 2: ext.define_macros.append(macro) extensions[i] = ext
[ "def", "check_extensions_list", "(", "self", ",", "extensions", ")", ":", "if", "not", "isinstance", "(", "extensions", ",", "list", ")", ":", "raise", "DistutilsSetupError", ",", "\"'ext_modules' option must be a list of Extension instances\"", "for", "i", ",", "ext"...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/distutils/command/build_ext.py#L342-L418
htcondor/htcondor
4829724575176d1d6c936e4693dfd78a728569b0
src/condor_credd/condor_credmon_oauth/credmon/CredentialMonitors/OAuthCredmonWebserver/OAuthCredmonWebserver.py
python
oauth_return
(provider)
return redirect("/")
Returning from OAuth provider
Returning from OAuth provider
[ "Returning", "from", "OAuth", "provider" ]
def oauth_return(provider): """ Returning from OAuth provider """ # get the provider name from the outgoing_provider set in oauth_login() provider = session.pop('outgoing_provider', get_provider_str(provider, '')) if not ('providers' in session): sys.stderr.write('"providers" key was not found in session object: {0}\n'.format(session)) raise KeyError('Key "providers" was not found in session object. This session is invalid.') if not (provider in session['providers']): sys.stderr.write('key {0} was not found in session["providers"] dict: {1}\n'.format(provider, session)) raise KeyError("Provider {0} was not found in list of providers. This session is invalid.".format(provider)) provider_ad = get_provider_ad(provider, session['key_path']) # gather information from the key file classad client_id = provider_ad['ClientId'] redirect_uri = provider_ad['ReturnUrl'] state = session['providers'][provider]['state'] oauth = OAuth2Session(client_id, state=state, redirect_uri=redirect_uri) # convert http url to https if needed if request.url.startswith("http://"): updated_url = request.url.replace('http://', 'https://', 1) else: updated_url = request.url # fetch token client_secret = provider_ad['ClientSecret'] token_url = provider_ad['TokenUrl'] token = oauth.fetch_token(token_url, authorization_response=updated_url, client_secret=client_secret, method='POST', **fetch_token_kwargs) print('Got {0} token for user {1}'.format(provider, session['local_username'])) # get user info if available try: (user_url, user_field_keys) = api_endpoints.user(provider_ad['TokenUrl']) if user_url is not None: get_user_info = oauth.get(user_url) user_info = get_user_info.json() for user_field in user_field_keys: username = user_info[user_field] username = str(username) session['providers'][provider]['username'] = username elif 'sub' in token: # scitokens/jwt session['providers'][provider]['username'] = token['sub'] elif 'name' in token: # scitokens/jwt session['providers'][provider]['username'] = token['name'] else: session['providers'][provider]['username'] = 'Unknown' except ValueError: session['providers'][provider]['username'] = 'Unknown' # split off the refresh token from the access token if it exists try: refresh_token_string = token.pop('refresh_token') except KeyError: # no refresh token use_refresh_token = False refresh_token_string = '' else: use_refresh_token = True refresh_token = { 'refresh_token': refresh_token_string } if 'Scopes' in provider_ad and provider_ad['Scopes'] != "": # add scopes to the .top file, with blanks removed, for check # that makes sure the scopes don't change for a given request refresh_token['scopes'] = provider_ad['Scopes'].replace(" ","") if 'Audience' in provider_ad and provider_ad['Audience'] != "": # likewise for the audience refresh_token['audience'] = provider_ad['Audience'].replace(" ","") # create a metadata file for refreshing the token metadata = { 'client_id': client_id, 'client_secret': client_secret, 'token_url': token_url, 'use_refresh_token': use_refresh_token } # atomically write the tokens to the cred dir cred_dir = get_cred_dir() user_cred_dir = os.path.join(cred_dir, session['local_username']) if not os.path.isdir(user_cred_dir): os.makedirs(user_cred_dir) refresh_token_path = os.path.join(user_cred_dir, provider.replace(' ', '_') + '.top') access_token_path = os.path.join(user_cred_dir, provider.replace(' ', '_') + '.use') metadata_path = os.path.join(user_cred_dir, provider.replace(' ', '_') + '.meta') # write tokens to tmp files try: (tmp_fd, tmp_access_token_path) = tempfile.mkstemp(dir = user_cred_dir) except OSError as oe: print("Failed to create temporary file in the user credential directory: {0}".format(str(oe))) raise with os.fdopen(tmp_fd, 'w') as f: json.dump(token, f) (tmp_fd, tmp_refresh_token_path) = tempfile.mkstemp(dir = user_cred_dir) with os.fdopen(tmp_fd, 'w') as f: json.dump(refresh_token, f) (tmp_fd, tmp_metadata_path) = tempfile.mkstemp(dir = user_cred_dir) with os.fdopen(tmp_fd, 'w') as f: json.dump(metadata, f) # (over)write token files try: atomic_rename(tmp_access_token_path, access_token_path) atomic_rename(tmp_refresh_token_path, refresh_token_path) atomic_rename(tmp_metadata_path, metadata_path) except OSError as e: sys.stderr.write('{0}\n'.format(str(e))) # mark provider as logged in session['providers'][provider]['logged_in'] = True # check if other providers are logged in session['logged_in'] = True for provider in session['providers']: if session['providers'][provider]['logged_in'] == False: session['logged_in'] = False # cleanup key file if logged in if session['logged_in']: print('Attempting to remove session file {0}'.format(session['key_path'])) try: os.unlink(session['key_path']) except OSError as e: sys.stderr.write('Could not remove session file {0}: {1}\n'.format(session['key_path'], str(e))) return redirect("/")
[ "def", "oauth_return", "(", "provider", ")", ":", "# get the provider name from the outgoing_provider set in oauth_login()", "provider", "=", "session", ".", "pop", "(", "'outgoing_provider'", ",", "get_provider_str", "(", "provider", ",", "''", ")", ")", "if", "not", ...
https://github.com/htcondor/htcondor/blob/4829724575176d1d6c936e4693dfd78a728569b0/src/condor_credd/condor_credmon_oauth/credmon/CredentialMonitors/OAuthCredmonWebserver/OAuthCredmonWebserver.py#L235-L370
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/ops/distributions/special_math.py
python
ndtri
(p, name="ndtri")
The inverse of the CDF of the Normal distribution function. Returns x such that the area under the pdf from minus infinity to x is equal to p. A piece-wise rational approximation is done for the function. This is a port of the implementation in netlib. Args: p: `Tensor` of type `float32`, `float64`. name: Python string. A name for the operation (default="ndtri"). Returns: x: `Tensor` with `dtype=p.dtype`. Raises: TypeError: if `p` is not floating-type.
The inverse of the CDF of the Normal distribution function.
[ "The", "inverse", "of", "the", "CDF", "of", "the", "Normal", "distribution", "function", "." ]
def ndtri(p, name="ndtri"): """The inverse of the CDF of the Normal distribution function. Returns x such that the area under the pdf from minus infinity to x is equal to p. A piece-wise rational approximation is done for the function. This is a port of the implementation in netlib. Args: p: `Tensor` of type `float32`, `float64`. name: Python string. A name for the operation (default="ndtri"). Returns: x: `Tensor` with `dtype=p.dtype`. Raises: TypeError: if `p` is not floating-type. """ with ops.name_scope(name, values=[p]): p = ops.convert_to_tensor(p, name="p") if p.dtype.as_numpy_dtype not in [np.float32, np.float64]: raise TypeError( "p.dtype=%s is not handled, see docstring for supported types." % p.dtype) return _ndtri(p)
[ "def", "ndtri", "(", "p", ",", "name", "=", "\"ndtri\"", ")", ":", "with", "ops", ".", "name_scope", "(", "name", ",", "values", "=", "[", "p", "]", ")", ":", "p", "=", "ops", ".", "convert_to_tensor", "(", "p", ",", "name", "=", "\"p\"", ")", ...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/distributions/special_math.py#L104-L130
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_gdi.py
python
MemoryDC.SelectObject
(*args, **kwargs)
return _gdi_.MemoryDC_SelectObject(*args, **kwargs)
SelectObject(self, Bitmap bitmap) Selects the bitmap into the device context, to use as the memory bitmap. Selecting the bitmap into a memory DC allows you to draw into the DC, and therefore the bitmap, and also to use Blit to copy the bitmap to a window. If the argument is wx.NullBitmap (or some other uninitialised `wx.Bitmap`) the current bitmap is selected out of the device context, and the original bitmap restored, allowing the current bitmap to be destroyed safely.
SelectObject(self, Bitmap bitmap)
[ "SelectObject", "(", "self", "Bitmap", "bitmap", ")" ]
def SelectObject(*args, **kwargs): """ SelectObject(self, Bitmap bitmap) Selects the bitmap into the device context, to use as the memory bitmap. Selecting the bitmap into a memory DC allows you to draw into the DC, and therefore the bitmap, and also to use Blit to copy the bitmap to a window. If the argument is wx.NullBitmap (or some other uninitialised `wx.Bitmap`) the current bitmap is selected out of the device context, and the original bitmap restored, allowing the current bitmap to be destroyed safely. """ return _gdi_.MemoryDC_SelectObject(*args, **kwargs)
[ "def", "SelectObject", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "MemoryDC_SelectObject", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L5157-L5171
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/richtext.py
python
RichTextBuffer.SetScale
(*args, **kwargs)
return _richtext.RichTextBuffer_SetScale(*args, **kwargs)
SetScale(self, double scale)
SetScale(self, double scale)
[ "SetScale", "(", "self", "double", "scale", ")" ]
def SetScale(*args, **kwargs): """SetScale(self, double scale)""" return _richtext.RichTextBuffer_SetScale(*args, **kwargs)
[ "def", "SetScale", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextBuffer_SetScale", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L2639-L2641
facebookarchive/LogDevice
ce7726050edc49a1e15d9160e81c890736b779e2
build/fbcode_builder/getdeps/fetcher.py
python
ShipitPathMap.add_mapping
(self, fbsource_dir, target_dir)
Add a posix path or pattern. We cannot normpath the input here because that would change the paths from posix to windows form and break the logic throughout this class.
Add a posix path or pattern. We cannot normpath the input here because that would change the paths from posix to windows form and break the logic throughout this class.
[ "Add", "a", "posix", "path", "or", "pattern", ".", "We", "cannot", "normpath", "the", "input", "here", "because", "that", "would", "change", "the", "paths", "from", "posix", "to", "windows", "form", "and", "break", "the", "logic", "throughout", "this", "cl...
def add_mapping(self, fbsource_dir, target_dir): """Add a posix path or pattern. We cannot normpath the input here because that would change the paths from posix to windows form and break the logic throughout this class.""" self.roots.append(fbsource_dir) self.mapping.append((fbsource_dir, target_dir))
[ "def", "add_mapping", "(", "self", ",", "fbsource_dir", ",", "target_dir", ")", ":", "self", ".", "roots", ".", "append", "(", "fbsource_dir", ")", "self", ".", "mapping", ".", "append", "(", "(", "fbsource_dir", ",", "target_dir", ")", ")" ]
https://github.com/facebookarchive/LogDevice/blob/ce7726050edc49a1e15d9160e81c890736b779e2/build/fbcode_builder/getdeps/fetcher.py#L381-L386
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/contextlib.py
python
ExitStack.close
(self)
Immediately unwind the context stack.
Immediately unwind the context stack.
[ "Immediately", "unwind", "the", "context", "stack", "." ]
def close(self): """Immediately unwind the context stack.""" self.__exit__(None, None, None)
[ "def", "close", "(", "self", ")", ":", "self", ".", "__exit__", "(", "None", ",", "None", ",", "None", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/contextlib.py#L530-L532
gnina/gnina
b9ae032f52fc7a8153987bde09c0efa3620d8bb6
caffe/python/caffe/pycaffe.py
python
_Net_batch
(self, blobs)
Batch blob lists according to net's batch size. Parameters ---------- blobs: Keys blob names and values are lists of blobs (of any length). Naturally, all the lists should have the same length. Yields ------ batch: {blob name: list of blobs} dict for a single batch.
Batch blob lists according to net's batch size.
[ "Batch", "blob", "lists", "according", "to", "net", "s", "batch", "size", "." ]
def _Net_batch(self, blobs): """ Batch blob lists according to net's batch size. Parameters ---------- blobs: Keys blob names and values are lists of blobs (of any length). Naturally, all the lists should have the same length. Yields ------ batch: {blob name: list of blobs} dict for a single batch. """ num = len(six.next(six.itervalues(blobs))) batch_size = six.next(six.itervalues(self.blobs)).shape[0] remainder = num % batch_size num_batches = num // batch_size # Yield full batches. for b in range(num_batches): i = b * batch_size yield {name: blobs[name][i:i + batch_size] for name in blobs} # Yield last padded batch, if any. if remainder > 0: padded_batch = {} for name in blobs: padding = np.zeros((batch_size - remainder,) + blobs[name].shape[1:]) padded_batch[name] = np.concatenate([blobs[name][-remainder:], padding]) yield padded_batch
[ "def", "_Net_batch", "(", "self", ",", "blobs", ")", ":", "num", "=", "len", "(", "six", ".", "next", "(", "six", ".", "itervalues", "(", "blobs", ")", ")", ")", "batch_size", "=", "six", ".", "next", "(", "six", ".", "itervalues", "(", "self", "...
https://github.com/gnina/gnina/blob/b9ae032f52fc7a8153987bde09c0efa3620d8bb6/caffe/python/caffe/pycaffe.py#L272-L303
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
example/gluon/embedding_learning/train.py
python
train
(epochs, ctx)
return best_val
Training function.
Training function.
[ "Training", "function", "." ]
def train(epochs, ctx): """Training function.""" if isinstance(ctx, mx.Context): ctx = [ctx] net.initialize(mx.init.Xavier(magnitude=2), ctx=ctx) opt_options = {'learning_rate': opt.lr, 'wd': opt.wd} if opt.optimizer == 'sgd': opt_options['momentum'] = 0.9 if opt.optimizer == 'adam': opt_options['epsilon'] = 1e-7 trainer = gluon.Trainer(net.collect_params(), opt.optimizer, opt_options, kvstore=opt.kvstore) if opt.lr_beta > 0.0: # Jointly train class-specific beta. # See "sampling matters in deep embedding learning" paper for details. beta.initialize(mx.init.Constant(opt.beta), ctx=ctx) trainer_beta = gluon.Trainer([beta], 'sgd', {'learning_rate': opt.lr_beta, 'momentum': 0.9}, kvstore=opt.kvstore) loss = MarginLoss(margin=opt.margin, nu=opt.nu) best_val = 0.0 for epoch in range(epochs): tic = time.time() prev_loss, cumulative_loss = 0.0, 0.0 # Learning rate schedule. trainer.set_learning_rate(get_lr(opt.lr, epoch, steps, opt.factor)) logging.info('Epoch %d learning rate=%f', epoch, trainer.learning_rate) if opt.lr_beta > 0.0: trainer_beta.set_learning_rate(get_lr(opt.lr_beta, epoch, steps, opt.factor)) logging.info('Epoch %d beta learning rate=%f', epoch, trainer_beta.learning_rate) # Inner training loop. for i in range(200): batch = train_data.next() data = gluon.utils.split_and_load(batch.data[0], ctx_list=ctx, batch_axis=0) label = gluon.utils.split_and_load(batch.label[0], ctx_list=ctx, batch_axis=0) Ls = [] with ag.record(): for x, y in zip(data, label): a_indices, anchors, positives, negatives, _ = net(x) if opt.lr_beta > 0.0: L = loss(anchors, positives, negatives, beta, y[a_indices]) else: L = loss(anchors, positives, negatives, opt.beta, None) # Store the loss and do backward after we have done forward # on all GPUs for better speed on multiple GPUs. Ls.append(L) cumulative_loss += nd.mean(L).asscalar() for L in Ls: L.backward() # Update. trainer.step(batch.data[0].shape[0]) if opt.lr_beta > 0.0: trainer_beta.step(batch.data[0].shape[0]) if (i+1) % opt.log_interval == 0: logging.info('[Epoch %d, Iter %d] training loss=%f' % ( epoch, i+1, cumulative_loss - prev_loss)) prev_loss = cumulative_loss logging.info('[Epoch %d] training loss=%f'%(epoch, cumulative_loss)) logging.info('[Epoch %d] time cost: %f'%(epoch, time.time()-tic)) names, val_accs = test(ctx) for name, val_acc in zip(names, val_accs): logging.info('[Epoch %d] validation: %s=%f'%(epoch, name, val_acc)) if val_accs[0] > best_val: best_val = val_accs[0] logging.info('Saving %s.' % opt.save_model_prefix) net.save_parameters('%s.params' % opt.save_model_prefix) return best_val
[ "def", "train", "(", "epochs", ",", "ctx", ")", ":", "if", "isinstance", "(", "ctx", ",", "mx", ".", "Context", ")", ":", "ctx", "=", "[", "ctx", "]", "net", ".", "initialize", "(", "mx", ".", "init", ".", "Xavier", "(", "magnitude", "=", "2", ...
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/example/gluon/embedding_learning/train.py#L169-L250
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
catboost/jvm-packages/tools/copy_prebuilt_native_files.py
python
makedirs_if_not_exist
(dir_path)
ensure that target directory exists, can't use exist_ok flag because it is unavailable in python 2.7
ensure that target directory exists, can't use exist_ok flag because it is unavailable in python 2.7
[ "ensure", "that", "target", "directory", "exists", "can", "t", "use", "exist_ok", "flag", "because", "it", "is", "unavailable", "in", "python", "2", ".", "7" ]
def makedirs_if_not_exist(dir_path): """ ensure that target directory exists, can't use exist_ok flag because it is unavailable in python 2.7 """ try: os.makedirs(dir_path) except OSError as e: if e.errno != errno.EEXIST: raise
[ "def", "makedirs_if_not_exist", "(", "dir_path", ")", ":", "try", ":", "os", ".", "makedirs", "(", "dir_path", ")", "except", "OSError", "as", "e", ":", "if", "e", ".", "errno", "!=", "errno", ".", "EEXIST", ":", "raise" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/catboost/jvm-packages/tools/copy_prebuilt_native_files.py#L10-L19
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
third_party/closure_linter/closure_linter/ecmametadatapass.py
python
EcmaMetaDataPass.__init__
(self)
Initialize the meta data pass object.
Initialize the meta data pass object.
[ "Initialize", "the", "meta", "data", "pass", "object", "." ]
def __init__(self): """Initialize the meta data pass object.""" self.Reset()
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "Reset", "(", ")" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/closure_linter/closure_linter/ecmametadatapass.py#L188-L190
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/io/pytables.py
python
HDFStore.put
(self, key, value, format=None, append=False, **kwargs)
Store object in HDFStore Parameters ---------- key : object value : {Series, DataFrame, Panel} format : 'fixed(f)|table(t)', default is 'fixed' fixed(f) : Fixed format Fast writing/reading. Not-appendable, nor searchable table(t) : Table format Write as a PyTables Table structure which may perform worse but allow more flexible operations like searching / selecting subsets of the data append : boolean, default False This will force Table format, append the input data to the existing. data_columns : list of columns to create as data columns, or True to use all columns. See `here <http://pandas.pydata.org/pandas-docs/stable/io.html#query-via-data-columns>`__ # noqa encoding : default None, provide an encoding for strings dropna : boolean, default False, do not write an ALL nan row to the store settable by the option 'io.hdf.dropna_table'
Store object in HDFStore
[ "Store", "object", "in", "HDFStore" ]
def put(self, key, value, format=None, append=False, **kwargs): """ Store object in HDFStore Parameters ---------- key : object value : {Series, DataFrame, Panel} format : 'fixed(f)|table(t)', default is 'fixed' fixed(f) : Fixed format Fast writing/reading. Not-appendable, nor searchable table(t) : Table format Write as a PyTables Table structure which may perform worse but allow more flexible operations like searching / selecting subsets of the data append : boolean, default False This will force Table format, append the input data to the existing. data_columns : list of columns to create as data columns, or True to use all columns. See `here <http://pandas.pydata.org/pandas-docs/stable/io.html#query-via-data-columns>`__ # noqa encoding : default None, provide an encoding for strings dropna : boolean, default False, do not write an ALL nan row to the store settable by the option 'io.hdf.dropna_table' """ if format is None: format = get_option("io.hdf.default_format") or 'fixed' kwargs = self._validate_format(format, kwargs) self._write_to_group(key, value, append=append, **kwargs)
[ "def", "put", "(", "self", ",", "key", ",", "value", ",", "format", "=", "None", ",", "append", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "format", "is", "None", ":", "format", "=", "get_option", "(", "\"io.hdf.default_format\"", ")", "o...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/io/pytables.py#L861-L889
devpack/android-python27
d42dd67565e104cf7b0b50eb473f615db3e69901
python-build-with-qt/sip-4.11.2/siputils.py
python
ModuleMakefile.generate_target_clean
(self, mfile)
Generate the clean target. mfile is the file object.
Generate the clean target.
[ "Generate", "the", "clean", "target", "." ]
def generate_target_clean(self, mfile): """Generate the clean target. mfile is the file object. """ mfile.write("\nclean:\n") self.clean_build_file_objects(mfile, self._build) if self._manifest and not self.static: mfile.write("\t-%s $(TARGET).manifest\n" % self.rm) # Remove any export file on AIX, Linux and Solaris. if self._limit_exports and (sys.platform[:5] == 'linux' or sys.platform[:5] == 'sunos' or sys.platform[:3] == 'aix'): mfile.write("\t-%s %s.exp\n" % (self.rm, self._target))
[ "def", "generate_target_clean", "(", "self", ",", "mfile", ")", ":", "mfile", ".", "write", "(", "\"\\nclean:\\n\"", ")", "self", ".", "clean_build_file_objects", "(", "mfile", ",", "self", ".", "_build", ")", "if", "self", ".", "_manifest", "and", "not", ...
https://github.com/devpack/android-python27/blob/d42dd67565e104cf7b0b50eb473f615db3e69901/python-build-with-qt/sip-4.11.2/siputils.py#L1626-L1641
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
src/pybind/mgr/k8sevents/module.py
python
Module.k8s_ready
(self)
return ready, missing
Validate the k8s_config dict Returns: - bool .... indicating whether the config is ready to use - string .. variables that need to be defined before the module will function
Validate the k8s_config dict
[ "Validate", "the", "k8s_config", "dict" ]
def k8s_ready(self): """Validate the k8s_config dict Returns: - bool .... indicating whether the config is ready to use - string .. variables that need to be defined before the module will function """ missing = list() ready = True for k in self.k8s_config: if not self.k8s_config[k]: missing.append(k) ready = False return ready, missing
[ "def", "k8s_ready", "(", "self", ")", ":", "missing", "=", "list", "(", ")", "ready", "=", "True", "for", "k", "in", "self", ".", "k8s_config", ":", "if", "not", "self", ".", "k8s_config", "[", "k", "]", ":", "missing", ".", "append", "(", "k", "...
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/pybind/mgr/k8sevents/module.py#L1080-L1094
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/functions/DSFinterp1DFit.py
python
DSFinterp1DFit.function1D
(self, xvals)
return intensities_interpolator(xvals)
Fit using the interpolated structure factor
Fit using the interpolated structure factor
[ "Fit", "using", "the", "interpolated", "structure", "factor" ]
def function1D(self, xvals): ''' Fit using the interpolated structure factor ''' p = self.validateParams() if not p: # return zeros if parameters not valid return numpy.zeros(len(xvals), dtype=float) # The first time the function is called requires initialization of the interpolator if self._channelgroup is None: # Check consistency of the input # check InputWorkspaces have at least the workspace index for w in self._InputWorkspaces: if mtd[w].getNumberHistograms() <= self._WorkspaceIndex: message = 'Numer of histograms in Workspace {0} does not allow for workspace index {1}'.format( w, self._WorkspaceIndex) logger.error(message) raise IndexError(message) # check number of input workspaces and parameters is the same if len(self._ParameterValues) != len(self._InputWorkspaces): message = 'Number of InputWorkspaces and ParameterValues should be the same.' +\ ' Found {0} and {1}, respectively'.format( len(self._InputWorkspaces), len(self._ParameterValues)) logger.error(message) raise ValueError(message) # check the regression type is valid if self._RegressionType not in self._RegressionTypes: message = 'Regression type {0} not implemented. choose one of {1}'.format(self._RegressionType, ', '.join(self._RegressionTypes)) logger.error(message) raise NotImplementedError(message) # check the regression window is appropriate for the regression type selected if self._RegressionWindow < self._minWindow[self._RegressionType]: message = 'RegressionWindow must be equal or bigger than ' +\ '{0} for regression type {1}'.format( self._minWindow[self._RegressionType], self._RegressionType) logger.error(message) raise ValueError(message) # Initialize the energies of the channels with the first of the input workspaces self._xvalues = numpy.copy( mtd[self._InputWorkspaces[0]].dataX(self._WorkspaceIndex)) if len(self._xvalues) == 1 + len(mtd[self._InputWorkspaces[0]].dataY(self._WorkspaceIndex)): # Deal with histogram data self._xvalues = (self._xvalues[1:]+self._xvalues[:-1])/2.0 # Initialize the channel group nf = len(self._ParameterValues) # Load the InputWorkspaces into a group of dynamic structure factors from dsfinterp.dsf import Dsf from dsfinterp.dsfgroup import DsfGroup dsfgroup = DsfGroup() for idsf in range(nf): dsf = Dsf() dsf.SetIntensities( mtd[self._InputWorkspaces[idsf]].dataY(self._WorkspaceIndex)) dsf.errors = None # do not incorporate error data if self._LoadErrors: dsf.SetErrors(mtd[self._InputWorkspaces[idsf]].dataE( self._WorkspaceIndex)) dsf.SetFvalue(self._ParameterValues[idsf]) dsfgroup.InsertDsf(dsf) # Create the interpolator from dsfinterp.channelgroup import ChannelGroup self._channelgroup = ChannelGroup() self._channelgroup.InitFromDsfGroup(dsfgroup) if self._LocalRegression: self._channelgroup.InitializeInterpolator( running_regr_type=self._RegressionType, windowlength=self._RegressionWindow) else: self._channelgroup.InitializeInterpolator(windowlength=0) # channel group has been initialized, so evaluate the interpolator dsf = self._channelgroup(p['TargetParameter']) # Linear interpolation between the energies of the channels and the xvalues we require # NOTE: interpolator evaluates to zero for any of the xvals outside of the domain defined by self._xvalues intensities_interpolator = scipy.interpolate.interp1d( self._xvalues, p['Intensity']*dsf.intensities, kind='linear') return intensities_interpolator(xvals)
[ "def", "function1D", "(", "self", ",", "xvals", ")", ":", "p", "=", "self", ".", "validateParams", "(", ")", "if", "not", "p", ":", "# return zeros if parameters not valid", "return", "numpy", ".", "zeros", "(", "len", "(", "xvals", ")", ",", "dtype", "=...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/functions/DSFinterp1DFit.py#L111-L184
SpaceNetChallenge/BuildingDetectors
3def3c44b5847c744cd2f3356182892d92496579
qinhaifang/src/caffe-mnc/scripts/cpp_lint.py
python
PrintCategories
()
Prints a list of all the error-categories used by error messages. These are the categories used to filter messages via --filter.
Prints a list of all the error-categories used by error messages.
[ "Prints", "a", "list", "of", "all", "the", "error", "-", "categories", "used", "by", "error", "messages", "." ]
def PrintCategories(): """Prints a list of all the error-categories used by error messages. These are the categories used to filter messages via --filter. """ sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES)) sys.exit(0)
[ "def", "PrintCategories", "(", ")", ":", "sys", ".", "stderr", ".", "write", "(", "''", ".", "join", "(", "' %s\\n'", "%", "cat", "for", "cat", "in", "_ERROR_CATEGORIES", ")", ")", "sys", ".", "exit", "(", "0", ")" ]
https://github.com/SpaceNetChallenge/BuildingDetectors/blob/3def3c44b5847c744cd2f3356182892d92496579/qinhaifang/src/caffe-mnc/scripts/cpp_lint.py#L4770-L4776
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_controls.py
python
TextAttr.SetAlignment
(*args, **kwargs)
return _controls_.TextAttr_SetAlignment(*args, **kwargs)
SetAlignment(self, int alignment)
SetAlignment(self, int alignment)
[ "SetAlignment", "(", "self", "int", "alignment", ")" ]
def SetAlignment(*args, **kwargs): """SetAlignment(self, int alignment)""" return _controls_.TextAttr_SetAlignment(*args, **kwargs)
[ "def", "SetAlignment", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "TextAttr_SetAlignment", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L1519-L1521
zju3dv/clean-pvnet
5870c509e3cc205e1bb28910a7b1a9a3c8add9a8
lib/utils/meshrenderer/pysixd/transform.py
python
random_rotation_matrix
(rand=None)
return quaternion_matrix(random_quaternion(rand))
Return uniform random rotation matrix. rand: array like Three independent random variables that are uniformly distributed between 0 and 1 for each returned quaternion. >>> R = random_rotation_matrix() >>> numpy.allclose(numpy.dot(R.T, R), numpy.identity(4)) True
Return uniform random rotation matrix.
[ "Return", "uniform", "random", "rotation", "matrix", "." ]
def random_rotation_matrix(rand=None): """Return uniform random rotation matrix. rand: array like Three independent random variables that are uniformly distributed between 0 and 1 for each returned quaternion. >>> R = random_rotation_matrix() >>> numpy.allclose(numpy.dot(R.T, R), numpy.identity(4)) True """ return quaternion_matrix(random_quaternion(rand))
[ "def", "random_rotation_matrix", "(", "rand", "=", "None", ")", ":", "return", "quaternion_matrix", "(", "random_quaternion", "(", "rand", ")", ")" ]
https://github.com/zju3dv/clean-pvnet/blob/5870c509e3cc205e1bb28910a7b1a9a3c8add9a8/lib/utils/meshrenderer/pysixd/transform.py#L1491-L1503
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/buildscripts/resmokelib/selector.py
python
TestFileExplorer.list_dbtests
(self, dbtest_binary)
return stdout.splitlines()
Lists the available dbtests suites.
Lists the available dbtests suites.
[ "Lists", "the", "available", "dbtests", "suites", "." ]
def list_dbtests(self, dbtest_binary): """Lists the available dbtests suites.""" returncode, stdout = self._run_program(dbtest_binary, ["--list"]) if returncode != 0: raise errors.ResmokeError("Getting list of dbtest suites failed") return stdout.splitlines()
[ "def", "list_dbtests", "(", "self", ",", "dbtest_binary", ")", ":", "returncode", ",", "stdout", "=", "self", ".", "_run_program", "(", "dbtest_binary", ",", "[", "\"--list\"", "]", ")", "if", "returncode", "!=", "0", ":", "raise", "errors", ".", "ResmokeE...
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/resmokelib/selector.py#L86-L93
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/series.py
python
Series.to_period
(self, freq=None, copy=True)
return self._constructor(new_values, index=new_index).__finalize__(self)
Convert Series from DatetimeIndex to PeriodIndex with desired frequency (inferred from index if not passed). Parameters ---------- freq : string, default Returns ------- ts : Series with PeriodIndex
Convert Series from DatetimeIndex to PeriodIndex with desired frequency (inferred from index if not passed).
[ "Convert", "Series", "from", "DatetimeIndex", "to", "PeriodIndex", "with", "desired", "frequency", "(", "inferred", "from", "index", "if", "not", "passed", ")", "." ]
def to_period(self, freq=None, copy=True): """ Convert Series from DatetimeIndex to PeriodIndex with desired frequency (inferred from index if not passed). Parameters ---------- freq : string, default Returns ------- ts : Series with PeriodIndex """ new_values = self._values if copy: new_values = new_values.copy() new_index = self.index.to_period(freq=freq) return self._constructor(new_values, index=new_index).__finalize__(self)
[ "def", "to_period", "(", "self", ",", "freq", "=", "None", ",", "copy", "=", "True", ")", ":", "new_values", "=", "self", ".", "_values", "if", "copy", ":", "new_values", "=", "new_values", ".", "copy", "(", ")", "new_index", "=", "self", ".", "index...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/series.py#L4351-L4370
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/numpy/files/numpy/f2py/capi_maps.py
python
sign2map
(a,var)
return ret
varname,ctype,atype init,init.r,init.i,pytype vardebuginfo,vardebugshowvalue,varshowvalue varrfromat intent
varname,ctype,atype init,init.r,init.i,pytype vardebuginfo,vardebugshowvalue,varshowvalue varrfromat intent
[ "varname", "ctype", "atype", "init", "init", ".", "r", "init", ".", "i", "pytype", "vardebuginfo", "vardebugshowvalue", "varshowvalue", "varrfromat", "intent" ]
def sign2map(a,var): """ varname,ctype,atype init,init.r,init.i,pytype vardebuginfo,vardebugshowvalue,varshowvalue varrfromat intent """ global lcb_map,cb_map out_a = a if isintent_out(var): for k in var['intent']: if k[:4]=='out=': out_a = k[4:] break ret={'varname':a,'outvarname':out_a} ret['ctype']=getctype(var) intent_flags = [] for f,s in isintent_dict.items(): if f(var): intent_flags.append('F2PY_%s'%s) if intent_flags: #XXX: Evaluate intent_flags here. ret['intent'] = '|'.join(intent_flags) else: ret['intent'] = 'F2PY_INTENT_IN' if isarray(var): ret['varrformat']='N' elif ret['ctype'] in c2buildvalue_map: ret['varrformat']=c2buildvalue_map[ret['ctype']] else: ret['varrformat']='O' ret['init'],ret['showinit']=getinit(a,var) if hasinitvalue(var) and iscomplex(var) and not isarray(var): ret['init.r'],ret['init.i'] = markoutercomma(ret['init'][1:-1]).split('@,@') if isexternal(var): ret['cbnamekey']=a if a in lcb_map: ret['cbname']=lcb_map[a] ret['maxnofargs']=lcb2_map[lcb_map[a]]['maxnofargs'] ret['nofoptargs']=lcb2_map[lcb_map[a]]['nofoptargs'] ret['cbdocstr']=lcb2_map[lcb_map[a]]['docstr'] ret['cblatexdocstr']=lcb2_map[lcb_map[a]]['latexdocstr'] else: ret['cbname']=a errmess('sign2map: Confused: external %s is not in lcb_map%s.\n'%(a,lcb_map.keys())) if isstring(var): ret['length']=getstrlength(var) if isarray(var): ret=dictappend(ret,getarrdims(a,var)) dim=copy.copy(var['dimension']) if ret['ctype'] in c2capi_map: ret['atype']=c2capi_map[ret['ctype']] # Debug info if debugcapi(var): il=[isintent_in,'input',isintent_out,'output', isintent_inout,'inoutput',isrequired,'required', isoptional,'optional',isintent_hide,'hidden', iscomplex,'complex scalar', l_and(isscalar,l_not(iscomplex)),'scalar', isstring,'string',isarray,'array', iscomplexarray,'complex array',isstringarray,'string array', iscomplexfunction,'complex function', l_and(isfunction,l_not(iscomplexfunction)),'function', isexternal,'callback', isintent_callback,'callback', isintent_aux,'auxiliary', #ismutable,'mutable',l_not(ismutable),'immutable', ] rl=[] for i in range(0,len(il),2): if il[i](var): rl.append(il[i+1]) if isstring(var): rl.append('slen(%s)=%s'%(a,ret['length'])) if isarray(var): # if not isintent_c(var): # var['dimension'].reverse() ddim=','.join(map(lambda x,y:'%s|%s'%(x,y),var['dimension'],dim)) rl.append('dims(%s)'%ddim) # if not isintent_c(var): # var['dimension'].reverse() if isexternal(var): ret['vardebuginfo']='debug-capi:%s=>%s:%s'%(a,ret['cbname'],','.join(rl)) else: ret['vardebuginfo']='debug-capi:%s %s=%s:%s'%(ret['ctype'],a,ret['showinit'],','.join(rl)) if isscalar(var): if ret['ctype'] in cformat_map: ret['vardebugshowvalue']='debug-capi:%s=%s'%(a,cformat_map[ret['ctype']]) if isstring(var): ret['vardebugshowvalue']='debug-capi:slen(%s)=%%d %s=\\"%%s\\"'%(a,a) if isexternal(var): ret['vardebugshowvalue']='debug-capi:%s=%%p'%(a) if ret['ctype'] in cformat_map: ret['varshowvalue']='#name#:%s=%s'%(a,cformat_map[ret['ctype']]) ret['showvalueformat']='%s'%(cformat_map[ret['ctype']]) if isstring(var): ret['varshowvalue']='#name#:slen(%s)=%%d %s=\\"%%s\\"'%(a,a) ret['pydocsign'],ret['pydocsignout']=getpydocsign(a,var) if hasnote(var): ret['note']=var['note'] return ret
[ "def", "sign2map", "(", "a", ",", "var", ")", ":", "global", "lcb_map", ",", "cb_map", "out_a", "=", "a", "if", "isintent_out", "(", "var", ")", ":", "for", "k", "in", "var", "[", "'intent'", "]", ":", "if", "k", "[", ":", "4", "]", "==", "'out...
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/f2py/capi_maps.py#L450-L547
neopenx/Dragon
0e639a7319035ddc81918bd3df059230436ee0a1
Dragon/python/dragon/vm/theano/tensor/basic.py
python
ones_like
(model, dtype=None, **kwargs)
return ops.Fill(shape=ops.Shape(model), value=1)
Initialize a tensor with ones, refer the shape of another tensor. The values can be access only after the run of graph. If dtype is ``None``, use ``config.floatX``. Parameters ---------- model : Tensor The tensor to refer shape. dtype : str The data type of Tensor. Returns ------- Tensor The initialized tensor.
Initialize a tensor with ones, refer the shape of another tensor.
[ "Initialize", "a", "tensor", "with", "ones", "refer", "the", "shape", "of", "another", "tensor", "." ]
def ones_like(model, dtype=None, **kwargs): """Initialize a tensor with ones, refer the shape of another tensor. The values can be access only after the run of graph. If dtype is ``None``, use ``config.floatX``. Parameters ---------- model : Tensor The tensor to refer shape. dtype : str The data type of Tensor. Returns ------- Tensor The initialized tensor. """ if dtype is None: dtype = config.floatX else: raise TypeError("Unsupported data type: {}".format(dtype)) return ops.Fill(shape=ops.Shape(model), value=1)
[ "def", "ones_like", "(", "model", ",", "dtype", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "dtype", "is", "None", ":", "dtype", "=", "config", ".", "floatX", "else", ":", "raise", "TypeError", "(", "\"Unsupported data type: {}\"", ".", "format...
https://github.com/neopenx/Dragon/blob/0e639a7319035ddc81918bd3df059230436ee0a1/Dragon/python/dragon/vm/theano/tensor/basic.py#L178-L201
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/numpy/files/numpy/ma/extras.py
python
clump_unmasked
(a)
return result
Return list of slices corresponding to the unmasked clumps of a 1-D array. (A "clump" is defined as a contiguous region of the array). Parameters ---------- a : ndarray A one-dimensional masked array. Returns ------- slices : list of slice The list of slices, one for each continuous region of unmasked elements in `a`. Notes ----- .. versionadded:: 1.4.0 See Also -------- flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges, notmasked_contiguous, clump_masked Examples -------- >>> a = np.ma.masked_array(np.arange(10)) >>> a[[0, 1, 2, 6, 8, 9]] = np.ma.masked >>> np.ma.extras.clump_unmasked(a) [slice(3, 6, None), slice(7, 8, None)]
Return list of slices corresponding to the unmasked clumps of a 1-D array. (A "clump" is defined as a contiguous region of the array).
[ "Return", "list", "of", "slices", "corresponding", "to", "the", "unmasked", "clumps", "of", "a", "1", "-", "D", "array", ".", "(", "A", "clump", "is", "defined", "as", "a", "contiguous", "region", "of", "the", "array", ")", "." ]
def clump_unmasked(a): """ Return list of slices corresponding to the unmasked clumps of a 1-D array. (A "clump" is defined as a contiguous region of the array). Parameters ---------- a : ndarray A one-dimensional masked array. Returns ------- slices : list of slice The list of slices, one for each continuous region of unmasked elements in `a`. Notes ----- .. versionadded:: 1.4.0 See Also -------- flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges, notmasked_contiguous, clump_masked Examples -------- >>> a = np.ma.masked_array(np.arange(10)) >>> a[[0, 1, 2, 6, 8, 9]] = np.ma.masked >>> np.ma.extras.clump_unmasked(a) [slice(3, 6, None), slice(7, 8, None)] """ mask = getattr(a, '_mask', nomask) if mask is nomask: return [slice(0, a.size)] slices = _ezclump(mask) if a[0] is masked: result = slices[1::2] else: result = slices[::2] return result
[ "def", "clump_unmasked", "(", "a", ")", ":", "mask", "=", "getattr", "(", "a", ",", "'_mask'", ",", "nomask", ")", "if", "mask", "is", "nomask", ":", "return", "[", "slice", "(", "0", ",", "a", ".", "size", ")", "]", "slices", "=", "_ezclump", "(...
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/ma/extras.py#L1742-L1783
KratosMultiphysics/Kratos
0000833054ed0503424eb28205d6508d9ca6cbbc
applications/CoSimulationApplication/python_scripts/data_transfer_operators/kratos_mapping.py
python
KratosMappingDataTransferOperator.__GetModelPartFromInterfaceData
(interface_data)
If the solver does not exist on this rank, then pass a dummy ModelPart to the Mapper that has a DataCommunicator that is not defined on this rank
If the solver does not exist on this rank, then pass a dummy ModelPart to the Mapper that has a DataCommunicator that is not defined on this rank
[ "If", "the", "solver", "does", "not", "exist", "on", "this", "rank", "then", "pass", "a", "dummy", "ModelPart", "to", "the", "Mapper", "that", "has", "a", "DataCommunicator", "that", "is", "not", "defined", "on", "this", "rank" ]
def __GetModelPartFromInterfaceData(interface_data): """If the solver does not exist on this rank, then pass a dummy ModelPart to the Mapper that has a DataCommunicator that is not defined on this rank """ if interface_data.IsDefinedOnThisRank(): return interface_data.GetModelPart() else: return KratosMappingDataTransferOperator.__GetRankZeroModelPart()
[ "def", "__GetModelPartFromInterfaceData", "(", "interface_data", ")", ":", "if", "interface_data", ".", "IsDefinedOnThisRank", "(", ")", ":", "return", "interface_data", ".", "GetModelPart", "(", ")", "else", ":", "return", "KratosMappingDataTransferOperator", ".", "_...
https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/CoSimulationApplication/python_scripts/data_transfer_operators/kratos_mapping.py#L117-L125
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
contrib/gizmos/msw/gizmos.py
python
TreeListCtrl.__init__
(self, *args, **kwargs)
__init__(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=TR_DEFAULT_STYLE, Validator validator=DefaultValidator, String name=TreeListCtrlNameStr) -> TreeListCtrl
__init__(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=TR_DEFAULT_STYLE, Validator validator=DefaultValidator, String name=TreeListCtrlNameStr) -> TreeListCtrl
[ "__init__", "(", "self", "Window", "parent", "int", "id", "=", "-", "1", "Point", "pos", "=", "DefaultPosition", "Size", "size", "=", "DefaultSize", "long", "style", "=", "TR_DEFAULT_STYLE", "Validator", "validator", "=", "DefaultValidator", "String", "name", ...
def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=TR_DEFAULT_STYLE, Validator validator=DefaultValidator, String name=TreeListCtrlNameStr) -> TreeListCtrl """ _gizmos.TreeListCtrl_swiginit(self,_gizmos.new_TreeListCtrl(*args, **kwargs)) self._setOORInfo(self);TreeListCtrl._setCallbackInfo(self, self, TreeListCtrl)
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_gizmos", ".", "TreeListCtrl_swiginit", "(", "self", ",", "_gizmos", ".", "new_TreeListCtrl", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "self", ".", "_se...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/msw/gizmos.py#L474-L482
SIPp/sipp
f44d0cf5dec0013eff8fd7b4da885d455aa82e0e
cpplint.py
python
GetLineWidth
(line)
Determines the width of the line in column positions. Args: line: A string, which may be a Unicode string. Returns: The width of the line in column positions, accounting for Unicode combining characters and wide characters.
Determines the width of the line in column positions.
[ "Determines", "the", "width", "of", "the", "line", "in", "column", "positions", "." ]
def GetLineWidth(line): """Determines the width of the line in column positions. Args: line: A string, which may be a Unicode string. Returns: The width of the line in column positions, accounting for Unicode combining characters and wide characters. """ if isinstance(line, unicode): width = 0 for uc in unicodedata.normalize('NFC', line): if unicodedata.east_asian_width(uc) in ('W', 'F'): width += 2 elif not unicodedata.combining(uc): width += 1 return width else: return len(line)
[ "def", "GetLineWidth", "(", "line", ")", ":", "if", "isinstance", "(", "line", ",", "unicode", ")", ":", "width", "=", "0", "for", "uc", "in", "unicodedata", ".", "normalize", "(", "'NFC'", ",", "line", ")", ":", "if", "unicodedata", ".", "east_asian_w...
https://github.com/SIPp/sipp/blob/f44d0cf5dec0013eff8fd7b4da885d455aa82e0e/cpplint.py#L2770-L2789
cmu-db/noisepage
79276e68fe83322f1249e8a8be96bd63c583ae56
script/self_driving/model_server.py
python
_infer_with_cache
(model, features, cache)
return np.array(results)
Perform model inference with caching :param model: the model to invoke :param features: input features :param cache: cache the inference result based on the input feature :return: inference results with the features
Perform model inference with caching :param model: the model to invoke :param features: input features :param cache: cache the inference result based on the input feature :return: inference results with the features
[ "Perform", "model", "inference", "with", "caching", ":", "param", "model", ":", "the", "model", "to", "invoke", ":", "param", "features", ":", "input", "features", ":", "param", "cache", ":", "cache", "the", "inference", "result", "based", "on", "the", "in...
def _infer_with_cache(model, features, cache): """ Perform model inference with caching :param model: the model to invoke :param features: input features :param cache: cache the inference result based on the input feature :return: inference results with the features """ # Convert features to integers to use for cache key int_features = (features * 100).astype(int) n = features.shape[0] results = [] for i in range(n): # convert to tuple as hash key feature = tuple(int_features[i]) if feature not in cache: # TODO(lin): we may want to infer all the uncached features at once to make it a bit faster? This seems # fine for now pred = model.predict(features[i:i+1])[0] cache[feature] = pred results.append(cache[feature]) return np.array(results)
[ "def", "_infer_with_cache", "(", "model", ",", "features", ",", "cache", ")", ":", "# Convert features to integers to use for cache key", "int_features", "=", "(", "features", "*", "100", ")", ".", "astype", "(", "int", ")", "n", "=", "features", ".", "shape", ...
https://github.com/cmu-db/noisepage/blob/79276e68fe83322f1249e8a8be96bd63c583ae56/script/self_driving/model_server.py#L202-L225
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/model/sensing.py
python
camera_ray
(camera : SimRobotSensor, robot : RobotModel, x : float, y : float)
return camera_to_viewport(camera,robot).click_ray(x,y)
Returns the (source,direction) of a ray emanating from the SimRobotSensor at pixel coordinates (x,y). If you are doing this multiple times, it's faster to convert the camera to GLViewport and use GLViewport.click_ray. Arguments: camera (SimRobotSensor): the camera robot (RobotModel): the robot on which the camera is mounted. x (int/float): x pixel coordinates y (int/float): y pixel coordinates Returns: A pair (source,direction) giving the world-space ray source/direction.
Returns the (source,direction) of a ray emanating from the SimRobotSensor at pixel coordinates (x,y).
[ "Returns", "the", "(", "source", "direction", ")", "of", "a", "ray", "emanating", "from", "the", "SimRobotSensor", "at", "pixel", "coordinates", "(", "x", "y", ")", "." ]
def camera_ray(camera : SimRobotSensor, robot : RobotModel, x : float, y : float) -> Tuple[Vector3,Vector3]: """Returns the (source,direction) of a ray emanating from the SimRobotSensor at pixel coordinates (x,y). If you are doing this multiple times, it's faster to convert the camera to GLViewport and use GLViewport.click_ray. Arguments: camera (SimRobotSensor): the camera robot (RobotModel): the robot on which the camera is mounted. x (int/float): x pixel coordinates y (int/float): y pixel coordinates Returns: A pair (source,direction) giving the world-space ray source/direction. """ return camera_to_viewport(camera,robot).click_ray(x,y)
[ "def", "camera_ray", "(", "camera", ":", "SimRobotSensor", ",", "robot", ":", "RobotModel", ",", "x", ":", "float", ",", "y", ":", "float", ")", "->", "Tuple", "[", "Vector3", ",", "Vector3", "]", ":", "return", "camera_to_viewport", "(", "camera", ",", ...
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/model/sensing.py#L845-L861
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/os2emxpath.py
python
ismount
(path)
return len(p) == 1 and p[0] in '/\\'
Test whether a path is a mount point (defined as root of drive)
Test whether a path is a mount point (defined as root of drive)
[ "Test", "whether", "a", "path", "is", "a", "mount", "point", "(", "defined", "as", "root", "of", "drive", ")" ]
def ismount(path): """Test whether a path is a mount point (defined as root of drive)""" unc, rest = splitunc(path) if unc: return rest in ("", "/", "\\") p = splitdrive(path)[1] return len(p) == 1 and p[0] in '/\\'
[ "def", "ismount", "(", "path", ")", ":", "unc", ",", "rest", "=", "splitunc", "(", "path", ")", "if", "unc", ":", "return", "rest", "in", "(", "\"\"", ",", "\"/\"", ",", "\"\\\\\"", ")", "p", "=", "splitdrive", "(", "path", ")", "[", "1", "]", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/os2emxpath.py#L110-L116
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/array_grad.py
python
_MatrixSetDiagGradV2
(op, grad)
return (grad_input, grad_diag, None)
Gradient for MatrixSetDiagV2.
Gradient for MatrixSetDiagV2.
[ "Gradient", "for", "MatrixSetDiagV2", "." ]
def _MatrixSetDiagGradV2(op, grad): """Gradient for MatrixSetDiagV2.""" diag_shape = op.inputs[1].get_shape() if not diag_shape.is_fully_defined(): # Need to know the values of `d_lower` and `d_upper` to infer diag_shape. grad_shape = array_ops.shape(grad) batch_shape = grad_shape[:-2] matrix_shape = grad_shape[-2:] diag_index = array_ops.reshape(op.inputs[2], [-1]) # Converts to vector. d_lower = diag_index[0] d_upper = diag_index[-1] # Works both when len(diag_index) is 1 and 2. y_offset = control_flow_ops.cond( math_ops.less(d_upper, 0), lambda: d_upper, lambda: 0) x_offset = control_flow_ops.cond( math_ops.greater(d_lower, 0), lambda: -d_lower, lambda: 0) max_diag_len = math_ops.minimum(matrix_shape[0] + y_offset, matrix_shape[1] + x_offset) # pylint: disable=g-long-lambda # pyformat: disable postfix = control_flow_ops.cond( math_ops.equal(d_lower, d_upper), lambda: ops.convert_to_tensor([max_diag_len]), lambda: ops.convert_to_tensor([d_upper - d_lower + 1, max_diag_len])) # pyformat: enable # pylint: enable=g-long-lambda diag_shape = array_ops.concat([batch_shape, postfix], 0) grad_input = array_ops.matrix_set_diag( grad, array_ops.zeros(diag_shape, dtype=grad.dtype), k=op.inputs[2]) grad_diag = array_ops.matrix_diag_part(grad, k=op.inputs[2]) return (grad_input, grad_diag, None)
[ "def", "_MatrixSetDiagGradV2", "(", "op", ",", "grad", ")", ":", "diag_shape", "=", "op", ".", "inputs", "[", "1", "]", ".", "get_shape", "(", ")", "if", "not", "diag_shape", ".", "is_fully_defined", "(", ")", ":", "# Need to know the values of `d_lower` and `...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/array_grad.py#L452-L484
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/setuptools/command/build_ext.py
python
build_ext.run
(self)
Build extensions in build directory, then copy if --inplace
Build extensions in build directory, then copy if --inplace
[ "Build", "extensions", "in", "build", "directory", "then", "copy", "if", "--", "inplace" ]
def run(self): """Build extensions in build directory, then copy if --inplace""" old_inplace, self.inplace = self.inplace, 0 _build_ext.run(self) self.inplace = old_inplace if old_inplace: self.copy_extensions_to_source()
[ "def", "run", "(", "self", ")", ":", "old_inplace", ",", "self", ".", "inplace", "=", "self", ".", "inplace", ",", "0", "_build_ext", ".", "run", "(", "self", ")", "self", ".", "inplace", "=", "old_inplace", "if", "old_inplace", ":", "self", ".", "co...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/setuptools/command/build_ext.py#L75-L81
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/the-kth-factor-of-n.py
python
Solution.kthFactor
(self, n, k)
return result if k <= count else n//result
:type n: int :type k: int :rtype: int
:type n: int :type k: int :rtype: int
[ ":", "type", "n", ":", "int", ":", "type", "k", ":", "int", ":", "rtype", ":", "int" ]
def kthFactor(self, n, k): """ :type n: int :type k: int :rtype: int """ def kth_factor(n, k=0): mid = None i = 1 while i*i <= n: if not n%i: mid = i k -= 1 if not k: break i += 1 return mid, -k mid, count = kth_factor(n) total = 2*count-(mid*mid == n) if k > total: return -1 result = kth_factor(n, k if k <= count else total-(k-1))[0] return result if k <= count else n//result
[ "def", "kthFactor", "(", "self", ",", "n", ",", "k", ")", ":", "def", "kth_factor", "(", "n", ",", "k", "=", "0", ")", ":", "mid", "=", "None", "i", "=", "1", "while", "i", "*", "i", "<=", "n", ":", "if", "not", "n", "%", "i", ":", "mid",...
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/the-kth-factor-of-n.py#L5-L28
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/setuptools/command/easy_install.py
python
expand_paths
(inputs)
Yield sys.path directories that might contain "old-style" packages
Yield sys.path directories that might contain "old-style" packages
[ "Yield", "sys", ".", "path", "directories", "that", "might", "contain", "old", "-", "style", "packages" ]
def expand_paths(inputs): """Yield sys.path directories that might contain "old-style" packages""" seen = {} for dirname in inputs: dirname = normalize_path(dirname) if dirname in seen: continue seen[dirname] = 1 if not os.path.isdir(dirname): continue files = os.listdir(dirname) yield dirname, files for name in files: if not name.endswith('.pth'): # We only care about the .pth files continue if name in ('easy-install.pth', 'setuptools.pth'): # Ignore .pth files that we control continue # Read the .pth file f = open(os.path.join(dirname, name)) lines = list(yield_lines(f)) f.close() # Yield existing non-dupe, non-import directory lines from it for line in lines: if not line.startswith("import"): line = normalize_path(line.rstrip()) if line not in seen: seen[line] = 1 if not os.path.isdir(line): continue yield line, os.listdir(line)
[ "def", "expand_paths", "(", "inputs", ")", ":", "seen", "=", "{", "}", "for", "dirname", "in", "inputs", ":", "dirname", "=", "normalize_path", "(", "dirname", ")", "if", "dirname", "in", "seen", ":", "continue", "seen", "[", "dirname", "]", "=", "1", ...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/setuptools/command/easy_install.py#L1458-L1496
msoos/cryptominisat
02f53d1fc045fdba53671306964d3d094feb949e
scripts/reconf/generate_reconf.py
python
query_yes_no
(question, default="no")
Ask a yes/no question via input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits <Enter>. It must be "yes" (the default), "no" or None (meaning an answer is required of the user). The "answer" return value is True for "yes" or False for "no".
Ask a yes/no question via input() and return their answer.
[ "Ask", "a", "yes", "/", "no", "question", "via", "input", "()", "and", "return", "their", "answer", "." ]
def query_yes_no(question, default="no"): """Ask a yes/no question via input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits <Enter>. It must be "yes" (the default), "no" or None (meaning an answer is required of the user). The "answer" return value is True for "yes" or False for "no". """ valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False} if default is None: prompt = " [y/n] " elif default == "yes": prompt = " [Y/n] " elif default == "no": prompt = " [y/N] " else: raise ValueError("invalid default answer: '%s'" % default) while True: sys.stdout.write(question + prompt) choice = input().lower() if default is not None and choice == '': return valid[default] elif choice in valid: return valid[choice] else: sys.stdout.write("Please respond with 'yes' or 'no' " "(or 'y' or 'n').\n")
[ "def", "query_yes_no", "(", "question", ",", "default", "=", "\"no\"", ")", ":", "valid", "=", "{", "\"yes\"", ":", "True", ",", "\"y\"", ":", "True", ",", "\"ye\"", ":", "True", ",", "\"no\"", ":", "False", ",", "\"n\"", ":", "False", "}", "if", "...
https://github.com/msoos/cryptominisat/blob/02f53d1fc045fdba53671306964d3d094feb949e/scripts/reconf/generate_reconf.py#L27-L57
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/stc.py
python
StyledTextCtrl.StyleClearAll
(*args, **kwargs)
return _stc.StyledTextCtrl_StyleClearAll(*args, **kwargs)
StyleClearAll(self) Clear all the styles and make equivalent to the global default style.
StyleClearAll(self)
[ "StyleClearAll", "(", "self", ")" ]
def StyleClearAll(*args, **kwargs): """ StyleClearAll(self) Clear all the styles and make equivalent to the global default style. """ return _stc.StyledTextCtrl_StyleClearAll(*args, **kwargs)
[ "def", "StyleClearAll", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_StyleClearAll", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L2506-L2512
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/tools/cpplint.py
python
_FilterExcludedFiles
(fnames)
return [f for f in fnames if not any(e for e in exclude_paths if _IsParentOrSame(e, os.path.abspath(f)))]
Filters out files listed in the --exclude command line switch. File paths in the switch are evaluated relative to the current working directory
Filters out files listed in the --exclude command line switch. File paths in the switch are evaluated relative to the current working directory
[ "Filters", "out", "files", "listed", "in", "the", "--", "exclude", "command", "line", "switch", ".", "File", "paths", "in", "the", "switch", "are", "evaluated", "relative", "to", "the", "current", "working", "directory" ]
def _FilterExcludedFiles(fnames): """Filters out files listed in the --exclude command line switch. File paths in the switch are evaluated relative to the current working directory """ exclude_paths = [os.path.abspath(f) for f in _excludes] # because globbing does not work recursively, exclude all subpath of all excluded entries return [f for f in fnames if not any(e for e in exclude_paths if _IsParentOrSame(e, os.path.abspath(f)))]
[ "def", "_FilterExcludedFiles", "(", "fnames", ")", ":", "exclude_paths", "=", "[", "os", ".", "path", ".", "abspath", "(", "f", ")", "for", "f", "in", "_excludes", "]", "# because globbing does not work recursively, exclude all subpath of all excluded entries", "return"...
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/cpplint.py#L6945-L6953
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/distributed/distributed_c10d.py
python
_rank_not_in_group
(group: ProcessGroup)
return group == GroupMember.NON_GROUP_MEMBER
Helper that checks if the current process's rank is not in a given group.
Helper that checks if the current process's rank is not in a given group.
[ "Helper", "that", "checks", "if", "the", "current", "process", "s", "rank", "is", "not", "in", "a", "given", "group", "." ]
def _rank_not_in_group(group: ProcessGroup): """ Helper that checks if the current process's rank is not in a given group. """ if group is None: return False return group == GroupMember.NON_GROUP_MEMBER
[ "def", "_rank_not_in_group", "(", "group", ":", "ProcessGroup", ")", ":", "if", "group", "is", "None", ":", "return", "False", "return", "group", "==", "GroupMember", ".", "NON_GROUP_MEMBER" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributed/distributed_c10d.py#L267-L273
ucb-bar/esp-llvm
8aec2ae754fd66d4e73b9b777a9f20c4583a0f03
utils/llvm-build/llvmbuild/main.py
python
LLVMProjectInfo.write_cmake_fragment
(self, output_path, enabled_optional_components)
write_cmake_fragment(output_path) -> None Generate a CMake fragment which includes all of the collated LLVMBuild information in a format that is easily digestible by a CMake. The exact contents of this are closely tied to how the CMake configuration integrates LLVMBuild, see CMakeLists.txt in the top-level.
write_cmake_fragment(output_path) -> None
[ "write_cmake_fragment", "(", "output_path", ")", "-", ">", "None" ]
def write_cmake_fragment(self, output_path, enabled_optional_components): """ write_cmake_fragment(output_path) -> None Generate a CMake fragment which includes all of the collated LLVMBuild information in a format that is easily digestible by a CMake. The exact contents of this are closely tied to how the CMake configuration integrates LLVMBuild, see CMakeLists.txt in the top-level. """ dependencies = list(self.get_fragment_dependencies()) # Write out the CMake fragment. make_install_dir(os.path.dirname(output_path)) f = open(output_path, 'w') # Write the header. header_fmt = '\ #===-- %s - LLVMBuild Configuration for LLVM %s-*- CMake -*--===#' header_name = os.path.basename(output_path) header_pad = '-' * (80 - len(header_fmt % (header_name, ''))) header_string = header_fmt % (header_name, header_pad) f.write("""\ %s # # The LLVM Compiler Infrastructure # # This file is distributed under the University of Illinois Open Source # License. See LICENSE.TXT for details. # #===------------------------------------------------------------------------===# # # This file contains the LLVMBuild project information in a format easily # consumed by the CMake based build system. # # This file is autogenerated by llvm-build, do not edit! # #===------------------------------------------------------------------------===# """ % header_string) # Write the dependency information in the best way we can. f.write(""" # LLVMBuild CMake fragment dependencies. # # CMake has no builtin way to declare that the configuration depends on # a particular file. However, a side effect of configure_file is to add # said input file to CMake's internal dependency list. So, we use that # and a dummy output file to communicate the dependency information to # CMake. # # FIXME: File a CMake RFE to get a properly supported version of this # feature. """) for dep in dependencies: f.write("""\ configure_file(\"%s\" ${CMAKE_CURRENT_BINARY_DIR}/DummyConfigureOutput)\n""" % ( cmake_quote_path(dep),)) # Write the properties we use to encode the required library dependency # information in a form CMake can easily use directly. f.write(""" # Explicit library dependency information. # # The following property assignments effectively create a map from component # names to required libraries, in a way that is easily accessed from CMake. """) self.foreach_cmake_library( lambda ci: f.write("""\ set_property(GLOBAL PROPERTY LLVMBUILD_LIB_DEPS_%s %s)\n""" % ( ci.get_prefixed_library_name(), " ".join(sorted( dep.get_prefixed_library_name() for dep in self.get_required_libraries_for_component(ci))))) , enabled_optional_components, skip_disabled = False, skip_not_installed = False # Dependency info must be emitted for internals libs too ) f.close()
[ "def", "write_cmake_fragment", "(", "self", ",", "output_path", ",", "enabled_optional_components", ")", ":", "dependencies", "=", "list", "(", "self", ".", "get_fragment_dependencies", "(", ")", ")", "# Write out the CMake fragment.", "make_install_dir", "(", "os", "...
https://github.com/ucb-bar/esp-llvm/blob/8aec2ae754fd66d4e73b9b777a9f20c4583a0f03/utils/llvm-build/llvmbuild/main.py#L535-L616
crosslife/OpenBird
9e0198a1a2295f03fa1e8676e216e22c9c7d380b
cocos2d/tools/bindings-generator/clang/cindex.py
python
Cursor.semantic_parent
(self)
return self._semantic_parent
Return the semantic parent for this cursor.
Return the semantic parent for this cursor.
[ "Return", "the", "semantic", "parent", "for", "this", "cursor", "." ]
def semantic_parent(self): """Return the semantic parent for this cursor.""" if not hasattr(self, '_semantic_parent'): self._semantic_parent = conf.lib.clang_getCursorSemanticParent(self) return self._semantic_parent
[ "def", "semantic_parent", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_semantic_parent'", ")", ":", "self", ".", "_semantic_parent", "=", "conf", ".", "lib", ".", "clang_getCursorSemanticParent", "(", "self", ")", "return", "self", "."...
https://github.com/crosslife/OpenBird/blob/9e0198a1a2295f03fa1e8676e216e22c9c7d380b/cocos2d/tools/bindings-generator/clang/cindex.py#L1400-L1405
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/grid.py
python
GridEditorCreatedEvent.SetCol
(*args, **kwargs)
return _grid.GridEditorCreatedEvent_SetCol(*args, **kwargs)
SetCol(self, int col)
SetCol(self, int col)
[ "SetCol", "(", "self", "int", "col", ")" ]
def SetCol(*args, **kwargs): """SetCol(self, int col)""" return _grid.GridEditorCreatedEvent_SetCol(*args, **kwargs)
[ "def", "SetCol", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "GridEditorCreatedEvent_SetCol", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/grid.py#L2483-L2485
llvm/llvm-project
ffa6262cb4e2a335d26416fad39a581b4f98c5f4
mlir/python/mlir/dialects/_pdl_ops_ext.py
python
_get_int_attr
(bits: int, value: Union[IntegerAttr, int])
Converts the given value to signless integer attribute of given bit width.
Converts the given value to signless integer attribute of given bit width.
[ "Converts", "the", "given", "value", "to", "signless", "integer", "attribute", "of", "given", "bit", "width", "." ]
def _get_int_attr(bits: int, value: Union[IntegerAttr, int]) -> IntegerAttr: """Converts the given value to signless integer attribute of given bit width.""" if isinstance(value, int): ty = IntegerType.get_signless(bits) return IntegerAttr.get(ty, value) else: return value
[ "def", "_get_int_attr", "(", "bits", ":", "int", ",", "value", ":", "Union", "[", "IntegerAttr", ",", "int", "]", ")", "->", "IntegerAttr", ":", "if", "isinstance", "(", "value", ",", "int", ")", ":", "ty", "=", "IntegerType", ".", "get_signless", "(",...
https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/mlir/python/mlir/dialects/_pdl_ops_ext.py#L15-L21
openai/atari-py
b0117f704919ed4cbbd5addcec5ec1b0fb3bff99
atari_py/ale_python_interface.py
python
ALEInterface.getRAM
(self, ram=None)
return ram
This function grabs the atari RAM. ram MUST be a numpy array of uint8/int8. This can be initialized like so: ram = np.array(ram_size, dtype=uint8) Notice: It must be ram_size where ram_size can be retrieved via the getRAMSize function. If it is None, then this function will initialize it.
This function grabs the atari RAM. ram MUST be a numpy array of uint8/int8. This can be initialized like so: ram = np.array(ram_size, dtype=uint8) Notice: It must be ram_size where ram_size can be retrieved via the getRAMSize function. If it is None, then this function will initialize it.
[ "This", "function", "grabs", "the", "atari", "RAM", ".", "ram", "MUST", "be", "a", "numpy", "array", "of", "uint8", "/", "int8", ".", "This", "can", "be", "initialized", "like", "so", ":", "ram", "=", "np", ".", "array", "(", "ram_size", "dtype", "="...
def getRAM(self, ram=None): """This function grabs the atari RAM. ram MUST be a numpy array of uint8/int8. This can be initialized like so: ram = np.array(ram_size, dtype=uint8) Notice: It must be ram_size where ram_size can be retrieved via the getRAMSize function. If it is None, then this function will initialize it. """ if(ram is None): ram_size = ale_lib.getRAMSize(self.obj) ram = np.zeros(ram_size, dtype=np.uint8) ale_lib.getRAM(self.obj, as_ctypes(ram)) return ram
[ "def", "getRAM", "(", "self", ",", "ram", "=", "None", ")", ":", "if", "(", "ram", "is", "None", ")", ":", "ram_size", "=", "ale_lib", ".", "getRAMSize", "(", "self", ".", "obj", ")", "ram", "=", "np", ".", "zeros", "(", "ram_size", ",", "dtype",...
https://github.com/openai/atari-py/blob/b0117f704919ed4cbbd5addcec5ec1b0fb3bff99/atari_py/ale_python_interface.py#L285-L296
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/archive_util.py
python
unpack_archive
( filename, extract_dir, progress_filter=default_filter, drivers=None)
Unpack `filename` to `extract_dir`, or raise ``UnrecognizedFormat`` `progress_filter` is a function taking two arguments: a source path internal to the archive ('/'-separated), and a filesystem path where it will be extracted. The callback must return the desired extract path (which may be the same as the one passed in), or else ``None`` to skip that file or directory. The callback can thus be used to report on the progress of the extraction, as well as to filter the items extracted or alter their extraction paths. `drivers`, if supplied, must be a non-empty sequence of functions with the same signature as this function (minus the `drivers` argument), that raise ``UnrecognizedFormat`` if they do not support extracting the designated archive type. The `drivers` are tried in sequence until one is found that does not raise an error, or until all are exhausted (in which case ``UnrecognizedFormat`` is raised). If you do not supply a sequence of drivers, the module's ``extraction_drivers`` constant will be used, which means that ``unpack_zipfile`` and ``unpack_tarfile`` will be tried, in that order.
Unpack `filename` to `extract_dir`, or raise ``UnrecognizedFormat``
[ "Unpack", "filename", "to", "extract_dir", "or", "raise", "UnrecognizedFormat" ]
def unpack_archive( filename, extract_dir, progress_filter=default_filter, drivers=None): """Unpack `filename` to `extract_dir`, or raise ``UnrecognizedFormat`` `progress_filter` is a function taking two arguments: a source path internal to the archive ('/'-separated), and a filesystem path where it will be extracted. The callback must return the desired extract path (which may be the same as the one passed in), or else ``None`` to skip that file or directory. The callback can thus be used to report on the progress of the extraction, as well as to filter the items extracted or alter their extraction paths. `drivers`, if supplied, must be a non-empty sequence of functions with the same signature as this function (minus the `drivers` argument), that raise ``UnrecognizedFormat`` if they do not support extracting the designated archive type. The `drivers` are tried in sequence until one is found that does not raise an error, or until all are exhausted (in which case ``UnrecognizedFormat`` is raised). If you do not supply a sequence of drivers, the module's ``extraction_drivers`` constant will be used, which means that ``unpack_zipfile`` and ``unpack_tarfile`` will be tried, in that order. """ for driver in drivers or extraction_drivers: try: driver(filename, extract_dir, progress_filter) except UnrecognizedFormat: continue else: return else: raise UnrecognizedFormat( "Not a recognized archive type: %s" % filename )
[ "def", "unpack_archive", "(", "filename", ",", "extract_dir", ",", "progress_filter", "=", "default_filter", ",", "drivers", "=", "None", ")", ":", "for", "driver", "in", "drivers", "or", "extraction_drivers", ":", "try", ":", "driver", "(", "filename", ",", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/archive_util.py#L28-L61
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/html.py
python
HtmlBookRecord.GetBasePath
(*args, **kwargs)
return _html.HtmlBookRecord_GetBasePath(*args, **kwargs)
GetBasePath(self) -> String
GetBasePath(self) -> String
[ "GetBasePath", "(", "self", ")", "-", ">", "String" ]
def GetBasePath(*args, **kwargs): """GetBasePath(self) -> String""" return _html.HtmlBookRecord_GetBasePath(*args, **kwargs)
[ "def", "GetBasePath", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_html", ".", "HtmlBookRecord_GetBasePath", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/html.py#L1423-L1425
irods/irods
ed6328646cee87182098d569919004049bf4ce21
scripts/irods/pyparsing.py
python
countedArray
( expr, intExpr=None )
return ( intExpr + arrayExpr ).setName('(len) ' + _ustr(expr) + '...')
Helper to define a counted list of expressions. This helper defines a pattern of the form:: integer expr expr expr... where the leading integer tells how many expr expressions follow. The matched tokens returns the array of expr tokens as a list - the leading count token is suppressed.
Helper to define a counted list of expressions. This helper defines a pattern of the form:: integer expr expr expr... where the leading integer tells how many expr expressions follow. The matched tokens returns the array of expr tokens as a list - the leading count token is suppressed.
[ "Helper", "to", "define", "a", "counted", "list", "of", "expressions", ".", "This", "helper", "defines", "a", "pattern", "of", "the", "form", "::", "integer", "expr", "expr", "expr", "...", "where", "the", "leading", "integer", "tells", "how", "many", "exp...
def countedArray( expr, intExpr=None ): """Helper to define a counted list of expressions. This helper defines a pattern of the form:: integer expr expr expr... where the leading integer tells how many expr expressions follow. The matched tokens returns the array of expr tokens as a list - the leading count token is suppressed. """ arrayExpr = Forward() def countFieldParseAction(s,l,t): n = t[0] arrayExpr << (n and Group(And([expr]*n)) or Group(empty)) return [] if intExpr is None: intExpr = Word(nums).setParseAction(lambda t:int(t[0])) else: intExpr = intExpr.copy() intExpr.setName("arrayLen") intExpr.addParseAction(countFieldParseAction, callDuringTry=True) return ( intExpr + arrayExpr ).setName('(len) ' + _ustr(expr) + '...')
[ "def", "countedArray", "(", "expr", ",", "intExpr", "=", "None", ")", ":", "arrayExpr", "=", "Forward", "(", ")", "def", "countFieldParseAction", "(", "s", ",", "l", ",", "t", ")", ":", "n", "=", "t", "[", "0", "]", "arrayExpr", "<<", "(", "n", "...
https://github.com/irods/irods/blob/ed6328646cee87182098d569919004049bf4ce21/scripts/irods/pyparsing.py#L3218-L3236