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
vesoft-inc/nebula
25a06217ebaf169e1f0e5ff6a797ba6f0c41fc35
.linters/cpp/cpplint.py
python
_NamespaceInfo.CheckEnd
(self, filename, clean_lines, linenum, error)
Check end of namespace comments.
Check end of namespace comments.
[ "Check", "end", "of", "namespace", "comments", "." ]
def CheckEnd(self, filename, clean_lines, linenum, error): """Check end of namespace comments.""" line = clean_lines.raw_lines[linenum] # Check how many lines is enclosed in this namespace. Don't issue # warning for missing namespace comments if there aren't enough # lines. However, do apply checks if there is already an end of # namespace comment and it's incorrect. # # TODO(unknown): We always want to check end of namespace comments # if a namespace is large, but sometimes we also want to apply the # check if a short namespace contained nontrivial things (something # other than forward declarations). There is currently no logic on # deciding what these nontrivial things are, so this check is # triggered by namespace size only, which works most of the time. if (linenum - self.starting_linenum < 10 and not Match(r'^\s*};*\s*(//|/\*).*\bnamespace\b', line)): return # Look for matching comment at end of namespace. # # Note that we accept C style "/* */" comments for terminating # namespaces, so that code that terminate namespaces inside # preprocessor macros can be cpplint clean. # # We also accept stuff like "// end of namespace <name>." with the # period at the end. # # Besides these, we don't accept anything else, otherwise we might # get false negatives when existing comment is a substring of the # expected namespace. if self.name: # Named namespace if not Match((r'^\s*};*\s*(//|/\*).*\bnamespace\s+' + re.escape(self.name) + r'[\*/\.\\\s]*$'), line): error(filename, linenum, 'readability/namespace', 5, 'Namespace should be terminated with "// namespace %s"' % self.name) else: # Anonymous namespace if not Match(r'^\s*};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line): # If "// namespace anonymous" or "// anonymous namespace (more text)", # mention "// anonymous namespace" as an acceptable form if Match(r'^\s*}.*\b(namespace anonymous|anonymous namespace)\b', line): error(filename, linenum, 'readability/namespace', 5, 'Anonymous namespace should be terminated with "// namespace"' ' or "// anonymous namespace"') else: error(filename, linenum, 'readability/namespace', 5, 'Anonymous namespace should be terminated with "// namespace"')
[ "def", "CheckEnd", "(", "self", ",", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "raw_lines", "[", "linenum", "]", "# Check how many lines is enclosed in this namespace. Don't issue", "# warning for missing namespace comments if there aren't enough", "# lines. However, do apply checks if there is already an end of", "# namespace comment and it's incorrect.", "#", "# TODO(unknown): We always want to check end of namespace comments", "# if a namespace is large, but sometimes we also want to apply the", "# check if a short namespace contained nontrivial things (something", "# other than forward declarations). There is currently no logic on", "# deciding what these nontrivial things are, so this check is", "# triggered by namespace size only, which works most of the time.", "if", "(", "linenum", "-", "self", ".", "starting_linenum", "<", "10", "and", "not", "Match", "(", "r'^\\s*};*\\s*(//|/\\*).*\\bnamespace\\b'", ",", "line", ")", ")", ":", "return", "# Look for matching comment at end of namespace.", "#", "# Note that we accept C style \"/* */\" comments for terminating", "# namespaces, so that code that terminate namespaces inside", "# preprocessor macros can be cpplint clean.", "#", "# We also accept stuff like \"// end of namespace <name>.\" with the", "# period at the end.", "#", "# Besides these, we don't accept anything else, otherwise we might", "# get false negatives when existing comment is a substring of the", "# expected namespace.", "if", "self", ".", "name", ":", "# Named namespace", "if", "not", "Match", "(", "(", "r'^\\s*};*\\s*(//|/\\*).*\\bnamespace\\s+'", "+", "re", ".", "escape", "(", "self", ".", "name", ")", "+", "r'[\\*/\\.\\\\\\s]*$'", ")", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/namespace'", ",", "5", ",", "'Namespace should be terminated with \"// namespace %s\"'", "%", "self", ".", "name", ")", "else", ":", "# Anonymous namespace", "if", "not", "Match", "(", "r'^\\s*};*\\s*(//|/\\*).*\\bnamespace[\\*/\\.\\\\\\s]*$'", ",", "line", ")", ":", "# If \"// namespace anonymous\" or \"// anonymous namespace (more text)\",", "# mention \"// anonymous namespace\" as an acceptable form", "if", "Match", "(", "r'^\\s*}.*\\b(namespace anonymous|anonymous namespace)\\b'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/namespace'", ",", "5", ",", "'Anonymous namespace should be terminated with \"// namespace\"'", "' or \"// anonymous namespace\"'", ")", "else", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/namespace'", ",", "5", ",", "'Anonymous namespace should be terminated with \"// namespace\"'", ")" ]
https://github.com/vesoft-inc/nebula/blob/25a06217ebaf169e1f0e5ff6a797ba6f0c41fc35/.linters/cpp/cpplint.py#L2573-L2623
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/stats/_multivariate.py
python
multivariate_normal_gen.logcdf
(self, x, mean=None, cov=1, allow_singular=False, maxpts=None, abseps=1e-5, releps=1e-5)
return out
Log of the multivariate normal cumulative distribution function. Parameters ---------- x : array_like Quantiles, with the last axis of `x` denoting the components. %(_mvn_doc_default_callparams)s maxpts: integer, optional The maximum number of points to use for integration (default `1000000*dim`) abseps: float, optional Absolute error tolerance (default 1e-5) releps: float, optional Relative error tolerance (default 1e-5) Returns ------- cdf : ndarray or scalar Log of the cumulative distribution function evaluated at `x` Notes ----- %(_mvn_doc_callparams_note)s .. versionadded:: 1.0.0
Log of the multivariate normal cumulative distribution function.
[ "Log", "of", "the", "multivariate", "normal", "cumulative", "distribution", "function", "." ]
def logcdf(self, x, mean=None, cov=1, allow_singular=False, maxpts=None, abseps=1e-5, releps=1e-5): """ Log of the multivariate normal cumulative distribution function. Parameters ---------- x : array_like Quantiles, with the last axis of `x` denoting the components. %(_mvn_doc_default_callparams)s maxpts: integer, optional The maximum number of points to use for integration (default `1000000*dim`) abseps: float, optional Absolute error tolerance (default 1e-5) releps: float, optional Relative error tolerance (default 1e-5) Returns ------- cdf : ndarray or scalar Log of the cumulative distribution function evaluated at `x` Notes ----- %(_mvn_doc_callparams_note)s .. versionadded:: 1.0.0 """ dim, mean, cov = self._process_parameters(None, mean, cov) x = self._process_quantiles(x, dim) # Use _PSD to check covariance matrix _PSD(cov, allow_singular=allow_singular) if not maxpts: maxpts = 1000000 * dim out = np.log(self._cdf(x, mean, cov, maxpts, abseps, releps)) return out
[ "def", "logcdf", "(", "self", ",", "x", ",", "mean", "=", "None", ",", "cov", "=", "1", ",", "allow_singular", "=", "False", ",", "maxpts", "=", "None", ",", "abseps", "=", "1e-5", ",", "releps", "=", "1e-5", ")", ":", "dim", ",", "mean", ",", "cov", "=", "self", ".", "_process_parameters", "(", "None", ",", "mean", ",", "cov", ")", "x", "=", "self", ".", "_process_quantiles", "(", "x", ",", "dim", ")", "# Use _PSD to check covariance matrix", "_PSD", "(", "cov", ",", "allow_singular", "=", "allow_singular", ")", "if", "not", "maxpts", ":", "maxpts", "=", "1000000", "*", "dim", "out", "=", "np", ".", "log", "(", "self", ".", "_cdf", "(", "x", ",", "mean", ",", "cov", ",", "maxpts", ",", "abseps", ",", "releps", ")", ")", "return", "out" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/stats/_multivariate.py#L557-L594
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/html2.py
python
WebView.CanCut
(*args, **kwargs)
return _html2.WebView_CanCut(*args, **kwargs)
CanCut(self) -> bool
CanCut(self) -> bool
[ "CanCut", "(", "self", ")", "-", ">", "bool" ]
def CanCut(*args, **kwargs): """CanCut(self) -> bool""" return _html2.WebView_CanCut(*args, **kwargs)
[ "def", "CanCut", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_html2", ".", "WebView_CanCut", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/html2.py#L218-L220
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/html.py
python
HtmlWindow.HistoryClear
(*args, **kwargs)
return _html.HtmlWindow_HistoryClear(*args, **kwargs)
HistoryClear(self)
HistoryClear(self)
[ "HistoryClear", "(", "self", ")" ]
def HistoryClear(*args, **kwargs): """HistoryClear(self)""" return _html.HtmlWindow_HistoryClear(*args, **kwargs)
[ "def", "HistoryClear", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_html", ".", "HtmlWindow_HistoryClear", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/html.py#L1069-L1071
twhui/LiteFlowNet
00925aebf2db9ac50f4b1666f718688b10dd10d1
scripts/cpp_lint.py
python
CheckForNonConstReference
(filename, clean_lines, linenum, nesting_state, error)
Check for non-const references. Separate from CheckLanguage since it scans backwards from current line, instead of scanning forward. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found.
Check for non-const references.
[ "Check", "for", "non", "-", "const", "references", "." ]
def CheckForNonConstReference(filename, clean_lines, linenum, nesting_state, error): """Check for non-const references. Separate from CheckLanguage since it scans backwards from current line, instead of scanning forward. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ # Do nothing if there is no '&' on current line. line = clean_lines.elided[linenum] if '&' not in line: return # Long type names may be broken across multiple lines, usually in one # of these forms: # LongType # ::LongTypeContinued &identifier # LongType:: # LongTypeContinued &identifier # LongType< # ...>::LongTypeContinued &identifier # # If we detected a type split across two lines, join the previous # line to current line so that we can match const references # accordingly. # # Note that this only scans back one line, since scanning back # arbitrary number of lines would be expensive. If you have a type # that spans more than 2 lines, please use a typedef. if linenum > 1: previous = None if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line): # previous_line\n + ::current_line previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$', clean_lines.elided[linenum - 1]) elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line): # previous_line::\n + current_line previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$', clean_lines.elided[linenum - 1]) if previous: line = previous.group(1) + line.lstrip() else: # Check for templated parameter that is split across multiple lines endpos = line.rfind('>') if endpos > -1: (_, startline, startpos) = ReverseCloseExpression( clean_lines, linenum, endpos) if startpos > -1 and startline < linenum: # Found the matching < on an earlier line, collect all # pieces up to current line. line = '' for i in xrange(startline, linenum + 1): line += clean_lines.elided[i].strip() # Check for non-const references in function parameters. A single '&' may # found in the following places: # inside expression: binary & for bitwise AND # inside expression: unary & for taking the address of something # inside declarators: reference parameter # We will exclude the first two cases by checking that we are not inside a # function body, including one that was just introduced by a trailing '{'. # TODO(unknwon): Doesn't account for preprocessor directives. # TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare]. check_params = False if not nesting_state.stack: check_params = True # top level elif (isinstance(nesting_state.stack[-1], _ClassInfo) or isinstance(nesting_state.stack[-1], _NamespaceInfo)): check_params = True # within class or namespace elif Match(r'.*{\s*$', line): if (len(nesting_state.stack) == 1 or isinstance(nesting_state.stack[-2], _ClassInfo) or isinstance(nesting_state.stack[-2], _NamespaceInfo)): check_params = True # just opened global/class/namespace block # We allow non-const references in a few standard places, like functions # called "swap()" or iostream operators like "<<" or ">>". Do not check # those function parameters. # # We also accept & in static_assert, which looks like a function but # it's actually a declaration expression. whitelisted_functions = (r'(?:[sS]wap(?:<\w:+>)?|' r'operator\s*[<>][<>]|' r'static_assert|COMPILE_ASSERT' r')\s*\(') if Search(whitelisted_functions, line): check_params = False elif not Search(r'\S+\([^)]*$', line): # Don't see a whitelisted function on this line. Actually we # didn't see any function name on this line, so this is likely a # multi-line parameter list. Try a bit harder to catch this case. for i in xrange(2): if (linenum > i and Search(whitelisted_functions, clean_lines.elided[linenum - i - 1])): check_params = False break if check_params: decls = ReplaceAll(r'{[^}]*}', ' ', line) # exclude function body for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls): if not Match(_RE_PATTERN_CONST_REF_PARAM, parameter): error(filename, linenum, 'runtime/references', 2, 'Is this a non-const reference? ' 'If so, make const or use a pointer: ' + ReplaceAll(' *<', '<', parameter))
[ "def", "CheckForNonConstReference", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "nesting_state", ",", "error", ")", ":", "# Do nothing if there is no '&' on current line.", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "'&'", "not", "in", "line", ":", "return", "# Long type names may be broken across multiple lines, usually in one", "# of these forms:", "# LongType", "# ::LongTypeContinued &identifier", "# LongType::", "# LongTypeContinued &identifier", "# LongType<", "# ...>::LongTypeContinued &identifier", "#", "# If we detected a type split across two lines, join the previous", "# line to current line so that we can match const references", "# accordingly.", "#", "# Note that this only scans back one line, since scanning back", "# arbitrary number of lines would be expensive. If you have a type", "# that spans more than 2 lines, please use a typedef.", "if", "linenum", ">", "1", ":", "previous", "=", "None", "if", "Match", "(", "r'\\s*::(?:[\\w<>]|::)+\\s*&\\s*\\S'", ",", "line", ")", ":", "# previous_line\\n + ::current_line", "previous", "=", "Search", "(", "r'\\b((?:const\\s*)?(?:[\\w<>]|::)+[\\w<>])\\s*$'", ",", "clean_lines", ".", "elided", "[", "linenum", "-", "1", "]", ")", "elif", "Match", "(", "r'\\s*[a-zA-Z_]([\\w<>]|::)+\\s*&\\s*\\S'", ",", "line", ")", ":", "# previous_line::\\n + current_line", "previous", "=", "Search", "(", "r'\\b((?:const\\s*)?(?:[\\w<>]|::)+::)\\s*$'", ",", "clean_lines", ".", "elided", "[", "linenum", "-", "1", "]", ")", "if", "previous", ":", "line", "=", "previous", ".", "group", "(", "1", ")", "+", "line", ".", "lstrip", "(", ")", "else", ":", "# Check for templated parameter that is split across multiple lines", "endpos", "=", "line", ".", "rfind", "(", "'>'", ")", "if", "endpos", ">", "-", "1", ":", "(", "_", ",", "startline", ",", "startpos", ")", "=", "ReverseCloseExpression", "(", "clean_lines", ",", "linenum", ",", "endpos", ")", "if", "startpos", ">", "-", "1", "and", "startline", "<", "linenum", ":", "# Found the matching < on an earlier line, collect all", "# pieces up to current line.", "line", "=", "''", "for", "i", "in", "xrange", "(", "startline", ",", "linenum", "+", "1", ")", ":", "line", "+=", "clean_lines", ".", "elided", "[", "i", "]", ".", "strip", "(", ")", "# Check for non-const references in function parameters. A single '&' may", "# found in the following places:", "# inside expression: binary & for bitwise AND", "# inside expression: unary & for taking the address of something", "# inside declarators: reference parameter", "# We will exclude the first two cases by checking that we are not inside a", "# function body, including one that was just introduced by a trailing '{'.", "# TODO(unknwon): Doesn't account for preprocessor directives.", "# TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare].", "check_params", "=", "False", "if", "not", "nesting_state", ".", "stack", ":", "check_params", "=", "True", "# top level", "elif", "(", "isinstance", "(", "nesting_state", ".", "stack", "[", "-", "1", "]", ",", "_ClassInfo", ")", "or", "isinstance", "(", "nesting_state", ".", "stack", "[", "-", "1", "]", ",", "_NamespaceInfo", ")", ")", ":", "check_params", "=", "True", "# within class or namespace", "elif", "Match", "(", "r'.*{\\s*$'", ",", "line", ")", ":", "if", "(", "len", "(", "nesting_state", ".", "stack", ")", "==", "1", "or", "isinstance", "(", "nesting_state", ".", "stack", "[", "-", "2", "]", ",", "_ClassInfo", ")", "or", "isinstance", "(", "nesting_state", ".", "stack", "[", "-", "2", "]", ",", "_NamespaceInfo", ")", ")", ":", "check_params", "=", "True", "# just opened global/class/namespace block", "# We allow non-const references in a few standard places, like functions", "# called \"swap()\" or iostream operators like \"<<\" or \">>\". Do not check", "# those function parameters.", "#", "# We also accept & in static_assert, which looks like a function but", "# it's actually a declaration expression.", "whitelisted_functions", "=", "(", "r'(?:[sS]wap(?:<\\w:+>)?|'", "r'operator\\s*[<>][<>]|'", "r'static_assert|COMPILE_ASSERT'", "r')\\s*\\('", ")", "if", "Search", "(", "whitelisted_functions", ",", "line", ")", ":", "check_params", "=", "False", "elif", "not", "Search", "(", "r'\\S+\\([^)]*$'", ",", "line", ")", ":", "# Don't see a whitelisted function on this line. Actually we", "# didn't see any function name on this line, so this is likely a", "# multi-line parameter list. Try a bit harder to catch this case.", "for", "i", "in", "xrange", "(", "2", ")", ":", "if", "(", "linenum", ">", "i", "and", "Search", "(", "whitelisted_functions", ",", "clean_lines", ".", "elided", "[", "linenum", "-", "i", "-", "1", "]", ")", ")", ":", "check_params", "=", "False", "break", "if", "check_params", ":", "decls", "=", "ReplaceAll", "(", "r'{[^}]*}'", ",", "' '", ",", "line", ")", "# exclude function body", "for", "parameter", "in", "re", ".", "findall", "(", "_RE_PATTERN_REF_PARAM", ",", "decls", ")", ":", "if", "not", "Match", "(", "_RE_PATTERN_CONST_REF_PARAM", ",", "parameter", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/references'", ",", "2", ",", "'Is this a non-const reference? '", "'If so, make const or use a pointer: '", "+", "ReplaceAll", "(", "' *<'", ",", "'<'", ",", "parameter", ")", ")" ]
https://github.com/twhui/LiteFlowNet/blob/00925aebf2db9ac50f4b1666f718688b10dd10d1/scripts/cpp_lint.py#L4134-L4244
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/preprocessing/label.py
python
label_binarize
(y, classes, neg_label=0, pos_label=1, sparse_output=False)
return Y
Binarize labels in a one-vs-all fashion Several regression and binary classification algorithms are available in the scikit. A simple way to extend these algorithms to the multi-class classification case is to use the so-called one-vs-all scheme. This function makes it possible to compute this transformation for a fixed set of class labels known ahead of time. Parameters ---------- y : array-like Sequence of integer labels or multilabel data to encode. classes : array-like of shape [n_classes] Uniquely holds the label for each class. neg_label : int (default: 0) Value with which negative labels must be encoded. pos_label : int (default: 1) Value with which positive labels must be encoded. sparse_output : boolean (default: False), Set to true if output binary array is desired in CSR sparse format Returns ------- Y : numpy array or CSR matrix of shape [n_samples, n_classes] Shape will be [n_samples, 1] for binary problems. Examples -------- >>> from sklearn.preprocessing import label_binarize >>> label_binarize([1, 6], classes=[1, 2, 4, 6]) array([[1, 0, 0, 0], [0, 0, 0, 1]]) The class ordering is preserved: >>> label_binarize([1, 6], classes=[1, 6, 4, 2]) array([[1, 0, 0, 0], [0, 1, 0, 0]]) Binary targets transform to a column vector >>> label_binarize(['yes', 'no', 'no', 'yes'], classes=['no', 'yes']) array([[1], [0], [0], [1]]) See also -------- LabelBinarizer : class used to wrap the functionality of label_binarize and allow for fitting to classes independently of the transform operation
Binarize labels in a one-vs-all fashion
[ "Binarize", "labels", "in", "a", "one", "-", "vs", "-", "all", "fashion" ]
def label_binarize(y, classes, neg_label=0, pos_label=1, sparse_output=False): """Binarize labels in a one-vs-all fashion Several regression and binary classification algorithms are available in the scikit. A simple way to extend these algorithms to the multi-class classification case is to use the so-called one-vs-all scheme. This function makes it possible to compute this transformation for a fixed set of class labels known ahead of time. Parameters ---------- y : array-like Sequence of integer labels or multilabel data to encode. classes : array-like of shape [n_classes] Uniquely holds the label for each class. neg_label : int (default: 0) Value with which negative labels must be encoded. pos_label : int (default: 1) Value with which positive labels must be encoded. sparse_output : boolean (default: False), Set to true if output binary array is desired in CSR sparse format Returns ------- Y : numpy array or CSR matrix of shape [n_samples, n_classes] Shape will be [n_samples, 1] for binary problems. Examples -------- >>> from sklearn.preprocessing import label_binarize >>> label_binarize([1, 6], classes=[1, 2, 4, 6]) array([[1, 0, 0, 0], [0, 0, 0, 1]]) The class ordering is preserved: >>> label_binarize([1, 6], classes=[1, 6, 4, 2]) array([[1, 0, 0, 0], [0, 1, 0, 0]]) Binary targets transform to a column vector >>> label_binarize(['yes', 'no', 'no', 'yes'], classes=['no', 'yes']) array([[1], [0], [0], [1]]) See also -------- LabelBinarizer : class used to wrap the functionality of label_binarize and allow for fitting to classes independently of the transform operation """ if not isinstance(y, list): # XXX Workaround that will be removed when list of list format is # dropped y = check_array(y, accept_sparse='csr', ensure_2d=False, dtype=None) else: if _num_samples(y) == 0: raise ValueError('y has 0 samples: %r' % y) if neg_label >= pos_label: raise ValueError("neg_label={0} must be strictly less than " "pos_label={1}.".format(neg_label, pos_label)) if (sparse_output and (pos_label == 0 or neg_label != 0)): raise ValueError("Sparse binarization is only supported with non " "zero pos_label and zero neg_label, got " "pos_label={0} and neg_label={1}" "".format(pos_label, neg_label)) # To account for pos_label == 0 in the dense case pos_switch = pos_label == 0 if pos_switch: pos_label = -neg_label y_type = type_of_target(y) if 'multioutput' in y_type: raise ValueError("Multioutput target data is not supported with label " "binarization") if y_type == 'unknown': raise ValueError("The type of target data is not known") n_samples = y.shape[0] if sp.issparse(y) else len(y) n_classes = len(classes) classes = np.asarray(classes) if y_type == "binary": if n_classes == 1: if sparse_output: return sp.csr_matrix((n_samples, 1), dtype=int) else: Y = np.zeros((len(y), 1), dtype=np.int) Y += neg_label return Y elif len(classes) >= 3: y_type = "multiclass" sorted_class = np.sort(classes) if (y_type == "multilabel-indicator" and classes.size != y.shape[1]): raise ValueError("classes {0} missmatch with the labels {1}" "found in the data".format(classes, unique_labels(y))) if y_type in ("binary", "multiclass"): y = column_or_1d(y) # pick out the known labels from y y_in_classes = in1d(y, classes) y_seen = y[y_in_classes] indices = np.searchsorted(sorted_class, y_seen) indptr = np.hstack((0, np.cumsum(y_in_classes))) data = np.empty_like(indices) data.fill(pos_label) Y = sp.csr_matrix((data, indices, indptr), shape=(n_samples, n_classes)) elif y_type == "multilabel-indicator": Y = sp.csr_matrix(y) if pos_label != 1: data = np.empty_like(Y.data) data.fill(pos_label) Y.data = data else: raise ValueError("%s target data is not supported with label " "binarization" % y_type) if not sparse_output: Y = Y.toarray() Y = astype(Y, int, copy=False) if neg_label != 0: Y[Y == 0] = neg_label if pos_switch: Y[Y == pos_label] = 0 else: Y.data = astype(Y.data, int, copy=False) # preserve label ordering if np.any(classes != sorted_class): indices = np.searchsorted(sorted_class, classes) Y = Y[:, indices] if y_type == "binary": if sparse_output: Y = Y.getcol(-1) else: Y = Y[:, -1].reshape((-1, 1)) return Y
[ "def", "label_binarize", "(", "y", ",", "classes", ",", "neg_label", "=", "0", ",", "pos_label", "=", "1", ",", "sparse_output", "=", "False", ")", ":", "if", "not", "isinstance", "(", "y", ",", "list", ")", ":", "# XXX Workaround that will be removed when list of list format is", "# dropped", "y", "=", "check_array", "(", "y", ",", "accept_sparse", "=", "'csr'", ",", "ensure_2d", "=", "False", ",", "dtype", "=", "None", ")", "else", ":", "if", "_num_samples", "(", "y", ")", "==", "0", ":", "raise", "ValueError", "(", "'y has 0 samples: %r'", "%", "y", ")", "if", "neg_label", ">=", "pos_label", ":", "raise", "ValueError", "(", "\"neg_label={0} must be strictly less than \"", "\"pos_label={1}.\"", ".", "format", "(", "neg_label", ",", "pos_label", ")", ")", "if", "(", "sparse_output", "and", "(", "pos_label", "==", "0", "or", "neg_label", "!=", "0", ")", ")", ":", "raise", "ValueError", "(", "\"Sparse binarization is only supported with non \"", "\"zero pos_label and zero neg_label, got \"", "\"pos_label={0} and neg_label={1}\"", "\"\"", ".", "format", "(", "pos_label", ",", "neg_label", ")", ")", "# To account for pos_label == 0 in the dense case", "pos_switch", "=", "pos_label", "==", "0", "if", "pos_switch", ":", "pos_label", "=", "-", "neg_label", "y_type", "=", "type_of_target", "(", "y", ")", "if", "'multioutput'", "in", "y_type", ":", "raise", "ValueError", "(", "\"Multioutput target data is not supported with label \"", "\"binarization\"", ")", "if", "y_type", "==", "'unknown'", ":", "raise", "ValueError", "(", "\"The type of target data is not known\"", ")", "n_samples", "=", "y", ".", "shape", "[", "0", "]", "if", "sp", ".", "issparse", "(", "y", ")", "else", "len", "(", "y", ")", "n_classes", "=", "len", "(", "classes", ")", "classes", "=", "np", ".", "asarray", "(", "classes", ")", "if", "y_type", "==", "\"binary\"", ":", "if", "n_classes", "==", "1", ":", "if", "sparse_output", ":", "return", "sp", ".", "csr_matrix", "(", "(", "n_samples", ",", "1", ")", ",", "dtype", "=", "int", ")", "else", ":", "Y", "=", "np", ".", "zeros", "(", "(", "len", "(", "y", ")", ",", "1", ")", ",", "dtype", "=", "np", ".", "int", ")", "Y", "+=", "neg_label", "return", "Y", "elif", "len", "(", "classes", ")", ">=", "3", ":", "y_type", "=", "\"multiclass\"", "sorted_class", "=", "np", ".", "sort", "(", "classes", ")", "if", "(", "y_type", "==", "\"multilabel-indicator\"", "and", "classes", ".", "size", "!=", "y", ".", "shape", "[", "1", "]", ")", ":", "raise", "ValueError", "(", "\"classes {0} missmatch with the labels {1}\"", "\"found in the data\"", ".", "format", "(", "classes", ",", "unique_labels", "(", "y", ")", ")", ")", "if", "y_type", "in", "(", "\"binary\"", ",", "\"multiclass\"", ")", ":", "y", "=", "column_or_1d", "(", "y", ")", "# pick out the known labels from y", "y_in_classes", "=", "in1d", "(", "y", ",", "classes", ")", "y_seen", "=", "y", "[", "y_in_classes", "]", "indices", "=", "np", ".", "searchsorted", "(", "sorted_class", ",", "y_seen", ")", "indptr", "=", "np", ".", "hstack", "(", "(", "0", ",", "np", ".", "cumsum", "(", "y_in_classes", ")", ")", ")", "data", "=", "np", ".", "empty_like", "(", "indices", ")", "data", ".", "fill", "(", "pos_label", ")", "Y", "=", "sp", ".", "csr_matrix", "(", "(", "data", ",", "indices", ",", "indptr", ")", ",", "shape", "=", "(", "n_samples", ",", "n_classes", ")", ")", "elif", "y_type", "==", "\"multilabel-indicator\"", ":", "Y", "=", "sp", ".", "csr_matrix", "(", "y", ")", "if", "pos_label", "!=", "1", ":", "data", "=", "np", ".", "empty_like", "(", "Y", ".", "data", ")", "data", ".", "fill", "(", "pos_label", ")", "Y", ".", "data", "=", "data", "else", ":", "raise", "ValueError", "(", "\"%s target data is not supported with label \"", "\"binarization\"", "%", "y_type", ")", "if", "not", "sparse_output", ":", "Y", "=", "Y", ".", "toarray", "(", ")", "Y", "=", "astype", "(", "Y", ",", "int", ",", "copy", "=", "False", ")", "if", "neg_label", "!=", "0", ":", "Y", "[", "Y", "==", "0", "]", "=", "neg_label", "if", "pos_switch", ":", "Y", "[", "Y", "==", "pos_label", "]", "=", "0", "else", ":", "Y", ".", "data", "=", "astype", "(", "Y", ".", "data", ",", "int", ",", "copy", "=", "False", ")", "# preserve label ordering", "if", "np", ".", "any", "(", "classes", "!=", "sorted_class", ")", ":", "indices", "=", "np", ".", "searchsorted", "(", "sorted_class", ",", "classes", ")", "Y", "=", "Y", "[", ":", ",", "indices", "]", "if", "y_type", "==", "\"binary\"", ":", "if", "sparse_output", ":", "Y", "=", "Y", ".", "getcol", "(", "-", "1", ")", "else", ":", "Y", "=", "Y", "[", ":", ",", "-", "1", "]", ".", "reshape", "(", "(", "-", "1", ",", "1", ")", ")", "return", "Y" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/preprocessing/label.py#L388-L542
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/buttonpanel.py
python
ButtonInfo.SetShortHelp
(self, help="")
Sets the help string to be shown in a tooltip. :param string `help`: the string for the short help.
Sets the help string to be shown in a tooltip.
[ "Sets", "the", "help", "string", "to", "be", "shown", "in", "a", "tooltip", "." ]
def SetShortHelp(self, help=""): """ Sets the help string to be shown in a tooltip. :param string `help`: the string for the short help. """ self._shortHelp = help
[ "def", "SetShortHelp", "(", "self", ",", "help", "=", "\"\"", ")", ":", "self", ".", "_shortHelp", "=", "help" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/buttonpanel.py#L1738-L1745
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/platform/gfile.py
python
Walk
(top, topdown=1, onerror=None)
return os.walk(top, topdown=topdown, onerror=onerror, followlinks=True)
Recursive directory tree generator. Args: top: string, a pathname. topdown: bool, should traversal be pre-order (True) or post-order (False) onerror: function, optional callback for errors. By default, errors that occur when listing a directory are ignored. (This is the same semantics as Python's os.walk() generator.) If the optional argument "onerror" is specified, it should be a function. It will be called with one argument, an os.error instance. It can return to continue with the walk, or reraise the exception to abort the walk. By default, the walk follows symlinks that resolve into directories. Yields: # Each yield is a 3-tuple: the pathname of a directory, followed # by lists of all its subdirectories and leaf files. (dirname, [subdirname, subdirname, ...], [filename, filename, ...])
Recursive directory tree generator.
[ "Recursive", "directory", "tree", "generator", "." ]
def Walk(top, topdown=1, onerror=None): """Recursive directory tree generator. Args: top: string, a pathname. topdown: bool, should traversal be pre-order (True) or post-order (False) onerror: function, optional callback for errors. By default, errors that occur when listing a directory are ignored. (This is the same semantics as Python's os.walk() generator.) If the optional argument "onerror" is specified, it should be a function. It will be called with one argument, an os.error instance. It can return to continue with the walk, or reraise the exception to abort the walk. By default, the walk follows symlinks that resolve into directories. Yields: # Each yield is a 3-tuple: the pathname of a directory, followed # by lists of all its subdirectories and leaf files. (dirname, [subdirname, subdirname, ...], [filename, filename, ...]) """ return os.walk(top, topdown=topdown, onerror=onerror, followlinks=True)
[ "def", "Walk", "(", "top", ",", "topdown", "=", "1", ",", "onerror", "=", "None", ")", ":", "return", "os", ".", "walk", "(", "top", ",", "topdown", "=", "topdown", ",", "onerror", "=", "onerror", ",", "followlinks", "=", "True", ")" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/platform/gfile.py#L385-L405
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/richtext.py
python
RichTextCtrl.BeginItalic
(*args, **kwargs)
return _richtext.RichTextCtrl_BeginItalic(*args, **kwargs)
BeginItalic(self) -> bool Begin using italic
BeginItalic(self) -> bool
[ "BeginItalic", "(", "self", ")", "-", ">", "bool" ]
def BeginItalic(*args, **kwargs): """ BeginItalic(self) -> bool Begin using italic """ return _richtext.RichTextCtrl_BeginItalic(*args, **kwargs)
[ "def", "BeginItalic", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextCtrl_BeginItalic", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/richtext.py#L3351-L3357
MythTV/mythtv
d282a209cb8be85d036f85a62a8ec971b67d45f4
mythtv/programs/scripts/metadata/Television/tvmaze.py
python
main
()
Main executor for MythTV's tvmaze grabber.
Main executor for MythTV's tvmaze grabber.
[ "Main", "executor", "for", "MythTV", "s", "tvmaze", "grabber", "." ]
def main(): """ Main executor for MythTV's tvmaze grabber. """ parser = OptionParser() parser.add_option('-v', "--version", action="store_true", default=False, dest="version", help="Display version and author") parser.add_option('-t', "--test", action="store_true", default=False, dest="test", help="Perform self-test for dependencies.") parser.add_option('-M', "--list", action="store_true", default=False, dest="tvlist", help="Get TV Shows matching search.") parser.add_option('-D', "--data", action="store_true", default=False, dest="tvdata", help="Get TV Show data.") parser.add_option('-C', "--collection", action="store_true", default=False, dest="collectiondata", help="Get Collection data.") parser.add_option('-N', "--numbers", action="store_true", default=False, dest="tvnumbers", help="Get Season and Episode numbers") parser.add_option('-l', "--language", metavar="LANGUAGE", default=u'en', dest="language", help="Specify language for filtering.") parser.add_option('-a', "--area", metavar="COUNTRY", default=None, dest="country", help="Specify country for custom data.") parser.add_option('--debug', action="store_true", default=False, dest="debug", help=("Disable caching and enable raw " "data output.")) parser.add_option('--doctest', action="store_true", default=False, dest="doctest", help="Run doctests") opts, args = parser.parse_args() if opts.debug: print("Args: ", args) print("Opts: ", opts) if opts.doctest: import doctest try: with open("tvmaze_tests.txt") as f: dtests = "".join(f.readlines()) main.__doc__ += dtests except IOError: pass # perhaps try optionflags=doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE doctest.testmod(verbose=opts.debug, optionflags=doctest.ELLIPSIS) if opts.version: buildVersion() if opts.test: performSelfTest(opts) if opts.debug: import requests else: confdir = os.environ.get('MYTHCONFDIR', '') if (not confdir) or (confdir == '/'): confdir = os.environ.get('HOME', '') if (not confdir) or (confdir == '/'): print("Unable to find MythTV directory for metadata cache.") sys.exit(1) confdir = os.path.join(confdir, '.mythtv') cachedir = os.path.join(confdir, 'cache') if not os.path.exists(cachedir): os.makedirs(cachedir) cache_name = os.path.join(cachedir, 'py3tvmaze') import requests import requests_cache requests_cache.install_cache(cache_name, backend='sqlite', expire_after=3600) with requests.Session() as s: s.headers.update({'Accept': 'application/json', 'User-Agent': 'mythtv tvmaze grabber %s' % __version__}) opts.session = s try: if opts.tvlist: # option -M title if (len(args) != 1) or (len(args[0]) == 0): sys.stdout.write('ERROR: tvmaze -M requires exactly one non-empty argument') sys.exit(1) buildList(args[0], opts) if opts.tvnumbers: # either option -N inetref subtitle # or option -N title subtitle if (len(args) != 2) or (len(args[0]) == 0) or (len(args[1]) == 0): sys.stdout.write('ERROR: tvmaze -N requires exactly two non-empty arguments') sys.exit(1) buildNumbers(args, opts) if opts.tvdata: # option -D inetref season episode if (len(args) != 3) or (len(args[0]) == 0) or (len(args[1]) == 0) or (len(args[2]) == 0): sys.stdout.write('ERROR: tvmaze -D requires exactly three non-empty arguments') sys.exit(1) buildSingle(args, opts) if opts.collectiondata: # option -C inetref if (len(args) != 1) or (len(args[0]) == 0): sys.stdout.write('ERROR: tvmaze -C requires exactly one non-empty argument') sys.exit(1) buildCollection(args[0], opts) except: if opts.debug: raise sys.stdout.write('ERROR: ' + str(sys.exc_info()[0]) + ' : ' + str(sys.exc_info()[1]) + '\n') sys.exit(1)
[ "def", "main", "(", ")", ":", "parser", "=", "OptionParser", "(", ")", "parser", ".", "add_option", "(", "'-v'", ",", "\"--version\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ",", "dest", "=", "\"version\"", ",", "help", "=", "\"Display version and author\"", ")", "parser", ".", "add_option", "(", "'-t'", ",", "\"--test\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ",", "dest", "=", "\"test\"", ",", "help", "=", "\"Perform self-test for dependencies.\"", ")", "parser", ".", "add_option", "(", "'-M'", ",", "\"--list\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ",", "dest", "=", "\"tvlist\"", ",", "help", "=", "\"Get TV Shows matching search.\"", ")", "parser", ".", "add_option", "(", "'-D'", ",", "\"--data\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ",", "dest", "=", "\"tvdata\"", ",", "help", "=", "\"Get TV Show data.\"", ")", "parser", ".", "add_option", "(", "'-C'", ",", "\"--collection\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ",", "dest", "=", "\"collectiondata\"", ",", "help", "=", "\"Get Collection data.\"", ")", "parser", ".", "add_option", "(", "'-N'", ",", "\"--numbers\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ",", "dest", "=", "\"tvnumbers\"", ",", "help", "=", "\"Get Season and Episode numbers\"", ")", "parser", ".", "add_option", "(", "'-l'", ",", "\"--language\"", ",", "metavar", "=", "\"LANGUAGE\"", ",", "default", "=", "u'en'", ",", "dest", "=", "\"language\"", ",", "help", "=", "\"Specify language for filtering.\"", ")", "parser", ".", "add_option", "(", "'-a'", ",", "\"--area\"", ",", "metavar", "=", "\"COUNTRY\"", ",", "default", "=", "None", ",", "dest", "=", "\"country\"", ",", "help", "=", "\"Specify country for custom data.\"", ")", "parser", ".", "add_option", "(", "'--debug'", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ",", "dest", "=", "\"debug\"", ",", "help", "=", "(", "\"Disable caching and enable raw \"", "\"data output.\"", ")", ")", "parser", ".", "add_option", "(", "'--doctest'", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ",", "dest", "=", "\"doctest\"", ",", "help", "=", "\"Run doctests\"", ")", "opts", ",", "args", "=", "parser", ".", "parse_args", "(", ")", "if", "opts", ".", "debug", ":", "print", "(", "\"Args: \"", ",", "args", ")", "print", "(", "\"Opts: \"", ",", "opts", ")", "if", "opts", ".", "doctest", ":", "import", "doctest", "try", ":", "with", "open", "(", "\"tvmaze_tests.txt\"", ")", "as", "f", ":", "dtests", "=", "\"\"", ".", "join", "(", "f", ".", "readlines", "(", ")", ")", "main", ".", "__doc__", "+=", "dtests", "except", "IOError", ":", "pass", "# perhaps try optionflags=doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE", "doctest", ".", "testmod", "(", "verbose", "=", "opts", ".", "debug", ",", "optionflags", "=", "doctest", ".", "ELLIPSIS", ")", "if", "opts", ".", "version", ":", "buildVersion", "(", ")", "if", "opts", ".", "test", ":", "performSelfTest", "(", "opts", ")", "if", "opts", ".", "debug", ":", "import", "requests", "else", ":", "confdir", "=", "os", ".", "environ", ".", "get", "(", "'MYTHCONFDIR'", ",", "''", ")", "if", "(", "not", "confdir", ")", "or", "(", "confdir", "==", "'/'", ")", ":", "confdir", "=", "os", ".", "environ", ".", "get", "(", "'HOME'", ",", "''", ")", "if", "(", "not", "confdir", ")", "or", "(", "confdir", "==", "'/'", ")", ":", "print", "(", "\"Unable to find MythTV directory for metadata cache.\"", ")", "sys", ".", "exit", "(", "1", ")", "confdir", "=", "os", ".", "path", ".", "join", "(", "confdir", ",", "'.mythtv'", ")", "cachedir", "=", "os", ".", "path", ".", "join", "(", "confdir", ",", "'cache'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "cachedir", ")", ":", "os", ".", "makedirs", "(", "cachedir", ")", "cache_name", "=", "os", ".", "path", ".", "join", "(", "cachedir", ",", "'py3tvmaze'", ")", "import", "requests", "import", "requests_cache", "requests_cache", ".", "install_cache", "(", "cache_name", ",", "backend", "=", "'sqlite'", ",", "expire_after", "=", "3600", ")", "with", "requests", ".", "Session", "(", ")", "as", "s", ":", "s", ".", "headers", ".", "update", "(", "{", "'Accept'", ":", "'application/json'", ",", "'User-Agent'", ":", "'mythtv tvmaze grabber %s'", "%", "__version__", "}", ")", "opts", ".", "session", "=", "s", "try", ":", "if", "opts", ".", "tvlist", ":", "# option -M title", "if", "(", "len", "(", "args", ")", "!=", "1", ")", "or", "(", "len", "(", "args", "[", "0", "]", ")", "==", "0", ")", ":", "sys", ".", "stdout", ".", "write", "(", "'ERROR: tvmaze -M requires exactly one non-empty argument'", ")", "sys", ".", "exit", "(", "1", ")", "buildList", "(", "args", "[", "0", "]", ",", "opts", ")", "if", "opts", ".", "tvnumbers", ":", "# either option -N inetref subtitle", "# or option -N title subtitle", "if", "(", "len", "(", "args", ")", "!=", "2", ")", "or", "(", "len", "(", "args", "[", "0", "]", ")", "==", "0", ")", "or", "(", "len", "(", "args", "[", "1", "]", ")", "==", "0", ")", ":", "sys", ".", "stdout", ".", "write", "(", "'ERROR: tvmaze -N requires exactly two non-empty arguments'", ")", "sys", ".", "exit", "(", "1", ")", "buildNumbers", "(", "args", ",", "opts", ")", "if", "opts", ".", "tvdata", ":", "# option -D inetref season episode", "if", "(", "len", "(", "args", ")", "!=", "3", ")", "or", "(", "len", "(", "args", "[", "0", "]", ")", "==", "0", ")", "or", "(", "len", "(", "args", "[", "1", "]", ")", "==", "0", ")", "or", "(", "len", "(", "args", "[", "2", "]", ")", "==", "0", ")", ":", "sys", ".", "stdout", ".", "write", "(", "'ERROR: tvmaze -D requires exactly three non-empty arguments'", ")", "sys", ".", "exit", "(", "1", ")", "buildSingle", "(", "args", ",", "opts", ")", "if", "opts", ".", "collectiondata", ":", "# option -C inetref", "if", "(", "len", "(", "args", ")", "!=", "1", ")", "or", "(", "len", "(", "args", "[", "0", "]", ")", "==", "0", ")", ":", "sys", ".", "stdout", ".", "write", "(", "'ERROR: tvmaze -C requires exactly one non-empty argument'", ")", "sys", ".", "exit", "(", "1", ")", "buildCollection", "(", "args", "[", "0", "]", ",", "opts", ")", "except", ":", "if", "opts", ".", "debug", ":", "raise", "sys", ".", "stdout", ".", "write", "(", "'ERROR: '", "+", "str", "(", "sys", ".", "exc_info", "(", ")", "[", "0", "]", ")", "+", "' : '", "+", "str", "(", "sys", ".", "exc_info", "(", ")", "[", "1", "]", ")", "+", "'\\n'", ")", "sys", ".", "exit", "(", "1", ")" ]
https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/programs/scripts/metadata/Television/tvmaze.py#L635-L742
PyMesh/PyMesh
384ba882b7558ba6e8653ed263c419226c22bddf
python/pymesh/meshutils/generate_minimal_surface.py
python
generate_minimal_surface
(loop, resolution=10)
return surface
Generate a minimal surface (e.g. soap membrane) to fill the region bounded by ``loop``. Args: loop: (``numpy.ndarray``): A N by dim array of vertices forming a simple closed loop. resolution (``int``): (optional) How many times to divide the surface. Higher resolution means finer triangulation. Default is 10. Returns: A :py:class:`Mesh` representing the minimal surface that has the input ``loop`` as boundary.
Generate a minimal surface (e.g. soap membrane) to fill the region bounded by ``loop``.
[ "Generate", "a", "minimal", "surface", "(", "e", ".", "g", ".", "soap", "membrane", ")", "to", "fill", "the", "region", "bounded", "by", "loop", "." ]
def generate_minimal_surface(loop, resolution=10): """ Generate a minimal surface (e.g. soap membrane) to fill the region bounded by ``loop``. Args: loop: (``numpy.ndarray``): A N by dim array of vertices forming a simple closed loop. resolution (``int``): (optional) How many times to divide the surface. Higher resolution means finer triangulation. Default is 10. Returns: A :py:class:`Mesh` representing the minimal surface that has the input ``loop`` as boundary. """ N = len(loop) arc_lengths = np.zeros(N) for i in range(1,N): arc_lengths[i] = arc_lengths[i-1] + \ numpy.linalg.norm(loop[i-1] - loop[i]) L = arc_lengths[-1] + numpy.linalg.norm(loop[0] - loop[-1]) thetas = arc_lengths / L * 2 * math.pi x = np.cos(thetas) y = np.sin(thetas) pts = np.array([x,y]).T idx = np.arange(N, dtype=int) edges = np.array([idx, np.roll(idx, -1)]).T tri = triangle() tri.points = pts tri.segments = edges tri.max_area = (1.0 / resolution)**2 tri.split_boundary = False tri.run() domain = tri.mesh assembler = Assembler(domain) L = assembler.assemble("laplacian") pts = solve_harmonic(L, np.arange(N, dtype=int), loop) surface = form_mesh(pts, domain.faces) return surface
[ "def", "generate_minimal_surface", "(", "loop", ",", "resolution", "=", "10", ")", ":", "N", "=", "len", "(", "loop", ")", "arc_lengths", "=", "np", ".", "zeros", "(", "N", ")", "for", "i", "in", "range", "(", "1", ",", "N", ")", ":", "arc_lengths", "[", "i", "]", "=", "arc_lengths", "[", "i", "-", "1", "]", "+", "numpy", ".", "linalg", ".", "norm", "(", "loop", "[", "i", "-", "1", "]", "-", "loop", "[", "i", "]", ")", "L", "=", "arc_lengths", "[", "-", "1", "]", "+", "numpy", ".", "linalg", ".", "norm", "(", "loop", "[", "0", "]", "-", "loop", "[", "-", "1", "]", ")", "thetas", "=", "arc_lengths", "/", "L", "*", "2", "*", "math", ".", "pi", "x", "=", "np", ".", "cos", "(", "thetas", ")", "y", "=", "np", ".", "sin", "(", "thetas", ")", "pts", "=", "np", ".", "array", "(", "[", "x", ",", "y", "]", ")", ".", "T", "idx", "=", "np", ".", "arange", "(", "N", ",", "dtype", "=", "int", ")", "edges", "=", "np", ".", "array", "(", "[", "idx", ",", "np", ".", "roll", "(", "idx", ",", "-", "1", ")", "]", ")", ".", "T", "tri", "=", "triangle", "(", ")", "tri", ".", "points", "=", "pts", "tri", ".", "segments", "=", "edges", "tri", ".", "max_area", "=", "(", "1.0", "/", "resolution", ")", "**", "2", "tri", ".", "split_boundary", "=", "False", "tri", ".", "run", "(", ")", "domain", "=", "tri", ".", "mesh", "assembler", "=", "Assembler", "(", "domain", ")", "L", "=", "assembler", ".", "assemble", "(", "\"laplacian\"", ")", "pts", "=", "solve_harmonic", "(", "L", ",", "np", ".", "arange", "(", "N", ",", "dtype", "=", "int", ")", ",", "loop", ")", "surface", "=", "form_mesh", "(", "pts", ",", "domain", ".", "faces", ")", "return", "surface" ]
https://github.com/PyMesh/PyMesh/blob/384ba882b7558ba6e8653ed263c419226c22bddf/python/pymesh/meshutils/generate_minimal_surface.py#L32-L74
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/ops/variables.py
python
Variable.count_up_to
(self, limit)
return state_ops.count_up_to(self._variable, limit=limit)
Increments this variable until it reaches `limit`. When that Op is run it tries to increment the variable by `1`. If incrementing the variable would bring it above `limit` then the Op raises the exception `OutOfRangeError`. If no error is raised, the Op outputs the value of the variable before the increment. This is essentially a shortcut for `count_up_to(self, limit)`. Args: limit: value at which incrementing the variable raises an error. Returns: A `Tensor` that will hold the variable value before the increment. If no other Op modifies this variable, the values produced will all be distinct.
Increments this variable until it reaches `limit`.
[ "Increments", "this", "variable", "until", "it", "reaches", "limit", "." ]
def count_up_to(self, limit): """Increments this variable until it reaches `limit`. When that Op is run it tries to increment the variable by `1`. If incrementing the variable would bring it above `limit` then the Op raises the exception `OutOfRangeError`. If no error is raised, the Op outputs the value of the variable before the increment. This is essentially a shortcut for `count_up_to(self, limit)`. Args: limit: value at which incrementing the variable raises an error. Returns: A `Tensor` that will hold the variable value before the increment. If no other Op modifies this variable, the values produced will all be distinct. """ return state_ops.count_up_to(self._variable, limit=limit)
[ "def", "count_up_to", "(", "self", ",", "limit", ")", ":", "return", "state_ops", ".", "count_up_to", "(", "self", ".", "_variable", ",", "limit", "=", "limit", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/variables.py#L607-L627
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/propgrid.py
python
PGArrayEditorDialog.OnAddClick
(*args, **kwargs)
return _propgrid.PGArrayEditorDialog_OnAddClick(*args, **kwargs)
OnAddClick(self, CommandEvent event)
OnAddClick(self, CommandEvent event)
[ "OnAddClick", "(", "self", "CommandEvent", "event", ")" ]
def OnAddClick(*args, **kwargs): """OnAddClick(self, CommandEvent event)""" return _propgrid.PGArrayEditorDialog_OnAddClick(*args, **kwargs)
[ "def", "OnAddClick", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PGArrayEditorDialog_OnAddClick", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/propgrid.py#L3210-L3212
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/distutils/dist.py
python
DistributionMetadata.write_pkg_info
(self, base_dir)
Write the PKG-INFO file into the release tree.
Write the PKG-INFO file into the release tree.
[ "Write", "the", "PKG", "-", "INFO", "file", "into", "the", "release", "tree", "." ]
def write_pkg_info (self, base_dir): """Write the PKG-INFO file into the release tree. """ pkg_info = open( os.path.join(base_dir, 'PKG-INFO'), 'w') self.write_pkg_file(pkg_info) pkg_info.close()
[ "def", "write_pkg_info", "(", "self", ",", "base_dir", ")", ":", "pkg_info", "=", "open", "(", "os", ".", "path", ".", "join", "(", "base_dir", ",", "'PKG-INFO'", ")", ",", "'w'", ")", "self", ".", "write_pkg_file", "(", "pkg_info", ")", "pkg_info", ".", "close", "(", ")" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/distutils/dist.py#L1072-L1079
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
DataFormats/FWLite/python/__init__.py
python
Handle.__init__
(self, typeString, **kwargs)
Initialize python handle wrapper
Initialize python handle wrapper
[ "Initialize", "python", "handle", "wrapper" ]
def __init__ (self, typeString, **kwargs): """Initialize python handle wrapper """ # turn off warnings oldWarningLevel = ROOT.gErrorIgnoreLevel ROOT.gErrorIgnoreLevel = ROOT.kError self._nodel = False if kwargs.get ('noDelete'): print("Not deleting wrapper") del kwargs['noDelete'] else: self._nodel = True self._type = typeString self._resetWrapper() self._exception = RuntimeError ("getByLabel not called for '%s'", self) # restore warning state ROOT.gErrorIgnoreLevel = oldWarningLevel # Since we deleted the options as we used them, that means # that kwargs should be empty. If it's not, that means that # somebody passed in an argument that we're not using and we # should complain. if len (kwargs): raise RuntimeError("Unknown arguments %s" % kwargs)
[ "def", "__init__", "(", "self", ",", "typeString", ",", "*", "*", "kwargs", ")", ":", "# turn off warnings", "oldWarningLevel", "=", "ROOT", ".", "gErrorIgnoreLevel", "ROOT", ".", "gErrorIgnoreLevel", "=", "ROOT", ".", "kError", "self", ".", "_nodel", "=", "False", "if", "kwargs", ".", "get", "(", "'noDelete'", ")", ":", "print", "(", "\"Not deleting wrapper\"", ")", "del", "kwargs", "[", "'noDelete'", "]", "else", ":", "self", ".", "_nodel", "=", "True", "self", ".", "_type", "=", "typeString", "self", ".", "_resetWrapper", "(", ")", "self", ".", "_exception", "=", "RuntimeError", "(", "\"getByLabel not called for '%s'\"", ",", "self", ")", "# restore warning state", "ROOT", ".", "gErrorIgnoreLevel", "=", "oldWarningLevel", "# Since we deleted the options as we used them, that means", "# that kwargs should be empty. If it's not, that means that", "# somebody passed in an argument that we're not using and we", "# should complain.", "if", "len", "(", "kwargs", ")", ":", "raise", "RuntimeError", "(", "\"Unknown arguments %s\"", "%", "kwargs", ")" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/DataFormats/FWLite/python/__init__.py#L53-L76
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_gdi.py
python
Brush.IsHatch
(*args, **kwargs)
return _gdi_.Brush_IsHatch(*args, **kwargs)
IsHatch(self) -> bool Is the current style a hatch type?
IsHatch(self) -> bool
[ "IsHatch", "(", "self", ")", "-", ">", "bool" ]
def IsHatch(*args, **kwargs): """ IsHatch(self) -> bool Is the current style a hatch type? """ return _gdi_.Brush_IsHatch(*args, **kwargs)
[ "def", "IsHatch", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "Brush_IsHatch", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L572-L578
ideawu/ssdb-rocks
a3cbb322cafb2f493252829c608e2239df98c9ac
deps/cpy/antlr3/tree.py
python
TreeAdaptor.replaceChildren
(self, parent, startChildIndex, stopChildIndex, t)
Replace from start to stop child index of parent with t, which might be a list. Number of children may be different after this call. If parent is null, don't do anything; must be at root of overall tree. Can't replace whatever points to the parent externally. Do nothing.
Replace from start to stop child index of parent with t, which might be a list. Number of children may be different after this call.
[ "Replace", "from", "start", "to", "stop", "child", "index", "of", "parent", "with", "t", "which", "might", "be", "a", "list", ".", "Number", "of", "children", "may", "be", "different", "after", "this", "call", "." ]
def replaceChildren(self, parent, startChildIndex, stopChildIndex, t): """ Replace from start to stop child index of parent with t, which might be a list. Number of children may be different after this call. If parent is null, don't do anything; must be at root of overall tree. Can't replace whatever points to the parent externally. Do nothing. """ raise NotImplementedError
[ "def", "replaceChildren", "(", "self", ",", "parent", ",", "startChildIndex", ",", "stopChildIndex", ",", "t", ")", ":", "raise", "NotImplementedError" ]
https://github.com/ideawu/ssdb-rocks/blob/a3cbb322cafb2f493252829c608e2239df98c9ac/deps/cpy/antlr3/tree.py#L561-L571
ucsb-seclab/difuze
bb59a12ff87ad5ae45d9c60e349891bf80d72877
helper_scripts/post_processing/parse.py
python
build_pointer
(elem, name, offset)
return ptr_elem
pointers are just string elements.. we name them specially so that our post_processor can create a mapping later.
pointers are just string elements.. we name them specially so that our post_processor can create a mapping later.
[ "pointers", "are", "just", "string", "elements", "..", "we", "name", "them", "specially", "so", "that", "our", "post_processor", "can", "create", "a", "mapping", "later", "." ]
def build_pointer(elem, name, offset): ''' pointers are just string elements.. we name them specially so that our post_processor can create a mapping later. ''' # okay, there are a couple things to do here: # (1) If this is a simple ptr (char, void, int, etc). The depth is 1 and we already know the type # (2) get to the bottom of the pointer to assess pointer depth # (3) once there. Check if it's a ptr to a builtin, or a struct pointer_depth = 1 size = elem.get('bit-size') length = str(int(size)/8) elem_base = elem.get('base-type-builtin') elem_type = elem.get('type') # (1) we have a simple case here where it's a pointer to something like an int or char.. if elem_base is not None: ptr_to = lookup[elem_base] elem_size = size_lookup[elem_base] ptr_elem = ET.Element('Pointer', name=name, length=length, ptr_to=ptr_to, ptr_depth=str(pointer_depth), base=elem_base, offset=offset, elem_size=str(elem_size)) return ptr_elem # (2) okay, ptr to something else. Let's get to the bottom here. resolved_ele = find_type(root, elem.get('base-type')) resolved_base = resolved_ele.get('base-type-builtin') resolved_type = resolved_ele.get('type') # (2) cont. This ptr is more than 1 level deep. so keep going till we hit the bottom while (resolved_base is None and resolved_type == 'pointer'): pointer_depth += 1 resolved_ele = find_type(root, resolved_ele.get('base-type')) resolved_base = resolved_ele.get('base-type-builtin') resolved_type = resolved_ele.get('type') # (3) we've hit the bottom, now we either have a builtin, a struct, or some fucked up stuff that we're gonna ignore for now # (3a) it's a builtin, nice if resolved_base is not None: # this is to account for the fact that nonbuiltin ptrs will always have 1 extra depth just to get the the type pointer_depth += 1 resolved_size = size_lookup[resolved_base] ptr_to = lookup[resolved_base] ptr_elem = ET.Element('Pointer', name=name, length=length, ptr_to=ptr_to, ptr_depth=str(pointer_depth), offset=offset, base=resolved_base, elem_size=str(resolved_size)) else: # we're only handle structs right now so check if it's not a struct pointer. if resolved_type == 'struct': ptr_to = resolved_ele.get('ident') ptr_elem = ET.Element('Pointer', name=name, length=length, ptr_to=ptr_to, ptr_depth=str(pointer_depth), offset=offset) elif resolved_type == 'function': ptr_to = 'function' ptr_elem = ET.Element('Pointer', name=name, length=length, ptr_to=ptr_to, ptr_depth=str(pointer_depth), offset=offset) elif resolved_type == 'union': ptr_to = resolved_ele.get('ident') ptr_elem = ET.Element('Pointer', name=name, length=length, ptr_to=ptr_to, ptr_depth=str(pointer_depth), offset=offset) return ptr_elem
[ "def", "build_pointer", "(", "elem", ",", "name", ",", "offset", ")", ":", "# okay, there are a couple things to do here:", "# (1) If this is a simple ptr (char, void, int, etc). The depth is 1 and we already know the type", "# (2) get to the bottom of the pointer to assess pointer depth", "# (3) once there. Check if it's a ptr to a builtin, or a struct", "pointer_depth", "=", "1", "size", "=", "elem", ".", "get", "(", "'bit-size'", ")", "length", "=", "str", "(", "int", "(", "size", ")", "/", "8", ")", "elem_base", "=", "elem", ".", "get", "(", "'base-type-builtin'", ")", "elem_type", "=", "elem", ".", "get", "(", "'type'", ")", "# (1) we have a simple case here where it's a pointer to something like an int or char..", "if", "elem_base", "is", "not", "None", ":", "ptr_to", "=", "lookup", "[", "elem_base", "]", "elem_size", "=", "size_lookup", "[", "elem_base", "]", "ptr_elem", "=", "ET", ".", "Element", "(", "'Pointer'", ",", "name", "=", "name", ",", "length", "=", "length", ",", "ptr_to", "=", "ptr_to", ",", "ptr_depth", "=", "str", "(", "pointer_depth", ")", ",", "base", "=", "elem_base", ",", "offset", "=", "offset", ",", "elem_size", "=", "str", "(", "elem_size", ")", ")", "return", "ptr_elem", "# (2) okay, ptr to something else. Let's get to the bottom here.", "resolved_ele", "=", "find_type", "(", "root", ",", "elem", ".", "get", "(", "'base-type'", ")", ")", "resolved_base", "=", "resolved_ele", ".", "get", "(", "'base-type-builtin'", ")", "resolved_type", "=", "resolved_ele", ".", "get", "(", "'type'", ")", "# (2) cont. This ptr is more than 1 level deep. so keep going till we hit the bottom", "while", "(", "resolved_base", "is", "None", "and", "resolved_type", "==", "'pointer'", ")", ":", "pointer_depth", "+=", "1", "resolved_ele", "=", "find_type", "(", "root", ",", "resolved_ele", ".", "get", "(", "'base-type'", ")", ")", "resolved_base", "=", "resolved_ele", ".", "get", "(", "'base-type-builtin'", ")", "resolved_type", "=", "resolved_ele", ".", "get", "(", "'type'", ")", "# (3) we've hit the bottom, now we either have a builtin, a struct, or some fucked up stuff that we're gonna ignore for now", "# (3a) it's a builtin, nice", "if", "resolved_base", "is", "not", "None", ":", "# this is to account for the fact that nonbuiltin ptrs will always have 1 extra depth just to get the the type", "pointer_depth", "+=", "1", "resolved_size", "=", "size_lookup", "[", "resolved_base", "]", "ptr_to", "=", "lookup", "[", "resolved_base", "]", "ptr_elem", "=", "ET", ".", "Element", "(", "'Pointer'", ",", "name", "=", "name", ",", "length", "=", "length", ",", "ptr_to", "=", "ptr_to", ",", "ptr_depth", "=", "str", "(", "pointer_depth", ")", ",", "offset", "=", "offset", ",", "base", "=", "resolved_base", ",", "elem_size", "=", "str", "(", "resolved_size", ")", ")", "else", ":", "# we're only handle structs right now so check if it's not a struct pointer.", "if", "resolved_type", "==", "'struct'", ":", "ptr_to", "=", "resolved_ele", ".", "get", "(", "'ident'", ")", "ptr_elem", "=", "ET", ".", "Element", "(", "'Pointer'", ",", "name", "=", "name", ",", "length", "=", "length", ",", "ptr_to", "=", "ptr_to", ",", "ptr_depth", "=", "str", "(", "pointer_depth", ")", ",", "offset", "=", "offset", ")", "elif", "resolved_type", "==", "'function'", ":", "ptr_to", "=", "'function'", "ptr_elem", "=", "ET", ".", "Element", "(", "'Pointer'", ",", "name", "=", "name", ",", "length", "=", "length", ",", "ptr_to", "=", "ptr_to", ",", "ptr_depth", "=", "str", "(", "pointer_depth", ")", ",", "offset", "=", "offset", ")", "elif", "resolved_type", "==", "'union'", ":", "ptr_to", "=", "resolved_ele", ".", "get", "(", "'ident'", ")", "ptr_elem", "=", "ET", ".", "Element", "(", "'Pointer'", ",", "name", "=", "name", ",", "length", "=", "length", ",", "ptr_to", "=", "ptr_to", ",", "ptr_depth", "=", "str", "(", "pointer_depth", ")", ",", "offset", "=", "offset", ")", "return", "ptr_elem" ]
https://github.com/ucsb-seclab/difuze/blob/bb59a12ff87ad5ae45d9c60e349891bf80d72877/helper_scripts/post_processing/parse.py#L278-L338
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/memory_inspector/memory_inspector/core/backends.py
python
Register
(backend)
Called by each backend module to register upon initialization.
Called by each backend module to register upon initialization.
[ "Called", "by", "each", "backend", "module", "to", "register", "upon", "initialization", "." ]
def Register(backend): """Called by each backend module to register upon initialization.""" assert(isinstance(backend, Backend)) _backends[backend.name] = backend
[ "def", "Register", "(", "backend", ")", ":", "assert", "(", "isinstance", "(", "backend", ",", "Backend", ")", ")", "_backends", "[", "backend", ".", "name", "]", "=", "backend" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/memory_inspector/memory_inspector/core/backends.py#L8-L11
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/fourwaysplitter.py
python
FourWaySplitter.GetTopRight
(self)
return self.GetWindow(1)
Returns the top right window (window index: 1).
Returns the top right window (window index: 1).
[ "Returns", "the", "top", "right", "window", "(", "window", "index", ":", "1", ")", "." ]
def GetTopRight(self): """ Returns the top right window (window index: 1). """ return self.GetWindow(1)
[ "def", "GetTopRight", "(", "self", ")", ":", "return", "self", ".", "GetWindow", "(", "1", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/fourwaysplitter.py#L507-L510
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/time-needed-to-inform-all-employees.py
python
Solution.numOfMinutes
(self, n, headID, manager, informTime)
return result
:type n: int :type headID: int :type manager: List[int] :type informTime: List[int] :rtype: int
:type n: int :type headID: int :type manager: List[int] :type informTime: List[int] :rtype: int
[ ":", "type", "n", ":", "int", ":", "type", "headID", ":", "int", ":", "type", "manager", ":", "List", "[", "int", "]", ":", "type", "informTime", ":", "List", "[", "int", "]", ":", "rtype", ":", "int" ]
def numOfMinutes(self, n, headID, manager, informTime): """ :type n: int :type headID: int :type manager: List[int] :type informTime: List[int] :rtype: int """ children = collections.defaultdict(list) for child, parent in enumerate(manager): if parent != -1: children[parent].append(child) result = 0 stk = [(headID, 0)] while stk: node, curr = stk.pop() curr += informTime[node] result = max(result, curr) if node not in children: continue for c in children[node]: stk.append((c, curr)) return result
[ "def", "numOfMinutes", "(", "self", ",", "n", ",", "headID", ",", "manager", ",", "informTime", ")", ":", "children", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "child", ",", "parent", "in", "enumerate", "(", "manager", ")", ":", "if", "parent", "!=", "-", "1", ":", "children", "[", "parent", "]", ".", "append", "(", "child", ")", "result", "=", "0", "stk", "=", "[", "(", "headID", ",", "0", ")", "]", "while", "stk", ":", "node", ",", "curr", "=", "stk", ".", "pop", "(", ")", "curr", "+=", "informTime", "[", "node", "]", "result", "=", "max", "(", "result", ",", "curr", ")", "if", "node", "not", "in", "children", ":", "continue", "for", "c", "in", "children", "[", "node", "]", ":", "stk", ".", "append", "(", "(", "c", ",", "curr", ")", ")", "return", "result" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/time-needed-to-inform-all-employees.py#L9-L32
nyuwireless-unipd/ns3-mmwave
4ff9e87e8079764e04cbeccd8e85bff15ae16fb3
utils.py
python
get_bool_from_file
(file_path, bool_name, value_if_missing)
Looks for a Python boolean variable called bool_name in the file specified by file_path and returns its value. If the file or boolean variable aren't found, this function will return value_if_missing.
Looks for a Python boolean variable called bool_name in the file specified by file_path and returns its value.
[ "Looks", "for", "a", "Python", "boolean", "variable", "called", "bool_name", "in", "the", "file", "specified", "by", "file_path", "and", "returns", "its", "value", "." ]
def get_bool_from_file(file_path, bool_name, value_if_missing): '''Looks for a Python boolean variable called bool_name in the file specified by file_path and returns its value. If the file or boolean variable aren't found, this function will return value_if_missing. ''' # Read in the file if it exists. if os.path.exists(file_path): file_in = open(file_path, "r") # Look for the boolean variable. bool_found = False for line in file_in: # Remove any comments. if '#' in line: (line, comment) = line.split('#', 1) # Parse the line. if bool_name in line: # Evaluate the variable's line once it is found. Make # the split function only split it once. bool = eval(line.split('=', 1)[1].strip()) bool_found = True break # Close the file file_in.close() if bool_found: return bool else: return value_if_missing
[ "def", "get_bool_from_file", "(", "file_path", ",", "bool_name", ",", "value_if_missing", ")", ":", "# Read in the file if it exists.", "if", "os", ".", "path", ".", "exists", "(", "file_path", ")", ":", "file_in", "=", "open", "(", "file_path", ",", "\"r\"", ")", "# Look for the boolean variable.", "bool_found", "=", "False", "for", "line", "in", "file_in", ":", "# Remove any comments.", "if", "'#'", "in", "line", ":", "(", "line", ",", "comment", ")", "=", "line", ".", "split", "(", "'#'", ",", "1", ")", "# Parse the line.", "if", "bool_name", "in", "line", ":", "# Evaluate the variable's line once it is found. Make", "# the split function only split it once.", "bool", "=", "eval", "(", "line", ".", "split", "(", "'='", ",", "1", ")", "[", "1", "]", ".", "strip", "(", ")", ")", "bool_found", "=", "True", "break", "# Close the file", "file_in", ".", "close", "(", ")", "if", "bool_found", ":", "return", "bool", "else", ":", "return", "value_if_missing" ]
https://github.com/nyuwireless-unipd/ns3-mmwave/blob/4ff9e87e8079764e04cbeccd8e85bff15ae16fb3/utils.py#L53-L88
tensorflow/minigo
6d89c202cdceaf449aefc3149ab2110d44f1a6a4
bigtable_input.py
python
get_unparsed_moves_from_last_n_games
(games, games_nr, n, moves=2**21, shuffle=True, column_family=TFEXAMPLE, column='example', values_only=True)
return ds
Get a dataset of serialized TFExamples from the last N games. Args: games, games_nr: GameQueues of the regular selfplay and calibration (aka 'no resign') games to sample from. n: an integer indicating how many past games should be sourced. moves: an integer indicating how many moves should be sampled from those N games. column_family: name of the column family containing move examples. column: name of the column containing move examples. shuffle: if True, shuffle the selected move examples. values_only: if True, return only column values, no row keys. Returns: A dataset containing no more than `moves` examples, sampled randomly from the last `n` games in the table.
Get a dataset of serialized TFExamples from the last N games.
[ "Get", "a", "dataset", "of", "serialized", "TFExamples", "from", "the", "last", "N", "games", "." ]
def get_unparsed_moves_from_last_n_games(games, games_nr, n, moves=2**21, shuffle=True, column_family=TFEXAMPLE, column='example', values_only=True): """Get a dataset of serialized TFExamples from the last N games. Args: games, games_nr: GameQueues of the regular selfplay and calibration (aka 'no resign') games to sample from. n: an integer indicating how many past games should be sourced. moves: an integer indicating how many moves should be sampled from those N games. column_family: name of the column family containing move examples. column: name of the column containing move examples. shuffle: if True, shuffle the selected move examples. values_only: if True, return only column values, no row keys. Returns: A dataset containing no more than `moves` examples, sampled randomly from the last `n` games in the table. """ mix = mix_by_decile(n, moves, 9) resign = games.moves_from_last_n_games( mix.games_r, mix.moves_r, shuffle, column_family, column) no_resign = games_nr.moves_from_last_n_games( mix.games_c, mix.moves_c, shuffle, column_family, column) choice = tf.data.Dataset.from_tensor_slices(mix.selection).repeat().take(moves) ds = tf.data.experimental.choose_from_datasets([resign, no_resign], choice) if shuffle: ds = ds.shuffle(len(mix.selection) * 2) if values_only: ds = ds.map(lambda row_name, s: s) return ds
[ "def", "get_unparsed_moves_from_last_n_games", "(", "games", ",", "games_nr", ",", "n", ",", "moves", "=", "2", "**", "21", ",", "shuffle", "=", "True", ",", "column_family", "=", "TFEXAMPLE", ",", "column", "=", "'example'", ",", "values_only", "=", "True", ")", ":", "mix", "=", "mix_by_decile", "(", "n", ",", "moves", ",", "9", ")", "resign", "=", "games", ".", "moves_from_last_n_games", "(", "mix", ".", "games_r", ",", "mix", ".", "moves_r", ",", "shuffle", ",", "column_family", ",", "column", ")", "no_resign", "=", "games_nr", ".", "moves_from_last_n_games", "(", "mix", ".", "games_c", ",", "mix", ".", "moves_c", ",", "shuffle", ",", "column_family", ",", "column", ")", "choice", "=", "tf", ".", "data", ".", "Dataset", ".", "from_tensor_slices", "(", "mix", ".", "selection", ")", ".", "repeat", "(", ")", ".", "take", "(", "moves", ")", "ds", "=", "tf", ".", "data", ".", "experimental", ".", "choose_from_datasets", "(", "[", "resign", ",", "no_resign", "]", ",", "choice", ")", "if", "shuffle", ":", "ds", "=", "ds", ".", "shuffle", "(", "len", "(", "mix", ".", "selection", ")", "*", "2", ")", "if", "values_only", ":", "ds", "=", "ds", ".", "map", "(", "lambda", "row_name", ",", "s", ":", "s", ")", "return", "ds" ]
https://github.com/tensorflow/minigo/blob/6d89c202cdceaf449aefc3149ab2110d44f1a6a4/bigtable_input.py#L644-L684
gnuradio/gnuradio
09c3c4fa4bfb1a02caac74cb5334dfe065391e3b
grc/core/blocks/block.py
python
Block.is_deprecated
(self)
return False
Check whether the block is deprecated. For now, we just check the category name for presence of "deprecated". As it might be desirable in the future to have such "tags" be stored explicitly, we're taking the detour of introducing a property.
Check whether the block is deprecated.
[ "Check", "whether", "the", "block", "is", "deprecated", "." ]
def is_deprecated(self): """ Check whether the block is deprecated. For now, we just check the category name for presence of "deprecated". As it might be desirable in the future to have such "tags" be stored explicitly, we're taking the detour of introducing a property. """ if not self.category: return False try: return self.flags.deprecated or any("deprecated".casefold() in cat.casefold() for cat in self.category) except Exception as exception: print(exception.message) return False
[ "def", "is_deprecated", "(", "self", ")", ":", "if", "not", "self", ".", "category", ":", "return", "False", "try", ":", "return", "self", ".", "flags", ".", "deprecated", "or", "any", "(", "\"deprecated\"", ".", "casefold", "(", ")", "in", "cat", ".", "casefold", "(", ")", "for", "cat", "in", "self", ".", "category", ")", "except", "Exception", "as", "exception", ":", "print", "(", "exception", ".", "message", ")", "return", "False" ]
https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/grc/core/blocks/block.py#L560-L577
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/training/evaluation.py
python
_get_or_create_eval_step
()
Gets or creates the eval step `Tensor`. Returns: A `Tensor` representing a counter for the evaluation step. Raises: ValueError: If multiple `Tensors` have been added to the `tf.GraphKeys.EVAL_STEP` collection.
Gets or creates the eval step `Tensor`.
[ "Gets", "or", "creates", "the", "eval", "step", "Tensor", "." ]
def _get_or_create_eval_step(): """Gets or creates the eval step `Tensor`. Returns: A `Tensor` representing a counter for the evaluation step. Raises: ValueError: If multiple `Tensors` have been added to the `tf.GraphKeys.EVAL_STEP` collection. """ graph = ops.get_default_graph() eval_steps = graph.get_collection(ops.GraphKeys.EVAL_STEP) if len(eval_steps) == 1: return eval_steps[0] elif len(eval_steps) > 1: raise ValueError('Multiple tensors added to tf.GraphKeys.EVAL_STEP') else: counter = variable_scope.get_variable( 'eval_step', shape=[], dtype=dtypes.int64, initializer=init_ops.zeros_initializer(), trainable=False, collections=[ops.GraphKeys.LOCAL_VARIABLES, ops.GraphKeys.EVAL_STEP]) return counter
[ "def", "_get_or_create_eval_step", "(", ")", ":", "graph", "=", "ops", ".", "get_default_graph", "(", ")", "eval_steps", "=", "graph", ".", "get_collection", "(", "ops", ".", "GraphKeys", ".", "EVAL_STEP", ")", "if", "len", "(", "eval_steps", ")", "==", "1", ":", "return", "eval_steps", "[", "0", "]", "elif", "len", "(", "eval_steps", ")", ">", "1", ":", "raise", "ValueError", "(", "'Multiple tensors added to tf.GraphKeys.EVAL_STEP'", ")", "else", ":", "counter", "=", "variable_scope", ".", "get_variable", "(", "'eval_step'", ",", "shape", "=", "[", "]", ",", "dtype", "=", "dtypes", ".", "int64", ",", "initializer", "=", "init_ops", ".", "zeros_initializer", "(", ")", ",", "trainable", "=", "False", ",", "collections", "=", "[", "ops", ".", "GraphKeys", ".", "LOCAL_VARIABLES", ",", "ops", ".", "GraphKeys", ".", "EVAL_STEP", "]", ")", "return", "counter" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/training/evaluation.py#L35-L59
bingwin/MicroChat
81d9a71a212c1cbca5bba497ec42659a7d25dccf
mars/lint/cpplint.py
python
NestingState.InNamespaceBody
(self)
return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
Check if we are currently one level inside a namespace body. Returns: True if top of the stack is a namespace block, False otherwise.
Check if we are currently one level inside a namespace body.
[ "Check", "if", "we", "are", "currently", "one", "level", "inside", "a", "namespace", "body", "." ]
def InNamespaceBody(self): """Check if we are currently one level inside a namespace body. Returns: True if top of the stack is a namespace block, False otherwise. """ return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
[ "def", "InNamespaceBody", "(", "self", ")", ":", "return", "self", ".", "stack", "and", "isinstance", "(", "self", ".", "stack", "[", "-", "1", "]", ",", "_NamespaceInfo", ")" ]
https://github.com/bingwin/MicroChat/blob/81d9a71a212c1cbca5bba497ec42659a7d25dccf/mars/lint/cpplint.py#L2239-L2245
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
ppapi/generators/idl_gen_wrapper.py
python
WrapperGen.InterfaceNeedsWrapper
(self, iface, releases)
return True
Return true if the interface has ANY methods that need wrapping.
Return true if the interface has ANY methods that need wrapping.
[ "Return", "true", "if", "the", "interface", "has", "ANY", "methods", "that", "need", "wrapping", "." ]
def InterfaceNeedsWrapper(self, iface, releases): """Return true if the interface has ANY methods that need wrapping. """ return True
[ "def", "InterfaceNeedsWrapper", "(", "self", ",", "iface", ",", "releases", ")", ":", "return", "True" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/ppapi/generators/idl_gen_wrapper.py#L200-L203
casadi/casadi
8d0f80a4d0fe2054384bfb9748f7a0f6bae540ff
misc/cpplint.py
python
_SetVerboseLevel
(level)
return _cpplint_state.SetVerboseLevel(level)
Sets the module's verbosity, and returns the previous setting.
Sets the module's verbosity, and returns the previous setting.
[ "Sets", "the", "module", "s", "verbosity", "and", "returns", "the", "previous", "setting", "." ]
def _SetVerboseLevel(level): """Sets the module's verbosity, and returns the previous setting.""" return _cpplint_state.SetVerboseLevel(level)
[ "def", "_SetVerboseLevel", "(", "level", ")", ":", "return", "_cpplint_state", ".", "SetVerboseLevel", "(", "level", ")" ]
https://github.com/casadi/casadi/blob/8d0f80a4d0fe2054384bfb9748f7a0f6bae540ff/misc/cpplint.py#L775-L777
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
python/mxnet/kvstore.py
python
create
(name='local')
return KVStore(handle)
Creates a new KVStore. For single machine training, there are two commonly used types: ``local``: Copies all gradients to CPU memory and updates weights there. ``device``: Aggregates gradients and updates weights on GPUs. With this setting, the KVStore also attempts to use GPU peer-to-peer communication, potentially accelerating the communication. For distributed training, KVStore also supports a number of types: ``dist_sync``: Behaves similarly to ``local`` but with one major difference. With ``dist_sync``, batch-size now means the batch size used on each machine. So if there are ``n`` machines and we use batch size ``b``, then ``dist_sync`` behaves like ``local`` with batch size ``n * b``. ``dist_device_sync``: Identical to ``dist_sync`` with the difference similar to ``device`` vs ``local``. ``dist_async``: Performs asynchronous updates. The weights are updated whenever gradients are received from any machine. No two updates happen on the same weight at the same time. However, the order is not guaranteed. Parameters ---------- name : {'local', 'device', 'nccl', 'dist_sync', 'dist_device_sync', 'dist_async'} The type of KVStore. Returns ------- kv : KVStore The created KVStore.
Creates a new KVStore.
[ "Creates", "a", "new", "KVStore", "." ]
def create(name='local'): """Creates a new KVStore. For single machine training, there are two commonly used types: ``local``: Copies all gradients to CPU memory and updates weights there. ``device``: Aggregates gradients and updates weights on GPUs. With this setting, the KVStore also attempts to use GPU peer-to-peer communication, potentially accelerating the communication. For distributed training, KVStore also supports a number of types: ``dist_sync``: Behaves similarly to ``local`` but with one major difference. With ``dist_sync``, batch-size now means the batch size used on each machine. So if there are ``n`` machines and we use batch size ``b``, then ``dist_sync`` behaves like ``local`` with batch size ``n * b``. ``dist_device_sync``: Identical to ``dist_sync`` with the difference similar to ``device`` vs ``local``. ``dist_async``: Performs asynchronous updates. The weights are updated whenever gradients are received from any machine. No two updates happen on the same weight at the same time. However, the order is not guaranteed. Parameters ---------- name : {'local', 'device', 'nccl', 'dist_sync', 'dist_device_sync', 'dist_async'} The type of KVStore. Returns ------- kv : KVStore The created KVStore. """ if not isinstance(name, string_types): raise TypeError('name must be a string') handle = KVStoreHandle() check_call(_LIB.MXKVStoreCreate(c_str(name), ctypes.byref(handle))) return KVStore(handle)
[ "def", "create", "(", "name", "=", "'local'", ")", ":", "if", "not", "isinstance", "(", "name", ",", "string_types", ")", ":", "raise", "TypeError", "(", "'name must be a string'", ")", "handle", "=", "KVStoreHandle", "(", ")", "check_call", "(", "_LIB", ".", "MXKVStoreCreate", "(", "c_str", "(", "name", ")", ",", "ctypes", ".", "byref", "(", "handle", ")", ")", ")", "return", "KVStore", "(", "handle", ")" ]
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/kvstore.py#L600-L640
davisking/dlib
d665bfb8994a52029bdf56576ad4e982cbc684be
setup.py
python
read_version_from_cmakelists
(cmake_file)
return major + '.' + minor + '.' + patch
Read version information
Read version information
[ "Read", "version", "information" ]
def read_version_from_cmakelists(cmake_file): """Read version information """ major = re.findall("set\(CPACK_PACKAGE_VERSION_MAJOR.*\"(.*)\"", open(cmake_file).read())[0] minor = re.findall("set\(CPACK_PACKAGE_VERSION_MINOR.*\"(.*)\"", open(cmake_file).read())[0] patch = re.findall("set\(CPACK_PACKAGE_VERSION_PATCH.*\"(.*)\"", open(cmake_file).read())[0] return major + '.' + minor + '.' + patch
[ "def", "read_version_from_cmakelists", "(", "cmake_file", ")", ":", "major", "=", "re", ".", "findall", "(", "\"set\\(CPACK_PACKAGE_VERSION_MAJOR.*\\\"(.*)\\\"\"", ",", "open", "(", "cmake_file", ")", ".", "read", "(", ")", ")", "[", "0", "]", "minor", "=", "re", ".", "findall", "(", "\"set\\(CPACK_PACKAGE_VERSION_MINOR.*\\\"(.*)\\\"\"", ",", "open", "(", "cmake_file", ")", ".", "read", "(", ")", ")", "[", "0", "]", "patch", "=", "re", ".", "findall", "(", "\"set\\(CPACK_PACKAGE_VERSION_PATCH.*\\\"(.*)\\\"\"", ",", "open", "(", "cmake_file", ")", ".", "read", "(", ")", ")", "[", "0", "]", "return", "major", "+", "'.'", "+", "minor", "+", "'.'", "+", "patch" ]
https://github.com/davisking/dlib/blob/d665bfb8994a52029bdf56576ad4e982cbc684be/setup.py#L209-L215
fossephate/JoyCon-Driver
857e4e76e26f05d72400ae5d9f2a22cae88f3548
joycon-driver/full/wxWidgets-3.0.3/build/bakefiles/wxwin.py
python
mkLibName
(wxid)
return '$(WXNAMEPREFIXGUI)$(WXNAMESUFFIX)_%s$(WXVERSIONTAG)$(HOST_SUFFIX)' % wxid
Returns string that can be used as library name, including name suffixes, prefixes, version tags etc. This must be kept in sync with variables defined in common.bkl!
Returns string that can be used as library name, including name suffixes, prefixes, version tags etc. This must be kept in sync with variables defined in common.bkl!
[ "Returns", "string", "that", "can", "be", "used", "as", "library", "name", "including", "name", "suffixes", "prefixes", "version", "tags", "etc", ".", "This", "must", "be", "kept", "in", "sync", "with", "variables", "defined", "in", "common", ".", "bkl!" ]
def mkLibName(wxid): """Returns string that can be used as library name, including name suffixes, prefixes, version tags etc. This must be kept in sync with variables defined in common.bkl!""" if wxid == 'mono': return '$(WXNAMEPREFIXGUI)$(WXNAMESUFFIX)$(WXVERSIONTAG)$(HOST_SUFFIX)' if wxid == 'base': return '$(WXNAMEPREFIX)$(WXNAMESUFFIX)$(WXVERSIONTAG)$(HOST_SUFFIX)' if wxid in LIBS_NOGUI: return '$(WXNAMEPREFIX)$(WXNAMESUFFIX)_%s$(WXVERSIONTAG)$(HOST_SUFFIX)' % wxid return '$(WXNAMEPREFIXGUI)$(WXNAMESUFFIX)_%s$(WXVERSIONTAG)$(HOST_SUFFIX)' % wxid
[ "def", "mkLibName", "(", "wxid", ")", ":", "if", "wxid", "==", "'mono'", ":", "return", "'$(WXNAMEPREFIXGUI)$(WXNAMESUFFIX)$(WXVERSIONTAG)$(HOST_SUFFIX)'", "if", "wxid", "==", "'base'", ":", "return", "'$(WXNAMEPREFIX)$(WXNAMESUFFIX)$(WXVERSIONTAG)$(HOST_SUFFIX)'", "if", "wxid", "in", "LIBS_NOGUI", ":", "return", "'$(WXNAMEPREFIX)$(WXNAMESUFFIX)_%s$(WXVERSIONTAG)$(HOST_SUFFIX)'", "%", "wxid", "return", "'$(WXNAMEPREFIXGUI)$(WXNAMESUFFIX)_%s$(WXVERSIONTAG)$(HOST_SUFFIX)'", "%", "wxid" ]
https://github.com/fossephate/JoyCon-Driver/blob/857e4e76e26f05d72400ae5d9f2a22cae88f3548/joycon-driver/full/wxWidgets-3.0.3/build/bakefiles/wxwin.py#L57-L67
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
packages/seacas/scripts/exomerge3.py
python
ExodusModel.get_side_set_name
(self, side_set_id)
return self.side_sets[side_set_id][0]
Return the name of a side set.
Return the name of a side set.
[ "Return", "the", "name", "of", "a", "side", "set", "." ]
def get_side_set_name(self, side_set_id): """Return the name of a side set.""" [side_set_id] = self._format_side_set_id_list([side_set_id], single=True) return self.side_sets[side_set_id][0]
[ "def", "get_side_set_name", "(", "self", ",", "side_set_id", ")", ":", "[", "side_set_id", "]", "=", "self", ".", "_format_side_set_id_list", "(", "[", "side_set_id", "]", ",", "single", "=", "True", ")", "return", "self", ".", "side_sets", "[", "side_set_id", "]", "[", "0", "]" ]
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exomerge3.py#L3848-L3851
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/logging/config.py
python
DictConfigurator.configure
(self)
Do the configuration.
Do the configuration.
[ "Do", "the", "configuration", "." ]
def configure(self): """Do the configuration.""" config = self.config if 'version' not in config: raise ValueError("dictionary doesn't specify a version") if config['version'] != 1: raise ValueError("Unsupported version: %s" % config['version']) incremental = config.pop('incremental', False) EMPTY_DICT = {} logging._acquireLock() try: if incremental: handlers = config.get('handlers', EMPTY_DICT) for name in handlers: if name not in logging._handlers: raise ValueError('No handler found with ' 'name %r' % name) else: try: handler = logging._handlers[name] handler_config = handlers[name] level = handler_config.get('level', None) if level: handler.setLevel(logging._checkLevel(level)) except StandardError, e: raise ValueError('Unable to configure handler ' '%r: %s' % (name, e)) loggers = config.get('loggers', EMPTY_DICT) for name in loggers: try: self.configure_logger(name, loggers[name], True) except StandardError, e: raise ValueError('Unable to configure logger ' '%r: %s' % (name, e)) root = config.get('root', None) if root: try: self.configure_root(root, True) except StandardError, e: raise ValueError('Unable to configure root ' 'logger: %s' % e) else: disable_existing = config.pop('disable_existing_loggers', True) logging._handlers.clear() del logging._handlerList[:] # Do formatters first - they don't refer to anything else formatters = config.get('formatters', EMPTY_DICT) for name in formatters: try: formatters[name] = self.configure_formatter( formatters[name]) except StandardError, e: raise ValueError('Unable to configure ' 'formatter %r: %s' % (name, e)) # Next, do filters - they don't refer to anything else, either filters = config.get('filters', EMPTY_DICT) for name in filters: try: filters[name] = self.configure_filter(filters[name]) except StandardError, e: raise ValueError('Unable to configure ' 'filter %r: %s' % (name, e)) # Next, do handlers - they refer to formatters and filters # As handlers can refer to other handlers, sort the keys # to allow a deterministic order of configuration handlers = config.get('handlers', EMPTY_DICT) deferred = [] for name in sorted(handlers): try: handler = self.configure_handler(handlers[name]) handler.name = name handlers[name] = handler except StandardError, e: if 'target not configured yet' in str(e): deferred.append(name) else: raise ValueError('Unable to configure handler ' '%r: %s' % (name, e)) # Now do any that were deferred for name in deferred: try: handler = self.configure_handler(handlers[name]) handler.name = name handlers[name] = handler except StandardError, e: raise ValueError('Unable to configure handler ' '%r: %s' % (name, e)) # Next, do loggers - they refer to handlers and filters #we don't want to lose the existing loggers, #since other threads may have pointers to them. #existing is set to contain all existing loggers, #and as we go through the new configuration we #remove any which are configured. At the end, #what's left in existing is the set of loggers #which were in the previous configuration but #which are not in the new configuration. root = logging.root existing = root.manager.loggerDict.keys() #The list needs to be sorted so that we can #avoid disabling child loggers of explicitly #named loggers. With a sorted list it is easier #to find the child loggers. existing.sort() #We'll keep the list of existing loggers #which are children of named loggers here... child_loggers = [] #now set up the new ones... loggers = config.get('loggers', EMPTY_DICT) for name in loggers: name = _encoded(name) if name in existing: i = existing.index(name) prefixed = name + "." pflen = len(prefixed) num_existing = len(existing) i = i + 1 # look at the entry after name while (i < num_existing) and\ (existing[i][:pflen] == prefixed): child_loggers.append(existing[i]) i = i + 1 existing.remove(name) try: self.configure_logger(name, loggers[name]) except StandardError, e: raise ValueError('Unable to configure logger ' '%r: %s' % (name, e)) #Disable any old loggers. There's no point deleting #them as other threads may continue to hold references #and by disabling them, you stop them doing any logging. #However, don't disable children of named loggers, as that's #probably not what was intended by the user. for log in existing: logger = root.manager.loggerDict[log] if log in child_loggers: logger.level = logging.NOTSET logger.handlers = [] logger.propagate = True elif disable_existing: logger.disabled = True # And finally, do the root logger root = config.get('root', None) if root: try: self.configure_root(root) except StandardError, e: raise ValueError('Unable to configure root ' 'logger: %s' % e) finally: logging._releaseLock()
[ "def", "configure", "(", "self", ")", ":", "config", "=", "self", ".", "config", "if", "'version'", "not", "in", "config", ":", "raise", "ValueError", "(", "\"dictionary doesn't specify a version\"", ")", "if", "config", "[", "'version'", "]", "!=", "1", ":", "raise", "ValueError", "(", "\"Unsupported version: %s\"", "%", "config", "[", "'version'", "]", ")", "incremental", "=", "config", ".", "pop", "(", "'incremental'", ",", "False", ")", "EMPTY_DICT", "=", "{", "}", "logging", ".", "_acquireLock", "(", ")", "try", ":", "if", "incremental", ":", "handlers", "=", "config", ".", "get", "(", "'handlers'", ",", "EMPTY_DICT", ")", "for", "name", "in", "handlers", ":", "if", "name", "not", "in", "logging", ".", "_handlers", ":", "raise", "ValueError", "(", "'No handler found with '", "'name %r'", "%", "name", ")", "else", ":", "try", ":", "handler", "=", "logging", ".", "_handlers", "[", "name", "]", "handler_config", "=", "handlers", "[", "name", "]", "level", "=", "handler_config", ".", "get", "(", "'level'", ",", "None", ")", "if", "level", ":", "handler", ".", "setLevel", "(", "logging", ".", "_checkLevel", "(", "level", ")", ")", "except", "StandardError", ",", "e", ":", "raise", "ValueError", "(", "'Unable to configure handler '", "'%r: %s'", "%", "(", "name", ",", "e", ")", ")", "loggers", "=", "config", ".", "get", "(", "'loggers'", ",", "EMPTY_DICT", ")", "for", "name", "in", "loggers", ":", "try", ":", "self", ".", "configure_logger", "(", "name", ",", "loggers", "[", "name", "]", ",", "True", ")", "except", "StandardError", ",", "e", ":", "raise", "ValueError", "(", "'Unable to configure logger '", "'%r: %s'", "%", "(", "name", ",", "e", ")", ")", "root", "=", "config", ".", "get", "(", "'root'", ",", "None", ")", "if", "root", ":", "try", ":", "self", ".", "configure_root", "(", "root", ",", "True", ")", "except", "StandardError", ",", "e", ":", "raise", "ValueError", "(", "'Unable to configure root '", "'logger: %s'", "%", "e", ")", "else", ":", "disable_existing", "=", "config", ".", "pop", "(", "'disable_existing_loggers'", ",", "True", ")", "logging", ".", "_handlers", ".", "clear", "(", ")", "del", "logging", ".", "_handlerList", "[", ":", "]", "# Do formatters first - they don't refer to anything else", "formatters", "=", "config", ".", "get", "(", "'formatters'", ",", "EMPTY_DICT", ")", "for", "name", "in", "formatters", ":", "try", ":", "formatters", "[", "name", "]", "=", "self", ".", "configure_formatter", "(", "formatters", "[", "name", "]", ")", "except", "StandardError", ",", "e", ":", "raise", "ValueError", "(", "'Unable to configure '", "'formatter %r: %s'", "%", "(", "name", ",", "e", ")", ")", "# Next, do filters - they don't refer to anything else, either", "filters", "=", "config", ".", "get", "(", "'filters'", ",", "EMPTY_DICT", ")", "for", "name", "in", "filters", ":", "try", ":", "filters", "[", "name", "]", "=", "self", ".", "configure_filter", "(", "filters", "[", "name", "]", ")", "except", "StandardError", ",", "e", ":", "raise", "ValueError", "(", "'Unable to configure '", "'filter %r: %s'", "%", "(", "name", ",", "e", ")", ")", "# Next, do handlers - they refer to formatters and filters", "# As handlers can refer to other handlers, sort the keys", "# to allow a deterministic order of configuration", "handlers", "=", "config", ".", "get", "(", "'handlers'", ",", "EMPTY_DICT", ")", "deferred", "=", "[", "]", "for", "name", "in", "sorted", "(", "handlers", ")", ":", "try", ":", "handler", "=", "self", ".", "configure_handler", "(", "handlers", "[", "name", "]", ")", "handler", ".", "name", "=", "name", "handlers", "[", "name", "]", "=", "handler", "except", "StandardError", ",", "e", ":", "if", "'target not configured yet'", "in", "str", "(", "e", ")", ":", "deferred", ".", "append", "(", "name", ")", "else", ":", "raise", "ValueError", "(", "'Unable to configure handler '", "'%r: %s'", "%", "(", "name", ",", "e", ")", ")", "# Now do any that were deferred", "for", "name", "in", "deferred", ":", "try", ":", "handler", "=", "self", ".", "configure_handler", "(", "handlers", "[", "name", "]", ")", "handler", ".", "name", "=", "name", "handlers", "[", "name", "]", "=", "handler", "except", "StandardError", ",", "e", ":", "raise", "ValueError", "(", "'Unable to configure handler '", "'%r: %s'", "%", "(", "name", ",", "e", ")", ")", "# Next, do loggers - they refer to handlers and filters", "#we don't want to lose the existing loggers,", "#since other threads may have pointers to them.", "#existing is set to contain all existing loggers,", "#and as we go through the new configuration we", "#remove any which are configured. At the end,", "#what's left in existing is the set of loggers", "#which were in the previous configuration but", "#which are not in the new configuration.", "root", "=", "logging", ".", "root", "existing", "=", "root", ".", "manager", ".", "loggerDict", ".", "keys", "(", ")", "#The list needs to be sorted so that we can", "#avoid disabling child loggers of explicitly", "#named loggers. With a sorted list it is easier", "#to find the child loggers.", "existing", ".", "sort", "(", ")", "#We'll keep the list of existing loggers", "#which are children of named loggers here...", "child_loggers", "=", "[", "]", "#now set up the new ones...", "loggers", "=", "config", ".", "get", "(", "'loggers'", ",", "EMPTY_DICT", ")", "for", "name", "in", "loggers", ":", "name", "=", "_encoded", "(", "name", ")", "if", "name", "in", "existing", ":", "i", "=", "existing", ".", "index", "(", "name", ")", "prefixed", "=", "name", "+", "\".\"", "pflen", "=", "len", "(", "prefixed", ")", "num_existing", "=", "len", "(", "existing", ")", "i", "=", "i", "+", "1", "# look at the entry after name", "while", "(", "i", "<", "num_existing", ")", "and", "(", "existing", "[", "i", "]", "[", ":", "pflen", "]", "==", "prefixed", ")", ":", "child_loggers", ".", "append", "(", "existing", "[", "i", "]", ")", "i", "=", "i", "+", "1", "existing", ".", "remove", "(", "name", ")", "try", ":", "self", ".", "configure_logger", "(", "name", ",", "loggers", "[", "name", "]", ")", "except", "StandardError", ",", "e", ":", "raise", "ValueError", "(", "'Unable to configure logger '", "'%r: %s'", "%", "(", "name", ",", "e", ")", ")", "#Disable any old loggers. There's no point deleting", "#them as other threads may continue to hold references", "#and by disabling them, you stop them doing any logging.", "#However, don't disable children of named loggers, as that's", "#probably not what was intended by the user.", "for", "log", "in", "existing", ":", "logger", "=", "root", ".", "manager", ".", "loggerDict", "[", "log", "]", "if", "log", "in", "child_loggers", ":", "logger", ".", "level", "=", "logging", ".", "NOTSET", "logger", ".", "handlers", "=", "[", "]", "logger", ".", "propagate", "=", "True", "elif", "disable_existing", ":", "logger", ".", "disabled", "=", "True", "# And finally, do the root logger", "root", "=", "config", ".", "get", "(", "'root'", ",", "None", ")", "if", "root", ":", "try", ":", "self", ".", "configure_root", "(", "root", ")", "except", "StandardError", ",", "e", ":", "raise", "ValueError", "(", "'Unable to configure root '", "'logger: %s'", "%", "e", ")", "finally", ":", "logging", ".", "_releaseLock", "(", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/logging/config.py#L504-L661
etotheipi/BitcoinArmory
2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98
subprocess_win.py
python
_args_from_interpreter_flags
()
return args
Return a list of command-line arguments reproducing the current settings in sys.flags and sys.warnoptions.
Return a list of command-line arguments reproducing the current settings in sys.flags and sys.warnoptions.
[ "Return", "a", "list", "of", "command", "-", "line", "arguments", "reproducing", "the", "current", "settings", "in", "sys", ".", "flags", "and", "sys", ".", "warnoptions", "." ]
def _args_from_interpreter_flags(): """Return a list of command-line arguments reproducing the current settings in sys.flags and sys.warnoptions.""" flag_opt_map = { 'debug': 'd', # 'inspect': 'i', # 'interactive': 'i', 'optimize': 'O', 'dont_write_bytecode': 'B', 'no_user_site': 's', 'no_site': 'S', 'ignore_environment': 'E', 'verbose': 'v', 'bytes_warning': 'b', 'hash_randomization': 'R', 'py3k_warning': '3', } args = [] for flag, opt in flag_opt_map.items(): v = getattr(sys.flags, flag) if v > 0: args.append('-' + opt * v) for opt in sys.warnoptions: args.append('-W' + opt) return args
[ "def", "_args_from_interpreter_flags", "(", ")", ":", "flag_opt_map", "=", "{", "'debug'", ":", "'d'", ",", "# 'inspect': 'i',", "# 'interactive': 'i',", "'optimize'", ":", "'O'", ",", "'dont_write_bytecode'", ":", "'B'", ",", "'no_user_site'", ":", "'s'", ",", "'no_site'", ":", "'S'", ",", "'ignore_environment'", ":", "'E'", ",", "'verbose'", ":", "'v'", ",", "'bytes_warning'", ":", "'b'", ",", "'hash_randomization'", ":", "'R'", ",", "'py3k_warning'", ":", "'3'", ",", "}", "args", "=", "[", "]", "for", "flag", ",", "opt", "in", "flag_opt_map", ".", "items", "(", ")", ":", "v", "=", "getattr", "(", "sys", ".", "flags", ",", "flag", ")", "if", "v", ">", "0", ":", "args", ".", "append", "(", "'-'", "+", "opt", "*", "v", ")", "for", "opt", "in", "sys", ".", "warnoptions", ":", "args", ".", "append", "(", "'-W'", "+", "opt", ")", "return", "args" ]
https://github.com/etotheipi/BitcoinArmory/blob/2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98/subprocess_win.py#L493-L517
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
qa/tasks/cephfs/mount.py
python
CephFSMount.touch
(self, fs_path)
Create a dentry if it doesn't already exist. This python implementation exists because the usual command line tool doesn't pass through error codes like EIO. :param fs_path: :return:
Create a dentry if it doesn't already exist. This python implementation exists because the usual command line tool doesn't pass through error codes like EIO.
[ "Create", "a", "dentry", "if", "it", "doesn", "t", "already", "exist", ".", "This", "python", "implementation", "exists", "because", "the", "usual", "command", "line", "tool", "doesn", "t", "pass", "through", "error", "codes", "like", "EIO", "." ]
def touch(self, fs_path): """ Create a dentry if it doesn't already exist. This python implementation exists because the usual command line tool doesn't pass through error codes like EIO. :param fs_path: :return: """ abs_path = os.path.join(self.hostfs_mntpt, fs_path) pyscript = dedent(""" import sys import errno try: f = open("{path}", "w") f.close() except IOError as e: sys.exit(errno.EIO) """).format(path=abs_path) proc = self._run_python(pyscript) proc.wait()
[ "def", "touch", "(", "self", ",", "fs_path", ")", ":", "abs_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "hostfs_mntpt", ",", "fs_path", ")", "pyscript", "=", "dedent", "(", "\"\"\"\n import sys\n import errno\n\n try:\n f = open(\"{path}\", \"w\")\n f.close()\n except IOError as e:\n sys.exit(errno.EIO)\n \"\"\"", ")", ".", "format", "(", "path", "=", "abs_path", ")", "proc", "=", "self", ".", "_run_python", "(", "pyscript", ")", "proc", ".", "wait", "(", ")" ]
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/qa/tasks/cephfs/mount.py#L1223-L1244
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/dist.py
python
Distribution._exclude_misc
(self, name, value)
Handle 'exclude()' for list/tuple attrs without a special handler
Handle 'exclude()' for list/tuple attrs without a special handler
[ "Handle", "exclude", "()", "for", "list", "/", "tuple", "attrs", "without", "a", "special", "handler" ]
def _exclude_misc(self, name, value): """Handle 'exclude()' for list/tuple attrs without a special handler""" if not isinstance(value, sequence): raise DistutilsSetupError( "%s: setting must be a list or tuple (%r)" % (name, value) ) try: old = getattr(self, name) except AttributeError: raise DistutilsSetupError( "%s: No such distribution setting" % name ) if old is not None and not isinstance(old, sequence): raise DistutilsSetupError( name + ": this setting cannot be changed via include/exclude" ) elif old: setattr(self, name, [item for item in old if item not in value])
[ "def", "_exclude_misc", "(", "self", ",", "name", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "sequence", ")", ":", "raise", "DistutilsSetupError", "(", "\"%s: setting must be a list or tuple (%r)\"", "%", "(", "name", ",", "value", ")", ")", "try", ":", "old", "=", "getattr", "(", "self", ",", "name", ")", "except", "AttributeError", ":", "raise", "DistutilsSetupError", "(", "\"%s: No such distribution setting\"", "%", "name", ")", "if", "old", "is", "not", "None", "and", "not", "isinstance", "(", "old", ",", "sequence", ")", ":", "raise", "DistutilsSetupError", "(", "name", "+", "\": this setting cannot be changed via include/exclude\"", ")", "elif", "old", ":", "setattr", "(", "self", ",", "name", ",", "[", "item", "for", "item", "in", "old", "if", "item", "not", "in", "value", "]", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/dist.py#L838-L855
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/protobuf/py3/google/protobuf/message.py
python
Message.DiscardUnknownFields
(self)
Clears all fields in the :class:`UnknownFieldSet`. This operation is recursive for nested message.
Clears all fields in the :class:`UnknownFieldSet`.
[ "Clears", "all", "fields", "in", "the", ":", "class", ":", "UnknownFieldSet", "." ]
def DiscardUnknownFields(self): """Clears all fields in the :class:`UnknownFieldSet`. This operation is recursive for nested message. """ raise NotImplementedError
[ "def", "DiscardUnknownFields", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py3/google/protobuf/message.py#L345-L350
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/py_vulcanize/third_party/rjsmin/_setup/py3/dist.py
python
run_setup
(*args, **kwargs)
return not _shell.spawn(*argv)
Run setup
Run setup
[ "Run", "setup" ]
def run_setup(*args, **kwargs): """ Run setup """ if 'setup' in kwargs: script = kwargs.get('setup') or 'setup.py' del kwargs['setup'] else: script = 'setup.py' if 'fakeroot' in kwargs: fakeroot = kwargs['fakeroot'] del kwargs['fakeroot'] else: fakeroot = None if kwargs: raise TypeError("Unrecognized keyword parameters") script = _shell.native(script) argv = [_sys.executable, script] + list(args) if fakeroot: argv.insert(0, fakeroot) return not _shell.spawn(*argv)
[ "def", "run_setup", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "'setup'", "in", "kwargs", ":", "script", "=", "kwargs", ".", "get", "(", "'setup'", ")", "or", "'setup.py'", "del", "kwargs", "[", "'setup'", "]", "else", ":", "script", "=", "'setup.py'", "if", "'fakeroot'", "in", "kwargs", ":", "fakeroot", "=", "kwargs", "[", "'fakeroot'", "]", "del", "kwargs", "[", "'fakeroot'", "]", "else", ":", "fakeroot", "=", "None", "if", "kwargs", ":", "raise", "TypeError", "(", "\"Unrecognized keyword parameters\"", ")", "script", "=", "_shell", ".", "native", "(", "script", ")", "argv", "=", "[", "_sys", ".", "executable", ",", "script", "]", "+", "list", "(", "args", ")", "if", "fakeroot", ":", "argv", ".", "insert", "(", "0", ",", "fakeroot", ")", "return", "not", "_shell", ".", "spawn", "(", "*", "argv", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/py_vulcanize/third_party/rjsmin/_setup/py3/dist.py#L32-L51
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
python/psutil/psutil/__init__.py
python
test
()
List info of all currently running processes emulating ps aux output.
List info of all currently running processes emulating ps aux output.
[ "List", "info", "of", "all", "currently", "running", "processes", "emulating", "ps", "aux", "output", "." ]
def test(): """List info of all currently running processes emulating ps aux output. """ import datetime from psutil._compat import print_ today_day = datetime.date.today() templ = "%-10s %5s %4s %4s %7s %7s %-13s %5s %7s %s" attrs = ['pid', 'get_cpu_percent', 'get_memory_percent', 'name', 'get_cpu_times', 'create_time', 'get_memory_info'] if os.name == 'posix': attrs.append('uids') attrs.append('terminal') print_(templ % ("USER", "PID", "%CPU", "%MEM", "VSZ", "RSS", "TTY", "START", "TIME", "COMMAND")) for p in sorted(process_iter(), key=lambda p: p.pid): try: pinfo = p.as_dict(attrs, ad_value='') except NoSuchProcess: pass else: if pinfo['create_time']: ctime = datetime.datetime.fromtimestamp(pinfo['create_time']) if ctime.date() == today_day: ctime = ctime.strftime("%H:%M") else: ctime = ctime.strftime("%b%d") else: ctime = '' cputime = time.strftime("%M:%S", time.localtime(sum(pinfo['cpu_times']))) try: user = p.username except KeyError: if os.name == 'posix': if pinfo['uids']: user = str(pinfo['uids'].real) else: user = '' else: raise except Error: user = '' if os.name == 'nt' and '\\' in user: user = user.split('\\')[1] vms = pinfo['memory_info'] and \ int(pinfo['memory_info'].vms / 1024) or '?' rss = pinfo['memory_info'] and \ int(pinfo['memory_info'].rss / 1024) or '?' memp = pinfo['memory_percent'] and \ round(pinfo['memory_percent'], 1) or '?' print_(templ % (user[:10], pinfo['pid'], pinfo['cpu_percent'], memp, vms, rss, pinfo.get('terminal', '') or '?', ctime, cputime, pinfo['name'].strip() or '?'))
[ "def", "test", "(", ")", ":", "import", "datetime", "from", "psutil", ".", "_compat", "import", "print_", "today_day", "=", "datetime", ".", "date", ".", "today", "(", ")", "templ", "=", "\"%-10s %5s %4s %4s %7s %7s %-13s %5s %7s %s\"", "attrs", "=", "[", "'pid'", ",", "'get_cpu_percent'", ",", "'get_memory_percent'", ",", "'name'", ",", "'get_cpu_times'", ",", "'create_time'", ",", "'get_memory_info'", "]", "if", "os", ".", "name", "==", "'posix'", ":", "attrs", ".", "append", "(", "'uids'", ")", "attrs", ".", "append", "(", "'terminal'", ")", "print_", "(", "templ", "%", "(", "\"USER\"", ",", "\"PID\"", ",", "\"%CPU\"", ",", "\"%MEM\"", ",", "\"VSZ\"", ",", "\"RSS\"", ",", "\"TTY\"", ",", "\"START\"", ",", "\"TIME\"", ",", "\"COMMAND\"", ")", ")", "for", "p", "in", "sorted", "(", "process_iter", "(", ")", ",", "key", "=", "lambda", "p", ":", "p", ".", "pid", ")", ":", "try", ":", "pinfo", "=", "p", ".", "as_dict", "(", "attrs", ",", "ad_value", "=", "''", ")", "except", "NoSuchProcess", ":", "pass", "else", ":", "if", "pinfo", "[", "'create_time'", "]", ":", "ctime", "=", "datetime", ".", "datetime", ".", "fromtimestamp", "(", "pinfo", "[", "'create_time'", "]", ")", "if", "ctime", ".", "date", "(", ")", "==", "today_day", ":", "ctime", "=", "ctime", ".", "strftime", "(", "\"%H:%M\"", ")", "else", ":", "ctime", "=", "ctime", ".", "strftime", "(", "\"%b%d\"", ")", "else", ":", "ctime", "=", "''", "cputime", "=", "time", ".", "strftime", "(", "\"%M:%S\"", ",", "time", ".", "localtime", "(", "sum", "(", "pinfo", "[", "'cpu_times'", "]", ")", ")", ")", "try", ":", "user", "=", "p", ".", "username", "except", "KeyError", ":", "if", "os", ".", "name", "==", "'posix'", ":", "if", "pinfo", "[", "'uids'", "]", ":", "user", "=", "str", "(", "pinfo", "[", "'uids'", "]", ".", "real", ")", "else", ":", "user", "=", "''", "else", ":", "raise", "except", "Error", ":", "user", "=", "''", "if", "os", ".", "name", "==", "'nt'", "and", "'\\\\'", "in", "user", ":", "user", "=", "user", ".", "split", "(", "'\\\\'", ")", "[", "1", "]", "vms", "=", "pinfo", "[", "'memory_info'", "]", "and", "int", "(", "pinfo", "[", "'memory_info'", "]", ".", "vms", "/", "1024", ")", "or", "'?'", "rss", "=", "pinfo", "[", "'memory_info'", "]", "and", "int", "(", "pinfo", "[", "'memory_info'", "]", ".", "rss", "/", "1024", ")", "or", "'?'", "memp", "=", "pinfo", "[", "'memory_percent'", "]", "and", "round", "(", "pinfo", "[", "'memory_percent'", "]", ",", "1", ")", "or", "'?'", "print_", "(", "templ", "%", "(", "user", "[", ":", "10", "]", ",", "pinfo", "[", "'pid'", "]", ",", "pinfo", "[", "'cpu_percent'", "]", ",", "memp", ",", "vms", ",", "rss", ",", "pinfo", ".", "get", "(", "'terminal'", ",", "''", ")", "or", "'?'", ",", "ctime", ",", "cputime", ",", "pinfo", "[", "'name'", "]", ".", "strip", "(", ")", "or", "'?'", ")", ")" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/psutil/psutil/__init__.py#L1340-L1400
Netflix/NfWebCrypto
499faf4eb9f9ccf0b21dc728e974970f54bd6c52
plugin/ppapi/ppapi/generators/idl_generator.py
python
GeneratorByFile.GenerateFile
(self, filenode, releases, options)
return 0
Generates an output file from the IDL source. Returns true if the generated file is different than the previously generated file.
Generates an output file from the IDL source.
[ "Generates", "an", "output", "file", "from", "the", "IDL", "source", "." ]
def GenerateFile(self, filenode, releases, options): """Generates an output file from the IDL source. Returns true if the generated file is different than the previously generated file. """ __pychecker__ = 'unusednames=filenode,releases,options' self.Error("Undefined release generator.") return 0
[ "def", "GenerateFile", "(", "self", ",", "filenode", ",", "releases", ",", "options", ")", ":", "__pychecker__", "=", "'unusednames=filenode,releases,options'", "self", ".", "Error", "(", "\"Undefined release generator.\"", ")", "return", "0" ]
https://github.com/Netflix/NfWebCrypto/blob/499faf4eb9f9ccf0b21dc728e974970f54bd6c52/plugin/ppapi/ppapi/generators/idl_generator.py#L163-L171
faasm/faasm
b3bc196d887adbd0bb9802bcb93323543bad59cb
faasmcli/faasmcli/tasks/disas.py
python
symbols
(ctx, user, func)
Print out the symbols for this function
Print out the symbols for this function
[ "Print", "out", "the", "symbols", "for", "this", "function" ]
def symbols(ctx, user, func): """ Print out the symbols for this function """ syms_path = disassemble_function(user, func) with open(syms_path) as fh: print(fh.read()) print("\nSymbols written to {}".format(syms_path))
[ "def", "symbols", "(", "ctx", ",", "user", ",", "func", ")", ":", "syms_path", "=", "disassemble_function", "(", "user", ",", "func", ")", "with", "open", "(", "syms_path", ")", "as", "fh", ":", "print", "(", "fh", ".", "read", "(", ")", ")", "print", "(", "\"\\nSymbols written to {}\"", ".", "format", "(", "syms_path", ")", ")" ]
https://github.com/faasm/faasm/blob/b3bc196d887adbd0bb9802bcb93323543bad59cb/faasmcli/faasmcli/tasks/disas.py#L10-L19
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/logging/handlers.py
python
SysLogHandler.close
(self)
Closes the socket.
Closes the socket.
[ "Closes", "the", "socket", "." ]
def close(self): """ Closes the socket. """ self.acquire() try: self.socket.close() logging.Handler.close(self) finally: self.release()
[ "def", "close", "(", "self", ")", ":", "self", ".", "acquire", "(", ")", "try", ":", "self", ".", "socket", ".", "close", "(", ")", "logging", ".", "Handler", ".", "close", "(", "self", ")", "finally", ":", "self", ".", "release", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/logging/handlers.py#L886-L895
RoboJackets/robocup-software
bce13ce53ddb2ecb9696266d980722c34617dc15
rj_gameplay/stp/rc.py
python
Field.floor_length_m
(self)
return self.__floor_length_m
:return: check on this one
:return: check on this one
[ ":", "return", ":", "check", "on", "this", "one" ]
def floor_length_m(self) -> float: """ :return: check on this one """ return self.__floor_length_m
[ "def", "floor_length_m", "(", "self", ")", "->", "float", ":", "return", "self", ".", "__floor_length_m" ]
https://github.com/RoboJackets/robocup-software/blob/bce13ce53ddb2ecb9696266d980722c34617dc15/rj_gameplay/stp/rc.py#L385-L389
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/python/turicreate/toolkits/topic_model/topic_model.py
python
TopicModel.evaluate
(self, train_data, test_data=None, metric="perplexity")
return ret
Estimate the model's ability to predict new data. Imagine you have a corpus of books. One common approach to evaluating topic models is to train on the first half of all of the books and see how well the model predicts the second half of each book. This method returns a metric called perplexity, which is related to the likelihood of observing these words under the given model. See :py:func:`~turicreate.topic_model.perplexity` for more details. The provided `train_data` and `test_data` must have the same length, i.e., both data sets must have the same number of documents; the model will use train_data to estimate which topic the document belongs to, and this is used to estimate the model's performance at predicting the unseen words in the test data. See :py:func:`~turicreate.topic_model.TopicModel.predict` for details on how these predictions are made, and see :py:func:`~turicreate.text_analytics.random_split` for a helper function that can be used for making train/test splits. Parameters ---------- train_data : SArray or SFrame A set of documents to predict topics for. test_data : SArray or SFrame, optional A set of documents to evaluate performance on. By default this will set to be the same as train_data. metric : str The chosen metric to use for evaluating the topic model. Currently only 'perplexity' is supported. Returns ------- out : dict The set of estimated evaluation metrics. See Also -------- predict, turicreate.toolkits.text_analytics.random_split Examples -------- >>> docs = turicreate.SArray('https://static.turi.com/datasets/nips-text') >>> train_data, test_data = turicreate.text_analytics.random_split(docs) >>> m = turicreate.topic_model.create(train_data) >>> m.evaluate(train_data, test_data) {'perplexity': 2467.530370396021}
Estimate the model's ability to predict new data. Imagine you have a corpus of books. One common approach to evaluating topic models is to train on the first half of all of the books and see how well the model predicts the second half of each book.
[ "Estimate", "the", "model", "s", "ability", "to", "predict", "new", "data", ".", "Imagine", "you", "have", "a", "corpus", "of", "books", ".", "One", "common", "approach", "to", "evaluating", "topic", "models", "is", "to", "train", "on", "the", "first", "half", "of", "all", "of", "the", "books", "and", "see", "how", "well", "the", "model", "predicts", "the", "second", "half", "of", "each", "book", "." ]
def evaluate(self, train_data, test_data=None, metric="perplexity"): """ Estimate the model's ability to predict new data. Imagine you have a corpus of books. One common approach to evaluating topic models is to train on the first half of all of the books and see how well the model predicts the second half of each book. This method returns a metric called perplexity, which is related to the likelihood of observing these words under the given model. See :py:func:`~turicreate.topic_model.perplexity` for more details. The provided `train_data` and `test_data` must have the same length, i.e., both data sets must have the same number of documents; the model will use train_data to estimate which topic the document belongs to, and this is used to estimate the model's performance at predicting the unseen words in the test data. See :py:func:`~turicreate.topic_model.TopicModel.predict` for details on how these predictions are made, and see :py:func:`~turicreate.text_analytics.random_split` for a helper function that can be used for making train/test splits. Parameters ---------- train_data : SArray or SFrame A set of documents to predict topics for. test_data : SArray or SFrame, optional A set of documents to evaluate performance on. By default this will set to be the same as train_data. metric : str The chosen metric to use for evaluating the topic model. Currently only 'perplexity' is supported. Returns ------- out : dict The set of estimated evaluation metrics. See Also -------- predict, turicreate.toolkits.text_analytics.random_split Examples -------- >>> docs = turicreate.SArray('https://static.turi.com/datasets/nips-text') >>> train_data, test_data = turicreate.text_analytics.random_split(docs) >>> m = turicreate.topic_model.create(train_data) >>> m.evaluate(train_data, test_data) {'perplexity': 2467.530370396021} """ train_data = _check_input(train_data) if test_data is None: test_data = train_data else: test_data = _check_input(test_data) predictions = self.predict(train_data, output_type="probability") topics = self.topics ret = {} ret["perplexity"] = perplexity( test_data, predictions, topics["topic_probabilities"], topics["vocabulary"] ) return ret
[ "def", "evaluate", "(", "self", ",", "train_data", ",", "test_data", "=", "None", ",", "metric", "=", "\"perplexity\"", ")", ":", "train_data", "=", "_check_input", "(", "train_data", ")", "if", "test_data", "is", "None", ":", "test_data", "=", "train_data", "else", ":", "test_data", "=", "_check_input", "(", "test_data", ")", "predictions", "=", "self", ".", "predict", "(", "train_data", ",", "output_type", "=", "\"probability\"", ")", "topics", "=", "self", ".", "topics", "ret", "=", "{", "}", "ret", "[", "\"perplexity\"", "]", "=", "perplexity", "(", "test_data", ",", "predictions", ",", "topics", "[", "\"topic_probabilities\"", "]", ",", "topics", "[", "\"vocabulary\"", "]", ")", "return", "ret" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/toolkits/topic_model/topic_model.py#L696-L763
microsoft/CNTK
e9396480025b9ca457d26b6f33dd07c474c6aa04
bindings/python/cntk/train/trainer.py
python
Trainer.model
(self)
return super(Trainer, self).model()
The model that the trainer is training.
The model that the trainer is training.
[ "The", "model", "that", "the", "trainer", "is", "training", "." ]
def model(self): ''' The model that the trainer is training. ''' return super(Trainer, self).model()
[ "def", "model", "(", "self", ")", ":", "return", "super", "(", "Trainer", ",", "self", ")", ".", "model", "(", ")" ]
https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/bindings/python/cntk/train/trainer.py#L264-L268
larq/compute-engine
a2611f8e33f5cb9b4d09b7c9aff7053620a24305
larq_compute_engine/mlir/python/util.py
python
_update_signature_def_tensors
(tensor_maps, map_old_to_new_tensors)
Update the tensors in the SignatureDef's TensorMaps.
Update the tensors in the SignatureDef's TensorMaps.
[ "Update", "the", "tensors", "in", "the", "SignatureDef", "s", "TensorMaps", "." ]
def _update_signature_def_tensors(tensor_maps, map_old_to_new_tensors): """Update the tensors in the SignatureDef's TensorMaps.""" for i in range(len(tensor_maps)): if tensor_maps[i].tensorIndex in map_old_to_new_tensors: tensor_maps[i].tensorIndex = map_old_to_new_tensors[ tensor_maps[i].tensorIndex ]
[ "def", "_update_signature_def_tensors", "(", "tensor_maps", ",", "map_old_to_new_tensors", ")", ":", "for", "i", "in", "range", "(", "len", "(", "tensor_maps", ")", ")", ":", "if", "tensor_maps", "[", "i", "]", ".", "tensorIndex", "in", "map_old_to_new_tensors", ":", "tensor_maps", "[", "i", "]", ".", "tensorIndex", "=", "map_old_to_new_tensors", "[", "tensor_maps", "[", "i", "]", ".", "tensorIndex", "]" ]
https://github.com/larq/compute-engine/blob/a2611f8e33f5cb9b4d09b7c9aff7053620a24305/larq_compute_engine/mlir/python/util.py#L57-L63
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/graph_editor/subgraph.py
python
SubGraphView._assign_from
(self, other)
Assign other to itself. Args: other: another subgraph-view. Returns: A new instance identical to the original one. Raises: TypeError: if other is not an SubGraphView.
Assign other to itself.
[ "Assign", "other", "to", "itself", "." ]
def _assign_from(self, other): """Assign other to itself. Args: other: another subgraph-view. Returns: A new instance identical to the original one. Raises: TypeError: if other is not an SubGraphView. """ if not isinstance(other, SubGraphView): raise TypeError("Expected SubGraphView, got: {}".format(type(other))) # pylint: disable=protected-access self._graph = other._graph self._ops = list(other._ops) self._passthrough_ts = list(other._passthrough_ts) self._input_ts = list(other._input_ts) self._output_ts = list(other._output_ts)
[ "def", "_assign_from", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "SubGraphView", ")", ":", "raise", "TypeError", "(", "\"Expected SubGraphView, got: {}\"", ".", "format", "(", "type", "(", "other", ")", ")", ")", "# pylint: disable=protected-access", "self", ".", "_graph", "=", "other", ".", "_graph", "self", ".", "_ops", "=", "list", "(", "other", ".", "_ops", ")", "self", ".", "_passthrough_ts", "=", "list", "(", "other", ".", "_passthrough_ts", ")", "self", ".", "_input_ts", "=", "list", "(", "other", ".", "_input_ts", ")", "self", ".", "_output_ts", "=", "list", "(", "other", ".", "_output_ts", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/graph_editor/subgraph.py#L234-L251
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/traitlets/py3/traitlets/utils/descriptions.py
python
add_article
(name, definite=False, capital=False)
Returns the string with a prepended article. The input does not need to begin with a charater. Parameters ---------- name : str Name to which to prepend an article definite : bool (default: False) Whether the article is definite or not. Indefinite articles being 'a' and 'an', while 'the' is definite. capital : bool (default: False) Whether the added article should have its first letter capitalized or not.
Returns the string with a prepended article.
[ "Returns", "the", "string", "with", "a", "prepended", "article", "." ]
def add_article(name, definite=False, capital=False): """Returns the string with a prepended article. The input does not need to begin with a charater. Parameters ---------- name : str Name to which to prepend an article definite : bool (default: False) Whether the article is definite or not. Indefinite articles being 'a' and 'an', while 'the' is definite. capital : bool (default: False) Whether the added article should have its first letter capitalized or not. """ if definite: result = "the " + name else: first_letters = re.compile(r'[\W_]+').sub('', name) if first_letters[:1].lower() in 'aeiou': result = 'an ' + name else: result = 'a ' + name if capital: return result[0].upper() + result[1:] else: return result
[ "def", "add_article", "(", "name", ",", "definite", "=", "False", ",", "capital", "=", "False", ")", ":", "if", "definite", ":", "result", "=", "\"the \"", "+", "name", "else", ":", "first_letters", "=", "re", ".", "compile", "(", "r'[\\W_]+'", ")", ".", "sub", "(", "''", ",", "name", ")", "if", "first_letters", "[", ":", "1", "]", ".", "lower", "(", ")", "in", "'aeiou'", ":", "result", "=", "'an '", "+", "name", "else", ":", "result", "=", "'a '", "+", "name", "if", "capital", ":", "return", "result", "[", "0", "]", ".", "upper", "(", ")", "+", "result", "[", "1", ":", "]", "else", ":", "return", "result" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/traitlets/py3/traitlets/utils/descriptions.py#L133-L161
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Code/Tools/waf-1.7.13/waflib/Tools/msvc.py
python
msvc_common_flags
(conf)
Setup the flags required for executing the msvc compiler
Setup the flags required for executing the msvc compiler
[ "Setup", "the", "flags", "required", "for", "executing", "the", "msvc", "compiler" ]
def msvc_common_flags(conf): """ Setup the flags required for executing the msvc compiler """ v = conf.env v['DEST_BINFMT'] = 'pe' v.append_value('CFLAGS', ['/nologo']) v.append_value('CXXFLAGS', ['/nologo']) v['DEFINES_ST'] = '/D%s' v['CC_SRC_F'] = '' v['CC_TGT_F'] = ['/c', '/Fo'] v['CXX_SRC_F'] = '' v['CXX_TGT_F'] = ['/c', '/Fo'] if (v.MSVC_COMPILER == 'msvc' and v.MSVC_VERSION >= 8) or (v.MSVC_COMPILER == 'wsdk' and v.MSVC_VERSION >= 6): v['CC_TGT_F']= ['/FC'] + v['CC_TGT_F'] v['CXX_TGT_F']= ['/FC'] + v['CXX_TGT_F'] v['CPPPATH_ST'] = '/I%s' # template for adding include paths v['AR_TGT_F'] = v['CCLNK_TGT_F'] = v['CXXLNK_TGT_F'] = '/OUT:' # Subsystem specific flags v['CFLAGS_CONSOLE'] = v['CXXFLAGS_CONSOLE'] = ['/SUBSYSTEM:CONSOLE'] v['CFLAGS_NATIVE'] = v['CXXFLAGS_NATIVE'] = ['/SUBSYSTEM:NATIVE'] v['CFLAGS_POSIX'] = v['CXXFLAGS_POSIX'] = ['/SUBSYSTEM:POSIX'] v['CFLAGS_WINDOWS'] = v['CXXFLAGS_WINDOWS'] = ['/SUBSYSTEM:WINDOWS'] v['CFLAGS_WINDOWSCE'] = v['CXXFLAGS_WINDOWSCE'] = ['/SUBSYSTEM:WINDOWSCE'] # CRT specific flags v['CFLAGS_CRT_MULTITHREADED'] = v['CXXFLAGS_CRT_MULTITHREADED'] = ['/MT'] v['CFLAGS_CRT_MULTITHREADED_DLL'] = v['CXXFLAGS_CRT_MULTITHREADED_DLL'] = ['/MD'] v['CFLAGS_CRT_MULTITHREADED_DBG'] = v['CXXFLAGS_CRT_MULTITHREADED_DBG'] = ['/MTd'] v['CFLAGS_CRT_MULTITHREADED_DLL_DBG'] = v['CXXFLAGS_CRT_MULTITHREADED_DLL_DBG'] = ['/MDd'] # linker v['LIB_ST'] = '%s.lib' # template for adding shared libs v['LIBPATH_ST'] = '/LIBPATH:%s' # template for adding libpaths v['STLIB_ST'] = '%s.lib' v['STLIBPATH_ST'] = '/LIBPATH:%s' v.append_value('LINKFLAGS', ['/NOLOGO']) if v['MSVC_MANIFEST']: v.append_value('LINKFLAGS', ['/MANIFEST:EMBED']) # shared library v['CFLAGS_cshlib'] = [] v['CXXFLAGS_cxxshlib'] = [] v['LINKFLAGS_cshlib'] = v['LINKFLAGS_cxxshlib'] = ['/DLL'] v['cshlib_PATTERN'] = v['cxxshlib_PATTERN'] = '%s.dll' v['implib_PATTERN'] = '%s.lib' v['IMPLIB_ST'] = '/IMPLIB:%s' # static library v['LINKFLAGS_cstlib'] = [] v['cstlib_PATTERN'] = v['cxxstlib_PATTERN'] = '%s.lib' # program v['cprogram_PATTERN'] = v['cxxprogram_PATTERN'] = '%s.exe'
[ "def", "msvc_common_flags", "(", "conf", ")", ":", "v", "=", "conf", ".", "env", "v", "[", "'DEST_BINFMT'", "]", "=", "'pe'", "v", ".", "append_value", "(", "'CFLAGS'", ",", "[", "'/nologo'", "]", ")", "v", ".", "append_value", "(", "'CXXFLAGS'", ",", "[", "'/nologo'", "]", ")", "v", "[", "'DEFINES_ST'", "]", "=", "'/D%s'", "v", "[", "'CC_SRC_F'", "]", "=", "''", "v", "[", "'CC_TGT_F'", "]", "=", "[", "'/c'", ",", "'/Fo'", "]", "v", "[", "'CXX_SRC_F'", "]", "=", "''", "v", "[", "'CXX_TGT_F'", "]", "=", "[", "'/c'", ",", "'/Fo'", "]", "if", "(", "v", ".", "MSVC_COMPILER", "==", "'msvc'", "and", "v", ".", "MSVC_VERSION", ">=", "8", ")", "or", "(", "v", ".", "MSVC_COMPILER", "==", "'wsdk'", "and", "v", ".", "MSVC_VERSION", ">=", "6", ")", ":", "v", "[", "'CC_TGT_F'", "]", "=", "[", "'/FC'", "]", "+", "v", "[", "'CC_TGT_F'", "]", "v", "[", "'CXX_TGT_F'", "]", "=", "[", "'/FC'", "]", "+", "v", "[", "'CXX_TGT_F'", "]", "v", "[", "'CPPPATH_ST'", "]", "=", "'/I%s'", "# template for adding include paths", "v", "[", "'AR_TGT_F'", "]", "=", "v", "[", "'CCLNK_TGT_F'", "]", "=", "v", "[", "'CXXLNK_TGT_F'", "]", "=", "'/OUT:'", "# Subsystem specific flags", "v", "[", "'CFLAGS_CONSOLE'", "]", "=", "v", "[", "'CXXFLAGS_CONSOLE'", "]", "=", "[", "'/SUBSYSTEM:CONSOLE'", "]", "v", "[", "'CFLAGS_NATIVE'", "]", "=", "v", "[", "'CXXFLAGS_NATIVE'", "]", "=", "[", "'/SUBSYSTEM:NATIVE'", "]", "v", "[", "'CFLAGS_POSIX'", "]", "=", "v", "[", "'CXXFLAGS_POSIX'", "]", "=", "[", "'/SUBSYSTEM:POSIX'", "]", "v", "[", "'CFLAGS_WINDOWS'", "]", "=", "v", "[", "'CXXFLAGS_WINDOWS'", "]", "=", "[", "'/SUBSYSTEM:WINDOWS'", "]", "v", "[", "'CFLAGS_WINDOWSCE'", "]", "=", "v", "[", "'CXXFLAGS_WINDOWSCE'", "]", "=", "[", "'/SUBSYSTEM:WINDOWSCE'", "]", "# CRT specific flags", "v", "[", "'CFLAGS_CRT_MULTITHREADED'", "]", "=", "v", "[", "'CXXFLAGS_CRT_MULTITHREADED'", "]", "=", "[", "'/MT'", "]", "v", "[", "'CFLAGS_CRT_MULTITHREADED_DLL'", "]", "=", "v", "[", "'CXXFLAGS_CRT_MULTITHREADED_DLL'", "]", "=", "[", "'/MD'", "]", "v", "[", "'CFLAGS_CRT_MULTITHREADED_DBG'", "]", "=", "v", "[", "'CXXFLAGS_CRT_MULTITHREADED_DBG'", "]", "=", "[", "'/MTd'", "]", "v", "[", "'CFLAGS_CRT_MULTITHREADED_DLL_DBG'", "]", "=", "v", "[", "'CXXFLAGS_CRT_MULTITHREADED_DLL_DBG'", "]", "=", "[", "'/MDd'", "]", "# linker", "v", "[", "'LIB_ST'", "]", "=", "'%s.lib'", "# template for adding shared libs", "v", "[", "'LIBPATH_ST'", "]", "=", "'/LIBPATH:%s'", "# template for adding libpaths", "v", "[", "'STLIB_ST'", "]", "=", "'%s.lib'", "v", "[", "'STLIBPATH_ST'", "]", "=", "'/LIBPATH:%s'", "v", ".", "append_value", "(", "'LINKFLAGS'", ",", "[", "'/NOLOGO'", "]", ")", "if", "v", "[", "'MSVC_MANIFEST'", "]", ":", "v", ".", "append_value", "(", "'LINKFLAGS'", ",", "[", "'/MANIFEST:EMBED'", "]", ")", "# shared library", "v", "[", "'CFLAGS_cshlib'", "]", "=", "[", "]", "v", "[", "'CXXFLAGS_cxxshlib'", "]", "=", "[", "]", "v", "[", "'LINKFLAGS_cshlib'", "]", "=", "v", "[", "'LINKFLAGS_cxxshlib'", "]", "=", "[", "'/DLL'", "]", "v", "[", "'cshlib_PATTERN'", "]", "=", "v", "[", "'cxxshlib_PATTERN'", "]", "=", "'%s.dll'", "v", "[", "'implib_PATTERN'", "]", "=", "'%s.lib'", "v", "[", "'IMPLIB_ST'", "]", "=", "'/IMPLIB:%s'", "# static library", "v", "[", "'LINKFLAGS_cstlib'", "]", "=", "[", "]", "v", "[", "'cstlib_PATTERN'", "]", "=", "v", "[", "'cxxstlib_PATTERN'", "]", "=", "'%s.lib'", "# program", "v", "[", "'cprogram_PATTERN'", "]", "=", "v", "[", "'cxxprogram_PATTERN'", "]", "=", "'%s.exe'" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/Tools/msvc.py#L778-L839
dicecco1/fpga_caffe
7a191704efd7873071cfef35772d7e7bf3e3cfd6
python/caffe/pycaffe.py
python
_Net_set_input_arrays
(self, data, labels)
return self._set_input_arrays(data, labels)
Set input arrays of the in-memory MemoryDataLayer. (Note: this is only for networks declared with the memory data layer.)
Set input arrays of the in-memory MemoryDataLayer. (Note: this is only for networks declared with the memory data layer.)
[ "Set", "input", "arrays", "of", "the", "in", "-", "memory", "MemoryDataLayer", ".", "(", "Note", ":", "this", "is", "only", "for", "networks", "declared", "with", "the", "memory", "data", "layer", ".", ")" ]
def _Net_set_input_arrays(self, data, labels): """ Set input arrays of the in-memory MemoryDataLayer. (Note: this is only for networks declared with the memory data layer.) """ if labels.ndim == 1: labels = np.ascontiguousarray(labels[:, np.newaxis, np.newaxis, np.newaxis]) return self._set_input_arrays(data, labels)
[ "def", "_Net_set_input_arrays", "(", "self", ",", "data", ",", "labels", ")", ":", "if", "labels", ".", "ndim", "==", "1", ":", "labels", "=", "np", ".", "ascontiguousarray", "(", "labels", "[", ":", ",", "np", ".", "newaxis", ",", "np", ".", "newaxis", ",", "np", ".", "newaxis", "]", ")", "return", "self", ".", "_set_input_arrays", "(", "data", ",", "labels", ")" ]
https://github.com/dicecco1/fpga_caffe/blob/7a191704efd7873071cfef35772d7e7bf3e3cfd6/python/caffe/pycaffe.py#L261-L269
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
SetCursorEvent.SetCursor
(*args, **kwargs)
return _core_.SetCursorEvent_SetCursor(*args, **kwargs)
SetCursor(self, Cursor cursor) Sets the cursor associated with this event.
SetCursor(self, Cursor cursor)
[ "SetCursor", "(", "self", "Cursor", "cursor", ")" ]
def SetCursor(*args, **kwargs): """ SetCursor(self, Cursor cursor) Sets the cursor associated with this event. """ return _core_.SetCursorEvent_SetCursor(*args, **kwargs)
[ "def", "SetCursor", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "SetCursorEvent_SetCursor", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L5891-L5897
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/menus.py
python
CompletionsMenuControl.mouse_handler
(self, mouse_event: MouseEvent)
return None
Handle mouse events: clicking and scrolling.
Handle mouse events: clicking and scrolling.
[ "Handle", "mouse", "events", ":", "clicking", "and", "scrolling", "." ]
def mouse_handler(self, mouse_event: MouseEvent) -> "NotImplementedOrNone": """ Handle mouse events: clicking and scrolling. """ b = get_app().current_buffer if mouse_event.event_type == MouseEventType.MOUSE_UP: # Select completion. b.go_to_completion(mouse_event.position.y) b.complete_state = None elif mouse_event.event_type == MouseEventType.SCROLL_DOWN: # Scroll up. b.complete_next(count=3, disable_wrap_around=True) elif mouse_event.event_type == MouseEventType.SCROLL_UP: # Scroll down. b.complete_previous(count=3, disable_wrap_around=True) return None
[ "def", "mouse_handler", "(", "self", ",", "mouse_event", ":", "MouseEvent", ")", "->", "\"NotImplementedOrNone\"", ":", "b", "=", "get_app", "(", ")", ".", "current_buffer", "if", "mouse_event", ".", "event_type", "==", "MouseEventType", ".", "MOUSE_UP", ":", "# Select completion.", "b", ".", "go_to_completion", "(", "mouse_event", ".", "position", ".", "y", ")", "b", ".", "complete_state", "=", "None", "elif", "mouse_event", ".", "event_type", "==", "MouseEventType", ".", "SCROLL_DOWN", ":", "# Scroll up.", "b", ".", "complete_next", "(", "count", "=", "3", ",", "disable_wrap_around", "=", "True", ")", "elif", "mouse_event", ".", "event_type", "==", "MouseEventType", ".", "SCROLL_UP", ":", "# Scroll down.", "b", ".", "complete_previous", "(", "count", "=", "3", ",", "disable_wrap_around", "=", "True", ")", "return", "None" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/menus.py#L188-L207
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/third_party/png/png.py
python
Reader.read
(self, lenient=False)
return self.width, self.height, pixels, meta
Read the PNG file and decode it. Returns (`width`, `height`, `pixels`, `metadata`). May use excessive memory. `pixels` are returned in boxed row flat pixel format. If the optional `lenient` argument evaluates to True, checksum failures will raise warnings rather than exceptions.
Read the PNG file and decode it. Returns (`width`, `height`, `pixels`, `metadata`).
[ "Read", "the", "PNG", "file", "and", "decode", "it", ".", "Returns", "(", "width", "height", "pixels", "metadata", ")", "." ]
def read(self, lenient=False): """ Read the PNG file and decode it. Returns (`width`, `height`, `pixels`, `metadata`). May use excessive memory. `pixels` are returned in boxed row flat pixel format. If the optional `lenient` argument evaluates to True, checksum failures will raise warnings rather than exceptions. """ def iteridat(): """Iterator that yields all the ``IDAT`` chunks as strings.""" while True: try: type, data = self.chunk(lenient=lenient) except ValueError, e: raise ChunkError(e.args[0]) if type == 'IEND': # http://www.w3.org/TR/PNG/#11IEND break if type != 'IDAT': continue # type == 'IDAT' # http://www.w3.org/TR/PNG/#11IDAT if self.colormap and not self.plte: warnings.warn("PLTE chunk is required before IDAT chunk") yield data def iterdecomp(idat): """Iterator that yields decompressed strings. `idat` should be an iterator that yields the ``IDAT`` chunk data. """ # Currently, with no max_length paramter to decompress, this # routine will do one yield per IDAT chunk. So not very # incremental. d = zlib.decompressobj() # Each IDAT chunk is passed to the decompressor, then any # remaining state is decompressed out. for data in idat: # :todo: add a max_length argument here to limit output # size. yield array('B', d.decompress(data)) yield array('B', d.flush()) self.preamble(lenient=lenient) raw = iterdecomp(iteridat()) if self.interlace: raw = array('B', itertools.chain(*raw)) arraycode = 'BH'[self.bitdepth>8] # Like :meth:`group` but producing an array.array object for # each row. pixels = itertools.imap(lambda *row: array(arraycode, row), *[iter(self.deinterlace(raw))]*self.width*self.planes) else: pixels = self.iterboxed(self.iterstraight(raw)) meta = dict() for attr in 'greyscale alpha planes bitdepth interlace'.split(): meta[attr] = getattr(self, attr) meta['size'] = (self.width, self.height) for attr in 'gamma transparent background'.split(): a = getattr(self, attr, None) if a is not None: meta[attr] = a if self.plte: meta['palette'] = self.palette() return self.width, self.height, pixels, meta
[ "def", "read", "(", "self", ",", "lenient", "=", "False", ")", ":", "def", "iteridat", "(", ")", ":", "\"\"\"Iterator that yields all the ``IDAT`` chunks as strings.\"\"\"", "while", "True", ":", "try", ":", "type", ",", "data", "=", "self", ".", "chunk", "(", "lenient", "=", "lenient", ")", "except", "ValueError", ",", "e", ":", "raise", "ChunkError", "(", "e", ".", "args", "[", "0", "]", ")", "if", "type", "==", "'IEND'", ":", "# http://www.w3.org/TR/PNG/#11IEND", "break", "if", "type", "!=", "'IDAT'", ":", "continue", "# type == 'IDAT'", "# http://www.w3.org/TR/PNG/#11IDAT", "if", "self", ".", "colormap", "and", "not", "self", ".", "plte", ":", "warnings", ".", "warn", "(", "\"PLTE chunk is required before IDAT chunk\"", ")", "yield", "data", "def", "iterdecomp", "(", "idat", ")", ":", "\"\"\"Iterator that yields decompressed strings. `idat` should\n be an iterator that yields the ``IDAT`` chunk data.\n \"\"\"", "# Currently, with no max_length paramter to decompress, this", "# routine will do one yield per IDAT chunk. So not very", "# incremental.", "d", "=", "zlib", ".", "decompressobj", "(", ")", "# Each IDAT chunk is passed to the decompressor, then any", "# remaining state is decompressed out.", "for", "data", "in", "idat", ":", "# :todo: add a max_length argument here to limit output", "# size.", "yield", "array", "(", "'B'", ",", "d", ".", "decompress", "(", "data", ")", ")", "yield", "array", "(", "'B'", ",", "d", ".", "flush", "(", ")", ")", "self", ".", "preamble", "(", "lenient", "=", "lenient", ")", "raw", "=", "iterdecomp", "(", "iteridat", "(", ")", ")", "if", "self", ".", "interlace", ":", "raw", "=", "array", "(", "'B'", ",", "itertools", ".", "chain", "(", "*", "raw", ")", ")", "arraycode", "=", "'BH'", "[", "self", ".", "bitdepth", ">", "8", "]", "# Like :meth:`group` but producing an array.array object for", "# each row.", "pixels", "=", "itertools", ".", "imap", "(", "lambda", "*", "row", ":", "array", "(", "arraycode", ",", "row", ")", ",", "*", "[", "iter", "(", "self", ".", "deinterlace", "(", "raw", ")", ")", "]", "*", "self", ".", "width", "*", "self", ".", "planes", ")", "else", ":", "pixels", "=", "self", ".", "iterboxed", "(", "self", ".", "iterstraight", "(", "raw", ")", ")", "meta", "=", "dict", "(", ")", "for", "attr", "in", "'greyscale alpha planes bitdepth interlace'", ".", "split", "(", ")", ":", "meta", "[", "attr", "]", "=", "getattr", "(", "self", ",", "attr", ")", "meta", "[", "'size'", "]", "=", "(", "self", ".", "width", ",", "self", ".", "height", ")", "for", "attr", "in", "'gamma transparent background'", ".", "split", "(", ")", ":", "a", "=", "getattr", "(", "self", ",", "attr", ",", "None", ")", "if", "a", "is", "not", "None", ":", "meta", "[", "attr", "]", "=", "a", "if", "self", ".", "plte", ":", "meta", "[", "'palette'", "]", "=", "self", ".", "palette", "(", ")", "return", "self", ".", "width", ",", "self", ".", "height", ",", "pixels", ",", "meta" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/png/png.py#L1866-L1936
leela-zero/leela-zero
e3ed6310d33d75078ba74c3adf887d18439fc2e3
scripts/cpplint.py
python
_CppLintState.AddFilters
(self, filters)
Adds more filters to the existing list of error-message filters.
Adds more filters to the existing list of error-message filters.
[ "Adds", "more", "filters", "to", "the", "existing", "list", "of", "error", "-", "message", "filters", "." ]
def AddFilters(self, filters): """ Adds more filters to the existing list of error-message 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", "AddFilters", "(", "self", ",", "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/leela-zero/leela-zero/blob/e3ed6310d33d75078ba74c3adf887d18439fc2e3/scripts/cpplint.py#L807-L816
forkineye/ESPixelStick
22926f1c0d1131f1369fc7cad405689a095ae3cb
dist/bin/pyserial/serial/serialcli.py
python
Serial.dsr
(self)
return self._port_handle.DsrHolding
Read terminal status line: Data Set Ready
Read terminal status line: Data Set Ready
[ "Read", "terminal", "status", "line", ":", "Data", "Set", "Ready" ]
def dsr(self): """Read terminal status line: Data Set Ready""" if not self.is_open: raise portNotOpenError return self._port_handle.DsrHolding
[ "def", "dsr", "(", "self", ")", ":", "if", "not", "self", ".", "is_open", ":", "raise", "portNotOpenError", "return", "self", ".", "_port_handle", ".", "DsrHolding" ]
https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/pyserial/serial/serialcli.py#L229-L233
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py3/numpy/core/multiarray.py
python
putmask
(a, mask, values)
return (a, mask, values)
putmask(a, mask, values) Changes elements of an array based on conditional and input values. Sets ``a.flat[n] = values[n]`` for each n where ``mask.flat[n]==True``. If `values` is not the same size as `a` and `mask` then it will repeat. This gives behavior different from ``a[mask] = values``. Parameters ---------- a : ndarray Target array. mask : array_like Boolean mask array. It has to be the same shape as `a`. values : array_like Values to put into `a` where `mask` is True. If `values` is smaller than `a` it will be repeated. See Also -------- place, put, take, copyto Examples -------- >>> x = np.arange(6).reshape(2, 3) >>> np.putmask(x, x>2, x**2) >>> x array([[ 0, 1, 2], [ 9, 16, 25]]) If `values` is smaller than `a` it is repeated: >>> x = np.arange(5) >>> np.putmask(x, x>1, [-33, -44]) >>> x array([ 0, 1, -33, -44, -33])
putmask(a, mask, values)
[ "putmask", "(", "a", "mask", "values", ")" ]
def putmask(a, mask, values): """ putmask(a, mask, values) Changes elements of an array based on conditional and input values. Sets ``a.flat[n] = values[n]`` for each n where ``mask.flat[n]==True``. If `values` is not the same size as `a` and `mask` then it will repeat. This gives behavior different from ``a[mask] = values``. Parameters ---------- a : ndarray Target array. mask : array_like Boolean mask array. It has to be the same shape as `a`. values : array_like Values to put into `a` where `mask` is True. If `values` is smaller than `a` it will be repeated. See Also -------- place, put, take, copyto Examples -------- >>> x = np.arange(6).reshape(2, 3) >>> np.putmask(x, x>2, x**2) >>> x array([[ 0, 1, 2], [ 9, 16, 25]]) If `values` is smaller than `a` it is repeated: >>> x = np.arange(5) >>> np.putmask(x, x>1, [-33, -44]) >>> x array([ 0, 1, -33, -44, -33]) """ return (a, mask, values)
[ "def", "putmask", "(", "a", ",", "mask", ",", "values", ")", ":", "return", "(", "a", ",", "mask", ",", "values", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/core/multiarray.py#L1107-L1148
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/requests/help.py
python
info
()
return { 'platform': platform_info, 'implementation': implementation_info, 'system_ssl': system_ssl_info, 'using_pyopenssl': pyopenssl is not None, 'pyOpenSSL': pyopenssl_info, 'urllib3': urllib3_info, 'chardet': chardet_info, 'cryptography': cryptography_info, 'idna': idna_info, 'requests': { 'version': requests_version, }, }
Generate information for a bug report.
Generate information for a bug report.
[ "Generate", "information", "for", "a", "bug", "report", "." ]
def info(): """Generate information for a bug report.""" try: platform_info = { 'system': platform.system(), 'release': platform.release(), } except IOError: platform_info = { 'system': 'Unknown', 'release': 'Unknown', } implementation_info = _implementation() urllib3_info = {'version': urllib3.__version__} chardet_info = {'version': chardet.__version__} pyopenssl_info = { 'version': None, 'openssl_version': '', } if OpenSSL: pyopenssl_info = { 'version': OpenSSL.__version__, 'openssl_version': '%x' % OpenSSL.SSL.OPENSSL_VERSION_NUMBER, } cryptography_info = { 'version': getattr(cryptography, '__version__', ''), } idna_info = { 'version': getattr(idna, '__version__', ''), } system_ssl = ssl.OPENSSL_VERSION_NUMBER system_ssl_info = { 'version': '%x' % system_ssl if system_ssl is not None else '' } return { 'platform': platform_info, 'implementation': implementation_info, 'system_ssl': system_ssl_info, 'using_pyopenssl': pyopenssl is not None, 'pyOpenSSL': pyopenssl_info, 'urllib3': urllib3_info, 'chardet': chardet_info, 'cryptography': cryptography_info, 'idna': idna_info, 'requests': { 'version': requests_version, }, }
[ "def", "info", "(", ")", ":", "try", ":", "platform_info", "=", "{", "'system'", ":", "platform", ".", "system", "(", ")", ",", "'release'", ":", "platform", ".", "release", "(", ")", ",", "}", "except", "IOError", ":", "platform_info", "=", "{", "'system'", ":", "'Unknown'", ",", "'release'", ":", "'Unknown'", ",", "}", "implementation_info", "=", "_implementation", "(", ")", "urllib3_info", "=", "{", "'version'", ":", "urllib3", ".", "__version__", "}", "chardet_info", "=", "{", "'version'", ":", "chardet", ".", "__version__", "}", "pyopenssl_info", "=", "{", "'version'", ":", "None", ",", "'openssl_version'", ":", "''", ",", "}", "if", "OpenSSL", ":", "pyopenssl_info", "=", "{", "'version'", ":", "OpenSSL", ".", "__version__", ",", "'openssl_version'", ":", "'%x'", "%", "OpenSSL", ".", "SSL", ".", "OPENSSL_VERSION_NUMBER", ",", "}", "cryptography_info", "=", "{", "'version'", ":", "getattr", "(", "cryptography", ",", "'__version__'", ",", "''", ")", ",", "}", "idna_info", "=", "{", "'version'", ":", "getattr", "(", "idna", ",", "'__version__'", ",", "''", ")", ",", "}", "system_ssl", "=", "ssl", ".", "OPENSSL_VERSION_NUMBER", "system_ssl_info", "=", "{", "'version'", ":", "'%x'", "%", "system_ssl", "if", "system_ssl", "is", "not", "None", "else", "''", "}", "return", "{", "'platform'", ":", "platform_info", ",", "'implementation'", ":", "implementation_info", ",", "'system_ssl'", ":", "system_ssl_info", ",", "'using_pyopenssl'", ":", "pyopenssl", "is", "not", "None", ",", "'pyOpenSSL'", ":", "pyopenssl_info", ",", "'urllib3'", ":", "urllib3_info", ",", "'chardet'", ":", "chardet_info", ",", "'cryptography'", ":", "cryptography_info", ",", "'idna'", ":", "idna_info", ",", "'requests'", ":", "{", "'version'", ":", "requests_version", ",", "}", ",", "}" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/requests/help.py#L59-L110
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/floatspin.py
python
FloatSpin.GetValue
(self)
return float(self._value)
Returns the :class:`FloatSpin` value.
Returns the :class:`FloatSpin` value.
[ "Returns", "the", ":", "class", ":", "FloatSpin", "value", "." ]
def GetValue(self): """ Returns the :class:`FloatSpin` value. """ return float(self._value)
[ "def", "GetValue", "(", "self", ")", ":", "return", "float", "(", "self", ".", "_value", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/floatspin.py#L821-L824
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/importlib/machinery.py
python
all_suffixes
()
return SOURCE_SUFFIXES + BYTECODE_SUFFIXES + EXTENSION_SUFFIXES
Returns a list of all recognized module suffixes for this process
Returns a list of all recognized module suffixes for this process
[ "Returns", "a", "list", "of", "all", "recognized", "module", "suffixes", "for", "this", "process" ]
def all_suffixes(): """Returns a list of all recognized module suffixes for this process""" return SOURCE_SUFFIXES + BYTECODE_SUFFIXES + EXTENSION_SUFFIXES
[ "def", "all_suffixes", "(", ")", ":", "return", "SOURCE_SUFFIXES", "+", "BYTECODE_SUFFIXES", "+", "EXTENSION_SUFFIXES" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/importlib/machinery.py#L19-L21
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/_pydecimal.py
python
Decimal._round_floor
(self, prec)
Rounds down (not towards 0 if negative)
Rounds down (not towards 0 if negative)
[ "Rounds", "down", "(", "not", "towards", "0", "if", "negative", ")" ]
def _round_floor(self, prec): """Rounds down (not towards 0 if negative)""" if not self._sign: return self._round_down(prec) else: return -self._round_down(prec)
[ "def", "_round_floor", "(", "self", ",", "prec", ")", ":", "if", "not", "self", ".", "_sign", ":", "return", "self", ".", "_round_down", "(", "prec", ")", "else", ":", "return", "-", "self", ".", "_round_down", "(", "prec", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/_pydecimal.py#L1805-L1810
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py3/prompt_toolkit/renderer.py
python
Renderer.report_absolute_cursor_row
(self, row: int)
To be called when we know the absolute cursor position. (As an answer of a "Cursor Position Request" response.)
To be called when we know the absolute cursor position. (As an answer of a "Cursor Position Request" response.)
[ "To", "be", "called", "when", "we", "know", "the", "absolute", "cursor", "position", ".", "(", "As", "an", "answer", "of", "a", "Cursor", "Position", "Request", "response", ".", ")" ]
def report_absolute_cursor_row(self, row: int) -> None: """ To be called when we know the absolute cursor position. (As an answer of a "Cursor Position Request" response.) """ self.cpr_support = CPR_Support.SUPPORTED # Calculate the amount of rows from the cursor position until the # bottom of the terminal. total_rows = self.output.get_size().rows rows_below_cursor = total_rows - row + 1 # Set the minimum available height. self._min_available_height = rows_below_cursor # Pop and set waiting for CPR future. try: f = self._waiting_for_cpr_futures.popleft() except IndexError: pass # Received CPR response without having a CPR. else: f.set_result(None)
[ "def", "report_absolute_cursor_row", "(", "self", ",", "row", ":", "int", ")", "->", "None", ":", "self", ".", "cpr_support", "=", "CPR_Support", ".", "SUPPORTED", "# Calculate the amount of rows from the cursor position until the", "# bottom of the terminal.", "total_rows", "=", "self", ".", "output", ".", "get_size", "(", ")", ".", "rows", "rows_below_cursor", "=", "total_rows", "-", "row", "+", "1", "# Set the minimum available height.", "self", ".", "_min_available_height", "=", "rows_below_cursor", "# Pop and set waiting for CPR future.", "try", ":", "f", "=", "self", ".", "_waiting_for_cpr_futures", ".", "popleft", "(", ")", "except", "IndexError", ":", "pass", "# Received CPR response without having a CPR.", "else", ":", "f", ".", "set_result", "(", "None", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/renderer.py#L522-L543
Kitware/ParaView
f760af9124ff4634b23ebbeab95a4f56e0261955
Wrapping/Python/paraview/simple.py
python
GetParaViewVersion
()
return paraview._version(servermanager.vtkSMProxyManager.GetVersionMajor(), servermanager.vtkSMProxyManager.GetVersionMinor())
Returns the version of the ParaView build
Returns the version of the ParaView build
[ "Returns", "the", "version", "of", "the", "ParaView", "build" ]
def GetParaViewVersion(): """Returns the version of the ParaView build""" return paraview._version(servermanager.vtkSMProxyManager.GetVersionMajor(), servermanager.vtkSMProxyManager.GetVersionMinor())
[ "def", "GetParaViewVersion", "(", ")", ":", "return", "paraview", ".", "_version", "(", "servermanager", ".", "vtkSMProxyManager", ".", "GetVersionMajor", "(", ")", ",", "servermanager", ".", "vtkSMProxyManager", ".", "GetVersionMinor", "(", ")", ")" ]
https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/Wrapping/Python/paraview/simple.py#L56-L59
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Code/Tools/waf-1.7.13/waflib/Tools/perl.py
python
check_perl_version
(self, minver=None)
return res
Check if Perl is installed, and set the variable PERL. minver is supposed to be a tuple
Check if Perl is installed, and set the variable PERL. minver is supposed to be a tuple
[ "Check", "if", "Perl", "is", "installed", "and", "set", "the", "variable", "PERL", ".", "minver", "is", "supposed", "to", "be", "a", "tuple" ]
def check_perl_version(self, minver=None): """ Check if Perl is installed, and set the variable PERL. minver is supposed to be a tuple """ res = True if minver: cver = '.'.join(map(str,minver)) else: cver = '' self.start_msg('Checking for minimum perl version %s' % cver) perl = getattr(Options.options, 'perlbinary', None) if not perl: perl = self.find_program('perl', var='PERL') if not perl: self.end_msg("Perl not found", color="YELLOW") return False self.env['PERL'] = perl version = self.cmd_and_log([perl, "-e", 'printf \"%vd\", $^V']) if not version: res = False version = "Unknown" elif not minver is None: ver = tuple(map(int, version.split("."))) if ver < minver: res = False self.end_msg(version, color=res and "GREEN" or "YELLOW") return res
[ "def", "check_perl_version", "(", "self", ",", "minver", "=", "None", ")", ":", "res", "=", "True", "if", "minver", ":", "cver", "=", "'.'", ".", "join", "(", "map", "(", "str", ",", "minver", ")", ")", "else", ":", "cver", "=", "''", "self", ".", "start_msg", "(", "'Checking for minimum perl version %s'", "%", "cver", ")", "perl", "=", "getattr", "(", "Options", ".", "options", ",", "'perlbinary'", ",", "None", ")", "if", "not", "perl", ":", "perl", "=", "self", ".", "find_program", "(", "'perl'", ",", "var", "=", "'PERL'", ")", "if", "not", "perl", ":", "self", ".", "end_msg", "(", "\"Perl not found\"", ",", "color", "=", "\"YELLOW\"", ")", "return", "False", "self", ".", "env", "[", "'PERL'", "]", "=", "perl", "version", "=", "self", ".", "cmd_and_log", "(", "[", "perl", ",", "\"-e\"", ",", "'printf \\\"%vd\\\", $^V'", "]", ")", "if", "not", "version", ":", "res", "=", "False", "version", "=", "\"Unknown\"", "elif", "not", "minver", "is", "None", ":", "ver", "=", "tuple", "(", "map", "(", "int", ",", "version", ".", "split", "(", "\".\"", ")", ")", ")", "if", "ver", "<", "minver", ":", "res", "=", "False", "self", ".", "end_msg", "(", "version", ",", "color", "=", "res", "and", "\"GREEN\"", "or", "\"YELLOW\"", ")", "return", "res" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/Tools/perl.py#L60-L95
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/_backport/tarfile.py
python
TarFile.list
(self, verbose=True)
Print a table of contents to sys.stdout. If `verbose' is False, only the names of the members are printed. If it is True, an `ls -l'-like output is produced.
Print a table of contents to sys.stdout. If `verbose' is False, only the names of the members are printed. If it is True, an `ls -l'-like output is produced.
[ "Print", "a", "table", "of", "contents", "to", "sys", ".", "stdout", ".", "If", "verbose", "is", "False", "only", "the", "names", "of", "the", "members", "are", "printed", ".", "If", "it", "is", "True", "an", "ls", "-", "l", "-", "like", "output", "is", "produced", "." ]
def list(self, verbose=True): """Print a table of contents to sys.stdout. If `verbose' is False, only the names of the members are printed. If it is True, an `ls -l'-like output is produced. """ self._check() for tarinfo in self: if verbose: print(filemode(tarinfo.mode), end=' ') print("%s/%s" % (tarinfo.uname or tarinfo.uid, tarinfo.gname or tarinfo.gid), end=' ') if tarinfo.ischr() or tarinfo.isblk(): print("%10s" % ("%d,%d" \ % (tarinfo.devmajor, tarinfo.devminor)), end=' ') else: print("%10d" % tarinfo.size, end=' ') print("%d-%02d-%02d %02d:%02d:%02d" \ % time.localtime(tarinfo.mtime)[:6], end=' ') print(tarinfo.name + ("/" if tarinfo.isdir() else ""), end=' ') if verbose: if tarinfo.issym(): print("->", tarinfo.linkname, end=' ') if tarinfo.islnk(): print("link to", tarinfo.linkname, end=' ') print()
[ "def", "list", "(", "self", ",", "verbose", "=", "True", ")", ":", "self", ".", "_check", "(", ")", "for", "tarinfo", "in", "self", ":", "if", "verbose", ":", "print", "(", "filemode", "(", "tarinfo", ".", "mode", ")", ",", "end", "=", "' '", ")", "print", "(", "\"%s/%s\"", "%", "(", "tarinfo", ".", "uname", "or", "tarinfo", ".", "uid", ",", "tarinfo", ".", "gname", "or", "tarinfo", ".", "gid", ")", ",", "end", "=", "' '", ")", "if", "tarinfo", ".", "ischr", "(", ")", "or", "tarinfo", ".", "isblk", "(", ")", ":", "print", "(", "\"%10s\"", "%", "(", "\"%d,%d\"", "%", "(", "tarinfo", ".", "devmajor", ",", "tarinfo", ".", "devminor", ")", ")", ",", "end", "=", "' '", ")", "else", ":", "print", "(", "\"%10d\"", "%", "tarinfo", ".", "size", ",", "end", "=", "' '", ")", "print", "(", "\"%d-%02d-%02d %02d:%02d:%02d\"", "%", "time", ".", "localtime", "(", "tarinfo", ".", "mtime", ")", "[", ":", "6", "]", ",", "end", "=", "' '", ")", "print", "(", "tarinfo", ".", "name", "+", "(", "\"/\"", "if", "tarinfo", ".", "isdir", "(", ")", "else", "\"\"", ")", ",", "end", "=", "' '", ")", "if", "verbose", ":", "if", "tarinfo", ".", "issym", "(", ")", ":", "print", "(", "\"->\"", ",", "tarinfo", ".", "linkname", ",", "end", "=", "' '", ")", "if", "tarinfo", ".", "islnk", "(", ")", ":", "print", "(", "\"link to\"", ",", "tarinfo", ".", "linkname", ",", "end", "=", "' '", ")", "print", "(", ")" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/_backport/tarfile.py#L2009-L2036
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/protobuf/python/mox.py
python
IgnoreArg.equals
(self, unused_rhs)
return True
Ignores arguments and returns True. Args: unused_rhs: any python object Returns: always returns True
Ignores arguments and returns True.
[ "Ignores", "arguments", "and", "returns", "True", "." ]
def equals(self, unused_rhs): """Ignores arguments and returns True. Args: unused_rhs: any python object Returns: always returns True """ return True
[ "def", "equals", "(", "self", ",", "unused_rhs", ")", ":", "return", "True" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/protobuf/python/mox.py#L1166-L1176
clementine-player/Clementine
111379dfd027802b59125829fcf87e3e1d0ad73b
dist/cpplint.py
python
CheckForNonConstReference
(filename, clean_lines, linenum, nesting_state, error)
Check for non-const references. Separate from CheckLanguage since it scans backwards from current line, instead of scanning forward. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found.
Check for non-const references.
[ "Check", "for", "non", "-", "const", "references", "." ]
def CheckForNonConstReference(filename, clean_lines, linenum, nesting_state, error): """Check for non-const references. Separate from CheckLanguage since it scans backwards from current line, instead of scanning forward. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ # Do nothing if there is no '&' on current line. line = clean_lines.elided[linenum] if '&' not in line: return # If a function is inherited, current function doesn't have much of # a choice, so any non-const references should not be blamed on # derived function. if IsDerivedFunction(clean_lines, linenum): return # Long type names may be broken across multiple lines, usually in one # of these forms: # LongType # ::LongTypeContinued &identifier # LongType:: # LongTypeContinued &identifier # LongType< # ...>::LongTypeContinued &identifier # # If we detected a type split across two lines, join the previous # line to current line so that we can match const references # accordingly. # # Note that this only scans back one line, since scanning back # arbitrary number of lines would be expensive. If you have a type # that spans more than 2 lines, please use a typedef. if linenum > 1: previous = None if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line): # previous_line\n + ::current_line previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$', clean_lines.elided[linenum - 1]) elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line): # previous_line::\n + current_line previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$', clean_lines.elided[linenum - 1]) if previous: line = previous.group(1) + line.lstrip() else: # Check for templated parameter that is split across multiple lines endpos = line.rfind('>') if endpos > -1: (_, startline, startpos) = ReverseCloseExpression( clean_lines, linenum, endpos) if startpos > -1 and startline < linenum: # Found the matching < on an earlier line, collect all # pieces up to current line. line = '' for i in xrange(startline, linenum + 1): line += clean_lines.elided[i].strip() # Check for non-const references in function parameters. A single '&' may # found in the following places: # inside expression: binary & for bitwise AND # inside expression: unary & for taking the address of something # inside declarators: reference parameter # We will exclude the first two cases by checking that we are not inside a # function body, including one that was just introduced by a trailing '{'. # TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare]. if (nesting_state.previous_stack_top and not (isinstance(nesting_state.previous_stack_top, _ClassInfo) or isinstance(nesting_state.previous_stack_top, _NamespaceInfo))): # Not at toplevel, not within a class, and not within a namespace return # Avoid initializer lists. We only need to scan back from the # current line for something that starts with ':'. # # We don't need to check the current line, since the '&' would # appear inside the second set of parentheses on the current line as # opposed to the first set. if linenum > 0: for i in xrange(linenum - 1, max(0, linenum - 10), -1): previous_line = clean_lines.elided[i] if not Search(r'[),]\s*$', previous_line): break if Match(r'^\s*:\s+\S', previous_line): return # Avoid preprocessors if Search(r'\\\s*$', line): return # Avoid constructor initializer lists if IsInitializerList(clean_lines, linenum): return # We allow non-const references in a few standard places, like functions # called "swap()" or iostream operators like "<<" or ">>". Do not check # those function parameters. # # We also accept & in static_assert, which looks like a function but # it's actually a declaration expression. whitelisted_functions = (r'(?:[sS]wap(?:<\w:+>)?|' r'operator\s*[<>][<>]|' r'static_assert|COMPILE_ASSERT' r')\s*\(') if Search(whitelisted_functions, line): return elif not Search(r'\S+\([^)]*$', line): # Don't see a whitelisted function on this line. Actually we # didn't see any function name on this line, so this is likely a # multi-line parameter list. Try a bit harder to catch this case. for i in xrange(2): if (linenum > i and Search(whitelisted_functions, clean_lines.elided[linenum - i - 1])): return decls = ReplaceAll(r'{[^}]*}', ' ', line) # exclude function body for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls): if not Match(_RE_PATTERN_CONST_REF_PARAM, parameter): error(filename, linenum, 'runtime/references', 2, 'Is this a non-const reference? ' 'If so, make const or use a pointer: ' + ReplaceAll(' *<', '<', parameter))
[ "def", "CheckForNonConstReference", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "nesting_state", ",", "error", ")", ":", "# Do nothing if there is no '&' on current line.", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "'&'", "not", "in", "line", ":", "return", "# If a function is inherited, current function doesn't have much of", "# a choice, so any non-const references should not be blamed on", "# derived function.", "if", "IsDerivedFunction", "(", "clean_lines", ",", "linenum", ")", ":", "return", "# Long type names may be broken across multiple lines, usually in one", "# of these forms:", "# LongType", "# ::LongTypeContinued &identifier", "# LongType::", "# LongTypeContinued &identifier", "# LongType<", "# ...>::LongTypeContinued &identifier", "#", "# If we detected a type split across two lines, join the previous", "# line to current line so that we can match const references", "# accordingly.", "#", "# Note that this only scans back one line, since scanning back", "# arbitrary number of lines would be expensive. If you have a type", "# that spans more than 2 lines, please use a typedef.", "if", "linenum", ">", "1", ":", "previous", "=", "None", "if", "Match", "(", "r'\\s*::(?:[\\w<>]|::)+\\s*&\\s*\\S'", ",", "line", ")", ":", "# previous_line\\n + ::current_line", "previous", "=", "Search", "(", "r'\\b((?:const\\s*)?(?:[\\w<>]|::)+[\\w<>])\\s*$'", ",", "clean_lines", ".", "elided", "[", "linenum", "-", "1", "]", ")", "elif", "Match", "(", "r'\\s*[a-zA-Z_]([\\w<>]|::)+\\s*&\\s*\\S'", ",", "line", ")", ":", "# previous_line::\\n + current_line", "previous", "=", "Search", "(", "r'\\b((?:const\\s*)?(?:[\\w<>]|::)+::)\\s*$'", ",", "clean_lines", ".", "elided", "[", "linenum", "-", "1", "]", ")", "if", "previous", ":", "line", "=", "previous", ".", "group", "(", "1", ")", "+", "line", ".", "lstrip", "(", ")", "else", ":", "# Check for templated parameter that is split across multiple lines", "endpos", "=", "line", ".", "rfind", "(", "'>'", ")", "if", "endpos", ">", "-", "1", ":", "(", "_", ",", "startline", ",", "startpos", ")", "=", "ReverseCloseExpression", "(", "clean_lines", ",", "linenum", ",", "endpos", ")", "if", "startpos", ">", "-", "1", "and", "startline", "<", "linenum", ":", "# Found the matching < on an earlier line, collect all", "# pieces up to current line.", "line", "=", "''", "for", "i", "in", "xrange", "(", "startline", ",", "linenum", "+", "1", ")", ":", "line", "+=", "clean_lines", ".", "elided", "[", "i", "]", ".", "strip", "(", ")", "# Check for non-const references in function parameters. A single '&' may", "# found in the following places:", "# inside expression: binary & for bitwise AND", "# inside expression: unary & for taking the address of something", "# inside declarators: reference parameter", "# We will exclude the first two cases by checking that we are not inside a", "# function body, including one that was just introduced by a trailing '{'.", "# TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare].", "if", "(", "nesting_state", ".", "previous_stack_top", "and", "not", "(", "isinstance", "(", "nesting_state", ".", "previous_stack_top", ",", "_ClassInfo", ")", "or", "isinstance", "(", "nesting_state", ".", "previous_stack_top", ",", "_NamespaceInfo", ")", ")", ")", ":", "# Not at toplevel, not within a class, and not within a namespace", "return", "# Avoid initializer lists. We only need to scan back from the", "# current line for something that starts with ':'.", "#", "# We don't need to check the current line, since the '&' would", "# appear inside the second set of parentheses on the current line as", "# opposed to the first set.", "if", "linenum", ">", "0", ":", "for", "i", "in", "xrange", "(", "linenum", "-", "1", ",", "max", "(", "0", ",", "linenum", "-", "10", ")", ",", "-", "1", ")", ":", "previous_line", "=", "clean_lines", ".", "elided", "[", "i", "]", "if", "not", "Search", "(", "r'[),]\\s*$'", ",", "previous_line", ")", ":", "break", "if", "Match", "(", "r'^\\s*:\\s+\\S'", ",", "previous_line", ")", ":", "return", "# Avoid preprocessors", "if", "Search", "(", "r'\\\\\\s*$'", ",", "line", ")", ":", "return", "# Avoid constructor initializer lists", "if", "IsInitializerList", "(", "clean_lines", ",", "linenum", ")", ":", "return", "# We allow non-const references in a few standard places, like functions", "# called \"swap()\" or iostream operators like \"<<\" or \">>\". Do not check", "# those function parameters.", "#", "# We also accept & in static_assert, which looks like a function but", "# it's actually a declaration expression.", "whitelisted_functions", "=", "(", "r'(?:[sS]wap(?:<\\w:+>)?|'", "r'operator\\s*[<>][<>]|'", "r'static_assert|COMPILE_ASSERT'", "r')\\s*\\('", ")", "if", "Search", "(", "whitelisted_functions", ",", "line", ")", ":", "return", "elif", "not", "Search", "(", "r'\\S+\\([^)]*$'", ",", "line", ")", ":", "# Don't see a whitelisted function on this line. Actually we", "# didn't see any function name on this line, so this is likely a", "# multi-line parameter list. Try a bit harder to catch this case.", "for", "i", "in", "xrange", "(", "2", ")", ":", "if", "(", "linenum", ">", "i", "and", "Search", "(", "whitelisted_functions", ",", "clean_lines", ".", "elided", "[", "linenum", "-", "i", "-", "1", "]", ")", ")", ":", "return", "decls", "=", "ReplaceAll", "(", "r'{[^}]*}'", ",", "' '", ",", "line", ")", "# exclude function body", "for", "parameter", "in", "re", ".", "findall", "(", "_RE_PATTERN_REF_PARAM", ",", "decls", ")", ":", "if", "not", "Match", "(", "_RE_PATTERN_CONST_REF_PARAM", ",", "parameter", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/references'", ",", "2", ",", "'Is this a non-const reference? '", "'If so, make const or use a pointer: '", "+", "ReplaceAll", "(", "' *<'", ",", "'<'", ",", "parameter", ")", ")" ]
https://github.com/clementine-player/Clementine/blob/111379dfd027802b59125829fcf87e3e1d0ad73b/dist/cpplint.py#L4935-L5065
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/ops/math_grad.py
python
_MaxGrad
(op, grad)
return _MinOrMaxGrad(op, grad)
Gradient for Max.
Gradient for Max.
[ "Gradient", "for", "Max", "." ]
def _MaxGrad(op, grad): """Gradient for Max.""" return _MinOrMaxGrad(op, grad)
[ "def", "_MaxGrad", "(", "op", ",", "grad", ")", ":", "return", "_MinOrMaxGrad", "(", "op", ",", "grad", ")" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/math_grad.py#L83-L85
reverbrain/elliptics
4b4f9b8094d7616c1ec50eb8605edb059b9f228e
bindings/python/src/route.py
python
RouteList.get_address_backend_ranges
(self, address, backend_id)
return ranges
Returns id ranges which belong to specified @backend_id at @address\n ranges = routes.get_address_backend_ranges( Address.from_host_port_family('host.com:1025:2', 0))
Returns id ranges which belong to specified
[ "Returns", "id", "ranges", "which", "belong", "to", "specified" ]
def get_address_backend_ranges(self, address, backend_id): """ Returns id ranges which belong to specified @backend_id at @address\n ranges = routes.get_address_backend_ranges( Address.from_host_port_family('host.com:1025:2', 0)) """ ranges = [] group = self.get_address_backend_group(address, backend_id) id = None for route in self.filter_by_groups([group]): if (route.address, route.backend_id) == (address, backend_id): if id is None: id = route.id elif id: ranges.append((id, route.id)) id = None if id: ranges.append((id, Id([255] * 64, id.group_id))) return ranges
[ "def", "get_address_backend_ranges", "(", "self", ",", "address", ",", "backend_id", ")", ":", "ranges", "=", "[", "]", "group", "=", "self", ".", "get_address_backend_group", "(", "address", ",", "backend_id", ")", "id", "=", "None", "for", "route", "in", "self", ".", "filter_by_groups", "(", "[", "group", "]", ")", ":", "if", "(", "route", ".", "address", ",", "route", ".", "backend_id", ")", "==", "(", "address", ",", "backend_id", ")", ":", "if", "id", "is", "None", ":", "id", "=", "route", ".", "id", "elif", "id", ":", "ranges", ".", "append", "(", "(", "id", ",", "route", ".", "id", ")", ")", "id", "=", "None", "if", "id", ":", "ranges", ".", "append", "(", "(", "id", ",", "Id", "(", "[", "255", "]", "*", "64", ",", "id", ".", "group_id", ")", ")", ")", "return", "ranges" ]
https://github.com/reverbrain/elliptics/blob/4b4f9b8094d7616c1ec50eb8605edb059b9f228e/bindings/python/src/route.py#L364-L382
xhzdeng/crpn
a5aef0f80dbe486103123f740c634fb01e6cc9a1
caffe-fast-rcnn/tools/extra/parse_log.py
python
save_csv_files
(logfile_path, output_dir, train_dict_list, test_dict_list, delimiter=',', verbose=False)
Save CSV files to output_dir If the input log file is, e.g., caffe.INFO, the names will be caffe.INFO.train and caffe.INFO.test
Save CSV files to output_dir
[ "Save", "CSV", "files", "to", "output_dir" ]
def save_csv_files(logfile_path, output_dir, train_dict_list, test_dict_list, delimiter=',', verbose=False): """Save CSV files to output_dir If the input log file is, e.g., caffe.INFO, the names will be caffe.INFO.train and caffe.INFO.test """ log_basename = os.path.basename(logfile_path) train_filename = os.path.join(output_dir, log_basename + '.train') write_csv(train_filename, train_dict_list, delimiter, verbose) test_filename = os.path.join(output_dir, log_basename + '.test') write_csv(test_filename, test_dict_list, delimiter, verbose)
[ "def", "save_csv_files", "(", "logfile_path", ",", "output_dir", ",", "train_dict_list", ",", "test_dict_list", ",", "delimiter", "=", "','", ",", "verbose", "=", "False", ")", ":", "log_basename", "=", "os", ".", "path", ".", "basename", "(", "logfile_path", ")", "train_filename", "=", "os", ".", "path", ".", "join", "(", "output_dir", ",", "log_basename", "+", "'.train'", ")", "write_csv", "(", "train_filename", ",", "train_dict_list", ",", "delimiter", ",", "verbose", ")", "test_filename", "=", "os", ".", "path", ".", "join", "(", "output_dir", ",", "log_basename", "+", "'.test'", ")", "write_csv", "(", "test_filename", ",", "test_dict_list", ",", "delimiter", ",", "verbose", ")" ]
https://github.com/xhzdeng/crpn/blob/a5aef0f80dbe486103123f740c634fb01e6cc9a1/caffe-fast-rcnn/tools/extra/parse_log.py#L141-L154
aimerykong/Low-Rank-Bilinear-Pooling
487eb2c857fd9c95357a5166b0c15ad0fe135b28
caffe-20160312/scripts/cpp_lint.py
python
CheckSpacingForFunctionCall
(filename, line, linenum, error)
Checks for the correctness of various spacing around function calls. Args: filename: The name of the current file. line: The text of the line to check. linenum: The number of the line to check. error: The function to call with any errors found.
Checks for the correctness of various spacing around function calls.
[ "Checks", "for", "the", "correctness", "of", "various", "spacing", "around", "function", "calls", "." ]
def CheckSpacingForFunctionCall(filename, line, linenum, error): """Checks for the correctness of various spacing around function calls. Args: filename: The name of the current file. line: The text of the line to check. linenum: The number of the line to check. error: The function to call with any errors found. """ # Since function calls often occur inside if/for/while/switch # expressions - which have their own, more liberal conventions - we # first see if we should be looking inside such an expression for a # function call, to which we can apply more strict standards. fncall = line # if there's no control flow construct, look at whole line for pattern in (r'\bif\s*\((.*)\)\s*{', r'\bfor\s*\((.*)\)\s*{', r'\bwhile\s*\((.*)\)\s*[{;]', r'\bswitch\s*\((.*)\)\s*{'): match = Search(pattern, line) if match: fncall = match.group(1) # look inside the parens for function calls break # Except in if/for/while/switch, there should never be space # immediately inside parens (eg "f( 3, 4 )"). We make an exception # for nested parens ( (a+b) + c ). Likewise, there should never be # a space before a ( when it's a function argument. I assume it's a # function argument when the char before the whitespace is legal in # a function name (alnum + _) and we're not starting a macro. Also ignore # pointers and references to arrays and functions coz they're too tricky: # we use a very simple way to recognize these: # " (something)(maybe-something)" or # " (something)(maybe-something," or # " (something)[something]" # Note that we assume the contents of [] to be short enough that # they'll never need to wrap. if ( # Ignore control structures. not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b', fncall) and # Ignore pointers/references to functions. not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and # Ignore pointers/references to arrays. not Search(r' \([^)]+\)\[[^\]]+\]', fncall)): if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call error(filename, linenum, 'whitespace/parens', 4, 'Extra space after ( in function call') elif Search(r'\(\s+(?!(\s*\\)|\()', fncall): error(filename, linenum, 'whitespace/parens', 2, 'Extra space after (') if (Search(r'\w\s+\(', fncall) and not Search(r'#\s*define|typedef', fncall) and not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall)): error(filename, linenum, 'whitespace/parens', 4, 'Extra space before ( in function call') # If the ) is followed only by a newline or a { + newline, assume it's # part of a control statement (if/while/etc), and don't complain if Search(r'[^)]\s+\)\s*[^{\s]', fncall): # If the closing parenthesis is preceded by only whitespaces, # try to give a more descriptive error message. if Search(r'^\s+\)', fncall): error(filename, linenum, 'whitespace/parens', 2, 'Closing ) should be moved to the previous line') else: error(filename, linenum, 'whitespace/parens', 2, 'Extra space before )')
[ "def", "CheckSpacingForFunctionCall", "(", "filename", ",", "line", ",", "linenum", ",", "error", ")", ":", "# Since function calls often occur inside if/for/while/switch", "# expressions - which have their own, more liberal conventions - we", "# first see if we should be looking inside such an expression for a", "# function call, to which we can apply more strict standards.", "fncall", "=", "line", "# if there's no control flow construct, look at whole line", "for", "pattern", "in", "(", "r'\\bif\\s*\\((.*)\\)\\s*{'", ",", "r'\\bfor\\s*\\((.*)\\)\\s*{'", ",", "r'\\bwhile\\s*\\((.*)\\)\\s*[{;]'", ",", "r'\\bswitch\\s*\\((.*)\\)\\s*{'", ")", ":", "match", "=", "Search", "(", "pattern", ",", "line", ")", "if", "match", ":", "fncall", "=", "match", ".", "group", "(", "1", ")", "# look inside the parens for function calls", "break", "# Except in if/for/while/switch, there should never be space", "# immediately inside parens (eg \"f( 3, 4 )\"). We make an exception", "# for nested parens ( (a+b) + c ). Likewise, there should never be", "# a space before a ( when it's a function argument. I assume it's a", "# function argument when the char before the whitespace is legal in", "# a function name (alnum + _) and we're not starting a macro. Also ignore", "# pointers and references to arrays and functions coz they're too tricky:", "# we use a very simple way to recognize these:", "# \" (something)(maybe-something)\" or", "# \" (something)(maybe-something,\" or", "# \" (something)[something]\"", "# Note that we assume the contents of [] to be short enough that", "# they'll never need to wrap.", "if", "(", "# Ignore control structures.", "not", "Search", "(", "r'\\b(if|for|while|switch|return|new|delete|catch|sizeof)\\b'", ",", "fncall", ")", "and", "# Ignore pointers/references to functions.", "not", "Search", "(", "r' \\([^)]+\\)\\([^)]*(\\)|,$)'", ",", "fncall", ")", "and", "# Ignore pointers/references to arrays.", "not", "Search", "(", "r' \\([^)]+\\)\\[[^\\]]+\\]'", ",", "fncall", ")", ")", ":", "if", "Search", "(", "r'\\w\\s*\\(\\s(?!\\s*\\\\$)'", ",", "fncall", ")", ":", "# a ( used for a fn call", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "4", ",", "'Extra space after ( in function call'", ")", "elif", "Search", "(", "r'\\(\\s+(?!(\\s*\\\\)|\\()'", ",", "fncall", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "2", ",", "'Extra space after ('", ")", "if", "(", "Search", "(", "r'\\w\\s+\\('", ",", "fncall", ")", "and", "not", "Search", "(", "r'#\\s*define|typedef'", ",", "fncall", ")", "and", "not", "Search", "(", "r'\\w\\s+\\((\\w+::)*\\*\\w+\\)\\('", ",", "fncall", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "4", ",", "'Extra space before ( in function call'", ")", "# If the ) is followed only by a newline or a { + newline, assume it's", "# part of a control statement (if/while/etc), and don't complain", "if", "Search", "(", "r'[^)]\\s+\\)\\s*[^{\\s]'", ",", "fncall", ")", ":", "# If the closing parenthesis is preceded by only whitespaces,", "# try to give a more descriptive error message.", "if", "Search", "(", "r'^\\s+\\)'", ",", "fncall", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "2", ",", "'Closing ) should be moved to the previous line'", ")", "else", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "2", ",", "'Extra space before )'", ")" ]
https://github.com/aimerykong/Low-Rank-Bilinear-Pooling/blob/487eb2c857fd9c95357a5166b0c15ad0fe135b28/caffe-20160312/scripts/cpp_lint.py#L2301-L2366
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/logging/__init__.py
python
setLoggerClass
(klass)
Set the class to be used when instantiating a logger. The class should define __init__() such that only a name argument is required, and the __init__() should call Logger.__init__()
Set the class to be used when instantiating a logger. The class should define __init__() such that only a name argument is required, and the __init__() should call Logger.__init__()
[ "Set", "the", "class", "to", "be", "used", "when", "instantiating", "a", "logger", ".", "The", "class", "should", "define", "__init__", "()", "such", "that", "only", "a", "name", "argument", "is", "required", "and", "the", "__init__", "()", "should", "call", "Logger", ".", "__init__", "()" ]
def setLoggerClass(klass): """ Set the class to be used when instantiating a logger. The class should define __init__() such that only a name argument is required, and the __init__() should call Logger.__init__() """ if klass != Logger: if not issubclass(klass, Logger): raise TypeError("logger not derived from logging.Logger: " + klass.__name__) global _loggerClass _loggerClass = klass
[ "def", "setLoggerClass", "(", "klass", ")", ":", "if", "klass", "!=", "Logger", ":", "if", "not", "issubclass", "(", "klass", ",", "Logger", ")", ":", "raise", "TypeError", "(", "\"logger not derived from logging.Logger: \"", "+", "klass", ".", "__name__", ")", "global", "_loggerClass", "_loggerClass", "=", "klass" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/logging/__init__.py#L972-L983
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/models.py
python
PreparedRequest.prepare_method
(self, method)
Prepares the given HTTP method.
Prepares the given HTTP method.
[ "Prepares", "the", "given", "HTTP", "method", "." ]
def prepare_method(self, method): """Prepares the given HTTP method.""" self.method = method if self.method is not None: self.method = to_native_string(self.method.upper())
[ "def", "prepare_method", "(", "self", ",", "method", ")", ":", "self", ".", "method", "=", "method", "if", "self", ".", "method", "is", "not", "None", ":", "self", ".", "method", "=", "to_native_string", "(", "self", ".", "method", ".", "upper", "(", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/models.py#L340-L344
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/dummy_thread.py
python
interrupt_main
()
Set _interrupt flag to True to have start_new_thread raise KeyboardInterrupt upon exiting.
Set _interrupt flag to True to have start_new_thread raise KeyboardInterrupt upon exiting.
[ "Set", "_interrupt", "flag", "to", "True", "to", "have", "start_new_thread", "raise", "KeyboardInterrupt", "upon", "exiting", "." ]
def interrupt_main(): """Set _interrupt flag to True to have start_new_thread raise KeyboardInterrupt upon exiting.""" if _main: raise KeyboardInterrupt else: global _interrupt _interrupt = True
[ "def", "interrupt_main", "(", ")", ":", "if", "_main", ":", "raise", "KeyboardInterrupt", "else", ":", "global", "_interrupt", "_interrupt", "=", "True" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/dummy_thread.py#L138-L145
bitconch/bitconch-core
5537f3215b3e3b76f6720d6f908676a6c34bc5db
deploy-morgan.py
python
prnt_error
(in_text)
Print an error message
Print an error message
[ "Print", "an", "error", "message" ]
def prnt_error(in_text): """ Print an error message """ print(Fore.RED + "[~]"+in_text) print(Style.RESET_ALL)
[ "def", "prnt_error", "(", "in_text", ")", ":", "print", "(", "Fore", ".", "RED", "+", "\"[~]\"", "+", "in_text", ")", "print", "(", "Style", ".", "RESET_ALL", ")" ]
https://github.com/bitconch/bitconch-core/blob/5537f3215b3e3b76f6720d6f908676a6c34bc5db/deploy-morgan.py#L68-L73
cmu-db/noisepage
79276e68fe83322f1249e8a8be96bd63c583ae56
build-support/asan_symbolize.py
python
DarwinSymbolizer.symbolize
(self, addr, binary, offset)
Overrides Symbolizer.symbolize.
Overrides Symbolizer.symbolize.
[ "Overrides", "Symbolizer", ".", "symbolize", "." ]
def symbolize(self, addr, binary, offset): """Overrides Symbolizer.symbolize.""" if self.binary != binary: return None self.open_atos() self.write_addr_to_pipe(offset) self.pipe.stdin.close() atos_line = self.pipe.stdout.readline().rstrip() # A well-formed atos response looks like this: # foo(type1, type2) (in object.name) (filename.cc:80) match = re.match('^(.*) \(in (.*)\) \((.*:\d*)\)$', atos_line) if DEBUG: print('atos_line: {0}'.format(atos_line)) if match: function_name = match.group(1) function_name = re.sub('\(.*?\)', '', function_name) file_name = fix_filename(match.group(3)) return ['%s in %s %s' % (addr, function_name, file_name)] else: return ['%s in %s' % (addr, atos_line)]
[ "def", "symbolize", "(", "self", ",", "addr", ",", "binary", ",", "offset", ")", ":", "if", "self", ".", "binary", "!=", "binary", ":", "return", "None", "self", ".", "open_atos", "(", ")", "self", ".", "write_addr_to_pipe", "(", "offset", ")", "self", ".", "pipe", ".", "stdin", ".", "close", "(", ")", "atos_line", "=", "self", ".", "pipe", ".", "stdout", ".", "readline", "(", ")", ".", "rstrip", "(", ")", "# A well-formed atos response looks like this:", "# foo(type1, type2) (in object.name) (filename.cc:80)", "match", "=", "re", ".", "match", "(", "'^(.*) \\(in (.*)\\) \\((.*:\\d*)\\)$'", ",", "atos_line", ")", "if", "DEBUG", ":", "print", "(", "'atos_line: {0}'", ".", "format", "(", "atos_line", ")", ")", "if", "match", ":", "function_name", "=", "match", ".", "group", "(", "1", ")", "function_name", "=", "re", ".", "sub", "(", "'\\(.*?\\)'", ",", "''", ",", "function_name", ")", "file_name", "=", "fix_filename", "(", "match", ".", "group", "(", "3", ")", ")", "return", "[", "'%s in %s %s'", "%", "(", "addr", ",", "function_name", ",", "file_name", ")", "]", "else", ":", "return", "[", "'%s in %s'", "%", "(", "addr", ",", "atos_line", ")", "]" ]
https://github.com/cmu-db/noisepage/blob/79276e68fe83322f1249e8a8be96bd63c583ae56/build-support/asan_symbolize.py#L162-L181
apache/madlib
be297fe6beada0640f93317e8948834032718e32
src/madpack/upgrade_util.py
python
ViewDependency._detect_direct_view_dependency_udf_uda
(self)
@brief Detect direct view dependencies on MADlib UDFs/UDAs
[]
def _detect_direct_view_dependency_udf_uda(self): """ @brief Detect direct view dependencies on MADlib UDFs/UDAs """ proisagg_wrapper = "p.proisagg" if self._portid == 'postgres' and self._dbver > 11: proisagg_wrapper = "p.prokind = 'a'" rows = self._run_sql(""" SELECT view, nsp.nspname AS schema, procname, procoid, proisagg FROM pg_namespace nsp, ( SELECT c.relname AS view, c.relnamespace AS namespace, p.proname As procname, p.oid AS procoid, {proisagg_wrapper} AS proisagg FROM pg_class AS c, pg_rewrite AS rw, pg_depend AS d, pg_proc AS p WHERE c.oid = rw.ev_class AND rw.oid = d.objid AND d.classid = 'pg_rewrite'::regclass AND d.refclassid = 'pg_proc'::regclass AND d.refobjid = p.oid AND p.pronamespace = {schema_madlib_oid} ) t1 WHERE t1.namespace = nsp.oid """.format(schema_madlib_oid=self._schema_oid, proisagg_wrapper=proisagg_wrapper)) self._view2proc = defaultdict(list) for row in rows: key = (row['schema'], row['view']) self._view2proc[key].append( (row['procname'], row['procoid'], 'UDA' if row['proisagg'] == 't' else 'UDF'))
[ "def", "_detect_direct_view_dependency_udf_uda", "(", "self", ")", ":", "proisagg_wrapper", "=", "\"p.proisagg\"", "if", "self", ".", "_portid", "==", "'postgres'", "and", "self", ".", "_dbver", ">", "11", ":", "proisagg_wrapper", "=", "\"p.prokind = 'a'\"", "rows", "=", "self", ".", "_run_sql", "(", "\"\"\"\n SELECT\n view, nsp.nspname AS schema, procname, procoid, proisagg\n FROM\n pg_namespace nsp,\n (\n SELECT\n c.relname AS view,\n c.relnamespace AS namespace,\n p.proname As procname,\n p.oid AS procoid,\n {proisagg_wrapper} AS proisagg\n FROM\n pg_class AS c,\n pg_rewrite AS rw,\n pg_depend AS d,\n pg_proc AS p\n WHERE\n c.oid = rw.ev_class AND\n rw.oid = d.objid AND\n d.classid = 'pg_rewrite'::regclass AND\n d.refclassid = 'pg_proc'::regclass AND\n d.refobjid = p.oid AND\n p.pronamespace = {schema_madlib_oid}\n ) t1\n WHERE\n t1.namespace = nsp.oid\n \"\"\"", ".", "format", "(", "schema_madlib_oid", "=", "self", ".", "_schema_oid", ",", "proisagg_wrapper", "=", "proisagg_wrapper", ")", ")", "self", ".", "_view2proc", "=", "defaultdict", "(", "list", ")", "for", "row", "in", "rows", ":", "key", "=", "(", "row", "[", "'schema'", "]", ",", "row", "[", "'view'", "]", ")", "self", ".", "_view2proc", "[", "key", "]", ".", "append", "(", "(", "row", "[", "'procname'", "]", ",", "row", "[", "'procoid'", "]", ",", "'UDA'", "if", "row", "[", "'proisagg'", "]", "==", "'t'", "else", "'UDF'", ")", ")" ]
https://github.com/apache/madlib/blob/be297fe6beada0640f93317e8948834032718e32/src/madpack/upgrade_util.py#L493-L535
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py
python
_GenerateMSBuildFiltersFile
(filters_path, source_files, rule_dependencies, extension_to_rule_name)
Generate the filters file. This file is used by Visual Studio to organize the presentation of source files into folders. Arguments: filters_path: The path of the file to be created. source_files: The hierarchical structure of all the sources. extension_to_rule_name: A dictionary mapping file extensions to rules.
Generate the filters file.
[ "Generate", "the", "filters", "file", "." ]
def _GenerateMSBuildFiltersFile(filters_path, source_files, rule_dependencies, extension_to_rule_name): """Generate the filters file. This file is used by Visual Studio to organize the presentation of source files into folders. Arguments: filters_path: The path of the file to be created. source_files: The hierarchical structure of all the sources. extension_to_rule_name: A dictionary mapping file extensions to rules. """ filter_group = [] source_group = [] _AppendFiltersForMSBuild('', source_files, rule_dependencies, extension_to_rule_name, filter_group, source_group) if filter_group: content = ['Project', {'ToolsVersion': '4.0', 'xmlns': 'http://schemas.microsoft.com/developer/msbuild/2003' }, ['ItemGroup'] + filter_group, ['ItemGroup'] + source_group ] easy_xml.WriteXmlIfChanged(content, filters_path, pretty=True, win32=True) elif os.path.exists(filters_path): # We don't need this filter anymore. Delete the old filter file. os.unlink(filters_path)
[ "def", "_GenerateMSBuildFiltersFile", "(", "filters_path", ",", "source_files", ",", "rule_dependencies", ",", "extension_to_rule_name", ")", ":", "filter_group", "=", "[", "]", "source_group", "=", "[", "]", "_AppendFiltersForMSBuild", "(", "''", ",", "source_files", ",", "rule_dependencies", ",", "extension_to_rule_name", ",", "filter_group", ",", "source_group", ")", "if", "filter_group", ":", "content", "=", "[", "'Project'", ",", "{", "'ToolsVersion'", ":", "'4.0'", ",", "'xmlns'", ":", "'http://schemas.microsoft.com/developer/msbuild/2003'", "}", ",", "[", "'ItemGroup'", "]", "+", "filter_group", ",", "[", "'ItemGroup'", "]", "+", "source_group", "]", "easy_xml", ".", "WriteXmlIfChanged", "(", "content", ",", "filters_path", ",", "pretty", "=", "True", ",", "win32", "=", "True", ")", "elif", "os", ".", "path", ".", "exists", "(", "filters_path", ")", ":", "# We don't need this filter anymore. Delete the old filter file.", "os", ".", "unlink", "(", "filters_path", ")" ]
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py#L2021-L2048
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TFltRect.SaveXml
(self, *args)
return _snap.TFltRect_SaveXml(self, *args)
SaveXml(TFltRect self, TSOut SOut, TStr Nm) Parameters: SOut: TSOut & Nm: TStr const &
SaveXml(TFltRect self, TSOut SOut, TStr Nm)
[ "SaveXml", "(", "TFltRect", "self", "TSOut", "SOut", "TStr", "Nm", ")" ]
def SaveXml(self, *args): """ SaveXml(TFltRect self, TSOut SOut, TStr Nm) Parameters: SOut: TSOut & Nm: TStr const & """ return _snap.TFltRect_SaveXml(self, *args)
[ "def", "SaveXml", "(", "self", ",", "*", "args", ")", ":", "return", "_snap", ".", "TFltRect_SaveXml", "(", "self", ",", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L15187-L15196
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/propgrid.py
python
PropertyGridInterface.SetValidationFailureBehavior
(*args, **kwargs)
return _propgrid.PropertyGridInterface_SetValidationFailureBehavior(*args, **kwargs)
SetValidationFailureBehavior(self, int vfbFlags)
SetValidationFailureBehavior(self, int vfbFlags)
[ "SetValidationFailureBehavior", "(", "self", "int", "vfbFlags", ")" ]
def SetValidationFailureBehavior(*args, **kwargs): """SetValidationFailureBehavior(self, int vfbFlags)""" return _propgrid.PropertyGridInterface_SetValidationFailureBehavior(*args, **kwargs)
[ "def", "SetValidationFailureBehavior", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PropertyGridInterface_SetValidationFailureBehavior", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/propgrid.py#L1458-L1460
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/poplib.py
python
POP3.rset
(self)
return self._shortcmd('RSET')
Unmark all messages marked for deletion.
Unmark all messages marked for deletion.
[ "Unmark", "all", "messages", "marked", "for", "deletion", "." ]
def rset(self): """Unmark all messages marked for deletion.""" return self._shortcmd('RSET')
[ "def", "rset", "(", "self", ")", ":", "return", "self", ".", "_shortcmd", "(", "'RSET'", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/poplib.py#L272-L274
chromiumembedded/cef
80caf947f3fe2210e5344713c5281d8af9bdc295
tools/gypi_to_gn.py
python
ReplaceSubstrings
(values, search_for, replace_with)
return values
Recursively replaces substrings in a value. Replaces all substrings of the "search_for" with "repace_with" for all strings occurring in "values". This is done by recursively iterating into lists as well as the keys and values of dictionaries.
Recursively replaces substrings in a value.
[ "Recursively", "replaces", "substrings", "in", "a", "value", "." ]
def ReplaceSubstrings(values, search_for, replace_with): """Recursively replaces substrings in a value. Replaces all substrings of the "search_for" with "repace_with" for all strings occurring in "values". This is done by recursively iterating into lists as well as the keys and values of dictionaries.""" if isinstance(values, str): return values.replace(search_for, replace_with) if isinstance(values, list): return [ReplaceSubstrings(v, search_for, replace_with) for v in values] if isinstance(values, dict): # For dictionaries, do the search for both the key and values. result = {} for key, value in values.items(): new_key = ReplaceSubstrings(key, search_for, replace_with) new_value = ReplaceSubstrings(value, search_for, replace_with) result[new_key] = new_value return result # Assume everything else is unchanged. return values
[ "def", "ReplaceSubstrings", "(", "values", ",", "search_for", ",", "replace_with", ")", ":", "if", "isinstance", "(", "values", ",", "str", ")", ":", "return", "values", ".", "replace", "(", "search_for", ",", "replace_with", ")", "if", "isinstance", "(", "values", ",", "list", ")", ":", "return", "[", "ReplaceSubstrings", "(", "v", ",", "search_for", ",", "replace_with", ")", "for", "v", "in", "values", "]", "if", "isinstance", "(", "values", ",", "dict", ")", ":", "# For dictionaries, do the search for both the key and values.", "result", "=", "{", "}", "for", "key", ",", "value", "in", "values", ".", "items", "(", ")", ":", "new_key", "=", "ReplaceSubstrings", "(", "key", ",", "search_for", ",", "replace_with", ")", "new_value", "=", "ReplaceSubstrings", "(", "value", ",", "search_for", ",", "replace_with", ")", "result", "[", "new_key", "]", "=", "new_value", "return", "result", "# Assume everything else is unchanged.", "return", "values" ]
https://github.com/chromiumembedded/cef/blob/80caf947f3fe2210e5344713c5281d8af9bdc295/tools/gypi_to_gn.py#L146-L168
fasiondog/hikyuu
842751aa25283f9fdafc6f560ea262f79e67a307
hikyuu/shell/hkucmd.py
python
HKUShell.do_quit
(self, arg)
return True
Stop recording, and exit: BYE
Stop recording, and exit: BYE
[ "Stop", "recording", "and", "exit", ":", "BYE" ]
def do_quit(self, arg): 'Stop recording, and exit: BYE' print('Thank you for using hikyuu.\n') return True
[ "def", "do_quit", "(", "self", ",", "arg", ")", ":", "print", "(", "'Thank you for using hikyuu.\\n'", ")", "return", "True" ]
https://github.com/fasiondog/hikyuu/blob/842751aa25283f9fdafc6f560ea262f79e67a307/hikyuu/shell/hkucmd.py#L85-L88
microsoft/ivy
9f3c7ecc0b2383129fdd0953e10890d98d09a82d
ivy/ivy_cpp.py
python
add_expr
(code)
Adds code to the current expression context.
Adds code to the current expression context.
[ "Adds", "code", "to", "the", "current", "expression", "context", "." ]
def add_expr(code): """ Adds code to the current expression context. """ context.expr.write(code)
[ "def", "add_expr", "(", "code", ")", ":", "context", ".", "expr", ".", "write", "(", "code", ")" ]
https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_cpp.py#L133-L135
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/isapi/install.py
python
UninstallModule
(conf_module_name, params, options, log=lambda *args:None)
Remove the extension
Remove the extension
[ "Remove", "the", "extension" ]
def UninstallModule(conf_module_name, params, options, log=lambda *args:None): "Remove the extension" loader_dll = GetLoaderModuleName(conf_module_name, False) _PatchParamsModule(params, loader_dll, False) Uninstall(params, options) log(1, "Uninstallation complete.")
[ "def", "UninstallModule", "(", "conf_module_name", ",", "params", ",", "options", ",", "log", "=", "lambda", "*", "args", ":", "None", ")", ":", "loader_dll", "=", "GetLoaderModuleName", "(", "conf_module_name", ",", "False", ")", "_PatchParamsModule", "(", "params", ",", "loader_dll", ",", "False", ")", "Uninstall", "(", "params", ",", "options", ")", "log", "(", "1", ",", "\"Uninstallation complete.\"", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/isapi/install.py#L618-L623
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBValue.GetAddress
(self)
return _lldb.SBValue_GetAddress(self)
GetAddress(self) -> SBAddress
GetAddress(self) -> SBAddress
[ "GetAddress", "(", "self", ")", "-", ">", "SBAddress" ]
def GetAddress(self): """GetAddress(self) -> SBAddress""" return _lldb.SBValue_GetAddress(self)
[ "def", "GetAddress", "(", "self", ")", ":", "return", "_lldb", ".", "SBValue_GetAddress", "(", "self", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L12211-L12213
fifengine/fifengine
4b62c42e85bec19893cef8e63e6855927cff2c47
engine/python/fife/extensions/pychan/widgets/widget.py
python
Widget.findChild
(self,**kwargs)
return None
Find the first contained child widgets by attribute values. Usage:: closeButton = root_widget.findChild(name='close')
Find the first contained child widgets by attribute values.
[ "Find", "the", "first", "contained", "child", "widgets", "by", "attribute", "values", "." ]
def findChild(self,**kwargs): """ Find the first contained child widgets by attribute values. Usage:: closeButton = root_widget.findChild(name='close') """ if list(kwargs.keys()) == ["name"]: return self.findChildByName(kwargs["name"]) children = self.findChildren(**kwargs) if children: return children[0] return None
[ "def", "findChild", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "list", "(", "kwargs", ".", "keys", "(", ")", ")", "==", "[", "\"name\"", "]", ":", "return", "self", ".", "findChildByName", "(", "kwargs", "[", "\"name\"", "]", ")", "children", "=", "self", ".", "findChildren", "(", "*", "*", "kwargs", ")", "if", "children", ":", "return", "children", "[", "0", "]", "return", "None" ]
https://github.com/fifengine/fifengine/blob/4b62c42e85bec19893cef8e63e6855927cff2c47/engine/python/fife/extensions/pychan/widgets/widget.py#L589-L601
openfoamtutorials/OpenFOAM_Tutorials_
29e19833aea3f6ee87ecceae3d061b050ee3ed89
InProgress/MultiElementBiWing/plot.py
python
processForceLine
(line)
return ret
Returns a dictionary of lists: ret = {time, pressureForce, viscousForce, pressureMoment, viscousMoment} (porous quantities are ignored)
Returns a dictionary of lists: ret = {time, pressureForce, viscousForce, pressureMoment, viscousMoment} (porous quantities are ignored)
[ "Returns", "a", "dictionary", "of", "lists", ":", "ret", "=", "{", "time", "pressureForce", "viscousForce", "pressureMoment", "viscousMoment", "}", "(", "porous", "quantities", "are", "ignored", ")" ]
def processForceLine(line): """ Returns a dictionary of lists: ret = {time, pressureForce, viscousForce, pressureMoment, viscousMoment} (porous quantities are ignored) """ raw = line.split() ret = {} ret['time'] = float(cleanString(raw[0])) ret['pressureForce'] = cleanList(raw[1:4]) ret['viscousForce'] = cleanList(raw[4:7]) ret['pressureMoment'] = cleanList(raw[10:14]) ret['viscousMoment'] = cleanList(raw[14:17]) return ret
[ "def", "processForceLine", "(", "line", ")", ":", "raw", "=", "line", ".", "split", "(", ")", "ret", "=", "{", "}", "ret", "[", "'time'", "]", "=", "float", "(", "cleanString", "(", "raw", "[", "0", "]", ")", ")", "ret", "[", "'pressureForce'", "]", "=", "cleanList", "(", "raw", "[", "1", ":", "4", "]", ")", "ret", "[", "'viscousForce'", "]", "=", "cleanList", "(", "raw", "[", "4", ":", "7", "]", ")", "ret", "[", "'pressureMoment'", "]", "=", "cleanList", "(", "raw", "[", "10", ":", "14", "]", ")", "ret", "[", "'viscousMoment'", "]", "=", "cleanList", "(", "raw", "[", "14", ":", "17", "]", ")", "return", "ret" ]
https://github.com/openfoamtutorials/OpenFOAM_Tutorials_/blob/29e19833aea3f6ee87ecceae3d061b050ee3ed89/InProgress/MultiElementBiWing/plot.py#L20-L33
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_misc.py
python
ConfigBase.GetNumberOfGroups
(*args, **kwargs)
return _misc_.ConfigBase_GetNumberOfGroups(*args, **kwargs)
GetNumberOfGroups(self, bool recursive=False) -> size_t Get the number of subgroups in the current group, with or without its subgroups.
GetNumberOfGroups(self, bool recursive=False) -> size_t
[ "GetNumberOfGroups", "(", "self", "bool", "recursive", "=", "False", ")", "-", ">", "size_t" ]
def GetNumberOfGroups(*args, **kwargs): """ GetNumberOfGroups(self, bool recursive=False) -> size_t Get the number of subgroups in the current group, with or without its subgroups. """ return _misc_.ConfigBase_GetNumberOfGroups(*args, **kwargs)
[ "def", "GetNumberOfGroups", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "ConfigBase_GetNumberOfGroups", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L3214-L3221
tfwu/FaceDetection-ConvNet-3D
f9251c48eb40c5aec8fba7455115c355466555be
python/build/lib.linux-x86_64-2.7/mxnet/model.py
python
FeedForward._init_params
(self, input_shapes, overwrite=False)
return (arg_names, list(param_names), aux_names)
Initialize weight parameters and auxiliary states
Initialize weight parameters and auxiliary states
[ "Initialize", "weight", "parameters", "and", "auxiliary", "states" ]
def _init_params(self, input_shapes, overwrite=False): """Initialize weight parameters and auxiliary states""" arg_shapes, _, aux_shapes = self.symbol.infer_shape(**input_shapes) assert(arg_shapes is not None) arg_names = self.symbol.list_arguments() input_names = input_shapes.keys() param_names = [key for key in arg_names if key not in input_names] aux_names = self.symbol.list_auxiliary_states() param_name_shapes = [x for x in zip(arg_names, arg_shapes) if x[0] in param_names] arg_params = {k : nd.zeros(s) for k, s in param_name_shapes} aux_params = {k : nd.zeros(s) for k, s in zip(aux_names, aux_shapes)} for k, v in arg_params.items(): if self.arg_params and k in self.arg_params and (not overwrite): arg_params[k][:] = self.arg_params[k][:] else: self.initializer(k, v) for k, v in aux_params.items(): if self.aux_params and k in self.aux_params and (not overwrite): aux_params[k][:] = self.aux_params[k][:] else: self.initializer(k, v) self.arg_params = arg_params self.aux_params = aux_params return (arg_names, list(param_names), aux_names)
[ "def", "_init_params", "(", "self", ",", "input_shapes", ",", "overwrite", "=", "False", ")", ":", "arg_shapes", ",", "_", ",", "aux_shapes", "=", "self", ".", "symbol", ".", "infer_shape", "(", "*", "*", "input_shapes", ")", "assert", "(", "arg_shapes", "is", "not", "None", ")", "arg_names", "=", "self", ".", "symbol", ".", "list_arguments", "(", ")", "input_names", "=", "input_shapes", ".", "keys", "(", ")", "param_names", "=", "[", "key", "for", "key", "in", "arg_names", "if", "key", "not", "in", "input_names", "]", "aux_names", "=", "self", ".", "symbol", ".", "list_auxiliary_states", "(", ")", "param_name_shapes", "=", "[", "x", "for", "x", "in", "zip", "(", "arg_names", ",", "arg_shapes", ")", "if", "x", "[", "0", "]", "in", "param_names", "]", "arg_params", "=", "{", "k", ":", "nd", ".", "zeros", "(", "s", ")", "for", "k", ",", "s", "in", "param_name_shapes", "}", "aux_params", "=", "{", "k", ":", "nd", ".", "zeros", "(", "s", ")", "for", "k", ",", "s", "in", "zip", "(", "aux_names", ",", "aux_shapes", ")", "}", "for", "k", ",", "v", "in", "arg_params", ".", "items", "(", ")", ":", "if", "self", ".", "arg_params", "and", "k", "in", "self", ".", "arg_params", "and", "(", "not", "overwrite", ")", ":", "arg_params", "[", "k", "]", "[", ":", "]", "=", "self", ".", "arg_params", "[", "k", "]", "[", ":", "]", "else", ":", "self", ".", "initializer", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "aux_params", ".", "items", "(", ")", ":", "if", "self", ".", "aux_params", "and", "k", "in", "self", ".", "aux_params", "and", "(", "not", "overwrite", ")", ":", "aux_params", "[", "k", "]", "[", ":", "]", "=", "self", ".", "aux_params", "[", "k", "]", "[", ":", "]", "else", ":", "self", ".", "initializer", "(", "k", ",", "v", ")", "self", ".", "arg_params", "=", "arg_params", "self", ".", "aux_params", "=", "aux_params", "return", "(", "arg_names", ",", "list", "(", "param_names", ")", ",", "aux_names", ")" ]
https://github.com/tfwu/FaceDetection-ConvNet-3D/blob/f9251c48eb40c5aec8fba7455115c355466555be/python/build/lib.linux-x86_64-2.7/mxnet/model.py#L481-L509
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
python/mxnet/gluon/block.py
python
Block.load_parameters
(self, filename, ctx=None, allow_missing=False, ignore_extra=False, cast_dtype=False, dtype_source='current')
Load parameters from file previously saved by `save_parameters`. Parameters ---------- filename : str Path to parameter file. ctx : Context or list of Context, default cpu() Context(s) to initialize loaded parameters on. allow_missing : bool, default False Whether to silently skip loading parameters not represents in the file. ignore_extra : bool, default False Whether to silently ignore parameters from the file that are not present in this Block. cast_dtype : bool, default False Cast the data type of the NDArray loaded from the checkpoint to the dtype provided by the Parameter if any. dtype_source : str, default 'current' must be in {'current', 'saved'} Only valid if cast_dtype=True, specify the source of the dtype for casting the parameters References ---------- `Saving and Loading Gluon Models \ <https://mxnet.incubator.apache.org/tutorials/gluon/save_load_params.html>`_
Load parameters from file previously saved by `save_parameters`.
[ "Load", "parameters", "from", "file", "previously", "saved", "by", "save_parameters", "." ]
def load_parameters(self, filename, ctx=None, allow_missing=False, ignore_extra=False, cast_dtype=False, dtype_source='current'): """Load parameters from file previously saved by `save_parameters`. Parameters ---------- filename : str Path to parameter file. ctx : Context or list of Context, default cpu() Context(s) to initialize loaded parameters on. allow_missing : bool, default False Whether to silently skip loading parameters not represents in the file. ignore_extra : bool, default False Whether to silently ignore parameters from the file that are not present in this Block. cast_dtype : bool, default False Cast the data type of the NDArray loaded from the checkpoint to the dtype provided by the Parameter if any. dtype_source : str, default 'current' must be in {'current', 'saved'} Only valid if cast_dtype=True, specify the source of the dtype for casting the parameters References ---------- `Saving and Loading Gluon Models \ <https://mxnet.incubator.apache.org/tutorials/gluon/save_load_params.html>`_ """ loaded = ndarray.load(filename) params = self._collect_params_with_prefix() if not loaded and not params: return if not any('.' in i for i in loaded.keys()): # legacy loading del loaded self.collect_params().load( filename, ctx, allow_missing, ignore_extra, self.prefix, cast_dtype=cast_dtype, dtype_source=dtype_source) return if not allow_missing: for name in params.keys(): assert name in loaded, \ "Parameter '%s' is missing in file '%s', which contains parameters: %s. " \ "Set allow_missing=True to ignore missing parameters."%( name, filename, _brief_print_list(loaded.keys())) for name in loaded: if not ignore_extra and name not in params: raise ValueError( "Parameter '%s' loaded from file '%s' is not present in ParameterDict, " \ "which contains parameters %s. Set ignore_extra=True to ignore. "%( name, filename, _brief_print_list(self._params.keys()))) if name in params: params[name]._load_init(loaded[name], ctx, cast_dtype=cast_dtype, dtype_source=dtype_source)
[ "def", "load_parameters", "(", "self", ",", "filename", ",", "ctx", "=", "None", ",", "allow_missing", "=", "False", ",", "ignore_extra", "=", "False", ",", "cast_dtype", "=", "False", ",", "dtype_source", "=", "'current'", ")", ":", "loaded", "=", "ndarray", ".", "load", "(", "filename", ")", "params", "=", "self", ".", "_collect_params_with_prefix", "(", ")", "if", "not", "loaded", "and", "not", "params", ":", "return", "if", "not", "any", "(", "'.'", "in", "i", "for", "i", "in", "loaded", ".", "keys", "(", ")", ")", ":", "# legacy loading", "del", "loaded", "self", ".", "collect_params", "(", ")", ".", "load", "(", "filename", ",", "ctx", ",", "allow_missing", ",", "ignore_extra", ",", "self", ".", "prefix", ",", "cast_dtype", "=", "cast_dtype", ",", "dtype_source", "=", "dtype_source", ")", "return", "if", "not", "allow_missing", ":", "for", "name", "in", "params", ".", "keys", "(", ")", ":", "assert", "name", "in", "loaded", ",", "\"Parameter '%s' is missing in file '%s', which contains parameters: %s. \"", "\"Set allow_missing=True to ignore missing parameters.\"", "%", "(", "name", ",", "filename", ",", "_brief_print_list", "(", "loaded", ".", "keys", "(", ")", ")", ")", "for", "name", "in", "loaded", ":", "if", "not", "ignore_extra", "and", "name", "not", "in", "params", ":", "raise", "ValueError", "(", "\"Parameter '%s' loaded from file '%s' is not present in ParameterDict, \"", "\"which contains parameters %s. Set ignore_extra=True to ignore. \"", "%", "(", "name", ",", "filename", ",", "_brief_print_list", "(", "self", ".", "_params", ".", "keys", "(", ")", ")", ")", ")", "if", "name", "in", "params", ":", "params", "[", "name", "]", ".", "_load_init", "(", "loaded", "[", "name", "]", ",", "ctx", ",", "cast_dtype", "=", "cast_dtype", ",", "dtype_source", "=", "dtype_source", ")" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/gluon/block.py#L358-L411
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Source/ThirdParty/CEF3/pristine/cef_source/tools/cefbuilds/cef_json_builder.py
python
cef_json_builder.get_versions
(self, platform)
return self._data[platform]['versions']
Return all versions for the specified |platform|.
Return all versions for the specified |platform|.
[ "Return", "all", "versions", "for", "the", "specified", "|platform|", "." ]
def get_versions(self, platform): """ Return all versions for the specified |platform|. """ return self._data[platform]['versions']
[ "def", "get_versions", "(", "self", ",", "platform", ")", ":", "return", "self", ".", "_data", "[", "platform", "]", "[", "'versions'", "]" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Source/ThirdParty/CEF3/pristine/cef_source/tools/cefbuilds/cef_json_builder.py#L432-L434
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/utils/extmath.py
python
_deterministic_vector_sign_flip
(u)
return u
Modify the sign of vectors for reproducibility Flips the sign of elements of all the vectors (rows of u) such that the absolute maximum element of each vector is positive. Parameters ---------- u : ndarray Array with vectors as its rows. Returns ------- u_flipped : ndarray with same shape as u Array with the sign flipped vectors as its rows.
Modify the sign of vectors for reproducibility
[ "Modify", "the", "sign", "of", "vectors", "for", "reproducibility" ]
def _deterministic_vector_sign_flip(u): """Modify the sign of vectors for reproducibility Flips the sign of elements of all the vectors (rows of u) such that the absolute maximum element of each vector is positive. Parameters ---------- u : ndarray Array with vectors as its rows. Returns ------- u_flipped : ndarray with same shape as u Array with the sign flipped vectors as its rows. """ max_abs_rows = np.argmax(np.abs(u), axis=1) signs = np.sign(u[range(u.shape[0]), max_abs_rows]) u *= signs[:, np.newaxis] return u
[ "def", "_deterministic_vector_sign_flip", "(", "u", ")", ":", "max_abs_rows", "=", "np", ".", "argmax", "(", "np", ".", "abs", "(", "u", ")", ",", "axis", "=", "1", ")", "signs", "=", "np", ".", "sign", "(", "u", "[", "range", "(", "u", ".", "shape", "[", "0", "]", ")", ",", "max_abs_rows", "]", ")", "u", "*=", "signs", "[", ":", ",", "np", ".", "newaxis", "]", "return", "u" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/utils/extmath.py#L825-L844
htcondor/htcondor
4829724575176d1d6c936e4693dfd78a728569b0
src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/conversion.py
python
IConversion.TextToGroupType
(self, Text)
return self._TextTo('grp', Text)
Returns group type code. @param Text: Text, one of L{Group type<enums.grpUnknown>}. @type Text: unicode @return: Group type. @rtype: L{Group type<enums.grpUnknown>} @note: Currently, this method only checks if the given string is one of the allowed ones and returns it or raises a C{ValueError}.
Returns group type code.
[ "Returns", "group", "type", "code", "." ]
def TextToGroupType(self, Text): '''Returns group type code. @param Text: Text, one of L{Group type<enums.grpUnknown>}. @type Text: unicode @return: Group type. @rtype: L{Group type<enums.grpUnknown>} @note: Currently, this method only checks if the given string is one of the allowed ones and returns it or raises a C{ValueError}. ''' return self._TextTo('grp', Text)
[ "def", "TextToGroupType", "(", "self", ",", "Text", ")", ":", "return", "self", ".", "_TextTo", "(", "'grp'", ",", "Text", ")" ]
https://github.com/htcondor/htcondor/blob/4829724575176d1d6c936e4693dfd78a728569b0/src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/conversion.py#L317-L327
AojunZhou/Incremental-Network-Quantization
c7f6a609d5817d8424ce224209cf4c50f1e4de50
scripts/cpp_lint.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/AojunZhou/Incremental-Network-Quantization/blob/c7f6a609d5817d8424ce224209cf4c50f1e4de50/scripts/cpp_lint.py#L495-L497
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/base.py
python
BaseContext.get_preferred_array_alignment
(context, ty)
return 32
Get preferred array alignment for Numba type *ty*.
Get preferred array alignment for Numba type *ty*.
[ "Get", "preferred", "array", "alignment", "for", "Numba", "type", "*", "ty", "*", "." ]
def get_preferred_array_alignment(context, ty): """ Get preferred array alignment for Numba type *ty*. """ # AVX prefers 32-byte alignment return 32
[ "def", "get_preferred_array_alignment", "(", "context", ",", "ty", ")", ":", "# AVX prefers 32-byte alignment", "return", "32" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/base.py#L1092-L1097
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_controls.py
python
Toolbook.Realize
(*args, **kwargs)
return _controls_.Toolbook_Realize(*args, **kwargs)
Realize(self)
Realize(self)
[ "Realize", "(", "self", ")" ]
def Realize(*args, **kwargs): """Realize(self)""" return _controls_.Toolbook_Realize(*args, **kwargs)
[ "def", "Realize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "Toolbook_Realize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L3388-L3390
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/profiler/internal/flops_registry.py
python
_neg_flops
(graph, node)
return _unary_op_flops(graph, node)
Compute flops for Neg operation.
Compute flops for Neg operation.
[ "Compute", "flops", "for", "Neg", "operation", "." ]
def _neg_flops(graph, node): """Compute flops for Neg operation.""" return _unary_op_flops(graph, node)
[ "def", "_neg_flops", "(", "graph", ",", "node", ")", ":", "return", "_unary_op_flops", "(", "graph", ",", "node", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/profiler/internal/flops_registry.py#L93-L95
SoarGroup/Soar
a1c5e249499137a27da60533c72969eef3b8ab6b
scons/scons-local-4.1.0/SCons/SConf.py
python
SConfBase.Define
(self, name, value = None, comment = None)
Define a pre processor symbol name, with the optional given value in the current config header. If value is None (default), then #define name is written. If value is not none, then #define name value is written. comment is a string which will be put as a C comment in the header, to explain the meaning of the value (appropriate C comments will be added automatically).
Define a pre processor symbol name, with the optional given value in the current config header.
[ "Define", "a", "pre", "processor", "symbol", "name", "with", "the", "optional", "given", "value", "in", "the", "current", "config", "header", "." ]
def Define(self, name, value = None, comment = None): """ Define a pre processor symbol name, with the optional given value in the current config header. If value is None (default), then #define name is written. If value is not none, then #define name value is written. comment is a string which will be put as a C comment in the header, to explain the meaning of the value (appropriate C comments will be added automatically). """ lines = [] if comment: comment_str = "/* %s */" % comment lines.append(comment_str) if value is not None: define_str = "#define %s %s" % (name, value) else: define_str = "#define %s" % name lines.append(define_str) lines.append('') self.config_h_text = self.config_h_text + '\n'.join(lines)
[ "def", "Define", "(", "self", ",", "name", ",", "value", "=", "None", ",", "comment", "=", "None", ")", ":", "lines", "=", "[", "]", "if", "comment", ":", "comment_str", "=", "\"/* %s */\"", "%", "comment", "lines", ".", "append", "(", "comment_str", ")", "if", "value", "is", "not", "None", ":", "define_str", "=", "\"#define %s %s\"", "%", "(", "name", ",", "value", ")", "else", ":", "define_str", "=", "\"#define %s\"", "%", "name", "lines", ".", "append", "(", "define_str", ")", "lines", ".", "append", "(", "''", ")", "self", ".", "config_h_text", "=", "self", ".", "config_h_text", "+", "'\\n'", ".", "join", "(", "lines", ")" ]
https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/SConf.py#L472-L495
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/stats/kde.py
python
gaussian_kde.integrate_box_1d
(self, low, high)
return value
Computes the integral of a 1D pdf between two bounds. Parameters ---------- low : scalar Lower bound of integration. high : scalar Upper bound of integration. Returns ------- value : scalar The result of the integral. Raises ------ ValueError If the KDE is over more than one dimension.
Computes the integral of a 1D pdf between two bounds.
[ "Computes", "the", "integral", "of", "a", "1D", "pdf", "between", "two", "bounds", "." ]
def integrate_box_1d(self, low, high): """ Computes the integral of a 1D pdf between two bounds. Parameters ---------- low : scalar Lower bound of integration. high : scalar Upper bound of integration. Returns ------- value : scalar The result of the integral. Raises ------ ValueError If the KDE is over more than one dimension. """ if self.d != 1: raise ValueError("integrate_box_1d() only handles 1D pdfs") stdev = ravel(sqrt(self.covariance))[0] normalized_low = ravel((low - self.dataset) / stdev) normalized_high = ravel((high - self.dataset) / stdev) value = np.mean(special.ndtr(normalized_high) - special.ndtr(normalized_low)) return value
[ "def", "integrate_box_1d", "(", "self", ",", "low", ",", "high", ")", ":", "if", "self", ".", "d", "!=", "1", ":", "raise", "ValueError", "(", "\"integrate_box_1d() only handles 1D pdfs\"", ")", "stdev", "=", "ravel", "(", "sqrt", "(", "self", ".", "covariance", ")", ")", "[", "0", "]", "normalized_low", "=", "ravel", "(", "(", "low", "-", "self", ".", "dataset", ")", "/", "stdev", ")", "normalized_high", "=", "ravel", "(", "(", "high", "-", "self", ".", "dataset", ")", "/", "stdev", ")", "value", "=", "np", ".", "mean", "(", "special", ".", "ndtr", "(", "normalized_high", ")", "-", "special", ".", "ndtr", "(", "normalized_low", ")", ")", "return", "value" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/stats/kde.py#L279-L311
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/resource_variable_ops.py
python
BaseResourceVariable.device
(self)
return self.handle.device
The device this variable is on.
The device this variable is on.
[ "The", "device", "this", "variable", "is", "on", "." ]
def device(self): """The device this variable is on.""" return self.handle.device
[ "def", "device", "(", "self", ")", ":", "return", "self", ".", "handle", ".", "device" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/resource_variable_ops.py#L559-L561