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
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/lib/mixins.py
python
_disables_array_ufunc
(obj)
True when __array_ufunc__ is set to None.
True when __array_ufunc__ is set to None.
[ "True", "when", "__array_ufunc__", "is", "set", "to", "None", "." ]
def _disables_array_ufunc(obj): """True when __array_ufunc__ is set to None.""" try: return obj.__array_ufunc__ is None except AttributeError: return False
[ "def", "_disables_array_ufunc", "(", "obj", ")", ":", "try", ":", "return", "obj", ".", "__array_ufunc__", "is", "None", "except", "AttributeError", ":", "return", "False" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/lib/mixins.py#L12-L17
eric612/MobileNet-YOLO
69b4441cb3ec8d553fbdef788ad033e246f901bd
python/caffe/draw.py
python
get_pooling_types_dict
()
return d
Get dictionary mapping pooling type number to type name
Get dictionary mapping pooling type number to type name
[ "Get", "dictionary", "mapping", "pooling", "type", "number", "to", "type", "name" ]
def get_pooling_types_dict(): """Get dictionary mapping pooling type number to type name """ desc = caffe_pb2.PoolingParameter.PoolMethod.DESCRIPTOR d = {} for k, v in desc.values_by_name.items(): d[v.number] = k return d
[ "def", "get_pooling_types_dict", "(", ")", ":", "desc", "=", "caffe_pb2", ".", "PoolingParameter", ".", "PoolMethod", ".", "DESCRIPTOR", "d", "=", "{", "}", "for", "k", ",", "v", "in", "desc", ".", "values_by_name", ".", "items", "(", ")", ":", "d", "[...
https://github.com/eric612/MobileNet-YOLO/blob/69b4441cb3ec8d553fbdef788ad033e246f901bd/python/caffe/draw.py#L36-L43
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_op_impl/tbe/range.py
python
_range_tbe
()
return
Range TBE register
Range TBE register
[ "Range", "TBE", "register" ]
def _range_tbe(): """Range TBE register""" return
[ "def", "_range_tbe", "(", ")", ":", "return" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/range.py#L37-L39
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Code/Tools/waf-1.7.13/crywaflib/msvs.py
python
vsnode.ptype
(self)
Return a special uuid for projects written in the solution file
Return a special uuid for projects written in the solution file
[ "Return", "a", "special", "uuid", "for", "projects", "written", "in", "the", "solution", "file" ]
def ptype(self): """ Return a special uuid for projects written in the solution file """ pass
[ "def", "ptype", "(", "self", ")", ":", "pass" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/crywaflib/msvs.py#L942-L946
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/pytables.py
python
HDFStore.walk
(self, where="/")
Walk the pytables group hierarchy for pandas objects. This generator will yield the group path, subgroups and pandas object names for each group. Any non-pandas PyTables objects that are not a group will be ignored. The `where` group itself is listed first (preorder), then each of its child groups (following an alphanumerical order) is also traversed, following the same procedure. .. versionadded:: 0.24.0 Parameters ---------- where : str, default "/" Group where to start walking. Yields ------ path : str Full path to a group (without trailing '/'). groups : list Names (strings) of the groups contained in `path`. leaves : list Names (strings) of the pandas objects contained in `path`.
Walk the pytables group hierarchy for pandas objects.
[ "Walk", "the", "pytables", "group", "hierarchy", "for", "pandas", "objects", "." ]
def walk(self, where="/"): """ Walk the pytables group hierarchy for pandas objects. This generator will yield the group path, subgroups and pandas object names for each group. Any non-pandas PyTables objects that are not a group will be ignored. The `where` group itself is listed first (preorder), then each of its child groups (following an alphanumerical order) is also traversed, following the same procedure. .. versionadded:: 0.24.0 Parameters ---------- where : str, default "/" Group where to start walking. Yields ------ path : str Full path to a group (without trailing '/'). groups : list Names (strings) of the groups contained in `path`. leaves : list Names (strings) of the pandas objects contained in `path`. """ _tables() self._check_if_open() for g in self._handle.walk_groups(where): if getattr(g._v_attrs, "pandas_type", None) is not None: continue groups = [] leaves = [] for child in g._v_children.values(): pandas_type = getattr(child._v_attrs, "pandas_type", None) if pandas_type is None: if isinstance(child, _table_mod.group.Group): groups.append(child._v_name) else: leaves.append(child._v_name) yield (g._v_pathname.rstrip("/"), groups, leaves)
[ "def", "walk", "(", "self", ",", "where", "=", "\"/\"", ")", ":", "_tables", "(", ")", "self", ".", "_check_if_open", "(", ")", "for", "g", "in", "self", ".", "_handle", ".", "walk_groups", "(", "where", ")", ":", "if", "getattr", "(", "g", ".", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/pytables.py#L1343-L1388
InsightSoftwareConsortium/ITK
87acfce9a93d928311c38bc371b666b515b9f19d
Wrapping/Generators/Python/itk/support/template_class.py
python
itkTemplate.GetTypesAsList
(self)
return ctypes + classes + others
Helper method which returns the available template parameters.
Helper method which returns the available template parameters.
[ "Helper", "method", "which", "returns", "the", "available", "template", "parameters", "." ]
def GetTypesAsList(self): """Helper method which returns the available template parameters.""" # Make a list of allowed types, and sort them ctypes = [] classes = [] others = [] for key_tuple in self.__template__: key = str(key_tuple) if "itkCType" in key: ctypes.append(key) elif "class" in key: classes.append(key) else: others.append(key) # Sort the lists ctypes = sorted(ctypes) classes = sorted(classes) others = sorted(others) return ctypes + classes + others
[ "def", "GetTypesAsList", "(", "self", ")", ":", "# Make a list of allowed types, and sort them", "ctypes", "=", "[", "]", "classes", "=", "[", "]", "others", "=", "[", "]", "for", "key_tuple", "in", "self", ".", "__template__", ":", "key", "=", "str", "(", ...
https://github.com/InsightSoftwareConsortium/ITK/blob/87acfce9a93d928311c38bc371b666b515b9f19d/Wrapping/Generators/Python/itk/support/template_class.py#L772-L793
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/mixture/dpgmm.py
python
_DPGMMBase._initialize_gamma
(self)
Initializes the concentration parameters
Initializes the concentration parameters
[ "Initializes", "the", "concentration", "parameters" ]
def _initialize_gamma(self): "Initializes the concentration parameters" self.gamma_ = self.alpha * np.ones((self.n_components, 3))
[ "def", "_initialize_gamma", "(", "self", ")", ":", "self", ".", "gamma_", "=", "self", ".", "alpha", "*", "np", ".", "ones", "(", "(", "self", ".", "n_components", ",", "3", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/mixture/dpgmm.py#L408-L410
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/accessor.py
python
_register_accessor
(name, cls)
return decorator
Register a custom accessor on {klass} objects. Parameters ---------- name : str Name under which the accessor should be registered. A warning is issued if this name conflicts with a preexisting attribute. Returns ------- callable A class decorator. See Also -------- register_dataframe_accessor : Register a custom accessor on DataFrame objects. register_series_accessor : Register a custom accessor on Series objects. register_index_accessor : Register a custom accessor on Index objects. Notes ----- When accessed, your accessor will be initialized with the pandas object the user is interacting with. So the signature must be .. code-block:: python def __init__(self, pandas_object): # noqa: E999 ... For consistency with pandas methods, you should raise an ``AttributeError`` if the data passed to your accessor has an incorrect dtype. >>> pd.Series(['a', 'b']).dt Traceback (most recent call last): ... AttributeError: Can only use .dt accessor with datetimelike values Examples -------- In your library code:: import pandas as pd @pd.api.extensions.register_dataframe_accessor("geo") class GeoAccessor: def __init__(self, pandas_obj): self._obj = pandas_obj @property def center(self): # return the geographic center point of this DataFrame lat = self._obj.latitude lon = self._obj.longitude return (float(lon.mean()), float(lat.mean())) def plot(self): # plot this array's data on a map, e.g., using Cartopy pass Back in an interactive IPython session: .. code-block:: ipython In [1]: ds = pd.DataFrame({{"longitude": np.linspace(0, 10), ...: "latitude": np.linspace(0, 20)}}) In [2]: ds.geo.center Out[2]: (5.0, 10.0) In [3]: ds.geo.plot() # plots data on a map
Register a custom accessor on {klass} objects.
[ "Register", "a", "custom", "accessor", "on", "{", "klass", "}", "objects", "." ]
def _register_accessor(name, cls): """ Register a custom accessor on {klass} objects. Parameters ---------- name : str Name under which the accessor should be registered. A warning is issued if this name conflicts with a preexisting attribute. Returns ------- callable A class decorator. See Also -------- register_dataframe_accessor : Register a custom accessor on DataFrame objects. register_series_accessor : Register a custom accessor on Series objects. register_index_accessor : Register a custom accessor on Index objects. Notes ----- When accessed, your accessor will be initialized with the pandas object the user is interacting with. So the signature must be .. code-block:: python def __init__(self, pandas_object): # noqa: E999 ... For consistency with pandas methods, you should raise an ``AttributeError`` if the data passed to your accessor has an incorrect dtype. >>> pd.Series(['a', 'b']).dt Traceback (most recent call last): ... AttributeError: Can only use .dt accessor with datetimelike values Examples -------- In your library code:: import pandas as pd @pd.api.extensions.register_dataframe_accessor("geo") class GeoAccessor: def __init__(self, pandas_obj): self._obj = pandas_obj @property def center(self): # return the geographic center point of this DataFrame lat = self._obj.latitude lon = self._obj.longitude return (float(lon.mean()), float(lat.mean())) def plot(self): # plot this array's data on a map, e.g., using Cartopy pass Back in an interactive IPython session: .. code-block:: ipython In [1]: ds = pd.DataFrame({{"longitude": np.linspace(0, 10), ...: "latitude": np.linspace(0, 20)}}) In [2]: ds.geo.center Out[2]: (5.0, 10.0) In [3]: ds.geo.plot() # plots data on a map """ def decorator(accessor): if hasattr(cls, name): warnings.warn( f"registration of accessor {repr(accessor)} under name " f"{repr(name)} for type {repr(cls)} is overriding a preexisting " f"attribute with the same name.", UserWarning, stacklevel=2, ) setattr(cls, name, CachedAccessor(name, accessor)) cls._accessors.add(name) return accessor return decorator
[ "def", "_register_accessor", "(", "name", ",", "cls", ")", ":", "def", "decorator", "(", "accessor", ")", ":", "if", "hasattr", "(", "cls", ",", "name", ")", ":", "warnings", ".", "warn", "(", "f\"registration of accessor {repr(accessor)} under name \"", "f\"{re...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/accessor.py#L191-L276
plumonito/dtslam
5994bb9cf7a11981b830370db206bceb654c085d
3rdparty/opencv-git/3rdparty/jinja2/sandbox.py
python
SandboxedEnvironment.call_unop
(self, context, operator, arg)
return self.unop_table[operator](arg)
For intercepted unary operator calls (:meth:`intercepted_unops`) this function is executed instead of the builtin operator. This can be used to fine tune the behavior of certain operators. .. versionadded:: 2.6
For intercepted unary operator calls (:meth:`intercepted_unops`) this function is executed instead of the builtin operator. This can be used to fine tune the behavior of certain operators.
[ "For", "intercepted", "unary", "operator", "calls", "(", ":", "meth", ":", "intercepted_unops", ")", "this", "function", "is", "executed", "instead", "of", "the", "builtin", "operator", ".", "This", "can", "be", "used", "to", "fine", "tune", "the", "behavior...
def call_unop(self, context, operator, arg): """For intercepted unary operator calls (:meth:`intercepted_unops`) this function is executed instead of the builtin operator. This can be used to fine tune the behavior of certain operators. .. versionadded:: 2.6 """ return self.unop_table[operator](arg)
[ "def", "call_unop", "(", "self", ",", "context", ",", "operator", ",", "arg", ")", ":", "return", "self", ".", "unop_table", "[", "operator", "]", "(", "arg", ")" ]
https://github.com/plumonito/dtslam/blob/5994bb9cf7a11981b830370db206bceb654c085d/3rdparty/opencv-git/3rdparty/jinja2/sandbox.py#L295-L302
junhyukoh/caffe-lstm
598d45456fa2a1b127a644f4aa38daa8fb9fc722
scripts/cpp_lint.py
python
GetPreviousNonBlankLine
(clean_lines, linenum)
return ('', -1)
Return the most recent non-blank line and its line number. Args: clean_lines: A CleansedLines instance containing the file contents. linenum: The number of the line to check. Returns: A tuple with two elements. The first element is the contents of the last non-blank line before the current line, or the empty string if this is the first non-blank line. The second is the line number of that line, or -1 if this is the first non-blank line.
Return the most recent non-blank line and its line number.
[ "Return", "the", "most", "recent", "non", "-", "blank", "line", "and", "its", "line", "number", "." ]
def GetPreviousNonBlankLine(clean_lines, linenum): """Return the most recent non-blank line and its line number. Args: clean_lines: A CleansedLines instance containing the file contents. linenum: The number of the line to check. Returns: A tuple with two elements. The first element is the contents of the last non-blank line before the current line, or the empty string if this is the first non-blank line. The second is the line number of that line, or -1 if this is the first non-blank line. """ prevlinenum = linenum - 1 while prevlinenum >= 0: prevline = clean_lines.elided[prevlinenum] if not IsBlankLine(prevline): # if not a blank line... return (prevline, prevlinenum) prevlinenum -= 1 return ('', -1)
[ "def", "GetPreviousNonBlankLine", "(", "clean_lines", ",", "linenum", ")", ":", "prevlinenum", "=", "linenum", "-", "1", "while", "prevlinenum", ">=", "0", ":", "prevline", "=", "clean_lines", ".", "elided", "[", "prevlinenum", "]", "if", "not", "IsBlankLine",...
https://github.com/junhyukoh/caffe-lstm/blob/598d45456fa2a1b127a644f4aa38daa8fb9fc722/scripts/cpp_lint.py#L3046-L3066
llvm/llvm-project
ffa6262cb4e2a335d26416fad39a581b4f98c5f4
clang-tools-extra/clang-include-fixer/find-all-symbols/tool/run-find-all-symbols.py
python
find_compilation_database
(path)
return os.path.realpath(result)
Adjusts the directory until a compilation database is found.
Adjusts the directory until a compilation database is found.
[ "Adjusts", "the", "directory", "until", "a", "compilation", "database", "is", "found", "." ]
def find_compilation_database(path): """Adjusts the directory until a compilation database is found.""" result = './' while not os.path.isfile(os.path.join(result, path)): if os.path.realpath(result) == '/': print 'Error: could not find compilation database.' sys.exit(1) result += '../' return os.path.realpath(result)
[ "def", "find_compilation_database", "(", "path", ")", ":", "result", "=", "'./'", "while", "not", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "result", ",", "path", ")", ")", ":", "if", "os", ".", "path", ".", "realp...
https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/clang-tools-extra/clang-include-fixer/find-all-symbols/tool/run-find-all-symbols.py#L37-L45
alibaba/weex_js_engine
2bdf4b6f020c1fc99c63f649718f6faf7e27fdde
jni/v8core/v8/tools/stats-viewer.py
python
CounterCollection.CountersInUse
(self)
return self.data.IntAt(12)
Return the number of counters in active use.
Return the number of counters in active use.
[ "Return", "the", "number", "of", "counters", "in", "active", "use", "." ]
def CountersInUse(self): """Return the number of counters in active use.""" return self.data.IntAt(12)
[ "def", "CountersInUse", "(", "self", ")", ":", "return", "self", ".", "data", ".", "IntAt", "(", "12", ")" ]
https://github.com/alibaba/weex_js_engine/blob/2bdf4b6f020c1fc99c63f649718f6faf7e27fdde/jni/v8core/v8/tools/stats-viewer.py#L370-L372
h2oai/deepwater
80e345c582e6ef912a31f42707a2f31c01b064da
docs/sphinxext/apigen.py
python
ApiDocWriter.__init__
(self, package_name, rst_extension='.rst', package_skip_patterns=None, module_skip_patterns=None, )
Initialize package for parsing Parameters ---------- package_name : string Name of the top-level package. *package_name* must be the name of an importable package rst_extension : string, optional Extension for reST files, default '.rst' package_skip_patterns : None or sequence of {strings, regexps} Sequence of strings giving URIs of packages to be excluded Operates on the package path, starting at (including) the first dot in the package path, after *package_name* - so, if *package_name* is ``sphinx``, then ``sphinx.util`` will result in ``.util`` being passed for earching by these regexps. If is None, gives default. Default is: ['\.tests$'] module_skip_patterns : None or sequence Sequence of strings giving URIs of modules to be excluded Operates on the module name including preceding URI path, back to the first dot after *package_name*. For example ``sphinx.util.console`` results in the string to search of ``.util.console`` If is None, gives default. Default is: ['\.setup$', '\._']
Initialize package for parsing
[ "Initialize", "package", "for", "parsing" ]
def __init__(self, package_name, rst_extension='.rst', package_skip_patterns=None, module_skip_patterns=None, ): ''' Initialize package for parsing Parameters ---------- package_name : string Name of the top-level package. *package_name* must be the name of an importable package rst_extension : string, optional Extension for reST files, default '.rst' package_skip_patterns : None or sequence of {strings, regexps} Sequence of strings giving URIs of packages to be excluded Operates on the package path, starting at (including) the first dot in the package path, after *package_name* - so, if *package_name* is ``sphinx``, then ``sphinx.util`` will result in ``.util`` being passed for earching by these regexps. If is None, gives default. Default is: ['\.tests$'] module_skip_patterns : None or sequence Sequence of strings giving URIs of modules to be excluded Operates on the module name including preceding URI path, back to the first dot after *package_name*. For example ``sphinx.util.console`` results in the string to search of ``.util.console`` If is None, gives default. Default is: ['\.setup$', '\._'] ''' if package_skip_patterns is None: package_skip_patterns = ['\\.tests$'] if module_skip_patterns is None: module_skip_patterns = ['\\.setup$', '\\._'] self.package_name = package_name self.rst_extension = rst_extension self.package_skip_patterns = package_skip_patterns self.module_skip_patterns = module_skip_patterns
[ "def", "__init__", "(", "self", ",", "package_name", ",", "rst_extension", "=", "'.rst'", ",", "package_skip_patterns", "=", "None", ",", "module_skip_patterns", "=", "None", ",", ")", ":", "if", "package_skip_patterns", "is", "None", ":", "package_skip_patterns",...
https://github.com/h2oai/deepwater/blob/80e345c582e6ef912a31f42707a2f31c01b064da/docs/sphinxext/apigen.py#L32-L71
electron/electron
8dfcf817e4182c48cd7e9d3471319c61224677e3
script/lib/git.py
python
remove_patch_filename
(patch)
Strip out the Patch-Filename trailer from a patch's message body
Strip out the Patch-Filename trailer from a patch's message body
[ "Strip", "out", "the", "Patch", "-", "Filename", "trailer", "from", "a", "patch", "s", "message", "body" ]
def remove_patch_filename(patch): """Strip out the Patch-Filename trailer from a patch's message body""" force_keep_next_line = False for i, l in enumerate(patch): is_patchfilename = l.startswith('Patch-Filename: ') next_is_patchfilename = i < len(patch) - 1 and patch[i + 1].startswith( 'Patch-Filename: ' ) if not force_keep_next_line and ( is_patchfilename or (next_is_patchfilename and len(l.rstrip()) == 0) ): pass # drop this line else: yield l force_keep_next_line = l.startswith('Subject: ')
[ "def", "remove_patch_filename", "(", "patch", ")", ":", "force_keep_next_line", "=", "False", "for", "i", ",", "l", "in", "enumerate", "(", "patch", ")", ":", "is_patchfilename", "=", "l", ".", "startswith", "(", "'Patch-Filename: '", ")", "next_is_patchfilename...
https://github.com/electron/electron/blob/8dfcf817e4182c48cd7e9d3471319c61224677e3/script/lib/git.py#L215-L229
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/share/gdb/python/gdb/command/explore.py
python
Explorer.explore_type
(name, datatype, is_child)
Main function to explore a data type. Arguments: name: The string representing the path to the data type being explored. datatype: The gdb.Type value of the data type being explored. is_child: Boolean value to indicate if the name is a child. A name is a child if it is derived from the main name entered by the user. For example, if the user entered the name of struct type, then when exploring the fields of the struct, is_child is set to True internally. Returns: No return value.
Main function to explore a data type.
[ "Main", "function", "to", "explore", "a", "data", "type", "." ]
def explore_type(name, datatype, is_child): """Main function to explore a data type. Arguments: name: The string representing the path to the data type being explored. datatype: The gdb.Type value of the data type being explored. is_child: Boolean value to indicate if the name is a child. A name is a child if it is derived from the main name entered by the user. For example, if the user entered the name of struct type, then when exploring the fields of the struct, is_child is set to True internally. Returns: No return value. """ type_code = datatype.code if type_code in Explorer.type_code_to_explorer_map: explorer_class = Explorer.type_code_to_explorer_map[type_code] while explorer_class.explore_type(name, datatype, is_child): pass else: print ("Explorer for type '%s' not yet available.\n" % str(datatype))
[ "def", "explore_type", "(", "name", ",", "datatype", ",", "is_child", ")", ":", "type_code", "=", "datatype", ".", "code", "if", "type_code", "in", "Explorer", ".", "type_code_to_explorer_map", ":", "explorer_class", "=", "Explorer", ".", "type_code_to_explorer_ma...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/share/gdb/python/gdb/command/explore.py#L92-L115
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/tools/ci_build/update_version.py
python
main
()
This script updates all instances of version in the tensorflow directory. Requirements: version: The version tag OR nightly: Create a nightly tag with current date Raises: RuntimeError: If the script is not being run from tf source dir
This script updates all instances of version in the tensorflow directory.
[ "This", "script", "updates", "all", "instances", "of", "version", "in", "the", "tensorflow", "directory", "." ]
def main(): """This script updates all instances of version in the tensorflow directory. Requirements: version: The version tag OR nightly: Create a nightly tag with current date Raises: RuntimeError: If the script is not being run from tf source dir """ parser = argparse.ArgumentParser(description="Cherry picking automation.") # Arg information parser.add_argument("--version", help="<new_major_ver>.<new_minor_ver>.<new_patch_ver>", default="") parser.add_argument("--nightly", help="disable the service provisioning step", action="store_true") args = parser.parse_args() check_all_files() old_version = get_current_semver_version() if args.nightly: if args.version: new_version = Version.parse_from_string(args.version, NIGHTLY_VERSION) new_version.set_identifier_string("-dev" + time.strftime("%Y%m%d")) else: # Dev minor version is one ahead of official. nightly_minor_ver = int(old_version.minor) + 1 new_version = Version(old_version.major, str(nightly_minor_ver), old_version.patch, "-dev" + time.strftime("%Y%m%d"), NIGHTLY_VERSION) else: new_version = Version.parse_from_string(args.version, REGULAR_VERSION) update_version_h(old_version, new_version) update_setup_dot_py(old_version, new_version) update_readme(old_version, new_version) update_tensorflow_bzl(old_version, new_version) # Print transition details. print("Major: %s -> %s" % (old_version.major, new_version.major)) print("Minor: %s -> %s" % (old_version.minor, new_version.minor)) print("Patch: %s -> %s\n" % (old_version.patch, new_version.patch)) check_for_old_version(old_version, new_version)
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Cherry picking automation.\"", ")", "# Arg information", "parser", ".", "add_argument", "(", "\"--version\"", ",", "help", "=", "\"<new_major_ver>.<new_minor_ve...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/tools/ci_build/update_version.py#L265-L317
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/composite/multitype_ops/not_in_impl.py
python
_str_not_in_dict
(x, y)
return F.not_in_dict(x, y)
Determine if a str not in dict. Args: x: str y: dict Returns: bool, if x not in y return true, x in y return false.
Determine if a str not in dict.
[ "Determine", "if", "a", "str", "not", "in", "dict", "." ]
def _str_not_in_dict(x, y): """ Determine if a str not in dict. Args: x: str y: dict Returns: bool, if x not in y return true, x in y return false. """ return F.not_in_dict(x, y)
[ "def", "_str_not_in_dict", "(", "x", ",", "y", ")", ":", "return", "F", ".", "not_in_dict", "(", "x", ",", "y", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/composite/multitype_ops/not_in_impl.py#L91-L102
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/imputil.py
python
_compile
(pathname, timestamp)
return code
Compile (and cache) a Python source file. The file specified by <pathname> is compiled to a code object and returned. Presuming the appropriate privileges exist, the bytecodes will be saved back to the filesystem for future imports. The source file's modification timestamp must be provided as a Long value.
Compile (and cache) a Python source file.
[ "Compile", "(", "and", "cache", ")", "a", "Python", "source", "file", "." ]
def _compile(pathname, timestamp): """Compile (and cache) a Python source file. The file specified by <pathname> is compiled to a code object and returned. Presuming the appropriate privileges exist, the bytecodes will be saved back to the filesystem for future imports. The source file's modification timestamp must be provided as a Long value. """ codestring = open(pathname, 'rU').read() if codestring and codestring[-1] != '\n': codestring = codestring + '\n' code = __builtin__.compile(codestring, pathname, 'exec') # try to cache the compiled code try: f = open(pathname + _suffix_char, 'wb') except IOError: pass else: f.write('\0\0\0\0') f.write(struct.pack('<I', timestamp)) marshal.dump(code, f) f.flush() f.seek(0, 0) f.write(imp.get_magic()) f.close() return code
[ "def", "_compile", "(", "pathname", ",", "timestamp", ")", ":", "codestring", "=", "open", "(", "pathname", ",", "'rU'", ")", ".", "read", "(", ")", "if", "codestring", "and", "codestring", "[", "-", "1", "]", "!=", "'\\n'", ":", "codestring", "=", "...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/imputil.py#L415-L444
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_ninja.py
python
CreateWrapper
(target_list, target_dicts, data, params)
return (new_target_list, new_target_dicts, new_data)
Initialize targets for the ninja wrapper. This sets up the necessary variables in the targets to generate Xcode projects that use ninja as an external builder. Arguments: target_list: List of target pairs: 'base/base.gyp:base'. target_dicts: Dict of target properties keyed on target pair. data: Dict of flattened build files keyed on gyp path. params: Dict of global options for gyp.
Initialize targets for the ninja wrapper.
[ "Initialize", "targets", "for", "the", "ninja", "wrapper", "." ]
def CreateWrapper(target_list, target_dicts, data, params): """Initialize targets for the ninja wrapper. This sets up the necessary variables in the targets to generate Xcode projects that use ninja as an external builder. Arguments: target_list: List of target pairs: 'base/base.gyp:base'. target_dicts: Dict of target properties keyed on target pair. data: Dict of flattened build files keyed on gyp path. params: Dict of global options for gyp. """ orig_gyp = params['build_files'][0] for gyp_name, gyp_dict in data.iteritems(): if gyp_name == orig_gyp: depth = gyp_dict['_DEPTH'] # Check for custom main gyp name, otherwise use the default CHROMIUM_GYP_FILE # and prepend .ninja before the .gyp extension. generator_flags = params.get('generator_flags', {}) main_gyp = generator_flags.get('xcode_ninja_main_gyp', None) if main_gyp is None: (build_file_root, build_file_ext) = os.path.splitext(orig_gyp) main_gyp = build_file_root + ".ninja" + build_file_ext # Create new |target_list|, |target_dicts| and |data| data structures. new_target_list = [] new_target_dicts = {} new_data = {} # Set base keys needed for |data|. new_data[main_gyp] = {} new_data[main_gyp]['included_files'] = [] new_data[main_gyp]['targets'] = [] new_data[main_gyp]['xcode_settings'] = \ data[orig_gyp].get('xcode_settings', {}) # Normally the xcode-ninja generator includes only valid executable targets. # If |xcode_ninja_executable_target_pattern| is set, that list is reduced to # executable targets that match the pattern. (Default all) executable_target_pattern = \ generator_flags.get('xcode_ninja_executable_target_pattern', None) # For including other non-executable targets, add the matching target name # to the |xcode_ninja_target_pattern| regular expression. (Default none) target_extras = generator_flags.get('xcode_ninja_target_pattern', None) for old_qualified_target in target_list: spec = target_dicts[old_qualified_target] if IsValidTargetForWrapper(target_extras, executable_target_pattern, spec): # Add to new_target_list. target_name = spec.get('target_name') new_target_name = '%s:%s#target' % (main_gyp, target_name) new_target_list.append(new_target_name) # Add to new_target_dicts. new_target_dicts[new_target_name] = _TargetFromSpec(spec, params) # Add to new_data. for old_target in data[old_qualified_target.split(':')[0]]['targets']: if old_target['target_name'] == target_name: new_data_target = {} new_data_target['target_name'] = old_target['target_name'] new_data_target['toolset'] = old_target['toolset'] new_data[main_gyp]['targets'].append(new_data_target) # Create sources target. sources_target_name = 'sources_for_indexing' sources_target = _TargetFromSpec( { 'target_name' : sources_target_name, 'toolset': 'target', 'default_configuration': 'Default', 'mac_bundle': '0', 'type': 'executable' }, None) # Tell Xcode to look everywhere for headers. sources_target['configurations'] = {'Default': { 'include_dirs': [ depth ] } } sources = [] for target, target_dict in target_dicts.iteritems(): base = os.path.dirname(target) files = target_dict.get('sources', []) + \ target_dict.get('mac_bundle_resources', []) for action in target_dict.get('actions', []): files.extend(action.get('inputs', [])) # Remove files starting with $. These are mostly intermediate files for the # build system. files = [ file for file in files if not file.startswith('$')] # Make sources relative to root build file. relative_path = os.path.dirname(main_gyp) sources += [ os.path.relpath(os.path.join(base, file), relative_path) for file in files ] sources_target['sources'] = sorted(set(sources)) # Put sources_to_index in it's own gyp. sources_gyp = \ os.path.join(os.path.dirname(main_gyp), sources_target_name + ".gyp") fully_qualified_target_name = \ '%s:%s#target' % (sources_gyp, sources_target_name) # Add to new_target_list, new_target_dicts and new_data. new_target_list.append(fully_qualified_target_name) new_target_dicts[fully_qualified_target_name] = sources_target new_data_target = {} new_data_target['target_name'] = sources_target['target_name'] new_data_target['_DEPTH'] = depth new_data_target['toolset'] = "target" new_data[sources_gyp] = {} new_data[sources_gyp]['targets'] = [] new_data[sources_gyp]['included_files'] = [] new_data[sources_gyp]['xcode_settings'] = \ data[orig_gyp].get('xcode_settings', {}) new_data[sources_gyp]['targets'].append(new_data_target) # Write workspace to file. _WriteWorkspace(main_gyp, sources_gyp, params) return (new_target_list, new_target_dicts, new_data)
[ "def", "CreateWrapper", "(", "target_list", ",", "target_dicts", ",", "data", ",", "params", ")", ":", "orig_gyp", "=", "params", "[", "'build_files'", "]", "[", "0", "]", "for", "gyp_name", ",", "gyp_dict", "in", "data", ".", "iteritems", "(", ")", ":",...
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_ninja.py#L152-L270
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
SizerFlags.Center
(*args, **kwargs)
return _core_.SizerFlags_Center(*args, **kwargs)
Center(self) -> SizerFlags Sets the centering alignment flags.
Center(self) -> SizerFlags
[ "Center", "(", "self", ")", "-", ">", "SizerFlags" ]
def Center(*args, **kwargs): """ Center(self) -> SizerFlags Sets the centering alignment flags. """ return _core_.SizerFlags_Center(*args, **kwargs)
[ "def", "Center", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "SizerFlags_Center", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L13806-L13812
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/framework/ops.py
python
Operation.node_def
(self)
return self._node_def
Returns a serialized `NodeDef` representation of this operation. Returns: A [`NodeDef`](https://www.tensorflow.org/code/tensorflow/core/framework/node_def.proto) protocol buffer.
Returns a serialized `NodeDef` representation of this operation.
[ "Returns", "a", "serialized", "NodeDef", "representation", "of", "this", "operation", "." ]
def node_def(self): # pylint: disable=line-too-long """Returns a serialized `NodeDef` representation of this operation. Returns: A [`NodeDef`](https://www.tensorflow.org/code/tensorflow/core/framework/node_def.proto) protocol buffer. """ # pylint: enable=line-too-long return self._node_def
[ "def", "node_def", "(", "self", ")", ":", "# pylint: disable=line-too-long", "# pylint: enable=line-too-long", "return", "self", ".", "_node_def" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/framework/ops.py#L1978-L1988
Bitcoin-ABC/bitcoin-abc
aff7e41f00bef9d52786c6cffb49faca5c84d32e
contrib/buildbot/phabricator_wrapper.py
python
PhabWrapper.get_project_members
(self, project_PHID)
return [m["phid"] for m in project_data[0]["attachments"]["members"]["members"]]
Return a list of user PHIDs corresponding to the ABC members
Return a list of user PHIDs corresponding to the ABC members
[ "Return", "a", "list", "of", "user", "PHIDs", "corresponding", "to", "the", "ABC", "members" ]
def get_project_members(self, project_PHID): """ Return a list of user PHIDs corresponding to the ABC members """ project_data = self.project.search( constraints={ "phids": [project_PHID], }, attachments={ "members": True, }, ).data if len(project_data) != 1: self.logger.info( "Found {} project(s) while searching for Bitcoin ABC: '{}'".format( len(project_data), project_data)) return [] return [m["phid"] for m in project_data[0]["attachments"]["members"]["members"]]
[ "def", "get_project_members", "(", "self", ",", "project_PHID", ")", ":", "project_data", "=", "self", ".", "project", ".", "search", "(", "constraints", "=", "{", "\"phids\"", ":", "[", "project_PHID", "]", ",", "}", ",", "attachments", "=", "{", "\"membe...
https://github.com/Bitcoin-ABC/bitcoin-abc/blob/aff7e41f00bef9d52786c6cffb49faca5c84d32e/contrib/buildbot/phabricator_wrapper.py#L296-L314
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/logging/handlers.py
python
DatagramHandler.__init__
(self, host, port)
Initializes the handler with a specific host address and port.
Initializes the handler with a specific host address and port.
[ "Initializes", "the", "handler", "with", "a", "specific", "host", "address", "and", "port", "." ]
def __init__(self, host, port): """ Initializes the handler with a specific host address and port. """ SocketHandler.__init__(self, host, port) self.closeOnError = 0
[ "def", "__init__", "(", "self", ",", "host", ",", "port", ")", ":", "SocketHandler", ".", "__init__", "(", "self", ",", "host", ",", "port", ")", "self", ".", "closeOnError", "=", "0" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/logging/handlers.py#L568-L573
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
python/mxnet/module/executor_group.py
python
DataParallelExecutorGroup.get_params
(self, arg_params, aux_params)
Copy data from each executor to `arg_params` and `aux_params`. Parameters ---------- arg_params : list of NDArray Target parameter arrays. aux_params : list of NDArray Target aux arrays. Notes ----- - This function will inplace update the NDArrays in arg_params and aux_params.
Copy data from each executor to `arg_params` and `aux_params`.
[ "Copy", "data", "from", "each", "executor", "to", "arg_params", "and", "aux_params", "." ]
def get_params(self, arg_params, aux_params): """ Copy data from each executor to `arg_params` and `aux_params`. Parameters ---------- arg_params : list of NDArray Target parameter arrays. aux_params : list of NDArray Target aux arrays. Notes ----- - This function will inplace update the NDArrays in arg_params and aux_params. """ for name, block in zip(self.param_names, self.param_arrays): weight = sum(w.copyto(ctx.cpu()) for w in block) / len(block) weight.astype(arg_params[name].dtype).copyto(arg_params[name]) for name, block in zip(self.aux_names, self.aux_arrays): weight = sum(w.copyto(ctx.cpu()) for w in block) / len(block) weight.astype(aux_params[name].dtype).copyto(aux_params[name])
[ "def", "get_params", "(", "self", ",", "arg_params", ",", "aux_params", ")", ":", "for", "name", ",", "block", "in", "zip", "(", "self", ".", "param_names", ",", "self", ".", "param_arrays", ")", ":", "weight", "=", "sum", "(", "w", ".", "copyto", "(...
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/module/executor_group.py#L373-L392
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/agilepy/lib_wx/ogleditor.py
python
StretchTool.activate
(self, canvas=None)
This call by metacanvas signals that the tool has been activated and can now interact with metacanvas.
This call by metacanvas signals that the tool has been activated and can now interact with metacanvas.
[ "This", "call", "by", "metacanvas", "signals", "that", "the", "tool", "has", "been", "activated", "and", "can", "now", "interact", "with", "metacanvas", "." ]
def activate(self, canvas=None): """ This call by metacanvas signals that the tool has been activated and can now interact with metacanvas. """ self.activate_select(canvas) self.is_animated = False self._is_active = True
[ "def", "activate", "(", "self", ",", "canvas", "=", "None", ")", ":", "self", ".", "activate_select", "(", "canvas", ")", "self", ".", "is_animated", "=", "False", "self", ".", "_is_active", "=", "True" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/agilepy/lib_wx/ogleditor.py#L1382-L1389
intel/caffe
3f494b442ee3f9d17a07b09ecbd5fa2bbda00836
scripts/run_benchmark.py
python
CaffeBenchmark.run_benchmark
(self)
run intelcaffe training benchmark
run intelcaffe training benchmark
[ "run", "intelcaffe", "training", "benchmark" ]
def run_benchmark(self): '''run intelcaffe training benchmark''' self.detect_cpu() logging.info("Cpu model: {}".format(self.model_string)) if self.topology == 'all_train': for model in self.support_topologies: if model == 'all_train': continue logging.info("--{}".format(model)) if self.test_mode == "scal_test": self.run_scal_test(model) else: self.run_specific_model(model) elif self.topology == 'all_inf': for model in self.support_inf_topologies: print("run " + model) if model == 'all_inf': continue logging.info("") logging.info("--{}".format(model)) print("--{}".format(model)) self.run_specific_model(model) else: self.run_specific_model(self.topology)
[ "def", "run_benchmark", "(", "self", ")", ":", "self", ".", "detect_cpu", "(", ")", "logging", ".", "info", "(", "\"Cpu model: {}\"", ".", "format", "(", "self", ".", "model_string", ")", ")", "if", "self", ".", "topology", "==", "'all_train'", ":", "for...
https://github.com/intel/caffe/blob/3f494b442ee3f9d17a07b09ecbd5fa2bbda00836/scripts/run_benchmark.py#L418-L441
Atarity/Lightpack
4dee73a443cba4c4073291febe450e6c1941f3af
Software/apiexamples/liOSC/OSC.py
python
OSCRequestHandler.dispatchMessage
(self, pattern, tags, data)
return replies
Attmept to match the given OSC-address pattern, which may contain '*', against all callbacks registered with the OSCServer. Calls the matching callback and returns whatever it returns. If no match is found, and a 'default' callback is registered, it calls that one, or raises NoCallbackError if a 'default' callback is not registered. - pattern (string): The OSC-address of the receied message - tags (string): The OSC-typetags of the receied message's arguments, without ',' - data (list): The message arguments
Attmept to match the given OSC-address pattern, which may contain '*', against all callbacks registered with the OSCServer. Calls the matching callback and returns whatever it returns. If no match is found, and a 'default' callback is registered, it calls that one, or raises NoCallbackError if a 'default' callback is not registered. - pattern (string): The OSC-address of the receied message - tags (string): The OSC-typetags of the receied message's arguments, without ',' - data (list): The message arguments
[ "Attmept", "to", "match", "the", "given", "OSC", "-", "address", "pattern", "which", "may", "contain", "*", "against", "all", "callbacks", "registered", "with", "the", "OSCServer", ".", "Calls", "the", "matching", "callback", "and", "returns", "whatever", "it"...
def dispatchMessage(self, pattern, tags, data): """Attmept to match the given OSC-address pattern, which may contain '*', against all callbacks registered with the OSCServer. Calls the matching callback and returns whatever it returns. If no match is found, and a 'default' callback is registered, it calls that one, or raises NoCallbackError if a 'default' callback is not registered. - pattern (string): The OSC-address of the receied message - tags (string): The OSC-typetags of the receied message's arguments, without ',' - data (list): The message arguments """ if len(tags) != len(data): raise OSCServerError("Malformed OSC-message; got %d typetags [%s] vs. %d values" % (len(tags), tags, len(data))) expr = getRegEx(pattern) replies = [] matched = 0 for addr in self.server.callbacks.keys(): match = expr.match(addr) if match and (match.end() == len(addr)): reply = self.server.callbacks[addr](pattern, tags, data, self.client_address) matched += 1 if isinstance(reply, OSCMessage): replies.append(reply) elif reply != None: raise TypeError("Message-callback %s did not return OSCMessage or None: %s" % (self.server.callbacks[addr], type(reply))) if matched == 0: if 'default' in self.server.callbacks: reply = self.server.callbacks['default'](pattern, tags, data, self.client_address) if isinstance(reply, OSCMessage): replies.append(reply) elif reply != None: raise TypeError("Message-callback %s did not return OSCMessage or None: %s" % (self.server.callbacks['default'], type(reply))) else: raise NoCallbackError(pattern) return replies
[ "def", "dispatchMessage", "(", "self", ",", "pattern", ",", "tags", ",", "data", ")", ":", "if", "len", "(", "tags", ")", "!=", "len", "(", "data", ")", ":", "raise", "OSCServerError", "(", "\"Malformed OSC-message; got %d typetags [%s] vs. %d values\"", "%", ...
https://github.com/Atarity/Lightpack/blob/4dee73a443cba4c4073291febe450e6c1941f3af/Software/apiexamples/liOSC/OSC.py#L1612-L1650
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py
python
Misc.tk_setPalette
(self, *args, **kw)
Set a new color scheme for all widget elements. A single color as argument will cause that all colors of Tk widget elements are derived from this. Alternatively several keyword parameters and its associated colors can be given. The following keywords are valid: activeBackground, foreground, selectColor, activeForeground, highlightBackground, selectBackground, background, highlightColor, selectForeground, disabledForeground, insertBackground, troughColor.
Set a new color scheme for all widget elements.
[ "Set", "a", "new", "color", "scheme", "for", "all", "widget", "elements", "." ]
def tk_setPalette(self, *args, **kw): """Set a new color scheme for all widget elements. A single color as argument will cause that all colors of Tk widget elements are derived from this. Alternatively several keyword parameters and its associated colors can be given. The following keywords are valid: activeBackground, foreground, selectColor, activeForeground, highlightBackground, selectBackground, background, highlightColor, selectForeground, disabledForeground, insertBackground, troughColor.""" self.tk.call(('tk_setPalette',) + _flatten(args) + _flatten(kw.items()))
[ "def", "tk_setPalette", "(", "self", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "self", ".", "tk", ".", "call", "(", "(", "'tk_setPalette'", ",", ")", "+", "_flatten", "(", "args", ")", "+", "_flatten", "(", "kw", ".", "items", "(", ")", ...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py#L411-L423
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py2/pkg_resources/__init__.py
python
register_namespace_handler
(importer_type, namespace_handler)
Register `namespace_handler` to declare namespace packages `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item handler), and `namespace_handler` is a callable like this:: def namespace_handler(importer, path_entry, moduleName, module): # return a path_entry to use for child packages Namespace handlers are only called if the importer object has already agreed that it can handle the relevant path item, and they should only return a subpath if the module __path__ does not already contain an equivalent subpath. For an example namespace handler, see ``pkg_resources.file_ns_handler``.
Register `namespace_handler` to declare namespace packages
[ "Register", "namespace_handler", "to", "declare", "namespace", "packages" ]
def register_namespace_handler(importer_type, namespace_handler): """Register `namespace_handler` to declare namespace packages `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item handler), and `namespace_handler` is a callable like this:: def namespace_handler(importer, path_entry, moduleName, module): # return a path_entry to use for child packages Namespace handlers are only called if the importer object has already agreed that it can handle the relevant path item, and they should only return a subpath if the module __path__ does not already contain an equivalent subpath. For an example namespace handler, see ``pkg_resources.file_ns_handler``. """ _namespace_handlers[importer_type] = namespace_handler
[ "def", "register_namespace_handler", "(", "importer_type", ",", "namespace_handler", ")", ":", "_namespace_handlers", "[", "importer_type", "]", "=", "namespace_handler" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/pkg_resources/__init__.py#L2173-L2188
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
utils/vim-lldb/python-vim-lldb/lldb_controller.py
python
returnCompleteCommand
(a, l, p)
Returns a "\n"-separated string with possible completion results for command a with length l and cursor at p.
Returns a "\n"-separated string with possible completion results for command a with length l and cursor at p.
[ "Returns", "a", "\\", "n", "-", "separated", "string", "with", "possible", "completion", "results", "for", "command", "a", "with", "length", "l", "and", "cursor", "at", "p", "." ]
def returnCompleteCommand(a, l, p): """ Returns a "\n"-separated string with possible completion results for command a with length l and cursor at p. """ separator = "\n" results = ctrl.completeCommand(a, l, p) vim.command('return "%s%s"' % (separator.join(results), separator))
[ "def", "returnCompleteCommand", "(", "a", ",", "l", ",", "p", ")", ":", "separator", "=", "\"\\n\"", "results", "=", "ctrl", ".", "completeCommand", "(", "a", ",", "l", ",", "p", ")", "vim", ".", "command", "(", "'return \"%s%s\"'", "%", "(", "separato...
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/utils/vim-lldb/python-vim-lldb/lldb_controller.py#L390-L396
fengbingchun/NN_Test
d6305825d5273e4569ccd1eda9ffa2a9c72e18d2
src/tiny-dnn/third_party/gemmlowp/meta/generators/gemm_MxNxK.py
python
GenerateGemm
(emitter, output_type, aligned, rows, cols, leftovers)
Build one gemm function for given row, col, and depth leftovers.
Build one gemm function for given row, col, and depth leftovers.
[ "Build", "one", "gemm", "function", "for", "given", "row", "col", "and", "depth", "leftovers", "." ]
def GenerateGemm(emitter, output_type, aligned, rows, cols, leftovers): """Build one gemm function for given row, col, and depth leftovers.""" emitter.EmitFunctionBeginA( BuildName(output_type, aligned, rows, cols, leftovers), GetStridedGemmParameters(output_type), 'void') emitter.EmitAssert('m %% 3 == %d' % rows) emitter.EmitAssert('n %% 3 == %d' % cols) emitter.EmitAssert('k %% 8 == %d' % leftovers) if output_type is _QUANTIZED_8BIT: GenerateQuantized8BitTempsCountersAndConsts(emitter, rows) GenerateZipRhs(emitter, aligned, cols, leftovers) GenerateQuantized8BitMul(emitter, aligned, rows, cols, leftovers) elif output_type is _FULL_32BIT: GenerateFullTempsCountersAndConsts(emitter, 'std::int32_t*', rows) GenerateZipRhs(emitter, aligned, cols, leftovers) GenerateFullMul(emitter, 'int32', aligned, rows, cols, leftovers) elif output_type is _FULL_FLOAT: GenerateFullTempsCountersAndConsts(emitter, 'float*', rows) GenerateZipRhs(emitter, aligned, cols, leftovers) GenerateFullMul(emitter, 'float', aligned, rows, cols, leftovers) else: raise ConfigurationError('Unknown output type: %s' % output_type) emitter.EmitFunctionEnd()
[ "def", "GenerateGemm", "(", "emitter", ",", "output_type", ",", "aligned", ",", "rows", ",", "cols", ",", "leftovers", ")", ":", "emitter", ".", "EmitFunctionBeginA", "(", "BuildName", "(", "output_type", ",", "aligned", ",", "rows", ",", "cols", ",", "lef...
https://github.com/fengbingchun/NN_Test/blob/d6305825d5273e4569ccd1eda9ffa2a9c72e18d2/src/tiny-dnn/third_party/gemmlowp/meta/generators/gemm_MxNxK.py#L210-L235
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
Window.GetClientRect
(*args, **kwargs)
return _core_.Window_GetClientRect(*args, **kwargs)
GetClientRect(self) -> Rect Get the client area position and size as a `wx.Rect` object.
GetClientRect(self) -> Rect
[ "GetClientRect", "(", "self", ")", "-", ">", "Rect" ]
def GetClientRect(*args, **kwargs): """ GetClientRect(self) -> Rect Get the client area position and size as a `wx.Rect` object. """ return _core_.Window_GetClientRect(*args, **kwargs)
[ "def", "GetClientRect", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Window_GetClientRect", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L9555-L9561
DLR-SC/tigl
d1c5901e948e33d10b1f9659ff3e22c4717b455f
thirdparty/nsiqcppstyle/nsiqcppstyle_rulemanager.py
python
RollbackImporter.__init__
(self)
Creates an instance and installs as the global importer
Creates an instance and installs as the global importer
[ "Creates", "an", "instance", "and", "installs", "as", "the", "global", "importer" ]
def __init__(self): "Creates an instance and installs as the global importer" self.previousModules = sys.modules.copy() self.realImport = __builtins__["__import__"] __builtins__["__import__"] = self._import self.newModules = {}
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "previousModules", "=", "sys", ".", "modules", ".", "copy", "(", ")", "self", ".", "realImport", "=", "__builtins__", "[", "\"__import__\"", "]", "__builtins__", "[", "\"__import__\"", "]", "=", "self"...
https://github.com/DLR-SC/tigl/blob/d1c5901e948e33d10b1f9659ff3e22c4717b455f/thirdparty/nsiqcppstyle/nsiqcppstyle_rulemanager.py#L238-L243
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/protobuf/python/google/protobuf/descriptor_database.py
python
_ExtractSymbols
(desc_proto, package)
Pulls out all the symbols from a descriptor proto. Args: desc_proto: The proto to extract symbols from. package: The package containing the descriptor type. Yields: The fully qualified name found in the descriptor.
Pulls out all the symbols from a descriptor proto.
[ "Pulls", "out", "all", "the", "symbols", "from", "a", "descriptor", "proto", "." ]
def _ExtractSymbols(desc_proto, package): """Pulls out all the symbols from a descriptor proto. Args: desc_proto: The proto to extract symbols from. package: The package containing the descriptor type. Yields: The fully qualified name found in the descriptor. """ message_name = '.'.join((package, desc_proto.name)) yield message_name for nested_type in desc_proto.nested_type: for symbol in _ExtractSymbols(nested_type, message_name): yield symbol for enum_type in desc_proto.enum_type: yield '.'.join((message_name, enum_type.name))
[ "def", "_ExtractSymbols", "(", "desc_proto", ",", "package", ")", ":", "message_name", "=", "'.'", ".", "join", "(", "(", "package", ",", "desc_proto", ".", "name", ")", ")", "yield", "message_name", "for", "nested_type", "in", "desc_proto", ".", "nested_typ...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/protobuf/python/google/protobuf/descriptor_database.py#L103-L120
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/pyparsing.py
python
ParserElement.__add__
(self, other)
return And([self, other])
Implementation of + operator - returns :class:`And`. Adding strings to a ParserElement converts them to :class:`Literal`s by default. Example:: greet = Word(alphas) + "," + Word(alphas) + "!" hello = "Hello, World!" print (hello, "->", greet.parseString(hello)) prints:: Hello, World! -> ['Hello', ',', 'World', '!'] ``...`` may be used as a parse expression as a short form of :class:`SkipTo`. Literal('start') + ... + Literal('end') is equivalent to: Literal('start') + SkipTo('end')("_skipped*") + Literal('end') Note that the skipped text is returned with '_skipped' as a results name, and to support having multiple skips in the same parser, the value returned is a list of all skipped text.
[]
def __add__(self, other): """ Implementation of + operator - returns :class:`And`. Adding strings to a ParserElement converts them to :class:`Literal`s by default. Example:: greet = Word(alphas) + "," + Word(alphas) + "!" hello = "Hello, World!" print (hello, "->", greet.parseString(hello)) prints:: Hello, World! -> ['Hello', ',', 'World', '!'] ``...`` may be used as a parse expression as a short form of :class:`SkipTo`. Literal('start') + ... + Literal('end') is equivalent to: Literal('start') + SkipTo('end')("_skipped*") + Literal('end') Note that the skipped text is returned with '_skipped' as a results name, and to support having multiple skips in the same parser, the value returned is a list of all skipped text. """ if other is Ellipsis: return _PendingSkip(self) if isinstance(other, basestring): other = self._literalStringClass(other) if not isinstance(other, ParserElement): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return And([self, other])
[ "def", "__add__", "(", "self", ",", "other", ")", ":", "if", "other", "is", "Ellipsis", ":", "return", "_PendingSkip", "(", "self", ")", "if", "isinstance", "(", "other", ",", "basestring", ")", ":", "other", "=", "self", ".", "_literalStringClass", "(",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/pyparsing.py#L4275-L4347
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/_config/config.py
python
_build_option_description
(k: str)
return s
Builds a formatted description of a registered option and prints it
Builds a formatted description of a registered option and prints it
[ "Builds", "a", "formatted", "description", "of", "a", "registered", "option", "and", "prints", "it" ]
def _build_option_description(k: str) -> str: """Builds a formatted description of a registered option and prints it""" o = _get_registered_option(k) d = _get_deprecated_option(k) s = f"{k} " if o.doc: s += "\n".join(o.doc.strip().split("\n")) else: s += "No description available." if o: s += f"\n [default: {o.defval}] [currently: {_get_option(k, True)}]" if d: rkey = d.rkey or "" s += "\n (Deprecated" s += f", use `{rkey}` instead." s += ")" return s
[ "def", "_build_option_description", "(", "k", ":", "str", ")", "->", "str", ":", "o", "=", "_get_registered_option", "(", "k", ")", "d", "=", "_get_deprecated_option", "(", "k", ")", "s", "=", "f\"{k} \"", "if", "o", ".", "doc", ":", "s", "+=", "\"\\n\...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/_config/config.py#L645-L666
InsightSoftwareConsortium/ITK
87acfce9a93d928311c38bc371b666b515b9f19d
Modules/ThirdParty/pygccxml/src/pygccxml/utils/utils.py
python
cxx_standard.__init__
(self, cflags)
Class constructor that parses the XML generator's command line Args: cflags (str): cflags command line arguments passed to the XML generator
Class constructor that parses the XML generator's command line
[ "Class", "constructor", "that", "parses", "the", "XML", "generator", "s", "command", "line" ]
def __init__(self, cflags): """Class constructor that parses the XML generator's command line Args: cflags (str): cflags command line arguments passed to the XML generator """ super(cxx_standard, self).__init__() self._stdcxx = None self._is_implicit = False for key in cxx_standard.__STD_CXX: if key in cflags: self._stdcxx = key self._cplusplus = cxx_standard.__STD_CXX[key] if not self._stdcxx: if '-std=' in cflags: raise RuntimeError('Unknown -std=c++xx flag used') # Assume c++03 by default self._stdcxx = '-std=c++03' self._cplusplus = cxx_standard.__STD_CXX['-std=c++03'] self._is_implicit = True
[ "def", "__init__", "(", "self", ",", "cflags", ")", ":", "super", "(", "cxx_standard", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "_stdcxx", "=", "None", "self", ".", "_is_implicit", "=", "False", "for", "key", "in", "cxx_standard", ".",...
https://github.com/InsightSoftwareConsortium/ITK/blob/87acfce9a93d928311c38bc371b666b515b9f19d/Modules/ThirdParty/pygccxml/src/pygccxml/utils/utils.py#L306-L329
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/idlelib/run.py
python
exit
()
Exit subprocess, possibly after first deleting sys.exitfunc If config-main.cfg/.def 'General' 'delete-exitfunc' is True, then any sys.exitfunc will be removed before exiting. (VPython support)
Exit subprocess, possibly after first deleting sys.exitfunc
[ "Exit", "subprocess", "possibly", "after", "first", "deleting", "sys", ".", "exitfunc" ]
def exit(): """Exit subprocess, possibly after first deleting sys.exitfunc If config-main.cfg/.def 'General' 'delete-exitfunc' is True, then any sys.exitfunc will be removed before exiting. (VPython support) """ if no_exitfunc: try: del sys.exitfunc except AttributeError: pass capture_warnings(False) sys.exit(0)
[ "def", "exit", "(", ")", ":", "if", "no_exitfunc", ":", "try", ":", "del", "sys", ".", "exitfunc", "except", "AttributeError", ":", "pass", "capture_warnings", "(", "False", ")", "sys", ".", "exit", "(", "0", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/idlelib/run.py#L229-L242
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBCommandReturnObject.PutOutput
(self, *args)
return _lldb.SBCommandReturnObject_PutOutput(self, *args)
PutOutput(self, FILE fh) -> size_t
PutOutput(self, FILE fh) -> size_t
[ "PutOutput", "(", "self", "FILE", "fh", ")", "-", ">", "size_t" ]
def PutOutput(self, *args): """PutOutput(self, FILE fh) -> size_t""" return _lldb.SBCommandReturnObject_PutOutput(self, *args)
[ "def", "PutOutput", "(", "self", ",", "*", "args", ")", ":", "return", "_lldb", ".", "SBCommandReturnObject_PutOutput", "(", "self", ",", "*", "args", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L2322-L2324
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
python/mxnet/callback.py
python
Speedometer.__call__
(self, param)
Callback to Show speed.
Callback to Show speed.
[ "Callback", "to", "Show", "speed", "." ]
def __call__(self, param): """Callback to Show speed.""" count = param.nbatch if self.last_count > count: self.init = False self.last_count = count if self.init: if count % self.frequent == 0: speed = self.frequent * self.batch_size / (time.time() - self.tic) if param.eval_metric is not None: name_value = param.eval_metric.get_name_value() if self.auto_reset: param.eval_metric.reset() msg = 'Epoch[%d] Batch [%d]\tSpeed: %.2f samples/sec' msg += '\t%s=%f'*len(name_value) logging.info(msg, param.epoch, count, speed, *sum(name_value, ())) else: logging.info("Iter[%d] Batch [%d]\tSpeed: %.2f samples/sec", param.epoch, count, speed) self.tic = time.time() else: self.init = True self.tic = time.time()
[ "def", "__call__", "(", "self", ",", "param", ")", ":", "count", "=", "param", ".", "nbatch", "if", "self", ".", "last_count", ">", "count", ":", "self", ".", "init", "=", "False", "self", ".", "last_count", "=", "count", "if", "self", ".", "init", ...
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/callback.py#L150-L173
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/richtext.py
python
RichTextLine.GetRange
(*args, **kwargs)
return _richtext.RichTextLine_GetRange(*args, **kwargs)
GetRange(self) -> RichTextRange
GetRange(self) -> RichTextRange
[ "GetRange", "(", "self", ")", "-", ">", "RichTextRange" ]
def GetRange(*args, **kwargs): """GetRange(self) -> RichTextRange""" return _richtext.RichTextLine_GetRange(*args, **kwargs)
[ "def", "GetRange", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextLine_GetRange", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L1911-L1913
smilehao/xlua-framework
a03801538be2b0e92d39332d445b22caca1ef61f
ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/google/protobuf/internal/python_message.py
python
_IsPresent
(item)
Given a (FieldDescriptor, value) tuple from _fields, return true if the value should be included in the list returned by ListFields().
Given a (FieldDescriptor, value) tuple from _fields, return true if the value should be included in the list returned by ListFields().
[ "Given", "a", "(", "FieldDescriptor", "value", ")", "tuple", "from", "_fields", "return", "true", "if", "the", "value", "should", "be", "included", "in", "the", "list", "returned", "by", "ListFields", "()", "." ]
def _IsPresent(item): """Given a (FieldDescriptor, value) tuple from _fields, return true if the value should be included in the list returned by ListFields().""" if item[0].label == _FieldDescriptor.LABEL_REPEATED: return bool(item[1]) elif item[0].cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: return item[1]._is_present_in_parent else: return True
[ "def", "_IsPresent", "(", "item", ")", ":", "if", "item", "[", "0", "]", ".", "label", "==", "_FieldDescriptor", ".", "LABEL_REPEATED", ":", "return", "bool", "(", "item", "[", "1", "]", ")", "elif", "item", "[", "0", "]", ".", "cpp_type", "==", "_...
https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/google/protobuf/internal/python_message.py#L562-L571
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/numbers.py
python
Integral.__rrshift__
(self, other)
other >> self
other >> self
[ "other", ">>", "self" ]
def __rrshift__(self, other): """other >> self""" raise NotImplementedError
[ "def", "__rrshift__", "(", "self", ",", "other", ")", ":", "raise", "NotImplementedError" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/numbers.py#L336-L338
nasa/fprime
595cf3682d8365943d86c1a6fe7c78f0a116acf0
Autocoders/Python/src/fprime_ac/models/ModelParser.py
python
ModelParser.getChannelsList
(self, obj)
return channel_instance_name_list
Return list of telemetry channels
Return list of telemetry channels
[ "Return", "list", "of", "telemetry", "channels" ]
def getChannelsList(self, obj): """ Return list of telemetry channels """ channel_instance_name_list = [] for channel in obj.get_channels(): i = channel.get_ids() n = channel.get_name() t = channel.get_type() ti = None if isinstance(t, tuple): # rename type to enum type t = t[0][1] ti = "enum" elif t not in TypesList.types_list: ti = "user" s = channel.get_size() u = channel.get_update() c = channel.get_comment() channel_instance_name_list.append((i, n, t, s, u, c, ti)) return channel_instance_name_list
[ "def", "getChannelsList", "(", "self", ",", "obj", ")", ":", "channel_instance_name_list", "=", "[", "]", "for", "channel", "in", "obj", ".", "get_channels", "(", ")", ":", "i", "=", "channel", ".", "get_ids", "(", ")", "n", "=", "channel", ".", "get_n...
https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/models/ModelParser.py#L383-L404
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/plot_widget/plotting_canvas/plotting_canvas_presenter.py
python
PlottingCanvasPresenter.set_axis_title
(self, ax_num, title)
Sets the title for a specified axis in the figure
Sets the title for a specified axis in the figure
[ "Sets", "the", "title", "for", "a", "specified", "axis", "in", "the", "figure" ]
def set_axis_title(self, ax_num, title): """Sets the title for a specified axis in the figure""" self._view.set_title(ax_num, title)
[ "def", "set_axis_title", "(", "self", ",", "ax_num", ",", "title", ")", ":", "self", ".", "_view", ".", "set_title", "(", "ax_num", ",", "title", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/plot_widget/plotting_canvas/plotting_canvas_presenter.py#L111-L113
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/SANS/sans/algorithm_detail/xml_shapes.py
python
finite_cylinder
(centre, radius, height, axis, shape_id='shape')
return '<cylinder id="' + str(shape_id) + '">' + \ '<centre-of-bottom-base x="' + str(centre[0]) + '" y="' + str(centre[1]) + '" z="' + str(centre[2]) + \ '" />' + \ '<axis x="' + str(axis[0]) + '" y="' + str(axis[1]) + '" z="' + str(axis[2]) + '" />' + \ '<radius val="' + str(radius) + '" /><height val="' + str(height) + '" /></cylinder>\n'
Generates xml code for an infintely long cylinder :param centre: a tuple for a point on the axis :param radius: cylinder radius :param height: cylinder height :param axis: cylinder orientation :param shape_id: a string to refer to the shape by :return the xml string
Generates xml code for an infintely long cylinder :param centre: a tuple for a point on the axis :param radius: cylinder radius :param height: cylinder height :param axis: cylinder orientation :param shape_id: a string to refer to the shape by :return the xml string
[ "Generates", "xml", "code", "for", "an", "infintely", "long", "cylinder", ":", "param", "centre", ":", "a", "tuple", "for", "a", "point", "on", "the", "axis", ":", "param", "radius", ":", "cylinder", "radius", ":", "param", "height", ":", "cylinder", "he...
def finite_cylinder(centre, radius, height, axis, shape_id='shape'): """ Generates xml code for an infintely long cylinder :param centre: a tuple for a point on the axis :param radius: cylinder radius :param height: cylinder height :param axis: cylinder orientation :param shape_id: a string to refer to the shape by :return the xml string """ return '<cylinder id="' + str(shape_id) + '">' + \ '<centre-of-bottom-base x="' + str(centre[0]) + '" y="' + str(centre[1]) + '" z="' + str(centre[2]) + \ '" />' + \ '<axis x="' + str(axis[0]) + '" y="' + str(axis[1]) + '" z="' + str(axis[2]) + '" />' + \ '<radius val="' + str(radius) + '" /><height val="' + str(height) + '" /></cylinder>\n'
[ "def", "finite_cylinder", "(", "centre", ",", "radius", ",", "height", ",", "axis", ",", "shape_id", "=", "'shape'", ")", ":", "return", "'<cylinder id=\"'", "+", "str", "(", "shape_id", ")", "+", "'\">'", "+", "'<centre-of-bottom-base x=\"'", "+", "str", "(...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/sans/algorithm_detail/xml_shapes.py#L53-L67
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
tools/code_coverage/process_coverage.py
python
CleanPathNames
(dir)
Clean the pathnames of the HTML generated by genhtml. This method is required only for code coverage on Win32. Due to a known issue with reading from CIFS shares mounted on Linux, genhtml appends a ^M to every file name it reads from the Windows share, causing corrupt filenames in genhtml's output folder. Args: dir: Output folder of the genhtml output. Returns: None
Clean the pathnames of the HTML generated by genhtml.
[ "Clean", "the", "pathnames", "of", "the", "HTML", "generated", "by", "genhtml", "." ]
def CleanPathNames(dir): """Clean the pathnames of the HTML generated by genhtml. This method is required only for code coverage on Win32. Due to a known issue with reading from CIFS shares mounted on Linux, genhtml appends a ^M to every file name it reads from the Windows share, causing corrupt filenames in genhtml's output folder. Args: dir: Output folder of the genhtml output. Returns: None """ # Stip off the ^M characters that get appended to the file name for dirpath, dirname, filenames in os.walk(dir): for file in filenames: file_clean = file.replace('\r', '') if file_clean != file: os.rename(file, file_clean)
[ "def", "CleanPathNames", "(", "dir", ")", ":", "# Stip off the ^M characters that get appended to the file name", "for", "dirpath", ",", "dirname", ",", "filenames", "in", "os", ".", "walk", "(", "dir", ")", ":", "for", "file", "in", "filenames", ":", "file_clean"...
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/tools/code_coverage/process_coverage.py#L38-L57
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/ctypes/__init__.py
python
create_string_buffer
(init, size=None)
create_string_buffer(aBytes) -> character array create_string_buffer(anInteger) -> character array create_string_buffer(aBytes, anInteger) -> character array
create_string_buffer(aBytes) -> character array create_string_buffer(anInteger) -> character array create_string_buffer(aBytes, anInteger) -> character array
[ "create_string_buffer", "(", "aBytes", ")", "-", ">", "character", "array", "create_string_buffer", "(", "anInteger", ")", "-", ">", "character", "array", "create_string_buffer", "(", "aBytes", "anInteger", ")", "-", ">", "character", "array" ]
def create_string_buffer(init, size=None): """create_string_buffer(aBytes) -> character array create_string_buffer(anInteger) -> character array create_string_buffer(aBytes, anInteger) -> character array """ if isinstance(init, bytes): if size is None: size = len(init)+1 buftype = c_char * size buf = buftype() buf.value = init return buf elif isinstance(init, int): buftype = c_char * init buf = buftype() return buf raise TypeError(init)
[ "def", "create_string_buffer", "(", "init", ",", "size", "=", "None", ")", ":", "if", "isinstance", "(", "init", ",", "bytes", ")", ":", "if", "size", "is", "None", ":", "size", "=", "len", "(", "init", ")", "+", "1", "buftype", "=", "c_char", "*",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/ctypes/__init__.py#L47-L63
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/keras/engine/training_generator_v1.py
python
model_iteration
(model, data, steps_per_epoch=None, epochs=1, verbose=1, callbacks=None, validation_data=None, validation_steps=None, validation_freq=1, class_weight=None, max_queue_size=10, workers=1, use_multiprocessing=False, shuffle=False, initial_epoch=0, mode=ModeKeys.TRAIN, batch_size=None, steps_name='steps', **kwargs)
return results
Loop function for arrays of data with modes TRAIN/TEST/PREDICT. Args: model: Keras Model instance. data: Either a tuple of NumPy/Tensor inputs (i.e. `(x,)` or `(x, y)` or `(x, y, sample_weights)`) or a generator or `keras.utils.data_utils.Sequence` object or Eager Iterator or Dataset. steps_per_epoch: Total number of steps (batches of samples) before declaring one epoch finished and starting the next epoch. Ignored with the default value of `None`. epochs: Number of times to iterate over the data. verbose: 0, 1, or 2. Verbosity mode. 0 = silent, 1 = progress bar, 2 = one line per epoch. Note that the progress bar is not particularly useful when logged to a file, so verbose=2 is recommended when not running interactively (eg, in a production environment). callbacks: List of callbacks to be called during training. validation_data: Either a tuple of NumPy/Tensor inputs (i.e. `(x,)` or `(x, y)` or `(x, y, sample_weights)`) or a generator or `keras.utils.data_utils.Sequence` object or Eager Iterator or Dataset. validation_steps: Total number of steps (batches of samples) before declaring validation finished. validation_freq: Only relevant if validation data is provided. Integer or `collections.abc.Container` instance (e.g. list, tuple, etc.). If an integer, specifies how many training epochs to run before a new validation run is performed, e.g. `validation_freq=2` runs validation every 2 epochs. If a Container, specifies the epochs on which to run validation, e.g. `validation_freq=[1, 2, 10]` runs validation at the end of the 1st, 2nd, and 10th epochs. class_weight: Dictionary mapping class indices to a weight for the class. max_queue_size: Integer. Maximum size for the generator queue. If unspecified, `max_queue_size` will default to 10. workers: Integer. Maximum number of processes to spin up when using process-based threading. If unspecified, `workers` will default to 1. If 0, will execute the generator on the main thread. use_multiprocessing: Boolean. If `True`, use process-based threading. If unspecified, `use_multiprocessing` will default to `False`. Note that because this implementation relies on multiprocessing, you should not pass non-picklable arguments to the generator as they can't be passed easily to children processes. shuffle: Boolean. Whether to shuffle the order of the batches at the beginning of each epoch. Only used with instances of `Sequence` (`keras.utils.Sequence`). Has no effect when `steps_per_epoch` is not `None`. initial_epoch: Epoch at which to start training (useful for resuming a previous training run). mode: One of ModeKeys.TRAIN/ModeKeys.TEST/ModeKeys.PREDICT. batch_size: Integer batch size or None if unknown. Will only be used if `data` is in NumPy/Tensor format. steps_name: The string name of the steps argument, either `steps`, `validation_steps`, or `steps_per_epoch`. Only used for error message formatting. **kwargs: Additional arguments for backwards compatibility. `steps` is accepted as an alias for `steps_per_epoch`. Returns: - In TRAIN mode: `History` object. - In TEST mode: Evaluation metrics. - In PREDICT mode: Outputs of the Model called on inputs. Raises: ValueError: in case of invalid arguments.
Loop function for arrays of data with modes TRAIN/TEST/PREDICT.
[ "Loop", "function", "for", "arrays", "of", "data", "with", "modes", "TRAIN", "/", "TEST", "/", "PREDICT", "." ]
def model_iteration(model, data, steps_per_epoch=None, epochs=1, verbose=1, callbacks=None, validation_data=None, validation_steps=None, validation_freq=1, class_weight=None, max_queue_size=10, workers=1, use_multiprocessing=False, shuffle=False, initial_epoch=0, mode=ModeKeys.TRAIN, batch_size=None, steps_name='steps', **kwargs): """Loop function for arrays of data with modes TRAIN/TEST/PREDICT. Args: model: Keras Model instance. data: Either a tuple of NumPy/Tensor inputs (i.e. `(x,)` or `(x, y)` or `(x, y, sample_weights)`) or a generator or `keras.utils.data_utils.Sequence` object or Eager Iterator or Dataset. steps_per_epoch: Total number of steps (batches of samples) before declaring one epoch finished and starting the next epoch. Ignored with the default value of `None`. epochs: Number of times to iterate over the data. verbose: 0, 1, or 2. Verbosity mode. 0 = silent, 1 = progress bar, 2 = one line per epoch. Note that the progress bar is not particularly useful when logged to a file, so verbose=2 is recommended when not running interactively (eg, in a production environment). callbacks: List of callbacks to be called during training. validation_data: Either a tuple of NumPy/Tensor inputs (i.e. `(x,)` or `(x, y)` or `(x, y, sample_weights)`) or a generator or `keras.utils.data_utils.Sequence` object or Eager Iterator or Dataset. validation_steps: Total number of steps (batches of samples) before declaring validation finished. validation_freq: Only relevant if validation data is provided. Integer or `collections.abc.Container` instance (e.g. list, tuple, etc.). If an integer, specifies how many training epochs to run before a new validation run is performed, e.g. `validation_freq=2` runs validation every 2 epochs. If a Container, specifies the epochs on which to run validation, e.g. `validation_freq=[1, 2, 10]` runs validation at the end of the 1st, 2nd, and 10th epochs. class_weight: Dictionary mapping class indices to a weight for the class. max_queue_size: Integer. Maximum size for the generator queue. If unspecified, `max_queue_size` will default to 10. workers: Integer. Maximum number of processes to spin up when using process-based threading. If unspecified, `workers` will default to 1. If 0, will execute the generator on the main thread. use_multiprocessing: Boolean. If `True`, use process-based threading. If unspecified, `use_multiprocessing` will default to `False`. Note that because this implementation relies on multiprocessing, you should not pass non-picklable arguments to the generator as they can't be passed easily to children processes. shuffle: Boolean. Whether to shuffle the order of the batches at the beginning of each epoch. Only used with instances of `Sequence` (`keras.utils.Sequence`). Has no effect when `steps_per_epoch` is not `None`. initial_epoch: Epoch at which to start training (useful for resuming a previous training run). mode: One of ModeKeys.TRAIN/ModeKeys.TEST/ModeKeys.PREDICT. batch_size: Integer batch size or None if unknown. Will only be used if `data` is in NumPy/Tensor format. steps_name: The string name of the steps argument, either `steps`, `validation_steps`, or `steps_per_epoch`. Only used for error message formatting. **kwargs: Additional arguments for backwards compatibility. `steps` is accepted as an alias for `steps_per_epoch`. Returns: - In TRAIN mode: `History` object. - In TEST mode: Evaluation metrics. - In PREDICT mode: Outputs of the Model called on inputs. Raises: ValueError: in case of invalid arguments. """ if 'steps' in kwargs: steps_per_epoch = kwargs['steps'] # Determine the number of steps per epoch and whether we should reset the # dataset at the end of each epoch. reset_dataset_after_each_epoch = False original_dataset = None is_dataset = isinstance(data, (dataset_ops.DatasetV2, dataset_ops.DatasetV1)) if is_dataset: original_dataset = data if steps_per_epoch is None: reset_dataset_after_each_epoch = True steps_per_epoch = training_utils_v1.infer_steps_for_dataset( model, data, steps_per_epoch, epochs=epochs, steps_name=steps_name) # Convert to a format that supports `next(generator)`. generator, steps_per_epoch = convert_to_generator_like( data, steps_per_epoch=steps_per_epoch, batch_size=batch_size, epochs=epochs - initial_epoch, shuffle=shuffle) do_validation = validation_data is not None is_sequence = isinstance(generator, data_utils.Sequence) _validate_arguments(is_sequence, is_dataset, use_multiprocessing, workers, steps_per_epoch, validation_data, validation_steps, mode, kwargs) batch_function = _make_execution_function( model, mode, class_weight=class_weight) # Create the queue for the generator. enqueuer = None if not is_dataset: generator, enqueuer = _make_enqueued_generator( generator, workers=workers, use_multiprocessing=use_multiprocessing, max_queue_size=max_queue_size, shuffle=shuffle) num_samples_or_steps, use_steps = _get_num_samples_or_steps( data, steps_per_epoch) count_mode = 'steps' if use_steps else 'samples' callbacks = cbks.configure_callbacks( callbacks, model, do_validation=do_validation, epochs=epochs, steps_per_epoch=steps_per_epoch, batch_size=batch_size, samples=num_samples_or_steps, count_mode=count_mode, verbose=verbose, mode=mode) if mode == ModeKeys.PREDICT: aggregator = training_utils_v1.OutputsAggregator( True, steps=steps_per_epoch) else: aggregator = training_utils_v1.MetricsAggregator( True, steps=steps_per_epoch) should_set_learning_phase = context.executing_eagerly() and model.run_eagerly if should_set_learning_phase: learning_phase_scope = backend.eager_learning_phase_scope( 1 if mode == ModeKeys.TRAIN else 0) learning_phase_scope.__enter__() callbacks.model.stop_training = False callbacks._call_begin_hook(mode) initial_epoch = model._maybe_load_initial_epoch_from_ckpt(initial_epoch, mode) for epoch in range(initial_epoch, epochs): if callbacks.model.stop_training: break # Setup work for each epoch. model.reset_metrics() epoch_logs = {} if mode == ModeKeys.TRAIN: callbacks.on_epoch_begin(epoch, epoch_logs) if steps_per_epoch is None: # Loop over dataset until `OutOfRangeError` is raised. target_steps = np.inf else: # Loop over dataset for the specified number of steps. target_steps = steps_per_epoch step = 0 while step < target_steps: batch_data = _get_next_batch(generator) if batch_data is None: if is_dataset: # The dataset passed by the user ran out of batches. # Now we know the cardinality of the dataset. # If steps_per_epoch was specified, then running out of data is # unexpected, so we stop training and inform the user. if steps_per_epoch: callbacks.model.stop_training = True logging.warning( 'Your dataset ran out of data; interrupting training. ' 'Make sure that your dataset can generate at least ' '`%s * epochs` batches (in this case, %d batches). ' 'You may need to use the repeat() function when ' 'building your dataset.' % (steps_name, steps_per_epoch * epochs)) elif step > 0: steps_per_epoch = step aggregator.steps = steps_per_epoch else: # We ran out of batches while the user passed an iterator (legacy). callbacks.model.stop_training = True logging.warning( 'Your dataset iterator ran out of data; ' 'interrupting training. Make sure that your iterator ' 'can generate at least `%s * epochs` ' 'batches (in this case, %d batches). You may need to' 'use the repeat() function when building your ' 'dataset.' % (steps_name, steps_per_epoch * epochs)) break # `batch_size` used for validation data if validation # data is NumPy/EagerTensors. batch_size = int(nest.flatten(batch_data)[0].shape[0]) # Callbacks batch begin. batch_logs = {'batch': step, 'size': batch_size} callbacks._call_batch_hook(mode, 'begin', step, batch_logs) is_deferred = not model._is_compiled batch_outs = batch_function(*batch_data) if not isinstance(batch_outs, list): batch_outs = [batch_outs] if step == 0: aggregator.create(batch_outs) if is_deferred: # Set callbacks params. We do this here when model is compiled only # in the first iteration of this loop (deferred build scenario). cbks.set_callback_parameters( callbacks, model, do_validation=do_validation, batch_size=batch_size, epochs=epochs, steps_per_epoch=steps_per_epoch, samples=num_samples_or_steps, verbose=verbose, mode=mode) # Aggregate results. aggregator.aggregate(batch_outs) # Callbacks batch end. batch_logs = cbks.make_logs(model, batch_logs, batch_outs, mode) callbacks._call_batch_hook(mode, 'end', step, batch_logs) step += 1 if callbacks.model.stop_training: break aggregator.finalize() results = aggregator.results epoch_logs = cbks.make_logs(model, epoch_logs, results, mode) if len(results) == 1: results = results[0] # Run the test loop every epoch during training. if (do_validation and training_utils_v1.should_run_validation(validation_freq, epoch) and not callbacks.model.stop_training): val_results = model_iteration( model, validation_data, steps_per_epoch=validation_steps, batch_size=batch_size, class_weight=class_weight, workers=workers, use_multiprocessing=use_multiprocessing, max_queue_size=max_queue_size, callbacks=callbacks, verbose=verbose, mode=ModeKeys.TEST, steps_name='validation_steps') if not isinstance(val_results, list): val_results = [val_results] epoch_logs = cbks.make_logs( model, epoch_logs, val_results, mode, prefix='val_') if mode == ModeKeys.TRAIN: # Epochs only apply to `fit`. callbacks.on_epoch_end(epoch, epoch_logs) # Recreate dataset iterator for the next epoch. if reset_dataset_after_each_epoch and epoch < epochs - 1: generator = dataset_ops.make_one_shot_iterator(original_dataset) model._successful_loop_finish = True callbacks._call_end_hook(mode) if enqueuer is not None: enqueuer.stop() if should_set_learning_phase: learning_phase_scope.__exit__(None, None, None) if mode == ModeKeys.TRAIN: return model.history return results
[ "def", "model_iteration", "(", "model", ",", "data", ",", "steps_per_epoch", "=", "None", ",", "epochs", "=", "1", ",", "verbose", "=", "1", ",", "callbacks", "=", "None", ",", "validation_data", "=", "None", ",", "validation_steps", "=", "None", ",", "v...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/engine/training_generator_v1.py#L39-L336
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/ir_utils.py
python
restore_copy_var_names
(blocks, save_copies, typemap)
restores variable names of user variables after applying copy propagation
restores variable names of user variables after applying copy propagation
[ "restores", "variable", "names", "of", "user", "variables", "after", "applying", "copy", "propagation" ]
def restore_copy_var_names(blocks, save_copies, typemap): """ restores variable names of user variables after applying copy propagation """ rename_dict = {} for (a, b) in save_copies: # a is string name, b is variable # if a is user variable and b is generated temporary and b is not # already renamed if (not a.startswith('$') and b.name.startswith('$') and b.name not in rename_dict): new_name = mk_unique_var('${}'.format(a)); rename_dict[b.name] = new_name typ = typemap.pop(b.name) typemap[new_name] = typ replace_var_names(blocks, rename_dict)
[ "def", "restore_copy_var_names", "(", "blocks", ",", "save_copies", ",", "typemap", ")", ":", "rename_dict", "=", "{", "}", "for", "(", "a", ",", "b", ")", "in", "save_copies", ":", "# a is string name, b is variable", "# if a is user variable and b is generated tempo...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/ir_utils.py#L1381-L1397
glotzerlab/hoomd-blue
f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a
hoomd/update/particle_filter.py
python
FilterUpdater.__eq__
(self, other)
return super().__eq__(other) and self._filters == other._filters
Return whether two objects are equivalent.
Return whether two objects are equivalent.
[ "Return", "whether", "two", "objects", "are", "equivalent", "." ]
def __eq__(self, other): """Return whether two objects are equivalent.""" return super().__eq__(other) and self._filters == other._filters
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "return", "super", "(", ")", ".", "__eq__", "(", "other", ")", "and", "self", ".", "_filters", "==", "other", ".", "_filters" ]
https://github.com/glotzerlab/hoomd-blue/blob/f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a/hoomd/update/particle_filter.py#L96-L98
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/signal/windows/windows.py
python
nuttall
(M, sym=True)
return general_cosine(M, [0.3635819, 0.4891775, 0.1365995, 0.0106411], sym)
Return a minimum 4-term Blackman-Harris window according to Nuttall. This variation is called "Nuttall4c" by Heinzel. [2]_ Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. sym : bool, optional When True (default), generates a symmetric window, for use in filter design. When False, generates a periodic window, for use in spectral analysis. Returns ------- w : ndarray The window, with the maximum value normalized to 1 (though the value 1 does not appear if `M` is even and `sym` is True). References ---------- .. [1] A. Nuttall, "Some windows with very good sidelobe behavior," IEEE Transactions on Acoustics, Speech, and Signal Processing, vol. 29, no. 1, pp. 84-91, Feb 1981. :doi:`10.1109/TASSP.1981.1163506`. .. [2] Heinzel G. et al., "Spectrum and spectral density estimation by the Discrete Fourier transform (DFT), including a comprehensive list of window functions and some new flat-top windows", February 15, 2002 https://holometer.fnal.gov/GH_FFT.pdf Examples -------- Plot the window and its frequency response: >>> from scipy import signal >>> from scipy.fftpack import fft, fftshift >>> import matplotlib.pyplot as plt >>> window = signal.nuttall(51) >>> plt.plot(window) >>> plt.title("Nuttall window") >>> plt.ylabel("Amplitude") >>> plt.xlabel("Sample") >>> plt.figure() >>> A = fft(window, 2048) / (len(window)/2.0) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) >>> plt.plot(freq, response) >>> plt.axis([-0.5, 0.5, -120, 0]) >>> plt.title("Frequency response of the Nuttall window") >>> plt.ylabel("Normalized magnitude [dB]") >>> plt.xlabel("Normalized frequency [cycles per sample]")
Return a minimum 4-term Blackman-Harris window according to Nuttall.
[ "Return", "a", "minimum", "4", "-", "term", "Blackman", "-", "Harris", "window", "according", "to", "Nuttall", "." ]
def nuttall(M, sym=True): """Return a minimum 4-term Blackman-Harris window according to Nuttall. This variation is called "Nuttall4c" by Heinzel. [2]_ Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. sym : bool, optional When True (default), generates a symmetric window, for use in filter design. When False, generates a periodic window, for use in spectral analysis. Returns ------- w : ndarray The window, with the maximum value normalized to 1 (though the value 1 does not appear if `M` is even and `sym` is True). References ---------- .. [1] A. Nuttall, "Some windows with very good sidelobe behavior," IEEE Transactions on Acoustics, Speech, and Signal Processing, vol. 29, no. 1, pp. 84-91, Feb 1981. :doi:`10.1109/TASSP.1981.1163506`. .. [2] Heinzel G. et al., "Spectrum and spectral density estimation by the Discrete Fourier transform (DFT), including a comprehensive list of window functions and some new flat-top windows", February 15, 2002 https://holometer.fnal.gov/GH_FFT.pdf Examples -------- Plot the window and its frequency response: >>> from scipy import signal >>> from scipy.fftpack import fft, fftshift >>> import matplotlib.pyplot as plt >>> window = signal.nuttall(51) >>> plt.plot(window) >>> plt.title("Nuttall window") >>> plt.ylabel("Amplitude") >>> plt.xlabel("Sample") >>> plt.figure() >>> A = fft(window, 2048) / (len(window)/2.0) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) >>> plt.plot(freq, response) >>> plt.axis([-0.5, 0.5, -120, 0]) >>> plt.title("Frequency response of the Nuttall window") >>> plt.ylabel("Normalized magnitude [dB]") >>> plt.xlabel("Normalized frequency [cycles per sample]") """ return general_cosine(M, [0.3635819, 0.4891775, 0.1365995, 0.0106411], sym)
[ "def", "nuttall", "(", "M", ",", "sym", "=", "True", ")", ":", "return", "general_cosine", "(", "M", ",", "[", "0.3635819", ",", "0.4891775", ",", "0.1365995", ",", "0.0106411", "]", ",", "sym", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/signal/windows/windows.py#L442-L498
RLBot/RLBot
34332b12cf158b3ef8dbf174ae67c53683368a9d
src/main/python/rlbot/utils/game_state_util.py
python
CarState.convert_to_flat
(self, builder)
return DesiredCarState.DesiredCarStateEnd(builder)
In this conversion, we always want to return a valid flatbuffer pointer even if all the contents are blank because sometimes we need to put empty car states into the car list to make the indices line up.
In this conversion, we always want to return a valid flatbuffer pointer even if all the contents are blank because sometimes we need to put empty car states into the car list to make the indices line up.
[ "In", "this", "conversion", "we", "always", "want", "to", "return", "a", "valid", "flatbuffer", "pointer", "even", "if", "all", "the", "contents", "are", "blank", "because", "sometimes", "we", "need", "to", "put", "empty", "car", "states", "into", "the", "...
def convert_to_flat(self, builder): """ In this conversion, we always want to return a valid flatbuffer pointer even if all the contents are blank because sometimes we need to put empty car states into the car list to make the indices line up. """ physics_offset = None if self.physics is None else self.physics.convert_to_flat(builder) DesiredCarState.DesiredCarStateStart(builder) if physics_offset is not None: DesiredCarState.DesiredCarStateAddPhysics(builder, physics_offset) if self.boost_amount is not None: DesiredCarState.DesiredCarStateAddBoostAmount(builder, Float.CreateFloat(builder, self.boost_amount)) if self.jumped is not None: DesiredCarState.DesiredCarStateAddJumped(builder, Bool.CreateBool(builder, self.jumped)) if self.double_jumped is not None: DesiredCarState.DesiredCarStateAddDoubleJumped(builder, Bool.CreateBool(builder, self.double_jumped)) return DesiredCarState.DesiredCarStateEnd(builder)
[ "def", "convert_to_flat", "(", "self", ",", "builder", ")", ":", "physics_offset", "=", "None", "if", "self", ".", "physics", "is", "None", "else", "self", ".", "physics", ".", "convert_to_flat", "(", "builder", ")", "DesiredCarState", ".", "DesiredCarStateSta...
https://github.com/RLBot/RLBot/blob/34332b12cf158b3ef8dbf174ae67c53683368a9d/src/main/python/rlbot/utils/game_state_util.py#L109-L126
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/bintrees/bintrees/treemixin.py
python
TreeMixin.symmetric_difference
(self, tree)
return self.__class__( ((key, self.get(key)) for key in rkeys) )
x.symmetric_difference(t1) -> Tree with keys in either T and t1 but not both
x.symmetric_difference(t1) -> Tree with keys in either T and t1 but not both
[ "x", ".", "symmetric_difference", "(", "t1", ")", "-", ">", "Tree", "with", "keys", "in", "either", "T", "and", "t1", "but", "not", "both" ]
def symmetric_difference(self, tree): """ x.symmetric_difference(t1) -> Tree with keys in either T and t1 but not both """ thiskeys = frozenset(self.keys()) rkeys = thiskeys.symmetric_difference(frozenset(tree.keys())) return self.__class__( ((key, self.get(key)) for key in rkeys) )
[ "def", "symmetric_difference", "(", "self", ",", "tree", ")", ":", "thiskeys", "=", "frozenset", "(", "self", ".", "keys", "(", ")", ")", "rkeys", "=", "thiskeys", ".", "symmetric_difference", "(", "frozenset", "(", "tree", ".", "keys", "(", ")", ")", ...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/bintrees/bintrees/treemixin.py#L616-L622
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/propgrid.py
python
PropertyGridManager.SelectProperty
(*args, **kwargs)
return _propgrid.PropertyGridManager_SelectProperty(*args, **kwargs)
SelectProperty(self, PGPropArg id, bool focus=False) -> bool
SelectProperty(self, PGPropArg id, bool focus=False) -> bool
[ "SelectProperty", "(", "self", "PGPropArg", "id", "bool", "focus", "=", "False", ")", "-", ">", "bool" ]
def SelectProperty(*args, **kwargs): """SelectProperty(self, PGPropArg id, bool focus=False) -> bool""" return _propgrid.PropertyGridManager_SelectProperty(*args, **kwargs)
[ "def", "SelectProperty", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PropertyGridManager_SelectProperty", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L3562-L3564
p4lang/behavioral-model
81ce0163f0770c6b9d6056a28ce2e0cc035bb6e9
tools/cpplint.py
python
CheckVlogArguments
(filename, clean_lines, linenum, error)
Checks that VLOG() is only used for defining a logging level. For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and VLOG(FATAL) are not. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Checks that VLOG() is only used for defining a logging level.
[ "Checks", "that", "VLOG", "()", "is", "only", "used", "for", "defining", "a", "logging", "level", "." ]
def CheckVlogArguments(filename, clean_lines, linenum, error): """Checks that VLOG() is only used for defining a logging level. For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and VLOG(FATAL) are not. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] if Search(r'\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)', line): error(filename, linenum, 'runtime/vlog', 5, 'VLOG() should be used with numeric verbosity level. ' 'Use LOG() if you want symbolic severity levels.')
[ "def", "CheckVlogArguments", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "Search", "(", "r'\\bVLOG\\((INFO|ERROR|WARNING|DFATAL|FATAL)\\)'", ",", "line", ")", ...
https://github.com/p4lang/behavioral-model/blob/81ce0163f0770c6b9d6056a28ce2e0cc035bb6e9/tools/cpplint.py#L2636-L2652
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/robotsim.py
python
GeneralizedIKSolver.solve
(self)
return _robotsim.GeneralizedIKSolver_solve(self)
solve(GeneralizedIKSolver self) -> PyObject * Tries to find a configuration that satifies all simultaneous objectives up to the desired tolerance. Returns: res,iters (pair of bool, int): res indicates whether x converged, and iters is the number of iterations used.
solve(GeneralizedIKSolver self) -> PyObject *
[ "solve", "(", "GeneralizedIKSolver", "self", ")", "-", ">", "PyObject", "*" ]
def solve(self): """ solve(GeneralizedIKSolver self) -> PyObject * Tries to find a configuration that satifies all simultaneous objectives up to the desired tolerance. Returns: res,iters (pair of bool, int): res indicates whether x converged, and iters is the number of iterations used. """ return _robotsim.GeneralizedIKSolver_solve(self)
[ "def", "solve", "(", "self", ")", ":", "return", "_robotsim", ".", "GeneralizedIKSolver_solve", "(", "self", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/robotsim.py#L7074-L7087
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/feature_column/feature_column.py
python
_SharedEmbeddingColumn._get_dense_tensor_internal
(self, inputs, weight_collections=None, trainable=None)
Private method that follows the signature of _get_dense_tensor.
Private method that follows the signature of _get_dense_tensor.
[ "Private", "method", "that", "follows", "the", "signature", "of", "_get_dense_tensor", "." ]
def _get_dense_tensor_internal(self, inputs, weight_collections=None, trainable=None): """Private method that follows the signature of _get_dense_tensor.""" # This method is called from a variable_scope with name _var_scope_name, # which is shared among all shared embeddings. Open a name_scope here, so # that the ops for different columns have distinct names. with ops.name_scope(None, default_name=self.name): # Get sparse IDs and weights. sparse_tensors = self.categorical_column._get_sparse_tensors( # pylint: disable=protected-access inputs, weight_collections=weight_collections, trainable=trainable) sparse_ids = sparse_tensors.id_tensor sparse_weights = sparse_tensors.weight_tensor embedding_shape = (self.categorical_column._num_buckets, self.dimension) # pylint: disable=protected-access shared_embedding_collection = ops.get_collection( self.shared_embedding_collection_name) if shared_embedding_collection: if len(shared_embedding_collection) > 1: raise ValueError( 'Collection {} can only contain one variable. ' 'Suggested fix A: Choose a unique name for this collection. ' 'Suggested fix B: Do not add any variables to this collection. ' 'The feature_column library already adds a variable under the ' 'hood.'.format(shared_embedding_collection)) embedding_weights = shared_embedding_collection[0] if embedding_weights.get_shape() != embedding_shape: raise ValueError( 'Shared embedding collection {} contains variable {} of ' 'unexpected shape {}. Expected shape is {}. ' 'Suggested fix A: Choose a unique name for this collection. ' 'Suggested fix B: Do not add any variables to this collection. ' 'The feature_column library already adds a variable under the ' 'hood.'.format(self.shared_embedding_collection_name, embedding_weights.name, embedding_weights.get_shape(), embedding_shape)) else: embedding_weights = variable_scope.get_variable( name='embedding_weights', shape=embedding_shape, dtype=dtypes.float32, initializer=self.initializer, trainable=self.trainable and trainable, collections=weight_collections) ops.add_to_collection(self.shared_embedding_collection_name, embedding_weights) if self.ckpt_to_load_from is not None: to_restore = embedding_weights if isinstance(to_restore, variables.PartitionedVariable): to_restore = to_restore._get_variable_list() # pylint: disable=protected-access checkpoint_utils.init_from_checkpoint(self.ckpt_to_load_from, { self.tensor_name_in_ckpt: to_restore }) sparse_id_rank = tensor_shape.dimension_value( sparse_ids.dense_shape.get_shape()[0]) embedding_lookup_sparse = embedding_ops.safe_embedding_lookup_sparse if (not self.use_safe_embedding_lookup and sparse_id_rank is not None and sparse_id_rank <= 2): embedding_lookup_sparse = embedding_ops.embedding_lookup_sparse_v2 # Return embedding lookup result. return embedding_lookup_sparse( embedding_weights, sparse_ids, sparse_weights, combiner=self.combiner, name='%s_weights' % self.name, max_norm=self.max_norm)
[ "def", "_get_dense_tensor_internal", "(", "self", ",", "inputs", ",", "weight_collections", "=", "None", ",", "trainable", "=", "None", ")", ":", "# This method is called from a variable_scope with name _var_scope_name,", "# which is shared among all shared embeddings. Open a name_...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/feature_column/feature_column.py#L2640-L2708
pyne/pyne
0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3
pyne/cccc.py
python
Isotxs._read_file_ID
(self)
Reads the file identification block. This block is always present in the ISOTXS format and contains a label and file version number.
Reads the file identification block. This block is always present in the ISOTXS format and contains a label and file version number.
[ "Reads", "the", "file", "identification", "block", ".", "This", "block", "is", "always", "present", "in", "the", "ISOTXS", "format", "and", "contains", "a", "label", "and", "file", "version", "number", "." ]
def _read_file_ID(self): """Reads the file identification block. This block is always present in the ISOTXS format and contains a label and file version number. """ # Get first record from file fileID = self.get_fortran_record() # Read data from file identification record self.label = fileID.get_string(24)[0] self.fileVersion = fileID.get_int()[0]
[ "def", "_read_file_ID", "(", "self", ")", ":", "# Get first record from file", "fileID", "=", "self", ".", "get_fortran_record", "(", ")", "# Read data from file identification record", "self", ".", "label", "=", "fileID", ".", "get_string", "(", "24", ")", "[", "...
https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/pyne/cccc.py#L121-L131
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py
python
xmlDoc.isID
(self, elem, attr)
return ret
Determine whether an attribute is of type ID. In case we have DTD(s) then this is done if DTD loading has been requested. In the case of HTML documents parsed with the HTML parser, then ID detection is done systematically.
Determine whether an attribute is of type ID. In case we have DTD(s) then this is done if DTD loading has been requested. In the case of HTML documents parsed with the HTML parser, then ID detection is done systematically.
[ "Determine", "whether", "an", "attribute", "is", "of", "type", "ID", ".", "In", "case", "we", "have", "DTD", "(", "s", ")", "then", "this", "is", "done", "if", "DTD", "loading", "has", "been", "requested", ".", "In", "the", "case", "of", "HTML", "doc...
def isID(self, elem, attr): """Determine whether an attribute is of type ID. In case we have DTD(s) then this is done if DTD loading has been requested. In the case of HTML documents parsed with the HTML parser, then ID detection is done systematically. """ if elem is None: elem__o = None else: elem__o = elem._o if attr is None: attr__o = None else: attr__o = attr._o ret = libxml2mod.xmlIsID(self._o, elem__o, attr__o) return ret
[ "def", "isID", "(", "self", ",", "elem", ",", "attr", ")", ":", "if", "elem", "is", "None", ":", "elem__o", "=", "None", "else", ":", "elem__o", "=", "elem", ".", "_o", "if", "attr", "is", "None", ":", "attr__o", "=", "None", "else", ":", "attr__...
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L3816-L3826
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py3/IPython/lib/pretty.py
python
PrettyPrinter.break_
(self)
Explicitly insert a newline into the output, maintaining correct indentation.
Explicitly insert a newline into the output, maintaining correct indentation.
[ "Explicitly", "insert", "a", "newline", "into", "the", "output", "maintaining", "correct", "indentation", "." ]
def break_(self): """ Explicitly insert a newline into the output, maintaining correct indentation. """ group = self.group_queue.deq() if group: self._break_one_group(group) self.flush() self.output.write(self.newline) self.output.write(' ' * self.indentation) self.output_width = self.indentation self.buffer_width = 0
[ "def", "break_", "(", "self", ")", ":", "group", "=", "self", ".", "group_queue", ".", "deq", "(", ")", "if", "group", ":", "self", ".", "_break_one_group", "(", "group", ")", "self", ".", "flush", "(", ")", "self", ".", "output", ".", "write", "("...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/lib/pretty.py#L250-L261
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/ndimage/filters.py
python
minimum_filter1d
(input, size, axis=-1, output=None, mode="reflect", cval=0.0, origin=0)
return return_value
Calculate a one-dimensional minimum filter along the given axis. The lines of the array along the given axis are filtered with a minimum filter of given size. Parameters ---------- %(input)s size : int length along which to calculate 1D minimum %(axis)s %(output)s %(mode)s %(cval)s %(origin)s Notes ----- This function implements the MINLIST algorithm [1]_, as described by Richard Harter [2]_, and has a guaranteed O(n) performance, `n` being the `input` length, regardless of filter size. References ---------- .. [1] http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.2777 .. [2] http://www.richardhartersworld.com/cri/2001/slidingmin.html
Calculate a one-dimensional minimum filter along the given axis.
[ "Calculate", "a", "one", "-", "dimensional", "minimum", "filter", "along", "the", "given", "axis", "." ]
def minimum_filter1d(input, size, axis=-1, output=None, mode="reflect", cval=0.0, origin=0): """Calculate a one-dimensional minimum filter along the given axis. The lines of the array along the given axis are filtered with a minimum filter of given size. Parameters ---------- %(input)s size : int length along which to calculate 1D minimum %(axis)s %(output)s %(mode)s %(cval)s %(origin)s Notes ----- This function implements the MINLIST algorithm [1]_, as described by Richard Harter [2]_, and has a guaranteed O(n) performance, `n` being the `input` length, regardless of filter size. References ---------- .. [1] http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.2777 .. [2] http://www.richardhartersworld.com/cri/2001/slidingmin.html """ input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') axis = _ni_support._check_axis(axis, input.ndim) if size < 1: raise RuntimeError('incorrect filter size') output, return_value = _ni_support._get_output(output, input) if (size // 2 + origin < 0) or (size // 2 + origin >= size): raise ValueError('invalid origin') mode = _ni_support._extend_mode_to_code(mode) _nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval, origin, 1) return return_value
[ "def", "minimum_filter1d", "(", "input", ",", "size", ",", "axis", "=", "-", "1", ",", "output", "=", "None", ",", "mode", "=", "\"reflect\"", ",", "cval", "=", "0.0", ",", "origin", "=", "0", ")", ":", "input", "=", "numpy", ".", "asarray", "(", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/ndimage/filters.py#L835-L876
physercoe/starquant
c00cad64d1de2da05081b3dc320ef264c6295e08
source/engine/strategy_engine.py
python
StrategyEngine.load_strategy_class
(self, reload: bool = False)
Load strategy class from source code.
Load strategy class from source code.
[ "Load", "strategy", "class", "from", "source", "code", "." ]
def load_strategy_class(self, reload: bool = False): """ Load strategy class from source code. """ # app_path = Path(__file__).parent.parent # path1 = app_path.joinpath("cta_strategy", "strategies") # self.load_strategy_class_from_folder( # path1, "vnpy.app.cta_strategy.strategies") path2 = Path.cwd().joinpath("mystrategy") self.load_strategy_class_from_folder(path2, "", reload)
[ "def", "load_strategy_class", "(", "self", ",", "reload", ":", "bool", "=", "False", ")", ":", "# app_path = Path(__file__).parent.parent", "# path1 = app_path.joinpath(\"cta_strategy\", \"strategies\")", "# self.load_strategy_class_from_folder(", "# path1, \"vnpy.app.cta_strategy....
https://github.com/physercoe/starquant/blob/c00cad64d1de2da05081b3dc320ef264c6295e08/source/engine/strategy_engine.py#L618-L628
llvm/llvm-project
ffa6262cb4e2a335d26416fad39a581b4f98c5f4
lldb/third_party/Python/module/pexpect-4.6/pexpect/pxssh.py
python
pxssh.try_read_prompt
(self, timeout_multiplier)
return prompt
This facilitates using communication timeouts to perform synchronization as quickly as possible, while supporting high latency connections with a tunable worst case performance. Fast connections should be read almost immediately. Worst case performance for this method is timeout_multiplier * 3 seconds.
This facilitates using communication timeouts to perform synchronization as quickly as possible, while supporting high latency connections with a tunable worst case performance. Fast connections should be read almost immediately. Worst case performance for this method is timeout_multiplier * 3 seconds.
[ "This", "facilitates", "using", "communication", "timeouts", "to", "perform", "synchronization", "as", "quickly", "as", "possible", "while", "supporting", "high", "latency", "connections", "with", "a", "tunable", "worst", "case", "performance", ".", "Fast", "connect...
def try_read_prompt(self, timeout_multiplier): '''This facilitates using communication timeouts to perform synchronization as quickly as possible, while supporting high latency connections with a tunable worst case performance. Fast connections should be read almost immediately. Worst case performance for this method is timeout_multiplier * 3 seconds. ''' # maximum time allowed to read the first response first_char_timeout = timeout_multiplier * 0.5 # maximum time allowed between subsequent characters inter_char_timeout = timeout_multiplier * 0.1 # maximum time for reading the entire prompt total_timeout = timeout_multiplier * 3.0 prompt = self.string_type() begin = time.time() expired = 0.0 timeout = first_char_timeout while expired < total_timeout: try: prompt += self.read_nonblocking(size=1, timeout=timeout) expired = time.time() - begin # updated total time expired timeout = inter_char_timeout except TIMEOUT: break return prompt
[ "def", "try_read_prompt", "(", "self", ",", "timeout_multiplier", ")", ":", "# maximum time allowed to read the first response", "first_char_timeout", "=", "timeout_multiplier", "*", "0.5", "# maximum time allowed between subsequent characters", "inter_char_timeout", "=", "timeout_...
https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/lldb/third_party/Python/module/pexpect-4.6/pexpect/pxssh.py#L183-L213
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/tools/cpplint.py
python
_AddFilters
(filters)
Adds more filter overrides. Unlike _SetFilters, this function does not reset the current list of filters available. Args: filters: A string of comma-separated filters (eg "whitespace/indent"). Each filter should start with + or -; else we die.
Adds more filter overrides.
[ "Adds", "more", "filter", "overrides", "." ]
def _AddFilters(filters): """Adds more filter overrides. Unlike _SetFilters, this function does not reset the current list of filters available. Args: filters: A string of comma-separated filters (eg "whitespace/indent"). Each filter should start with + or -; else we die. """ _cpplint_state.AddFilters(filters)
[ "def", "_AddFilters", "(", "filters", ")", ":", "_cpplint_state", ".", "AddFilters", "(", "filters", ")" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/cpplint.py#L1479-L1489
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_windows.py
python
SplashScreen.GetTimeout
(*args, **kwargs)
return _windows_.SplashScreen_GetTimeout(*args, **kwargs)
GetTimeout(self) -> int
GetTimeout(self) -> int
[ "GetTimeout", "(", "self", ")", "-", ">", "int" ]
def GetTimeout(*args, **kwargs): """GetTimeout(self) -> int""" return _windows_.SplashScreen_GetTimeout(*args, **kwargs)
[ "def", "GetTimeout", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "SplashScreen_GetTimeout", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L1153-L1155
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/libdeps/libdeps/graph.py
python
LibdepsGraph.get_deptype
(self, deptype)
return self._deptypes[deptype]
Convert graphs deptypes from json string to dict, and return requested value.
Convert graphs deptypes from json string to dict, and return requested value.
[ "Convert", "graphs", "deptypes", "from", "json", "string", "to", "dict", "and", "return", "requested", "value", "." ]
def get_deptype(self, deptype): """Convert graphs deptypes from json string to dict, and return requested value.""" if not self._deptypes: self._deptypes = json.loads(self.graph.get('deptypes', "{}")) if self.graph['graph_schema_version'] == 1: # get and set the legacy values self._deptypes['Global'] = self._deptypes.get('Global', 0) self._deptypes['Public'] = self._deptypes.get('Public', 1) self._deptypes['Private'] = self._deptypes.get('Private', 2) self._deptypes['Interface'] = self._deptypes.get('Interface', 3) return self._deptypes[deptype]
[ "def", "get_deptype", "(", "self", ",", "deptype", ")", ":", "if", "not", "self", ".", "_deptypes", ":", "self", ".", "_deptypes", "=", "json", ".", "loads", "(", "self", ".", "graph", ".", "get", "(", "'deptypes'", ",", "\"{}\"", ")", ")", "if", "...
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/libdeps/libdeps/graph.py#L108-L120
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPML_DIGEST_VALUES.fromBytes
(buffer)
return TpmBuffer(buffer).createObj(TPML_DIGEST_VALUES)
Returns new TPML_DIGEST_VALUES object constructed from its marshaled representation in the given byte buffer
Returns new TPML_DIGEST_VALUES object constructed from its marshaled representation in the given byte buffer
[ "Returns", "new", "TPML_DIGEST_VALUES", "object", "constructed", "from", "its", "marshaled", "representation", "in", "the", "given", "byte", "buffer" ]
def fromBytes(buffer): """ Returns new TPML_DIGEST_VALUES object constructed from its marshaled representation in the given byte buffer """ return TpmBuffer(buffer).createObj(TPML_DIGEST_VALUES)
[ "def", "fromBytes", "(", "buffer", ")", ":", "return", "TpmBuffer", "(", "buffer", ")", ".", "createObj", "(", "TPML_DIGEST_VALUES", ")" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L4655-L4659
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
src/pybind/mgr/dashboard/controllers/_version.py
python
APIVersion.from_mime_type
(cls, mime_type: str)
return cls.from_string(cls.__MIME_TYPE_REGEX.match(mime_type).group(1))
>>> APIVersion.from_mime_type('application/vnd.ceph.api.v1.0+json') APIVersion(major=1, minor=0)
>>> APIVersion.from_mime_type('application/vnd.ceph.api.v1.0+json') APIVersion(major=1, minor=0)
[ ">>>", "APIVersion", ".", "from_mime_type", "(", "application", "/", "vnd", ".", "ceph", ".", "api", ".", "v1", ".", "0", "+", "json", ")", "APIVersion", "(", "major", "=", "1", "minor", "=", "0", ")" ]
def from_mime_type(cls, mime_type: str) -> 'APIVersion': """ >>> APIVersion.from_mime_type('application/vnd.ceph.api.v1.0+json') APIVersion(major=1, minor=0) """ return cls.from_string(cls.__MIME_TYPE_REGEX.match(mime_type).group(1))
[ "def", "from_mime_type", "(", "cls", ",", "mime_type", ":", "str", ")", "->", "'APIVersion'", ":", "return", "cls", ".", "from_string", "(", "cls", ".", "__MIME_TYPE_REGEX", ".", "match", "(", "mime_type", ")", ".", "group", "(", "1", ")", ")" ]
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/pybind/mgr/dashboard/controllers/_version.py#L35-L41
borglab/gtsam
a5bee157efce6a0563704bce6a5d188c29817f39
wrap/gtwrap/pybind_wrapper.py
python
PybindWrapper.wrap_variable
(self, namespace, module_var, variable, prefix='\n' + ' ' * 8)
return '{prefix}{module_var}.attr("{variable_name}") = {namespace}{variable_value};'.format( prefix=prefix, module_var=module_var, variable_name=variable.name, namespace=namespace, variable_value=variable_value)
Wrap a variable that's not part of a class (i.e. global)
Wrap a variable that's not part of a class (i.e. global)
[ "Wrap", "a", "variable", "that", "s", "not", "part", "of", "a", "class", "(", "i", ".", "e", ".", "global", ")" ]
def wrap_variable(self, namespace, module_var, variable, prefix='\n' + ' ' * 8): """ Wrap a variable that's not part of a class (i.e. global) """ variable_value = "" if variable.default is None: variable_value = variable.name else: variable_value = variable.default return '{prefix}{module_var}.attr("{variable_name}") = {namespace}{variable_value};'.format( prefix=prefix, module_var=module_var, variable_name=variable.name, namespace=namespace, variable_value=variable_value)
[ "def", "wrap_variable", "(", "self", ",", "namespace", ",", "module_var", ",", "variable", ",", "prefix", "=", "'\\n'", "+", "' '", "*", "8", ")", ":", "variable_value", "=", "\"\"", "if", "variable", ".", "default", "is", "None", ":", "variable_value", ...
https://github.com/borglab/gtsam/blob/a5bee157efce6a0563704bce6a5d188c29817f39/wrap/gtwrap/pybind_wrapper.py#L268-L287
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py
python
NinjaWriter.WriteLinkForArch
(self, ninja_file, spec, config_name, config, link_deps, arch=None)
return linked_binary
Write out a link step. Fills out target.binary.
Write out a link step. Fills out target.binary.
[ "Write", "out", "a", "link", "step", ".", "Fills", "out", "target", ".", "binary", "." ]
def WriteLinkForArch(self, ninja_file, spec, config_name, config, link_deps, arch=None): """Write out a link step. Fills out target.binary. """ command = { 'executable': 'link', 'loadable_module': 'solink_module', 'shared_library': 'solink', }[spec['type']] command_suffix = '' implicit_deps = set() solibs = set() order_deps = set() if 'dependencies' in spec: # Two kinds of dependencies: # - Linkable dependencies (like a .a or a .so): add them to the link line. # - Non-linkable dependencies (like a rule that generates a file # and writes a stamp file): add them to implicit_deps extra_link_deps = set() for dep in spec['dependencies']: target = self.target_outputs.get(dep) if not target: continue linkable = target.Linkable() if linkable: new_deps = [] if (self.flavor == 'win' and target.component_objs and self.msvs_settings.IsUseLibraryDependencyInputs(config_name)): new_deps = target.component_objs if target.compile_deps: order_deps.add(target.compile_deps) elif self.flavor == 'win' and target.import_lib: new_deps = [target.import_lib] elif target.UsesToc(self.flavor): solibs.add(target.binary) implicit_deps.add(target.binary + '.TOC') else: new_deps = [target.binary] for new_dep in new_deps: if new_dep not in extra_link_deps: extra_link_deps.add(new_dep) link_deps.append(new_dep) final_output = target.FinalOutput() if not linkable or final_output != target.binary: implicit_deps.add(final_output) extra_bindings = [] if self.uses_cpp and self.flavor != 'win': extra_bindings.append(('ld', '$ldxx')) output = self.ComputeOutput(spec, arch) if arch is None and not self.is_mac_bundle: self.AppendPostbuildVariable(extra_bindings, spec, output, output) is_executable = spec['type'] == 'executable' # The ldflags config key is not used on mac or win. On those platforms # linker flags are set via xcode_settings and msvs_settings, respectively. env_ldflags = os.environ.get('LDFLAGS', '').split() if self.flavor == 'mac': ldflags = self.xcode_settings.GetLdflags(config_name, self.ExpandSpecial(generator_default_variables['PRODUCT_DIR']), self.GypPathToNinja, arch) ldflags = env_ldflags + ldflags elif self.flavor == 'win': manifest_base_name = self.GypPathToUniqueOutput( self.ComputeOutputFileName(spec)) ldflags, intermediate_manifest, manifest_files = \ self.msvs_settings.GetLdflags(config_name, self.GypPathToNinja, self.ExpandSpecial, manifest_base_name, output, is_executable, self.toplevel_build) ldflags = env_ldflags + ldflags self.WriteVariableList(ninja_file, 'manifests', manifest_files) implicit_deps = implicit_deps.union(manifest_files) if intermediate_manifest: self.WriteVariableList( ninja_file, 'intermediatemanifest', [intermediate_manifest]) command_suffix = _GetWinLinkRuleNameSuffix( self.msvs_settings.IsEmbedManifest(config_name)) def_file = self.msvs_settings.GetDefFile(self.GypPathToNinja) if def_file: implicit_deps.add(def_file) else: # Respect environment variables related to build, but target-specific # flags can still override them. ldflags = env_ldflags + config.get('ldflags', []) if is_executable and len(solibs): rpath = 'lib/' if self.toolset != 'target': rpath += self.toolset ldflags.append(r'-Wl,-rpath=\$$ORIGIN/%s' % rpath) ldflags.append('-Wl,-rpath-link=%s' % rpath) self.WriteVariableList(ninja_file, 'ldflags', map(self.ExpandSpecial, ldflags)) library_dirs = config.get('library_dirs', []) if self.flavor == 'win': library_dirs = [self.msvs_settings.ConvertVSMacros(l, config_name) for l in library_dirs] library_dirs = ['/LIBPATH:' + QuoteShellArgument(self.GypPathToNinja(l), self.flavor) for l in library_dirs] else: library_dirs = [QuoteShellArgument('-L' + self.GypPathToNinja(l), self.flavor) for l in library_dirs] libraries = gyp.common.uniquer(map(self.ExpandSpecial, spec.get('libraries', []))) if self.flavor == 'mac': libraries = self.xcode_settings.AdjustLibraries(libraries, config_name) elif self.flavor == 'win': libraries = self.msvs_settings.AdjustLibraries(libraries) self.WriteVariableList(ninja_file, 'libs', library_dirs + libraries) linked_binary = output if command in ('solink', 'solink_module'): extra_bindings.append(('soname', os.path.split(output)[1])) extra_bindings.append(('lib', gyp.common.EncodePOSIXShellArgument(output))) if self.flavor != 'win': link_file_list = output if self.is_mac_bundle: # 'Dependency Framework.framework/Versions/A/Dependency Framework' -> # 'Dependency Framework.framework.rsp' link_file_list = self.xcode_settings.GetWrapperName() if arch: link_file_list += '.' + arch link_file_list += '.rsp' # If an rspfile contains spaces, ninja surrounds the filename with # quotes around it and then passes it to open(), creating a file with # quotes in its name (and when looking for the rsp file, the name # makes it through bash which strips the quotes) :-/ link_file_list = link_file_list.replace(' ', '_') extra_bindings.append( ('link_file_list', gyp.common.EncodePOSIXShellArgument(link_file_list))) if self.flavor == 'win': extra_bindings.append(('binary', output)) if ('/NOENTRY' not in ldflags and not self.msvs_settings.GetNoImportLibrary(config_name)): self.target.import_lib = output + '.lib' extra_bindings.append(('implibflag', '/IMPLIB:%s' % self.target.import_lib)) pdbname = self.msvs_settings.GetPDBName( config_name, self.ExpandSpecial, output + '.pdb') output = [output, self.target.import_lib] if pdbname: output.append(pdbname) elif not self.is_mac_bundle: output = [output, output + '.TOC'] else: command = command + '_notoc' elif self.flavor == 'win': extra_bindings.append(('binary', output)) pdbname = self.msvs_settings.GetPDBName( config_name, self.ExpandSpecial, output + '.pdb') if pdbname: output = [output, pdbname] if len(solibs): extra_bindings.append(('solibs', gyp.common.EncodePOSIXShellList(solibs))) ninja_file.build(output, command + command_suffix, link_deps, implicit=list(implicit_deps), order_only=list(order_deps), variables=extra_bindings) return linked_binary
[ "def", "WriteLinkForArch", "(", "self", ",", "ninja_file", ",", "spec", ",", "config_name", ",", "config", ",", "link_deps", ",", "arch", "=", "None", ")", ":", "command", "=", "{", "'executable'", ":", "'link'", ",", "'loadable_module'", ":", "'solink_modul...
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py#L1088-L1261
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/protorpc/protorpc/messages.py
python
_MessageClass.__new__
(cls, name, bases, dct)
return _DefinitionClass.__new__(cls, name, bases, dct)
Create new Message class instance. The __new__ method of the _MessageClass type is overridden so as to allow the translation of Field instances to slots.
Create new Message class instance.
[ "Create", "new", "Message", "class", "instance", "." ]
def __new__(cls, name, bases, dct): """Create new Message class instance. The __new__ method of the _MessageClass type is overridden so as to allow the translation of Field instances to slots. """ by_number = {} by_name = {} variant_map = {} if bases != (object,): # Can only define one level of sub-classes below Message. if bases != (Message,): raise MessageDefinitionError( 'Message types may only inherit from Message') enums = [] messages = [] # Must not use iteritems because this loop will change the state of dct. for key, field in dct.items(): if key in _RESERVED_ATTRIBUTE_NAMES: continue if isinstance(field, type) and issubclass(field, Enum): enums.append(key) continue if (isinstance(field, type) and issubclass(field, Message) and field is not Message): messages.append(key) continue # Reject anything that is not a field. if type(field) is Field or not isinstance(field, Field): raise MessageDefinitionError( 'May only use fields in message definitions. Found: %s = %s' % (key, field)) if field.number in by_number: raise DuplicateNumberError( 'Field with number %d declared more than once in %s' % (field.number, name)) field.name = key # Place in name and number maps. by_name[key] = field by_number[field.number] = field # Add enums if any exist. if enums: dct['__enums__'] = sorted(enums) # Add messages if any exist. if messages: dct['__messages__'] = sorted(messages) dct['_Message__by_number'] = by_number dct['_Message__by_name'] = by_name return _DefinitionClass.__new__(cls, name, bases, dct)
[ "def", "__new__", "(", "cls", ",", "name", ",", "bases", ",", "dct", ")", ":", "by_number", "=", "{", "}", "by_name", "=", "{", "}", "variant_map", "=", "{", "}", "if", "bases", "!=", "(", "object", ",", ")", ":", "# Can only define one level of sub-cl...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/protorpc/protorpc/messages.py#L606-L669
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/numpy/files/numpy/lib/npyio.py
python
seek_gzip_factory
(f)
return f
Use this factory to produce the class so that we can do a lazy import on gzip.
Use this factory to produce the class so that we can do a lazy import on gzip.
[ "Use", "this", "factory", "to", "produce", "the", "class", "so", "that", "we", "can", "do", "a", "lazy", "import", "on", "gzip", "." ]
def seek_gzip_factory(f): """Use this factory to produce the class so that we can do a lazy import on gzip. """ import gzip class GzipFile(gzip.GzipFile): def seek(self, offset, whence=0): # figure out new position (we can only seek forwards) if whence == 1: offset = self.offset + offset if whence not in [0, 1]: raise IOError, "Illegal argument" if offset < self.offset: # for negative seek, rewind and do positive seek self.rewind() count = offset - self.offset for i in range(count // 1024): self.read(1024) self.read(count % 1024) def tell(self): return self.offset if isinstance(f, str): f = GzipFile(f) elif isinstance(f, gzip.GzipFile): # cast to our GzipFile if its already a gzip.GzipFile try: name = f.name except AttributeError: # Backward compatibility for <= 2.5 name = f.filename mode = f.mode f = GzipFile(fileobj=f.fileobj, filename=name) f.mode = mode return f
[ "def", "seek_gzip_factory", "(", "f", ")", ":", "import", "gzip", "class", "GzipFile", "(", "gzip", ".", "GzipFile", ")", ":", "def", "seek", "(", "self", ",", "offset", ",", "whence", "=", "0", ")", ":", "# figure out new position (we can only seek forwards)"...
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/lib/npyio.py#L32-L76
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/analyzer.py
python
_WasGypIncludeFileModified
(params, files)
return False
Returns true if one of the files in |files| is in the set of included files.
Returns true if one of the files in |files| is in the set of included files.
[ "Returns", "true", "if", "one", "of", "the", "files", "in", "|files|", "is", "in", "the", "set", "of", "included", "files", "." ]
def _WasGypIncludeFileModified(params, files): """Returns true if one of the files in |files| is in the set of included files.""" if params['options'].includes: for include in params['options'].includes: if _ToGypPath(os.path.normpath(include)) in files: print('Include file modified, assuming all changed', include) return True return False
[ "def", "_WasGypIncludeFileModified", "(", "params", ",", "files", ")", ":", "if", "params", "[", "'options'", "]", ".", "includes", ":", "for", "include", "in", "params", "[", "'options'", "]", ".", "includes", ":", "if", "_ToGypPath", "(", "os", ".", "p...
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/analyzer.py#L555-L563
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/third_party/altgraph/altgraph/Graph.py
python
Graph.out_edges
(self, node)
return None
Returns a list of the outgoing edges
Returns a list of the outgoing edges
[ "Returns", "a", "list", "of", "the", "outgoing", "edges" ]
def out_edges(self, node): """ Returns a list of the outgoing edges """ try: return list(self.nodes[node][1]) except KeyError: raise GraphError('Invalid node %s' % node) return None
[ "def", "out_edges", "(", "self", ",", "node", ")", ":", "try", ":", "return", "list", "(", "self", ".", "nodes", "[", "node", "]", "[", "1", "]", ")", "except", "KeyError", ":", "raise", "GraphError", "(", "'Invalid node %s'", "%", "node", ")", "retu...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/altgraph/altgraph/Graph.py#L337-L346
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/dataview.py
python
DataViewTreeStore.SetItemText
(*args, **kwargs)
return _dataview.DataViewTreeStore_SetItemText(*args, **kwargs)
SetItemText(self, DataViewItem item, String text)
SetItemText(self, DataViewItem item, String text)
[ "SetItemText", "(", "self", "DataViewItem", "item", "String", "text", ")" ]
def SetItemText(*args, **kwargs): """SetItemText(self, DataViewItem item, String text)""" return _dataview.DataViewTreeStore_SetItemText(*args, **kwargs)
[ "def", "SetItemText", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_dataview", ".", "DataViewTreeStore_SetItemText", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/dataview.py#L2411-L2413
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/clustering_ops.py
python
_InitializeClustersOpFactory.__init__
(self, inputs, num_clusters, initial_clusters, distance_metric, random_seed, kmeans_plus_plus_num_retries, kmc2_chain_length, cluster_centers, cluster_centers_updated, cluster_centers_initialized)
Creates an op factory. Args: inputs: See KMeans constructor. num_clusters: An integer Tensor providing the number of clusters. initial_clusters: See KMeans constructor. distance_metric: See KMeans constructor. random_seed: See KMeans constructor. kmeans_plus_plus_num_retries: See KMeans constructor. kmc2_chain_length: See KMeans constructor. cluster_centers: The TF variable holding the initial centers. It may already contain some centers when the op is executed. cluster_centers_updated: A second TF variable to hold a copy of the initial centers, used for full-batch mode. In mini-batch mode, cluster_centers_updated is the same variable as cluster_centers. cluster_centers_initialized: A boolean TF variable that will be set to true when all the initial centers have been chosen.
Creates an op factory.
[ "Creates", "an", "op", "factory", "." ]
def __init__(self, inputs, num_clusters, initial_clusters, distance_metric, random_seed, kmeans_plus_plus_num_retries, kmc2_chain_length, cluster_centers, cluster_centers_updated, cluster_centers_initialized): """Creates an op factory. Args: inputs: See KMeans constructor. num_clusters: An integer Tensor providing the number of clusters. initial_clusters: See KMeans constructor. distance_metric: See KMeans constructor. random_seed: See KMeans constructor. kmeans_plus_plus_num_retries: See KMeans constructor. kmc2_chain_length: See KMeans constructor. cluster_centers: The TF variable holding the initial centers. It may already contain some centers when the op is executed. cluster_centers_updated: A second TF variable to hold a copy of the initial centers, used for full-batch mode. In mini-batch mode, cluster_centers_updated is the same variable as cluster_centers. cluster_centers_initialized: A boolean TF variable that will be set to true when all the initial centers have been chosen. """ # All of these instance variables are constants. self._inputs = inputs self._num_clusters = num_clusters self._initial_clusters = initial_clusters self._distance_metric = distance_metric self._seed = random_seed self._kmeans_plus_plus_num_retries = kmeans_plus_plus_num_retries self._kmc2_chain_length = kmc2_chain_length self._cluster_centers = cluster_centers self._cluster_centers_updated = cluster_centers_updated self._cluster_centers_initialized = cluster_centers_initialized self._num_selected = array_ops.shape(self._cluster_centers)[0] self._num_remaining = self._num_clusters - self._num_selected self._num_data = math_ops.add_n( [array_ops.shape(i)[0] for i in self._inputs])
[ "def", "__init__", "(", "self", ",", "inputs", ",", "num_clusters", ",", "initial_clusters", ",", "distance_metric", ",", "random_seed", ",", "kmeans_plus_plus_num_retries", ",", "kmc2_chain_length", ",", "cluster_centers", ",", "cluster_centers_updated", ",", "cluster_...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/clustering_ops.py#L561-L598
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/numpy/utils_const.py
python
_check_shape
(shape)
return shape
check the shape param to match the numpy style
check the shape param to match the numpy style
[ "check", "the", "shape", "param", "to", "match", "the", "numpy", "style" ]
def _check_shape(shape): """check the shape param to match the numpy style""" if not isinstance(shape, (int, tuple, list, typing.Tuple, typing.List)): raise TypeError(f"only int, tuple and list are allowed for shape, but got {type(shape)}") if isinstance(shape, int): shape = (shape,) if isinstance(shape, (list, typing.List)): shape = tuple(shape) for s in shape: if not isinstance(s, int): raise TypeError("each entry in shape should be int.") if s < 0: raise ValueError("each entry in shape should no less than 0.") return shape
[ "def", "_check_shape", "(", "shape", ")", ":", "if", "not", "isinstance", "(", "shape", ",", "(", "int", ",", "tuple", ",", "list", ",", "typing", ".", "Tuple", ",", "typing", ".", "List", ")", ")", ":", "raise", "TypeError", "(", "f\"only int, tuple a...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/numpy/utils_const.py#L37-L50
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/gettext.py
python
c2py
(plural)
Gets a C expression as used in PO files for plural forms and returns a Python function that implements an equivalent expression.
Gets a C expression as used in PO files for plural forms and returns a Python function that implements an equivalent expression.
[ "Gets", "a", "C", "expression", "as", "used", "in", "PO", "files", "for", "plural", "forms", "and", "returns", "a", "Python", "function", "that", "implements", "an", "equivalent", "expression", "." ]
def c2py(plural): """Gets a C expression as used in PO files for plural forms and returns a Python function that implements an equivalent expression. """ if len(plural) > 1000: raise ValueError('plural form expression is too long') try: result, nexttok = _parse(_tokenize(plural)) if nexttok: raise _error(nexttok) depth = 0 for c in result: if c == '(': depth += 1 if depth > 20: # Python compiler limit is about 90. # The most complex example has 2. raise ValueError('plural form expression is too complex') elif c == ')': depth -= 1 ns = {'_as_int': _as_int} exec('''if True: def func(n): if not isinstance(n, int): n = _as_int(n) return int(%s) ''' % result, ns) return ns['func'] except RecursionError: # Recursion error can be raised in _parse() or exec(). raise ValueError('plural form expression is too complex')
[ "def", "c2py", "(", "plural", ")", ":", "if", "len", "(", "plural", ")", ">", "1000", ":", "raise", "ValueError", "(", "'plural form expression is too long'", ")", "try", ":", "result", ",", "nexttok", "=", "_parse", "(", "_tokenize", "(", "plural", ")", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/gettext.py#L175-L208
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/robotsim.py
python
Simulator.enableContactFeedbackAll
(self)
return _robotsim.Simulator_enableContactFeedbackAll(self)
enableContactFeedbackAll(Simulator self) Call this to enable contact feedback between all pairs of objects. Contact feedback has a small overhead so you may want to do this selectively.
enableContactFeedbackAll(Simulator self)
[ "enableContactFeedbackAll", "(", "Simulator", "self", ")" ]
def enableContactFeedbackAll(self): """ enableContactFeedbackAll(Simulator self) Call this to enable contact feedback between all pairs of objects. Contact feedback has a small overhead so you may want to do this selectively. """ return _robotsim.Simulator_enableContactFeedbackAll(self)
[ "def", "enableContactFeedbackAll", "(", "self", ")", ":", "return", "_robotsim", ".", "Simulator_enableContactFeedbackAll", "(", "self", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/robotsim.py#L8368-L8378
PixarAnimationStudios/USD
faed18ce62c8736b02413635b584a2f637156bad
pxr/usdImaging/usdviewq/selectionDataModel.py
python
SelectionDataModel.removeUnpopulatedPrims
(self)
Remove all prim paths whose corresponding prims do not currently exist on the stage. It is the application's responsibility to call this method while it is processing changes to the stage, *before* querying this object for selections. Because this is a synchronization operation rather than an expression of GUI state change, it does *not* perform any notifications/signals, which could cause reentrant application change processing.
Remove all prim paths whose corresponding prims do not currently exist on the stage. It is the application's responsibility to call this method while it is processing changes to the stage, *before* querying this object for selections. Because this is a synchronization operation rather than an expression of GUI state change, it does *not* perform any notifications/signals, which could cause reentrant application change processing.
[ "Remove", "all", "prim", "paths", "whose", "corresponding", "prims", "do", "not", "currently", "exist", "on", "the", "stage", ".", "It", "is", "the", "application", "s", "responsibility", "to", "call", "this", "method", "while", "it", "is", "processing", "ch...
def removeUnpopulatedPrims(self): """Remove all prim paths whose corresponding prims do not currently exist on the stage. It is the application's responsibility to call this method while it is processing changes to the stage, *before* querying this object for selections. Because this is a synchronization operation rather than an expression of GUI state change, it does *not* perform any notifications/signals, which could cause reentrant application change processing.""" stage = self._rootDataModel.stage self._primSelection.removeMatchingPaths(lambda path: not stage.GetPrimAtPath(path)) self._primSelectionChanged(emitSelChangedSignal=False)
[ "def", "removeUnpopulatedPrims", "(", "self", ")", ":", "stage", "=", "self", ".", "_rootDataModel", ".", "stage", "self", ".", "_primSelection", ".", "removeMatchingPaths", "(", "lambda", "path", ":", "not", "stage", ".", "GetPrimAtPath", "(", "path", ")", ...
https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/pxr/usdImaging/usdviewq/selectionDataModel.py#L781-L791
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/contrib/learn/python/learn/learn_io/data_feeder.py
python
DataFeeder.__init__
( self, x, y, n_classes, batch_size=None, shuffle=True, random_state=None, epochs=None)
Initializes a DataFeeder instance. Args: x: Feature Nd numpy matrix of shape `[n_samples, n_features, ...]`. y: Target vector, either floats for regression or class id for classification. If matrix, will consider as a sequence of targets. Can be `None` for unsupervised setting. n_classes: Number of classes, 0 and 1 are considered regression, `None` will pass through the input labels without one-hot conversion. batch_size: Mini-batch size to accumulate. shuffle: Whether to shuffle `x`. random_state: Numpy `RandomState` object to reproduce sampling. epochs: Number of times to iterate over input data before raising `StopIteration` exception. Attributes: x: Input features. y: Input target. n_classes: Number of classes (if `None`, pass through indices without one-hot conversion). batch_size: Mini-batch size to accumulate. input_shape: Shape of the input. output_shape: Shape of the output. input_dtype: DType of input. output_dtype: DType of output.
Initializes a DataFeeder instance.
[ "Initializes", "a", "DataFeeder", "instance", "." ]
def __init__( self, x, y, n_classes, batch_size=None, shuffle=True, random_state=None, epochs=None): """Initializes a DataFeeder instance. Args: x: Feature Nd numpy matrix of shape `[n_samples, n_features, ...]`. y: Target vector, either floats for regression or class id for classification. If matrix, will consider as a sequence of targets. Can be `None` for unsupervised setting. n_classes: Number of classes, 0 and 1 are considered regression, `None` will pass through the input labels without one-hot conversion. batch_size: Mini-batch size to accumulate. shuffle: Whether to shuffle `x`. random_state: Numpy `RandomState` object to reproduce sampling. epochs: Number of times to iterate over input data before raising `StopIteration` exception. Attributes: x: Input features. y: Input target. n_classes: Number of classes (if `None`, pass through indices without one-hot conversion). batch_size: Mini-batch size to accumulate. input_shape: Shape of the input. output_shape: Shape of the output. input_dtype: DType of input. output_dtype: DType of output. """ self._x = check_array(x, dtype=x.dtype) # self.n_classes is None means we're passing in raw target indices. y_dtype = ( np.int64 if n_classes is not None and n_classes > 1 else np.float32) if n_classes is not None: self._y = (None if y is None else check_array(y, dtype=y_dtype)) elif isinstance(y, list): self._y = np.array(y) else: self._y = y self.n_classes = n_classes self.max_epochs = epochs self.input_shape, self.output_shape, self._batch_size = _get_in_out_shape( self._x.shape, None if self._y is None else self._y.shape, n_classes, batch_size) # Input dtype matches dtype of x. self._input_dtype = _check_dtype(self._x.dtype) # self.n_classes is None means we're passing in raw target indices if n_classes is not None or self._y is None: self._output_dtype = np.float32 else: self._output_dtype = _check_dtype(self._y.dtype) self._shuffle = shuffle self.random_state = np.random.RandomState( 42) if random_state is None else random_state if self._shuffle: self.indices = self.random_state.permutation(self._x.shape[0]) else: self.indices = np.array(range(self._x.shape[0])) self.offset = 0 self.epoch = 0 self._epoch_placeholder = None
[ "def", "__init__", "(", "self", ",", "x", ",", "y", ",", "n_classes", ",", "batch_size", "=", "None", ",", "shuffle", "=", "True", ",", "random_state", "=", "None", ",", "epochs", "=", "None", ")", ":", "self", ".", "_x", "=", "check_array", "(", "...
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/learn/python/learn/learn_io/data_feeder.py#L220-L280
ApolloAuto/apollo
463fb82f9e979d02dcb25044e60931293ab2dba0
tools/bootstrap.py
python
get_native_cuda_compute_capabilities
(environ_cp)
return output
Get native cuda compute capabilities. Args: environ_cp: copy of the os.environ. Returns: string of native cuda compute capabilities, separated by comma.
Get native cuda compute capabilities.
[ "Get", "native", "cuda", "compute", "capabilities", "." ]
def get_native_cuda_compute_capabilities(environ_cp): """Get native cuda compute capabilities. Args: environ_cp: copy of the os.environ. Returns: string of native cuda compute capabilities, separated by comma. """ device_query_bin = os.path.join( environ_cp.get('CUDA_TOOLKIT_PATH'), 'extras/demo_suite/deviceQuery') if os.path.isfile(device_query_bin) and os.access(device_query_bin, os.X_OK): try: output = run_shell(device_query_bin).split('\n') pattern = re.compile('[0-9]*\\.[0-9]*') output = [pattern.search(x) for x in output if 'Capability' in x] output = ','.join(x.group() for x in output if x is not None) except subprocess.CalledProcessError: output = '' else: output = '' return output
[ "def", "get_native_cuda_compute_capabilities", "(", "environ_cp", ")", ":", "device_query_bin", "=", "os", ".", "path", ".", "join", "(", "environ_cp", ".", "get", "(", "'CUDA_TOOLKIT_PATH'", ")", ",", "'extras/demo_suite/deviceQuery'", ")", "if", "os", ".", "path...
https://github.com/ApolloAuto/apollo/blob/463fb82f9e979d02dcb25044e60931293ab2dba0/tools/bootstrap.py#L708-L730
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/autopep8.py
python
normalize_line_endings
(lines, newline)
return [line.rstrip('\n\r') + newline for line in lines]
Return fixed line endings. All lines will be modified to use the most common line ending.
Return fixed line endings.
[ "Return", "fixed", "line", "endings", "." ]
def normalize_line_endings(lines, newline): """Return fixed line endings. All lines will be modified to use the most common line ending. """ return [line.rstrip('\n\r') + newline for line in lines]
[ "def", "normalize_line_endings", "(", "lines", ",", "newline", ")", ":", "return", "[", "line", ".", "rstrip", "(", "'\\n\\r'", ")", "+", "newline", "for", "line", "in", "lines", "]" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/autopep8.py#L2786-L2792
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/mhlib.py
python
Folder.getlast
(self)
return self.last
Return the last message number.
Return the last message number.
[ "Return", "the", "last", "message", "number", "." ]
def getlast(self): """Return the last message number.""" if not hasattr(self, 'last'): self.listmessages() # Set self.last return self.last
[ "def", "getlast", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'last'", ")", ":", "self", ".", "listmessages", "(", ")", "# Set self.last", "return", "self", ".", "last" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/mhlib.py#L649-L653
apple/swift-llbuild
25333daca549aed69004c9b3d4c6b69d3f32d1d0
bindings/python/llbuild.py
python
BuildEngine.task_discovered_dependency
(self, task, key)
\ task_discovered_dependency(task, key) Inform the engine of an input dependency that was discovered by the task during its execution, a la compiler generated dependency files. This call may only be made after a task has received all of its inputs; inputs discovered prior to that point should simply be requested as normal input dependencies. Such a dependency is not used to provide additional input to the task, rather it is a way for the task to report an additional input which should be considered the next time the rule is evaluated. The expected use case for a discovered dependency is is when a processing task cannot predict all of its inputs prior to being run, but can presume that any unknown inputs already exist. In such cases, the task can go ahead and run and can report the all of the discovered inputs as it executes. Once the task is complete, these inputs will be recorded as being dependencies of the task so that it will be recomputed when any of the inputs change. It is legal to call this method from any thread, but the caller is responsible for ensuring that it is never called concurrently for the same task.
\ task_discovered_dependency(task, key)
[ "\\", "task_discovered_dependency", "(", "task", "key", ")" ]
def task_discovered_dependency(self, task, key): """\ task_discovered_dependency(task, key) Inform the engine of an input dependency that was discovered by the task during its execution, a la compiler generated dependency files. This call may only be made after a task has received all of its inputs; inputs discovered prior to that point should simply be requested as normal input dependencies. Such a dependency is not used to provide additional input to the task, rather it is a way for the task to report an additional input which should be considered the next time the rule is evaluated. The expected use case for a discovered dependency is is when a processing task cannot predict all of its inputs prior to being run, but can presume that any unknown inputs already exist. In such cases, the task can go ahead and run and can report the all of the discovered inputs as it executes. Once the task is complete, these inputs will be recorded as being dependencies of the task so that it will be recomputed when any of the inputs change. It is legal to call this method from any thread, but the caller is responsible for ensuring that it is never called concurrently for the same task.""" key = _Data(key) libllbuild.llb_buildengine_task_must_follow( self._engine, task._task, key.key)
[ "def", "task_discovered_dependency", "(", "self", ",", "task", ",", "key", ")", ":", "key", "=", "_Data", "(", "key", ")", "libllbuild", ".", "llb_buildengine_task_must_follow", "(", "self", ".", "_engine", ",", "task", ".", "_task", ",", "key", ".", "key"...
https://github.com/apple/swift-llbuild/blob/25333daca549aed69004c9b3d4c6b69d3f32d1d0/bindings/python/llbuild.py#L274-L300
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
samples/pySketch/pySketch.py
python
DrawingFrame._buildStoredState
(self)
return info
Remember the current state of the document, to allow for undo. We make a copy of the document's contents, so that we can return to the previous contents if the user does something and then wants to undo the operation. Returns an object representing the current document state.
Remember the current state of the document, to allow for undo.
[ "Remember", "the", "current", "state", "of", "the", "document", "to", "allow", "for", "undo", "." ]
def _buildStoredState(self): """ Remember the current state of the document, to allow for undo. We make a copy of the document's contents, so that we can return to the previous contents if the user does something and then wants to undo the operation. Returns an object representing the current document state. """ savedContents = [] for obj in self.contents: savedContents.append([obj.__class__, obj.getData()]) savedSelection = [] for i in range(len(self.contents)): if self.contents[i] in self.selection: savedSelection.append(i) info = {"contents" : savedContents, "selection" : savedSelection} return info
[ "def", "_buildStoredState", "(", "self", ")", ":", "savedContents", "=", "[", "]", "for", "obj", "in", "self", ".", "contents", ":", "savedContents", ".", "append", "(", "[", "obj", ".", "__class__", ",", "obj", ".", "getData", "(", ")", "]", ")", "s...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/samples/pySketch/pySketch.py#L1402-L1423
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_misc.py
python
DateTime.GetCentury
(*args, **kwargs)
return _misc_.DateTime_GetCentury(*args, **kwargs)
GetCentury(int year=Inv_Year) -> int
GetCentury(int year=Inv_Year) -> int
[ "GetCentury", "(", "int", "year", "=", "Inv_Year", ")", "-", ">", "int" ]
def GetCentury(*args, **kwargs): """GetCentury(int year=Inv_Year) -> int""" return _misc_.DateTime_GetCentury(*args, **kwargs)
[ "def", "GetCentury", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "DateTime_GetCentury", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L3707-L3709
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/generateParkingAreaRerouters.py
python
get_options
(cmd_args=None)
return options
Argument Parser.
Argument Parser.
[ "Argument", "Parser", "." ]
def get_options(cmd_args=None): """ Argument Parser. """ parser = sumolib.options.ArgumentParser( prog='generateParkingAreaRerouters.py', usage='%(prog)s [options]', description='Generate parking area rerouters from the parking area definition.') parser.add_argument( '-a', '--parking-areas', type=str, dest='parking_area_definition', required=True, help='SUMO parkingArea definition.') parser.add_argument( '-n', '--sumo-net', type=str, dest='sumo_net_definition', required=True, help='SUMO network definition.') parser.add_argument( '--max-number-alternatives', type=int, dest='num_alternatives', default=10, help='Rerouter: max number of alternatives.') parser.add_argument( '--max-distance-alternatives', type=float, dest='dist_alternatives', default=500.0, help='Rerouter: max distance for the alternatives.') parser.add_argument( '--min-capacity-visibility-true', type=int, dest='capacity_threshold', default=25, help='Rerouter: parking capacity for the visibility threshold.') parser.add_argument( '--max-distance-visibility-true', type=float, dest='dist_threshold', default=250.0, help='Rerouter: parking distance for the visibility threshold.') parser.add_argument( '--opposite-visible', action="store_true", dest='opposite_visible', default=False, help="ParkingArea on the opposite side of the road is always visible") parser.add_argument( '--prefer-visible', action="store_true", dest='prefer_visible', default=False, help="ParkingAreas which are visible are preferentially") parser.add_argument( '--min-capacity', type=int, dest='min_capacity', default=1, help='Do no reroute to parkingAreas with less than min-capacity') parser.add_argument( '--distribute', dest='distribute', help='Distribute alternatives by distance according to the given weights. "3,1"' + 'means that 75 percent of the alternatives are below the median distance of all' + 'alternatives in range and 25 percent are above the median distance') parser.add_argument( '--visible-ids', dest='visible_ids', default="", help='set list of parkingArea ids as always visible') parser.add_argument( '--processes', type=int, dest='processes', default=1, help='Number of processes spawned to compute the distance between parking areas.') parser.add_argument( '-o', '--output', type=str, dest='output', required=True, help='Name for the output file.') parser.add_argument( '--tqdm', dest='with_tqdm', action='store_true', help='Enable TQDM feature.') parser.set_defaults(with_tqdm=False) options = parser.parse_args(cmd_args) if options.distribute is not None: dists = options.distribute.split(',') for x in dists: try: x = float(x) except ValueError: print("Value '%s' in option --distribute must be numeric" % x, file=sys.stderr) sys.exit() options.visible_ids = set(options.visible_ids.split(',')) return options
[ "def", "get_options", "(", "cmd_args", "=", "None", ")", ":", "parser", "=", "sumolib", ".", "options", ".", "ArgumentParser", "(", "prog", "=", "'generateParkingAreaRerouters.py'", ",", "usage", "=", "'%(prog)s [options]'", ",", "description", "=", "'Generate par...
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/generateParkingAreaRerouters.py#L45-L110
MegEngine/MegEngine
ce9ad07a27ec909fb8db4dd67943d24ba98fb93a
imperative/python/megengine/functional/nn.py
python
pixel_shuffle
(inp: Tensor, upscale_factor: int)
return outvar
Rearranges elements in a tensor of shape (*, C x r^2, H, W) to a tensor of shape (*, C, H x r, W x r), where r is an upscale factor, where * is zero or more batch dimensions. :param inp: input tensor. :param upscale_factor: upscale factor of pixel_shuffle. :return: output tensor.
Rearranges elements in a tensor of shape (*, C x r^2, H, W) to a tensor of shape (*, C, H x r, W x r), where r is an upscale factor, where * is zero or more batch dimensions.
[ "Rearranges", "elements", "in", "a", "tensor", "of", "shape", "(", "*", "C", "x", "r^2", "H", "W", ")", "to", "a", "tensor", "of", "shape", "(", "*", "C", "H", "x", "r", "W", "x", "r", ")", "where", "r", "is", "an", "upscale", "factor", "where"...
def pixel_shuffle(inp: Tensor, upscale_factor: int) -> Tensor: """ Rearranges elements in a tensor of shape (*, C x r^2, H, W) to a tensor of shape (*, C, H x r, W x r), where r is an upscale factor, where * is zero or more batch dimensions. :param inp: input tensor. :param upscale_factor: upscale factor of pixel_shuffle. :return: output tensor. """ assert upscale_factor > 0, "upscale_factor should larger than 0" assert inp.ndim >= 3, "the input dimension of pixel_shuffle should be larger than 3" assert ( inp.shape[-3] % (upscale_factor ** 2) == 0 ), "the -3 dimension should be divided by (upscale_factor ** 2)" _device = inp.device _dtype = inp.dtype shape_ori = inp.shape high_dim = shape_ori[:-3] square = upscale_factor ** 2 n = 1 for item in high_dim: n *= item shape_0 = ( n, int(shape_ori[-3] / square), upscale_factor, upscale_factor, shape_ori[-2], shape_ori[-1], ) shape_1 = ( *high_dim, int(shape_ori[-3] / square), shape_ori[-2] * upscale_factor, shape_ori[-1] * upscale_factor, ) dim_order = (0, 1, 4, 2, 5, 3) layerPixelShuffle = _get_layerPixelShuffle(_device, _dtype, dim_order) shape_0 = convert_single_value(shape_0, device=inp.device) shape_1 = convert_single_value(shape_1, device=inp.device) outvar, *_ = apply(layerPixelShuffle(), inp, shape_0, shape_1) return outvar
[ "def", "pixel_shuffle", "(", "inp", ":", "Tensor", ",", "upscale_factor", ":", "int", ")", "->", "Tensor", ":", "assert", "upscale_factor", ">", "0", ",", "\"upscale_factor should larger than 0\"", "assert", "inp", ".", "ndim", ">=", "3", ",", "\"the input dimen...
https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/functional/nn.py#L1812-L1859
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/richtext.py
python
RichTextPlainText.Copy
(*args, **kwargs)
return _richtext.RichTextPlainText_Copy(*args, **kwargs)
Copy(self, RichTextPlainText obj)
Copy(self, RichTextPlainText obj)
[ "Copy", "(", "self", "RichTextPlainText", "obj", ")" ]
def Copy(*args, **kwargs): """Copy(self, RichTextPlainText obj)""" return _richtext.RichTextPlainText_Copy(*args, **kwargs)
[ "def", "Copy", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextPlainText_Copy", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L2104-L2106
albertz/openlierox
d316c14a8eb57848ef56e9bfa7b23a56f694a51b
tools/DedicatedServerVideo/gdata/tlslite/TLSRecordLayer.py
python
TLSRecordLayer.getpeername
(self)
return self.sock.getpeername()
Return the remote address to which the socket is connected (socket emulation).
Return the remote address to which the socket is connected (socket emulation).
[ "Return", "the", "remote", "address", "to", "which", "the", "socket", "is", "connected", "(", "socket", "emulation", ")", "." ]
def getpeername(self): """Return the remote address to which the socket is connected (socket emulation).""" return self.sock.getpeername()
[ "def", "getpeername", "(", "self", ")", ":", "return", "self", ".", "sock", ".", "getpeername", "(", ")" ]
https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/tlslite/TLSRecordLayer.py#L407-L410
priyankchheda/algorithms
c361aa9071573fa9966d5b02d05e524815abcf2b
graph/library/graph.py
python
Graph.__init__
(self, graph_dict=None)
initialize a graph object if no dictionary or none is given, an empty dictionary will be used :param graph_dict: initial graph setup
initialize a graph object if no dictionary or none is given, an empty dictionary will be used :param graph_dict: initial graph setup
[ "initialize", "a", "graph", "object", "if", "no", "dictionary", "or", "none", "is", "given", "an", "empty", "dictionary", "will", "be", "used", ":", "param", "graph_dict", ":", "initial", "graph", "setup" ]
def __init__(self, graph_dict=None): """ initialize a graph object if no dictionary or none is given, an empty dictionary will be used :param graph_dict: initial graph setup """ if not graph_dict: graph_dict = {} self._graph_dict = graph_dict
[ "def", "__init__", "(", "self", ",", "graph_dict", "=", "None", ")", ":", "if", "not", "graph_dict", ":", "graph_dict", "=", "{", "}", "self", ".", "_graph_dict", "=", "graph_dict" ]
https://github.com/priyankchheda/algorithms/blob/c361aa9071573fa9966d5b02d05e524815abcf2b/graph/library/graph.py#L7-L15
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/series.py
python
Series.argsort
(self, axis=0, kind='quicksort', order=None)
Overrides ndarray.argsort. Argsorts the value, omitting NA/null values, and places the result in the same locations as the non-NA values. Parameters ---------- axis : int Has no effect but is accepted for compatibility with numpy. kind : {'mergesort', 'quicksort', 'heapsort'}, default 'quicksort' Choice of sorting algorithm. See np.sort for more information. 'mergesort' is the only stable algorithm order : None Has no effect but is accepted for compatibility with numpy. Returns ------- argsorted : Series, with -1 indicated where nan values are present See Also -------- numpy.ndarray.argsort
Overrides ndarray.argsort. Argsorts the value, omitting NA/null values, and places the result in the same locations as the non-NA values.
[ "Overrides", "ndarray", ".", "argsort", ".", "Argsorts", "the", "value", "omitting", "NA", "/", "null", "values", "and", "places", "the", "result", "in", "the", "same", "locations", "as", "the", "non", "-", "NA", "values", "." ]
def argsort(self, axis=0, kind='quicksort', order=None): """ Overrides ndarray.argsort. Argsorts the value, omitting NA/null values, and places the result in the same locations as the non-NA values. Parameters ---------- axis : int Has no effect but is accepted for compatibility with numpy. kind : {'mergesort', 'quicksort', 'heapsort'}, default 'quicksort' Choice of sorting algorithm. See np.sort for more information. 'mergesort' is the only stable algorithm order : None Has no effect but is accepted for compatibility with numpy. Returns ------- argsorted : Series, with -1 indicated where nan values are present See Also -------- numpy.ndarray.argsort """ values = self._values mask = isna(values) if mask.any(): result = Series(-1, index=self.index, name=self.name, dtype='int64') notmask = ~mask result[notmask] = np.argsort(values[notmask], kind=kind) return self._constructor(result, index=self.index).__finalize__(self) else: return self._constructor( np.argsort(values, kind=kind), index=self.index, dtype='int64').__finalize__(self)
[ "def", "argsort", "(", "self", ",", "axis", "=", "0", ",", "kind", "=", "'quicksort'", ",", "order", "=", "None", ")", ":", "values", "=", "self", ".", "_values", "mask", "=", "isna", "(", "values", ")", "if", "mask", ".", "any", "(", ")", ":", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/series.py#L2988-L3024
apiaryio/snowcrash
b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3
tools/gyp/pylib/gyp/MSVSVersion.py
python
VisualStudioVersion.UsesVcxproj
(self)
return self.uses_vcxproj
Returns true if this version uses a vcxproj file.
Returns true if this version uses a vcxproj file.
[ "Returns", "true", "if", "this", "version", "uses", "a", "vcxproj", "file", "." ]
def UsesVcxproj(self): """Returns true if this version uses a vcxproj file.""" return self.uses_vcxproj
[ "def", "UsesVcxproj", "(", "self", ")", ":", "return", "self", ".", "uses_vcxproj" ]
https://github.com/apiaryio/snowcrash/blob/b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3/tools/gyp/pylib/gyp/MSVSVersion.py#L50-L52
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/requests/requests/cookies.py
python
RequestsCookieJar.list_paths
(self)
return paths
Utility method to list all the paths in the jar.
Utility method to list all the paths in the jar.
[ "Utility", "method", "to", "list", "all", "the", "paths", "in", "the", "jar", "." ]
def list_paths(self): """Utility method to list all the paths in the jar.""" paths = [] for cookie in iter(self): if cookie.path not in paths: paths.append(cookie.path) return paths
[ "def", "list_paths", "(", "self", ")", ":", "paths", "=", "[", "]", "for", "cookie", "in", "iter", "(", "self", ")", ":", "if", "cookie", ".", "path", "not", "in", "paths", ":", "paths", ".", "append", "(", "cookie", ".", "path", ")", "return", "...
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/requests/requests/cookies.py#L243-L249
apache/kudu
90895ce76590f10730ad7aac3613b69d89ff5422
src/kudu/scripts/assign-location.py
python
get_location
(fpath, rule, uid, relaxed)
return location
Return location for the specified identifier 'uid'. To do that, use the specified location mapping rules and the information stored in the sequencer's state file. * Obtain advisory lock for the state file (using additional .lock file) * If the sequencer's state file exists: 1. Open the state file in read-only mode. 2. Read the information from the state file and search for location assigned to the server with the specified identifier. a. If already assigned location found: -- Return the location. b. If location assigned to the identifier is not found: -- Use current sequence number 'seq' to assign next location by calling LocationAssignmentRule.get_location(seq). -- Add the newly generated location assignment into the sequencer's state. -- Increment the sequence number. -- Reopen the state file for writing (if file exists) -- Rewrite the file with the new state of the sequencer. -- Return the newly assigned location. * If the sequencer's state file does not exist: 1. Set sequence number 'seq' to 0. 2. Use current sequence number 'seq' to assign next location by calling LocationAssignmentRule.get_location(seq). 3. Update the sequencer's state accordingly. 3. Rewrite the file with the new state of the sequencer. 4. Return the newly assigned location.
Return location for the specified identifier 'uid'. To do that, use the specified location mapping rules and the information stored in the sequencer's state file.
[ "Return", "location", "for", "the", "specified", "identifier", "uid", ".", "To", "do", "that", "use", "the", "specified", "location", "mapping", "rules", "and", "the", "information", "stored", "in", "the", "sequencer", "s", "state", "file", "." ]
def get_location(fpath, rule, uid, relaxed): """ Return location for the specified identifier 'uid'. To do that, use the specified location mapping rules and the information stored in the sequencer's state file. * Obtain advisory lock for the state file (using additional .lock file) * If the sequencer's state file exists: 1. Open the state file in read-only mode. 2. Read the information from the state file and search for location assigned to the server with the specified identifier. a. If already assigned location found: -- Return the location. b. If location assigned to the identifier is not found: -- Use current sequence number 'seq' to assign next location by calling LocationAssignmentRule.get_location(seq). -- Add the newly generated location assignment into the sequencer's state. -- Increment the sequence number. -- Reopen the state file for writing (if file exists) -- Rewrite the file with the new state of the sequencer. -- Return the newly assigned location. * If the sequencer's state file does not exist: 1. Set sequence number 'seq' to 0. 2. Use current sequence number 'seq' to assign next location by calling LocationAssignmentRule.get_location(seq). 3. Update the sequencer's state accordingly. 3. Rewrite the file with the new state of the sequencer. 4. Return the newly assigned location. """ lock_file = acquire_advisory_lock(fpath) state_file = None try: state_file = open(fpath) except IOError as e: if e.errno != errno.ENOENT: raise new_assignment = False if state_file is None: seq = 0 state = {} state['seq'] = seq state['mapping_rules'] = rule.location_mapping_rules state['mappings'] = {} mappings = state['mappings'] new_assignment = True else: # If the file exists, it must have proper content. state = json.load(state_file) seq = state.get('seq') mapping_rules = state.get('mapping_rules') # Make sure the stored mapping rule corresponds to the specified in args. rule_stored = json.dumps(mapping_rules) rule_specified = json.dumps(rule.location_mapping_rules) if rule_stored != rule_specified: raise Exception('stored and specified mapping rules mismatch: ' '{0} vs {1}'.format(rule_stored, rule_specified)) mappings = state['mappings'] location = mappings.get(uid, None) if location is None: seq += 1 state['seq'] = seq new_assignment = True if not new_assignment: return location if not relaxed and rule.total_count != 0 and rule.total_count <= seq: raise Exception('too many unique identifiers ({0}) to assign next location ' 'to {1} using mapping rules {2}. State: {3}'.format( seq + 1, uid, rule.location_mapping_rules, json.dumps(state))) if relaxed and rule.total_count <= seq: return "" # Get next location and add the { uid, location} binding into the mappings. location = rule.get_location(seq) mappings[uid] = location # Rewrite the file with the updated state information. if state_file is not None: state_file.close() state_file = open(fpath, 'w+') json.dump(state, state_file) state_file.close() lock_file.close() return location
[ "def", "get_location", "(", "fpath", ",", "rule", ",", "uid", ",", "relaxed", ")", ":", "lock_file", "=", "acquire_advisory_lock", "(", "fpath", ")", "state_file", "=", "None", "try", ":", "state_file", "=", "open", "(", "fpath", ")", "except", "IOError", ...
https://github.com/apache/kudu/blob/90895ce76590f10730ad7aac3613b69d89ff5422/src/kudu/scripts/assign-location.py#L126-L213
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/asyncio/base_events.py
python
BaseEventLoop.sendfile
(self, transport, file, offset=0, count=None, *, fallback=True)
return await self._sendfile_fallback(transport, file, offset, count)
Send a file to transport. Return the total number of bytes which were sent. The method uses high-performance os.sendfile if available. file must be a regular file object opened in binary mode. offset tells from where to start reading the file. If specified, count is the total number of bytes to transmit as opposed to sending the file until EOF is reached. File position is updated on return or also in case of error in which case file.tell() can be used to figure out the number of bytes which were sent. fallback set to True makes asyncio to manually read and send the file when the platform does not support the sendfile syscall (e.g. Windows or SSL socket on Unix). Raise SendfileNotAvailableError if the system does not support sendfile syscall and fallback is False.
Send a file to transport.
[ "Send", "a", "file", "to", "transport", "." ]
async def sendfile(self, transport, file, offset=0, count=None, *, fallback=True): """Send a file to transport. Return the total number of bytes which were sent. The method uses high-performance os.sendfile if available. file must be a regular file object opened in binary mode. offset tells from where to start reading the file. If specified, count is the total number of bytes to transmit as opposed to sending the file until EOF is reached. File position is updated on return or also in case of error in which case file.tell() can be used to figure out the number of bytes which were sent. fallback set to True makes asyncio to manually read and send the file when the platform does not support the sendfile syscall (e.g. Windows or SSL socket on Unix). Raise SendfileNotAvailableError if the system does not support sendfile syscall and fallback is False. """ if transport.is_closing(): raise RuntimeError("Transport is closing") mode = getattr(transport, '_sendfile_compatible', constants._SendfileMode.UNSUPPORTED) if mode is constants._SendfileMode.UNSUPPORTED: raise RuntimeError( f"sendfile is not supported for transport {transport!r}") if mode is constants._SendfileMode.TRY_NATIVE: try: return await self._sendfile_native(transport, file, offset, count) except events.SendfileNotAvailableError as exc: if not fallback: raise if not fallback: raise RuntimeError( f"fallback is disabled and native sendfile is not " f"supported for transport {transport!r}") return await self._sendfile_fallback(transport, file, offset, count)
[ "async", "def", "sendfile", "(", "self", ",", "transport", ",", "file", ",", "offset", "=", "0", ",", "count", "=", "None", ",", "*", ",", "fallback", "=", "True", ")", ":", "if", "transport", ".", "is_closing", "(", ")", ":", "raise", "RuntimeError"...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/asyncio/base_events.py#L1024-L1069
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
third_party/protobuf/python/google/protobuf/internal/containers.py
python
RepeatedScalarFieldContainer.append
(self, value)
Appends an item to the list. Similar to list.append().
Appends an item to the list. Similar to list.append().
[ "Appends", "an", "item", "to", "the", "list", ".", "Similar", "to", "list", ".", "append", "()", "." ]
def append(self, value): """Appends an item to the list. Similar to list.append().""" self._type_checker.CheckValue(value) self._values.append(value) if not self._message_listener.dirty: self._message_listener.Modified()
[ "def", "append", "(", "self", ",", "value", ")", ":", "self", ".", "_type_checker", ".", "CheckValue", "(", "value", ")", "self", ".", "_values", ".", "append", "(", "value", ")", "if", "not", "self", ".", "_message_listener", ".", "dirty", ":", "self"...
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/protobuf/python/google/protobuf/internal/containers.py#L104-L109
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/dataview.py
python
DataViewTreeStore.InsertContainer
(*args, **kwargs)
return _dataview.DataViewTreeStore_InsertContainer(*args, **kwargs)
InsertContainer(self, DataViewItem parent, DataViewItem previous, String text, Icon icon=wxNullIcon, Icon expanded=wxNullIcon, wxClientData data=None) -> DataViewItem
InsertContainer(self, DataViewItem parent, DataViewItem previous, String text, Icon icon=wxNullIcon, Icon expanded=wxNullIcon, wxClientData data=None) -> DataViewItem
[ "InsertContainer", "(", "self", "DataViewItem", "parent", "DataViewItem", "previous", "String", "text", "Icon", "icon", "=", "wxNullIcon", "Icon", "expanded", "=", "wxNullIcon", "wxClientData", "data", "=", "None", ")", "-", ">", "DataViewItem" ]
def InsertContainer(*args, **kwargs): """ InsertContainer(self, DataViewItem parent, DataViewItem previous, String text, Icon icon=wxNullIcon, Icon expanded=wxNullIcon, wxClientData data=None) -> DataViewItem """ return _dataview.DataViewTreeStore_InsertContainer(*args, **kwargs)
[ "def", "InsertContainer", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_dataview", ".", "DataViewTreeStore_InsertContainer", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/dataview.py#L2396-L2402