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
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/contrib/distributions/python/ops/exponential.py
python
Exponential.__init__
( self, lam, validate_args=True, allow_nan_stats=False, name="Exponential")
Construct Exponential distribution with parameter `lam`. Args: lam: Floating point tensor, the rate of the distribution(s). `lam` must contain only positive values. validate_args: Whether to assert that `lam > 0`, and that `x > 0` in the methods `prob(x)` and `log_prob(x)`. If `validate_args` is `False` and the inputs are invalid, correct behavior is not guaranteed. allow_nan_stats: Boolean, default `False`. If `False`, raise an exception if a statistic (e.g. mean/mode/etc...) is undefined for any batch member. If `True`, batch members with valid parameters leading to undefined statistics will return NaN for this statistic. name: The name to prepend to all ops created by this distribution.
Construct Exponential distribution with parameter `lam`.
[ "Construct", "Exponential", "distribution", "with", "parameter", "lam", "." ]
def __init__( self, lam, validate_args=True, allow_nan_stats=False, name="Exponential"): """Construct Exponential distribution with parameter `lam`. Args: lam: Floating point tensor, the rate of the distribution(s). `lam` must contain only positive values. validate_args: Whether to assert that `lam > 0`, and that `x > 0` in the methods `prob(x)` and `log_prob(x)`. If `validate_args` is `False` and the inputs are invalid, correct behavior is not guaranteed. allow_nan_stats: Boolean, default `False`. If `False`, raise an exception if a statistic (e.g. mean/mode/etc...) is undefined for any batch member. If `True`, batch members with valid parameters leading to undefined statistics will return NaN for this statistic. name: The name to prepend to all ops created by this distribution. """ # Even though all statistics of are defined for valid inputs, this is not # true in the parent class "Gamma." Therefore, passing # allow_nan_stats=False # through to the parent class results in unnecessary asserts. with ops.op_scope([lam], name): lam = ops.convert_to_tensor(lam) self._lam = lam super(Exponential, self).__init__( alpha=constant_op.constant(1.0, dtype=lam.dtype), beta=lam, allow_nan_stats=allow_nan_stats, validate_args=validate_args)
[ "def", "__init__", "(", "self", ",", "lam", ",", "validate_args", "=", "True", ",", "allow_nan_stats", "=", "False", ",", "name", "=", "\"Exponential\"", ")", ":", "# Even though all statistics of are defined for valid inputs, this is not", "# true in the parent class \"Gamma.\" Therefore, passing", "# allow_nan_stats=False", "# through to the parent class results in unnecessary asserts.", "with", "ops", ".", "op_scope", "(", "[", "lam", "]", ",", "name", ")", ":", "lam", "=", "ops", ".", "convert_to_tensor", "(", "lam", ")", "self", ".", "_lam", "=", "lam", "super", "(", "Exponential", ",", "self", ")", ".", "__init__", "(", "alpha", "=", "constant_op", ".", "constant", "(", "1.0", ",", "dtype", "=", "lam", ".", "dtype", ")", ",", "beta", "=", "lam", ",", "allow_nan_stats", "=", "allow_nan_stats", ",", "validate_args", "=", "validate_args", ")" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/exponential.py#L44-L71
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/preprocessing/label.py
python
MultiLabelBinarizer.fit_transform
(self, y)
return yt
Fit the label sets binarizer and transform the given label sets Parameters ---------- y : iterable of iterables A set of labels (any orderable and hashable object) for each sample. If the `classes` parameter is set, `y` will not be iterated. Returns ------- y_indicator : array or CSR matrix, shape (n_samples, n_classes) A matrix such that `y_indicator[i, j] = 1` iff `classes_[j]` is in `y[i]`, and 0 otherwise.
Fit the label sets binarizer and transform the given label sets
[ "Fit", "the", "label", "sets", "binarizer", "and", "transform", "the", "given", "label", "sets" ]
def fit_transform(self, y): """Fit the label sets binarizer and transform the given label sets Parameters ---------- y : iterable of iterables A set of labels (any orderable and hashable object) for each sample. If the `classes` parameter is set, `y` will not be iterated. Returns ------- y_indicator : array or CSR matrix, shape (n_samples, n_classes) A matrix such that `y_indicator[i, j] = 1` iff `classes_[j]` is in `y[i]`, and 0 otherwise. """ if self.classes is not None: return self.fit(y).transform(y) # Automatically increment on new class class_mapping = defaultdict(int) class_mapping.default_factory = class_mapping.__len__ yt = self._transform(y, class_mapping) # sort classes and reorder columns tmp = sorted(class_mapping, key=class_mapping.get) # (make safe for tuples) dtype = np.int if all(isinstance(c, int) for c in tmp) else object class_mapping = np.empty(len(tmp), dtype=dtype) class_mapping[:] = tmp self.classes_, inverse = np.unique(class_mapping, return_inverse=True) # ensure yt.indices keeps its current dtype yt.indices = np.array(inverse[yt.indices], dtype=yt.indices.dtype, copy=False) if not self.sparse_output: yt = yt.toarray() return yt
[ "def", "fit_transform", "(", "self", ",", "y", ")", ":", "if", "self", ".", "classes", "is", "not", "None", ":", "return", "self", ".", "fit", "(", "y", ")", ".", "transform", "(", "y", ")", "# Automatically increment on new class", "class_mapping", "=", "defaultdict", "(", "int", ")", "class_mapping", ".", "default_factory", "=", "class_mapping", ".", "__len__", "yt", "=", "self", ".", "_transform", "(", "y", ",", "class_mapping", ")", "# sort classes and reorder columns", "tmp", "=", "sorted", "(", "class_mapping", ",", "key", "=", "class_mapping", ".", "get", ")", "# (make safe for tuples)", "dtype", "=", "np", ".", "int", "if", "all", "(", "isinstance", "(", "c", ",", "int", ")", "for", "c", "in", "tmp", ")", "else", "object", "class_mapping", "=", "np", ".", "empty", "(", "len", "(", "tmp", ")", ",", "dtype", "=", "dtype", ")", "class_mapping", "[", ":", "]", "=", "tmp", "self", ".", "classes_", ",", "inverse", "=", "np", ".", "unique", "(", "class_mapping", ",", "return_inverse", "=", "True", ")", "# ensure yt.indices keeps its current dtype", "yt", ".", "indices", "=", "np", ".", "array", "(", "inverse", "[", "yt", ".", "indices", "]", ",", "dtype", "=", "yt", ".", "indices", ".", "dtype", ",", "copy", "=", "False", ")", "if", "not", "self", ".", "sparse_output", ":", "yt", "=", "yt", ".", "toarray", "(", ")", "return", "yt" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/preprocessing/label.py#L703-L742
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/optimize/_differentialevolution.py
python
DifferentialEvolutionSolver._calculate_population_energies
(self, population)
return energies
Calculate the energies of all the population members at the same time. Parameters ---------- population : ndarray An array of parameter vectors normalised to [0, 1] using lower and upper limits. Has shape ``(np.size(population, 0), len(x))``. Returns ------- energies : ndarray An array of energies corresponding to each population member. If maxfun will be exceeded during this call, then the number of function evaluations will be reduced and energies will be right-padded with np.inf. Has shape ``(np.size(population, 0),)``
Calculate the energies of all the population members at the same time.
[ "Calculate", "the", "energies", "of", "all", "the", "population", "members", "at", "the", "same", "time", "." ]
def _calculate_population_energies(self, population): """ Calculate the energies of all the population members at the same time. Parameters ---------- population : ndarray An array of parameter vectors normalised to [0, 1] using lower and upper limits. Has shape ``(np.size(population, 0), len(x))``. Returns ------- energies : ndarray An array of energies corresponding to each population member. If maxfun will be exceeded during this call, then the number of function evaluations will be reduced and energies will be right-padded with np.inf. Has shape ``(np.size(population, 0),)`` """ num_members = np.size(population, 0) nfevs = min(num_members, self.maxfun - num_members) energies = np.full(num_members, np.inf) parameters_pop = self._scale_parameters(population) try: calc_energies = list(self._mapwrapper(self.func, parameters_pop[0:nfevs])) energies[0:nfevs] = calc_energies except (TypeError, ValueError): # wrong number of arguments for _mapwrapper # or wrong length returned from the mapper raise RuntimeError("The map-like callable must be of the" " form f(func, iterable), returning a sequence" " of numbers the same length as 'iterable'") self._nfev += nfevs return energies
[ "def", "_calculate_population_energies", "(", "self", ",", "population", ")", ":", "num_members", "=", "np", ".", "size", "(", "population", ",", "0", ")", "nfevs", "=", "min", "(", "num_members", ",", "self", ".", "maxfun", "-", "num_members", ")", "energies", "=", "np", ".", "full", "(", "num_members", ",", "np", ".", "inf", ")", "parameters_pop", "=", "self", ".", "_scale_parameters", "(", "population", ")", "try", ":", "calc_energies", "=", "list", "(", "self", ".", "_mapwrapper", "(", "self", ".", "func", ",", "parameters_pop", "[", "0", ":", "nfevs", "]", ")", ")", "energies", "[", "0", ":", "nfevs", "]", "=", "calc_energies", "except", "(", "TypeError", ",", "ValueError", ")", ":", "# wrong number of arguments for _mapwrapper", "# or wrong length returned from the mapper", "raise", "RuntimeError", "(", "\"The map-like callable must be of the\"", "\" form f(func, iterable), returning a sequence\"", "\" of numbers the same length as 'iterable'\"", ")", "self", ".", "_nfev", "+=", "nfevs", "return", "energies" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/optimize/_differentialevolution.py#L748-L786
microsoft/bond
48dfc058380d88b85daa0165ad66d15e4205601a
tools/ci-scripts/linux/image-cleanup/collector/live_images.py
python
live_tags
(repo_path: str, roots: RevListRoots)
return frozenset((ImageTag(image_name.split(':')[1]) for image_name in live_images(repo_path, roots) if matches_expected_prefix(image_name)))
Return the image tags that are referenced by .travis.yml or Linux GitHub Action workflow files in the commits specified by the given `roots`. :param repo_path: Path to the repository to inspect. :param roots: A collection of argument lists to pass to ``git rev-list`` to limit the matched commits.
Return the image tags that are referenced by .travis.yml or Linux GitHub Action workflow files in the commits specified by the given `roots`.
[ "Return", "the", "image", "tags", "that", "are", "referenced", "by", ".", "travis", ".", "yml", "or", "Linux", "GitHub", "Action", "workflow", "files", "in", "the", "commits", "specified", "by", "the", "given", "roots", "." ]
def live_tags(repo_path: str, roots: RevListRoots) -> AbstractSet[ImageTag]: """Return the image tags that are referenced by .travis.yml or Linux GitHub Action workflow files in the commits specified by the given `roots`. :param repo_path: Path to the repository to inspect. :param roots: A collection of argument lists to pass to ``git rev-list`` to limit the matched commits. """ expected_prefix = '{}.azurecr.io/{}'.format(REGISTRY_NAME, REPOSITORY_NAME) def matches_expected_prefix(image_name: ImageName) -> bool: """Check (and log) whether an image name is from the expected repository.""" if image_name.startswith(expected_prefix): return True _LOGGER.info( 'Discarding image "%s" that does not match expected prefix "%s"', image_name, expected_prefix) return False return frozenset((ImageTag(image_name.split(':')[1]) for image_name in live_images(repo_path, roots) if matches_expected_prefix(image_name)))
[ "def", "live_tags", "(", "repo_path", ":", "str", ",", "roots", ":", "RevListRoots", ")", "->", "AbstractSet", "[", "ImageTag", "]", ":", "expected_prefix", "=", "'{}.azurecr.io/{}'", ".", "format", "(", "REGISTRY_NAME", ",", "REPOSITORY_NAME", ")", "def", "matches_expected_prefix", "(", "image_name", ":", "ImageName", ")", "->", "bool", ":", "\"\"\"Check (and log) whether an image name is from the expected repository.\"\"\"", "if", "image_name", ".", "startswith", "(", "expected_prefix", ")", ":", "return", "True", "_LOGGER", ".", "info", "(", "'Discarding image \"%s\" that does not match expected prefix \"%s\"'", ",", "image_name", ",", "expected_prefix", ")", "return", "False", "return", "frozenset", "(", "(", "ImageTag", "(", "image_name", ".", "split", "(", "':'", ")", "[", "1", "]", ")", "for", "image_name", "in", "live_images", "(", "repo_path", ",", "roots", ")", "if", "matches_expected_prefix", "(", "image_name", ")", ")", ")" ]
https://github.com/microsoft/bond/blob/48dfc058380d88b85daa0165ad66d15e4205601a/tools/ci-scripts/linux/image-cleanup/collector/live_images.py#L145-L169
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/share/doc/python3.7/examples/Tools/importbench/importbench.py
python
bench
(name, cleanup=lambda: None, *, seconds=1, repeat=3)
Bench the given statement as many times as necessary until total executions take one second.
Bench the given statement as many times as necessary until total executions take one second.
[ "Bench", "the", "given", "statement", "as", "many", "times", "as", "necessary", "until", "total", "executions", "take", "one", "second", "." ]
def bench(name, cleanup=lambda: None, *, seconds=1, repeat=3): """Bench the given statement as many times as necessary until total executions take one second.""" stmt = "__import__({!r})".format(name) timer = timeit.Timer(stmt) for x in range(repeat): total_time = 0 count = 0 while total_time < seconds: try: total_time += timer.timeit(1) finally: cleanup() count += 1 else: # One execution too far if total_time > seconds: count -= 1 yield count // seconds
[ "def", "bench", "(", "name", ",", "cleanup", "=", "lambda", ":", "None", ",", "*", ",", "seconds", "=", "1", ",", "repeat", "=", "3", ")", ":", "stmt", "=", "\"__import__({!r})\"", ".", "format", "(", "name", ")", "timer", "=", "timeit", ".", "Timer", "(", "stmt", ")", "for", "x", "in", "range", "(", "repeat", ")", ":", "total_time", "=", "0", "count", "=", "0", "while", "total_time", "<", "seconds", ":", "try", ":", "total_time", "+=", "timer", ".", "timeit", "(", "1", ")", "finally", ":", "cleanup", "(", ")", "count", "+=", "1", "else", ":", "# One execution too far", "if", "total_time", ">", "seconds", ":", "count", "-=", "1", "yield", "count", "//", "seconds" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/share/doc/python3.7/examples/Tools/importbench/importbench.py#L20-L38
vgough/encfs
c444f9b9176beea1ad41a7b2e29ca26e709b57f7
vendor/github.com/muflihun/easyloggingpp/tools/cpplint.py
python
_CppLintState.SetFilters
(self, filters)
Sets the error-message filters. These filters are applied when deciding whether to emit a given error message. Args: filters: A string of comma-separated filters (eg "+whitespace/indent"). Each filter should start with + or -; else we die. Raises: ValueError: The comma-separated filters did not all start with '+' or '-'. E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
Sets the error-message filters.
[ "Sets", "the", "error", "-", "message", "filters", "." ]
def SetFilters(self, filters): """Sets the error-message filters. These filters are applied when deciding whether to emit a given error message. Args: filters: A string of comma-separated filters (eg "+whitespace/indent"). Each filter should start with + or -; else we die. Raises: ValueError: The comma-separated filters did not all start with '+' or '-'. E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter" """ # Default filters always have less priority than the flag ones. self.filters = _DEFAULT_FILTERS[:] for filt in filters.split(','): clean_filt = filt.strip() if clean_filt: self.filters.append(clean_filt) for filt in self.filters: if not (filt.startswith('+') or filt.startswith('-')): raise ValueError('Every filter in --filters must start with + or -' ' (%s does not)' % filt)
[ "def", "SetFilters", "(", "self", ",", "filters", ")", ":", "# Default filters always have less priority than the flag ones.", "self", ".", "filters", "=", "_DEFAULT_FILTERS", "[", ":", "]", "for", "filt", "in", "filters", ".", "split", "(", "','", ")", ":", "clean_filt", "=", "filt", ".", "strip", "(", ")", "if", "clean_filt", ":", "self", ".", "filters", ".", "append", "(", "clean_filt", ")", "for", "filt", "in", "self", ".", "filters", ":", "if", "not", "(", "filt", ".", "startswith", "(", "'+'", ")", "or", "filt", ".", "startswith", "(", "'-'", ")", ")", ":", "raise", "ValueError", "(", "'Every filter in --filters must start with + or -'", "' (%s does not)'", "%", "filt", ")" ]
https://github.com/vgough/encfs/blob/c444f9b9176beea1ad41a7b2e29ca26e709b57f7/vendor/github.com/muflihun/easyloggingpp/tools/cpplint.py#L694-L717
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/email/_parseaddr.py
python
quote
(str)
return str.replace('\\', '\\\\').replace('"', '\\"')
Prepare string to be used in a quoted string. Turns backslash and double quote characters into quoted pairs. These are the only characters that need to be quoted inside a quoted string. Does not add the surrounding double quotes.
Prepare string to be used in a quoted string.
[ "Prepare", "string", "to", "be", "used", "in", "a", "quoted", "string", "." ]
def quote(str): """Prepare string to be used in a quoted string. Turns backslash and double quote characters into quoted pairs. These are the only characters that need to be quoted inside a quoted string. Does not add the surrounding double quotes. """ return str.replace('\\', '\\\\').replace('"', '\\"')
[ "def", "quote", "(", "str", ")", ":", "return", "str", ".", "replace", "(", "'\\\\'", ",", "'\\\\\\\\'", ")", ".", "replace", "(", "'\"'", ",", "'\\\\\"'", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/email/_parseaddr.py#L162-L169
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
dom/bindings/parser/WebIDL.py
python
Parser.p_Attribute
(self, p)
Attribute : Inherit AttributeRest
Attribute : Inherit AttributeRest
[ "Attribute", ":", "Inherit", "AttributeRest" ]
def p_Attribute(self, p): """ Attribute : Inherit AttributeRest """ (location, identifier, type, readonly) = p[2] p[0] = IDLAttribute(location, identifier, type, readonly, inherit=p[1])
[ "def", "p_Attribute", "(", "self", ",", "p", ")", ":", "(", "location", ",", "identifier", ",", "type", ",", "readonly", ")", "=", "p", "[", "2", "]", "p", "[", "0", "]", "=", "IDLAttribute", "(", "location", ",", "identifier", ",", "type", ",", "readonly", ",", "inherit", "=", "p", "[", "1", "]", ")" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/dom/bindings/parser/WebIDL.py#L4636-L4641
alibaba/weex_js_engine
2bdf4b6f020c1fc99c63f649718f6faf7e27fdde
jni/v8core/v8/build/gyp/pylib/gyp/MSVSProject.py
python
Writer.AddFiles
(self, files)
Adds files to the project. Args: files: A list of Filter objects and/or relative paths to files. This makes a copy of the file/filter tree at the time of this call. If you later add files to a Filter object which was passed into a previous call to AddFiles(), it will not be reflected in this project.
Adds files to the project.
[ "Adds", "files", "to", "the", "project", "." ]
def AddFiles(self, files): """Adds files to the project. Args: files: A list of Filter objects and/or relative paths to files. This makes a copy of the file/filter tree at the time of this call. If you later add files to a Filter object which was passed into a previous call to AddFiles(), it will not be reflected in this project. """ self._AddFilesToNode(self.files_section, files)
[ "def", "AddFiles", "(", "self", ",", "files", ")", ":", "self", ".", "_AddFilesToNode", "(", "self", ".", "files_section", ",", "files", ")" ]
https://github.com/alibaba/weex_js_engine/blob/2bdf4b6f020c1fc99c63f649718f6faf7e27fdde/jni/v8core/v8/build/gyp/pylib/gyp/MSVSProject.py#L152-L162
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/pydocview.py
python
DocApp.OnInit
(self)
return True
Initializes the DocApp.
Initializes the DocApp.
[ "Initializes", "the", "DocApp", "." ]
def OnInit(self): """ Initializes the DocApp. """ self._services = [] self._defaultIcon = None self._registeredCloseEvent = False self._useTabbedMDI = True if not hasattr(self, "_debug"): # only set if not already initialized self._debug = False if not hasattr(self, "_singleInstance"): # only set if not already initialized self._singleInstance = True # if _singleInstance is TRUE only allow one single instance of app to run. # When user tries to run a second instance of the app, abort startup, # But if user also specifies files to open in command line, send message to running app to open those files if self._singleInstance: # create shared memory temporary file if wx.Platform == '__WXMSW__': tfile = tempfile.TemporaryFile(prefix="ag", suffix="tmp") fno = tfile.fileno() self._sharedMemory = mmap.mmap(fno, 1024, "shared_memory") else: tfile = file(os.path.join(tempfile.gettempdir(), tempfile.gettempprefix() + self.GetAppName() + '-' + wx.GetUserId() + "AGSharedMemory"), 'w+b') tfile.write("*") tfile.seek(1024) tfile.write(" ") tfile.flush() fno = tfile.fileno() self._sharedMemory = mmap.mmap(fno, 1024) self._singleInstanceChecker = wx.SingleInstanceChecker(self.GetAppName() + '-' + wx.GetUserId(), tempfile.gettempdir()) if self._singleInstanceChecker.IsAnotherRunning(): # have running single instance open file arguments data = pickle.dumps(sys.argv[1:]) while 1: self._sharedMemory.seek(0) marker = self._sharedMemory.read_byte() if marker == '\0' or marker == '*': # available buffer self._sharedMemory.seek(0) self._sharedMemory.write_byte('-') # set writing marker self._sharedMemory.write(data) # write files we tried to open to shared memory self._sharedMemory.seek(0) self._sharedMemory.write_byte('+') # set finished writing marker self._sharedMemory.flush() break else: time.sleep(1) # give enough time for buffer to be available return False else: self._timer = wx.PyTimer(self.DoBackgroundListenAndLoad) self._timer.Start(250) return True
[ "def", "OnInit", "(", "self", ")", ":", "self", ".", "_services", "=", "[", "]", "self", ".", "_defaultIcon", "=", "None", "self", ".", "_registeredCloseEvent", "=", "False", "self", ".", "_useTabbedMDI", "=", "True", "if", "not", "hasattr", "(", "self", ",", "\"_debug\"", ")", ":", "# only set if not already initialized", "self", ".", "_debug", "=", "False", "if", "not", "hasattr", "(", "self", ",", "\"_singleInstance\"", ")", ":", "# only set if not already initialized", "self", ".", "_singleInstance", "=", "True", "# if _singleInstance is TRUE only allow one single instance of app to run.", "# When user tries to run a second instance of the app, abort startup,", "# But if user also specifies files to open in command line, send message to running app to open those files", "if", "self", ".", "_singleInstance", ":", "# create shared memory temporary file", "if", "wx", ".", "Platform", "==", "'__WXMSW__'", ":", "tfile", "=", "tempfile", ".", "TemporaryFile", "(", "prefix", "=", "\"ag\"", ",", "suffix", "=", "\"tmp\"", ")", "fno", "=", "tfile", ".", "fileno", "(", ")", "self", ".", "_sharedMemory", "=", "mmap", ".", "mmap", "(", "fno", ",", "1024", ",", "\"shared_memory\"", ")", "else", ":", "tfile", "=", "file", "(", "os", ".", "path", ".", "join", "(", "tempfile", ".", "gettempdir", "(", ")", ",", "tempfile", ".", "gettempprefix", "(", ")", "+", "self", ".", "GetAppName", "(", ")", "+", "'-'", "+", "wx", ".", "GetUserId", "(", ")", "+", "\"AGSharedMemory\"", ")", ",", "'w+b'", ")", "tfile", ".", "write", "(", "\"*\"", ")", "tfile", ".", "seek", "(", "1024", ")", "tfile", ".", "write", "(", "\" \"", ")", "tfile", ".", "flush", "(", ")", "fno", "=", "tfile", ".", "fileno", "(", ")", "self", ".", "_sharedMemory", "=", "mmap", ".", "mmap", "(", "fno", ",", "1024", ")", "self", ".", "_singleInstanceChecker", "=", "wx", ".", "SingleInstanceChecker", "(", "self", ".", "GetAppName", "(", ")", "+", "'-'", "+", "wx", ".", "GetUserId", "(", ")", ",", "tempfile", ".", "gettempdir", "(", ")", ")", "if", "self", ".", "_singleInstanceChecker", ".", "IsAnotherRunning", "(", ")", ":", "# have running single instance open file arguments", "data", "=", "pickle", ".", "dumps", "(", "sys", ".", "argv", "[", "1", ":", "]", ")", "while", "1", ":", "self", ".", "_sharedMemory", ".", "seek", "(", "0", ")", "marker", "=", "self", ".", "_sharedMemory", ".", "read_byte", "(", ")", "if", "marker", "==", "'\\0'", "or", "marker", "==", "'*'", ":", "# available buffer", "self", ".", "_sharedMemory", ".", "seek", "(", "0", ")", "self", ".", "_sharedMemory", ".", "write_byte", "(", "'-'", ")", "# set writing marker", "self", ".", "_sharedMemory", ".", "write", "(", "data", ")", "# write files we tried to open to shared memory", "self", ".", "_sharedMemory", ".", "seek", "(", "0", ")", "self", ".", "_sharedMemory", ".", "write_byte", "(", "'+'", ")", "# set finished writing marker", "self", ".", "_sharedMemory", ".", "flush", "(", ")", "break", "else", ":", "time", ".", "sleep", "(", "1", ")", "# give enough time for buffer to be available", "return", "False", "else", ":", "self", ".", "_timer", "=", "wx", ".", "PyTimer", "(", "self", ".", "DoBackgroundListenAndLoad", ")", "self", ".", "_timer", ".", "Start", "(", "250", ")", "return", "True" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/pydocview.py#L1664-L1719
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
packages/seacas/libraries/ioss/src/visualization/catalyst/phactori/Operation/PhactoriMpiUtilities.py
python
ReadAndMpiBroadcastJsonFile
(inJsonFileName)
return returnJson
given a json format file, read in the contents using the python json library on process zero, use MPI to broadcast the contents to all processes (via converting to a long char string)
given a json format file, read in the contents using the python json library on process zero, use MPI to broadcast the contents to all processes (via converting to a long char string)
[ "given", "a", "json", "format", "file", "read", "in", "the", "contents", "using", "the", "python", "json", "library", "on", "process", "zero", "use", "MPI", "to", "broadcast", "the", "contents", "to", "all", "processes", "(", "via", "converting", "to", "a", "long", "char", "string", ")" ]
def ReadAndMpiBroadcastJsonFile(inJsonFileName): """given a json format file, read in the contents using the python json library on process zero, use MPI to broadcast the contents to all processes (via converting to a long char string)""" if SmartGetLocalProcessId() == 0: #process zero loads json script and broadcasts returnJson = HandleJsonScriptLoadProcessZero(inJsonFileName) else: #other processes receive json script returnJson = HandleJsonScriptLoadProcessNotZero() return returnJson
[ "def", "ReadAndMpiBroadcastJsonFile", "(", "inJsonFileName", ")", ":", "if", "SmartGetLocalProcessId", "(", ")", "==", "0", ":", "#process zero loads json script and broadcasts", "returnJson", "=", "HandleJsonScriptLoadProcessZero", "(", "inJsonFileName", ")", "else", ":", "#other processes receive json script", "returnJson", "=", "HandleJsonScriptLoadProcessNotZero", "(", ")", "return", "returnJson" ]
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/libraries/ioss/src/visualization/catalyst/phactori/Operation/PhactoriMpiUtilities.py#L220-L230
google/omaha
61e8c2833fd69c9a13978400108e5b9ebff24a09
omaha/site_scons/site_tools/atlmfc_vc15_0.py
python
generate
(env)
SCons entry point for this tool.
SCons entry point for this tool.
[ "SCons", "entry", "point", "for", "this", "tool", "." ]
def generate(env): # NOTE: SCons requires the use of this name, which fails gpylint. """SCons entry point for this tool.""" if not env.get('ATLMFC_VC15_0_DIR'): env['ATLMFC_VC15_0_DIR'] = _FindLocalInstall() env.AppendENVPath('INCLUDE', env.Dir('$ATLMFC_VC15_0_DIR/include').abspath) env.AppendENVPath('LIB', env.Dir('$ATLMFC_VC15_0_DIR/lib/x86').abspath)
[ "def", "generate", "(", "env", ")", ":", "# NOTE: SCons requires the use of this name, which fails gpylint.", "if", "not", "env", ".", "get", "(", "'ATLMFC_VC15_0_DIR'", ")", ":", "env", "[", "'ATLMFC_VC15_0_DIR'", "]", "=", "_FindLocalInstall", "(", ")", "env", ".", "AppendENVPath", "(", "'INCLUDE'", ",", "env", ".", "Dir", "(", "'$ATLMFC_VC15_0_DIR/include'", ")", ".", "abspath", ")", "env", ".", "AppendENVPath", "(", "'LIB'", ",", "env", ".", "Dir", "(", "'$ATLMFC_VC15_0_DIR/lib/x86'", ")", ".", "abspath", ")" ]
https://github.com/google/omaha/blob/61e8c2833fd69c9a13978400108e5b9ebff24a09/omaha/site_scons/site_tools/atlmfc_vc15_0.py#L34-L42
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftguitools/gui_offset.py
python
Offset.action
(self, arg)
Handle the 3D scene events. This is installed as an EventCallback in the Inventor view. Parameters ---------- arg: dict Dictionary with strings that indicates the type of event received from the 3D view.
Handle the 3D scene events.
[ "Handle", "the", "3D", "scene", "events", "." ]
def action(self, arg): """Handle the 3D scene events. This is installed as an EventCallback in the Inventor view. Parameters ---------- arg: dict Dictionary with strings that indicates the type of event received from the 3D view. """ import DraftGeomUtils plane = App.DraftWorkingPlane if arg["Type"] == "SoKeyboardEvent": if arg["Key"] == "ESCAPE": self.finish() elif arg["Type"] == "SoLocation2Event": self.point, ctrlPoint, info = gui_tool_utils.getPoint(self, arg) if (gui_tool_utils.hasMod(arg, gui_tool_utils.MODCONSTRAIN) and self.constrainSeg): dist = DraftGeomUtils.findPerpendicular(self.point, self.shape, self.constrainSeg[1]) else: dist = DraftGeomUtils.findPerpendicular(self.point, self.shape.Edges) if dist: self.ghost.on() if self.mode == "Wire": d = dist[0].negative() v1 = DraftGeomUtils.getTangent(self.shape.Edges[0], self.point) v2 = DraftGeomUtils.getTangent(self.shape.Edges[dist[1]], self.point) a = -DraftVecUtils.angle(v1, v2, plane.axis) self.dvec = DraftVecUtils.rotate(d, a, plane.axis) occmode = self.ui.occOffset.isChecked() utils.param.SetBool("Offset_OCC", occmode) _wire = DraftGeomUtils.offsetWire(self.shape, self.dvec, occ=occmode) self.ghost.update(_wire, forceclosed=occmode) elif self.mode == "BSpline": d = dist[0].negative() e = self.shape.Edges[0] basetan = DraftGeomUtils.getTangent(e, self.point) self.npts = [] for p in self.sel.Points: currtan = DraftGeomUtils.getTangent(e, p) a = -DraftVecUtils.angle(currtan, basetan, plane.axis) self.dvec = DraftVecUtils.rotate(d, a, plane.axis) self.npts.append(p.add(self.dvec)) self.ghost.update(self.npts) elif self.mode == "Circle": self.dvec = self.point.sub(self.center).Length self.ghost.setRadius(self.dvec) self.constrainSeg = dist self.linetrack.on() self.linetrack.p1(self.point) self.linetrack.p2(self.point.add(dist[0])) self.ui.setRadiusValue(dist[0].Length, unit="Length") else: self.dvec = None self.ghost.off() self.constrainSeg = None self.linetrack.off() self.ui.radiusValue.setText("off") self.ui.radiusValue.setFocus() self.ui.radiusValue.selectAll() if self.extendedCopy: if not gui_tool_utils.hasMod(arg, gui_tool_utils.MODALT): self.finish() gui_tool_utils.redraw3DView() elif arg["Type"] == "SoMouseButtonEvent": if (arg["State"] == "DOWN") and (arg["Button"] == "BUTTON1"): copymode = False occmode = self.ui.occOffset.isChecked() utils.param.SetBool("Offset_OCC", occmode) if (gui_tool_utils.hasMod(arg, gui_tool_utils.MODALT) or self.ui.isCopy.isChecked()): copymode = True Gui.addModule("Draft") if self.npts: # _msg("offset:npts= " + str(self.npts)) _cmd = 'Draft.offset' _cmd += '(' _cmd += 'FreeCAD.ActiveDocument.' _cmd += self.sel.Name + ', ' _cmd += DraftVecUtils.toString(self.npts) + ', ' _cmd += 'copy=' + str(copymode) _cmd += ')' _cmd_list = ['offst = ' + _cmd, 'FreeCAD.ActiveDocument.recompute()'] self.commit(translate("draft", "Offset"), _cmd_list) elif self.dvec: if isinstance(self.dvec, float): delta = str(self.dvec) else: delta = DraftVecUtils.toString(self.dvec) _cmd = 'Draft.offset' _cmd += '(' _cmd += 'FreeCAD.ActiveDocument.' _cmd += self.sel.Name + ', ' _cmd += delta + ', ' _cmd += 'copy=' + str(copymode) + ', ' _cmd += 'occ=' + str(occmode) _cmd += ')' _cmd_list = ['offst = ' + _cmd, 'FreeCAD.ActiveDocument.recompute()'] self.commit(translate("draft", "Offset"), _cmd_list) if gui_tool_utils.hasMod(arg, gui_tool_utils.MODALT): self.extendedCopy = True else: self.finish()
[ "def", "action", "(", "self", ",", "arg", ")", ":", "import", "DraftGeomUtils", "plane", "=", "App", ".", "DraftWorkingPlane", "if", "arg", "[", "\"Type\"", "]", "==", "\"SoKeyboardEvent\"", ":", "if", "arg", "[", "\"Key\"", "]", "==", "\"ESCAPE\"", ":", "self", ".", "finish", "(", ")", "elif", "arg", "[", "\"Type\"", "]", "==", "\"SoLocation2Event\"", ":", "self", ".", "point", ",", "ctrlPoint", ",", "info", "=", "gui_tool_utils", ".", "getPoint", "(", "self", ",", "arg", ")", "if", "(", "gui_tool_utils", ".", "hasMod", "(", "arg", ",", "gui_tool_utils", ".", "MODCONSTRAIN", ")", "and", "self", ".", "constrainSeg", ")", ":", "dist", "=", "DraftGeomUtils", ".", "findPerpendicular", "(", "self", ".", "point", ",", "self", ".", "shape", ",", "self", ".", "constrainSeg", "[", "1", "]", ")", "else", ":", "dist", "=", "DraftGeomUtils", ".", "findPerpendicular", "(", "self", ".", "point", ",", "self", ".", "shape", ".", "Edges", ")", "if", "dist", ":", "self", ".", "ghost", ".", "on", "(", ")", "if", "self", ".", "mode", "==", "\"Wire\"", ":", "d", "=", "dist", "[", "0", "]", ".", "negative", "(", ")", "v1", "=", "DraftGeomUtils", ".", "getTangent", "(", "self", ".", "shape", ".", "Edges", "[", "0", "]", ",", "self", ".", "point", ")", "v2", "=", "DraftGeomUtils", ".", "getTangent", "(", "self", ".", "shape", ".", "Edges", "[", "dist", "[", "1", "]", "]", ",", "self", ".", "point", ")", "a", "=", "-", "DraftVecUtils", ".", "angle", "(", "v1", ",", "v2", ",", "plane", ".", "axis", ")", "self", ".", "dvec", "=", "DraftVecUtils", ".", "rotate", "(", "d", ",", "a", ",", "plane", ".", "axis", ")", "occmode", "=", "self", ".", "ui", ".", "occOffset", ".", "isChecked", "(", ")", "utils", ".", "param", ".", "SetBool", "(", "\"Offset_OCC\"", ",", "occmode", ")", "_wire", "=", "DraftGeomUtils", ".", "offsetWire", "(", "self", ".", "shape", ",", "self", ".", "dvec", ",", "occ", "=", "occmode", ")", "self", ".", "ghost", ".", "update", "(", "_wire", ",", "forceclosed", "=", "occmode", ")", "elif", "self", ".", "mode", "==", "\"BSpline\"", ":", "d", "=", "dist", "[", "0", "]", ".", "negative", "(", ")", "e", "=", "self", ".", "shape", ".", "Edges", "[", "0", "]", "basetan", "=", "DraftGeomUtils", ".", "getTangent", "(", "e", ",", "self", ".", "point", ")", "self", ".", "npts", "=", "[", "]", "for", "p", "in", "self", ".", "sel", ".", "Points", ":", "currtan", "=", "DraftGeomUtils", ".", "getTangent", "(", "e", ",", "p", ")", "a", "=", "-", "DraftVecUtils", ".", "angle", "(", "currtan", ",", "basetan", ",", "plane", ".", "axis", ")", "self", ".", "dvec", "=", "DraftVecUtils", ".", "rotate", "(", "d", ",", "a", ",", "plane", ".", "axis", ")", "self", ".", "npts", ".", "append", "(", "p", ".", "add", "(", "self", ".", "dvec", ")", ")", "self", ".", "ghost", ".", "update", "(", "self", ".", "npts", ")", "elif", "self", ".", "mode", "==", "\"Circle\"", ":", "self", ".", "dvec", "=", "self", ".", "point", ".", "sub", "(", "self", ".", "center", ")", ".", "Length", "self", ".", "ghost", ".", "setRadius", "(", "self", ".", "dvec", ")", "self", ".", "constrainSeg", "=", "dist", "self", ".", "linetrack", ".", "on", "(", ")", "self", ".", "linetrack", ".", "p1", "(", "self", ".", "point", ")", "self", ".", "linetrack", ".", "p2", "(", "self", ".", "point", ".", "add", "(", "dist", "[", "0", "]", ")", ")", "self", ".", "ui", ".", "setRadiusValue", "(", "dist", "[", "0", "]", ".", "Length", ",", "unit", "=", "\"Length\"", ")", "else", ":", "self", ".", "dvec", "=", "None", "self", ".", "ghost", ".", "off", "(", ")", "self", ".", "constrainSeg", "=", "None", "self", ".", "linetrack", ".", "off", "(", ")", "self", ".", "ui", ".", "radiusValue", ".", "setText", "(", "\"off\"", ")", "self", ".", "ui", ".", "radiusValue", ".", "setFocus", "(", ")", "self", ".", "ui", ".", "radiusValue", ".", "selectAll", "(", ")", "if", "self", ".", "extendedCopy", ":", "if", "not", "gui_tool_utils", ".", "hasMod", "(", "arg", ",", "gui_tool_utils", ".", "MODALT", ")", ":", "self", ".", "finish", "(", ")", "gui_tool_utils", ".", "redraw3DView", "(", ")", "elif", "arg", "[", "\"Type\"", "]", "==", "\"SoMouseButtonEvent\"", ":", "if", "(", "arg", "[", "\"State\"", "]", "==", "\"DOWN\"", ")", "and", "(", "arg", "[", "\"Button\"", "]", "==", "\"BUTTON1\"", ")", ":", "copymode", "=", "False", "occmode", "=", "self", ".", "ui", ".", "occOffset", ".", "isChecked", "(", ")", "utils", ".", "param", ".", "SetBool", "(", "\"Offset_OCC\"", ",", "occmode", ")", "if", "(", "gui_tool_utils", ".", "hasMod", "(", "arg", ",", "gui_tool_utils", ".", "MODALT", ")", "or", "self", ".", "ui", ".", "isCopy", ".", "isChecked", "(", ")", ")", ":", "copymode", "=", "True", "Gui", ".", "addModule", "(", "\"Draft\"", ")", "if", "self", ".", "npts", ":", "# _msg(\"offset:npts= \" + str(self.npts))", "_cmd", "=", "'Draft.offset'", "_cmd", "+=", "'('", "_cmd", "+=", "'FreeCAD.ActiveDocument.'", "_cmd", "+=", "self", ".", "sel", ".", "Name", "+", "', '", "_cmd", "+=", "DraftVecUtils", ".", "toString", "(", "self", ".", "npts", ")", "+", "', '", "_cmd", "+=", "'copy='", "+", "str", "(", "copymode", ")", "_cmd", "+=", "')'", "_cmd_list", "=", "[", "'offst = '", "+", "_cmd", ",", "'FreeCAD.ActiveDocument.recompute()'", "]", "self", ".", "commit", "(", "translate", "(", "\"draft\"", ",", "\"Offset\"", ")", ",", "_cmd_list", ")", "elif", "self", ".", "dvec", ":", "if", "isinstance", "(", "self", ".", "dvec", ",", "float", ")", ":", "delta", "=", "str", "(", "self", ".", "dvec", ")", "else", ":", "delta", "=", "DraftVecUtils", ".", "toString", "(", "self", ".", "dvec", ")", "_cmd", "=", "'Draft.offset'", "_cmd", "+=", "'('", "_cmd", "+=", "'FreeCAD.ActiveDocument.'", "_cmd", "+=", "self", ".", "sel", ".", "Name", "+", "', '", "_cmd", "+=", "delta", "+", "', '", "_cmd", "+=", "'copy='", "+", "str", "(", "copymode", ")", "+", "', '", "_cmd", "+=", "'occ='", "+", "str", "(", "occmode", ")", "_cmd", "+=", "')'", "_cmd_list", "=", "[", "'offst = '", "+", "_cmd", ",", "'FreeCAD.ActiveDocument.recompute()'", "]", "self", ".", "commit", "(", "translate", "(", "\"draft\"", ",", "\"Offset\"", ")", ",", "_cmd_list", ")", "if", "gui_tool_utils", ".", "hasMod", "(", "arg", ",", "gui_tool_utils", ".", "MODALT", ")", ":", "self", ".", "extendedCopy", "=", "True", "else", ":", "self", ".", "finish", "(", ")" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_offset.py#L148-L265
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
TextEntryBase.CanCut
(*args, **kwargs)
return _core_.TextEntryBase_CanCut(*args, **kwargs)
CanCut(self) -> bool Returns True if the text field is editable and there is a text selection to copy to the clipboard.
CanCut(self) -> bool
[ "CanCut", "(", "self", ")", "-", ">", "bool" ]
def CanCut(*args, **kwargs): """ CanCut(self) -> bool Returns True if the text field is editable and there is a text selection to copy to the clipboard. """ return _core_.TextEntryBase_CanCut(*args, **kwargs)
[ "def", "CanCut", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "TextEntryBase_CanCut", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L13193-L13200
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/framework/tensor_shape.py
python
TensorShape.with_rank_at_least
(self, rank)
Returns a shape based on `self` with at least the given rank. Args: rank: An integer. Returns: A shape that is at least as specific as `self` with at least the given rank. Raises: ValueError: If `self` does not represent a shape with at least the given `rank`.
Returns a shape based on `self` with at least the given rank.
[ "Returns", "a", "shape", "based", "on", "self", "with", "at", "least", "the", "given", "rank", "." ]
def with_rank_at_least(self, rank): """Returns a shape based on `self` with at least the given rank. Args: rank: An integer. Returns: A shape that is at least as specific as `self` with at least the given rank. Raises: ValueError: If `self` does not represent a shape with at least the given `rank`. """ if self.ndims is not None and self.ndims < rank: raise ValueError("Shape %s must have rank at least %d" % (self, rank)) else: return self
[ "def", "with_rank_at_least", "(", "self", ",", "rank", ")", ":", "if", "self", ".", "ndims", "is", "not", "None", "and", "self", ".", "ndims", "<", "rank", ":", "raise", "ValueError", "(", "\"Shape %s must have rank at least %d\"", "%", "(", "self", ",", "rank", ")", ")", "else", ":", "return", "self" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/framework/tensor_shape.py#L656-L673
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/fmcustomizedlg.py
python
FMCustomizeDlg.CreateOptionsPage
(self)
return options
Creates the :class:`LabelBook` option page which holds the :class:`FlatMenu` styles.
Creates the :class:`LabelBook` option page which holds the :class:`FlatMenu` styles.
[ "Creates", "the", ":", "class", ":", "LabelBook", "option", "page", "which", "holds", "the", ":", "class", ":", "FlatMenu", "styles", "." ]
def CreateOptionsPage(self): """ Creates the :class:`LabelBook` option page which holds the :class:`FlatMenu` styles. """ options = wx.Panel(self._book, wx.ID_ANY, wx.DefaultPosition, wx.Size(300, 300)) # Create some options here vsizer = wx.BoxSizer(wx.VERTICAL) options.SetSizer(vsizer) #----------------------------------------------------------- # options page layout # - Menu Style: Default or 2007 (radio group) # # - Default Style Settings: (static box) # + Draw vertical gradient (check box) # + Draw border (check box) # + Drop toolbar shadow (check box) # # - Colour Scheme (static box) # + Menu bar background colour (combo button) #----------------------------------------------------------- self._menuStyleID = wx.NewId() choices = [_("Default Style"), _("Metallic")] self._menuStyle = wx.RadioBox(options, self._menuStyleID, _("Menu bar style"), wx.DefaultPosition, wx.DefaultSize, choices) # update the selection theme = ArtManager.Get().GetMenuTheme() if theme == Style2007: self._menuStyle.SetSelection(1) else: self._menuStyle.SetSelection(0) # connect event to the control self._menuStyle.Bind(wx.EVT_RADIOBOX, self.OnChangeStyle) vsizer.Add(self._menuStyle, 0, wx.EXPAND | wx.ALL, 5) self._sbStyle = wx.StaticBoxSizer(wx.StaticBox(options, -1, _("Default style settings")), wx.VERTICAL) self._drawVertGradID = wx.NewId() self._verticalGradient = wx.CheckBox(options, self._drawVertGradID, _("Draw vertical gradient")) self._verticalGradient.Bind(wx.EVT_CHECKBOX, self.OnChangeStyle) self._sbStyle.Add(self._verticalGradient, 0, wx.EXPAND | wx.ALL, 3) self._verticalGradient.SetValue(ArtManager.Get().GetMBVerticalGradient()) self._drawBorderID = wx.NewId() self._drawBorder = wx.CheckBox(options, self._drawBorderID, _("Draw border around menu bar")) self._drawBorder.Bind(wx.EVT_CHECKBOX, self.OnChangeStyle) self._sbStyle.Add(self._drawBorder, 0, wx.EXPAND | wx.ALL, 3) self._drawBorder.SetValue(ArtManager.Get().GetMenuBarBorder()) self._shadowUnderTBID = wx.NewId() self._shadowUnderTB = wx.CheckBox(options, self._shadowUnderTBID, _("Toolbar float over menu bar")) self._shadowUnderTB.Bind(wx.EVT_CHECKBOX, self.OnChangeStyle) self._sbStyle.Add(self._shadowUnderTB, 0, wx.EXPAND | wx.ALL, 3) self._shadowUnderTB.SetValue(ArtManager.Get().GetRaiseToolbar()) vsizer.Add(self._sbStyle, 0, wx.EXPAND | wx.ALL, 5) # Misc sb = wx.StaticBoxSizer(wx.StaticBox(options, -1, _("Colour Scheme")), wx.VERTICAL) self._colourID = wx.NewId() colourChoices = ArtManager.Get().GetColourSchemes() colourChoices.sort() self._colour = wx.ComboBox(options, self._colourID, ArtManager.Get().GetMenuBarColourScheme(), choices=colourChoices, style=wx.CB_DROPDOWN | wx.CB_READONLY) sb.Add(self._colour, 0, wx.EXPAND) vsizer.Add(sb, 0, wx.EXPAND | wx.ALL, 5) self._colour.Bind(wx.EVT_COMBOBOX, self.OnChangeStyle) # update the dialog by sending all possible events to us event = wx.CommandEvent(wx.wxEVT_COMMAND_RADIOBOX_SELECTED, self._menuStyleID) event.SetEventObject(self) event.SetInt(self._menuStyle.GetSelection()) self._menuStyle.ProcessEvent(event) event.SetEventType(wx.wxEVT_COMMAND_CHECKBOX_CLICKED) event.SetId(self._drawVertGradID) event.SetInt(ArtManager.Get().GetMBVerticalGradient()) self._verticalGradient.ProcessEvent(event) event.SetEventType(wx.wxEVT_COMMAND_CHECKBOX_CLICKED) event.SetId(self._shadowUnderTBID) event.SetInt(ArtManager.Get().GetRaiseToolbar()) self._shadowUnderTB.ProcessEvent(event) event.SetEventType(wx.wxEVT_COMMAND_CHECKBOX_CLICKED) event.SetId(self._drawBorderID) event.SetInt(ArtManager.Get().GetMenuBarBorder()) self._drawBorder.ProcessEvent(event) event.SetEventType(wx.wxEVT_COMMAND_COMBOBOX_SELECTED) event.SetId(self._colourID) self._colour.ProcessEvent(event) return options
[ "def", "CreateOptionsPage", "(", "self", ")", ":", "options", "=", "wx", ".", "Panel", "(", "self", ".", "_book", ",", "wx", ".", "ID_ANY", ",", "wx", ".", "DefaultPosition", ",", "wx", ".", "Size", "(", "300", ",", "300", ")", ")", "# Create some options here", "vsizer", "=", "wx", ".", "BoxSizer", "(", "wx", ".", "VERTICAL", ")", "options", ".", "SetSizer", "(", "vsizer", ")", "#-----------------------------------------------------------", "# options page layout ", "# - Menu Style: Default or 2007 (radio group)", "#", "# - Default Style Settings: (static box)", "# + Draw vertical gradient (check box)", "# + Draw border (check box)", "# + Drop toolbar shadow (check box)", "#", "# - Colour Scheme (static box)", "# + Menu bar background colour (combo button)", "#-----------------------------------------------------------", "self", ".", "_menuStyleID", "=", "wx", ".", "NewId", "(", ")", "choices", "=", "[", "_", "(", "\"Default Style\"", ")", ",", "_", "(", "\"Metallic\"", ")", "]", "self", ".", "_menuStyle", "=", "wx", ".", "RadioBox", "(", "options", ",", "self", ".", "_menuStyleID", ",", "_", "(", "\"Menu bar style\"", ")", ",", "wx", ".", "DefaultPosition", ",", "wx", ".", "DefaultSize", ",", "choices", ")", "# update the selection", "theme", "=", "ArtManager", ".", "Get", "(", ")", ".", "GetMenuTheme", "(", ")", "if", "theme", "==", "Style2007", ":", "self", ".", "_menuStyle", ".", "SetSelection", "(", "1", ")", "else", ":", "self", ".", "_menuStyle", ".", "SetSelection", "(", "0", ")", "# connect event to the control", "self", ".", "_menuStyle", ".", "Bind", "(", "wx", ".", "EVT_RADIOBOX", ",", "self", ".", "OnChangeStyle", ")", "vsizer", ".", "Add", "(", "self", ".", "_menuStyle", ",", "0", ",", "wx", ".", "EXPAND", "|", "wx", ".", "ALL", ",", "5", ")", "self", ".", "_sbStyle", "=", "wx", ".", "StaticBoxSizer", "(", "wx", ".", "StaticBox", "(", "options", ",", "-", "1", ",", "_", "(", "\"Default style settings\"", ")", ")", ",", "wx", ".", "VERTICAL", ")", "self", ".", "_drawVertGradID", "=", "wx", ".", "NewId", "(", ")", "self", ".", "_verticalGradient", "=", "wx", ".", "CheckBox", "(", "options", ",", "self", ".", "_drawVertGradID", ",", "_", "(", "\"Draw vertical gradient\"", ")", ")", "self", ".", "_verticalGradient", ".", "Bind", "(", "wx", ".", "EVT_CHECKBOX", ",", "self", ".", "OnChangeStyle", ")", "self", ".", "_sbStyle", ".", "Add", "(", "self", ".", "_verticalGradient", ",", "0", ",", "wx", ".", "EXPAND", "|", "wx", ".", "ALL", ",", "3", ")", "self", ".", "_verticalGradient", ".", "SetValue", "(", "ArtManager", ".", "Get", "(", ")", ".", "GetMBVerticalGradient", "(", ")", ")", "self", ".", "_drawBorderID", "=", "wx", ".", "NewId", "(", ")", "self", ".", "_drawBorder", "=", "wx", ".", "CheckBox", "(", "options", ",", "self", ".", "_drawBorderID", ",", "_", "(", "\"Draw border around menu bar\"", ")", ")", "self", ".", "_drawBorder", ".", "Bind", "(", "wx", ".", "EVT_CHECKBOX", ",", "self", ".", "OnChangeStyle", ")", "self", ".", "_sbStyle", ".", "Add", "(", "self", ".", "_drawBorder", ",", "0", ",", "wx", ".", "EXPAND", "|", "wx", ".", "ALL", ",", "3", ")", "self", ".", "_drawBorder", ".", "SetValue", "(", "ArtManager", ".", "Get", "(", ")", ".", "GetMenuBarBorder", "(", ")", ")", "self", ".", "_shadowUnderTBID", "=", "wx", ".", "NewId", "(", ")", "self", ".", "_shadowUnderTB", "=", "wx", ".", "CheckBox", "(", "options", ",", "self", ".", "_shadowUnderTBID", ",", "_", "(", "\"Toolbar float over menu bar\"", ")", ")", "self", ".", "_shadowUnderTB", ".", "Bind", "(", "wx", ".", "EVT_CHECKBOX", ",", "self", ".", "OnChangeStyle", ")", "self", ".", "_sbStyle", ".", "Add", "(", "self", ".", "_shadowUnderTB", ",", "0", ",", "wx", ".", "EXPAND", "|", "wx", ".", "ALL", ",", "3", ")", "self", ".", "_shadowUnderTB", ".", "SetValue", "(", "ArtManager", ".", "Get", "(", ")", ".", "GetRaiseToolbar", "(", ")", ")", "vsizer", ".", "Add", "(", "self", ".", "_sbStyle", ",", "0", ",", "wx", ".", "EXPAND", "|", "wx", ".", "ALL", ",", "5", ")", "# Misc ", "sb", "=", "wx", ".", "StaticBoxSizer", "(", "wx", ".", "StaticBox", "(", "options", ",", "-", "1", ",", "_", "(", "\"Colour Scheme\"", ")", ")", ",", "wx", ".", "VERTICAL", ")", "self", ".", "_colourID", "=", "wx", ".", "NewId", "(", ")", "colourChoices", "=", "ArtManager", ".", "Get", "(", ")", ".", "GetColourSchemes", "(", ")", "colourChoices", ".", "sort", "(", ")", "self", ".", "_colour", "=", "wx", ".", "ComboBox", "(", "options", ",", "self", ".", "_colourID", ",", "ArtManager", ".", "Get", "(", ")", ".", "GetMenuBarColourScheme", "(", ")", ",", "choices", "=", "colourChoices", ",", "style", "=", "wx", ".", "CB_DROPDOWN", "|", "wx", ".", "CB_READONLY", ")", "sb", ".", "Add", "(", "self", ".", "_colour", ",", "0", ",", "wx", ".", "EXPAND", ")", "vsizer", ".", "Add", "(", "sb", ",", "0", ",", "wx", ".", "EXPAND", "|", "wx", ".", "ALL", ",", "5", ")", "self", ".", "_colour", ".", "Bind", "(", "wx", ".", "EVT_COMBOBOX", ",", "self", ".", "OnChangeStyle", ")", "# update the dialog by sending all possible events to us", "event", "=", "wx", ".", "CommandEvent", "(", "wx", ".", "wxEVT_COMMAND_RADIOBOX_SELECTED", ",", "self", ".", "_menuStyleID", ")", "event", ".", "SetEventObject", "(", "self", ")", "event", ".", "SetInt", "(", "self", ".", "_menuStyle", ".", "GetSelection", "(", ")", ")", "self", ".", "_menuStyle", ".", "ProcessEvent", "(", "event", ")", "event", ".", "SetEventType", "(", "wx", ".", "wxEVT_COMMAND_CHECKBOX_CLICKED", ")", "event", ".", "SetId", "(", "self", ".", "_drawVertGradID", ")", "event", ".", "SetInt", "(", "ArtManager", ".", "Get", "(", ")", ".", "GetMBVerticalGradient", "(", ")", ")", "self", ".", "_verticalGradient", ".", "ProcessEvent", "(", "event", ")", "event", ".", "SetEventType", "(", "wx", ".", "wxEVT_COMMAND_CHECKBOX_CLICKED", ")", "event", ".", "SetId", "(", "self", ".", "_shadowUnderTBID", ")", "event", ".", "SetInt", "(", "ArtManager", ".", "Get", "(", ")", ".", "GetRaiseToolbar", "(", ")", ")", "self", ".", "_shadowUnderTB", ".", "ProcessEvent", "(", "event", ")", "event", ".", "SetEventType", "(", "wx", ".", "wxEVT_COMMAND_CHECKBOX_CLICKED", ")", "event", ".", "SetId", "(", "self", ".", "_drawBorderID", ")", "event", ".", "SetInt", "(", "ArtManager", ".", "Get", "(", ")", ".", "GetMenuBarBorder", "(", ")", ")", "self", ".", "_drawBorder", ".", "ProcessEvent", "(", "event", ")", "event", ".", "SetEventType", "(", "wx", ".", "wxEVT_COMMAND_COMBOBOX_SELECTED", ")", "event", ".", "SetId", "(", "self", ".", "_colourID", ")", "self", ".", "_colour", ".", "ProcessEvent", "(", "event", ")", "return", "options" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/fmcustomizedlg.py#L298-L397
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/pythonapi.py
python
PythonAPI.get_c_object
(self, name)
return self.context.get_c_value(self.builder, self.pyobj.pointee, name, dllimport=True)
Get a Python object through its C-accessible *name* (e.g. "PyExc_ValueError"). The underlying variable must be a `PyObject *`, and the value of that pointer is returned.
Get a Python object through its C-accessible *name* (e.g. "PyExc_ValueError"). The underlying variable must be a `PyObject *`, and the value of that pointer is returned.
[ "Get", "a", "Python", "object", "through", "its", "C", "-", "accessible", "*", "name", "*", "(", "e", ".", "g", ".", "PyExc_ValueError", ")", ".", "The", "underlying", "variable", "must", "be", "a", "PyObject", "*", "and", "the", "value", "of", "that", "pointer", "is", "returned", "." ]
def get_c_object(self, name): """ Get a Python object through its C-accessible *name* (e.g. "PyExc_ValueError"). The underlying variable must be a `PyObject *`, and the value of that pointer is returned. """ # A LLVM global variable is implicitly a pointer to the declared # type, so fix up by using pyobj.pointee. return self.context.get_c_value(self.builder, self.pyobj.pointee, name, dllimport=True)
[ "def", "get_c_object", "(", "self", ",", "name", ")", ":", "# A LLVM global variable is implicitly a pointer to the declared", "# type, so fix up by using pyobj.pointee.", "return", "self", ".", "context", ".", "get_c_value", "(", "self", ".", "builder", ",", "self", ".", "pyobj", ".", "pointee", ",", "name", ",", "dllimport", "=", "True", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/pythonapi.py#L360-L369
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/prepare_binding_Python.py
python
run_python_script
(script_and_args)
Runs a python script, logging appropriately. If the command returns anything non-zero, it is registered as an error and exits the program. @param script_and_args the python script to execute, along with the command line arguments to pass to it.
Runs a python script, logging appropriately.
[ "Runs", "a", "python", "script", "logging", "appropriately", "." ]
def run_python_script(script_and_args): """Runs a python script, logging appropriately. If the command returns anything non-zero, it is registered as an error and exits the program. @param script_and_args the python script to execute, along with the command line arguments to pass to it. """ command = [sys.executable] + script_and_args process = subprocess.Popen(command) script_stdout, script_stderr = process.communicate() return_code = process.returncode if return_code != 0: logging.error("failed to run %r: %r", command, script_stderr) sys.exit(return_code) else: logging.info("ran script %r'", command) if script_stdout is not None: logging.info("output: %s", script_stdout)
[ "def", "run_python_script", "(", "script_and_args", ")", ":", "command", "=", "[", "sys", ".", "executable", "]", "+", "script_and_args", "process", "=", "subprocess", ".", "Popen", "(", "command", ")", "script_stdout", ",", "script_stderr", "=", "process", ".", "communicate", "(", ")", "return_code", "=", "process", ".", "returncode", "if", "return_code", "!=", "0", ":", "logging", ".", "error", "(", "\"failed to run %r: %r\"", ",", "command", ",", "script_stderr", ")", "sys", ".", "exit", "(", "return_code", ")", "else", ":", "logging", ".", "info", "(", "\"ran script %r'\"", ",", "command", ")", "if", "script_stdout", "is", "not", "None", ":", "logging", ".", "info", "(", "\"output: %s\"", ",", "script_stdout", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/prepare_binding_Python.py#L345-L364
larroy/clearskies_core
3574ddf0edc8555454c7044126e786a6c29444dc
tools/gyp/pylib/gyp/ordered_dict.py
python
OrderedDict.items
(self)
return [(key, self[key]) for key in self]
od.items() -> list of (key, value) pairs in od
od.items() -> list of (key, value) pairs in od
[ "od", ".", "items", "()", "-", ">", "list", "of", "(", "key", "value", ")", "pairs", "in", "od" ]
def items(self): 'od.items() -> list of (key, value) pairs in od' return [(key, self[key]) for key in self]
[ "def", "items", "(", "self", ")", ":", "return", "[", "(", "key", ",", "self", "[", "key", "]", ")", "for", "key", "in", "self", "]" ]
https://github.com/larroy/clearskies_core/blob/3574ddf0edc8555454c7044126e786a6c29444dc/tools/gyp/pylib/gyp/ordered_dict.py#L151-L153
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/py_vulcanize/third_party/rcssmin/_setup/py2/commands.py
python
Build.finalize_options
(self)
Finalize options
Finalize options
[ "Finalize", "options" ]
def finalize_options(self): """ Finalize options """ _build.build.finalize_options(self) if _option_inherits.has_key('build'): for parent, opt_name in _option_inherits['build']: self.set_undefined_options(parent, (opt_name, opt_name)) if _option_finalizers.has_key('build'): for func in _option_finalizers['build'].values(): func(self)
[ "def", "finalize_options", "(", "self", ")", ":", "_build", ".", "build", ".", "finalize_options", "(", "self", ")", "if", "_option_inherits", ".", "has_key", "(", "'build'", ")", ":", "for", "parent", ",", "opt_name", "in", "_option_inherits", "[", "'build'", "]", ":", "self", ".", "set_undefined_options", "(", "parent", ",", "(", "opt_name", ",", "opt_name", ")", ")", "if", "_option_finalizers", ".", "has_key", "(", "'build'", ")", ":", "for", "func", "in", "_option_finalizers", "[", "'build'", "]", ".", "values", "(", ")", ":", "func", "(", "self", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/py_vulcanize/third_party/rcssmin/_setup/py2/commands.py#L259-L267
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
gpu/command_buffer/build_gles2_cmd_buffer.py
python
ImmediateFunction.WriteFormatTest
(self, file)
Overridden from Function
Overridden from Function
[ "Overridden", "from", "Function" ]
def WriteFormatTest(self, file): """Overridden from Function""" self.type_handler.WriteImmediateFormatTest(self, file)
[ "def", "WriteFormatTest", "(", "self", ",", "file", ")", ":", "self", ".", "type_handler", ".", "WriteImmediateFormatTest", "(", "self", ",", "file", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/gpu/command_buffer/build_gles2_cmd_buffer.py#L6750-L6752
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/server/wsgi/serve/snippets/util/path_utils.py
python
MakeOldStyle
(newstyle_fieldpath)
return oldstyle
New style: a.b.000003.c -> old style: a.b[3].c . Args: newstyle_fieldpath: new-style path to convert. Returns: Old-style version of path.
New style: a.b.000003.c -> old style: a.b[3].c .
[ "New", "style", ":", "a", ".", "b", ".", "000003", ".", "c", "-", ">", "old", "style", ":", "a", ".", "b", "[", "3", "]", ".", "c", "." ]
def MakeOldStyle(newstyle_fieldpath): """New style: a.b.000003.c -> old style: a.b[3].c . Args: newstyle_fieldpath: new-style path to convert. Returns: Old-style version of path. """ tokens = newstyle_fieldpath.split(".") oldstyle = "" is_first = True for token in tokens: if token.isdigit(): assert not is_first, "indexes are never first" oldstyle += "[%d]" % int(token) else: oldstyle += token if is_first else "." + token is_first = False return oldstyle
[ "def", "MakeOldStyle", "(", "newstyle_fieldpath", ")", ":", "tokens", "=", "newstyle_fieldpath", ".", "split", "(", "\".\"", ")", "oldstyle", "=", "\"\"", "is_first", "=", "True", "for", "token", "in", "tokens", ":", "if", "token", ".", "isdigit", "(", ")", ":", "assert", "not", "is_first", ",", "\"indexes are never first\"", "oldstyle", "+=", "\"[%d]\"", "%", "int", "(", "token", ")", "else", ":", "oldstyle", "+=", "token", "if", "is_first", "else", "\".\"", "+", "token", "is_first", "=", "False", "return", "oldstyle" ]
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/server/wsgi/serve/snippets/util/path_utils.py#L271-L289
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
IndividualLayoutConstraint.Below
(*args, **kwargs)
return _core_.IndividualLayoutConstraint_Below(*args, **kwargs)
Below(self, Window sibling, int marg=0) Constrains this edge to be below the given window, with an optional margin. Implicitly, this is relative to the bottom edge of the other window.
Below(self, Window sibling, int marg=0)
[ "Below", "(", "self", "Window", "sibling", "int", "marg", "=", "0", ")" ]
def Below(*args, **kwargs): """ Below(self, Window sibling, int marg=0) Constrains this edge to be below the given window, with an optional margin. Implicitly, this is relative to the bottom edge of the other window. """ return _core_.IndividualLayoutConstraint_Below(*args, **kwargs)
[ "def", "Below", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "IndividualLayoutConstraint_Below", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L16162-L16170
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Source/ThirdParty/CEF3/pristine/cef_source/tools/cefbuilds/cef_json_builder.py
python
cef_json_builder.get_files
(self, platform=None, version=None, type=None)
return results
Return the files that match the input parameters. All parameters are optional. Version will do partial matching.
Return the files that match the input parameters. All parameters are optional. Version will do partial matching.
[ "Return", "the", "files", "that", "match", "the", "input", "parameters", ".", "All", "parameters", "are", "optional", ".", "Version", "will", "do", "partial", "matching", "." ]
def get_files(self, platform=None, version=None, type=None): """ Return the files that match the input parameters. All parameters are optional. Version will do partial matching. """ results = [] if platform is None: platforms = self._data.keys() else: platforms = [platform] for platform in platforms: for version_obj in self._data[platform]['versions']: if version is None or version_obj['cef_version'].find(version) == 0: for file_obj in version_obj['files']: if type is None or type == file_obj['type']: result_obj = file_obj; # Add additional metadata. result_obj['platform'] = platform result_obj['cef_version'] = version_obj['cef_version'] result_obj['chromium_version'] = version_obj['chromium_version'] results.append(result_obj) return results
[ "def", "get_files", "(", "self", ",", "platform", "=", "None", ",", "version", "=", "None", ",", "type", "=", "None", ")", ":", "results", "=", "[", "]", "if", "platform", "is", "None", ":", "platforms", "=", "self", ".", "_data", ".", "keys", "(", ")", "else", ":", "platforms", "=", "[", "platform", "]", "for", "platform", "in", "platforms", ":", "for", "version_obj", "in", "self", ".", "_data", "[", "platform", "]", "[", "'versions'", "]", ":", "if", "version", "is", "None", "or", "version_obj", "[", "'cef_version'", "]", ".", "find", "(", "version", ")", "==", "0", ":", "for", "file_obj", "in", "version_obj", "[", "'files'", "]", ":", "if", "type", "is", "None", "or", "type", "==", "file_obj", "[", "'type'", "]", ":", "result_obj", "=", "file_obj", "# Add additional metadata.", "result_obj", "[", "'platform'", "]", "=", "platform", "result_obj", "[", "'cef_version'", "]", "=", "version_obj", "[", "'cef_version'", "]", "result_obj", "[", "'chromium_version'", "]", "=", "version_obj", "[", "'chromium_version'", "]", "results", ".", "append", "(", "result_obj", ")", "return", "results" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Source/ThirdParty/CEF3/pristine/cef_source/tools/cefbuilds/cef_json_builder.py#L408-L430
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/_extends/parse/standard_method.py
python
scalar_floordiv
(x, y)
return x.__floordiv__(y)
Implementation of `scalar_floordiv`.
Implementation of `scalar_floordiv`.
[ "Implementation", "of", "scalar_floordiv", "." ]
def scalar_floordiv(x, y): """Implementation of `scalar_floordiv`.""" return x.__floordiv__(y)
[ "def", "scalar_floordiv", "(", "x", ",", "y", ")", ":", "return", "x", ".", "__floordiv__", "(", "y", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/_extends/parse/standard_method.py#L1473-L1475
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/bitstring/bitstring.py
python
Bits._set
(self, pos)
Set bit at pos to 1.
Set bit at pos to 1.
[ "Set", "bit", "at", "pos", "to", "1", "." ]
def _set(self, pos): """Set bit at pos to 1.""" assert 0 <= pos < self.len self._datastore.setbit(pos)
[ "def", "_set", "(", "self", ",", "pos", ")", ":", "assert", "0", "<=", "pos", "<", "self", ".", "len", "self", ".", "_datastore", ".", "setbit", "(", "pos", ")" ]
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/bitstring/bitstring.py#L2153-L2156
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/tools/cpplint.py
python
NestingState.SeenOpenBrace
(self)
return (not self.stack) or self.stack[-1].seen_open_brace
Check if we have seen the opening brace for the innermost block. Returns: True if we have seen the opening brace, False if the innermost block is still expecting an opening brace.
Check if we have seen the opening brace for the innermost block.
[ "Check", "if", "we", "have", "seen", "the", "opening", "brace", "for", "the", "innermost", "block", "." ]
def SeenOpenBrace(self): """Check if we have seen the opening brace for the innermost block. Returns: True if we have seen the opening brace, False if the innermost block is still expecting an opening brace. """ return (not self.stack) or self.stack[-1].seen_open_brace
[ "def", "SeenOpenBrace", "(", "self", ")", ":", "return", "(", "not", "self", ".", "stack", ")", "or", "self", ".", "stack", "[", "-", "1", "]", ".", "seen_open_brace" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/cpplint.py#L2951-L2958
fatih/subvim
241b6d170597857105da219c9b7d36059e9f11fb
vim/base/YouCompleteMe/third_party/requests/requests/api.py
python
head
(url, **kwargs)
return request('head', url, **kwargs)
Sends a HEAD request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes.
Sends a HEAD request. Returns :class:`Response` object.
[ "Sends", "a", "HEAD", "request", ".", "Returns", ":", "class", ":", "Response", "object", "." ]
def head(url, **kwargs): """Sends a HEAD request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. """ kwargs.setdefault('allow_redirects', False) return request('head', url, **kwargs)
[ "def", "head", "(", "url", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'allow_redirects'", ",", "False", ")", "return", "request", "(", "'head'", ",", "url", ",", "*", "*", "kwargs", ")" ]
https://github.com/fatih/subvim/blob/241b6d170597857105da219c9b7d36059e9f11fb/vim/base/YouCompleteMe/third_party/requests/requests/api.py#L69-L77
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/ensemble/_stacking.py
python
StackingClassifier.predict_proba
(self, X)
return self.final_estimator_.predict_proba(self.transform(X))
Predict class probabilities for X using `final_estimator_.predict_proba`. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training vectors, where n_samples is the number of samples and n_features is the number of features. Returns ------- probabilities : ndarray of shape (n_samples, n_classes) or \ list of ndarray of shape (n_output,) The class probabilities of the input samples.
Predict class probabilities for X using `final_estimator_.predict_proba`.
[ "Predict", "class", "probabilities", "for", "X", "using", "final_estimator_", ".", "predict_proba", "." ]
def predict_proba(self, X): """Predict class probabilities for X using `final_estimator_.predict_proba`. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training vectors, where n_samples is the number of samples and n_features is the number of features. Returns ------- probabilities : ndarray of shape (n_samples, n_classes) or \ list of ndarray of shape (n_output,) The class probabilities of the input samples. """ check_is_fitted(self) return self.final_estimator_.predict_proba(self.transform(X))
[ "def", "predict_proba", "(", "self", ",", "X", ")", ":", "check_is_fitted", "(", "self", ")", "return", "self", ".", "final_estimator_", ".", "predict_proba", "(", "self", ".", "transform", "(", "X", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/ensemble/_stacking.py#L440-L457
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/receptive_field/python/util/receptive_field.py
python
ReceptiveField.compute_input_center_coordinates
(self, y, axis=None)
return -self.padding[axis] + y * self.stride[axis] + ( self.size[axis] - 1) / 2
Computes the center of the receptive field that generated a feature. Args: y: An array of feature coordinates with shape `(..., d)`, where `d` is the number of dimensions of the coordinates. axis: The dimensions for which to compute the input center coordinates. If `None` (the default), compute the input center coordinates for all dimensions. Returns: x: Center of the receptive field that generated the features, at the input of the network. Raises: ValueError: If the number of dimensions of the feature coordinates does not match the number of elements in `axis`.
Computes the center of the receptive field that generated a feature.
[ "Computes", "the", "center", "of", "the", "receptive", "field", "that", "generated", "a", "feature", "." ]
def compute_input_center_coordinates(self, y, axis=None): """Computes the center of the receptive field that generated a feature. Args: y: An array of feature coordinates with shape `(..., d)`, where `d` is the number of dimensions of the coordinates. axis: The dimensions for which to compute the input center coordinates. If `None` (the default), compute the input center coordinates for all dimensions. Returns: x: Center of the receptive field that generated the features, at the input of the network. Raises: ValueError: If the number of dimensions of the feature coordinates does not match the number of elements in `axis`. """ # Use all dimensions. if axis is None: axis = range(self.size.size) # Ensure axis is a list because tuples have different indexing behavior. axis = list(axis) y = np.asarray(y) if y.shape[-1] != len(axis): raise ValueError("Dimensionality of the feature coordinates `y` (%d) " "does not match dimensionality of `axis` (%d)" % (y.shape[-1], len(axis))) return -self.padding[axis] + y * self.stride[axis] + ( self.size[axis] - 1) / 2
[ "def", "compute_input_center_coordinates", "(", "self", ",", "y", ",", "axis", "=", "None", ")", ":", "# Use all dimensions.", "if", "axis", "is", "None", ":", "axis", "=", "range", "(", "self", ".", "size", ".", "size", ")", "# Ensure axis is a list because tuples have different indexing behavior.", "axis", "=", "list", "(", "axis", ")", "y", "=", "np", ".", "asarray", "(", "y", ")", "if", "y", ".", "shape", "[", "-", "1", "]", "!=", "len", "(", "axis", ")", ":", "raise", "ValueError", "(", "\"Dimensionality of the feature coordinates `y` (%d) \"", "\"does not match dimensionality of `axis` (%d)\"", "%", "(", "y", ".", "shape", "[", "-", "1", "]", ",", "len", "(", "axis", ")", ")", ")", "return", "-", "self", ".", "padding", "[", "axis", "]", "+", "y", "*", "self", ".", "stride", "[", "axis", "]", "+", "(", "self", ".", "size", "[", "axis", "]", "-", "1", ")", "/", "2" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/receptive_field/python/util/receptive_field.py#L88-L117
facebookresearch/habitat-sim
63b6c71d9ca8adaefb140b198196f5d0ca1f1e34
examples/fairmotion_interface.py
python
FairmotionInterface.next_pose
(self, repeat=False, step_size=None)
Set the model state from the next frame in the motion trajectory. `repeat` is set to `True` when the user would like to repeat the last frame.
Set the model state from the next frame in the motion trajectory. `repeat` is set to `True` when the user would like to repeat the last frame.
[ "Set", "the", "model", "state", "from", "the", "next", "frame", "in", "the", "motion", "trajectory", ".", "repeat", "is", "set", "to", "True", "when", "the", "user", "would", "like", "to", "repeat", "the", "last", "frame", "." ]
def next_pose(self, repeat=False, step_size=None) -> None: """ Set the model state from the next frame in the motion trajectory. `repeat` is set to `True` when the user would like to repeat the last frame. """ # precondition if not all([self.model, self.motion, self.activity == Activity.MOTION_STAGE]): return # tracks is_reversed and changes the direction of the motion accordingly. def sign(i): return -1 * i if self.is_reversed else i step_size = step_size or int(self.motion.fps / self.draw_fps) # repeat if not repeat: # iterate the frame counter self.motion_stepper = ( self.motion_stepper + sign(step_size) ) % self.motion.num_frames() ( new_pose, new_root_translate, new_root_rotation, ) = self.convert_CMUamass_single_pose( self.motion.poses[abs(self.motion_stepper)], self.model ) self.model.joint_positions = new_pose self.model.rotation = new_root_rotation self.model.translation = new_root_translate
[ "def", "next_pose", "(", "self", ",", "repeat", "=", "False", ",", "step_size", "=", "None", ")", "->", "None", ":", "# precondition", "if", "not", "all", "(", "[", "self", ".", "model", ",", "self", ".", "motion", ",", "self", ".", "activity", "==", "Activity", ".", "MOTION_STAGE", "]", ")", ":", "return", "# tracks is_reversed and changes the direction of the motion accordingly.", "def", "sign", "(", "i", ")", ":", "return", "-", "1", "*", "i", "if", "self", ".", "is_reversed", "else", "i", "step_size", "=", "step_size", "or", "int", "(", "self", ".", "motion", ".", "fps", "/", "self", ".", "draw_fps", ")", "# repeat", "if", "not", "repeat", ":", "# iterate the frame counter", "self", ".", "motion_stepper", "=", "(", "self", ".", "motion_stepper", "+", "sign", "(", "step_size", ")", ")", "%", "self", ".", "motion", ".", "num_frames", "(", ")", "(", "new_pose", ",", "new_root_translate", ",", "new_root_rotation", ",", ")", "=", "self", ".", "convert_CMUamass_single_pose", "(", "self", ".", "motion", ".", "poses", "[", "abs", "(", "self", ".", "motion_stepper", ")", "]", ",", "self", ".", "model", ")", "self", ".", "model", ".", "joint_positions", "=", "new_pose", "self", ".", "model", ".", "rotation", "=", "new_root_rotation", "self", ".", "model", ".", "translation", "=", "new_root_translate" ]
https://github.com/facebookresearch/habitat-sim/blob/63b6c71d9ca8adaefb140b198196f5d0ca1f1e34/examples/fairmotion_interface.py#L346-L378
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
src/pybind/mgr/cli_api/module.py
python
CephCommander.to_ceph_signature
(self)
return { 'prefix': f'mgr cli {self.func.__name__}', 'perm': API.perm.get(self.func) }
Generate CephCommand signature (dict-like)
Generate CephCommand signature (dict-like)
[ "Generate", "CephCommand", "signature", "(", "dict", "-", "like", ")" ]
def to_ceph_signature(self) -> Dict[str, str]: """ Generate CephCommand signature (dict-like) """ return { 'prefix': f'mgr cli {self.func.__name__}', 'perm': API.perm.get(self.func) }
[ "def", "to_ceph_signature", "(", "self", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "return", "{", "'prefix'", ":", "f'mgr cli {self.func.__name__}'", ",", "'perm'", ":", "API", ".", "perm", ".", "get", "(", "self", ".", "func", ")", "}" ]
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/pybind/mgr/cli_api/module.py#L31-L38
Constellation/iv
64c3a9c7c517063f29d90d449180ea8f6f4d946f
tools/cpplint.py
python
FileInfo.NoExtension
(self)
return '/'.join(self.Split()[0:2])
File has no source file extension.
File has no source file extension.
[ "File", "has", "no", "source", "file", "extension", "." ]
def NoExtension(self): """File has no source file extension.""" return '/'.join(self.Split()[0:2])
[ "def", "NoExtension", "(", "self", ")", ":", "return", "'/'", ".", "join", "(", "self", ".", "Split", "(", ")", "[", "0", ":", "2", "]", ")" ]
https://github.com/Constellation/iv/blob/64c3a9c7c517063f29d90d449180ea8f6f4d946f/tools/cpplint.py#L940-L942
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/arrays/datetimes.py
python
_validate_dt64_dtype
(dtype)
return dtype
Check that a dtype, if passed, represents either a numpy datetime64[ns] dtype or a pandas DatetimeTZDtype. Parameters ---------- dtype : object Returns ------- dtype : None, numpy.dtype, or DatetimeTZDtype Raises ------ ValueError : invalid dtype Notes ----- Unlike validate_tz_from_dtype, this does _not_ allow non-existent tz errors to go through
Check that a dtype, if passed, represents either a numpy datetime64[ns] dtype or a pandas DatetimeTZDtype.
[ "Check", "that", "a", "dtype", "if", "passed", "represents", "either", "a", "numpy", "datetime64", "[", "ns", "]", "dtype", "or", "a", "pandas", "DatetimeTZDtype", "." ]
def _validate_dt64_dtype(dtype): """ Check that a dtype, if passed, represents either a numpy datetime64[ns] dtype or a pandas DatetimeTZDtype. Parameters ---------- dtype : object Returns ------- dtype : None, numpy.dtype, or DatetimeTZDtype Raises ------ ValueError : invalid dtype Notes ----- Unlike validate_tz_from_dtype, this does _not_ allow non-existent tz errors to go through """ if dtype is not None: dtype = pandas_dtype(dtype) if is_dtype_equal(dtype, np.dtype("M8")): # no precision, warn dtype = _NS_DTYPE msg = textwrap.dedent("""\ Passing in 'datetime64' dtype with no precision is deprecated and will raise in a future version. Please pass in 'datetime64[ns]' instead.""") warnings.warn(msg, FutureWarning, stacklevel=5) if ((isinstance(dtype, np.dtype) and dtype != _NS_DTYPE) or not isinstance(dtype, (np.dtype, DatetimeTZDtype))): raise ValueError("Unexpected value for 'dtype': '{dtype}'. " "Must be 'datetime64[ns]' or DatetimeTZDtype'." .format(dtype=dtype)) return dtype
[ "def", "_validate_dt64_dtype", "(", "dtype", ")", ":", "if", "dtype", "is", "not", "None", ":", "dtype", "=", "pandas_dtype", "(", "dtype", ")", "if", "is_dtype_equal", "(", "dtype", ",", "np", ".", "dtype", "(", "\"M8\"", ")", ")", ":", "# no precision, warn", "dtype", "=", "_NS_DTYPE", "msg", "=", "textwrap", ".", "dedent", "(", "\"\"\"\\\n Passing in 'datetime64' dtype with no precision is deprecated\n and will raise in a future version. Please pass in\n 'datetime64[ns]' instead.\"\"\"", ")", "warnings", ".", "warn", "(", "msg", ",", "FutureWarning", ",", "stacklevel", "=", "5", ")", "if", "(", "(", "isinstance", "(", "dtype", ",", "np", ".", "dtype", ")", "and", "dtype", "!=", "_NS_DTYPE", ")", "or", "not", "isinstance", "(", "dtype", ",", "(", "np", ".", "dtype", ",", "DatetimeTZDtype", ")", ")", ")", ":", "raise", "ValueError", "(", "\"Unexpected value for 'dtype': '{dtype}'. \"", "\"Must be 'datetime64[ns]' or DatetimeTZDtype'.\"", ".", "format", "(", "dtype", "=", "dtype", ")", ")", "return", "dtype" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/arrays/datetimes.py#L1979-L2017
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/closure_linter/closure_linter/statetracker.py
python
DocComment.CompareParameters
(self, params)
return distance[source_len][target_len], edit_lists[source_len][target_len]
Computes the edit distance and list from the function params to the docs. Uses the Levenshtein edit distance algorithm, with code modified from http://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Levenshtein_distance#Python Args: params: The parameter list for the function declaration. Returns: The edit distance, the edit list.
Computes the edit distance and list from the function params to the docs.
[ "Computes", "the", "edit", "distance", "and", "list", "from", "the", "function", "params", "to", "the", "docs", "." ]
def CompareParameters(self, params): """Computes the edit distance and list from the function params to the docs. Uses the Levenshtein edit distance algorithm, with code modified from http://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Levenshtein_distance#Python Args: params: The parameter list for the function declaration. Returns: The edit distance, the edit list. """ source_len, target_len = len(self.ordered_params), len(params) edit_lists = [[]] distance = [[]] for i in range(target_len+1): edit_lists[0].append(['I'] * i) distance[0].append(i) for j in range(1, source_len+1): edit_lists.append([['D'] * j]) distance.append([j]) for i in range(source_len): for j in range(target_len): cost = 1 if self.ordered_params[i] == params[j]: cost = 0 deletion = distance[i][j+1] + 1 insertion = distance[i+1][j] + 1 substitution = distance[i][j] + cost edit_list = None best = None if deletion <= insertion and deletion <= substitution: # Deletion is best. best = deletion edit_list = list(edit_lists[i][j+1]) edit_list.append('D') elif insertion <= substitution: # Insertion is best. best = insertion edit_list = list(edit_lists[i+1][j]) edit_list.append('I') edit_lists[i+1].append(edit_list) else: # Substitution is best. best = substitution edit_list = list(edit_lists[i][j]) if cost: edit_list.append('S') else: edit_list.append('=') edit_lists[i+1].append(edit_list) distance[i+1].append(best) return distance[source_len][target_len], edit_lists[source_len][target_len]
[ "def", "CompareParameters", "(", "self", ",", "params", ")", ":", "source_len", ",", "target_len", "=", "len", "(", "self", ".", "ordered_params", ")", ",", "len", "(", "params", ")", "edit_lists", "=", "[", "[", "]", "]", "distance", "=", "[", "[", "]", "]", "for", "i", "in", "range", "(", "target_len", "+", "1", ")", ":", "edit_lists", "[", "0", "]", ".", "append", "(", "[", "'I'", "]", "*", "i", ")", "distance", "[", "0", "]", ".", "append", "(", "i", ")", "for", "j", "in", "range", "(", "1", ",", "source_len", "+", "1", ")", ":", "edit_lists", ".", "append", "(", "[", "[", "'D'", "]", "*", "j", "]", ")", "distance", ".", "append", "(", "[", "j", "]", ")", "for", "i", "in", "range", "(", "source_len", ")", ":", "for", "j", "in", "range", "(", "target_len", ")", ":", "cost", "=", "1", "if", "self", ".", "ordered_params", "[", "i", "]", "==", "params", "[", "j", "]", ":", "cost", "=", "0", "deletion", "=", "distance", "[", "i", "]", "[", "j", "+", "1", "]", "+", "1", "insertion", "=", "distance", "[", "i", "+", "1", "]", "[", "j", "]", "+", "1", "substitution", "=", "distance", "[", "i", "]", "[", "j", "]", "+", "cost", "edit_list", "=", "None", "best", "=", "None", "if", "deletion", "<=", "insertion", "and", "deletion", "<=", "substitution", ":", "# Deletion is best.", "best", "=", "deletion", "edit_list", "=", "list", "(", "edit_lists", "[", "i", "]", "[", "j", "+", "1", "]", ")", "edit_list", ".", "append", "(", "'D'", ")", "elif", "insertion", "<=", "substitution", ":", "# Insertion is best.", "best", "=", "insertion", "edit_list", "=", "list", "(", "edit_lists", "[", "i", "+", "1", "]", "[", "j", "]", ")", "edit_list", ".", "append", "(", "'I'", ")", "edit_lists", "[", "i", "+", "1", "]", ".", "append", "(", "edit_list", ")", "else", ":", "# Substitution is best.", "best", "=", "substitution", "edit_list", "=", "list", "(", "edit_lists", "[", "i", "]", "[", "j", "]", ")", "if", "cost", ":", "edit_list", ".", "append", "(", "'S'", ")", "else", ":", "edit_list", ".", "append", "(", "'='", ")", "edit_lists", "[", "i", "+", "1", "]", ".", "append", "(", "edit_list", ")", "distance", "[", "i", "+", "1", "]", ".", "append", "(", "best", ")", "return", "distance", "[", "source_len", "]", "[", "target_len", "]", ",", "edit_lists", "[", "source_len", "]", "[", "target_len", "]" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/closure_linter/closure_linter/statetracker.py#L507-L567
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/syntax/_issuelist.py
python
SyntaxData.GetSyntaxSpec
(self)
return SYNTAX_ITEMS
Syntax Specifications
Syntax Specifications
[ "Syntax", "Specifications" ]
def GetSyntaxSpec(self): """Syntax Specifications """ return SYNTAX_ITEMS
[ "def", "GetSyntaxSpec", "(", "self", ")", ":", "return", "SYNTAX_ITEMS" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/syntax/_issuelist.py#L74-L76
mozilla/DeepSpeech
aa1d28530d531d0d92289bf5f11a49fe516fdc86
training/deepspeech_training/util/sample_collections.py
python
CSV.__init__
(self, csv_filename, labeled=None, reverse=False)
Parameters ---------- csv_filename : str Path to the CSV file containing sample audio paths and transcripts labeled : bool or None If True: Reads LabeledSample instances. Fails, if CSV file has no transcript column. If False: Ignores transcripts (if available) and reads (unlabeled) util.audio.Sample instances. If None: Automatically determines if CSV file has a transcript column (reading util.sample_collections.LabeledSample instances) or not (reading util.audio.Sample instances). reverse : bool If the order of the samples should be reversed
Parameters ---------- csv_filename : str Path to the CSV file containing sample audio paths and transcripts labeled : bool or None If True: Reads LabeledSample instances. Fails, if CSV file has no transcript column. If False: Ignores transcripts (if available) and reads (unlabeled) util.audio.Sample instances. If None: Automatically determines if CSV file has a transcript column (reading util.sample_collections.LabeledSample instances) or not (reading util.audio.Sample instances). reverse : bool If the order of the samples should be reversed
[ "Parameters", "----------", "csv_filename", ":", "str", "Path", "to", "the", "CSV", "file", "containing", "sample", "audio", "paths", "and", "transcripts", "labeled", ":", "bool", "or", "None", "If", "True", ":", "Reads", "LabeledSample", "instances", ".", "Fails", "if", "CSV", "file", "has", "no", "transcript", "column", ".", "If", "False", ":", "Ignores", "transcripts", "(", "if", "available", ")", "and", "reads", "(", "unlabeled", ")", "util", ".", "audio", ".", "Sample", "instances", ".", "If", "None", ":", "Automatically", "determines", "if", "CSV", "file", "has", "a", "transcript", "column", "(", "reading", "util", ".", "sample_collections", ".", "LabeledSample", "instances", ")", "or", "not", "(", "reading", "util", ".", "audio", ".", "Sample", "instances", ")", ".", "reverse", ":", "bool", "If", "the", "order", "of", "the", "samples", "should", "be", "reversed" ]
def __init__(self, csv_filename, labeled=None, reverse=False): """ Parameters ---------- csv_filename : str Path to the CSV file containing sample audio paths and transcripts labeled : bool or None If True: Reads LabeledSample instances. Fails, if CSV file has no transcript column. If False: Ignores transcripts (if available) and reads (unlabeled) util.audio.Sample instances. If None: Automatically determines if CSV file has a transcript column (reading util.sample_collections.LabeledSample instances) or not (reading util.audio.Sample instances). reverse : bool If the order of the samples should be reversed """ rows = [] with open_remote(csv_filename, 'r', encoding='utf8') as csv_file: reader = csv.DictReader(csv_file) if 'transcript' in reader.fieldnames: if labeled is None: labeled = True elif labeled: raise RuntimeError('No transcript data (missing CSV column)') for row in reader: wav_filename = Path(row['wav_filename']) if not wav_filename.is_absolute() and not is_remote_path(row['wav_filename']): wav_filename = Path(csv_filename).parent / wav_filename wav_filename = str(wav_filename) else: # Pathlib otherwise removes a / from filenames like hdfs:// wav_filename = row['wav_filename'] wav_filesize = int(row['wav_filesize']) if 'wav_filesize' in row else 0 if labeled: rows.append((wav_filename, wav_filesize, row['transcript'])) else: rows.append((wav_filename, wav_filesize)) super(CSV, self).__init__(rows, labeled=labeled, reverse=reverse)
[ "def", "__init__", "(", "self", ",", "csv_filename", ",", "labeled", "=", "None", ",", "reverse", "=", "False", ")", ":", "rows", "=", "[", "]", "with", "open_remote", "(", "csv_filename", ",", "'r'", ",", "encoding", "=", "'utf8'", ")", "as", "csv_file", ":", "reader", "=", "csv", ".", "DictReader", "(", "csv_file", ")", "if", "'transcript'", "in", "reader", ".", "fieldnames", ":", "if", "labeled", "is", "None", ":", "labeled", "=", "True", "elif", "labeled", ":", "raise", "RuntimeError", "(", "'No transcript data (missing CSV column)'", ")", "for", "row", "in", "reader", ":", "wav_filename", "=", "Path", "(", "row", "[", "'wav_filename'", "]", ")", "if", "not", "wav_filename", ".", "is_absolute", "(", ")", "and", "not", "is_remote_path", "(", "row", "[", "'wav_filename'", "]", ")", ":", "wav_filename", "=", "Path", "(", "csv_filename", ")", ".", "parent", "/", "wav_filename", "wav_filename", "=", "str", "(", "wav_filename", ")", "else", ":", "# Pathlib otherwise removes a / from filenames like hdfs://", "wav_filename", "=", "row", "[", "'wav_filename'", "]", "wav_filesize", "=", "int", "(", "row", "[", "'wav_filesize'", "]", ")", "if", "'wav_filesize'", "in", "row", "else", "0", "if", "labeled", ":", "rows", ".", "append", "(", "(", "wav_filename", ",", "wav_filesize", ",", "row", "[", "'transcript'", "]", ")", ")", "else", ":", "rows", ".", "append", "(", "(", "wav_filename", ",", "wav_filesize", ")", ")", "super", "(", "CSV", ",", "self", ")", ".", "__init__", "(", "rows", ",", "labeled", "=", "labeled", ",", "reverse", "=", "reverse", ")" ]
https://github.com/mozilla/DeepSpeech/blob/aa1d28530d531d0d92289bf5f11a49fe516fdc86/training/deepspeech_training/util/sample_collections.py#L519-L554
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/model.py
python
Shape.metadata
(self)
return metadata
Metadata about the shape. This requires optional information about the shape, including: * min * max * enum * sensitive * required * idempotencyToken :rtype: dict :return: Metadata about the shape.
Metadata about the shape.
[ "Metadata", "about", "the", "shape", "." ]
def metadata(self): """Metadata about the shape. This requires optional information about the shape, including: * min * max * enum * sensitive * required * idempotencyToken :rtype: dict :return: Metadata about the shape. """ model = self._shape_model metadata = {} for attr in self.METADATA_ATTRS: if attr in self._shape_model: metadata[attr] = model[attr] return metadata
[ "def", "metadata", "(", "self", ")", ":", "model", "=", "self", ".", "_shape_model", "metadata", "=", "{", "}", "for", "attr", "in", "self", ".", "METADATA_ATTRS", ":", "if", "attr", "in", "self", ".", "_shape_model", ":", "metadata", "[", "attr", "]", "=", "model", "[", "attr", "]", "return", "metadata" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/model.py#L129-L150
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/ContainerIO.py
python
ContainerIO.readline
(self)
return s
Read a line of text. :returns: An 8-bit string.
Read a line of text.
[ "Read", "a", "line", "of", "text", "." ]
def readline(self): """ Read a line of text. :returns: An 8-bit string. """ s = b"" if "b" in self.fh.mode else "" newline_character = b"\n" if "b" in self.fh.mode else "\n" while True: c = self.read(1) if not c: break s = s + c if c == newline_character: break return s
[ "def", "readline", "(", "self", ")", ":", "s", "=", "b\"\"", "if", "\"b\"", "in", "self", ".", "fh", ".", "mode", "else", "\"\"", "newline_character", "=", "b\"\\n\"", "if", "\"b\"", "in", "self", ".", "fh", ".", "mode", "else", "\"\\n\"", "while", "True", ":", "c", "=", "self", ".", "read", "(", "1", ")", "if", "not", "c", ":", "break", "s", "=", "s", "+", "c", "if", "c", "==", "newline_character", ":", "break", "return", "s" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/ContainerIO.py#L89-L104
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/package_index.py
python
PackageIndex.check_hash
(self, checker, filename, tfp)
checker is a ContentChecker
checker is a ContentChecker
[ "checker", "is", "a", "ContentChecker" ]
def check_hash(self, checker, filename, tfp): """ checker is a ContentChecker """ checker.report( self.debug, "Validating %%s checksum for %s" % filename) if not checker.is_valid(): tfp.close() os.unlink(filename) raise DistutilsError( "%s validation failed for %s; " "possible download problem?" % (checker.hash.name, os.path.basename(filename)) )
[ "def", "check_hash", "(", "self", ",", "checker", ",", "filename", ",", "tfp", ")", ":", "checker", ".", "report", "(", "self", ".", "debug", ",", "\"Validating %%s checksum for %s\"", "%", "filename", ")", "if", "not", "checker", ".", "is_valid", "(", ")", ":", "tfp", ".", "close", "(", ")", "os", ".", "unlink", "(", "filename", ")", "raise", "DistutilsError", "(", "\"%s validation failed for %s; \"", "\"possible download problem?\"", "%", "(", "checker", ".", "hash", ".", "name", ",", "os", ".", "path", ".", "basename", "(", "filename", ")", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/package_index.py#L513-L527
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/metrics/pairwise.py
python
haversine_distances
(X, Y=None)
return DistanceMetric.get_metric('haversine').pairwise(X, Y)
Compute the Haversine distance between samples in X and Y The Haversine (or great circle) distance is the angular distance between two points on the surface of a sphere. The first distance of each point is assumed to be the latitude, the second is the longitude, given in radians. The dimension of the data must be 2. .. math:: D(x, y) = 2\\arcsin[\\sqrt{\\sin^2((x1 - y1) / 2) + \\cos(x1)\\cos(y1)\\sin^2((x2 - y2) / 2)}] Parameters ---------- X : array_like, shape (n_samples_1, 2) Y : array_like, shape (n_samples_2, 2), optional Returns ------- distance : {array}, shape (n_samples_1, n_samples_2) Notes ----- As the Earth is nearly spherical, the haversine formula provides a good approximation of the distance between two points of the Earth surface, with a less than 1% error on average. Examples -------- We want to calculate the distance between the Ezeiza Airport (Buenos Aires, Argentina) and the Charles de Gaulle Airport (Paris, France) >>> from sklearn.metrics.pairwise import haversine_distances >>> from math import radians >>> bsas = [-34.83333, -58.5166646] >>> paris = [49.0083899664, 2.53844117956] >>> bsas_in_radians = [radians(_) for _ in bsas] >>> paris_in_radians = [radians(_) for _ in paris] >>> result = haversine_distances([bsas_in_radians, paris_in_radians]) >>> result * 6371000/1000 # multiply by Earth radius to get kilometers array([[ 0. , 11099.54035582], [11099.54035582, 0. ]])
Compute the Haversine distance between samples in X and Y
[ "Compute", "the", "Haversine", "distance", "between", "samples", "in", "X", "and", "Y" ]
def haversine_distances(X, Y=None): """Compute the Haversine distance between samples in X and Y The Haversine (or great circle) distance is the angular distance between two points on the surface of a sphere. The first distance of each point is assumed to be the latitude, the second is the longitude, given in radians. The dimension of the data must be 2. .. math:: D(x, y) = 2\\arcsin[\\sqrt{\\sin^2((x1 - y1) / 2) + \\cos(x1)\\cos(y1)\\sin^2((x2 - y2) / 2)}] Parameters ---------- X : array_like, shape (n_samples_1, 2) Y : array_like, shape (n_samples_2, 2), optional Returns ------- distance : {array}, shape (n_samples_1, n_samples_2) Notes ----- As the Earth is nearly spherical, the haversine formula provides a good approximation of the distance between two points of the Earth surface, with a less than 1% error on average. Examples -------- We want to calculate the distance between the Ezeiza Airport (Buenos Aires, Argentina) and the Charles de Gaulle Airport (Paris, France) >>> from sklearn.metrics.pairwise import haversine_distances >>> from math import radians >>> bsas = [-34.83333, -58.5166646] >>> paris = [49.0083899664, 2.53844117956] >>> bsas_in_radians = [radians(_) for _ in bsas] >>> paris_in_radians = [radians(_) for _ in paris] >>> result = haversine_distances([bsas_in_radians, paris_in_radians]) >>> result * 6371000/1000 # multiply by Earth radius to get kilometers array([[ 0. , 11099.54035582], [11099.54035582, 0. ]]) """ from sklearn.neighbors import DistanceMetric return DistanceMetric.get_metric('haversine').pairwise(X, Y)
[ "def", "haversine_distances", "(", "X", ",", "Y", "=", "None", ")", ":", "from", "sklearn", ".", "neighbors", "import", "DistanceMetric", "return", "DistanceMetric", ".", "get_metric", "(", "'haversine'", ")", ".", "pairwise", "(", "X", ",", "Y", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/metrics/pairwise.py#L666-L711
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/fractions.py
python
Fraction.__neg__
(a)
return Fraction(-a._numerator, a._denominator)
-a
-a
[ "-", "a" ]
def __neg__(a): """-a""" return Fraction(-a._numerator, a._denominator)
[ "def", "__neg__", "(", "a", ")", ":", "return", "Fraction", "(", "-", "a", ".", "_numerator", ",", "a", ".", "_denominator", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/fractions.py#L493-L495
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/compiler-rt/lib/sanitizer_common/scripts/cpplint.py
python
ResetNolintSuppressions
()
Resets the set of NOLINT suppressions to empty.
Resets the set of NOLINT suppressions to empty.
[ "Resets", "the", "set", "of", "NOLINT", "suppressions", "to", "empty", "." ]
def ResetNolintSuppressions(): "Resets the set of NOLINT suppressions to empty." _error_suppressions.clear()
[ "def", "ResetNolintSuppressions", "(", ")", ":", "_error_suppressions", ".", "clear", "(", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L389-L391
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/python/turicreate/meta/asttools/visitors/cond_symbol_visitor.py
python
conditional_symbols
(node)
return lhs, rhs, undefined
Group lhs and rhs into conditional, stable and undefined :param node: ast node :returns: tuple of (conditional_lhs, stable_lhs),(conditional_rhs, stable_rhs), undefined
Group lhs and rhs into conditional, stable and undefined :param node: ast node
[ "Group", "lhs", "and", "rhs", "into", "conditional", "stable", "and", "undefined", ":", "param", "node", ":", "ast", "node" ]
def conditional_symbols(node): """ Group lhs and rhs into conditional, stable and undefined :param node: ast node :returns: tuple of (conditional_lhs, stable_lhs),(conditional_rhs, stable_rhs), undefined """ gen = ConditionalSymbolVisitor() gen.visit(node) lhs = gen.cond_lhs, gen.stable_lhs rhs = gen.cond_rhs, gen.stable_rhs undefined = gen.undefined return lhs, rhs, undefined
[ "def", "conditional_symbols", "(", "node", ")", ":", "gen", "=", "ConditionalSymbolVisitor", "(", ")", "gen", ".", "visit", "(", "node", ")", "lhs", "=", "gen", ".", "cond_lhs", ",", "gen", ".", "stable_lhs", "rhs", "=", "gen", ".", "cond_rhs", ",", "gen", ".", "stable_rhs", "undefined", "=", "gen", ".", "undefined", "return", "lhs", ",", "rhs", ",", "undefined" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/meta/asttools/visitors/cond_symbol_visitor.py#L413-L427
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/io/loader.py
python
readMatrix3
(text)
return so3.matrix(readSo3(text))
Reads a 3x3 matrix from a string
Reads a 3x3 matrix from a string
[ "Reads", "a", "3x3", "matrix", "from", "a", "string" ]
def readMatrix3(text): """Reads a 3x3 matrix from a string""" return so3.matrix(readSo3(text))
[ "def", "readMatrix3", "(", "text", ")", ":", "return", "so3", ".", "matrix", "(", "readSo3", "(", "text", ")", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/io/loader.py#L196-L198
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/framework/ops.py
python
register_dense_tensor_like_type
(tensor_type)
EXPERIMENTAL: Registers `tensor_type` as implementing the tensor interface. A "tensor-like type" can represent a single dense tensor, and implements the `name` and `dtype` properties. Args: tensor_type: A type implementing the tensor interface. Raises: TypeError: If `tensor_type` does not implement the tensor interface.
EXPERIMENTAL: Registers `tensor_type` as implementing the tensor interface.
[ "EXPERIMENTAL", ":", "Registers", "tensor_type", "as", "implementing", "the", "tensor", "interface", "." ]
def register_dense_tensor_like_type(tensor_type): """EXPERIMENTAL: Registers `tensor_type` as implementing the tensor interface. A "tensor-like type" can represent a single dense tensor, and implements the `name` and `dtype` properties. Args: tensor_type: A type implementing the tensor interface. Raises: TypeError: If `tensor_type` does not implement the tensor interface. """ try: if not isinstance(tensor_type.name, property): raise TypeError("Type %s does not define a `name` property") except AttributeError: raise TypeError("Type %s does not define a `name` property") try: if not isinstance(tensor_type.dtype, property): raise TypeError("Type %s does not define a `dtype` property") except AttributeError: raise TypeError("Type %s does not define a `dtype` property") # We expect this list to be small, so choose quadratic complexity # for registration, so that we have a tuple that can be used for # more efficient `isinstance` checks later. global _TENSOR_LIKE_TYPES _TENSOR_LIKE_TYPES = tuple(list(_TENSOR_LIKE_TYPES) + [tensor_type])
[ "def", "register_dense_tensor_like_type", "(", "tensor_type", ")", ":", "try", ":", "if", "not", "isinstance", "(", "tensor_type", ".", "name", ",", "property", ")", ":", "raise", "TypeError", "(", "\"Type %s does not define a `name` property\"", ")", "except", "AttributeError", ":", "raise", "TypeError", "(", "\"Type %s does not define a `name` property\"", ")", "try", ":", "if", "not", "isinstance", "(", "tensor_type", ".", "dtype", ",", "property", ")", ":", "raise", "TypeError", "(", "\"Type %s does not define a `dtype` property\"", ")", "except", "AttributeError", ":", "raise", "TypeError", "(", "\"Type %s does not define a `dtype` property\"", ")", "# We expect this list to be small, so choose quadratic complexity", "# for registration, so that we have a tuple that can be used for", "# more efficient `isinstance` checks later.", "global", "_TENSOR_LIKE_TYPES", "_TENSOR_LIKE_TYPES", "=", "tuple", "(", "list", "(", "_TENSOR_LIKE_TYPES", ")", "+", "[", "tensor_type", "]", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/framework/ops.py#L146-L172
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/fastparquet/api.py
python
ParquetFile.info
(self)
return {'name': self.fn, 'columns': self.columns, 'partitions': list(self.cats), 'rows': self.count}
Some metadata details
Some metadata details
[ "Some", "metadata", "details" ]
def info(self): """ Some metadata details """ return {'name': self.fn, 'columns': self.columns, 'partitions': list(self.cats), 'rows': self.count}
[ "def", "info", "(", "self", ")", ":", "return", "{", "'name'", ":", "self", ".", "fn", ",", "'columns'", ":", "self", ".", "columns", ",", "'partitions'", ":", "list", "(", "self", ".", "cats", ")", ",", "'rows'", ":", "self", ".", "count", "}" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/fastparquet/api.py#L447-L450
sdhash/sdhash
b9eff63e4e5867e910f41fd69032bbb1c94a2a5e
external/tools/build/v2/build/property_set.py
python
create
(raw_properties = [])
return __cache [key]
Creates a new 'PropertySet' instance for the given raw properties, or returns an already existing one.
Creates a new 'PropertySet' instance for the given raw properties, or returns an already existing one.
[ "Creates", "a", "new", "PropertySet", "instance", "for", "the", "given", "raw", "properties", "or", "returns", "an", "already", "existing", "one", "." ]
def create (raw_properties = []): """ Creates a new 'PropertySet' instance for the given raw properties, or returns an already existing one. """ # FIXME: propagate to callers. if len(raw_properties) > 0 and isinstance(raw_properties[0], property.Property): x = raw_properties else: x = [property.create_from_string(ps) for ps in raw_properties] x.sort() x = unique (x) # FIXME: can we do better, e.g. by directly computing # has value of the list? key = tuple(x) if not __cache.has_key (key): __cache [key] = PropertySet(x) return __cache [key]
[ "def", "create", "(", "raw_properties", "=", "[", "]", ")", ":", "# FIXME: propagate to callers.", "if", "len", "(", "raw_properties", ")", ">", "0", "and", "isinstance", "(", "raw_properties", "[", "0", "]", ",", "property", ".", "Property", ")", ":", "x", "=", "raw_properties", "else", ":", "x", "=", "[", "property", ".", "create_from_string", "(", "ps", ")", "for", "ps", "in", "raw_properties", "]", "x", ".", "sort", "(", ")", "x", "=", "unique", "(", "x", ")", "# FIXME: can we do better, e.g. by directly computing", "# has value of the list?", "key", "=", "tuple", "(", "x", ")", "if", "not", "__cache", ".", "has_key", "(", "key", ")", ":", "__cache", "[", "key", "]", "=", "PropertySet", "(", "x", ")", "return", "__cache", "[", "key", "]" ]
https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/external/tools/build/v2/build/property_set.py#L32-L51
llvm-mirror/lldb
d01083a850f577b85501a0902b52fd0930de72c7
third_party/Python/module/pexpect-4.6/pexpect/screen.py
python
screen.set_tab
(self)
Sets a tab at the current position.
Sets a tab at the current position.
[ "Sets", "a", "tab", "at", "the", "current", "position", "." ]
def set_tab (self): # <ESC>H '''Sets a tab at the current position.''' pass
[ "def", "set_tab", "(", "self", ")", ":", "# <ESC>H", "pass" ]
https://github.com/llvm-mirror/lldb/blob/d01083a850f577b85501a0902b52fd0930de72c7/third_party/Python/module/pexpect-4.6/pexpect/screen.py#L412-L415
llvm/llvm-project
ffa6262cb4e2a335d26416fad39a581b4f98c5f4
lldb/third_party/Python/module/ptyprocess-0.6.0/ptyprocess/ptyprocess.py
python
PtyProcess.wait
(self)
return self.exitstatus
This waits until the child exits. This is a blocking call. This will not read any data from the child, so this will block forever if the child has unread output and has terminated. In other words, the child may have printed output then called exit(), but, the child is technically still alive until its output is read by the parent.
This waits until the child exits. This is a blocking call. This will not read any data from the child, so this will block forever if the child has unread output and has terminated. In other words, the child may have printed output then called exit(), but, the child is technically still alive until its output is read by the parent.
[ "This", "waits", "until", "the", "child", "exits", ".", "This", "is", "a", "blocking", "call", ".", "This", "will", "not", "read", "any", "data", "from", "the", "child", "so", "this", "will", "block", "forever", "if", "the", "child", "has", "unread", "output", "and", "has", "terminated", ".", "In", "other", "words", "the", "child", "may", "have", "printed", "output", "then", "called", "exit", "()", "but", "the", "child", "is", "technically", "still", "alive", "until", "its", "output", "is", "read", "by", "the", "parent", "." ]
def wait(self): '''This waits until the child exits. This is a blocking call. This will not read any data from the child, so this will block forever if the child has unread output and has terminated. In other words, the child may have printed output then called exit(), but, the child is technically still alive until its output is read by the parent. ''' if self.isalive(): pid, status = os.waitpid(self.pid, 0) else: return self.exitstatus self.exitstatus = os.WEXITSTATUS(status) if os.WIFEXITED(status): self.status = status self.exitstatus = os.WEXITSTATUS(status) self.signalstatus = None self.terminated = True elif os.WIFSIGNALED(status): self.status = status self.exitstatus = None self.signalstatus = os.WTERMSIG(status) self.terminated = True elif os.WIFSTOPPED(status): # pragma: no cover # You can't call wait() on a child process in the stopped state. raise PtyProcessError('Called wait() on a stopped child ' + 'process. This is not supported. Is some other ' + 'process attempting job control with our child pid?') return self.exitstatus
[ "def", "wait", "(", "self", ")", ":", "if", "self", ".", "isalive", "(", ")", ":", "pid", ",", "status", "=", "os", ".", "waitpid", "(", "self", ".", "pid", ",", "0", ")", "else", ":", "return", "self", ".", "exitstatus", "self", ".", "exitstatus", "=", "os", ".", "WEXITSTATUS", "(", "status", ")", "if", "os", ".", "WIFEXITED", "(", "status", ")", ":", "self", ".", "status", "=", "status", "self", ".", "exitstatus", "=", "os", ".", "WEXITSTATUS", "(", "status", ")", "self", ".", "signalstatus", "=", "None", "self", ".", "terminated", "=", "True", "elif", "os", ".", "WIFSIGNALED", "(", "status", ")", ":", "self", ".", "status", "=", "status", "self", ".", "exitstatus", "=", "None", "self", ".", "signalstatus", "=", "os", ".", "WTERMSIG", "(", "status", ")", "self", ".", "terminated", "=", "True", "elif", "os", ".", "WIFSTOPPED", "(", "status", ")", ":", "# pragma: no cover", "# You can't call wait() on a child process in the stopped state.", "raise", "PtyProcessError", "(", "'Called wait() on a stopped child '", "+", "'process. This is not supported. Is some other '", "+", "'process attempting job control with our child pid?'", ")", "return", "self", ".", "exitstatus" ]
https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/lldb/third_party/Python/module/ptyprocess-0.6.0/ptyprocess/ptyprocess.py#L656-L683
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/bigtable/python/ops/bigtable_api.py
python
BigtableTable._make_parallel_scan_dataset
(self, ds, num_parallel_scans, normalized_probability, normalized_columns)
return ds
Builds a parallel dataset from a given range. Args: ds: A `_BigtableSampleKeyPairsDataset` returning ranges of keys to use. num_parallel_scans: The number of concurrent parallel scans to use. normalized_probability: A number between 0 and 1 for the keep probability. normalized_columns: The column families and column qualifiers to retrieve. Returns: A `tf.data.Dataset` representing the result of the parallel scan.
Builds a parallel dataset from a given range.
[ "Builds", "a", "parallel", "dataset", "from", "a", "given", "range", "." ]
def _make_parallel_scan_dataset(self, ds, num_parallel_scans, normalized_probability, normalized_columns): """Builds a parallel dataset from a given range. Args: ds: A `_BigtableSampleKeyPairsDataset` returning ranges of keys to use. num_parallel_scans: The number of concurrent parallel scans to use. normalized_probability: A number between 0 and 1 for the keep probability. normalized_columns: The column families and column qualifiers to retrieve. Returns: A `tf.data.Dataset` representing the result of the parallel scan. """ if num_parallel_scans is None: num_parallel_scans = 50 ds = ds.shuffle(buffer_size=10000) # TODO(saeta): Make configurable. def _interleave_fn(start, end): return _BigtableScanDataset( self, prefix="", start=start, end=end, normalized=normalized_columns, probability=normalized_probability) # Note prefetch_input_elements must be set in order to avoid rpc timeouts. ds = ds.apply( interleave_ops.parallel_interleave( _interleave_fn, cycle_length=num_parallel_scans, sloppy=True, prefetch_input_elements=1)) return ds
[ "def", "_make_parallel_scan_dataset", "(", "self", ",", "ds", ",", "num_parallel_scans", ",", "normalized_probability", ",", "normalized_columns", ")", ":", "if", "num_parallel_scans", "is", "None", ":", "num_parallel_scans", "=", "50", "ds", "=", "ds", ".", "shuffle", "(", "buffer_size", "=", "10000", ")", "# TODO(saeta): Make configurable.", "def", "_interleave_fn", "(", "start", ",", "end", ")", ":", "return", "_BigtableScanDataset", "(", "self", ",", "prefix", "=", "\"\"", ",", "start", "=", "start", ",", "end", "=", "end", ",", "normalized", "=", "normalized_columns", ",", "probability", "=", "normalized_probability", ")", "# Note prefetch_input_elements must be set in order to avoid rpc timeouts.", "ds", "=", "ds", ".", "apply", "(", "interleave_ops", ".", "parallel_interleave", "(", "_interleave_fn", ",", "cycle_length", "=", "num_parallel_scans", ",", "sloppy", "=", "True", ",", "prefetch_input_elements", "=", "1", ")", ")", "return", "ds" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/bigtable/python/ops/bigtable_api.py#L495-L529
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/metrics_impl.py
python
_maybe_expand_labels
(labels, predictions)
If necessary, expand `labels` along last dimension to match `predictions`. Args: labels: `Tensor` or `SparseTensor` with shape [D1, ... DN, num_labels] or [D1, ... DN]. The latter implies num_labels=1, in which case the result is an expanded `labels` with shape [D1, ... DN, 1]. predictions: `Tensor` with shape [D1, ... DN, num_classes]. Returns: `labels` with the same rank as `predictions`. Raises: ValueError: if `labels` has invalid shape.
If necessary, expand `labels` along last dimension to match `predictions`.
[ "If", "necessary", "expand", "labels", "along", "last", "dimension", "to", "match", "predictions", "." ]
def _maybe_expand_labels(labels, predictions): """If necessary, expand `labels` along last dimension to match `predictions`. Args: labels: `Tensor` or `SparseTensor` with shape [D1, ... DN, num_labels] or [D1, ... DN]. The latter implies num_labels=1, in which case the result is an expanded `labels` with shape [D1, ... DN, 1]. predictions: `Tensor` with shape [D1, ... DN, num_classes]. Returns: `labels` with the same rank as `predictions`. Raises: ValueError: if `labels` has invalid shape. """ with ops.name_scope(None, 'expand_labels', (labels, predictions)) as scope: labels = sparse_tensor.convert_to_tensor_or_sparse_tensor(labels) # If sparse, expand sparse shape. if isinstance(labels, sparse_tensor.SparseTensor): return control_flow_ops.cond( math_ops.equal( array_ops.rank(predictions), array_ops.size(labels.dense_shape) + 1), lambda: sparse_ops.sparse_reshape( # pylint: disable=g-long-lambda labels, shape=array_ops.concat((labels.dense_shape, (1,)), 0), name=scope), lambda: labels) # Otherwise, try to use static shape. labels_rank = labels.get_shape().ndims if labels_rank is not None: predictions_rank = predictions.get_shape().ndims if predictions_rank is not None: if predictions_rank == labels_rank: return labels if predictions_rank == labels_rank + 1: return array_ops.expand_dims(labels, -1, name=scope) raise ValueError( 'Unexpected labels shape %s for predictions shape %s.' % ( labels.get_shape(), predictions.get_shape())) # Otherwise, use dynamic shape. return control_flow_ops.cond( math_ops.equal(array_ops.rank(predictions), array_ops.rank(labels) + 1), lambda: array_ops.expand_dims(labels, -1, name=scope), lambda: labels)
[ "def", "_maybe_expand_labels", "(", "labels", ",", "predictions", ")", ":", "with", "ops", ".", "name_scope", "(", "None", ",", "'expand_labels'", ",", "(", "labels", ",", "predictions", ")", ")", "as", "scope", ":", "labels", "=", "sparse_tensor", ".", "convert_to_tensor_or_sparse_tensor", "(", "labels", ")", "# If sparse, expand sparse shape.", "if", "isinstance", "(", "labels", ",", "sparse_tensor", ".", "SparseTensor", ")", ":", "return", "control_flow_ops", ".", "cond", "(", "math_ops", ".", "equal", "(", "array_ops", ".", "rank", "(", "predictions", ")", ",", "array_ops", ".", "size", "(", "labels", ".", "dense_shape", ")", "+", "1", ")", ",", "lambda", ":", "sparse_ops", ".", "sparse_reshape", "(", "# pylint: disable=g-long-lambda", "labels", ",", "shape", "=", "array_ops", ".", "concat", "(", "(", "labels", ".", "dense_shape", ",", "(", "1", ",", ")", ")", ",", "0", ")", ",", "name", "=", "scope", ")", ",", "lambda", ":", "labels", ")", "# Otherwise, try to use static shape.", "labels_rank", "=", "labels", ".", "get_shape", "(", ")", ".", "ndims", "if", "labels_rank", "is", "not", "None", ":", "predictions_rank", "=", "predictions", ".", "get_shape", "(", ")", ".", "ndims", "if", "predictions_rank", "is", "not", "None", ":", "if", "predictions_rank", "==", "labels_rank", ":", "return", "labels", "if", "predictions_rank", "==", "labels_rank", "+", "1", ":", "return", "array_ops", ".", "expand_dims", "(", "labels", ",", "-", "1", ",", "name", "=", "scope", ")", "raise", "ValueError", "(", "'Unexpected labels shape %s for predictions shape %s.'", "%", "(", "labels", ".", "get_shape", "(", ")", ",", "predictions", ".", "get_shape", "(", ")", ")", ")", "# Otherwise, use dynamic shape.", "return", "control_flow_ops", ".", "cond", "(", "math_ops", ".", "equal", "(", "array_ops", ".", "rank", "(", "predictions", ")", ",", "array_ops", ".", "rank", "(", "labels", ")", "+", "1", ")", ",", "lambda", ":", "array_ops", ".", "expand_dims", "(", "labels", ",", "-", "1", ",", "name", "=", "scope", ")", ",", "lambda", ":", "labels", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/metrics_impl.py#L123-L171
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py3/IPython/core/prefilter.py
python
PrefilterManager.register_transformer
(self, transformer)
Register a transformer instance.
Register a transformer instance.
[ "Register", "a", "transformer", "instance", "." ]
def register_transformer(self, transformer): """Register a transformer instance.""" if transformer not in self._transformers: self._transformers.append(transformer) self.sort_transformers()
[ "def", "register_transformer", "(", "self", ",", "transformer", ")", ":", "if", "transformer", "not", "in", "self", ".", "_transformers", ":", "self", ".", "_transformers", ".", "append", "(", "transformer", ")", "self", ".", "sort_transformers", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/core/prefilter.py#L152-L156
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TStr.IsWord
(self, WsPrefixP=True, FirstUcAllowedP=True)
return _snap.TStr_IsWord(self, WsPrefixP, FirstUcAllowedP)
IsWord(TStr self, bool const & WsPrefixP=True, bool const & FirstUcAllowedP=True) -> bool Parameters: WsPrefixP: bool const & FirstUcAllowedP: bool const & IsWord(TStr self, bool const & WsPrefixP=True) -> bool Parameters: WsPrefixP: bool const & IsWord(TStr self) -> bool Parameters: self: TStr const *
IsWord(TStr self, bool const & WsPrefixP=True, bool const & FirstUcAllowedP=True) -> bool
[ "IsWord", "(", "TStr", "self", "bool", "const", "&", "WsPrefixP", "=", "True", "bool", "const", "&", "FirstUcAllowedP", "=", "True", ")", "-", ">", "bool" ]
def IsWord(self, WsPrefixP=True, FirstUcAllowedP=True): """ IsWord(TStr self, bool const & WsPrefixP=True, bool const & FirstUcAllowedP=True) -> bool Parameters: WsPrefixP: bool const & FirstUcAllowedP: bool const & IsWord(TStr self, bool const & WsPrefixP=True) -> bool Parameters: WsPrefixP: bool const & IsWord(TStr self) -> bool Parameters: self: TStr const * """ return _snap.TStr_IsWord(self, WsPrefixP, FirstUcAllowedP)
[ "def", "IsWord", "(", "self", ",", "WsPrefixP", "=", "True", ",", "FirstUcAllowedP", "=", "True", ")", ":", "return", "_snap", ".", "TStr_IsWord", "(", "self", ",", "WsPrefixP", ",", "FirstUcAllowedP", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L10605-L10624
tzutalin/dlib-android
989627cb7fe81cd1d41d73434b0e91ce1dd2683f
tools/lint/cpplint.py
python
Search
(pattern, s)
return _regexp_compile_cache[pattern].search(s)
Searches the string for the pattern, caching the compiled regexp.
Searches the string for the pattern, caching the compiled regexp.
[ "Searches", "the", "string", "for", "the", "pattern", "caching", "the", "compiled", "regexp", "." ]
def Search(pattern, s): """Searches the string for the pattern, caching the compiled regexp.""" if pattern not in _regexp_compile_cache: _regexp_compile_cache[pattern] = sre_compile.compile(pattern) return _regexp_compile_cache[pattern].search(s)
[ "def", "Search", "(", "pattern", ",", "s", ")", ":", "if", "pattern", "not", "in", "_regexp_compile_cache", ":", "_regexp_compile_cache", "[", "pattern", "]", "=", "sre_compile", ".", "compile", "(", "pattern", ")", "return", "_regexp_compile_cache", "[", "pattern", "]", ".", "search", "(", "s", ")" ]
https://github.com/tzutalin/dlib-android/blob/989627cb7fe81cd1d41d73434b0e91ce1dd2683f/tools/lint/cpplint.py#L632-L636
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/docview.py
python
Document.OnNewDocument
(self)
The default implementation calls OnSaveModified and DeleteContents, makes a default title for the document, and notifies the views that the filename (in fact, the title) has changed.
The default implementation calls OnSaveModified and DeleteContents, makes a default title for the document, and notifies the views that the filename (in fact, the title) has changed.
[ "The", "default", "implementation", "calls", "OnSaveModified", "and", "DeleteContents", "makes", "a", "default", "title", "for", "the", "document", "and", "notifies", "the", "views", "that", "the", "filename", "(", "in", "fact", "the", "title", ")", "has", "changed", "." ]
def OnNewDocument(self): """ The default implementation calls OnSaveModified and DeleteContents, makes a default title for the document, and notifies the views that the filename (in fact, the title) has changed. """ if not self.OnSaveModified() or not self.OnCloseDocument(): return False self.DeleteContents() self.Modify(False) self.SetDocumentSaved(False) name = self.GetDocumentManager().MakeDefaultName() self.SetTitle(name) self.SetFilename(name, notifyViews = True)
[ "def", "OnNewDocument", "(", "self", ")", ":", "if", "not", "self", ".", "OnSaveModified", "(", ")", "or", "not", "self", ".", "OnCloseDocument", "(", ")", ":", "return", "False", "self", ".", "DeleteContents", "(", ")", "self", ".", "Modify", "(", "False", ")", "self", ".", "SetDocumentSaved", "(", "False", ")", "name", "=", "self", ".", "GetDocumentManager", "(", ")", ".", "MakeDefaultName", "(", ")", "self", ".", "SetTitle", "(", "name", ")", "self", ".", "SetFilename", "(", "name", ",", "notifyViews", "=", "True", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/docview.py#L355-L368
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
PyApp_GetMacExitMenuItemId
(*args)
return _core_.PyApp_GetMacExitMenuItemId(*args)
PyApp_GetMacExitMenuItemId() -> long
PyApp_GetMacExitMenuItemId() -> long
[ "PyApp_GetMacExitMenuItemId", "()", "-", ">", "long" ]
def PyApp_GetMacExitMenuItemId(*args): """PyApp_GetMacExitMenuItemId() -> long""" return _core_.PyApp_GetMacExitMenuItemId(*args)
[ "def", "PyApp_GetMacExitMenuItemId", "(", "*", "args", ")", ":", "return", "_core_", ".", "PyApp_GetMacExitMenuItemId", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L8286-L8288
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pluggy/py2/pluggy/hooks.py
python
HookimplMarker.__call__
( self, function=None, hookwrapper=False, optionalhook=False, tryfirst=False, trylast=False, )
if passed a function, directly sets attributes on the function which will make it discoverable to :py:meth:`.PluginManager.register`. If passed no function, returns a decorator which can be applied to a function later using the attributes supplied. If ``optionalhook`` is ``True`` a missing matching hook specification will not result in an error (by default it is an error if no matching spec is found). If ``tryfirst`` is ``True`` this hook implementation will run as early as possible in the chain of N hook implementations for a specification. If ``trylast`` is ``True`` this hook implementation will run as late as possible in the chain of N hook implementations. If ``hookwrapper`` is ``True`` the hook implementations needs to execute exactly one ``yield``. The code before the ``yield`` is run early before any non-hookwrapper function is run. The code after the ``yield`` is run after all non-hookwrapper function have run. The ``yield`` receives a :py:class:`.callers._Result` object representing the exception or result outcome of the inner calls (including other hookwrapper calls).
if passed a function, directly sets attributes on the function which will make it discoverable to :py:meth:`.PluginManager.register`. If passed no function, returns a decorator which can be applied to a function later using the attributes supplied.
[ "if", "passed", "a", "function", "directly", "sets", "attributes", "on", "the", "function", "which", "will", "make", "it", "discoverable", "to", ":", "py", ":", "meth", ":", ".", "PluginManager", ".", "register", ".", "If", "passed", "no", "function", "returns", "a", "decorator", "which", "can", "be", "applied", "to", "a", "function", "later", "using", "the", "attributes", "supplied", "." ]
def __call__( self, function=None, hookwrapper=False, optionalhook=False, tryfirst=False, trylast=False, ): """ if passed a function, directly sets attributes on the function which will make it discoverable to :py:meth:`.PluginManager.register`. If passed no function, returns a decorator which can be applied to a function later using the attributes supplied. If ``optionalhook`` is ``True`` a missing matching hook specification will not result in an error (by default it is an error if no matching spec is found). If ``tryfirst`` is ``True`` this hook implementation will run as early as possible in the chain of N hook implementations for a specification. If ``trylast`` is ``True`` this hook implementation will run as late as possible in the chain of N hook implementations. If ``hookwrapper`` is ``True`` the hook implementations needs to execute exactly one ``yield``. The code before the ``yield`` is run early before any non-hookwrapper function is run. The code after the ``yield`` is run after all non-hookwrapper function have run. The ``yield`` receives a :py:class:`.callers._Result` object representing the exception or result outcome of the inner calls (including other hookwrapper calls). """ def setattr_hookimpl_opts(func): setattr( func, self.project_name + "_impl", dict( hookwrapper=hookwrapper, optionalhook=optionalhook, tryfirst=tryfirst, trylast=trylast, ), ) return func if function is None: return setattr_hookimpl_opts else: return setattr_hookimpl_opts(function)
[ "def", "__call__", "(", "self", ",", "function", "=", "None", ",", "hookwrapper", "=", "False", ",", "optionalhook", "=", "False", ",", "tryfirst", "=", "False", ",", "trylast", "=", "False", ",", ")", ":", "def", "setattr_hookimpl_opts", "(", "func", ")", ":", "setattr", "(", "func", ",", "self", ".", "project_name", "+", "\"_impl\"", ",", "dict", "(", "hookwrapper", "=", "hookwrapper", ",", "optionalhook", "=", "optionalhook", ",", "tryfirst", "=", "tryfirst", ",", "trylast", "=", "trylast", ",", ")", ",", ")", "return", "func", "if", "function", "is", "None", ":", "return", "setattr_hookimpl_opts", "else", ":", "return", "setattr_hookimpl_opts", "(", "function", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pluggy/py2/pluggy/hooks.py#L69-L117
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
samples/ide/activegrid/tool/CodeEditor.py
python
CodeView.GetAutoCompleteHint
(self)
return context, hint
Replace this method with Editor specific method
Replace this method with Editor specific method
[ "Replace", "this", "method", "with", "Editor", "specific", "method" ]
def GetAutoCompleteHint(self): """ Replace this method with Editor specific method """ pos = self.GetCtrl().GetCurrentPos() if pos == 0: return None, None if chr(self.GetCtrl().GetCharAt(pos - 1)) == '.': pos = pos - 1 hint = None else: hint = '' validLetters = string.letters + string.digits + '_.' word = '' while (True): pos = pos - 1 if pos < 0: break char = chr(self.GetCtrl().GetCharAt(pos)) if char not in validLetters: break word = char + word context = word if hint is not None: lastDot = word.rfind('.') if lastDot != -1: context = word[0:lastDot] hint = word[lastDot+1:] return context, hint
[ "def", "GetAutoCompleteHint", "(", "self", ")", ":", "pos", "=", "self", ".", "GetCtrl", "(", ")", ".", "GetCurrentPos", "(", ")", "if", "pos", "==", "0", ":", "return", "None", ",", "None", "if", "chr", "(", "self", ".", "GetCtrl", "(", ")", ".", "GetCharAt", "(", "pos", "-", "1", ")", ")", "==", "'.'", ":", "pos", "=", "pos", "-", "1", "hint", "=", "None", "else", ":", "hint", "=", "''", "validLetters", "=", "string", ".", "letters", "+", "string", ".", "digits", "+", "'_.'", "word", "=", "''", "while", "(", "True", ")", ":", "pos", "=", "pos", "-", "1", "if", "pos", "<", "0", ":", "break", "char", "=", "chr", "(", "self", ".", "GetCtrl", "(", ")", ".", "GetCharAt", "(", "pos", ")", ")", "if", "char", "not", "in", "validLetters", ":", "break", "word", "=", "char", "+", "word", "context", "=", "word", "if", "hint", "is", "not", "None", ":", "lastDot", "=", "word", ".", "rfind", "(", "'.'", ")", "if", "lastDot", "!=", "-", "1", ":", "context", "=", "word", "[", "0", ":", "lastDot", "]", "hint", "=", "word", "[", "lastDot", "+", "1", ":", "]", "return", "context", ",", "hint" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/samples/ide/activegrid/tool/CodeEditor.py#L335-L364
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/urllib3/util/connection.py
python
allowed_gai_family
()
return family
This function is designed to work in the context of getaddrinfo, where family=socket.AF_UNSPEC is the default and will perform a DNS search for both IPv6 and IPv4 records.
This function is designed to work in the context of getaddrinfo, where family=socket.AF_UNSPEC is the default and will perform a DNS search for both IPv6 and IPv4 records.
[ "This", "function", "is", "designed", "to", "work", "in", "the", "context", "of", "getaddrinfo", "where", "family", "=", "socket", ".", "AF_UNSPEC", "is", "the", "default", "and", "will", "perform", "a", "DNS", "search", "for", "both", "IPv6", "and", "IPv4", "records", "." ]
def allowed_gai_family(): """This function is designed to work in the context of getaddrinfo, where family=socket.AF_UNSPEC is the default and will perform a DNS search for both IPv6 and IPv4 records.""" family = socket.AF_INET if HAS_IPV6: family = socket.AF_UNSPEC return family
[ "def", "allowed_gai_family", "(", ")", ":", "family", "=", "socket", ".", "AF_INET", "if", "HAS_IPV6", ":", "family", "=", "socket", ".", "AF_UNSPEC", "return", "family" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/urllib3/util/connection.py#L97-L105
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/idlelib/CallTips.py
python
get_arg_text
(ob)
return arg_text
Get a string describing the arguments for the given object, only if it is callable.
Get a string describing the arguments for the given object, only if it is callable.
[ "Get", "a", "string", "describing", "the", "arguments", "for", "the", "given", "object", "only", "if", "it", "is", "callable", "." ]
def get_arg_text(ob): """Get a string describing the arguments for the given object, only if it is callable.""" arg_text = "" if ob is not None and hasattr(ob, '__call__'): arg_offset = 0 if type(ob) in (types.ClassType, types.TypeType): # Look for the highest __init__ in the class chain. fob = _find_constructor(ob) if fob is None: fob = lambda: None else: arg_offset = 1 elif type(ob)==types.MethodType: # bit of a hack for methods - turn it into a function # but we drop the "self" param. fob = ob.im_func arg_offset = 1 else: fob = ob # Try to build one for Python defined functions if type(fob) in [types.FunctionType, types.LambdaType]: argcount = fob.func_code.co_argcount real_args = fob.func_code.co_varnames[arg_offset:argcount] defaults = fob.func_defaults or [] defaults = list(map(lambda name: "=%s" % repr(name), defaults)) defaults = [""] * (len(real_args) - len(defaults)) + defaults items = map(lambda arg, dflt: arg + dflt, real_args, defaults) if fob.func_code.co_flags & 0x4: items.append("...") if fob.func_code.co_flags & 0x8: items.append("***") arg_text = ", ".join(items) arg_text = "(%s)" % re.sub("\.\d+", "<tuple>", arg_text) # See if we can use the docstring doc = getattr(ob, "__doc__", "") if doc: doc = doc.lstrip() pos = doc.find("\n") if pos < 0 or pos > 70: pos = 70 if arg_text: arg_text += "\n" arg_text += doc[:pos] return arg_text
[ "def", "get_arg_text", "(", "ob", ")", ":", "arg_text", "=", "\"\"", "if", "ob", "is", "not", "None", "and", "hasattr", "(", "ob", ",", "'__call__'", ")", ":", "arg_offset", "=", "0", "if", "type", "(", "ob", ")", "in", "(", "types", ".", "ClassType", ",", "types", ".", "TypeType", ")", ":", "# Look for the highest __init__ in the class chain.", "fob", "=", "_find_constructor", "(", "ob", ")", "if", "fob", "is", "None", ":", "fob", "=", "lambda", ":", "None", "else", ":", "arg_offset", "=", "1", "elif", "type", "(", "ob", ")", "==", "types", ".", "MethodType", ":", "# bit of a hack for methods - turn it into a function", "# but we drop the \"self\" param.", "fob", "=", "ob", ".", "im_func", "arg_offset", "=", "1", "else", ":", "fob", "=", "ob", "# Try to build one for Python defined functions", "if", "type", "(", "fob", ")", "in", "[", "types", ".", "FunctionType", ",", "types", ".", "LambdaType", "]", ":", "argcount", "=", "fob", ".", "func_code", ".", "co_argcount", "real_args", "=", "fob", ".", "func_code", ".", "co_varnames", "[", "arg_offset", ":", "argcount", "]", "defaults", "=", "fob", ".", "func_defaults", "or", "[", "]", "defaults", "=", "list", "(", "map", "(", "lambda", "name", ":", "\"=%s\"", "%", "repr", "(", "name", ")", ",", "defaults", ")", ")", "defaults", "=", "[", "\"\"", "]", "*", "(", "len", "(", "real_args", ")", "-", "len", "(", "defaults", ")", ")", "+", "defaults", "items", "=", "map", "(", "lambda", "arg", ",", "dflt", ":", "arg", "+", "dflt", ",", "real_args", ",", "defaults", ")", "if", "fob", ".", "func_code", ".", "co_flags", "&", "0x4", ":", "items", ".", "append", "(", "\"...\"", ")", "if", "fob", ".", "func_code", ".", "co_flags", "&", "0x8", ":", "items", ".", "append", "(", "\"***\"", ")", "arg_text", "=", "\", \"", ".", "join", "(", "items", ")", "arg_text", "=", "\"(%s)\"", "%", "re", ".", "sub", "(", "\"\\.\\d+\"", ",", "\"<tuple>\"", ",", "arg_text", ")", "# See if we can use the docstring", "doc", "=", "getattr", "(", "ob", ",", "\"__doc__\"", ",", "\"\"", ")", "if", "doc", ":", "doc", "=", "doc", ".", "lstrip", "(", ")", "pos", "=", "doc", ".", "find", "(", "\"\\n\"", ")", "if", "pos", "<", "0", "or", "pos", ">", "70", ":", "pos", "=", "70", "if", "arg_text", ":", "arg_text", "+=", "\"\\n\"", "arg_text", "+=", "doc", "[", ":", "pos", "]", "return", "arg_text" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/idlelib/CallTips.py#L133-L177
lmb-freiburg/flownet2
b92e198b56b0e52e1ba0a5a98dc0e39fa5ae70cc
scripts/cpp_lint.py
python
CheckBraces
(filename, clean_lines, linenum, error)
Looks for misplaced braces (e.g. at the end of line). 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.
Looks for misplaced braces (e.g. at the end of line).
[ "Looks", "for", "misplaced", "braces", "(", "e", ".", "g", ".", "at", "the", "end", "of", "line", ")", "." ]
def CheckBraces(filename, clean_lines, linenum, error): """Looks for misplaced braces (e.g. at the end of line). 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] # get rid of comments and strings if Match(r'\s*{\s*$', line): # We allow an open brace to start a line in the case where someone is using # braces in a block to explicitly create a new scope, which is commonly used # to control the lifetime of stack-allocated variables. Braces are also # used for brace initializers inside function calls. We don't detect this # perfectly: we just don't complain if the last non-whitespace character on # the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the # previous line starts a preprocessor block. prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if (not Search(r'[,;:}{(]\s*$', prevline) and not Match(r'\s*#', prevline)): error(filename, linenum, 'whitespace/braces', 4, '{ should almost always be at the end of the previous line') # An else clause should be on the same line as the preceding closing brace. if Match(r'\s*else\s*', line): prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if Match(r'\s*}\s*$', prevline): error(filename, linenum, 'whitespace/newline', 4, 'An else should appear on the same line as the preceding }') # If braces come on one side of an else, they should be on both. # However, we have to worry about "else if" that spans multiple lines! if Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line): if Search(r'}\s*else if([^{]*)$', line): # could be multi-line if # find the ( after the if pos = line.find('else if') pos = line.find('(', pos) if pos > 0: (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos) if endline[endpos:].find('{') == -1: # must be brace after if error(filename, linenum, 'readability/braces', 5, 'If an else has a brace on one side, it should have it on both') else: # common case: else not followed by a multi-line if error(filename, linenum, 'readability/braces', 5, 'If an else has a brace on one side, it should have it on both') # Likewise, an else should never have the else clause on the same line if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line): error(filename, linenum, 'whitespace/newline', 4, 'Else clause should never be on same line as else (use 2 lines)') # In the same way, a do/while should never be on one line if Match(r'\s*do [^\s{]', line): error(filename, linenum, 'whitespace/newline', 4, 'do/while clauses should not be on a single line') # Block bodies should not be followed by a semicolon. Due to C++11 # brace initialization, there are more places where semicolons are # required than not, so we use a whitelist approach to check these # rather than a blacklist. These are the places where "};" should # be replaced by just "}": # 1. Some flavor of block following closing parenthesis: # for (;;) {}; # while (...) {}; # switch (...) {}; # Function(...) {}; # if (...) {}; # if (...) else if (...) {}; # # 2. else block: # if (...) else {}; # # 3. const member function: # Function(...) const {}; # # 4. Block following some statement: # x = 42; # {}; # # 5. Block at the beginning of a function: # Function(...) { # {}; # } # # Note that naively checking for the preceding "{" will also match # braces inside multi-dimensional arrays, but this is fine since # that expression will not contain semicolons. # # 6. Block following another block: # while (true) {} # {}; # # 7. End of namespaces: # namespace {}; # # These semicolons seems far more common than other kinds of # redundant semicolons, possibly due to people converting classes # to namespaces. For now we do not warn for this case. # # Try matching case 1 first. match = Match(r'^(.*\)\s*)\{', line) if match: # Matched closing parenthesis (case 1). Check the token before the # matching opening parenthesis, and don't warn if it looks like a # macro. This avoids these false positives: # - macro that defines a base class # - multi-line macro that defines a base class # - macro that defines the whole class-head # # But we still issue warnings for macros that we know are safe to # warn, specifically: # - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P # - TYPED_TEST # - INTERFACE_DEF # - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED: # # We implement a whitelist of safe macros instead of a blacklist of # unsafe macros, even though the latter appears less frequently in # google code and would have been easier to implement. This is because # the downside for getting the whitelist wrong means some extra # semicolons, while the downside for getting the blacklist wrong # would result in compile errors. # # In addition to macros, we also don't want to warn on compound # literals. closing_brace_pos = match.group(1).rfind(')') opening_parenthesis = ReverseCloseExpression( clean_lines, linenum, closing_brace_pos) if opening_parenthesis[2] > -1: line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]] macro = Search(r'\b([A-Z_]+)\s*$', line_prefix) if ((macro and macro.group(1) not in ( 'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST', 'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED', 'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or Search(r'\s+=\s*$', line_prefix)): match = None else: # Try matching cases 2-3. match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line) if not match: # Try matching cases 4-6. These are always matched on separate lines. # # Note that we can't simply concatenate the previous line to the # current line and do a single match, otherwise we may output # duplicate warnings for the blank line case: # if (cond) { # // blank line # } prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if prevline and Search(r'[;{}]\s*$', prevline): match = Match(r'^(\s*)\{', line) # Check matching closing brace if match: (endline, endlinenum, endpos) = CloseExpression( clean_lines, linenum, len(match.group(1))) if endpos > -1 and Match(r'^\s*;', endline[endpos:]): # Current {} pair is eligible for semicolon check, and we have found # the redundant semicolon, output warning here. # # Note: because we are scanning forward for opening braces, and # outputting warnings for the matching closing brace, if there are # nested blocks with trailing semicolons, we will get the error # messages in reversed order. error(filename, endlinenum, 'readability/braces', 4, "You don't need a ; after a }")
[ "def", "CheckBraces", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# get rid of comments and strings", "if", "Match", "(", "r'\\s*{\\s*$'", ",", "line", ")", ":", "# We allow an open brace to start a line in the case where someone is using", "# braces in a block to explicitly create a new scope, which is commonly used", "# to control the lifetime of stack-allocated variables. Braces are also", "# used for brace initializers inside function calls. We don't detect this", "# perfectly: we just don't complain if the last non-whitespace character on", "# the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the", "# previous line starts a preprocessor block.", "prevline", "=", "GetPreviousNonBlankLine", "(", "clean_lines", ",", "linenum", ")", "[", "0", "]", "if", "(", "not", "Search", "(", "r'[,;:}{(]\\s*$'", ",", "prevline", ")", "and", "not", "Match", "(", "r'\\s*#'", ",", "prevline", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/braces'", ",", "4", ",", "'{ should almost always be at the end of the previous line'", ")", "# An else clause should be on the same line as the preceding closing brace.", "if", "Match", "(", "r'\\s*else\\s*'", ",", "line", ")", ":", "prevline", "=", "GetPreviousNonBlankLine", "(", "clean_lines", ",", "linenum", ")", "[", "0", "]", "if", "Match", "(", "r'\\s*}\\s*$'", ",", "prevline", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/newline'", ",", "4", ",", "'An else should appear on the same line as the preceding }'", ")", "# If braces come on one side of an else, they should be on both.", "# However, we have to worry about \"else if\" that spans multiple lines!", "if", "Search", "(", "r'}\\s*else[^{]*$'", ",", "line", ")", "or", "Match", "(", "r'[^}]*else\\s*{'", ",", "line", ")", ":", "if", "Search", "(", "r'}\\s*else if([^{]*)$'", ",", "line", ")", ":", "# could be multi-line if", "# find the ( after the if", "pos", "=", "line", ".", "find", "(", "'else if'", ")", "pos", "=", "line", ".", "find", "(", "'('", ",", "pos", ")", "if", "pos", ">", "0", ":", "(", "endline", ",", "_", ",", "endpos", ")", "=", "CloseExpression", "(", "clean_lines", ",", "linenum", ",", "pos", ")", "if", "endline", "[", "endpos", ":", "]", ".", "find", "(", "'{'", ")", "==", "-", "1", ":", "# must be brace after if", "error", "(", "filename", ",", "linenum", ",", "'readability/braces'", ",", "5", ",", "'If an else has a brace on one side, it should have it on both'", ")", "else", ":", "# common case: else not followed by a multi-line if", "error", "(", "filename", ",", "linenum", ",", "'readability/braces'", ",", "5", ",", "'If an else has a brace on one side, it should have it on both'", ")", "# Likewise, an else should never have the else clause on the same line", "if", "Search", "(", "r'\\belse [^\\s{]'", ",", "line", ")", "and", "not", "Search", "(", "r'\\belse if\\b'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/newline'", ",", "4", ",", "'Else clause should never be on same line as else (use 2 lines)'", ")", "# In the same way, a do/while should never be on one line", "if", "Match", "(", "r'\\s*do [^\\s{]'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/newline'", ",", "4", ",", "'do/while clauses should not be on a single line'", ")", "# Block bodies should not be followed by a semicolon. Due to C++11", "# brace initialization, there are more places where semicolons are", "# required than not, so we use a whitelist approach to check these", "# rather than a blacklist. These are the places where \"};\" should", "# be replaced by just \"}\":", "# 1. Some flavor of block following closing parenthesis:", "# for (;;) {};", "# while (...) {};", "# switch (...) {};", "# Function(...) {};", "# if (...) {};", "# if (...) else if (...) {};", "#", "# 2. else block:", "# if (...) else {};", "#", "# 3. const member function:", "# Function(...) const {};", "#", "# 4. Block following some statement:", "# x = 42;", "# {};", "#", "# 5. Block at the beginning of a function:", "# Function(...) {", "# {};", "# }", "#", "# Note that naively checking for the preceding \"{\" will also match", "# braces inside multi-dimensional arrays, but this is fine since", "# that expression will not contain semicolons.", "#", "# 6. Block following another block:", "# while (true) {}", "# {};", "#", "# 7. End of namespaces:", "# namespace {};", "#", "# These semicolons seems far more common than other kinds of", "# redundant semicolons, possibly due to people converting classes", "# to namespaces. For now we do not warn for this case.", "#", "# Try matching case 1 first.", "match", "=", "Match", "(", "r'^(.*\\)\\s*)\\{'", ",", "line", ")", "if", "match", ":", "# Matched closing parenthesis (case 1). Check the token before the", "# matching opening parenthesis, and don't warn if it looks like a", "# macro. This avoids these false positives:", "# - macro that defines a base class", "# - multi-line macro that defines a base class", "# - macro that defines the whole class-head", "#", "# But we still issue warnings for macros that we know are safe to", "# warn, specifically:", "# - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P", "# - TYPED_TEST", "# - INTERFACE_DEF", "# - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED:", "#", "# We implement a whitelist of safe macros instead of a blacklist of", "# unsafe macros, even though the latter appears less frequently in", "# google code and would have been easier to implement. This is because", "# the downside for getting the whitelist wrong means some extra", "# semicolons, while the downside for getting the blacklist wrong", "# would result in compile errors.", "#", "# In addition to macros, we also don't want to warn on compound", "# literals.", "closing_brace_pos", "=", "match", ".", "group", "(", "1", ")", ".", "rfind", "(", "')'", ")", "opening_parenthesis", "=", "ReverseCloseExpression", "(", "clean_lines", ",", "linenum", ",", "closing_brace_pos", ")", "if", "opening_parenthesis", "[", "2", "]", ">", "-", "1", ":", "line_prefix", "=", "opening_parenthesis", "[", "0", "]", "[", "0", ":", "opening_parenthesis", "[", "2", "]", "]", "macro", "=", "Search", "(", "r'\\b([A-Z_]+)\\s*$'", ",", "line_prefix", ")", "if", "(", "(", "macro", "and", "macro", ".", "group", "(", "1", ")", "not", "in", "(", "'TEST'", ",", "'TEST_F'", ",", "'MATCHER'", ",", "'MATCHER_P'", ",", "'TYPED_TEST'", ",", "'EXCLUSIVE_LOCKS_REQUIRED'", ",", "'SHARED_LOCKS_REQUIRED'", ",", "'LOCKS_EXCLUDED'", ",", "'INTERFACE_DEF'", ")", ")", "or", "Search", "(", "r'\\s+=\\s*$'", ",", "line_prefix", ")", ")", ":", "match", "=", "None", "else", ":", "# Try matching cases 2-3.", "match", "=", "Match", "(", "r'^(.*(?:else|\\)\\s*const)\\s*)\\{'", ",", "line", ")", "if", "not", "match", ":", "# Try matching cases 4-6. These are always matched on separate lines.", "#", "# Note that we can't simply concatenate the previous line to the", "# current line and do a single match, otherwise we may output", "# duplicate warnings for the blank line case:", "# if (cond) {", "# // blank line", "# }", "prevline", "=", "GetPreviousNonBlankLine", "(", "clean_lines", ",", "linenum", ")", "[", "0", "]", "if", "prevline", "and", "Search", "(", "r'[;{}]\\s*$'", ",", "prevline", ")", ":", "match", "=", "Match", "(", "r'^(\\s*)\\{'", ",", "line", ")", "# Check matching closing brace", "if", "match", ":", "(", "endline", ",", "endlinenum", ",", "endpos", ")", "=", "CloseExpression", "(", "clean_lines", ",", "linenum", ",", "len", "(", "match", ".", "group", "(", "1", ")", ")", ")", "if", "endpos", ">", "-", "1", "and", "Match", "(", "r'^\\s*;'", ",", "endline", "[", "endpos", ":", "]", ")", ":", "# Current {} pair is eligible for semicolon check, and we have found", "# the redundant semicolon, output warning here.", "#", "# Note: because we are scanning forward for opening braces, and", "# outputting warnings for the matching closing brace, if there are", "# nested blocks with trailing semicolons, we will get the error", "# messages in reversed order.", "error", "(", "filename", ",", "endlinenum", ",", "'readability/braces'", ",", "4", ",", "\"You don't need a ; after a }\"", ")" ]
https://github.com/lmb-freiburg/flownet2/blob/b92e198b56b0e52e1ba0a5a98dc0e39fa5ae70cc/scripts/cpp_lint.py#L3069-L3240
twtygqyy/caffe-augmentation
c76600d247e5132fa5bd89d87bb5df458341fa84
python/caffe/draw.py
python
choose_color_by_layertype
(layertype)
return color
Define colors for nodes based on the layer type.
Define colors for nodes based on the layer type.
[ "Define", "colors", "for", "nodes", "based", "on", "the", "layer", "type", "." ]
def choose_color_by_layertype(layertype): """Define colors for nodes based on the layer type. """ color = '#6495ED' # Default if layertype == 'Convolution' or layertype == 'Deconvolution': color = '#FF5050' elif layertype == 'Pooling': color = '#FF9900' elif layertype == 'InnerProduct': color = '#CC33FF' return color
[ "def", "choose_color_by_layertype", "(", "layertype", ")", ":", "color", "=", "'#6495ED'", "# Default", "if", "layertype", "==", "'Convolution'", "or", "layertype", "==", "'Deconvolution'", ":", "color", "=", "'#FF5050'", "elif", "layertype", "==", "'Pooling'", ":", "color", "=", "'#FF9900'", "elif", "layertype", "==", "'InnerProduct'", ":", "color", "=", "'#CC33FF'", "return", "color" ]
https://github.com/twtygqyy/caffe-augmentation/blob/c76600d247e5132fa5bd89d87bb5df458341fa84/python/caffe/draw.py#L117-L127
swift/swift
12d031cf8177fdec0137f9aa7e2912fa23c4416b
3rdParty/SCons/scons-3.0.1/engine/SCons/Tool/MSCommon/vs.py
python
query_versions
()
return versions
Query the system to get available versions of VS. A version is considered when a batfile is found.
Query the system to get available versions of VS. A version is considered when a batfile is found.
[ "Query", "the", "system", "to", "get", "available", "versions", "of", "VS", ".", "A", "version", "is", "considered", "when", "a", "batfile", "is", "found", "." ]
def query_versions(): """Query the system to get available versions of VS. A version is considered when a batfile is found.""" msvs_list = get_installed_visual_studios() versions = [msvs.version for msvs in msvs_list] return versions
[ "def", "query_versions", "(", ")", ":", "msvs_list", "=", "get_installed_visual_studios", "(", ")", "versions", "=", "[", "msvs", ".", "version", "for", "msvs", "in", "msvs_list", "]", "return", "versions" ]
https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/3rdParty/SCons/scons-3.0.1/engine/SCons/Tool/MSCommon/vs.py#L562-L567
francinexue/xuefu
b6ff79747a42e020588c0c0a921048e08fe4680c
api/ctpx/ctptd.py
python
CtpTd.onRspQrySettlementInfo
(self, SettlementInfoField, RspInfoField, requestId, final)
请求查询投资者结算结果响应
请求查询投资者结算结果响应
[ "请求查询投资者结算结果响应" ]
def onRspQrySettlementInfo(self, SettlementInfoField, RspInfoField, requestId, final): """请求查询投资者结算结果响应""" pass
[ "def", "onRspQrySettlementInfo", "(", "self", ",", "SettlementInfoField", ",", "RspInfoField", ",", "requestId", ",", "final", ")", ":", "pass" ]
https://github.com/francinexue/xuefu/blob/b6ff79747a42e020588c0c0a921048e08fe4680c/api/ctpx/ctptd.py#L241-L243
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/ops/control_flow_ops.py
python
WhileContext.loop_exits
(self)
return self._loop_exits
The list of exit tensors for loop variables.
The list of exit tensors for loop variables.
[ "The", "list", "of", "exit", "tensors", "for", "loop", "variables", "." ]
def loop_exits(self): """The list of exit tensors for loop variables.""" return self._loop_exits
[ "def", "loop_exits", "(", "self", ")", ":", "return", "self", ".", "_loop_exits" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/control_flow_ops.py#L1862-L1864
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/boto3/resources/collection.py
python
ResourceCollection.limit
(self, count)
return self._clone(limit=count)
Return at most this many resources. >>> for bucket in s3.buckets.limit(5): ... print(bucket.name) 'bucket1' 'bucket2' 'bucket3' 'bucket4' 'bucket5' :type count: int :param count: Return no more than this many items :rtype: :py:class:`ResourceCollection`
Return at most this many resources.
[ "Return", "at", "most", "this", "many", "resources", "." ]
def limit(self, count): """ Return at most this many resources. >>> for bucket in s3.buckets.limit(5): ... print(bucket.name) 'bucket1' 'bucket2' 'bucket3' 'bucket4' 'bucket5' :type count: int :param count: Return no more than this many items :rtype: :py:class:`ResourceCollection` """ return self._clone(limit=count)
[ "def", "limit", "(", "self", ",", "count", ")", ":", "return", "self", ".", "_clone", "(", "limit", "=", "count", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/boto3/resources/collection.py#L228-L244
metashell/metashell
f4177e4854ea00c8dbc722cadab26ef413d798ea
3rd/templight/compiler-rt/lib/asan/scripts/asan_symbolize.py
python
AsanSymbolizerPlugInProxy.has_plugin
(self, name)
return name in self._plugin_names
Returns true iff the plugin name is currently being managed by AsanSymbolizerPlugInProxy.
Returns true iff the plugin name is currently being managed by AsanSymbolizerPlugInProxy.
[ "Returns", "true", "iff", "the", "plugin", "name", "is", "currently", "being", "managed", "by", "AsanSymbolizerPlugInProxy", "." ]
def has_plugin(self, name): """ Returns true iff the plugin name is currently being managed by AsanSymbolizerPlugInProxy. """ return name in self._plugin_names
[ "def", "has_plugin", "(", "self", ",", "name", ")", ":", "return", "name", "in", "self", ".", "_plugin_names" ]
https://github.com/metashell/metashell/blob/f4177e4854ea00c8dbc722cadab26ef413d798ea/3rd/templight/compiler-rt/lib/asan/scripts/asan_symbolize.py#L583-L588
yrnkrn/zapcc
c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50
tools/clang/bindings/python/clang/cindex.py
python
Type.get_pointee
(self)
return conf.lib.clang_getPointeeType(self)
For pointer types, returns the type of the pointee.
For pointer types, returns the type of the pointee.
[ "For", "pointer", "types", "returns", "the", "type", "of", "the", "pointee", "." ]
def get_pointee(self): """ For pointer types, returns the type of the pointee. """ return conf.lib.clang_getPointeeType(self)
[ "def", "get_pointee", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_getPointeeType", "(", "self", ")" ]
https://github.com/yrnkrn/zapcc/blob/c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50/tools/clang/bindings/python/clang/cindex.py#L2303-L2307
Samsung/veles
95ed733c2e49bc011ad98ccf2416ecec23fbf352
veles/external/freetype/__init__.py
python
Face.select_size
(self, strike_index)
Select a bitmap strike. :param strike_index: The index of the bitmap strike in the 'available_sizes' field of Face object.
Select a bitmap strike.
[ "Select", "a", "bitmap", "strike", "." ]
def select_size(self, strike_index): ''' Select a bitmap strike. :param strike_index: The index of the bitmap strike in the 'available_sizes' field of Face object. ''' error = FT_Select_Size(self._FT_Face, strike_index) if error: raise FT_Exception(error)
[ "def", "select_size", "(", "self", ",", "strike_index", ")", ":", "error", "=", "FT_Select_Size", "(", "self", ".", "_FT_Face", ",", "strike_index", ")", "if", "error", ":", "raise", "FT_Exception", "(", "error", ")" ]
https://github.com/Samsung/veles/blob/95ed733c2e49bc011ad98ccf2416ecec23fbf352/veles/external/freetype/__init__.py#L1246-L1254
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/burn_in_tags.py
python
main
(expansion_file: str, verbose: bool)
Run new or changed tests in repeated mode to validate their stability. burn_in_tags detects jstests that are new or changed since the last git command and then runs those tests in a loop to validate their reliability. \f :param expansion_file: The expansion file containing the configuration params.
Run new or changed tests in repeated mode to validate their stability.
[ "Run", "new", "or", "changed", "tests", "in", "repeated", "mode", "to", "validate", "their", "stability", "." ]
def main(expansion_file: str, verbose: bool): """ Run new or changed tests in repeated mode to validate their stability. burn_in_tags detects jstests that are new or changed since the last git command and then runs those tests in a loop to validate their reliability. \f :param expansion_file: The expansion file containing the configuration params. """ _configure_logging(verbose) evg_api = RetryingEvergreenApi.get_api(config_file=EVG_CONFIG_FILE) repos = [Repo(x) for x in DEFAULT_REPO_LOCATIONS if os.path.isdir(x)] expansions_file_data = read_config.read_config_file(expansion_file) evg_conf = evergreen.parse_evergreen_file(EVERGREEN_FILE) burn_in(expansions_file_data, evg_conf, evg_api, repos)
[ "def", "main", "(", "expansion_file", ":", "str", ",", "verbose", ":", "bool", ")", ":", "_configure_logging", "(", "verbose", ")", "evg_api", "=", "RetryingEvergreenApi", ".", "get_api", "(", "config_file", "=", "EVG_CONFIG_FILE", ")", "repos", "=", "[", "Repo", "(", "x", ")", "for", "x", "in", "DEFAULT_REPO_LOCATIONS", "if", "os", ".", "path", ".", "isdir", "(", "x", ")", "]", "expansions_file_data", "=", "read_config", ".", "read_config_file", "(", "expansion_file", ")", "evg_conf", "=", "evergreen", ".", "parse_evergreen_file", "(", "EVERGREEN_FILE", ")", "burn_in", "(", "expansions_file_data", ",", "evg_conf", ",", "evg_api", ",", "repos", ")" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/burn_in_tags.py#L207-L223
facebookincubator/BOLT
88c70afe9d388ad430cc150cc158641701397f70
lldb/packages/Python/lldbsuite/support/seven.py
python
bitcast_to_bytes
(s)
return s if six.PY2 else s.encode("latin1")
Take a string and return a string(PY2) or a bytes(PY3) object. The returned object contains the exact same bytes as the input string. (latin1 <-> unicode transformation is an identity operation for the first 256 code points).
Take a string and return a string(PY2) or a bytes(PY3) object. The returned object contains the exact same bytes as the input string. (latin1 <-> unicode transformation is an identity operation for the first 256 code points).
[ "Take", "a", "string", "and", "return", "a", "string", "(", "PY2", ")", "or", "a", "bytes", "(", "PY3", ")", "object", ".", "The", "returned", "object", "contains", "the", "exact", "same", "bytes", "as", "the", "input", "string", ".", "(", "latin1", "<", "-", ">", "unicode", "transformation", "is", "an", "identity", "operation", "for", "the", "first", "256", "code", "points", ")", "." ]
def bitcast_to_bytes(s): """ Take a string and return a string(PY2) or a bytes(PY3) object. The returned object contains the exact same bytes as the input string. (latin1 <-> unicode transformation is an identity operation for the first 256 code points). """ return s if six.PY2 else s.encode("latin1")
[ "def", "bitcast_to_bytes", "(", "s", ")", ":", "return", "s", "if", "six", ".", "PY2", "else", "s", ".", "encode", "(", "\"latin1\"", ")" ]
https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/lldb/packages/Python/lldbsuite/support/seven.py#L37-L44
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/ftplib.py
python
FTP.login
(self, user = '', passwd = '', acct = '')
return resp
Login, default anonymous.
Login, default anonymous.
[ "Login", "default", "anonymous", "." ]
def login(self, user = '', passwd = '', acct = ''): '''Login, default anonymous.''' if not user: user = 'anonymous' if not passwd: passwd = '' if not acct: acct = '' if user == 'anonymous' and passwd in ('', '-'): # If there is no anonymous ftp password specified # then we'll just use anonymous@ # We don't send any other thing because: # - We want to remain anonymous # - We want to stop SPAM # - We don't want to let ftp sites to discriminate by the user, # host or country. passwd = passwd + 'anonymous@' resp = self.sendcmd('USER ' + user) if resp[0] == '3': resp = self.sendcmd('PASS ' + passwd) if resp[0] == '3': resp = self.sendcmd('ACCT ' + acct) if resp[0] != '2': raise error_reply, resp return resp
[ "def", "login", "(", "self", ",", "user", "=", "''", ",", "passwd", "=", "''", ",", "acct", "=", "''", ")", ":", "if", "not", "user", ":", "user", "=", "'anonymous'", "if", "not", "passwd", ":", "passwd", "=", "''", "if", "not", "acct", ":", "acct", "=", "''", "if", "user", "==", "'anonymous'", "and", "passwd", "in", "(", "''", ",", "'-'", ")", ":", "# If there is no anonymous ftp password specified", "# then we'll just use anonymous@", "# We don't send any other thing because:", "# - We want to remain anonymous", "# - We want to stop SPAM", "# - We don't want to let ftp sites to discriminate by the user,", "# host or country.", "passwd", "=", "passwd", "+", "'anonymous@'", "resp", "=", "self", ".", "sendcmd", "(", "'USER '", "+", "user", ")", "if", "resp", "[", "0", "]", "==", "'3'", ":", "resp", "=", "self", ".", "sendcmd", "(", "'PASS '", "+", "passwd", ")", "if", "resp", "[", "0", "]", "==", "'3'", ":", "resp", "=", "self", ".", "sendcmd", "(", "'ACCT '", "+", "acct", ")", "if", "resp", "[", "0", "]", "!=", "'2'", ":", "raise", "error_reply", ",", "resp", "return", "resp" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/ftplib.py#L358-L377
learnforpractice/pyeos
4f04eb982c86c1fdb413084af77c713a6fda3070
libraries/vm/vm_cpython_ss/lib/abc.py
python
get_cache_token
()
return ABCMeta._abc_invalidation_counter
Returns the current ABC cache token. The token is an opaque object (supporting equality testing) identifying the current version of the ABC cache for virtual subclasses. The token changes with every call to ``register()`` on any ABC.
Returns the current ABC cache token.
[ "Returns", "the", "current", "ABC", "cache", "token", "." ]
def get_cache_token(): """Returns the current ABC cache token. The token is an opaque object (supporting equality testing) identifying the current version of the ABC cache for virtual subclasses. The token changes with every call to ``register()`` on any ABC. """ return ABCMeta._abc_invalidation_counter
[ "def", "get_cache_token", "(", ")", ":", "return", "ABCMeta", ".", "_abc_invalidation_counter" ]
https://github.com/learnforpractice/pyeos/blob/4f04eb982c86c1fdb413084af77c713a6fda3070/libraries/vm/vm_cpython_ss/lib/abc.py#L241-L248
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/telemetry/benchmark.py
python
Benchmark.SetupBenchmarkDefaultTraceRerunOptions
(self, tbm_options)
Setup tracing categories associated with default trace option.
Setup tracing categories associated with default trace option.
[ "Setup", "tracing", "categories", "associated", "with", "default", "trace", "option", "." ]
def SetupBenchmarkDefaultTraceRerunOptions(self, tbm_options): """Setup tracing categories associated with default trace option."""
[ "def", "SetupBenchmarkDefaultTraceRerunOptions", "(", "self", ",", "tbm_options", ")", ":" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/benchmark.py#L165-L166
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/debug/debug_data.py
python
DebugTensorDatum.__init__
(self, dump_root, debug_dump_rel_path)
DebugTensorDatum constructor. Args: dump_root: Debug dump root directory. debug_dump_rel_path: Path to a debug dump file, relative to the debug dump root directory. For example, suppose the debug dump root directory is "/tmp/tfdbg_1" and the dump file is at "/tmp/tfdbg_1/ns_1/node_a_0_DebugIdentity_123456789", then the value of the debug_dump_rel_path should be "ns_1/node_a_0_DebugIdenity_1234456789".
DebugTensorDatum constructor.
[ "DebugTensorDatum", "constructor", "." ]
def __init__(self, dump_root, debug_dump_rel_path): """DebugTensorDatum constructor. Args: dump_root: Debug dump root directory. debug_dump_rel_path: Path to a debug dump file, relative to the debug dump root directory. For example, suppose the debug dump root directory is "/tmp/tfdbg_1" and the dump file is at "/tmp/tfdbg_1/ns_1/node_a_0_DebugIdentity_123456789", then the value of the debug_dump_rel_path should be "ns_1/node_a_0_DebugIdenity_1234456789". """ base = os.path.basename(debug_dump_rel_path) # TODO(cais): Add hostname and pid to support dumps from distributed # sessions. self._timestamp = int(base.split("_")[-1]) self._debug_op = base.split("_")[-2] self._output_slot = int(base.split("_")[-3]) namespace = os.path.dirname(debug_dump_rel_path) node_base_name = "_".join(base.split("_")[:-3]) if not namespace or namespace == ".": self._node_name = node_base_name else: self._node_name = namespace + "/" + node_base_name self._file_path = os.path.join(dump_root, debug_dump_rel_path)
[ "def", "__init__", "(", "self", ",", "dump_root", ",", "debug_dump_rel_path", ")", ":", "base", "=", "os", ".", "path", ".", "basename", "(", "debug_dump_rel_path", ")", "# TODO(cais): Add hostname and pid to support dumps from distributed", "# sessions.", "self", ".", "_timestamp", "=", "int", "(", "base", ".", "split", "(", "\"_\"", ")", "[", "-", "1", "]", ")", "self", ".", "_debug_op", "=", "base", ".", "split", "(", "\"_\"", ")", "[", "-", "2", "]", "self", ".", "_output_slot", "=", "int", "(", "base", ".", "split", "(", "\"_\"", ")", "[", "-", "3", "]", ")", "namespace", "=", "os", ".", "path", ".", "dirname", "(", "debug_dump_rel_path", ")", "node_base_name", "=", "\"_\"", ".", "join", "(", "base", ".", "split", "(", "\"_\"", ")", "[", ":", "-", "3", "]", ")", "if", "not", "namespace", "or", "namespace", "==", "\".\"", ":", "self", ".", "_node_name", "=", "node_base_name", "else", ":", "self", ".", "_node_name", "=", "namespace", "+", "\"/\"", "+", "node_base_name", "self", ".", "_file_path", "=", "os", ".", "path", ".", "join", "(", "dump_root", ",", "debug_dump_rel_path", ")" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/debug/debug_data.py#L220-L248
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/ops/io_ops.py
python
FixedLengthRecordReader.__init__
(self, record_bytes, header_bytes=None, footer_bytes=None, name=None)
Create a FixedLengthRecordReader. Args: record_bytes: An int. header_bytes: An optional int. Defaults to 0. footer_bytes: An optional int. Defaults to 0. name: A name for the operation (optional).
Create a FixedLengthRecordReader.
[ "Create", "a", "FixedLengthRecordReader", "." ]
def __init__(self, record_bytes, header_bytes=None, footer_bytes=None, name=None): """Create a FixedLengthRecordReader. Args: record_bytes: An int. header_bytes: An optional int. Defaults to 0. footer_bytes: An optional int. Defaults to 0. name: A name for the operation (optional). """ rr = gen_io_ops._fixed_length_record_reader( record_bytes=record_bytes, header_bytes=header_bytes, footer_bytes=footer_bytes, name=name) super(FixedLengthRecordReader, self).__init__(rr)
[ "def", "__init__", "(", "self", ",", "record_bytes", ",", "header_bytes", "=", "None", ",", "footer_bytes", "=", "None", ",", "name", "=", "None", ")", ":", "rr", "=", "gen_io_ops", ".", "_fixed_length_record_reader", "(", "record_bytes", "=", "record_bytes", ",", "header_bytes", "=", "header_bytes", ",", "footer_bytes", "=", "footer_bytes", ",", "name", "=", "name", ")", "super", "(", "FixedLengthRecordReader", ",", "self", ")", ".", "__init__", "(", "rr", ")" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/io_ops.py#L501-L514
wyrover/book-code
7f4883d9030d553bc6bcfa3da685e34789839900
3rdparty/protobuf/python/google/protobuf/text_format.py
python
_Parser.ParseLines
(self, lines, message)
return message
Parses a text representation of a protocol message into a message.
Parses a text representation of a protocol message into a message.
[ "Parses", "a", "text", "representation", "of", "a", "protocol", "message", "into", "a", "message", "." ]
def ParseLines(self, lines, message): """Parses a text representation of a protocol message into a message.""" self._allow_multiple_scalars = False self._ParseOrMerge(lines, message) return message
[ "def", "ParseLines", "(", "self", ",", "lines", ",", "message", ")", ":", "self", ".", "_allow_multiple_scalars", "=", "False", "self", ".", "_ParseOrMerge", "(", "lines", ",", "message", ")", "return", "message" ]
https://github.com/wyrover/book-code/blob/7f4883d9030d553bc6bcfa3da685e34789839900/3rdparty/protobuf/python/google/protobuf/text_format.py#L547-L551
jiangxiluning/FOTS.PyTorch
b1851c170b4f1ad18406766352cb5171648ce603
FOTS/utils/eval_tools/icdar2015/rrc_evaluation_funcs.py
python
decode_utf8
(raw)
Returns a Unicode object on success, or None on failure
Returns a Unicode object on success, or None on failure
[ "Returns", "a", "Unicode", "object", "on", "success", "or", "None", "on", "failure" ]
def decode_utf8(raw): """ Returns a Unicode object on success, or None on failure """ try: raw = codecs.decode(raw,'utf-8', 'replace') #extracts BOM if exists raw = raw.encode('utf8') if raw.startswith(codecs.BOM_UTF8): raw = raw.replace(codecs.BOM_UTF8, '', 1) return raw.decode('utf-8') except: return None
[ "def", "decode_utf8", "(", "raw", ")", ":", "try", ":", "raw", "=", "codecs", ".", "decode", "(", "raw", ",", "'utf-8'", ",", "'replace'", ")", "#extracts BOM if exists", "raw", "=", "raw", ".", "encode", "(", "'utf8'", ")", "if", "raw", ".", "startswith", "(", "codecs", ".", "BOM_UTF8", ")", ":", "raw", "=", "raw", ".", "replace", "(", "codecs", ".", "BOM_UTF8", ",", "''", ",", "1", ")", "return", "raw", ".", "decode", "(", "'utf-8'", ")", "except", ":", "return", "None" ]
https://github.com/jiangxiluning/FOTS.PyTorch/blob/b1851c170b4f1ad18406766352cb5171648ce603/FOTS/utils/eval_tools/icdar2015/rrc_evaluation_funcs.py#L78-L90
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/distribute/input_lib.py
python
_IterableInput.reduce
(self, initial_state, reduce_fn)
return final_state
Execute a `reduce_fn` over all the elements of the input.
Execute a `reduce_fn` over all the elements of the input.
[ "Execute", "a", "reduce_fn", "over", "all", "the", "elements", "of", "the", "input", "." ]
def reduce(self, initial_state, reduce_fn): """Execute a `reduce_fn` over all the elements of the input.""" iterator = iter(self) optional_data = iterator.get_next_as_optional() def cond(optional_data, state): del state # Unused. return optional_data.has_value() def loop_body(optional_data, state): """Executes `reduce_fn` in a loop till the dataset is empty.""" state = reduce_fn(state, optional_data.get_value()) optional_data = iterator.get_next_as_optional() return optional_data, state optional_data, final_state = control_flow_ops.while_loop( cond, loop_body, [optional_data, initial_state], parallel_iterations=1, return_same_structure=True) return final_state
[ "def", "reduce", "(", "self", ",", "initial_state", ",", "reduce_fn", ")", ":", "iterator", "=", "iter", "(", "self", ")", "optional_data", "=", "iterator", ".", "get_next_as_optional", "(", ")", "def", "cond", "(", "optional_data", ",", "state", ")", ":", "del", "state", "# Unused.", "return", "optional_data", ".", "has_value", "(", ")", "def", "loop_body", "(", "optional_data", ",", "state", ")", ":", "\"\"\"Executes `reduce_fn` in a loop till the dataset is empty.\"\"\"", "state", "=", "reduce_fn", "(", "state", ",", "optional_data", ".", "get_value", "(", ")", ")", "optional_data", "=", "iterator", ".", "get_next_as_optional", "(", ")", "return", "optional_data", ",", "state", "optional_data", ",", "final_state", "=", "control_flow_ops", ".", "while_loop", "(", "cond", ",", "loop_body", ",", "[", "optional_data", ",", "initial_state", "]", ",", "parallel_iterations", "=", "1", ",", "return_same_structure", "=", "True", ")", "return", "final_state" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/distribute/input_lib.py#L869-L889
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/protobuf/py2/google/protobuf/text_format.py
python
ParseFloat
(text)
Parse a floating point number. Args: text: Text to parse. Returns: The number parsed. Raises: ValueError: If a floating point number couldn't be parsed.
Parse a floating point number.
[ "Parse", "a", "floating", "point", "number", "." ]
def ParseFloat(text): """Parse a floating point number. Args: text: Text to parse. Returns: The number parsed. Raises: ValueError: If a floating point number couldn't be parsed. """ try: # Assume Python compatible syntax. return float(text) except ValueError: # Check alternative spellings. if _FLOAT_INFINITY.match(text): if text[0] == '-': return float('-inf') else: return float('inf') elif _FLOAT_NAN.match(text): return float('nan') else: # assume '1.0f' format try: return float(text.rstrip('f')) except ValueError: raise ValueError('Couldn\'t parse float: %s' % text)
[ "def", "ParseFloat", "(", "text", ")", ":", "try", ":", "# Assume Python compatible syntax.", "return", "float", "(", "text", ")", "except", "ValueError", ":", "# Check alternative spellings.", "if", "_FLOAT_INFINITY", ".", "match", "(", "text", ")", ":", "if", "text", "[", "0", "]", "==", "'-'", ":", "return", "float", "(", "'-inf'", ")", "else", ":", "return", "float", "(", "'inf'", ")", "elif", "_FLOAT_NAN", ".", "match", "(", "text", ")", ":", "return", "float", "(", "'nan'", ")", "else", ":", "# assume '1.0f' format", "try", ":", "return", "float", "(", "text", ".", "rstrip", "(", "'f'", ")", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'Couldn\\'t parse float: %s'", "%", "text", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py2/google/protobuf/text_format.py#L1738-L1767
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_misc.py
python
DataObjectComposite.GetObject
(*args, **kwargs)
return _misc_.DataObjectComposite_GetObject(*args, **kwargs)
GetObject(self, DataFormat format, wxDataObjectBase::Direction dir=Get) -> DataObjectSimple Returns the pointer to the object which supports this format or None. TODO: Fix this to use OOR and return the right object type.
GetObject(self, DataFormat format, wxDataObjectBase::Direction dir=Get) -> DataObjectSimple
[ "GetObject", "(", "self", "DataFormat", "format", "wxDataObjectBase", "::", "Direction", "dir", "=", "Get", ")", "-", ">", "DataObjectSimple" ]
def GetObject(*args, **kwargs): """ GetObject(self, DataFormat format, wxDataObjectBase::Direction dir=Get) -> DataObjectSimple Returns the pointer to the object which supports this format or None. TODO: Fix this to use OOR and return the right object type. """ return _misc_.DataObjectComposite_GetObject(*args, **kwargs)
[ "def", "GetObject", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "DataObjectComposite_GetObject", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L5154-L5161
ZhouWeikuan/DouDiZhu
0d84ff6c0bc54dba6ae37955de9ae9307513dc99
code/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py
python
CursorKind.is_attribute
(self)
return conf.lib.clang_isAttribute(self)
Test if this is an attribute kind.
Test if this is an attribute kind.
[ "Test", "if", "this", "is", "an", "attribute", "kind", "." ]
def is_attribute(self): """Test if this is an attribute kind.""" return conf.lib.clang_isAttribute(self)
[ "def", "is_attribute", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_isAttribute", "(", "self", ")" ]
https://github.com/ZhouWeikuan/DouDiZhu/blob/0d84ff6c0bc54dba6ae37955de9ae9307513dc99/code/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py#L648-L650
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Path/PathScripts/PathSanity.py
python
CommandPathSanity.__toolData
(self, obj)
return data
Returns information about the tools used in the job, and associated toolcontrollers Returns information about issues and problems with the tools (squawks)
Returns information about the tools used in the job, and associated toolcontrollers Returns information about issues and problems with the tools (squawks)
[ "Returns", "information", "about", "the", "tools", "used", "in", "the", "job", "and", "associated", "toolcontrollers", "Returns", "information", "about", "issues", "and", "problems", "with", "the", "tools", "(", "squawks", ")" ]
def __toolData(self, obj): """ Returns information about the tools used in the job, and associated toolcontrollers Returns information about issues and problems with the tools (squawks) """ data = {} try: for TC in obj.Tools.Group: if not hasattr(TC.Tool, "BitBody"): self.squawk( "PathSanity", "Tool number {} is a legacy tool. Legacy tools not \ supported by Path-Sanity".format( TC.ToolNumber ), squawkType="WARNING", ) continue # skip old-style tools tooldata = data.setdefault(str(TC.ToolNumber), {}) bitshape = tooldata.setdefault("BitShape", "") if bitshape not in ["", TC.Tool.BitShape]: self.squawk( "PathSanity", "Tool number {} used by multiple tools".format(TC.ToolNumber), squawkType="CAUTION", ) tooldata["bitShape"] = TC.Tool.BitShape tooldata["description"] = TC.Tool.Label tooldata["manufacturer"] = "" tooldata["url"] = "" tooldata["inspectionNotes"] = "" tooldata["diameter"] = str(TC.Tool.Diameter) tooldata["shape"] = TC.Tool.ShapeName tooldata["partNumber"] = "" imagedata = TC.Tool.Proxy.getBitThumbnail(TC.Tool) imagepath = "{}T{}.png".format(self.outputpath, TC.ToolNumber) tooldata["feedrate"] = str(TC.HorizFeed) if TC.HorizFeed.Value == 0.0: self.squawk( "PathSanity", "Tool Controller '{}' has no feedrate".format(TC.Label), squawkType="WARNING", ) tooldata["spindlespeed"] = str(TC.SpindleSpeed) if TC.SpindleSpeed == 0.0: self.squawk( "PathSanity", "Tool Controller '{}' has no spindlespeed".format(TC.Label), squawkType="WARNING", ) with open(imagepath, "wb") as fd: fd.write(imagedata) fd.close() tooldata["imagepath"] = imagepath used = False for op in obj.Operations.Group: if hasattr(op, "ToolController") and op.ToolController is TC: used = True tooldata.setdefault("ops", []).append( { "Operation": op.Label, "ToolController": TC.Label, "Feed": str(TC.HorizFeed), "Speed": str(TC.SpindleSpeed), } ) if used is False: tooldata.setdefault("ops", []) self.squawk( "PathSanity", "Tool Controller '{}' is not used".format(TC.Label), squawkType="WARNING", ) except Exception as e: data["errors"] = e self.squawk("PathSanity(__toolData)", e, squawkType="CAUTION") return data
[ "def", "__toolData", "(", "self", ",", "obj", ")", ":", "data", "=", "{", "}", "try", ":", "for", "TC", "in", "obj", ".", "Tools", ".", "Group", ":", "if", "not", "hasattr", "(", "TC", ".", "Tool", ",", "\"BitBody\"", ")", ":", "self", ".", "squawk", "(", "\"PathSanity\"", ",", "\"Tool number {} is a legacy tool. Legacy tools not \\\n supported by Path-Sanity\"", ".", "format", "(", "TC", ".", "ToolNumber", ")", ",", "squawkType", "=", "\"WARNING\"", ",", ")", "continue", "# skip old-style tools", "tooldata", "=", "data", ".", "setdefault", "(", "str", "(", "TC", ".", "ToolNumber", ")", ",", "{", "}", ")", "bitshape", "=", "tooldata", ".", "setdefault", "(", "\"BitShape\"", ",", "\"\"", ")", "if", "bitshape", "not", "in", "[", "\"\"", ",", "TC", ".", "Tool", ".", "BitShape", "]", ":", "self", ".", "squawk", "(", "\"PathSanity\"", ",", "\"Tool number {} used by multiple tools\"", ".", "format", "(", "TC", ".", "ToolNumber", ")", ",", "squawkType", "=", "\"CAUTION\"", ",", ")", "tooldata", "[", "\"bitShape\"", "]", "=", "TC", ".", "Tool", ".", "BitShape", "tooldata", "[", "\"description\"", "]", "=", "TC", ".", "Tool", ".", "Label", "tooldata", "[", "\"manufacturer\"", "]", "=", "\"\"", "tooldata", "[", "\"url\"", "]", "=", "\"\"", "tooldata", "[", "\"inspectionNotes\"", "]", "=", "\"\"", "tooldata", "[", "\"diameter\"", "]", "=", "str", "(", "TC", ".", "Tool", ".", "Diameter", ")", "tooldata", "[", "\"shape\"", "]", "=", "TC", ".", "Tool", ".", "ShapeName", "tooldata", "[", "\"partNumber\"", "]", "=", "\"\"", "imagedata", "=", "TC", ".", "Tool", ".", "Proxy", ".", "getBitThumbnail", "(", "TC", ".", "Tool", ")", "imagepath", "=", "\"{}T{}.png\"", ".", "format", "(", "self", ".", "outputpath", ",", "TC", ".", "ToolNumber", ")", "tooldata", "[", "\"feedrate\"", "]", "=", "str", "(", "TC", ".", "HorizFeed", ")", "if", "TC", ".", "HorizFeed", ".", "Value", "==", "0.0", ":", "self", ".", "squawk", "(", "\"PathSanity\"", ",", "\"Tool Controller '{}' has no feedrate\"", ".", "format", "(", "TC", ".", "Label", ")", ",", "squawkType", "=", "\"WARNING\"", ",", ")", "tooldata", "[", "\"spindlespeed\"", "]", "=", "str", "(", "TC", ".", "SpindleSpeed", ")", "if", "TC", ".", "SpindleSpeed", "==", "0.0", ":", "self", ".", "squawk", "(", "\"PathSanity\"", ",", "\"Tool Controller '{}' has no spindlespeed\"", ".", "format", "(", "TC", ".", "Label", ")", ",", "squawkType", "=", "\"WARNING\"", ",", ")", "with", "open", "(", "imagepath", ",", "\"wb\"", ")", "as", "fd", ":", "fd", ".", "write", "(", "imagedata", ")", "fd", ".", "close", "(", ")", "tooldata", "[", "\"imagepath\"", "]", "=", "imagepath", "used", "=", "False", "for", "op", "in", "obj", ".", "Operations", ".", "Group", ":", "if", "hasattr", "(", "op", ",", "\"ToolController\"", ")", "and", "op", ".", "ToolController", "is", "TC", ":", "used", "=", "True", "tooldata", ".", "setdefault", "(", "\"ops\"", ",", "[", "]", ")", ".", "append", "(", "{", "\"Operation\"", ":", "op", ".", "Label", ",", "\"ToolController\"", ":", "TC", ".", "Label", ",", "\"Feed\"", ":", "str", "(", "TC", ".", "HorizFeed", ")", ",", "\"Speed\"", ":", "str", "(", "TC", ".", "SpindleSpeed", ")", ",", "}", ")", "if", "used", "is", "False", ":", "tooldata", ".", "setdefault", "(", "\"ops\"", ",", "[", "]", ")", "self", ".", "squawk", "(", "\"PathSanity\"", ",", "\"Tool Controller '{}' is not used\"", ".", "format", "(", "TC", ".", "Label", ")", ",", "squawkType", "=", "\"WARNING\"", ",", ")", "except", "Exception", "as", "e", ":", "data", "[", "\"errors\"", "]", "=", "e", "self", ".", "squawk", "(", "\"PathSanity(__toolData)\"", ",", "e", ",", "squawkType", "=", "\"CAUTION\"", ")", "return", "data" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathSanity.py#L568-L653
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/jsonschema/_format.py
python
FormatChecker.check
(self, instance, format)
Check whether the instance conforms to the given format. Arguments: instance (*any primitive type*, i.e. str, number, bool): The instance to check format (str): The format that instance should conform to Raises: FormatError: if the instance does not conform to ``format``
Check whether the instance conforms to the given format.
[ "Check", "whether", "the", "instance", "conforms", "to", "the", "given", "format", "." ]
def check(self, instance, format): """ Check whether the instance conforms to the given format. Arguments: instance (*any primitive type*, i.e. str, number, bool): The instance to check format (str): The format that instance should conform to Raises: FormatError: if the instance does not conform to ``format`` """ if format not in self.checkers: return func, raises = self.checkers[format] result, cause = None, None try: result = func(instance) except raises as e: cause = e if not result: raise FormatError( "%r is not a %r" % (instance, format), cause=cause, )
[ "def", "check", "(", "self", ",", "instance", ",", "format", ")", ":", "if", "format", "not", "in", "self", ".", "checkers", ":", "return", "func", ",", "raises", "=", "self", ".", "checkers", "[", "format", "]", "result", ",", "cause", "=", "None", ",", "None", "try", ":", "result", "=", "func", "(", "instance", ")", "except", "raises", "as", "e", ":", "cause", "=", "e", "if", "not", "result", ":", "raise", "FormatError", "(", "\"%r is not a %r\"", "%", "(", "instance", ",", "format", ")", ",", "cause", "=", "cause", ",", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/jsonschema/_format.py#L71-L103
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/sparse_grad.py
python
_SparseFillEmptyRowsGrad
(op, unused_grad_output_indices, output_grad_values, unused_grad_empty_row_indicator, unused_grad_reverse_index_map)
return [None, d_values, None, d_default_value]
Gradients for SparseFillEmptyRows.
Gradients for SparseFillEmptyRows.
[ "Gradients", "for", "SparseFillEmptyRows", "." ]
def _SparseFillEmptyRowsGrad(op, unused_grad_output_indices, output_grad_values, unused_grad_empty_row_indicator, unused_grad_reverse_index_map): """Gradients for SparseFillEmptyRows.""" reverse_index_map = op.outputs[3] # pylint: disable=protected-access d_values, d_default_value = gen_sparse_ops._sparse_fill_empty_rows_grad( reverse_index_map=reverse_index_map, grad_values=output_grad_values) # d_indices, d_values, d_dense_shape, d_default_value. return [None, d_values, None, d_default_value]
[ "def", "_SparseFillEmptyRowsGrad", "(", "op", ",", "unused_grad_output_indices", ",", "output_grad_values", ",", "unused_grad_empty_row_indicator", ",", "unused_grad_reverse_index_map", ")", ":", "reverse_index_map", "=", "op", ".", "outputs", "[", "3", "]", "# pylint: disable=protected-access", "d_values", ",", "d_default_value", "=", "gen_sparse_ops", ".", "_sparse_fill_empty_rows_grad", "(", "reverse_index_map", "=", "reverse_index_map", ",", "grad_values", "=", "output_grad_values", ")", "# d_indices, d_values, d_dense_shape, d_default_value.", "return", "[", "None", ",", "d_values", ",", "None", ",", "d_default_value", "]" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/sparse_grad.py#L275-L286
apache/madlib
be297fe6beada0640f93317e8948834032718e32
src/madpack/upgrade_util.py
python
ChangeHandler._get_current_version
(self)
Get current version of MADlib This currently assumes that version is available in '$MADLIB_HOME/src/config/Version.yml'
Get current version of MADlib
[ "Get", "current", "version", "of", "MADlib" ]
def _get_current_version(self): """ Get current version of MADlib This currently assumes that version is available in '$MADLIB_HOME/src/config/Version.yml' """ version_filepath = os.path.abspath( os.path.join(self._maddir, 'config', 'Version.yml')) with open(version_filepath) as ver_file: version_str = str(yaml.load(ver_file)['version']) return get_rev_num(version_str)
[ "def", "_get_current_version", "(", "self", ")", ":", "version_filepath", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_maddir", ",", "'config'", ",", "'Version.yml'", ")", ")", "with", "open", "(", "version_filepath", ")", "as", "ver_file", ":", "version_str", "=", "str", "(", "yaml", ".", "load", "(", "ver_file", ")", "[", "'version'", "]", ")", "return", "get_rev_num", "(", "version_str", ")" ]
https://github.com/apache/madlib/blob/be297fe6beada0640f93317e8948834032718e32/src/madpack/upgrade_util.py#L147-L157
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/coremltools_wrap/coremltools/coremltools/converters/onnx/_operators_nd.py
python
_convert_mean
(builder, node, graph, err)
convert to CoreML Add Broadcastable Layer and Divide BroadCastable Layer: https://github.com/apple/coremltools/blob/655b3be5cc0d42c3c4fa49f0f0e4a93a26b3e492/mlmodel/format/NeuralNetwork.proto#L4117
convert to CoreML Add Broadcastable Layer and Divide BroadCastable Layer: https://github.com/apple/coremltools/blob/655b3be5cc0d42c3c4fa49f0f0e4a93a26b3e492/mlmodel/format/NeuralNetwork.proto#L4117
[ "convert", "to", "CoreML", "Add", "Broadcastable", "Layer", "and", "Divide", "BroadCastable", "Layer", ":", "https", ":", "//", "github", ".", "com", "/", "apple", "/", "coremltools", "/", "blob", "/", "655b3be5cc0d42c3c4fa49f0f0e4a93a26b3e492", "/", "mlmodel", "/", "format", "/", "NeuralNetwork", ".", "proto#L4117" ]
def _convert_mean(builder, node, graph, err): """ convert to CoreML Add Broadcastable Layer and Divide BroadCastable Layer: https://github.com/apple/coremltools/blob/655b3be5cc0d42c3c4fa49f0f0e4a93a26b3e492/mlmodel/format/NeuralNetwork.proto#L4117 """ number_of_inputs = len(node.inputs) output_name = node.outputs[0] node.outputs[0] = node.outputs[0] + "_sum" builder.add_load_constant_nd( name=node.name + "_divider", output_name=output_name + "_divider", constant_value=np.array(number_of_inputs), shape=[1], ) add_broadcastable_op_chain(builder, node, err, builder.add_add_broadcastable) builder.add_divide_broadcastable( name=node.name + "_mean", input_names=[node.outputs[0], output_name + "_divider"], output_name=output_name, )
[ "def", "_convert_mean", "(", "builder", ",", "node", ",", "graph", ",", "err", ")", ":", "number_of_inputs", "=", "len", "(", "node", ".", "inputs", ")", "output_name", "=", "node", ".", "outputs", "[", "0", "]", "node", ".", "outputs", "[", "0", "]", "=", "node", ".", "outputs", "[", "0", "]", "+", "\"_sum\"", "builder", ".", "add_load_constant_nd", "(", "name", "=", "node", ".", "name", "+", "\"_divider\"", ",", "output_name", "=", "output_name", "+", "\"_divider\"", ",", "constant_value", "=", "np", ".", "array", "(", "number_of_inputs", ")", ",", "shape", "=", "[", "1", "]", ",", ")", "add_broadcastable_op_chain", "(", "builder", ",", "node", ",", "err", ",", "builder", ".", "add_add_broadcastable", ")", "builder", ".", "add_divide_broadcastable", "(", "name", "=", "node", ".", "name", "+", "\"_mean\"", ",", "input_names", "=", "[", "node", ".", "outputs", "[", "0", "]", ",", "output_name", "+", "\"_divider\"", "]", ",", "output_name", "=", "output_name", ",", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/coremltools/converters/onnx/_operators_nd.py#L1671-L1691
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
tools/mo/openvino/tools/mo/front/onnx/loader.py
python
add_initializers_and_inputs_to_graph
(graph: Graph, graph_pb, data_nodes_map: dict)
return parameters
The function adds nodes specified in the 'initializer' attribute of the pb and input nodes. :param graph: the Graph to add nodes to :param graph_pb: the graph protobuf message :param data_nodes_map: the dictionary with mapping of tensor names to node id and port :return: the list of Parameter nodes
The function adds nodes specified in the 'initializer' attribute of the pb and input nodes. :param graph: the Graph to add nodes to :param graph_pb: the graph protobuf message :param data_nodes_map: the dictionary with mapping of tensor names to node id and port :return: the list of Parameter nodes
[ "The", "function", "adds", "nodes", "specified", "in", "the", "initializer", "attribute", "of", "the", "pb", "and", "input", "nodes", ".", ":", "param", "graph", ":", "the", "Graph", "to", "add", "nodes", "to", ":", "param", "graph_pb", ":", "the", "graph", "protobuf", "message", ":", "param", "data_nodes_map", ":", "the", "dictionary", "with", "mapping", "of", "tensor", "names", "to", "node", "id", "and", "port", ":", "return", ":", "the", "list", "of", "Parameter", "nodes" ]
def add_initializers_and_inputs_to_graph(graph: Graph, graph_pb, data_nodes_map: dict): """ The function adds nodes specified in the 'initializer' attribute of the pb and input nodes. :param graph: the Graph to add nodes to :param graph_pb: the graph protobuf message :param data_nodes_map: the dictionary with mapping of tensor names to node id and port :return: the list of Parameter nodes """ initializers = Graph() fill_graph_with_nodes(initializers, graph_pb.initializer, get_id=lambda pb: pb.name, get_attrs=protobuf_attrs) parameters = [] # first go through all inputs and separate constant from placeholders for inp in graph_pb.input: name = str(inp.name) if graph.has_node(name): raise Error('Name {} of input node already exists, input names are duplicated.', name) elif initializers.has_node(name): graph.add_node(name, kind='op', op='Const', pb=inp, pb_init=initializers.node[name]['pb']) else: graph.add_node(name, kind='op', op='Parameter', pb=inp) parameters.append(Node(graph, name)) assert name not in data_nodes_map, 'Inconsistency between data_nodes_map and graph.nodes' data_nodes_map[name] = (name, 0) # go over all initializers and make sure that all of them are added to the graph for initializer in initializers.nodes(): initializer_id = initializer if not graph.has_node(initializer_id): graph.add_node(initializer_id, kind='op', op='Const', pb=initializers.node[initializer]['pb'], pb_init=initializers.node[initializer]['pb']) data_nodes_map[initializer] = (initializer_id, 0) return parameters
[ "def", "add_initializers_and_inputs_to_graph", "(", "graph", ":", "Graph", ",", "graph_pb", ",", "data_nodes_map", ":", "dict", ")", ":", "initializers", "=", "Graph", "(", ")", "fill_graph_with_nodes", "(", "initializers", ",", "graph_pb", ".", "initializer", ",", "get_id", "=", "lambda", "pb", ":", "pb", ".", "name", ",", "get_attrs", "=", "protobuf_attrs", ")", "parameters", "=", "[", "]", "# first go through all inputs and separate constant from placeholders", "for", "inp", "in", "graph_pb", ".", "input", ":", "name", "=", "str", "(", "inp", ".", "name", ")", "if", "graph", ".", "has_node", "(", "name", ")", ":", "raise", "Error", "(", "'Name {} of input node already exists, input names are duplicated.'", ",", "name", ")", "elif", "initializers", ".", "has_node", "(", "name", ")", ":", "graph", ".", "add_node", "(", "name", ",", "kind", "=", "'op'", ",", "op", "=", "'Const'", ",", "pb", "=", "inp", ",", "pb_init", "=", "initializers", ".", "node", "[", "name", "]", "[", "'pb'", "]", ")", "else", ":", "graph", ".", "add_node", "(", "name", ",", "kind", "=", "'op'", ",", "op", "=", "'Parameter'", ",", "pb", "=", "inp", ")", "parameters", ".", "append", "(", "Node", "(", "graph", ",", "name", ")", ")", "assert", "name", "not", "in", "data_nodes_map", ",", "'Inconsistency between data_nodes_map and graph.nodes'", "data_nodes_map", "[", "name", "]", "=", "(", "name", ",", "0", ")", "# go over all initializers and make sure that all of them are added to the graph", "for", "initializer", "in", "initializers", ".", "nodes", "(", ")", ":", "initializer_id", "=", "initializer", "if", "not", "graph", ".", "has_node", "(", "initializer_id", ")", ":", "graph", ".", "add_node", "(", "initializer_id", ",", "kind", "=", "'op'", ",", "op", "=", "'Const'", ",", "pb", "=", "initializers", ".", "node", "[", "initializer", "]", "[", "'pb'", "]", ",", "pb_init", "=", "initializers", ".", "node", "[", "initializer", "]", "[", "'pb'", "]", ")", "data_nodes_map", "[", "initializer", "]", "=", "(", "initializer_id", ",", "0", ")", "return", "parameters" ]
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/front/onnx/loader.py#L137-L170
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_gdi.py
python
ImageList.GetBitmap
(*args, **kwargs)
return _gdi_.ImageList_GetBitmap(*args, **kwargs)
GetBitmap(self, int index) -> Bitmap
GetBitmap(self, int index) -> Bitmap
[ "GetBitmap", "(", "self", "int", "index", ")", "-", ">", "Bitmap" ]
def GetBitmap(*args, **kwargs): """GetBitmap(self, int index) -> Bitmap""" return _gdi_.ImageList_GetBitmap(*args, **kwargs)
[ "def", "GetBitmap", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "ImageList_GetBitmap", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L6931-L6933
arangodb/arangodb
0d658689c7d1b721b314fa3ca27d38303e1570c8
3rdParty/V8/gyp/msvs_emulation.py
python
_AddPrefix
(element, prefix)
Add |prefix| to |element| or each subelement if element is iterable.
Add |prefix| to |element| or each subelement if element is iterable.
[ "Add", "|prefix|", "to", "|element|", "or", "each", "subelement", "if", "element", "is", "iterable", "." ]
def _AddPrefix(element, prefix): """Add |prefix| to |element| or each subelement if element is iterable.""" if element is None: return element if isinstance(element, Iterable) and not isinstance(element, basestring): return [prefix + e for e in element] else: return prefix + element
[ "def", "_AddPrefix", "(", "element", ",", "prefix", ")", ":", "if", "element", "is", "None", ":", "return", "element", "if", "isinstance", "(", "element", ",", "Iterable", ")", "and", "not", "isinstance", "(", "element", ",", "basestring", ")", ":", "return", "[", "prefix", "+", "e", "for", "e", "in", "element", "]", "else", ":", "return", "prefix", "+", "element" ]
https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/gyp/msvs_emulation.py#L103-L110
linyouhappy/kongkongxiyou
7a69b2913eb29f4be77f9a62fb90cdd72c4160f1
cocosjs/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py
python
Type.element_count
(self)
return result
Retrieve the number of elements in this type. Returns an int. If the Type is not an array or vector, this raises.
Retrieve the number of elements in this type.
[ "Retrieve", "the", "number", "of", "elements", "in", "this", "type", "." ]
def element_count(self): """Retrieve the number of elements in this type. Returns an int. If the Type is not an array or vector, this raises. """ result = conf.lib.clang_getNumElements(self) if result < 0: raise Exception('Type does not have elements.') return result
[ "def", "element_count", "(", "self", ")", ":", "result", "=", "conf", ".", "lib", ".", "clang_getNumElements", "(", "self", ")", "if", "result", "<", "0", ":", "raise", "Exception", "(", "'Type does not have elements.'", ")", "return", "result" ]
https://github.com/linyouhappy/kongkongxiyou/blob/7a69b2913eb29f4be77f9a62fb90cdd72c4160f1/cocosjs/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py#L1693-L1704
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/codecs.py
python
getincrementalencoder
(encoding)
return encoder
Lookup up the codec for the given encoding and return its IncrementalEncoder class or factory function. Raises a LookupError in case the encoding cannot be found or the codecs doesn't provide an incremental encoder.
Lookup up the codec for the given encoding and return its IncrementalEncoder class or factory function.
[ "Lookup", "up", "the", "codec", "for", "the", "given", "encoding", "and", "return", "its", "IncrementalEncoder", "class", "or", "factory", "function", "." ]
def getincrementalencoder(encoding): """ Lookup up the codec for the given encoding and return its IncrementalEncoder class or factory function. Raises a LookupError in case the encoding cannot be found or the codecs doesn't provide an incremental encoder. """ encoder = lookup(encoding).incrementalencoder if encoder is None: raise LookupError(encoding) return encoder
[ "def", "getincrementalencoder", "(", "encoding", ")", ":", "encoder", "=", "lookup", "(", "encoding", ")", ".", "incrementalencoder", "if", "encoder", "is", "None", ":", "raise", "LookupError", "(", "encoding", ")", "return", "encoder" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/codecs.py#L976-L988
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/oauthlib/oauth1/rfc5849/request_validator.py
python
RequestValidator.get_client_secret
(self, client_key, request)
Retrieves the client secret associated with the client key. :param client_key: The client/consumer key. :param request: An oauthlib.common.Request object. :returns: The client secret as a string. This method must allow the use of a dummy client_key value. Fetching the secret using the dummy key must take the same amount of time as fetching a secret for a valid client:: # Unlikely to be near constant time as it uses two database # lookups for a valid client, and only one for an invalid. from your_datastore import ClientSecret if ClientSecret.has(client_key): return ClientSecret.get(client_key) else: return 'dummy' # Aim to mimic number of latency inducing operations no matter # whether the client is valid or not. from your_datastore import ClientSecret return ClientSecret.get(client_key, 'dummy') Note that the returned key must be in plaintext. This method is used by * AccessTokenEndpoint * RequestTokenEndpoint * ResourceEndpoint * SignatureOnlyEndpoint
Retrieves the client secret associated with the client key.
[ "Retrieves", "the", "client", "secret", "associated", "with", "the", "client", "key", "." ]
def get_client_secret(self, client_key, request): """Retrieves the client secret associated with the client key. :param client_key: The client/consumer key. :param request: An oauthlib.common.Request object. :returns: The client secret as a string. This method must allow the use of a dummy client_key value. Fetching the secret using the dummy key must take the same amount of time as fetching a secret for a valid client:: # Unlikely to be near constant time as it uses two database # lookups for a valid client, and only one for an invalid. from your_datastore import ClientSecret if ClientSecret.has(client_key): return ClientSecret.get(client_key) else: return 'dummy' # Aim to mimic number of latency inducing operations no matter # whether the client is valid or not. from your_datastore import ClientSecret return ClientSecret.get(client_key, 'dummy') Note that the returned key must be in plaintext. This method is used by * AccessTokenEndpoint * RequestTokenEndpoint * ResourceEndpoint * SignatureOnlyEndpoint """ raise self._subclass_must_implement('get_client_secret')
[ "def", "get_client_secret", "(", "self", ",", "client_key", ",", "request", ")", ":", "raise", "self", ".", "_subclass_must_implement", "(", "'get_client_secret'", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/oauthlib/oauth1/rfc5849/request_validator.py#L266-L299
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/configdialog.py
python
HighPage.var_changed_color
(self, *params)
Process change to color choice.
Process change to color choice.
[ "Process", "change", "to", "color", "choice", "." ]
def var_changed_color(self, *params): "Process change to color choice." self.on_new_color_set()
[ "def", "var_changed_color", "(", "self", ",", "*", "params", ")", ":", "self", ".", "on_new_color_set", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/configdialog.py#L1044-L1046
CanalTP/navitia
cb84ce9859070187e708818b058e6a7e0b7f891b
source/jormungandr/jormungandr/scenarios/helper_classes/helper_utils.py
python
_build_crowfly
(pt_journey, entry_point, mode, places_free_access, fallback_durations, fallback_type)
return _create_crowfly(pt_journey, crowfly_origin, crowfly_destination, begin, end, mode)
Return a new crowfly section for the current pt_journey. If the pt section's boundary is the same as the entry_point or within places_free_access, we won't do anything
Return a new crowfly section for the current pt_journey.
[ "Return", "a", "new", "crowfly", "section", "for", "the", "current", "pt_journey", "." ]
def _build_crowfly(pt_journey, entry_point, mode, places_free_access, fallback_durations, fallback_type): """ Return a new crowfly section for the current pt_journey. If the pt section's boundary is the same as the entry_point or within places_free_access, we won't do anything """ fallback_logic = _get_fallback_logic(fallback_type) pt_obj = fallback_logic.get_pt_boundaries(pt_journey) if pt_obj.uri == entry_point.uri: # No need for a crowfly if the pt section starts from the requested object return None if pt_obj.uri in places_free_access.odt: pt_obj.CopyFrom(entry_point) return None section_datetime = fallback_logic.get_pt_section_datetime(pt_journey) pt_datetime = fallback_logic.get_journey_bound_datetime(pt_journey) fallback_duration = fallback_durations[pt_obj.uri] crowfly_dt = fallback_logic.get_fallback_datetime(pt_datetime, fallback_duration) crowfly_origin, crowfly_destination = fallback_logic.route_params(entry_point, pt_obj) begin, end = fallback_logic.route_params(crowfly_dt, section_datetime) return _create_crowfly(pt_journey, crowfly_origin, crowfly_destination, begin, end, mode)
[ "def", "_build_crowfly", "(", "pt_journey", ",", "entry_point", ",", "mode", ",", "places_free_access", ",", "fallback_durations", ",", "fallback_type", ")", ":", "fallback_logic", "=", "_get_fallback_logic", "(", "fallback_type", ")", "pt_obj", "=", "fallback_logic", ".", "get_pt_boundaries", "(", "pt_journey", ")", "if", "pt_obj", ".", "uri", "==", "entry_point", ".", "uri", ":", "# No need for a crowfly if the pt section starts from the requested object", "return", "None", "if", "pt_obj", ".", "uri", "in", "places_free_access", ".", "odt", ":", "pt_obj", ".", "CopyFrom", "(", "entry_point", ")", "return", "None", "section_datetime", "=", "fallback_logic", ".", "get_pt_section_datetime", "(", "pt_journey", ")", "pt_datetime", "=", "fallback_logic", ".", "get_journey_bound_datetime", "(", "pt_journey", ")", "fallback_duration", "=", "fallback_durations", "[", "pt_obj", ".", "uri", "]", "crowfly_dt", "=", "fallback_logic", ".", "get_fallback_datetime", "(", "pt_datetime", ",", "fallback_duration", ")", "crowfly_origin", ",", "crowfly_destination", "=", "fallback_logic", ".", "route_params", "(", "entry_point", ",", "pt_obj", ")", "begin", ",", "end", "=", "fallback_logic", ".", "route_params", "(", "crowfly_dt", ",", "section_datetime", ")", "return", "_create_crowfly", "(", "pt_journey", ",", "crowfly_origin", ",", "crowfly_destination", ",", "begin", ",", "end", ",", "mode", ")" ]
https://github.com/CanalTP/navitia/blob/cb84ce9859070187e708818b058e6a7e0b7f891b/source/jormungandr/jormungandr/scenarios/helper_classes/helper_utils.py#L427-L453
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/build/android/dump_apk_resource_strings.py
python
ResourceStringValues.ToStringList
(self, res_id)
return result
Convert entry to string list for human-friendly output.
Convert entry to string list for human-friendly output.
[ "Convert", "entry", "to", "string", "list", "for", "human", "-", "friendly", "output", "." ]
def ToStringList(self, res_id): """Convert entry to string list for human-friendly output.""" values = sorted([(str(config), value) for config, value in self.res_values.items()]) if res_id is None: # res_id will be None when the resource ID should not be part # of the output. result = ['name=%s count=%d {' % (self.res_name, len(values))] else: result = [ 'res_id=0x%08x name=%s count=%d {' % (res_id, self.res_name, len(values)) ] for config, value in values: result.append('%-16s "%s"' % (config, QuoteString(value))) result.append('}') return result
[ "def", "ToStringList", "(", "self", ",", "res_id", ")", ":", "values", "=", "sorted", "(", "[", "(", "str", "(", "config", ")", ",", "value", ")", "for", "config", ",", "value", "in", "self", ".", "res_values", ".", "items", "(", ")", "]", ")", "if", "res_id", "is", "None", ":", "# res_id will be None when the resource ID should not be part", "# of the output.", "result", "=", "[", "'name=%s count=%d {'", "%", "(", "self", ".", "res_name", ",", "len", "(", "values", ")", ")", "]", "else", ":", "result", "=", "[", "'res_id=0x%08x name=%s count=%d {'", "%", "(", "res_id", ",", "self", ".", "res_name", ",", "len", "(", "values", ")", ")", "]", "for", "config", ",", "value", "in", "values", ":", "result", ".", "append", "(", "'%-16s \"%s\"'", "%", "(", "config", ",", "QuoteString", "(", "value", ")", ")", ")", "result", ".", "append", "(", "'}'", ")", "return", "result" ]
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/android/dump_apk_resource_strings.py#L220-L236
rrwick/Unicycler
96ffea71e3a78d63ade19d6124946773e65cf129
unicycler/misc.py
python
weighted_average_list
(nums, weights)
return sum(num * (weights[i] / weight_sum) for i, num in enumerate(nums))
A simple weighted mean of a list of numbers.
A simple weighted mean of a list of numbers.
[ "A", "simple", "weighted", "mean", "of", "a", "list", "of", "numbers", "." ]
def weighted_average_list(nums, weights): """ A simple weighted mean of a list of numbers. """ weight_sum = sum(weights) if weight_sum == 0.0: weights = [1.0] * len(nums) return sum(num * (weights[i] / weight_sum) for i, num in enumerate(nums))
[ "def", "weighted_average_list", "(", "nums", ",", "weights", ")", ":", "weight_sum", "=", "sum", "(", "weights", ")", "if", "weight_sum", "==", "0.0", ":", "weights", "=", "[", "1.0", "]", "*", "len", "(", "nums", ")", "return", "sum", "(", "num", "*", "(", "weights", "[", "i", "]", "/", "weight_sum", ")", "for", "i", ",", "num", "in", "enumerate", "(", "nums", ")", ")" ]
https://github.com/rrwick/Unicycler/blob/96ffea71e3a78d63ade19d6124946773e65cf129/unicycler/misc.py#L216-L223
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/media.py
python
MediaCtrl.SetPlaybackRate
(*args, **kwargs)
return _media.MediaCtrl_SetPlaybackRate(*args, **kwargs)
SetPlaybackRate(self, double dRate) -> bool
SetPlaybackRate(self, double dRate) -> bool
[ "SetPlaybackRate", "(", "self", "double", "dRate", ")", "-", ">", "bool" ]
def SetPlaybackRate(*args, **kwargs): """SetPlaybackRate(self, double dRate) -> bool""" return _media.MediaCtrl_SetPlaybackRate(*args, **kwargs)
[ "def", "SetPlaybackRate", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_media", ".", "MediaCtrl_SetPlaybackRate", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/media.py#L129-L131
waymo-research/waymo-open-dataset
5de359f3429e1496761790770868296140161b66
waymo_open_dataset/metrics/python/detection_metrics.py
python
_get_box_dof
(box_type)
return -1
Gets the desired number of box degree of freedom for a box type. Args: box_type: The type of the box. Returns: The desired degrees of freedom for the box type.
Gets the desired number of box degree of freedom for a box type.
[ "Gets", "the", "desired", "number", "of", "box", "degree", "of", "freedom", "for", "a", "box", "type", "." ]
def _get_box_dof(box_type): """Gets the desired number of box degree of freedom for a box type. Args: box_type: The type of the box. Returns: The desired degrees of freedom for the box type. """ if box_type == label_pb2.Label.Box.Type.Value('TYPE_3D'): return 7 if box_type == label_pb2.Label.Box.Type.Value('TYPE_2D'): return 5 if box_type == label_pb2.Label.Box.Type.Value('TYPE_AA_2D'): return 4 return -1
[ "def", "_get_box_dof", "(", "box_type", ")", ":", "if", "box_type", "==", "label_pb2", ".", "Label", ".", "Box", ".", "Type", ".", "Value", "(", "'TYPE_3D'", ")", ":", "return", "7", "if", "box_type", "==", "label_pb2", ".", "Label", ".", "Box", ".", "Type", ".", "Value", "(", "'TYPE_2D'", ")", ":", "return", "5", "if", "box_type", "==", "label_pb2", ".", "Label", ".", "Box", ".", "Type", ".", "Value", "(", "'TYPE_AA_2D'", ")", ":", "return", "4", "return", "-", "1" ]
https://github.com/waymo-research/waymo-open-dataset/blob/5de359f3429e1496761790770868296140161b66/waymo_open_dataset/metrics/python/detection_metrics.py#L57-L72