nwo
stringlengths
5
86
sha
stringlengths
40
40
path
stringlengths
4
189
language
stringclasses
1 value
identifier
stringlengths
1
94
parameters
stringlengths
2
4.03k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
11.5k
docstring
stringlengths
1
33.2k
docstring_summary
stringlengths
0
5.15k
docstring_tokens
list
function
stringlengths
34
151k
function_tokens
list
url
stringlengths
90
278
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/urllib3/request.py
python
RequestMethods.request_encode_body
( self, method, url, fields=None, headers=None, encode_multipart=True, multipart_boundary=None, **urlopen_kw )
return self.urlopen(method, url, **extra_kw)
Make a request using :meth:`urlopen` with the ``fields`` encoded in the body. This is useful for request methods like POST, PUT, PATCH, etc. When ``encode_multipart=True`` (default), then :meth:`urllib3.filepost.encode_multipart_formdata` is used to encode the payload with the appropriate content type. Otherwise :meth:`urllib.urlencode` is used with the 'application/x-www-form-urlencoded' content type. Multipart encoding must be used when posting files, and it's reasonably safe to use it in other times too. However, it may break request signing, such as with OAuth. Supports an optional ``fields`` parameter of key/value strings AND key/filetuple. A filetuple is a (filename, data, MIME type) tuple where the MIME type is optional. For example:: fields = { 'foo': 'bar', 'fakefile': ('foofile.txt', 'contents of foofile'), 'realfile': ('barfile.txt', open('realfile').read()), 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'), 'nonamefile': 'contents of nonamefile field', } When uploading a file, providing a filename (the first parameter of the tuple) is optional but recommended to best mimic behavior of browsers. Note that if ``headers`` are supplied, the 'Content-Type' header will be overwritten because it depends on the dynamic random boundary string which is used to compose the body of the request. The random boundary string can be explicitly set with the ``multipart_boundary`` parameter.
Make a request using :meth:`urlopen` with the ``fields`` encoded in the body. This is useful for request methods like POST, PUT, PATCH, etc.
[ "Make", "a", "request", "using", ":", "meth", ":", "urlopen", "with", "the", "fields", "encoded", "in", "the", "body", ".", "This", "is", "useful", "for", "request", "methods", "like", "POST", "PUT", "PATCH", "etc", "." ]
def request_encode_body( self, method, url, fields=None, headers=None, encode_multipart=True, multipart_boundary=None, **urlopen_kw ): """ Make a request using :meth:`urlopen` with the ``fields`` encoded in the body. This is useful for request methods like POST, PUT, PATCH, etc. When ``encode_multipart=True`` (default), then :meth:`urllib3.filepost.encode_multipart_formdata` is used to encode the payload with the appropriate content type. Otherwise :meth:`urllib.urlencode` is used with the 'application/x-www-form-urlencoded' content type. Multipart encoding must be used when posting files, and it's reasonably safe to use it in other times too. However, it may break request signing, such as with OAuth. Supports an optional ``fields`` parameter of key/value strings AND key/filetuple. A filetuple is a (filename, data, MIME type) tuple where the MIME type is optional. For example:: fields = { 'foo': 'bar', 'fakefile': ('foofile.txt', 'contents of foofile'), 'realfile': ('barfile.txt', open('realfile').read()), 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'), 'nonamefile': 'contents of nonamefile field', } When uploading a file, providing a filename (the first parameter of the tuple) is optional but recommended to best mimic behavior of browsers. Note that if ``headers`` are supplied, the 'Content-Type' header will be overwritten because it depends on the dynamic random boundary string which is used to compose the body of the request. The random boundary string can be explicitly set with the ``multipart_boundary`` parameter. """ if headers is None: headers = self.headers extra_kw = {"headers": {}} if fields: if "body" in urlopen_kw: raise TypeError( "request got values for both 'fields' and 'body', can only specify one." ) if encode_multipart: body, content_type = encode_multipart_formdata( fields, boundary=multipart_boundary ) else: body, content_type = ( urlencode(fields), "application/x-www-form-urlencoded", ) extra_kw["body"] = body extra_kw["headers"] = {"Content-Type": content_type} extra_kw["headers"].update(headers) extra_kw.update(urlopen_kw) return self.urlopen(method, url, **extra_kw)
[ "def", "request_encode_body", "(", "self", ",", "method", ",", "url", ",", "fields", "=", "None", ",", "headers", "=", "None", ",", "encode_multipart", "=", "True", ",", "multipart_boundary", "=", "None", ",", "*", "*", "urlopen_kw", ")", ":", "if", "headers", "is", "None", ":", "headers", "=", "self", ".", "headers", "extra_kw", "=", "{", "\"headers\"", ":", "{", "}", "}", "if", "fields", ":", "if", "\"body\"", "in", "urlopen_kw", ":", "raise", "TypeError", "(", "\"request got values for both 'fields' and 'body', can only specify one.\"", ")", "if", "encode_multipart", ":", "body", ",", "content_type", "=", "encode_multipart_formdata", "(", "fields", ",", "boundary", "=", "multipart_boundary", ")", "else", ":", "body", ",", "content_type", "=", "(", "urlencode", "(", "fields", ")", ",", "\"application/x-www-form-urlencoded\"", ",", ")", "extra_kw", "[", "\"body\"", "]", "=", "body", "extra_kw", "[", "\"headers\"", "]", "=", "{", "\"Content-Type\"", ":", "content_type", "}", "extra_kw", "[", "\"headers\"", "]", ".", "update", "(", "headers", ")", "extra_kw", ".", "update", "(", "urlopen_kw", ")", "return", "self", ".", "urlopen", "(", "method", ",", "url", ",", "*", "*", "extra_kw", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/urllib3/request.py#L99-L171
zhaoweicai/cascade-rcnn
2252f46158ea6555868ca6fa5c221ea71d9b5e6c
scripts/cpp_lint.py
python
CheckCheck
(filename, clean_lines, linenum, error)
Checks the use of CHECK and EXPECT macros. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Checks the use of CHECK and EXPECT macros.
[ "Checks", "the", "use", "of", "CHECK", "and", "EXPECT", "macros", "." ]
def CheckCheck(filename, clean_lines, linenum, error): """Checks the use of CHECK and EXPECT macros. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ # Decide the set of replacement macros that should be suggested lines = clean_lines.elided check_macro = None start_pos = -1 for macro in _CHECK_MACROS: i = lines[linenum].find(macro) if i >= 0: check_macro = macro # Find opening parenthesis. Do a regular expression match here # to make sure that we are matching the expected CHECK macro, as # opposed to some other macro that happens to contain the CHECK # substring. matched = Match(r'^(.*\b' + check_macro + r'\s*)\(', lines[linenum]) if not matched: continue start_pos = len(matched.group(1)) break if not check_macro or start_pos < 0: # Don't waste time here if line doesn't contain 'CHECK' or 'EXPECT' return # Find end of the boolean expression by matching parentheses (last_line, end_line, end_pos) = CloseExpression( clean_lines, linenum, start_pos) if end_pos < 0: return if linenum == end_line: expression = lines[linenum][start_pos + 1:end_pos - 1] else: expression = lines[linenum][start_pos + 1:] for i in xrange(linenum + 1, end_line): expression += lines[i] expression += last_line[0:end_pos - 1] # Parse expression so that we can take parentheses into account. # This avoids false positives for inputs like "CHECK((a < 4) == b)", # which is not replaceable by CHECK_LE. lhs = '' rhs = '' operator = None while expression: matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||' r'==|!=|>=|>|<=|<|\()(.*)$', expression) if matched: token = matched.group(1) if token == '(': # Parenthesized operand expression = matched.group(2) (end, _) = FindEndOfExpressionInLine(expression, 0, 1, '(', ')') if end < 0: return # Unmatched parenthesis lhs += '(' + expression[0:end] expression = expression[end:] elif token in ('&&', '||'): # Logical and/or operators. This means the expression # contains more than one term, for example: # CHECK(42 < a && a < b); # # These are not replaceable with CHECK_LE, so bail out early. return elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'): # Non-relational operator lhs += token expression = matched.group(2) else: # Relational operator operator = token rhs = matched.group(2) break else: # Unparenthesized operand. Instead of appending to lhs one character # at a time, we do another regular expression match to consume several # characters at once if possible. Trivial benchmark shows that this # is more efficient when the operands are longer than a single # character, which is generally the case. matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression) if not matched: matched = Match(r'^(\s*\S)(.*)$', expression) if not matched: break lhs += matched.group(1) expression = matched.group(2) # Only apply checks if we got all parts of the boolean expression if not (lhs and operator and rhs): return # Check that rhs do not contain logical operators. We already know # that lhs is fine since the loop above parses out && and ||. if rhs.find('&&') > -1 or rhs.find('||') > -1: return # At least one of the operands must be a constant literal. This is # to avoid suggesting replacements for unprintable things like # CHECK(variable != iterator) # # The following pattern matches decimal, hex integers, strings, and # characters (in that order). lhs = lhs.strip() rhs = rhs.strip() match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$' if Match(match_constant, lhs) or Match(match_constant, rhs): # Note: since we know both lhs and rhs, we can provide a more # descriptive error message like: # Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42) # Instead of: # Consider using CHECK_EQ instead of CHECK(a == b) # # We are still keeping the less descriptive message because if lhs # or rhs gets long, the error message might become unreadable. error(filename, linenum, 'readability/check', 2, 'Consider using %s instead of %s(a %s b)' % ( _CHECK_REPLACEMENT[check_macro][operator], check_macro, operator))
[ "def", "CheckCheck", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "# Decide the set of replacement macros that should be suggested", "lines", "=", "clean_lines", ".", "elided", "check_macro", "=", "None", "start_pos", "=", "-", "1", "for", "macro", "in", "_CHECK_MACROS", ":", "i", "=", "lines", "[", "linenum", "]", ".", "find", "(", "macro", ")", "if", "i", ">=", "0", ":", "check_macro", "=", "macro", "# Find opening parenthesis. Do a regular expression match here", "# to make sure that we are matching the expected CHECK macro, as", "# opposed to some other macro that happens to contain the CHECK", "# substring.", "matched", "=", "Match", "(", "r'^(.*\\b'", "+", "check_macro", "+", "r'\\s*)\\('", ",", "lines", "[", "linenum", "]", ")", "if", "not", "matched", ":", "continue", "start_pos", "=", "len", "(", "matched", ".", "group", "(", "1", ")", ")", "break", "if", "not", "check_macro", "or", "start_pos", "<", "0", ":", "# Don't waste time here if line doesn't contain 'CHECK' or 'EXPECT'", "return", "# Find end of the boolean expression by matching parentheses", "(", "last_line", ",", "end_line", ",", "end_pos", ")", "=", "CloseExpression", "(", "clean_lines", ",", "linenum", ",", "start_pos", ")", "if", "end_pos", "<", "0", ":", "return", "if", "linenum", "==", "end_line", ":", "expression", "=", "lines", "[", "linenum", "]", "[", "start_pos", "+", "1", ":", "end_pos", "-", "1", "]", "else", ":", "expression", "=", "lines", "[", "linenum", "]", "[", "start_pos", "+", "1", ":", "]", "for", "i", "in", "xrange", "(", "linenum", "+", "1", ",", "end_line", ")", ":", "expression", "+=", "lines", "[", "i", "]", "expression", "+=", "last_line", "[", "0", ":", "end_pos", "-", "1", "]", "# Parse expression so that we can take parentheses into account.", "# This avoids false positives for inputs like \"CHECK((a < 4) == b)\",", "# which is not replaceable by CHECK_LE.", "lhs", "=", "''", "rhs", "=", "''", "operator", "=", "None", "while", "expression", ":", "matched", "=", "Match", "(", "r'^\\s*(<<|<<=|>>|>>=|->\\*|->|&&|\\|\\||'", "r'==|!=|>=|>|<=|<|\\()(.*)$'", ",", "expression", ")", "if", "matched", ":", "token", "=", "matched", ".", "group", "(", "1", ")", "if", "token", "==", "'('", ":", "# Parenthesized operand", "expression", "=", "matched", ".", "group", "(", "2", ")", "(", "end", ",", "_", ")", "=", "FindEndOfExpressionInLine", "(", "expression", ",", "0", ",", "1", ",", "'('", ",", "')'", ")", "if", "end", "<", "0", ":", "return", "# Unmatched parenthesis", "lhs", "+=", "'('", "+", "expression", "[", "0", ":", "end", "]", "expression", "=", "expression", "[", "end", ":", "]", "elif", "token", "in", "(", "'&&'", ",", "'||'", ")", ":", "# Logical and/or operators. This means the expression", "# contains more than one term, for example:", "# CHECK(42 < a && a < b);", "#", "# These are not replaceable with CHECK_LE, so bail out early.", "return", "elif", "token", "in", "(", "'<<'", ",", "'<<='", ",", "'>>'", ",", "'>>='", ",", "'->*'", ",", "'->'", ")", ":", "# Non-relational operator", "lhs", "+=", "token", "expression", "=", "matched", ".", "group", "(", "2", ")", "else", ":", "# Relational operator", "operator", "=", "token", "rhs", "=", "matched", ".", "group", "(", "2", ")", "break", "else", ":", "# Unparenthesized operand. Instead of appending to lhs one character", "# at a time, we do another regular expression match to consume several", "# characters at once if possible. Trivial benchmark shows that this", "# is more efficient when the operands are longer than a single", "# character, which is generally the case.", "matched", "=", "Match", "(", "r'^([^-=!<>()&|]+)(.*)$'", ",", "expression", ")", "if", "not", "matched", ":", "matched", "=", "Match", "(", "r'^(\\s*\\S)(.*)$'", ",", "expression", ")", "if", "not", "matched", ":", "break", "lhs", "+=", "matched", ".", "group", "(", "1", ")", "expression", "=", "matched", ".", "group", "(", "2", ")", "# Only apply checks if we got all parts of the boolean expression", "if", "not", "(", "lhs", "and", "operator", "and", "rhs", ")", ":", "return", "# Check that rhs do not contain logical operators. We already know", "# that lhs is fine since the loop above parses out && and ||.", "if", "rhs", ".", "find", "(", "'&&'", ")", ">", "-", "1", "or", "rhs", ".", "find", "(", "'||'", ")", ">", "-", "1", ":", "return", "# At least one of the operands must be a constant literal. This is", "# to avoid suggesting replacements for unprintable things like", "# CHECK(variable != iterator)", "#", "# The following pattern matches decimal, hex integers, strings, and", "# characters (in that order).", "lhs", "=", "lhs", ".", "strip", "(", ")", "rhs", "=", "rhs", ".", "strip", "(", ")", "match_constant", "=", "r'^([-+]?(\\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|\".*\"|\\'.*\\')$'", "if", "Match", "(", "match_constant", ",", "lhs", ")", "or", "Match", "(", "match_constant", ",", "rhs", ")", ":", "# Note: since we know both lhs and rhs, we can provide a more", "# descriptive error message like:", "# Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42)", "# Instead of:", "# Consider using CHECK_EQ instead of CHECK(a == b)", "#", "# We are still keeping the less descriptive message because if lhs", "# or rhs gets long, the error message might become unreadable.", "error", "(", "filename", ",", "linenum", ",", "'readability/check'", ",", "2", ",", "'Consider using %s instead of %s(a %s b)'", "%", "(", "_CHECK_REPLACEMENT", "[", "check_macro", "]", "[", "operator", "]", ",", "check_macro", ",", "operator", ")", ")" ]
https://github.com/zhaoweicai/cascade-rcnn/blob/2252f46158ea6555868ca6fa5c221ea71d9b5e6c/scripts/cpp_lint.py#L3282-L3406
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/optimize/_dual_annealing.py
python
dual_annealing
(func, bounds, args=(), maxiter=1000, local_search_options={}, initial_temp=5230., restart_temp_ratio=2.e-5, visit=2.62, accept=-5.0, maxfun=1e7, seed=None, no_local_search=False, callback=None, x0=None)
return res
Find the global minimum of a function using Dual Annealing. Parameters ---------- func : callable The objective function to be minimized. Must be in the form ``f(x, *args)``, where ``x`` is the argument in the form of a 1-D array and ``args`` is a tuple of any additional fixed parameters needed to completely specify the function. bounds : sequence, shape (n, 2) Bounds for variables. ``(min, max)`` pairs for each element in ``x``, defining bounds for the objective function parameter. args : tuple, optional Any additional fixed parameters needed to completely specify the objective function. maxiter : int, optional The maximum number of global search iterations. Default value is 1000. local_search_options : dict, optional Extra keyword arguments to be passed to the local minimizer (`minimize`). Some important options could be: ``method`` for the minimizer method to use and ``args`` for objective function additional arguments. initial_temp : float, optional The initial temperature, use higher values to facilitates a wider search of the energy landscape, allowing dual_annealing to escape local minima that it is trapped in. Default value is 5230. Range is (0.01, 5.e4]. restart_temp_ratio : float, optional During the annealing process, temperature is decreasing, when it reaches ``initial_temp * restart_temp_ratio``, the reannealing process is triggered. Default value of the ratio is 2e-5. Range is (0, 1). visit : float, optional Parameter for visiting distribution. Default value is 2.62. Higher values give the visiting distribution a heavier tail, this makes the algorithm jump to a more distant region. The value range is (0, 3]. accept : float, optional Parameter for acceptance distribution. It is used to control the probability of acceptance. The lower the acceptance parameter, the smaller the probability of acceptance. Default value is -5.0 with a range (-1e4, -5]. maxfun : int, optional Soft limit for the number of objective function calls. If the algorithm is in the middle of a local search, this number will be exceeded, the algorithm will stop just after the local search is done. Default value is 1e7. seed : {int or `numpy.random.RandomState` instance}, optional If `seed` is not specified the `numpy.random.RandomState` singleton is used. If `seed` is an int, a new ``RandomState`` instance is used, seeded with `seed`. If `seed` is already a ``RandomState`` instance, then that instance is used. Specify `seed` for repeatable minimizations. The random numbers generated with this seed only affect the visiting distribution function and new coordinates generation. no_local_search : bool, optional If `no_local_search` is set to True, a traditional Generalized Simulated Annealing will be performed with no local search strategy applied. callback : callable, optional A callback function with signature ``callback(x, f, context)``, which will be called for all minima found. ``x`` and ``f`` are the coordinates and function value of the latest minimum found, and ``context`` has value in [0, 1, 2], with the following meaning: - 0: minimum detected in the annealing process. - 1: detection occured in the local search process. - 2: detection done in the dual annealing process. If the callback implementation returns True, the algorithm will stop. x0 : ndarray, shape(n,), optional Coordinates of a single n-dimensional starting point. Returns ------- res : OptimizeResult The optimization result represented as a `OptimizeResult` object. Important attributes are: ``x`` the solution array, ``fun`` the value of the function at the solution, and ``message`` which describes the cause of the termination. See `OptimizeResult` for a description of other attributes. Notes ----- This function implements the Dual Annealing optimization. This stochastic approach derived from [3]_ combines the generalization of CSA (Classical Simulated Annealing) and FSA (Fast Simulated Annealing) [1]_ [2]_ coupled to a strategy for applying a local search on accepted locations [4]_. An alternative implementation of this same algorithm is described in [5]_ and benchmarks are presented in [6]_. This approach introduces an advanced method to refine the solution found by the generalized annealing process. This algorithm uses a distorted Cauchy-Lorentz visiting distribution, with its shape controlled by the parameter :math:`q_{v}` .. math:: g_{q_{v}}(\\Delta x(t)) \\propto \\frac{ \\ \\left[T_{q_{v}}(t) \\right]^{-\\frac{D}{3-q_{v}}}}{ \\ \\left[{1+(q_{v}-1)\\frac{(\\Delta x(t))^{2}} { \\ \\left[T_{q_{v}}(t)\\right]^{\\frac{2}{3-q_{v}}}}}\\right]^{ \\ \\frac{1}{q_{v}-1}+\\frac{D-1}{2}}} Where :math:`t` is the artificial time. This visiting distribution is used to generate a trial jump distance :math:`\\Delta x(t)` of variable :math:`x(t)` under artificial temperature :math:`T_{q_{v}}(t)`. From the starting point, after calling the visiting distribution function, the acceptance probability is computed as follows: .. math:: p_{q_{a}} = \\min{\\{1,\\left[1-(1-q_{a}) \\beta \\Delta E \\right]^{ \\ \\frac{1}{1-q_{a}}}\\}} Where :math:`q_{a}` is a acceptance parameter. For :math:`q_{a}<1`, zero acceptance probability is assigned to the cases where .. math:: [1-(1-q_{a}) \\beta \\Delta E] < 0 The artificial temperature :math:`T_{q_{v}}(t)` is decreased according to .. math:: T_{q_{v}}(t) = T_{q_{v}}(1) \\frac{2^{q_{v}-1}-1}{\\left( \\ 1 + t\\right)^{q_{v}-1}-1} Where :math:`q_{v}` is the visiting parameter. .. versionadded:: 1.2.0 References ---------- .. [1] Tsallis C. Possible generalization of Boltzmann-Gibbs statistics. Journal of Statistical Physics, 52, 479-487 (1998). .. [2] Tsallis C, Stariolo DA. Generalized Simulated Annealing. Physica A, 233, 395-406 (1996). .. [3] Xiang Y, Sun DY, Fan W, Gong XG. Generalized Simulated Annealing Algorithm and Its Application to the Thomson Model. Physics Letters A, 233, 216-220 (1997). .. [4] Xiang Y, Gong XG. Efficiency of Generalized Simulated Annealing. Physical Review E, 62, 4473 (2000). .. [5] Xiang Y, Gubian S, Suomela B, Hoeng J. Generalized Simulated Annealing for Efficient Global Optimization: the GenSA Package for R. The R Journal, Volume 5/1 (2013). .. [6] Mullen, K. Continuous Global Optimization in R. Journal of Statistical Software, 60(6), 1 - 45, (2014). DOI:10.18637/jss.v060.i06 Examples -------- The following example is a 10-dimensional problem, with many local minima. The function involved is called Rastrigin (https://en.wikipedia.org/wiki/Rastrigin_function) >>> from scipy.optimize import dual_annealing >>> func = lambda x: np.sum(x*x - 10*np.cos(2*np.pi*x)) + 10*np.size(x) >>> lw = [-5.12] * 10 >>> up = [5.12] * 10 >>> ret = dual_annealing(func, bounds=list(zip(lw, up)), seed=1234) >>> print("global minimum: xmin = {0}, f(xmin) = {1:.6f}".format( ... ret.x, ret.fun)) global minimum: xmin = [-4.26437714e-09 -3.91699361e-09 -1.86149218e-09 -3.97165720e-09 -6.29151648e-09 -6.53145322e-09 -3.93616815e-09 -6.55623025e-09 -6.05775280e-09 -5.00668935e-09], f(xmin) = 0.000000
Find the global minimum of a function using Dual Annealing.
[ "Find", "the", "global", "minimum", "of", "a", "function", "using", "Dual", "Annealing", "." ]
def dual_annealing(func, bounds, args=(), maxiter=1000, local_search_options={}, initial_temp=5230., restart_temp_ratio=2.e-5, visit=2.62, accept=-5.0, maxfun=1e7, seed=None, no_local_search=False, callback=None, x0=None): """ Find the global minimum of a function using Dual Annealing. Parameters ---------- func : callable The objective function to be minimized. Must be in the form ``f(x, *args)``, where ``x`` is the argument in the form of a 1-D array and ``args`` is a tuple of any additional fixed parameters needed to completely specify the function. bounds : sequence, shape (n, 2) Bounds for variables. ``(min, max)`` pairs for each element in ``x``, defining bounds for the objective function parameter. args : tuple, optional Any additional fixed parameters needed to completely specify the objective function. maxiter : int, optional The maximum number of global search iterations. Default value is 1000. local_search_options : dict, optional Extra keyword arguments to be passed to the local minimizer (`minimize`). Some important options could be: ``method`` for the minimizer method to use and ``args`` for objective function additional arguments. initial_temp : float, optional The initial temperature, use higher values to facilitates a wider search of the energy landscape, allowing dual_annealing to escape local minima that it is trapped in. Default value is 5230. Range is (0.01, 5.e4]. restart_temp_ratio : float, optional During the annealing process, temperature is decreasing, when it reaches ``initial_temp * restart_temp_ratio``, the reannealing process is triggered. Default value of the ratio is 2e-5. Range is (0, 1). visit : float, optional Parameter for visiting distribution. Default value is 2.62. Higher values give the visiting distribution a heavier tail, this makes the algorithm jump to a more distant region. The value range is (0, 3]. accept : float, optional Parameter for acceptance distribution. It is used to control the probability of acceptance. The lower the acceptance parameter, the smaller the probability of acceptance. Default value is -5.0 with a range (-1e4, -5]. maxfun : int, optional Soft limit for the number of objective function calls. If the algorithm is in the middle of a local search, this number will be exceeded, the algorithm will stop just after the local search is done. Default value is 1e7. seed : {int or `numpy.random.RandomState` instance}, optional If `seed` is not specified the `numpy.random.RandomState` singleton is used. If `seed` is an int, a new ``RandomState`` instance is used, seeded with `seed`. If `seed` is already a ``RandomState`` instance, then that instance is used. Specify `seed` for repeatable minimizations. The random numbers generated with this seed only affect the visiting distribution function and new coordinates generation. no_local_search : bool, optional If `no_local_search` is set to True, a traditional Generalized Simulated Annealing will be performed with no local search strategy applied. callback : callable, optional A callback function with signature ``callback(x, f, context)``, which will be called for all minima found. ``x`` and ``f`` are the coordinates and function value of the latest minimum found, and ``context`` has value in [0, 1, 2], with the following meaning: - 0: minimum detected in the annealing process. - 1: detection occured in the local search process. - 2: detection done in the dual annealing process. If the callback implementation returns True, the algorithm will stop. x0 : ndarray, shape(n,), optional Coordinates of a single n-dimensional starting point. Returns ------- res : OptimizeResult The optimization result represented as a `OptimizeResult` object. Important attributes are: ``x`` the solution array, ``fun`` the value of the function at the solution, and ``message`` which describes the cause of the termination. See `OptimizeResult` for a description of other attributes. Notes ----- This function implements the Dual Annealing optimization. This stochastic approach derived from [3]_ combines the generalization of CSA (Classical Simulated Annealing) and FSA (Fast Simulated Annealing) [1]_ [2]_ coupled to a strategy for applying a local search on accepted locations [4]_. An alternative implementation of this same algorithm is described in [5]_ and benchmarks are presented in [6]_. This approach introduces an advanced method to refine the solution found by the generalized annealing process. This algorithm uses a distorted Cauchy-Lorentz visiting distribution, with its shape controlled by the parameter :math:`q_{v}` .. math:: g_{q_{v}}(\\Delta x(t)) \\propto \\frac{ \\ \\left[T_{q_{v}}(t) \\right]^{-\\frac{D}{3-q_{v}}}}{ \\ \\left[{1+(q_{v}-1)\\frac{(\\Delta x(t))^{2}} { \\ \\left[T_{q_{v}}(t)\\right]^{\\frac{2}{3-q_{v}}}}}\\right]^{ \\ \\frac{1}{q_{v}-1}+\\frac{D-1}{2}}} Where :math:`t` is the artificial time. This visiting distribution is used to generate a trial jump distance :math:`\\Delta x(t)` of variable :math:`x(t)` under artificial temperature :math:`T_{q_{v}}(t)`. From the starting point, after calling the visiting distribution function, the acceptance probability is computed as follows: .. math:: p_{q_{a}} = \\min{\\{1,\\left[1-(1-q_{a}) \\beta \\Delta E \\right]^{ \\ \\frac{1}{1-q_{a}}}\\}} Where :math:`q_{a}` is a acceptance parameter. For :math:`q_{a}<1`, zero acceptance probability is assigned to the cases where .. math:: [1-(1-q_{a}) \\beta \\Delta E] < 0 The artificial temperature :math:`T_{q_{v}}(t)` is decreased according to .. math:: T_{q_{v}}(t) = T_{q_{v}}(1) \\frac{2^{q_{v}-1}-1}{\\left( \\ 1 + t\\right)^{q_{v}-1}-1} Where :math:`q_{v}` is the visiting parameter. .. versionadded:: 1.2.0 References ---------- .. [1] Tsallis C. Possible generalization of Boltzmann-Gibbs statistics. Journal of Statistical Physics, 52, 479-487 (1998). .. [2] Tsallis C, Stariolo DA. Generalized Simulated Annealing. Physica A, 233, 395-406 (1996). .. [3] Xiang Y, Sun DY, Fan W, Gong XG. Generalized Simulated Annealing Algorithm and Its Application to the Thomson Model. Physics Letters A, 233, 216-220 (1997). .. [4] Xiang Y, Gong XG. Efficiency of Generalized Simulated Annealing. Physical Review E, 62, 4473 (2000). .. [5] Xiang Y, Gubian S, Suomela B, Hoeng J. Generalized Simulated Annealing for Efficient Global Optimization: the GenSA Package for R. The R Journal, Volume 5/1 (2013). .. [6] Mullen, K. Continuous Global Optimization in R. Journal of Statistical Software, 60(6), 1 - 45, (2014). DOI:10.18637/jss.v060.i06 Examples -------- The following example is a 10-dimensional problem, with many local minima. The function involved is called Rastrigin (https://en.wikipedia.org/wiki/Rastrigin_function) >>> from scipy.optimize import dual_annealing >>> func = lambda x: np.sum(x*x - 10*np.cos(2*np.pi*x)) + 10*np.size(x) >>> lw = [-5.12] * 10 >>> up = [5.12] * 10 >>> ret = dual_annealing(func, bounds=list(zip(lw, up)), seed=1234) >>> print("global minimum: xmin = {0}, f(xmin) = {1:.6f}".format( ... ret.x, ret.fun)) global minimum: xmin = [-4.26437714e-09 -3.91699361e-09 -1.86149218e-09 -3.97165720e-09 -6.29151648e-09 -6.53145322e-09 -3.93616815e-09 -6.55623025e-09 -6.05775280e-09 -5.00668935e-09], f(xmin) = 0.000000 """ if x0 is not None and not len(x0) == len(bounds): raise ValueError('Bounds size does not match x0') lu = list(zip(*bounds)) lower = np.array(lu[0]) upper = np.array(lu[1]) # Check that restart temperature ratio is correct if restart_temp_ratio <= 0. or restart_temp_ratio >= 1.: raise ValueError('Restart temperature ratio has to be in range (0, 1)') # Checking bounds are valid if (np.any(np.isinf(lower)) or np.any(np.isinf(upper)) or np.any( np.isnan(lower)) or np.any(np.isnan(upper))): raise ValueError('Some bounds values are inf values or nan values') # Checking that bounds are consistent if not np.all(lower < upper): raise ValueError('Bounds are not consistent min < max') # Checking that bounds are the same length if not len(lower) == len(upper): raise ValueError('Bounds do not have the same dimensions') # Wrapper for the objective function func_wrapper = ObjectiveFunWrapper(func, maxfun, *args) # Wrapper fot the minimizer minimizer_wrapper = LocalSearchWrapper( bounds, func_wrapper, **local_search_options) # Initialization of RandomState for reproducible runs if seed provided rand_state = check_random_state(seed) # Initialization of the energy state energy_state = EnergyState(lower, upper, callback) energy_state.reset(func_wrapper, rand_state, x0) # Minimum value of annealing temperature reached to perform # re-annealing temperature_restart = initial_temp * restart_temp_ratio # VisitingDistribution instance visit_dist = VisitingDistribution(lower, upper, visit, rand_state) # Strategy chain instance strategy_chain = StrategyChain(accept, visit_dist, func_wrapper, minimizer_wrapper, rand_state, energy_state) # Run the search loop need_to_stop = False iteration = 0 message = [] t1 = np.exp((visit - 1) * np.log(2.0)) - 1.0 while(not need_to_stop): for i in range(maxiter): # Compute temperature for this step s = float(i) + 2.0 t2 = np.exp((visit - 1) * np.log(s)) - 1.0 temperature = initial_temp * t1 / t2 if iteration >= maxiter: message.append("Maximum number of iteration reached") need_to_stop = True break # Need a re-annealing process? if temperature < temperature_restart: energy_state.reset(func_wrapper, rand_state) break # starting strategy chain val = strategy_chain.run(i, temperature) if val is not None: message.append(val) need_to_stop = True break # Possible local search at the end of the strategy chain if not no_local_search: val = strategy_chain.local_search() if val is not None: message.append(val) need_to_stop = True break iteration += 1 # Return the OptimizeResult res = OptimizeResult() res.x = energy_state.xbest res.fun = energy_state.ebest res.nit = iteration res.nfev = func_wrapper.nfev res.njev = func_wrapper.ngev res.nhev = func_wrapper.nhev res.message = message return res
[ "def", "dual_annealing", "(", "func", ",", "bounds", ",", "args", "=", "(", ")", ",", "maxiter", "=", "1000", ",", "local_search_options", "=", "{", "}", ",", "initial_temp", "=", "5230.", ",", "restart_temp_ratio", "=", "2.e-5", ",", "visit", "=", "2.62", ",", "accept", "=", "-", "5.0", ",", "maxfun", "=", "1e7", ",", "seed", "=", "None", ",", "no_local_search", "=", "False", ",", "callback", "=", "None", ",", "x0", "=", "None", ")", ":", "if", "x0", "is", "not", "None", "and", "not", "len", "(", "x0", ")", "==", "len", "(", "bounds", ")", ":", "raise", "ValueError", "(", "'Bounds size does not match x0'", ")", "lu", "=", "list", "(", "zip", "(", "*", "bounds", ")", ")", "lower", "=", "np", ".", "array", "(", "lu", "[", "0", "]", ")", "upper", "=", "np", ".", "array", "(", "lu", "[", "1", "]", ")", "# Check that restart temperature ratio is correct", "if", "restart_temp_ratio", "<=", "0.", "or", "restart_temp_ratio", ">=", "1.", ":", "raise", "ValueError", "(", "'Restart temperature ratio has to be in range (0, 1)'", ")", "# Checking bounds are valid", "if", "(", "np", ".", "any", "(", "np", ".", "isinf", "(", "lower", ")", ")", "or", "np", ".", "any", "(", "np", ".", "isinf", "(", "upper", ")", ")", "or", "np", ".", "any", "(", "np", ".", "isnan", "(", "lower", ")", ")", "or", "np", ".", "any", "(", "np", ".", "isnan", "(", "upper", ")", ")", ")", ":", "raise", "ValueError", "(", "'Some bounds values are inf values or nan values'", ")", "# Checking that bounds are consistent", "if", "not", "np", ".", "all", "(", "lower", "<", "upper", ")", ":", "raise", "ValueError", "(", "'Bounds are not consistent min < max'", ")", "# Checking that bounds are the same length", "if", "not", "len", "(", "lower", ")", "==", "len", "(", "upper", ")", ":", "raise", "ValueError", "(", "'Bounds do not have the same dimensions'", ")", "# Wrapper for the objective function", "func_wrapper", "=", "ObjectiveFunWrapper", "(", "func", ",", "maxfun", ",", "*", "args", ")", "# Wrapper fot the minimizer", "minimizer_wrapper", "=", "LocalSearchWrapper", "(", "bounds", ",", "func_wrapper", ",", "*", "*", "local_search_options", ")", "# Initialization of RandomState for reproducible runs if seed provided", "rand_state", "=", "check_random_state", "(", "seed", ")", "# Initialization of the energy state", "energy_state", "=", "EnergyState", "(", "lower", ",", "upper", ",", "callback", ")", "energy_state", ".", "reset", "(", "func_wrapper", ",", "rand_state", ",", "x0", ")", "# Minimum value of annealing temperature reached to perform", "# re-annealing", "temperature_restart", "=", "initial_temp", "*", "restart_temp_ratio", "# VisitingDistribution instance", "visit_dist", "=", "VisitingDistribution", "(", "lower", ",", "upper", ",", "visit", ",", "rand_state", ")", "# Strategy chain instance", "strategy_chain", "=", "StrategyChain", "(", "accept", ",", "visit_dist", ",", "func_wrapper", ",", "minimizer_wrapper", ",", "rand_state", ",", "energy_state", ")", "# Run the search loop", "need_to_stop", "=", "False", "iteration", "=", "0", "message", "=", "[", "]", "t1", "=", "np", ".", "exp", "(", "(", "visit", "-", "1", ")", "*", "np", ".", "log", "(", "2.0", ")", ")", "-", "1.0", "while", "(", "not", "need_to_stop", ")", ":", "for", "i", "in", "range", "(", "maxiter", ")", ":", "# Compute temperature for this step", "s", "=", "float", "(", "i", ")", "+", "2.0", "t2", "=", "np", ".", "exp", "(", "(", "visit", "-", "1", ")", "*", "np", ".", "log", "(", "s", ")", ")", "-", "1.0", "temperature", "=", "initial_temp", "*", "t1", "/", "t2", "if", "iteration", ">=", "maxiter", ":", "message", ".", "append", "(", "\"Maximum number of iteration reached\"", ")", "need_to_stop", "=", "True", "break", "# Need a re-annealing process?", "if", "temperature", "<", "temperature_restart", ":", "energy_state", ".", "reset", "(", "func_wrapper", ",", "rand_state", ")", "break", "# starting strategy chain", "val", "=", "strategy_chain", ".", "run", "(", "i", ",", "temperature", ")", "if", "val", "is", "not", "None", ":", "message", ".", "append", "(", "val", ")", "need_to_stop", "=", "True", "break", "# Possible local search at the end of the strategy chain", "if", "not", "no_local_search", ":", "val", "=", "strategy_chain", ".", "local_search", "(", ")", "if", "val", "is", "not", "None", ":", "message", ".", "append", "(", "val", ")", "need_to_stop", "=", "True", "break", "iteration", "+=", "1", "# Return the OptimizeResult", "res", "=", "OptimizeResult", "(", ")", "res", ".", "x", "=", "energy_state", ".", "xbest", "res", ".", "fun", "=", "energy_state", ".", "ebest", "res", ".", "nit", "=", "iteration", "res", ".", "nfev", "=", "func_wrapper", ".", "nfev", "res", ".", "njev", "=", "func_wrapper", ".", "ngev", "res", ".", "nhev", "=", "func_wrapper", ".", "nhev", "res", ".", "message", "=", "message", "return", "res" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/optimize/_dual_annealing.py#L417-L672
geemaple/leetcode
68bc5032e1ee52c22ef2f2e608053484c487af54
leetcode/53.maximum-subarray.py
python
Solution2.maxSubArray
(self, nums)
return largest
:type nums: List[int] :rtype: int
:type nums: List[int] :rtype: int
[ ":", "type", "nums", ":", "List", "[", "int", "]", ":", "rtype", ":", "int" ]
def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ # suppose sumTo[i] = a[0] + a[1] + ... [i - 1], sumTo(0) = 0 # the subarray a[i:j] = sumTo[j] - sumTo[i] largest = float('-inf') smallest = 0 sumTo = 0 for num in nums: sumTo += num largest = max(largest, sumTo - smallest) smallest = min(smallest, sumTo) return largest
[ "def", "maxSubArray", "(", "self", ",", "nums", ")", ":", "# suppose sumTo[i] = a[0] + a[1] + ... [i - 1], sumTo(0) = 0", "# the subarray a[i:j] = sumTo[j] - sumTo[i]", "largest", "=", "float", "(", "'-inf'", ")", "smallest", "=", "0", "sumTo", "=", "0", "for", "num", "in", "nums", ":", "sumTo", "+=", "num", "largest", "=", "max", "(", "largest", ",", "sumTo", "-", "smallest", ")", "smallest", "=", "min", "(", "smallest", ",", "sumTo", ")", "return", "largest" ]
https://github.com/geemaple/leetcode/blob/68bc5032e1ee52c22ef2f2e608053484c487af54/leetcode/53.maximum-subarray.py#L23-L40
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/distutils/ccompiler.py
python
get_default_compiler
(osname=None, platform=None)
return 'unix'
Determine the default compiler to use for the given platform. osname should be one of the standard Python OS names (i.e. the ones returned by os.name) and platform the common value returned by sys.platform for the platform in question. The default values are os.name and sys.platform in case the parameters are not given.
Determine the default compiler to use for the given platform.
[ "Determine", "the", "default", "compiler", "to", "use", "for", "the", "given", "platform", "." ]
def get_default_compiler(osname=None, platform=None): """ Determine the default compiler to use for the given platform. osname should be one of the standard Python OS names (i.e. the ones returned by os.name) and platform the common value returned by sys.platform for the platform in question. The default values are os.name and sys.platform in case the parameters are not given. """ if osname is None: osname = os.name if platform is None: platform = sys.platform if osname == "nt" and sys.version.find('GCC') >= 0: return 'mingw32' for pattern, compiler in _default_compilers: if re.match(pattern, platform) is not None or \ re.match(pattern, osname) is not None: return compiler # Default to Unix compiler return 'unix'
[ "def", "get_default_compiler", "(", "osname", "=", "None", ",", "platform", "=", "None", ")", ":", "if", "osname", "is", "None", ":", "osname", "=", "os", ".", "name", "if", "platform", "is", "None", ":", "platform", "=", "sys", ".", "platform", "if", "osname", "==", "\"nt\"", "and", "sys", ".", "version", ".", "find", "(", "'GCC'", ")", ">=", "0", ":", "return", "'mingw32'", "for", "pattern", ",", "compiler", "in", "_default_compilers", ":", "if", "re", ".", "match", "(", "pattern", ",", "platform", ")", "is", "not", "None", "or", "re", ".", "match", "(", "pattern", ",", "osname", ")", "is", "not", "None", ":", "return", "compiler", "# Default to Unix compiler", "return", "'unix'" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/distutils/ccompiler.py#L906-L928
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py
python
Text.edit
(self, *args)
return self.tk.call(self._w, 'edit', *args)
Internal method This method controls the undo mechanism and the modified flag. The exact behavior of the command depends on the option argument that follows the edit argument. The following forms of the command are currently supported: edit_modified, edit_redo, edit_reset, edit_separator and edit_undo
Internal method
[ "Internal", "method" ]
def edit(self, *args): """Internal method This method controls the undo mechanism and the modified flag. The exact behavior of the command depends on the option argument that follows the edit argument. The following forms of the command are currently supported: edit_modified, edit_redo, edit_reset, edit_separator and edit_undo """ return self.tk.call(self._w, 'edit', *args)
[ "def", "edit", "(", "self", ",", "*", "args", ")", ":", "return", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "'edit'", ",", "*", "args", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py#L2961-L2974
qgis/QGIS
15a77662d4bb712184f6aa60d0bd663010a76a75
python/plugins/MetaSearch/pavement.py
python
test_default_csw_connections
()
test that the default CSW connections work
test that the default CSW connections work
[ "test", "that", "the", "default", "CSW", "connections", "work" ]
def test_default_csw_connections(): """test that the default CSW connections work""" relpath = 'resources%sconnections-default.xml' % os.sep csw_connections_xml = options.base.plugin / relpath conns = etree.parse(csw_connections_xml) for conn in conns.findall('csw'): try: csw = CatalogueServiceWeb(conn.attrib.get('url')) # spellok info('Success: %s', csw.identification.title) csw.getrecords2() except Exception as err: raise ValueError('ERROR: %s', err)
[ "def", "test_default_csw_connections", "(", ")", ":", "relpath", "=", "'resources%sconnections-default.xml'", "%", "os", ".", "sep", "csw_connections_xml", "=", "options", ".", "base", ".", "plugin", "/", "relpath", "conns", "=", "etree", ".", "parse", "(", "csw_connections_xml", ")", "for", "conn", "in", "conns", ".", "findall", "(", "'csw'", ")", ":", "try", ":", "csw", "=", "CatalogueServiceWeb", "(", "conn", ".", "attrib", ".", "get", "(", "'url'", ")", ")", "# spellok", "info", "(", "'Success: %s'", ",", "csw", ".", "identification", ".", "title", ")", "csw", ".", "getrecords2", "(", ")", "except", "Exception", "as", "err", ":", "raise", "ValueError", "(", "'ERROR: %s'", ",", "err", ")" ]
https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/plugins/MetaSearch/pavement.py#L177-L191
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/nntplib.py
python
NNTP.newgroups
(self, date, time, file=None)
return self.longcmd('NEWGROUPS ' + date + ' ' + time, file)
Process a NEWGROUPS command. Arguments: - date: string 'yymmdd' indicating the date - time: string 'hhmmss' indicating the time Return: - resp: server response if successful - list: list of newsgroup names
Process a NEWGROUPS command. Arguments: - date: string 'yymmdd' indicating the date - time: string 'hhmmss' indicating the time Return: - resp: server response if successful - list: list of newsgroup names
[ "Process", "a", "NEWGROUPS", "command", ".", "Arguments", ":", "-", "date", ":", "string", "yymmdd", "indicating", "the", "date", "-", "time", ":", "string", "hhmmss", "indicating", "the", "time", "Return", ":", "-", "resp", ":", "server", "response", "if", "successful", "-", "list", ":", "list", "of", "newsgroup", "names" ]
def newgroups(self, date, time, file=None): """Process a NEWGROUPS command. Arguments: - date: string 'yymmdd' indicating the date - time: string 'hhmmss' indicating the time Return: - resp: server response if successful - list: list of newsgroup names""" return self.longcmd('NEWGROUPS ' + date + ' ' + time, file)
[ "def", "newgroups", "(", "self", ",", "date", ",", "time", ",", "file", "=", "None", ")", ":", "return", "self", ".", "longcmd", "(", "'NEWGROUPS '", "+", "date", "+", "' '", "+", "time", ",", "file", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/nntplib.py#L266-L274
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TChA.ChangeCh
(self, *args)
return _snap.TChA_ChangeCh(self, *args)
ChangeCh(TChA self, char const & SrcCh, char const & DstCh) Parameters: SrcCh: char const & DstCh: char const &
ChangeCh(TChA self, char const & SrcCh, char const & DstCh)
[ "ChangeCh", "(", "TChA", "self", "char", "const", "&", "SrcCh", "char", "const", "&", "DstCh", ")" ]
def ChangeCh(self, *args): """ ChangeCh(TChA self, char const & SrcCh, char const & DstCh) Parameters: SrcCh: char const & DstCh: char const & """ return _snap.TChA_ChangeCh(self, *args)
[ "def", "ChangeCh", "(", "self", ",", "*", "args", ")", ":", "return", "_snap", ".", "TChA_ChangeCh", "(", "self", ",", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L8973-L8982
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/fft/_pocketfft.py
python
ihfft
(a, n=None, axis=-1, norm=None)
return output * (1 / (sqrt(n) if unitary else n))
Compute the inverse FFT of a signal that has Hermitian symmetry. Parameters ---------- a : array_like Input array. n : int, optional Length of the inverse FFT, the number of points along transformation axis in the input to use. If `n` is smaller than the length of the input, the input is cropped. If it is larger, the input is padded with zeros. If `n` is not given, the length of the input along the axis specified by `axis` is used. axis : int, optional Axis over which to compute the inverse FFT. If not given, the last axis is used. norm : {None, "ortho"}, optional Normalization mode (see `numpy.fft`). Default is None. .. versionadded:: 1.10.0 Returns ------- out : complex ndarray The truncated or zero-padded input, transformed along the axis indicated by `axis`, or the last one if `axis` is not specified. The length of the transformed axis is ``n//2 + 1``. See also -------- hfft, irfft Notes ----- `hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the opposite case: here the signal has Hermitian symmetry in the time domain and is real in the frequency domain. So here it's `hfft` for which you must supply the length of the result if it is to be odd: * even: ``ihfft(hfft(a, 2*len(a) - 2) == a``, within roundoff error, * odd: ``ihfft(hfft(a, 2*len(a) - 1) == a``, within roundoff error. Examples -------- >>> spectrum = np.array([ 15, -4, 0, -1, 0, -4]) >>> np.fft.ifft(spectrum) array([1.+0.j, 2.+0.j, 3.+0.j, 4.+0.j, 3.+0.j, 2.+0.j]) # may vary >>> np.fft.ihfft(spectrum) array([ 1.-0.j, 2.-0.j, 3.-0.j, 4.-0.j]) # may vary
Compute the inverse FFT of a signal that has Hermitian symmetry.
[ "Compute", "the", "inverse", "FFT", "of", "a", "signal", "that", "has", "Hermitian", "symmetry", "." ]
def ihfft(a, n=None, axis=-1, norm=None): """ Compute the inverse FFT of a signal that has Hermitian symmetry. Parameters ---------- a : array_like Input array. n : int, optional Length of the inverse FFT, the number of points along transformation axis in the input to use. If `n` is smaller than the length of the input, the input is cropped. If it is larger, the input is padded with zeros. If `n` is not given, the length of the input along the axis specified by `axis` is used. axis : int, optional Axis over which to compute the inverse FFT. If not given, the last axis is used. norm : {None, "ortho"}, optional Normalization mode (see `numpy.fft`). Default is None. .. versionadded:: 1.10.0 Returns ------- out : complex ndarray The truncated or zero-padded input, transformed along the axis indicated by `axis`, or the last one if `axis` is not specified. The length of the transformed axis is ``n//2 + 1``. See also -------- hfft, irfft Notes ----- `hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the opposite case: here the signal has Hermitian symmetry in the time domain and is real in the frequency domain. So here it's `hfft` for which you must supply the length of the result if it is to be odd: * even: ``ihfft(hfft(a, 2*len(a) - 2) == a``, within roundoff error, * odd: ``ihfft(hfft(a, 2*len(a) - 1) == a``, within roundoff error. Examples -------- >>> spectrum = np.array([ 15, -4, 0, -1, 0, -4]) >>> np.fft.ifft(spectrum) array([1.+0.j, 2.+0.j, 3.+0.j, 4.+0.j, 3.+0.j, 2.+0.j]) # may vary >>> np.fft.ihfft(spectrum) array([ 1.-0.j, 2.-0.j, 3.-0.j, 4.-0.j]) # may vary """ a = asarray(a) if n is None: n = a.shape[axis] unitary = _unitary(norm) output = conjugate(rfft(a, n, axis)) return output * (1 / (sqrt(n) if unitary else n))
[ "def", "ihfft", "(", "a", ",", "n", "=", "None", ",", "axis", "=", "-", "1", ",", "norm", "=", "None", ")", ":", "a", "=", "asarray", "(", "a", ")", "if", "n", "is", "None", ":", "n", "=", "a", ".", "shape", "[", "axis", "]", "unitary", "=", "_unitary", "(", "norm", ")", "output", "=", "conjugate", "(", "rfft", "(", "a", ",", "n", ",", "axis", ")", ")", "return", "output", "*", "(", "1", "/", "(", "sqrt", "(", "n", ")", "if", "unitary", "else", "n", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/fft/_pocketfft.py#L570-L627
vslavik/poedit
f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a
deps/boost/tools/litre/cplusplus.py
python
_caller
(up=0)
return ('', 0, '', None)
Get file name, line number, function name and source text of the caller's caller as 4-tuple: (file, line, func, text). The optional argument 'up' allows retrieval of a caller further back up into the call stack. Note, the source text may be None and function name may be '?' in the returned result. In Python 2.3+ the file name may be an absolute path.
Get file name, line number, function name and source text of the caller's caller as 4-tuple: (file, line, func, text).
[ "Get", "file", "name", "line", "number", "function", "name", "and", "source", "text", "of", "the", "caller", "s", "caller", "as", "4", "-", "tuple", ":", "(", "file", "line", "func", "text", ")", "." ]
def _caller(up=0): '''Get file name, line number, function name and source text of the caller's caller as 4-tuple: (file, line, func, text). The optional argument 'up' allows retrieval of a caller further back up into the call stack. Note, the source text may be None and function name may be '?' in the returned result. In Python 2.3+ the file name may be an absolute path. ''' try: # just get a few frames' f = traceback.extract_stack(limit=up+2) if f: return f[0] except: pass # running with psyco? return ('', 0, '', None)
[ "def", "_caller", "(", "up", "=", "0", ")", ":", "try", ":", "# just get a few frames'", "f", "=", "traceback", ".", "extract_stack", "(", "limit", "=", "up", "+", "2", ")", "if", "f", ":", "return", "f", "[", "0", "]", "except", ":", "pass", "# running with psyco?", "return", "(", "''", ",", "0", ",", "''", ",", "None", ")" ]
https://github.com/vslavik/poedit/blob/f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a/deps/boost/tools/litre/cplusplus.py#L15-L35
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/lite/python/op_hint.py
python
_LiteOperand.aggregate_and_return_name_for_input
(self, out_graphdef)
This adds the node(s) to out_graphdef and returns the input node name. Args: out_graphdef: A graphdef that is ready to have this input added. Returns: The output that the stub should use as an input for this operand. Raises: RuntimeError: if the method is not implemented.
This adds the node(s) to out_graphdef and returns the input node name.
[ "This", "adds", "the", "node", "(", "s", ")", "to", "out_graphdef", "and", "returns", "the", "input", "node", "name", "." ]
def aggregate_and_return_name_for_input(self, out_graphdef): """This adds the node(s) to out_graphdef and returns the input node name. Args: out_graphdef: A graphdef that is ready to have this input added. Returns: The output that the stub should use as an input for this operand. Raises: RuntimeError: if the method is not implemented. """ del out_graphdef raise RuntimeError("Unimplemented abstract method.")
[ "def", "aggregate_and_return_name_for_input", "(", "self", ",", "out_graphdef", ")", ":", "del", "out_graphdef", "raise", "RuntimeError", "(", "\"Unimplemented abstract method.\"", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/lite/python/op_hint.py#L480-L493
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_misc.py
python
Display.GetFromPoint
(*args, **kwargs)
return _misc_.Display_GetFromPoint(*args, **kwargs)
GetFromPoint(Point pt) -> int Find the display where the given point lies, return wx.NOT_FOUND if it doesn't belong to any display
GetFromPoint(Point pt) -> int
[ "GetFromPoint", "(", "Point", "pt", ")", "-", ">", "int" ]
def GetFromPoint(*args, **kwargs): """ GetFromPoint(Point pt) -> int Find the display where the given point lies, return wx.NOT_FOUND if it doesn't belong to any display """ return _misc_.Display_GetFromPoint(*args, **kwargs)
[ "def", "GetFromPoint", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "Display_GetFromPoint", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L6101-L6108
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/PyChop/ISISDisk.py
python
ISISDisk.getMultiWidths
(self, Ei_in=None, frequency=None)
return {"Eis":Eis, "Moderator":tmod, "Chopper":tchp, "Energy":res_el}
Returns the time widths contributing to the calculated energy width for all reps
Returns the time widths contributing to the calculated energy width for all reps
[ "Returns", "the", "time", "widths", "contributing", "to", "the", "calculated", "energy", "width", "for", "all", "reps" ]
def getMultiWidths(self, Ei_in=None, frequency=None): """ Returns the time widths contributing to the calculated energy width for all reps """ Ei = self.Ei if Ei_in is None else Ei_in if not Ei: raise ValueError('Incident energy has not been specified') if frequency: oldfreq = self.freq self.setFrequency(frequency) Eis, _, res_el, percent, _, chop_width, mod_width = self.__LETgetResolution(False, 0., Ei) if any([iname in self.instname for iname in ['MERLIN', 'MAPS', 'MARI']]): chopper_inst = ISISFermi(self.instname, self.variant, self.freq[-1]) tchp = [] tmod = [] for ee in Eis: res_el.append(chopper_inst.getResolution(0., Ei)) v_van, mod_width, chop_width = chopper_inst.getVanVar(ee) tchp.append(chop_width * 1.e6) tmod.append(mod_width * 1.e6) else: tchp = chop_width tmod = mod_width if frequency: self.setFrequency(oldfreq) return {"Eis":Eis, "Moderator":tmod, "Chopper":tchp, "Energy":res_el}
[ "def", "getMultiWidths", "(", "self", ",", "Ei_in", "=", "None", ",", "frequency", "=", "None", ")", ":", "Ei", "=", "self", ".", "Ei", "if", "Ei_in", "is", "None", "else", "Ei_in", "if", "not", "Ei", ":", "raise", "ValueError", "(", "'Incident energy has not been specified'", ")", "if", "frequency", ":", "oldfreq", "=", "self", ".", "freq", "self", ".", "setFrequency", "(", "frequency", ")", "Eis", ",", "_", ",", "res_el", ",", "percent", ",", "_", ",", "chop_width", ",", "mod_width", "=", "self", ".", "__LETgetResolution", "(", "False", ",", "0.", ",", "Ei", ")", "if", "any", "(", "[", "iname", "in", "self", ".", "instname", "for", "iname", "in", "[", "'MERLIN'", ",", "'MAPS'", ",", "'MARI'", "]", "]", ")", ":", "chopper_inst", "=", "ISISFermi", "(", "self", ".", "instname", ",", "self", ".", "variant", ",", "self", ".", "freq", "[", "-", "1", "]", ")", "tchp", "=", "[", "]", "tmod", "=", "[", "]", "for", "ee", "in", "Eis", ":", "res_el", ".", "append", "(", "chopper_inst", ".", "getResolution", "(", "0.", ",", "Ei", ")", ")", "v_van", ",", "mod_width", ",", "chop_width", "=", "chopper_inst", ".", "getVanVar", "(", "ee", ")", "tchp", ".", "append", "(", "chop_width", "*", "1.e6", ")", "tmod", ".", "append", "(", "mod_width", "*", "1.e6", ")", "else", ":", "tchp", "=", "chop_width", "tmod", "=", "mod_width", "if", "frequency", ":", "self", ".", "setFrequency", "(", "oldfreq", ")", "return", "{", "\"Eis\"", ":", "Eis", ",", "\"Moderator\"", ":", "tmod", ",", "\"Chopper\"", ":", "tchp", ",", "\"Energy\"", ":", "res_el", "}" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/PyChop/ISISDisk.py#L300-L325
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/distutils/command/sdist.py
python
sdist.read_manifest
(self)
Read the manifest file (named by 'self.manifest') and use it to fill in 'self.filelist', the list of files to include in the source distribution.
Read the manifest file (named by 'self.manifest') and use it to fill in 'self.filelist', the list of files to include in the source distribution.
[ "Read", "the", "manifest", "file", "(", "named", "by", "self", ".", "manifest", ")", "and", "use", "it", "to", "fill", "in", "self", ".", "filelist", "the", "list", "of", "files", "to", "include", "in", "the", "source", "distribution", "." ]
def read_manifest(self): """Read the manifest file (named by 'self.manifest') and use it to fill in 'self.filelist', the list of files to include in the source distribution. """ log.info("reading manifest file '%s'", self.manifest) manifest = open(self.manifest) for line in manifest: # ignore comments and blank lines line = line.strip() if line.startswith('#') or not line: continue self.filelist.append(line) manifest.close()
[ "def", "read_manifest", "(", "self", ")", ":", "log", ".", "info", "(", "\"reading manifest file '%s'\"", ",", "self", ".", "manifest", ")", "manifest", "=", "open", "(", "self", ".", "manifest", ")", "for", "line", "in", "manifest", ":", "# ignore comments and blank lines", "line", "=", "line", ".", "strip", "(", ")", "if", "line", ".", "startswith", "(", "'#'", ")", "or", "not", "line", ":", "continue", "self", ".", "filelist", ".", "append", "(", "line", ")", "manifest", ".", "close", "(", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/distutils/command/sdist.py#L386-L399
zeakey/DeepSkeleton
dc70170f8fd2ec8ca1157484ce66129981104486
scripts/cpp_lint.py
python
_NestingState.InnermostClass
(self)
return None
Get class info on the top of the stack. Returns: A _ClassInfo object if we are inside a class, or None otherwise.
Get class info on the top of the stack.
[ "Get", "class", "info", "on", "the", "top", "of", "the", "stack", "." ]
def InnermostClass(self): """Get class info on the top of the stack. Returns: A _ClassInfo object if we are inside a class, or None otherwise. """ for i in range(len(self.stack), 0, -1): classinfo = self.stack[i - 1] if isinstance(classinfo, _ClassInfo): return classinfo return None
[ "def", "InnermostClass", "(", "self", ")", ":", "for", "i", "in", "range", "(", "len", "(", "self", ".", "stack", ")", ",", "0", ",", "-", "1", ")", ":", "classinfo", "=", "self", ".", "stack", "[", "i", "-", "1", "]", "if", "isinstance", "(", "classinfo", ",", "_ClassInfo", ")", ":", "return", "classinfo", "return", "None" ]
https://github.com/zeakey/DeepSkeleton/blob/dc70170f8fd2ec8ca1157484ce66129981104486/scripts/cpp_lint.py#L2160-L2170
NVIDIA/DALI
bf16cc86ba8f091b145f91962f21fe1b6aff243d
dali/python/nvidia/dali/pipeline.py
python
Pipeline.share_outputs
(self)
Returns the outputs of the pipeline. Main difference to :meth:`outputs` is that share_outputs doesn't release returned buffers, release_outputs need to be called for that. If the pipeline is executed asynchronously, this function blocks until the results become available. It provides the user with better control about when he wants to run the pipeline, when he wants to obtain the resulting buffers and when they can be returned to DALI pool when the results have been consumed. Needs to be used together with :meth:`release_outputs` and :meth:`schedule_run` Should not be mixed with :meth:`run` in the same pipeline. :return: A list of `TensorList` objects for respective pipeline outputs
Returns the outputs of the pipeline.
[ "Returns", "the", "outputs", "of", "the", "pipeline", "." ]
def share_outputs(self): """Returns the outputs of the pipeline. Main difference to :meth:`outputs` is that share_outputs doesn't release returned buffers, release_outputs need to be called for that. If the pipeline is executed asynchronously, this function blocks until the results become available. It provides the user with better control about when he wants to run the pipeline, when he wants to obtain the resulting buffers and when they can be returned to DALI pool when the results have been consumed. Needs to be used together with :meth:`release_outputs` and :meth:`schedule_run` Should not be mixed with :meth:`run` in the same pipeline. :return: A list of `TensorList` objects for respective pipeline outputs """ with self._check_api_type_scope(types.PipelineAPIType.SCHEDULED): if self._batches_to_consume == 0 or self._gpu_batches_to_consume == 0: raise StopIteration self._batches_to_consume -= 1 self._gpu_batches_to_consume -= 1 return self._pipe.ShareOutputs()
[ "def", "share_outputs", "(", "self", ")", ":", "with", "self", ".", "_check_api_type_scope", "(", "types", ".", "PipelineAPIType", ".", "SCHEDULED", ")", ":", "if", "self", ".", "_batches_to_consume", "==", "0", "or", "self", ".", "_gpu_batches_to_consume", "==", "0", ":", "raise", "StopIteration", "self", ".", "_batches_to_consume", "-=", "1", "self", ".", "_gpu_batches_to_consume", "-=", "1", "return", "self", ".", "_pipe", ".", "ShareOutputs", "(", ")" ]
https://github.com/NVIDIA/DALI/blob/bf16cc86ba8f091b145f91962f21fe1b6aff243d/dali/python/nvidia/dali/pipeline.py#L857-L879
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/labeled_tensor/python/ops/core.py
python
_find_consistent_ordering
(a, b)
return ordering
Find the left-most consistent ordering between two lists of unique items. A consistent ordering combines all elements in both a and b while keeping all elements in their original order in both inputs. The left-most consistent ordering orders elements from `a` not found in `b` before elements in `b` not found in `a`. For example, given ['x', 'z'] and ['y', 'z'], both ['x', 'y', 'z'] and ['y', 'x', 'z'] are consistent orderings because each of the inputs appears in each consistent ordering in the same order, and ['x', 'y', 'z'] is the left-most, because 'x' appears only in `a` and 'y' appears only in `b`. In contrast, there is no consistent ordering between ['x', 'y'] and ['y', 'x']. Args: a: list with unique elements. b: list with unique elements. Returns: List containing all elements in either a or b, or None, if no consistent ordering exists.
Find the left-most consistent ordering between two lists of unique items.
[ "Find", "the", "left", "-", "most", "consistent", "ordering", "between", "two", "lists", "of", "unique", "items", "." ]
def _find_consistent_ordering(a, b): """Find the left-most consistent ordering between two lists of unique items. A consistent ordering combines all elements in both a and b while keeping all elements in their original order in both inputs. The left-most consistent ordering orders elements from `a` not found in `b` before elements in `b` not found in `a`. For example, given ['x', 'z'] and ['y', 'z'], both ['x', 'y', 'z'] and ['y', 'x', 'z'] are consistent orderings because each of the inputs appears in each consistent ordering in the same order, and ['x', 'y', 'z'] is the left-most, because 'x' appears only in `a` and 'y' appears only in `b`. In contrast, there is no consistent ordering between ['x', 'y'] and ['y', 'x']. Args: a: list with unique elements. b: list with unique elements. Returns: List containing all elements in either a or b, or None, if no consistent ordering exists. """ a_set = set(a) b_set = set(b) i = 0 j = 0 ordering = [] while i < len(a) and j < len(b): if a[i] not in b_set: ordering.append(a[i]) i += 1 elif b[j] not in a_set: ordering.append(b[j]) j += 1 elif a[i] == b[j]: ordering.append(a[i]) i += 1 j += 1 else: return None ordering.extend(a[i:]) ordering.extend(b[j:]) return ordering
[ "def", "_find_consistent_ordering", "(", "a", ",", "b", ")", ":", "a_set", "=", "set", "(", "a", ")", "b_set", "=", "set", "(", "b", ")", "i", "=", "0", "j", "=", "0", "ordering", "=", "[", "]", "while", "i", "<", "len", "(", "a", ")", "and", "j", "<", "len", "(", "b", ")", ":", "if", "a", "[", "i", "]", "not", "in", "b_set", ":", "ordering", ".", "append", "(", "a", "[", "i", "]", ")", "i", "+=", "1", "elif", "b", "[", "j", "]", "not", "in", "a_set", ":", "ordering", ".", "append", "(", "b", "[", "j", "]", ")", "j", "+=", "1", "elif", "a", "[", "i", "]", "==", "b", "[", "j", "]", ":", "ordering", ".", "append", "(", "a", "[", "i", "]", ")", "i", "+=", "1", "j", "+=", "1", "else", ":", "return", "None", "ordering", ".", "extend", "(", "a", "[", "i", ":", "]", ")", "ordering", ".", "extend", "(", "b", "[", "j", ":", "]", ")", "return", "ordering" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/labeled_tensor/python/ops/core.py#L916-L960
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
example/reinforcement-learning/a3c/launcher.py
python
submit
(args)
Submit function of local jobs.
Submit function of local jobs.
[ "Submit", "function", "of", "local", "jobs", "." ]
def submit(args): gpus = args.gpus.strip().split(',') """Submit function of local jobs.""" def mthread_submit(nworker, nserver, envs): """ customized submit script, that submit nslave jobs, each must contain args as parameter note this can be a lambda function containing additional parameters in input Parameters ---------- nworker: number of slave process to start up nserver: number of server nodes to start up envs: enviroment variables to be added to the starting programs """ procs = {} for i, gpu in enumerate(gpus): for j in range(args.num_threads): procs[i] = Thread(target=exec_cmd, args=(args.command + ['--gpus=%s'%gpu], 'worker', i*args.num_threads+j, envs)) procs[i].setDaemon(True) procs[i].start() for i in range(len(gpus)*args.num_threads, len(gpus)*args.num_threads + nserver): procs[i] = Thread(target=exec_cmd, args=(args.command, 'server', i, envs)) procs[i].setDaemon(True) procs[i].start() # call submit, with nslave, the commands to run each job and submit function tracker.submit(args.num_threads*len(gpus), args.num_servers, fun_submit=mthread_submit, pscmd=(' '.join(args.command)))
[ "def", "submit", "(", "args", ")", ":", "gpus", "=", "args", ".", "gpus", ".", "strip", "(", ")", ".", "split", "(", "','", ")", "def", "mthread_submit", "(", "nworker", ",", "nserver", ",", "envs", ")", ":", "\"\"\"\n customized submit script, that submit nslave jobs, each must contain args as parameter\n note this can be a lambda function containing additional parameters in input\n\n Parameters\n ----------\n nworker: number of slave process to start up\n nserver: number of server nodes to start up\n envs: enviroment variables to be added to the starting programs\n \"\"\"", "procs", "=", "{", "}", "for", "i", ",", "gpu", "in", "enumerate", "(", "gpus", ")", ":", "for", "j", "in", "range", "(", "args", ".", "num_threads", ")", ":", "procs", "[", "i", "]", "=", "Thread", "(", "target", "=", "exec_cmd", ",", "args", "=", "(", "args", ".", "command", "+", "[", "'--gpus=%s'", "%", "gpu", "]", ",", "'worker'", ",", "i", "*", "args", ".", "num_threads", "+", "j", ",", "envs", ")", ")", "procs", "[", "i", "]", ".", "setDaemon", "(", "True", ")", "procs", "[", "i", "]", ".", "start", "(", ")", "for", "i", "in", "range", "(", "len", "(", "gpus", ")", "*", "args", ".", "num_threads", ",", "len", "(", "gpus", ")", "*", "args", ".", "num_threads", "+", "nserver", ")", ":", "procs", "[", "i", "]", "=", "Thread", "(", "target", "=", "exec_cmd", ",", "args", "=", "(", "args", ".", "command", ",", "'server'", ",", "i", ",", "envs", ")", ")", "procs", "[", "i", "]", ".", "setDaemon", "(", "True", ")", "procs", "[", "i", "]", ".", "start", "(", ")", "# call submit, with nslave, the commands to run each job and submit function", "tracker", ".", "submit", "(", "args", ".", "num_threads", "*", "len", "(", "gpus", ")", ",", "args", ".", "num_servers", ",", "fun_submit", "=", "mthread_submit", ",", "pscmd", "=", "(", "' '", ".", "join", "(", "args", ".", "command", ")", ")", ")" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/example/reinforcement-learning/a3c/launcher.py#L79-L106
devsisters/libquic
8954789a056d8e7d5fcb6452fd1572ca57eb5c4e
src/third_party/protobuf/python/google/protobuf/internal/well_known_types.py
python
Timestamp.ToMilliseconds
(self)
return (self.seconds * _MILLIS_PER_SECOND + self.nanos // _NANOS_PER_MILLISECOND)
Converts Timestamp to milliseconds since epoch.
Converts Timestamp to milliseconds since epoch.
[ "Converts", "Timestamp", "to", "milliseconds", "since", "epoch", "." ]
def ToMilliseconds(self): """Converts Timestamp to milliseconds since epoch.""" return (self.seconds * _MILLIS_PER_SECOND + self.nanos // _NANOS_PER_MILLISECOND)
[ "def", "ToMilliseconds", "(", "self", ")", ":", "return", "(", "self", ".", "seconds", "*", "_MILLIS_PER_SECOND", "+", "self", ".", "nanos", "//", "_NANOS_PER_MILLISECOND", ")" ]
https://github.com/devsisters/libquic/blob/8954789a056d8e7d5fcb6452fd1572ca57eb5c4e/src/third_party/protobuf/python/google/protobuf/internal/well_known_types.py#L197-L200
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/dataview.py
python
DataViewCtrl.SetExpanderColumn
(*args, **kwargs)
return _dataview.DataViewCtrl_SetExpanderColumn(*args, **kwargs)
SetExpanderColumn(self, DataViewColumn col)
SetExpanderColumn(self, DataViewColumn col)
[ "SetExpanderColumn", "(", "self", "DataViewColumn", "col", ")" ]
def SetExpanderColumn(*args, **kwargs): """SetExpanderColumn(self, DataViewColumn col)""" return _dataview.DataViewCtrl_SetExpanderColumn(*args, **kwargs)
[ "def", "SetExpanderColumn", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_dataview", ".", "DataViewCtrl_SetExpanderColumn", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/dataview.py#L1723-L1725
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
net/tools/dafsa/make_dafsa.py
python
reverse
(dafsa)
return sink
Generates a new DAFSA that is reversed, so that the old sink node becomes the new source node.
Generates a new DAFSA that is reversed, so that the old sink node becomes the new source node.
[ "Generates", "a", "new", "DAFSA", "that", "is", "reversed", "so", "that", "the", "old", "sink", "node", "becomes", "the", "new", "source", "node", "." ]
def reverse(dafsa): """Generates a new DAFSA that is reversed, so that the old sink node becomes the new source node. """ sink = [] nodemap = {} def dfs(node, parent): """Creates reverse nodes. A new reverse node will be created for each old node. The new node will get a reversed label and the parents of the old node as children. """ if not node: sink.append(parent) elif id(node) not in nodemap: nodemap[id(node)] = (node[0][::-1], [parent]) for child in node[1]: dfs(child, nodemap[id(node)]) else: nodemap[id(node)][1].append(parent) for node in dafsa: dfs(node, None) return sink
[ "def", "reverse", "(", "dafsa", ")", ":", "sink", "=", "[", "]", "nodemap", "=", "{", "}", "def", "dfs", "(", "node", ",", "parent", ")", ":", "\"\"\"Creates reverse nodes.\n\n A new reverse node will be created for each old node. The new node will\n get a reversed label and the parents of the old node as children.\n \"\"\"", "if", "not", "node", ":", "sink", ".", "append", "(", "parent", ")", "elif", "id", "(", "node", ")", "not", "in", "nodemap", ":", "nodemap", "[", "id", "(", "node", ")", "]", "=", "(", "node", "[", "0", "]", "[", ":", ":", "-", "1", "]", ",", "[", "parent", "]", ")", "for", "child", "in", "node", "[", "1", "]", ":", "dfs", "(", "child", ",", "nodemap", "[", "id", "(", "node", ")", "]", ")", "else", ":", "nodemap", "[", "id", "(", "node", ")", "]", "[", "1", "]", ".", "append", "(", "parent", ")", "for", "node", "in", "dafsa", ":", "dfs", "(", "node", ",", "None", ")", "return", "sink" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/net/tools/dafsa/make_dafsa.py#L226-L250
physercoe/starquant
c00cad64d1de2da05081b3dc320ef264c6295e08
cppsrc/log4cplus-2.0.4/catch/.conan/build.py
python
BuilderSettings.channel
(self)
return os.getenv("CONAN_CHANNEL", "testing")
Default Conan package channel when not stable
Default Conan package channel when not stable
[ "Default", "Conan", "package", "channel", "when", "not", "stable" ]
def channel(self): """ Default Conan package channel when not stable """ return os.getenv("CONAN_CHANNEL", "testing")
[ "def", "channel", "(", "self", ")", ":", "return", "os", ".", "getenv", "(", "\"CONAN_CHANNEL\"", ",", "\"testing\"", ")" ]
https://github.com/physercoe/starquant/blob/c00cad64d1de2da05081b3dc320ef264c6295e08/cppsrc/log4cplus-2.0.4/catch/.conan/build.py#L55-L58
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/polynomial/_polybase.py
python
ABCPolyBase.integ
(self, m=1, k=[], lbnd=None)
return self.__class__(coef, self.domain, self.window)
Integrate. Return a series instance that is the definite integral of the current series. Parameters ---------- m : non-negative int The number of integrations to perform. k : array_like Integration constants. The first constant is applied to the first integration, the second to the second, and so on. The list of values must less than or equal to `m` in length and any missing values are set to zero. lbnd : Scalar The lower bound of the definite integral. Returns ------- new_series : series A new series representing the integral. The domain is the same as the domain of the integrated series.
Integrate.
[ "Integrate", "." ]
def integ(self, m=1, k=[], lbnd=None): """Integrate. Return a series instance that is the definite integral of the current series. Parameters ---------- m : non-negative int The number of integrations to perform. k : array_like Integration constants. The first constant is applied to the first integration, the second to the second, and so on. The list of values must less than or equal to `m` in length and any missing values are set to zero. lbnd : Scalar The lower bound of the definite integral. Returns ------- new_series : series A new series representing the integral. The domain is the same as the domain of the integrated series. """ off, scl = self.mapparms() if lbnd is None: lbnd = 0 else: lbnd = off + scl*lbnd coef = self._int(self.coef, m, k, lbnd, 1./scl) return self.__class__(coef, self.domain, self.window)
[ "def", "integ", "(", "self", ",", "m", "=", "1", ",", "k", "=", "[", "]", ",", "lbnd", "=", "None", ")", ":", "off", ",", "scl", "=", "self", ".", "mapparms", "(", ")", "if", "lbnd", "is", "None", ":", "lbnd", "=", "0", "else", ":", "lbnd", "=", "off", "+", "scl", "*", "lbnd", "coef", "=", "self", ".", "_int", "(", "self", ".", "coef", ",", "m", ",", "k", ",", "lbnd", ",", "1.", "/", "scl", ")", "return", "self", ".", "__class__", "(", "coef", ",", "self", ".", "domain", ",", "self", ".", "window", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/polynomial/_polybase.py#L708-L739
xiaohaoChen/rrc_detection
4f2b110cd122da7f55e8533275a9b4809a88785a
python/caffe/io.py
python
Transformer.set_transpose
(self, in_, order)
Set the input channel order for e.g. RGB to BGR conversion as needed for the reference ImageNet model. Parameters ---------- in_ : which input to assign this channel order order : the order to transpose the dimensions
Set the input channel order for e.g. RGB to BGR conversion as needed for the reference ImageNet model.
[ "Set", "the", "input", "channel", "order", "for", "e", ".", "g", ".", "RGB", "to", "BGR", "conversion", "as", "needed", "for", "the", "reference", "ImageNet", "model", "." ]
def set_transpose(self, in_, order): """ Set the input channel order for e.g. RGB to BGR conversion as needed for the reference ImageNet model. Parameters ---------- in_ : which input to assign this channel order order : the order to transpose the dimensions """ self.__check_input(in_) if len(order) != len(self.inputs[in_]) - 1: raise Exception('Transpose order needs to have the same number of ' 'dimensions as the input.') self.transpose[in_] = order
[ "def", "set_transpose", "(", "self", ",", "in_", ",", "order", ")", ":", "self", ".", "__check_input", "(", "in_", ")", "if", "len", "(", "order", ")", "!=", "len", "(", "self", ".", "inputs", "[", "in_", "]", ")", "-", "1", ":", "raise", "Exception", "(", "'Transpose order needs to have the same number of '", "'dimensions as the input.'", ")", "self", ".", "transpose", "[", "in_", "]", "=", "order" ]
https://github.com/xiaohaoChen/rrc_detection/blob/4f2b110cd122da7f55e8533275a9b4809a88785a/python/caffe/io.py#L187-L201
Cisco-Talos/moflow
ed71dfb0540d9e0d7a4c72f0881b58958d573728
BAP-0.7-moflow/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/containers.py
python
RepeatedCompositeFieldContainer.MergeFrom
(self, other)
Appends the contents of another repeated field of the same type to this one, copying each individual message.
Appends the contents of another repeated field of the same type to this one, copying each individual message.
[ "Appends", "the", "contents", "of", "another", "repeated", "field", "of", "the", "same", "type", "to", "this", "one", "copying", "each", "individual", "message", "." ]
def MergeFrom(self, other): """Appends the contents of another repeated field of the same type to this one, copying each individual message. """ self.extend(other._values)
[ "def", "MergeFrom", "(", "self", ",", "other", ")", ":", "self", ".", "extend", "(", "other", ".", "_values", ")" ]
https://github.com/Cisco-Talos/moflow/blob/ed71dfb0540d9e0d7a4c72f0881b58958d573728/BAP-0.7-moflow/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/containers.py#L232-L236
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/control_flow_ops.py
python
group
(*inputs, **kwargs)
Create an op that groups multiple operations. When this op finishes, all ops in `inputs` have finished. This op has no output. See also @{tf.tuple$tuple} and @{tf.control_dependencies$control_dependencies}. Args: *inputs: Zero or more tensors to group. name: A name for this operation (optional). Returns: An Operation that executes all its inputs. Raises: ValueError: If an unknown keyword argument is provided.
Create an op that groups multiple operations.
[ "Create", "an", "op", "that", "groups", "multiple", "operations", "." ]
def group(*inputs, **kwargs): """Create an op that groups multiple operations. When this op finishes, all ops in `inputs` have finished. This op has no output. See also @{tf.tuple$tuple} and @{tf.control_dependencies$control_dependencies}. Args: *inputs: Zero or more tensors to group. name: A name for this operation (optional). Returns: An Operation that executes all its inputs. Raises: ValueError: If an unknown keyword argument is provided. """ if context.in_eager_mode(): return None name = kwargs.pop("name", None) if kwargs: raise ValueError("Unknown keyword arguments: " + ", ".join(kwargs.keys())) with ops.name_scope(name, "group_deps", inputs) as name: # Grouping no inputs means do nothing if not inputs: return no_op(name=name) # Sorts *inputs according to their devices. ops_on_device = {} # device -> operations specified on the device. for inp in nest.flatten(inputs): if not hasattr(inp, "device"): raise TypeError("Expected tf.group() expected Tensor arguments not " "'%s' with type '%s'" % (inp, type(inp))) if not hasattr(inp, "device"): if isinstance(inp, list): raise TypeError("To call tf.group() with a list, use " "tf.group(*[...]) not tf.group([...]).") raise TypeError("Expected tf.group() expected Tensor arguments not " "'%s' with type '%s'" % (inp, type(inp))) dev = inp.device if dev in ops_on_device: ops_on_device[dev].append(inp) else: ops_on_device[dev] = [inp] if len(ops_on_device) == 1: # 1-level tree. The root node is the returned NoOp node. (dev, deps), = ops_on_device.items() return _GroupControlDeps(dev, deps, name=name) # 2-level tree. The root node is the returned NoOp node. # deps contains 1 NoOp node for each device. deps = [] def device_key(dev): """A sort key that allows None to be compared to strings.""" return "" if dev is None else dev for dev in sorted(six.iterkeys(ops_on_device), key=device_key): deps.append(_GroupControlDeps(dev, ops_on_device[dev])) with ops.control_dependencies(deps): return no_op(name=name)
[ "def", "group", "(", "*", "inputs", ",", "*", "*", "kwargs", ")", ":", "if", "context", ".", "in_eager_mode", "(", ")", ":", "return", "None", "name", "=", "kwargs", ".", "pop", "(", "\"name\"", ",", "None", ")", "if", "kwargs", ":", "raise", "ValueError", "(", "\"Unknown keyword arguments: \"", "+", "\", \"", ".", "join", "(", "kwargs", ".", "keys", "(", ")", ")", ")", "with", "ops", ".", "name_scope", "(", "name", ",", "\"group_deps\"", ",", "inputs", ")", "as", "name", ":", "# Grouping no inputs means do nothing", "if", "not", "inputs", ":", "return", "no_op", "(", "name", "=", "name", ")", "# Sorts *inputs according to their devices.", "ops_on_device", "=", "{", "}", "# device -> operations specified on the device.", "for", "inp", "in", "nest", ".", "flatten", "(", "inputs", ")", ":", "if", "not", "hasattr", "(", "inp", ",", "\"device\"", ")", ":", "raise", "TypeError", "(", "\"Expected tf.group() expected Tensor arguments not \"", "\"'%s' with type '%s'\"", "%", "(", "inp", ",", "type", "(", "inp", ")", ")", ")", "if", "not", "hasattr", "(", "inp", ",", "\"device\"", ")", ":", "if", "isinstance", "(", "inp", ",", "list", ")", ":", "raise", "TypeError", "(", "\"To call tf.group() with a list, use \"", "\"tf.group(*[...]) not tf.group([...]).\"", ")", "raise", "TypeError", "(", "\"Expected tf.group() expected Tensor arguments not \"", "\"'%s' with type '%s'\"", "%", "(", "inp", ",", "type", "(", "inp", ")", ")", ")", "dev", "=", "inp", ".", "device", "if", "dev", "in", "ops_on_device", ":", "ops_on_device", "[", "dev", "]", ".", "append", "(", "inp", ")", "else", ":", "ops_on_device", "[", "dev", "]", "=", "[", "inp", "]", "if", "len", "(", "ops_on_device", ")", "==", "1", ":", "# 1-level tree. The root node is the returned NoOp node.", "(", "dev", ",", "deps", ")", ",", "=", "ops_on_device", ".", "items", "(", ")", "return", "_GroupControlDeps", "(", "dev", ",", "deps", ",", "name", "=", "name", ")", "# 2-level tree. The root node is the returned NoOp node.", "# deps contains 1 NoOp node for each device.", "deps", "=", "[", "]", "def", "device_key", "(", "dev", ")", ":", "\"\"\"A sort key that allows None to be compared to strings.\"\"\"", "return", "\"\"", "if", "dev", "is", "None", "else", "dev", "for", "dev", "in", "sorted", "(", "six", ".", "iterkeys", "(", "ops_on_device", ")", ",", "key", "=", "device_key", ")", ":", "deps", ".", "append", "(", "_GroupControlDeps", "(", "dev", ",", "ops_on_device", "[", "dev", "]", ")", ")", "with", "ops", ".", "control_dependencies", "(", "deps", ")", ":", "return", "no_op", "(", "name", "=", "name", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/control_flow_ops.py#L2910-L2972
cmu-db/peloton
484d76df9344cb5c153a2c361c5d5018912d4cf4
script/formatting/formatter.py
python
format_dir
(dir_path, update_header, clang_format_code)
Formats all the files in the dir passed as argument.
Formats all the files in the dir passed as argument.
[ "Formats", "all", "the", "files", "in", "the", "dir", "passed", "as", "argument", "." ]
def format_dir(dir_path, update_header, clang_format_code): """Formats all the files in the dir passed as argument.""" for subdir, _, files in os.walk(dir_path): # _ is for directories. for file in files: #print os.path.join(subdir, file) file_path = subdir + os.path.sep + file if file_path.endswith(".h") or file_path.endswith(".cpp"): format_file(file_path, None, update_header, clang_format_code)
[ "def", "format_dir", "(", "dir_path", ",", "update_header", ",", "clang_format_code", ")", ":", "for", "subdir", ",", "_", ",", "files", "in", "os", ".", "walk", "(", "dir_path", ")", ":", "# _ is for directories.", "for", "file", "in", "files", ":", "#print os.path.join(subdir, file)", "file_path", "=", "subdir", "+", "os", ".", "path", ".", "sep", "+", "file", "if", "file_path", ".", "endswith", "(", "\".h\"", ")", "or", "file_path", ".", "endswith", "(", "\".cpp\"", ")", ":", "format_file", "(", "file_path", ",", "None", ",", "update_header", ",", "clang_format_code", ")" ]
https://github.com/cmu-db/peloton/blob/484d76df9344cb5c153a2c361c5d5018912d4cf4/script/formatting/formatter.py#L113-L121
cmu-db/noisepage
79276e68fe83322f1249e8a8be96bd63c583ae56
build-support/cpplint.py
python
ParseArguments
(args)
return filenames
Parses the command line arguments. This may set the output format and verbosity level as side-effects. Args: args: The command line arguments: Returns: The list of filenames to lint.
Parses the command line arguments.
[ "Parses", "the", "command", "line", "arguments", "." ]
def ParseArguments(args): """Parses the command line arguments. This may set the output format and verbosity level as side-effects. Args: args: The command line arguments: Returns: The list of filenames to lint. """ try: (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=', 'v=', 'version', 'counting=', 'filter=', 'root=', 'repository=', 'linelength=', 'extensions=', 'exclude=', 'recursive', 'headers=', 'quiet']) except getopt.GetoptError: PrintUsage('Invalid arguments.') verbosity = _VerboseLevel() output_format = _OutputFormat() filters = '' quiet = _Quiet() counting_style = '' recursive = False for (opt, val) in opts: if opt == '--help': PrintUsage(None) if opt == '--version': PrintVersion() elif opt == '--output': if val not in ('emacs', 'vs7', 'eclipse', 'junit'): PrintUsage('The only allowed output formats are emacs, vs7, eclipse ' 'and junit.') output_format = val elif opt == '--quiet': quiet = True elif opt == '--verbose' or opt == '--v': verbosity = int(val) elif opt == '--filter': filters = val if not filters: PrintCategories() elif opt == '--counting': if val not in ('total', 'toplevel', 'detailed'): PrintUsage('Valid counting options are total, toplevel, and detailed') counting_style = val elif opt == '--root': global _root _root = val elif opt == '--repository': global _repository _repository = val elif opt == '--linelength': global _line_length try: _line_length = int(val) except ValueError: PrintUsage('Line length must be digits.') elif opt == '--exclude': global _excludes if not _excludes: _excludes = set() _excludes.update(glob.glob(val)) elif opt == '--extensions': ProcessExtensionsOption(val) elif opt == '--headers': ProcessHppHeadersOption(val) elif opt == '--recursive': recursive = True if not filenames: PrintUsage('No files were specified.') if recursive: filenames = _ExpandDirectories(filenames) if _excludes: filenames = _FilterExcludedFiles(filenames) _SetOutputFormat(output_format) _SetQuiet(quiet) _SetVerboseLevel(verbosity) _SetFilters(filters) _SetCountingStyle(counting_style) return filenames
[ "def", "ParseArguments", "(", "args", ")", ":", "try", ":", "(", "opts", ",", "filenames", ")", "=", "getopt", ".", "getopt", "(", "args", ",", "''", ",", "[", "'help'", ",", "'output='", ",", "'verbose='", ",", "'v='", ",", "'version'", ",", "'counting='", ",", "'filter='", ",", "'root='", ",", "'repository='", ",", "'linelength='", ",", "'extensions='", ",", "'exclude='", ",", "'recursive'", ",", "'headers='", ",", "'quiet'", "]", ")", "except", "getopt", ".", "GetoptError", ":", "PrintUsage", "(", "'Invalid arguments.'", ")", "verbosity", "=", "_VerboseLevel", "(", ")", "output_format", "=", "_OutputFormat", "(", ")", "filters", "=", "''", "quiet", "=", "_Quiet", "(", ")", "counting_style", "=", "''", "recursive", "=", "False", "for", "(", "opt", ",", "val", ")", "in", "opts", ":", "if", "opt", "==", "'--help'", ":", "PrintUsage", "(", "None", ")", "if", "opt", "==", "'--version'", ":", "PrintVersion", "(", ")", "elif", "opt", "==", "'--output'", ":", "if", "val", "not", "in", "(", "'emacs'", ",", "'vs7'", ",", "'eclipse'", ",", "'junit'", ")", ":", "PrintUsage", "(", "'The only allowed output formats are emacs, vs7, eclipse '", "'and junit.'", ")", "output_format", "=", "val", "elif", "opt", "==", "'--quiet'", ":", "quiet", "=", "True", "elif", "opt", "==", "'--verbose'", "or", "opt", "==", "'--v'", ":", "verbosity", "=", "int", "(", "val", ")", "elif", "opt", "==", "'--filter'", ":", "filters", "=", "val", "if", "not", "filters", ":", "PrintCategories", "(", ")", "elif", "opt", "==", "'--counting'", ":", "if", "val", "not", "in", "(", "'total'", ",", "'toplevel'", ",", "'detailed'", ")", ":", "PrintUsage", "(", "'Valid counting options are total, toplevel, and detailed'", ")", "counting_style", "=", "val", "elif", "opt", "==", "'--root'", ":", "global", "_root", "_root", "=", "val", "elif", "opt", "==", "'--repository'", ":", "global", "_repository", "_repository", "=", "val", "elif", "opt", "==", "'--linelength'", ":", "global", "_line_length", "try", ":", "_line_length", "=", "int", "(", "val", ")", "except", "ValueError", ":", "PrintUsage", "(", "'Line length must be digits.'", ")", "elif", "opt", "==", "'--exclude'", ":", "global", "_excludes", "if", "not", "_excludes", ":", "_excludes", "=", "set", "(", ")", "_excludes", ".", "update", "(", "glob", ".", "glob", "(", "val", ")", ")", "elif", "opt", "==", "'--extensions'", ":", "ProcessExtensionsOption", "(", "val", ")", "elif", "opt", "==", "'--headers'", ":", "ProcessHppHeadersOption", "(", "val", ")", "elif", "opt", "==", "'--recursive'", ":", "recursive", "=", "True", "if", "not", "filenames", ":", "PrintUsage", "(", "'No files were specified.'", ")", "if", "recursive", ":", "filenames", "=", "_ExpandDirectories", "(", "filenames", ")", "if", "_excludes", ":", "filenames", "=", "_FilterExcludedFiles", "(", "filenames", ")", "_SetOutputFormat", "(", "output_format", ")", "_SetQuiet", "(", "quiet", ")", "_SetVerboseLevel", "(", "verbosity", ")", "_SetFilters", "(", "filters", ")", "_SetCountingStyle", "(", "counting_style", ")", "return", "filenames" ]
https://github.com/cmu-db/noisepage/blob/79276e68fe83322f1249e8a8be96bd63c583ae56/build-support/cpplint.py#L6441-L6537
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/NTableWidget.py
python
NTableWidget.get_cell_value
(self, row_index, col_index)
return return_value
Purpose: Get cell value Requirements: row index and column index are integer and within range. Guarantees: the cell value with correct type is returned :param row_index: :param col_index: :return:
Purpose: Get cell value Requirements: row index and column index are integer and within range. Guarantees: the cell value with correct type is returned :param row_index: :param col_index: :return:
[ "Purpose", ":", "Get", "cell", "value", "Requirements", ":", "row", "index", "and", "column", "index", "are", "integer", "and", "within", "range", ".", "Guarantees", ":", "the", "cell", "value", "with", "correct", "type", "is", "returned", ":", "param", "row_index", ":", ":", "param", "col_index", ":", ":", "return", ":" ]
def get_cell_value(self, row_index, col_index): """ Purpose: Get cell value Requirements: row index and column index are integer and within range. Guarantees: the cell value with correct type is returned :param row_index: :param col_index: :return: """ # check assert isinstance(row_index, int), 'Row index {0} must be an integer'.format(row_index) assert isinstance(col_index, int), 'Column index {0} must be an integer'.format(col_index) if not 0 <= row_index < self.rowCount(): raise RuntimeError('Row index {0} is out of range [0, {1})' ''.format(row_index, self.rowCount())) if not 0 <= col_index < self.columnCount(): raise RuntimeError('Column index {0} is out of range [0, {1})' ''.format(col_index, self.columnCount())) # get cell type cell_data_type = self._myColumnTypeList[col_index] if cell_data_type == 'checkbox': # Check box cell_i_j = self.cellWidget(row_index, col_index) # PyQt5 compatible issue! assert isinstance(cell_i_j, QCheckBox), 'Cell {0} {1} must be of type QCheckBox but not a {2}' \ ''.format(row_index, col_index, type(cell_i_j)) return_value = cell_i_j.isChecked() else: # Regular cell for int, float or string item_i_j = self.item(row_index, col_index) assert isinstance(item_i_j, QTableWidgetItem), 'Cell {0} {1} must be of type QTableWidgetItem but not a ' \ '{2}'.format(row_index, col_index, type(item_i_j)) # get the string of the cell return_value = str(item_i_j.text()).strip() # cast to supported if return_value == 'None' or len(return_value) == 0: # None case return_value = None elif cell_data_type.startswith('str'): # case as str of string pass elif cell_data_type.startswith('int'): # integer try: return_value = int(return_value) except ValueError as val_err: raise RuntimeError('Unable to convert cell ({0}, {1}) with value "{2}" to integer due to {3}.' ''.format(row_index, col_index, return_value, val_err)) elif cell_data_type == 'float' or cell_data_type == 'double': # float or double try: return_value = float(return_value) except ValueError as val_err: raise RuntimeError('Unable to convert cell ({0}, {1}) with value "{2}" to float due to {3}.' ''.format(row_index, col_index, return_value, val_err)) # END-IF-ELSE # END-IF-ELSE return return_value
[ "def", "get_cell_value", "(", "self", ",", "row_index", ",", "col_index", ")", ":", "# check", "assert", "isinstance", "(", "row_index", ",", "int", ")", ",", "'Row index {0} must be an integer'", ".", "format", "(", "row_index", ")", "assert", "isinstance", "(", "col_index", ",", "int", ")", ",", "'Column index {0} must be an integer'", ".", "format", "(", "col_index", ")", "if", "not", "0", "<=", "row_index", "<", "self", ".", "rowCount", "(", ")", ":", "raise", "RuntimeError", "(", "'Row index {0} is out of range [0, {1})'", "''", ".", "format", "(", "row_index", ",", "self", ".", "rowCount", "(", ")", ")", ")", "if", "not", "0", "<=", "col_index", "<", "self", ".", "columnCount", "(", ")", ":", "raise", "RuntimeError", "(", "'Column index {0} is out of range [0, {1})'", "''", ".", "format", "(", "col_index", ",", "self", ".", "columnCount", "(", ")", ")", ")", "# get cell type", "cell_data_type", "=", "self", ".", "_myColumnTypeList", "[", "col_index", "]", "if", "cell_data_type", "==", "'checkbox'", ":", "# Check box", "cell_i_j", "=", "self", ".", "cellWidget", "(", "row_index", ",", "col_index", ")", "# PyQt5 compatible issue!", "assert", "isinstance", "(", "cell_i_j", ",", "QCheckBox", ")", ",", "'Cell {0} {1} must be of type QCheckBox but not a {2}'", "''", ".", "format", "(", "row_index", ",", "col_index", ",", "type", "(", "cell_i_j", ")", ")", "return_value", "=", "cell_i_j", ".", "isChecked", "(", ")", "else", ":", "# Regular cell for int, float or string", "item_i_j", "=", "self", ".", "item", "(", "row_index", ",", "col_index", ")", "assert", "isinstance", "(", "item_i_j", ",", "QTableWidgetItem", ")", ",", "'Cell {0} {1} must be of type QTableWidgetItem but not a '", "'{2}'", ".", "format", "(", "row_index", ",", "col_index", ",", "type", "(", "item_i_j", ")", ")", "# get the string of the cell", "return_value", "=", "str", "(", "item_i_j", ".", "text", "(", ")", ")", ".", "strip", "(", ")", "# cast to supported", "if", "return_value", "==", "'None'", "or", "len", "(", "return_value", ")", "==", "0", ":", "# None case", "return_value", "=", "None", "elif", "cell_data_type", ".", "startswith", "(", "'str'", ")", ":", "# case as str of string", "pass", "elif", "cell_data_type", ".", "startswith", "(", "'int'", ")", ":", "# integer", "try", ":", "return_value", "=", "int", "(", "return_value", ")", "except", "ValueError", "as", "val_err", ":", "raise", "RuntimeError", "(", "'Unable to convert cell ({0}, {1}) with value \"{2}\" to integer due to {3}.'", "''", ".", "format", "(", "row_index", ",", "col_index", ",", "return_value", ",", "val_err", ")", ")", "elif", "cell_data_type", "==", "'float'", "or", "cell_data_type", "==", "'double'", ":", "# float or double", "try", ":", "return_value", "=", "float", "(", "return_value", ")", "except", "ValueError", "as", "val_err", ":", "raise", "RuntimeError", "(", "'Unable to convert cell ({0}, {1}) with value \"{2}\" to float due to {3}.'", "''", ".", "format", "(", "row_index", ",", "col_index", ",", "return_value", ",", "val_err", ")", ")", "# END-IF-ELSE", "# END-IF-ELSE", "return", "return_value" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/NTableWidget.py#L151-L214
yuxng/PoseCNN
9f3dd7b7bce21dcafc05e8f18ccc90da3caabd04
lib/datasets/sym.py
python
sym._load_sym_annotation
(self, index)
return {'image': image_path, 'depth': depth_path, 'label': label_path, 'meta_data': metadata_path, 'class_colors': self._class_colors, 'class_weights': self._class_weights, 'cls_index': -1, 'flipped': False}
Load class name and meta data
Load class name and meta data
[ "Load", "class", "name", "and", "meta", "data" ]
def _load_sym_annotation(self, index): """ Load class name and meta data """ # image path image_path = self.image_path_from_index(index) # depth path depth_path = self.depth_path_from_index(index) # label path label_path = self.label_path_from_index(index) # metadata path metadata_path = self.metadata_path_from_index(index) return {'image': image_path, 'depth': depth_path, 'label': label_path, 'meta_data': metadata_path, 'class_colors': self._class_colors, 'class_weights': self._class_weights, 'cls_index': -1, 'flipped': False}
[ "def", "_load_sym_annotation", "(", "self", ",", "index", ")", ":", "# image path", "image_path", "=", "self", ".", "image_path_from_index", "(", "index", ")", "# depth path", "depth_path", "=", "self", ".", "depth_path_from_index", "(", "index", ")", "# label path", "label_path", "=", "self", ".", "label_path_from_index", "(", "index", ")", "# metadata path", "metadata_path", "=", "self", ".", "metadata_path_from_index", "(", "index", ")", "return", "{", "'image'", ":", "image_path", ",", "'depth'", ":", "depth_path", ",", "'label'", ":", "label_path", ",", "'meta_data'", ":", "metadata_path", ",", "'class_colors'", ":", "self", ".", "_class_colors", ",", "'class_weights'", ":", "self", ".", "_class_weights", ",", "'cls_index'", ":", "-", "1", ",", "'flipped'", ":", "False", "}" ]
https://github.com/yuxng/PoseCNN/blob/9f3dd7b7bce21dcafc05e8f18ccc90da3caabd04/lib/datasets/sym.py#L208-L231
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pdb.py
python
Pdb.do_undisplay
(self, arg)
undisplay [expression] Do not display the expression any more in the current frame. Without expression, clear all display expressions for the current frame.
undisplay [expression]
[ "undisplay", "[", "expression", "]" ]
def do_undisplay(self, arg): """undisplay [expression] Do not display the expression any more in the current frame. Without expression, clear all display expressions for the current frame. """ if arg: try: del self.displaying.get(self.curframe, {})[arg] except KeyError: self.error('not displaying %s' % arg) else: self.displaying.pop(self.curframe, None)
[ "def", "do_undisplay", "(", "self", ",", "arg", ")", ":", "if", "arg", ":", "try", ":", "del", "self", ".", "displaying", ".", "get", "(", "self", ".", "curframe", ",", "{", "}", ")", "[", "arg", "]", "except", "KeyError", ":", "self", ".", "error", "(", "'not displaying %s'", "%", "arg", ")", "else", ":", "self", ".", "displaying", ".", "pop", "(", "self", ".", "curframe", ",", "None", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pdb.py#L1353-L1366
rdiankov/openrave
d1a23023fd4b58f077d2ca949ceaf1b91f3f13d7
python/ikfast_sympy0_6.py
python
IKFastSolver.GetSolvers
()
return {'transform6d':IKFastSolver.solveFullIK_6D, 'rotation3d':IKFastSolver.solveFullIK_Rotation3D, 'translation3d':IKFastSolver.solveFullIK_Translation3D, 'direction3d':IKFastSolver.solveFullIK_Direction3D, 'ray4d':IKFastSolver.solveFullIK_Ray4D, 'lookat3d':IKFastSolver.solveFullIK_Lookat3D, 'translationdirection5d':IKFastSolver.solveFullIK_TranslationDirection5D, 'translationxy2d':IKFastSolver.solveFullIK_TranslationXY2D, 'translationxyorientation3d':IKFastSolver.solveFullIK_TranslationXYOrientation3D, 'translationxaxisangle4d':IKFastSolver.solveFullIK_TranslationAxisAngle4D, 'translationyaxisangle4d':IKFastSolver.solveFullIK_TranslationAxisAngle4D, 'translationzaxisangle4d':IKFastSolver.solveFullIK_TranslationAxisAngle4D, 'translationxaxisangleznorm4d':IKFastSolver.solveFullIK_TranslationAxisAngle4D, 'translationyaxisanglexnorm4d':IKFastSolver.solveFullIK_TranslationAxisAngle4D, 'translationzaxisangleynorm4d':IKFastSolver.solveFullIK_TranslationAxisAngle4D }
Returns a dictionary of all the supported solvers and their official identifier names
Returns a dictionary of all the supported solvers and their official identifier names
[ "Returns", "a", "dictionary", "of", "all", "the", "supported", "solvers", "and", "their", "official", "identifier", "names" ]
def GetSolvers(): """Returns a dictionary of all the supported solvers and their official identifier names""" return {'transform6d':IKFastSolver.solveFullIK_6D, 'rotation3d':IKFastSolver.solveFullIK_Rotation3D, 'translation3d':IKFastSolver.solveFullIK_Translation3D, 'direction3d':IKFastSolver.solveFullIK_Direction3D, 'ray4d':IKFastSolver.solveFullIK_Ray4D, 'lookat3d':IKFastSolver.solveFullIK_Lookat3D, 'translationdirection5d':IKFastSolver.solveFullIK_TranslationDirection5D, 'translationxy2d':IKFastSolver.solveFullIK_TranslationXY2D, 'translationxyorientation3d':IKFastSolver.solveFullIK_TranslationXYOrientation3D, 'translationxaxisangle4d':IKFastSolver.solveFullIK_TranslationAxisAngle4D, 'translationyaxisangle4d':IKFastSolver.solveFullIK_TranslationAxisAngle4D, 'translationzaxisangle4d':IKFastSolver.solveFullIK_TranslationAxisAngle4D, 'translationxaxisangleznorm4d':IKFastSolver.solveFullIK_TranslationAxisAngle4D, 'translationyaxisanglexnorm4d':IKFastSolver.solveFullIK_TranslationAxisAngle4D, 'translationzaxisangleynorm4d':IKFastSolver.solveFullIK_TranslationAxisAngle4D }
[ "def", "GetSolvers", "(", ")", ":", "return", "{", "'transform6d'", ":", "IKFastSolver", ".", "solveFullIK_6D", ",", "'rotation3d'", ":", "IKFastSolver", ".", "solveFullIK_Rotation3D", ",", "'translation3d'", ":", "IKFastSolver", ".", "solveFullIK_Translation3D", ",", "'direction3d'", ":", "IKFastSolver", ".", "solveFullIK_Direction3D", ",", "'ray4d'", ":", "IKFastSolver", ".", "solveFullIK_Ray4D", ",", "'lookat3d'", ":", "IKFastSolver", ".", "solveFullIK_Lookat3D", ",", "'translationdirection5d'", ":", "IKFastSolver", ".", "solveFullIK_TranslationDirection5D", ",", "'translationxy2d'", ":", "IKFastSolver", ".", "solveFullIK_TranslationXY2D", ",", "'translationxyorientation3d'", ":", "IKFastSolver", ".", "solveFullIK_TranslationXYOrientation3D", ",", "'translationxaxisangle4d'", ":", "IKFastSolver", ".", "solveFullIK_TranslationAxisAngle4D", ",", "'translationyaxisangle4d'", ":", "IKFastSolver", ".", "solveFullIK_TranslationAxisAngle4D", ",", "'translationzaxisangle4d'", ":", "IKFastSolver", ".", "solveFullIK_TranslationAxisAngle4D", ",", "'translationxaxisangleznorm4d'", ":", "IKFastSolver", ".", "solveFullIK_TranslationAxisAngle4D", ",", "'translationyaxisanglexnorm4d'", ":", "IKFastSolver", ".", "solveFullIK_TranslationAxisAngle4D", ",", "'translationzaxisangleynorm4d'", ":", "IKFastSolver", ".", "solveFullIK_TranslationAxisAngle4D", "}" ]
https://github.com/rdiankov/openrave/blob/d1a23023fd4b58f077d2ca949ceaf1b91f3f13d7/python/ikfast_sympy0_6.py#L5732-L5749
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/grit/grit/gather/policy_json.py
python
PolicyJson._AddMessages
(self)
Processed and adds the 'messages' section to the output.
Processed and adds the 'messages' section to the output.
[ "Processed", "and", "adds", "the", "messages", "section", "to", "the", "output", "." ]
def _AddMessages(self): '''Processed and adds the 'messages' section to the output.''' self._AddNontranslateableChunk(" 'messages': {\n") for name, message in self.data['messages'].iteritems(): self._AddNontranslateableChunk(" '%s': {\n" % name) self._AddNontranslateableChunk(" 'text': '''") self._ParseMessage(message['text'], message['desc']) self._AddNontranslateableChunk("'''\n") self._AddNontranslateableChunk(" },\n") self._AddNontranslateableChunk(" },\n")
[ "def", "_AddMessages", "(", "self", ")", ":", "self", ".", "_AddNontranslateableChunk", "(", "\" 'messages': {\\n\"", ")", "for", "name", ",", "message", "in", "self", ".", "data", "[", "'messages'", "]", ".", "iteritems", "(", ")", ":", "self", ".", "_AddNontranslateableChunk", "(", "\" '%s': {\\n\"", "%", "name", ")", "self", ".", "_AddNontranslateableChunk", "(", "\" 'text': '''\"", ")", "self", ".", "_ParseMessage", "(", "message", "[", "'text'", "]", ",", "message", "[", "'desc'", "]", ")", "self", ".", "_AddNontranslateableChunk", "(", "\"'''\\n\"", ")", "self", ".", "_AddNontranslateableChunk", "(", "\" },\\n\"", ")", "self", ".", "_AddNontranslateableChunk", "(", "\" },\\n\"", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/grit/grit/gather/policy_json.py#L215-L224
google/llvm-propeller
45c226984fe8377ebfb2ad7713c680d652ba678d
clang/bindings/python/clang/cindex.py
python
SourceRange.end
(self)
return conf.lib.clang_getRangeEnd(self)
Return a SourceLocation representing the last character within a source range.
Return a SourceLocation representing the last character within a source range.
[ "Return", "a", "SourceLocation", "representing", "the", "last", "character", "within", "a", "source", "range", "." ]
def end(self): """ Return a SourceLocation representing the last character within a source range. """ return conf.lib.clang_getRangeEnd(self)
[ "def", "end", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_getRangeEnd", "(", "self", ")" ]
https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/clang/bindings/python/clang/cindex.py#L328-L333
openthread/openthread
9fcdbed9c526c70f1556d1ed84099c1535c7cd32
tools/otci/otci/otci.py
python
OTCI.get_eidcache
(self)
return cache
Get the EID-to-RLOC cache entries.
Get the EID-to-RLOC cache entries.
[ "Get", "the", "EID", "-", "to", "-", "RLOC", "cache", "entries", "." ]
def get_eidcache(self) -> Dict[Ip6Addr, Rloc16]: """Get the EID-to-RLOC cache entries.""" output = self.execute_command('eidcache') cache = {} for line in output: ip, rloc16, _ = line.split(" ", 2) cache[Ip6Addr(ip)] = Rloc16(rloc16, 16) return cache
[ "def", "get_eidcache", "(", "self", ")", "->", "Dict", "[", "Ip6Addr", ",", "Rloc16", "]", ":", "output", "=", "self", ".", "execute_command", "(", "'eidcache'", ")", "cache", "=", "{", "}", "for", "line", "in", "output", ":", "ip", ",", "rloc16", ",", "_", "=", "line", ".", "split", "(", "\" \"", ",", "2", ")", "cache", "[", "Ip6Addr", "(", "ip", ")", "]", "=", "Rloc16", "(", "rloc16", ",", "16", ")", "return", "cache" ]
https://github.com/openthread/openthread/blob/9fcdbed9c526c70f1556d1ed84099c1535c7cd32/tools/otci/otci/otci.py#L2160-L2170
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/httplib2/upload-diffs.py
python
GetSubversionPropertyChanges
(filename)
return None
Return a Subversion's 'Property changes on ...' string, which is used in the patch file. Args: filename: filename whose property might be set by [auto-props] config. Returns: A string like 'Property changes on |filename| ...' if given |filename| matches any entries in [auto-props] section. None, otherwise.
Return a Subversion's 'Property changes on ...' string, which is used in the patch file.
[ "Return", "a", "Subversion", "s", "Property", "changes", "on", "...", "string", "which", "is", "used", "in", "the", "patch", "file", "." ]
def GetSubversionPropertyChanges(filename): """Return a Subversion's 'Property changes on ...' string, which is used in the patch file. Args: filename: filename whose property might be set by [auto-props] config. Returns: A string like 'Property changes on |filename| ...' if given |filename| matches any entries in [auto-props] section. None, otherwise. """ global svn_auto_props_map if svn_auto_props_map is None: svn_auto_props_map = LoadSubversionAutoProperties() all_props = [] for file_pattern, props in svn_auto_props_map.items(): if fnmatch.fnmatch(filename, file_pattern): all_props.extend(props) if all_props: return FormatSubversionPropertyChanges(filename, all_props) return None
[ "def", "GetSubversionPropertyChanges", "(", "filename", ")", ":", "global", "svn_auto_props_map", "if", "svn_auto_props_map", "is", "None", ":", "svn_auto_props_map", "=", "LoadSubversionAutoProperties", "(", ")", "all_props", "=", "[", "]", "for", "file_pattern", ",", "props", "in", "svn_auto_props_map", ".", "items", "(", ")", ":", "if", "fnmatch", ".", "fnmatch", "(", "filename", ",", "file_pattern", ")", ":", "all_props", ".", "extend", "(", "props", ")", "if", "all_props", ":", "return", "FormatSubversionPropertyChanges", "(", "filename", ",", "all_props", ")", "return", "None" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/httplib2/upload-diffs.py#L2143-L2164
PyMesh/PyMesh
384ba882b7558ba6e8653ed263c419226c22bddf
python/pymesh/predicates.py
python
orient_2D
(p1, p2, p3)
return PyMesh.orient2d(p1, p2, p3)
Determine the orientation 2D points p1, p2, p3 Args: p1,p2,p3: 2D points. Returns: positive if (p1, p2, p3) is in counterclockwise order. negative if (p1, p2, p3) is in clockwise order. 0.0 if they are collinear.
Determine the orientation 2D points p1, p2, p3
[ "Determine", "the", "orientation", "2D", "points", "p1", "p2", "p3" ]
def orient_2D(p1, p2, p3): """ Determine the orientation 2D points p1, p2, p3 Args: p1,p2,p3: 2D points. Returns: positive if (p1, p2, p3) is in counterclockwise order. negative if (p1, p2, p3) is in clockwise order. 0.0 if they are collinear. """ return PyMesh.orient2d(p1, p2, p3)
[ "def", "orient_2D", "(", "p1", ",", "p2", ",", "p3", ")", ":", "return", "PyMesh", ".", "orient2d", "(", "p1", ",", "p2", ",", "p3", ")" ]
https://github.com/PyMesh/PyMesh/blob/384ba882b7558ba6e8653ed263c419226c22bddf/python/pymesh/predicates.py#L10-L21
freeorion/freeorion
c266a40eccd3a99a17de8fe57c36ef6ba3771665
default/python/AI/MilitaryAI.py
python
Allocator._jump2_threat
(self)
return get_system_jump2_threat(self.sys_id)
Military rating of enemies present 2 jumps away from the system.
Military rating of enemies present 2 jumps away from the system.
[ "Military", "rating", "of", "enemies", "present", "2", "jumps", "away", "from", "the", "system", "." ]
def _jump2_threat(self): """Military rating of enemies present 2 jumps away from the system.""" return get_system_jump2_threat(self.sys_id)
[ "def", "_jump2_threat", "(", "self", ")", ":", "return", "get_system_jump2_threat", "(", "self", ".", "sys_id", ")" ]
https://github.com/freeorion/freeorion/blob/c266a40eccd3a99a17de8fe57c36ef6ba3771665/default/python/AI/MilitaryAI.py#L406-L408
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_gdi.py
python
DC.DrawRectanglePointSize
(*args, **kwargs)
return _gdi_.DC_DrawRectanglePointSize(*args, **kwargs)
DrawRectanglePointSize(self, Point pt, Size sz) Draws a rectangle with the given top left corner, and with the given size. The current pen is used for the outline and the current brush for filling the shape.
DrawRectanglePointSize(self, Point pt, Size sz)
[ "DrawRectanglePointSize", "(", "self", "Point", "pt", "Size", "sz", ")" ]
def DrawRectanglePointSize(*args, **kwargs): """ DrawRectanglePointSize(self, Point pt, Size sz) Draws a rectangle with the given top left corner, and with the given size. The current pen is used for the outline and the current brush for filling the shape. """ return _gdi_.DC_DrawRectanglePointSize(*args, **kwargs)
[ "def", "DrawRectanglePointSize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "DC_DrawRectanglePointSize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L3558-L3566
Studio3T/robomongo
2411cd032e2e69b968dadda13ac91ca4ef3483b0
src/third-party/qscintilla-2.8.4/sources/Python/configure.py
python
ModuleConfiguration.inform_user
(self, target_configuration)
Inform the user about module specific configuration information. target_configuration is the target configuration.
Inform the user about module specific configuration information. target_configuration is the target configuration.
[ "Inform", "the", "user", "about", "module", "specific", "configuration", "information", ".", "target_configuration", "is", "the", "target", "configuration", "." ]
def inform_user(self, target_configuration): """ Inform the user about module specific configuration information. target_configuration is the target configuration. """ inform("QScintilla %s is being used." % target_configuration.qsci_version) if target_configuration.qsci_sip_dir != '': inform("The QScintilla .sip files will be installed in %s." % target_configuration.qsci_sip_dir)
[ "def", "inform_user", "(", "self", ",", "target_configuration", ")", ":", "inform", "(", "\"QScintilla %s is being used.\"", "%", "target_configuration", ".", "qsci_version", ")", "if", "target_configuration", ".", "qsci_sip_dir", "!=", "''", ":", "inform", "(", "\"The QScintilla .sip files will be installed in %s.\"", "%", "target_configuration", ".", "qsci_sip_dir", ")" ]
https://github.com/Studio3T/robomongo/blob/2411cd032e2e69b968dadda13ac91ca4ef3483b0/src/third-party/qscintilla-2.8.4/sources/Python/configure.py#L235-L245
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_controls.py
python
FilePickerCtrl.GetTextCtrlValue
(*args, **kwargs)
return _controls_.FilePickerCtrl_GetTextCtrlValue(*args, **kwargs)
GetTextCtrlValue(self) -> String
GetTextCtrlValue(self) -> String
[ "GetTextCtrlValue", "(", "self", ")", "-", ">", "String" ]
def GetTextCtrlValue(*args, **kwargs): """GetTextCtrlValue(self) -> String""" return _controls_.FilePickerCtrl_GetTextCtrlValue(*args, **kwargs)
[ "def", "GetTextCtrlValue", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "FilePickerCtrl_GetTextCtrlValue", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L7128-L7130
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/lib/debug_data.py
python
DebugTensorDatum.debug_op
(self)
return self._debug_op
Name of the debug op. Returns: (`str`) debug op name (e.g., `DebugIdentity`).
Name of the debug op.
[ "Name", "of", "the", "debug", "op", "." ]
def debug_op(self): """Name of the debug op. Returns: (`str`) debug op name (e.g., `DebugIdentity`). """ return self._debug_op
[ "def", "debug_op", "(", "self", ")", ":", "return", "self", ".", "_debug_op" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/lib/debug_data.py#L378-L385
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/rexec.py
python
RExec.r_reload
(self, m)
return self.importer.reload(m)
Reload the module object, re-parsing and re-initializing it. This method is implicitly called by code executing in the restricted environment. Overriding this method in a subclass is used to change the policies enforced by a restricted environment.
Reload the module object, re-parsing and re-initializing it.
[ "Reload", "the", "module", "object", "re", "-", "parsing", "and", "re", "-", "initializing", "it", "." ]
def r_reload(self, m): """Reload the module object, re-parsing and re-initializing it. This method is implicitly called by code executing in the restricted environment. Overriding this method in a subclass is used to change the policies enforced by a restricted environment. """ return self.importer.reload(m)
[ "def", "r_reload", "(", "self", ",", "m", ")", ":", "return", "self", ".", "importer", ".", "reload", "(", "m", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/rexec.py#L349-L357
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/cloudsearch/layer1.py
python
Layer1.describe_domains
(self, domain_names=None)
return self.get_response(doc_path, 'DescribeDomains', params, verb='POST', list_marker='DomainStatusList')
Describes the domains (optionally limited to one or more domains by name) owned by this account. :type domain_names: list :param domain_names: Limits the response to the specified domains. :raises: BaseException, InternalException
Describes the domains (optionally limited to one or more domains by name) owned by this account.
[ "Describes", "the", "domains", "(", "optionally", "limited", "to", "one", "or", "more", "domains", "by", "name", ")", "owned", "by", "this", "account", "." ]
def describe_domains(self, domain_names=None): """ Describes the domains (optionally limited to one or more domains by name) owned by this account. :type domain_names: list :param domain_names: Limits the response to the specified domains. :raises: BaseException, InternalException """ doc_path = ('describe_domains_response', 'describe_domains_result', 'domain_status_list') params = {} if domain_names: for i, domain_name in enumerate(domain_names, 1): params['DomainNames.member.%d' % i] = domain_name return self.get_response(doc_path, 'DescribeDomains', params, verb='POST', list_marker='DomainStatusList')
[ "def", "describe_domains", "(", "self", ",", "domain_names", "=", "None", ")", ":", "doc_path", "=", "(", "'describe_domains_response'", ",", "'describe_domains_result'", ",", "'domain_status_list'", ")", "params", "=", "{", "}", "if", "domain_names", ":", "for", "i", ",", "domain_name", "in", "enumerate", "(", "domain_names", ",", "1", ")", ":", "params", "[", "'DomainNames.member.%d'", "%", "i", "]", "=", "domain_name", "return", "self", ".", "get_response", "(", "doc_path", ",", "'DescribeDomains'", ",", "params", ",", "verb", "=", "'POST'", ",", "list_marker", "=", "'DomainStatusList'", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/cloudsearch/layer1.py#L398-L417
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
python/mxnet/kvstore.py
python
KVStore.load_optimizer_states
(self, fname)
Loads the optimizer (updater) state from the file. Parameters ---------- fname : str Path to input states file.
Loads the optimizer (updater) state from the file.
[ "Loads", "the", "optimizer", "(", "updater", ")", "state", "from", "the", "file", "." ]
def load_optimizer_states(self, fname): """Loads the optimizer (updater) state from the file. Parameters ---------- fname : str Path to input states file. """ assert self._updater is not None, "Cannot load states for distributed training" self._updater.set_states(open(fname, 'rb').read())
[ "def", "load_optimizer_states", "(", "self", ",", "fname", ")", ":", "assert", "self", ".", "_updater", "is", "not", "None", ",", "\"Cannot load states for distributed training\"", "self", ".", "_updater", ".", "set_states", "(", "open", "(", "fname", ",", "'rb'", ")", ".", "read", "(", ")", ")" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/kvstore.py#L554-L563
tensorflow/deepmath
b5b721f54de1d5d6a02d78f5da5995237f9995f9
deepmath/treegen/cnf_train.py
python
evaluate
(hparams)
Evaluate a model under training repeatedly.
Evaluate a model under training repeatedly.
[ "Evaluate", "a", "model", "under", "training", "repeatedly", "." ]
def evaluate(hparams): """Evaluate a model under training repeatedly.""" data_iterator, clause_metadata = load_data(random_start=False) if FLAGS.model_type == 'tree': m = cnf_model.CNFTreeModel(data_iterator, hparams, clause_metadata) else: m = cnf_model.CNFSequenceModel(data_iterator, hparams, clause_metadata) all_metrics = [m.loss] + m.metrics.values() mean_values, mean_updates = zip(*(metrics.streaming_mean(v) for v in all_metrics)) tf.contrib.deprecated.scalar_summary('loss', mean_values[0]) for i, metric_name in enumerate(m.metrics.iterkeys()): tf.contrib.deprecated.scalar_summary('metric/' + metric_name, mean_values[i + 1]) num_evals = (FLAGS.eval_lines - 1) // hparams.batch_size + 1 slim.evaluation.evaluation_loop( FLAGS.master, FLAGS.eval_dir, FLAGS.tf_log_dir, num_evals, eval_op=tf.group(*mean_updates), eval_interval_secs=FLAGS.eval_interval_secs, # This resets the data iterator to the beginning of the file, so that # exactly the same lines are evaluated each loop iteration. # A py_func must return something convertible to a tensor; reset() returns # None, and reset() or "" returns "". final_op=tf.py_func(lambda: data_iterator.reset() or '', [], [tf.string]))
[ "def", "evaluate", "(", "hparams", ")", ":", "data_iterator", ",", "clause_metadata", "=", "load_data", "(", "random_start", "=", "False", ")", "if", "FLAGS", ".", "model_type", "==", "'tree'", ":", "m", "=", "cnf_model", ".", "CNFTreeModel", "(", "data_iterator", ",", "hparams", ",", "clause_metadata", ")", "else", ":", "m", "=", "cnf_model", ".", "CNFSequenceModel", "(", "data_iterator", ",", "hparams", ",", "clause_metadata", ")", "all_metrics", "=", "[", "m", ".", "loss", "]", "+", "m", ".", "metrics", ".", "values", "(", ")", "mean_values", ",", "mean_updates", "=", "zip", "(", "*", "(", "metrics", ".", "streaming_mean", "(", "v", ")", "for", "v", "in", "all_metrics", ")", ")", "tf", ".", "contrib", ".", "deprecated", ".", "scalar_summary", "(", "'loss'", ",", "mean_values", "[", "0", "]", ")", "for", "i", ",", "metric_name", "in", "enumerate", "(", "m", ".", "metrics", ".", "iterkeys", "(", ")", ")", ":", "tf", ".", "contrib", ".", "deprecated", ".", "scalar_summary", "(", "'metric/'", "+", "metric_name", ",", "mean_values", "[", "i", "+", "1", "]", ")", "num_evals", "=", "(", "FLAGS", ".", "eval_lines", "-", "1", ")", "//", "hparams", ".", "batch_size", "+", "1", "slim", ".", "evaluation", ".", "evaluation_loop", "(", "FLAGS", ".", "master", ",", "FLAGS", ".", "eval_dir", ",", "FLAGS", ".", "tf_log_dir", ",", "num_evals", ",", "eval_op", "=", "tf", ".", "group", "(", "*", "mean_updates", ")", ",", "eval_interval_secs", "=", "FLAGS", ".", "eval_interval_secs", ",", "# This resets the data iterator to the beginning of the file, so that", "# exactly the same lines are evaluated each loop iteration.", "# A py_func must return something convertible to a tensor; reset() returns", "# None, and reset() or \"\" returns \"\".", "final_op", "=", "tf", ".", "py_func", "(", "lambda", ":", "data_iterator", ".", "reset", "(", ")", "or", "''", ",", "[", "]", ",", "[", "tf", ".", "string", "]", ")", ")" ]
https://github.com/tensorflow/deepmath/blob/b5b721f54de1d5d6a02d78f5da5995237f9995f9/deepmath/treegen/cnf_train.py#L210-L240
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/eclib/ctrlbox.py
python
SegmentBar.GetSegmentLabel
(self, index)
return self._buttons[index].Label
Get the label of the given segment @param index: segment index @return: string
Get the label of the given segment @param index: segment index @return: string
[ "Get", "the", "label", "of", "the", "given", "segment", "@param", "index", ":", "segment", "index", "@return", ":", "string" ]
def GetSegmentLabel(self, index): """Get the label of the given segment @param index: segment index @return: string """ return self._buttons[index].Label
[ "def", "GetSegmentLabel", "(", "self", ",", "index", ")", ":", "return", "self", ".", "_buttons", "[", "index", "]", ".", "Label" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/eclib/ctrlbox.py#L920-L926
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/graph_editor/select.py
python
filter_ts_from_regex
(ops, regex)
return filter_ts(ops, positive_filter=lambda op: regex_obj.search(op.name))
r"""Get all the tensors linked to ops that match the given regex. Args: ops: an object convertible to a list of tf.Operation. regex: a regular expression matching the tensors' name. For example, "^foo(/.*)?:\d+$" will match all the tensors in the "foo" scope. Returns: A list of tf.Tensor. Raises: TypeError: if ops cannot be converted to a list of tf.Operation.
r"""Get all the tensors linked to ops that match the given regex.
[ "r", "Get", "all", "the", "tensors", "linked", "to", "ops", "that", "match", "the", "given", "regex", "." ]
def filter_ts_from_regex(ops, regex): r"""Get all the tensors linked to ops that match the given regex. Args: ops: an object convertible to a list of tf.Operation. regex: a regular expression matching the tensors' name. For example, "^foo(/.*)?:\d+$" will match all the tensors in the "foo" scope. Returns: A list of tf.Tensor. Raises: TypeError: if ops cannot be converted to a list of tf.Operation. """ ops = util.make_list_of_op(ops) regex_obj = make_regex(regex) return filter_ts(ops, positive_filter=lambda op: regex_obj.search(op.name))
[ "def", "filter_ts_from_regex", "(", "ops", ",", "regex", ")", ":", "ops", "=", "util", ".", "make_list_of_op", "(", "ops", ")", "regex_obj", "=", "make_regex", "(", "regex", ")", "return", "filter_ts", "(", "ops", ",", "positive_filter", "=", "lambda", "op", ":", "regex_obj", ".", "search", "(", "op", ".", "name", ")", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/graph_editor/select.py#L135-L150
gnuradio/gnuradio
09c3c4fa4bfb1a02caac74cb5334dfe065391e3b
gr-utils/modtool/core/info.py
python
ModToolInfo._get_base_dir
(self, start_dir)
return None
Figure out the base dir (where the top-level cmake file is)
Figure out the base dir (where the top-level cmake file is)
[ "Figure", "out", "the", "base", "dir", "(", "where", "the", "top", "-", "level", "cmake", "file", "is", ")" ]
def _get_base_dir(self, start_dir): """ Figure out the base dir (where the top-level cmake file is) """ base_dir = os.path.abspath(start_dir) if self._check_directory(base_dir): return base_dir else: (up_dir, this_dir) = os.path.split(base_dir) if os.path.split(up_dir)[1] == 'include': up_dir = os.path.split(up_dir)[0] if self._check_directory(up_dir): return up_dir return None
[ "def", "_get_base_dir", "(", "self", ",", "start_dir", ")", ":", "base_dir", "=", "os", ".", "path", ".", "abspath", "(", "start_dir", ")", "if", "self", ".", "_check_directory", "(", "base_dir", ")", ":", "return", "base_dir", "else", ":", "(", "up_dir", ",", "this_dir", ")", "=", "os", ".", "path", ".", "split", "(", "base_dir", ")", "if", "os", ".", "path", ".", "split", "(", "up_dir", ")", "[", "1", "]", "==", "'include'", ":", "up_dir", "=", "os", ".", "path", ".", "split", "(", "up_dir", ")", "[", "0", "]", "if", "self", ".", "_check_directory", "(", "up_dir", ")", ":", "return", "up_dir", "return", "None" ]
https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gr-utils/modtool/core/info.py#L71-L82
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/email/_parseaddr.py
python
mktime_tz
(data)
Turn a 10-tuple as returned by parsedate_tz() into a POSIX timestamp.
Turn a 10-tuple as returned by parsedate_tz() into a POSIX timestamp.
[ "Turn", "a", "10", "-", "tuple", "as", "returned", "by", "parsedate_tz", "()", "into", "a", "POSIX", "timestamp", "." ]
def mktime_tz(data): """Turn a 10-tuple as returned by parsedate_tz() into a POSIX timestamp.""" if data[9] is None: # No zone info, so localtime is better assumption than GMT return time.mktime(data[:8] + (-1,)) else: t = calendar.timegm(data) return t - data[9]
[ "def", "mktime_tz", "(", "data", ")", ":", "if", "data", "[", "9", "]", "is", "None", ":", "# No zone info, so localtime is better assumption than GMT", "return", "time", ".", "mktime", "(", "data", "[", ":", "8", "]", "+", "(", "-", "1", ",", ")", ")", "else", ":", "t", "=", "calendar", ".", "timegm", "(", "data", ")", "return", "t", "-", "data", "[", "9", "]" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/email/_parseaddr.py#L152-L159
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
python/psutil/psutil/__init__.py
python
Process.get_threads
(self)
return self._platform_impl.get_process_threads()
Return threads opened by process as a list of namedtuples including thread id and thread CPU times (user/system).
Return threads opened by process as a list of namedtuples including thread id and thread CPU times (user/system).
[ "Return", "threads", "opened", "by", "process", "as", "a", "list", "of", "namedtuples", "including", "thread", "id", "and", "thread", "CPU", "times", "(", "user", "/", "system", ")", "." ]
def get_threads(self): """Return threads opened by process as a list of namedtuples including thread id and thread CPU times (user/system). """ return self._platform_impl.get_process_threads()
[ "def", "get_threads", "(", "self", ")", ":", "return", "self", ".", "_platform_impl", ".", "get_process_threads", "(", ")" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/psutil/psutil/__init__.py#L490-L494
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py3/pkg_resources/_vendor/pyparsing.py
python
_makeTags
(tagStr, xml)
return openTag, closeTag
Internal helper to construct opening and closing tag expressions, given a tag name
Internal helper to construct opening and closing tag expressions, given a tag name
[ "Internal", "helper", "to", "construct", "opening", "and", "closing", "tag", "expressions", "given", "a", "tag", "name" ]
def _makeTags(tagStr, xml): """Internal helper to construct opening and closing tag expressions, given a tag name""" if isinstance(tagStr,basestring): resname = tagStr tagStr = Keyword(tagStr, caseless=not xml) else: resname = tagStr.name tagAttrName = Word(alphas,alphanums+"_-:") if (xml): tagAttrValue = dblQuotedString.copy().setParseAction( removeQuotes ) openTag = Suppress("<") + tagStr("tag") + \ Dict(ZeroOrMore(Group( tagAttrName + Suppress("=") + tagAttrValue ))) + \ Optional("/",default=[False]).setResultsName("empty").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(">") else: printablesLessRAbrack = "".join(c for c in printables if c not in ">") tagAttrValue = quotedString.copy().setParseAction( removeQuotes ) | Word(printablesLessRAbrack) openTag = Suppress("<") + tagStr("tag") + \ Dict(ZeroOrMore(Group( tagAttrName.setParseAction(downcaseTokens) + \ Optional( Suppress("=") + tagAttrValue ) ))) + \ Optional("/",default=[False]).setResultsName("empty").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(">") closeTag = Combine(_L("</") + tagStr + ">") openTag = openTag.setResultsName("start"+"".join(resname.replace(":"," ").title().split())).setName("<%s>" % resname) closeTag = closeTag.setResultsName("end"+"".join(resname.replace(":"," ").title().split())).setName("</%s>" % resname) openTag.tag = resname closeTag.tag = resname return openTag, closeTag
[ "def", "_makeTags", "(", "tagStr", ",", "xml", ")", ":", "if", "isinstance", "(", "tagStr", ",", "basestring", ")", ":", "resname", "=", "tagStr", "tagStr", "=", "Keyword", "(", "tagStr", ",", "caseless", "=", "not", "xml", ")", "else", ":", "resname", "=", "tagStr", ".", "name", "tagAttrName", "=", "Word", "(", "alphas", ",", "alphanums", "+", "\"_-:\"", ")", "if", "(", "xml", ")", ":", "tagAttrValue", "=", "dblQuotedString", ".", "copy", "(", ")", ".", "setParseAction", "(", "removeQuotes", ")", "openTag", "=", "Suppress", "(", "\"<\"", ")", "+", "tagStr", "(", "\"tag\"", ")", "+", "Dict", "(", "ZeroOrMore", "(", "Group", "(", "tagAttrName", "+", "Suppress", "(", "\"=\"", ")", "+", "tagAttrValue", ")", ")", ")", "+", "Optional", "(", "\"/\"", ",", "default", "=", "[", "False", "]", ")", ".", "setResultsName", "(", "\"empty\"", ")", ".", "setParseAction", "(", "lambda", "s", ",", "l", ",", "t", ":", "t", "[", "0", "]", "==", "'/'", ")", "+", "Suppress", "(", "\">\"", ")", "else", ":", "printablesLessRAbrack", "=", "\"\"", ".", "join", "(", "c", "for", "c", "in", "printables", "if", "c", "not", "in", "\">\"", ")", "tagAttrValue", "=", "quotedString", ".", "copy", "(", ")", ".", "setParseAction", "(", "removeQuotes", ")", "|", "Word", "(", "printablesLessRAbrack", ")", "openTag", "=", "Suppress", "(", "\"<\"", ")", "+", "tagStr", "(", "\"tag\"", ")", "+", "Dict", "(", "ZeroOrMore", "(", "Group", "(", "tagAttrName", ".", "setParseAction", "(", "downcaseTokens", ")", "+", "Optional", "(", "Suppress", "(", "\"=\"", ")", "+", "tagAttrValue", ")", ")", ")", ")", "+", "Optional", "(", "\"/\"", ",", "default", "=", "[", "False", "]", ")", ".", "setResultsName", "(", "\"empty\"", ")", ".", "setParseAction", "(", "lambda", "s", ",", "l", ",", "t", ":", "t", "[", "0", "]", "==", "'/'", ")", "+", "Suppress", "(", "\">\"", ")", "closeTag", "=", "Combine", "(", "_L", "(", "\"</\"", ")", "+", "tagStr", "+", "\">\"", ")", "openTag", "=", "openTag", ".", "setResultsName", "(", "\"start\"", "+", "\"\"", ".", "join", "(", "resname", ".", "replace", "(", "\":\"", ",", "\" \"", ")", ".", "title", "(", ")", ".", "split", "(", ")", ")", ")", ".", "setName", "(", "\"<%s>\"", "%", "resname", ")", "closeTag", "=", "closeTag", ".", "setResultsName", "(", "\"end\"", "+", "\"\"", ".", "join", "(", "resname", ".", "replace", "(", "\":\"", ",", "\" \"", ")", ".", "title", "(", ")", ".", "split", "(", ")", ")", ")", ".", "setName", "(", "\"</%s>\"", "%", "resname", ")", "openTag", ".", "tag", "=", "resname", "closeTag", ".", "tag", "=", "resname", "return", "openTag", ",", "closeTag" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/pkg_resources/_vendor/pyparsing.py#L4875-L4902
fatih/subvim
241b6d170597857105da219c9b7d36059e9f11fb
vim/base/YouCompleteMe/python/ycm/extra_conf_store.py
python
_RandomName
()
return ''.join( random.choice( string.ascii_lowercase ) for x in range( 15 ) )
Generates a random module name.
Generates a random module name.
[ "Generates", "a", "random", "module", "name", "." ]
def _RandomName(): """Generates a random module name.""" return ''.join( random.choice( string.ascii_lowercase ) for x in range( 15 ) )
[ "def", "_RandomName", "(", ")", ":", "return", "''", ".", "join", "(", "random", ".", "choice", "(", "string", ".", "ascii_lowercase", ")", "for", "x", "in", "range", "(", "15", ")", ")" ]
https://github.com/fatih/subvim/blob/241b6d170597857105da219c9b7d36059e9f11fb/vim/base/YouCompleteMe/python/ycm/extra_conf_store.py#L210-L212
SequoiaDB/SequoiaDB
2894ed7e5bd6fe57330afc900cf76d0ff0df9f64
tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py
python
xpathParserContext.xpathPopBoolean
(self)
return ret
Pops a boolean from the stack, handling conversion if needed. Check error with #xmlXPathCheckError.
Pops a boolean from the stack, handling conversion if needed. Check error with #xmlXPathCheckError.
[ "Pops", "a", "boolean", "from", "the", "stack", "handling", "conversion", "if", "needed", ".", "Check", "error", "with", "#xmlXPathCheckError", "." ]
def xpathPopBoolean(self): """Pops a boolean from the stack, handling conversion if needed. Check error with #xmlXPathCheckError. """ ret = libxml2mod.xmlXPathPopBoolean(self._o) return ret
[ "def", "xpathPopBoolean", "(", "self", ")", ":", "ret", "=", "libxml2mod", ".", "xmlXPathPopBoolean", "(", "self", ".", "_o", ")", "return", "ret" ]
https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L7743-L7747
mysql/mysql-workbench
2f35f9034f015cbcd22139a60e1baa2e3e8e795c
res/scripts/python/grt_python_debugger.py
python
PyDebugger.do_clear
(self, bp_number)
Handle how a breakpoint must be removed when it is a temporary one.
Handle how a breakpoint must be removed when it is a temporary one.
[ "Handle", "how", "a", "breakpoint", "must", "be", "removed", "when", "it", "is", "a", "temporary", "one", "." ]
def do_clear(self, bp_number): """Handle how a breakpoint must be removed when it is a temporary one.""" #self.ui_print("user_clear: %s\n" % arg) pass
[ "def", "do_clear", "(", "self", ",", "bp_number", ")", ":", "#self.ui_print(\"user_clear: %s\\n\" % arg)", "pass" ]
https://github.com/mysql/mysql-workbench/blob/2f35f9034f015cbcd22139a60e1baa2e3e8e795c/res/scripts/python/grt_python_debugger.py#L450-L453
arangodb/arangodb
0d658689c7d1b721b314fa3ca27d38303e1570c8
3rdParty/V8/v7.9.317/third_party/jinja2/environment.py
python
Template.get_corresponding_lineno
(self, lineno)
return 1
Return the source line number of a line number in the generated bytecode as they are not in sync.
Return the source line number of a line number in the generated bytecode as they are not in sync.
[ "Return", "the", "source", "line", "number", "of", "a", "line", "number", "in", "the", "generated", "bytecode", "as", "they", "are", "not", "in", "sync", "." ]
def get_corresponding_lineno(self, lineno): """Return the source line number of a line number in the generated bytecode as they are not in sync. """ for template_line, code_line in reversed(self.debug_info): if code_line <= lineno: return template_line return 1
[ "def", "get_corresponding_lineno", "(", "self", ",", "lineno", ")", ":", "for", "template_line", ",", "code_line", "in", "reversed", "(", "self", ".", "debug_info", ")", ":", "if", "code_line", "<=", "lineno", ":", "return", "template_line", "return", "1" ]
https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/v7.9.317/third_party/jinja2/environment.py#L1108-L1115
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/training/python/training/evaluation.py
python
evaluate_repeatedly
(checkpoint_dir, master='', scaffold=None, eval_ops=None, feed_dict=None, final_ops=None, final_ops_feed_dict=None, eval_interval_secs=60, hooks=None, config=None, max_number_of_evaluations=None, timeout=None, timeout_fn=None)
return final_ops_hook.final_ops_values
Repeatedly searches for a checkpoint in `checkpoint_dir` and evaluates it. During a single evaluation, the `eval_ops` is run until the session is interrupted or requested to finish. This is typically requested via a `tf.contrib.training.StopAfterNEvalsHook` which results in `eval_ops` running the requested number of times. Optionally, a user can pass in `final_ops`, a single `Tensor`, a list of `Tensors` or a dictionary from names to `Tensors`. The `final_ops` is evaluated a single time after `eval_ops` has finished running and the fetched values of `final_ops` are returned. If `final_ops` is left as `None`, then `None` is returned. One may also consider using a `tf.contrib.training.SummaryAtEndHook` to record summaries after the `eval_ops` have run. If `eval_ops` is `None`, the summaries run immediately after the model checkpoint has been restored. Note that `evaluate_once` creates a local variable used to track the number of evaluations run via `tf.contrib.training.get_or_create_eval_step`. Consequently, if a custom local init op is provided via a `scaffold`, the caller should ensure that the local init op also initializes the eval step. Args: checkpoint_dir: The directory where checkpoints are stored. master: The address of the TensorFlow master. scaffold: An tf.train.Scaffold instance for initializing variables and restoring variables. Note that `scaffold.init_fn` is used by the function to restore the checkpoint. If you supply a custom init_fn, then it must also take care of restoring the model from its checkpoint. eval_ops: A single `Tensor`, a list of `Tensors` or a dictionary of names to `Tensors`, which is run until the session is requested to stop, commonly done by a `tf.contrib.training.StopAfterNEvalsHook`. feed_dict: The feed dictionary to use when executing the `eval_ops`. final_ops: A single `Tensor`, a list of `Tensors` or a dictionary of names to `Tensors`. final_ops_feed_dict: A feed dictionary to use when evaluating `final_ops`. eval_interval_secs: The minimum number of seconds between evaluations. hooks: List of `tf.train.SessionRunHook` callbacks which are run inside the evaluation loop. config: An instance of `tf.ConfigProto` that will be used to configure the `Session`. If left as `None`, the default will be used. max_number_of_evaluations: The maximum times to run the evaluation. If left as `None`, then evaluation runs indefinitely. timeout: The maximum amount of time to wait between checkpoints. If left as `None`, then the process will wait indefinitely. timeout_fn: Optional function to call after a timeout. If the function returns True, then it means that no new checkpoints will be generated and the iterator will exit. The function is called with no arguments. Returns: The fetched values of `final_ops` or `None` if `final_ops` is `None`.
Repeatedly searches for a checkpoint in `checkpoint_dir` and evaluates it.
[ "Repeatedly", "searches", "for", "a", "checkpoint", "in", "checkpoint_dir", "and", "evaluates", "it", "." ]
def evaluate_repeatedly(checkpoint_dir, master='', scaffold=None, eval_ops=None, feed_dict=None, final_ops=None, final_ops_feed_dict=None, eval_interval_secs=60, hooks=None, config=None, max_number_of_evaluations=None, timeout=None, timeout_fn=None): """Repeatedly searches for a checkpoint in `checkpoint_dir` and evaluates it. During a single evaluation, the `eval_ops` is run until the session is interrupted or requested to finish. This is typically requested via a `tf.contrib.training.StopAfterNEvalsHook` which results in `eval_ops` running the requested number of times. Optionally, a user can pass in `final_ops`, a single `Tensor`, a list of `Tensors` or a dictionary from names to `Tensors`. The `final_ops` is evaluated a single time after `eval_ops` has finished running and the fetched values of `final_ops` are returned. If `final_ops` is left as `None`, then `None` is returned. One may also consider using a `tf.contrib.training.SummaryAtEndHook` to record summaries after the `eval_ops` have run. If `eval_ops` is `None`, the summaries run immediately after the model checkpoint has been restored. Note that `evaluate_once` creates a local variable used to track the number of evaluations run via `tf.contrib.training.get_or_create_eval_step`. Consequently, if a custom local init op is provided via a `scaffold`, the caller should ensure that the local init op also initializes the eval step. Args: checkpoint_dir: The directory where checkpoints are stored. master: The address of the TensorFlow master. scaffold: An tf.train.Scaffold instance for initializing variables and restoring variables. Note that `scaffold.init_fn` is used by the function to restore the checkpoint. If you supply a custom init_fn, then it must also take care of restoring the model from its checkpoint. eval_ops: A single `Tensor`, a list of `Tensors` or a dictionary of names to `Tensors`, which is run until the session is requested to stop, commonly done by a `tf.contrib.training.StopAfterNEvalsHook`. feed_dict: The feed dictionary to use when executing the `eval_ops`. final_ops: A single `Tensor`, a list of `Tensors` or a dictionary of names to `Tensors`. final_ops_feed_dict: A feed dictionary to use when evaluating `final_ops`. eval_interval_secs: The minimum number of seconds between evaluations. hooks: List of `tf.train.SessionRunHook` callbacks which are run inside the evaluation loop. config: An instance of `tf.ConfigProto` that will be used to configure the `Session`. If left as `None`, the default will be used. max_number_of_evaluations: The maximum times to run the evaluation. If left as `None`, then evaluation runs indefinitely. timeout: The maximum amount of time to wait between checkpoints. If left as `None`, then the process will wait indefinitely. timeout_fn: Optional function to call after a timeout. If the function returns True, then it means that no new checkpoints will be generated and the iterator will exit. The function is called with no arguments. Returns: The fetched values of `final_ops` or `None` if `final_ops` is `None`. """ eval_step = get_or_create_eval_step() # Prepare the run hooks. hooks = hooks or [] if eval_ops is not None: update_eval_step = state_ops.assign_add(eval_step, 1) for h in hooks: if isinstance(h, StopAfterNEvalsHook): h._set_evals_completed_tensor(update_eval_step) # pylint: disable=protected-access if isinstance(eval_ops, dict): eval_ops['update_eval_step'] = update_eval_step elif isinstance(eval_ops, (tuple, list)): eval_ops = list(eval_ops) + [update_eval_step] else: eval_ops = [eval_ops, update_eval_step] final_ops_hook = basic_session_run_hooks.FinalOpsHook(final_ops, final_ops_feed_dict) hooks.append(final_ops_hook) num_evaluations = 0 for checkpoint_path in checkpoints_iterator( checkpoint_dir, min_interval_secs=eval_interval_secs, timeout=timeout, timeout_fn=timeout_fn): session_creator = monitored_session.ChiefSessionCreator( scaffold=scaffold, checkpoint_filename_with_path=checkpoint_path, master=master, config=config) with monitored_session.MonitoredSession( session_creator=session_creator, hooks=hooks) as session: logging.info('Starting evaluation at ' + time.strftime( '%Y-%m-%d-%H:%M:%S', time.gmtime())) if eval_ops is not None: while not session.should_stop(): session.run(eval_ops, feed_dict) logging.info('Finished evaluation at ' + time.strftime( '%Y-%m-%d-%H:%M:%S', time.gmtime())) num_evaluations += 1 if (max_number_of_evaluations is not None and num_evaluations >= max_number_of_evaluations): return final_ops_hook.final_ops_values return final_ops_hook.final_ops_values
[ "def", "evaluate_repeatedly", "(", "checkpoint_dir", ",", "master", "=", "''", ",", "scaffold", "=", "None", ",", "eval_ops", "=", "None", ",", "feed_dict", "=", "None", ",", "final_ops", "=", "None", ",", "final_ops_feed_dict", "=", "None", ",", "eval_interval_secs", "=", "60", ",", "hooks", "=", "None", ",", "config", "=", "None", ",", "max_number_of_evaluations", "=", "None", ",", "timeout", "=", "None", ",", "timeout_fn", "=", "None", ")", ":", "eval_step", "=", "get_or_create_eval_step", "(", ")", "# Prepare the run hooks.", "hooks", "=", "hooks", "or", "[", "]", "if", "eval_ops", "is", "not", "None", ":", "update_eval_step", "=", "state_ops", ".", "assign_add", "(", "eval_step", ",", "1", ")", "for", "h", "in", "hooks", ":", "if", "isinstance", "(", "h", ",", "StopAfterNEvalsHook", ")", ":", "h", ".", "_set_evals_completed_tensor", "(", "update_eval_step", ")", "# pylint: disable=protected-access", "if", "isinstance", "(", "eval_ops", ",", "dict", ")", ":", "eval_ops", "[", "'update_eval_step'", "]", "=", "update_eval_step", "elif", "isinstance", "(", "eval_ops", ",", "(", "tuple", ",", "list", ")", ")", ":", "eval_ops", "=", "list", "(", "eval_ops", ")", "+", "[", "update_eval_step", "]", "else", ":", "eval_ops", "=", "[", "eval_ops", ",", "update_eval_step", "]", "final_ops_hook", "=", "basic_session_run_hooks", ".", "FinalOpsHook", "(", "final_ops", ",", "final_ops_feed_dict", ")", "hooks", ".", "append", "(", "final_ops_hook", ")", "num_evaluations", "=", "0", "for", "checkpoint_path", "in", "checkpoints_iterator", "(", "checkpoint_dir", ",", "min_interval_secs", "=", "eval_interval_secs", ",", "timeout", "=", "timeout", ",", "timeout_fn", "=", "timeout_fn", ")", ":", "session_creator", "=", "monitored_session", ".", "ChiefSessionCreator", "(", "scaffold", "=", "scaffold", ",", "checkpoint_filename_with_path", "=", "checkpoint_path", ",", "master", "=", "master", ",", "config", "=", "config", ")", "with", "monitored_session", ".", "MonitoredSession", "(", "session_creator", "=", "session_creator", ",", "hooks", "=", "hooks", ")", "as", "session", ":", "logging", ".", "info", "(", "'Starting evaluation at '", "+", "time", ".", "strftime", "(", "'%Y-%m-%d-%H:%M:%S'", ",", "time", ".", "gmtime", "(", ")", ")", ")", "if", "eval_ops", "is", "not", "None", ":", "while", "not", "session", ".", "should_stop", "(", ")", ":", "session", ".", "run", "(", "eval_ops", ",", "feed_dict", ")", "logging", ".", "info", "(", "'Finished evaluation at '", "+", "time", ".", "strftime", "(", "'%Y-%m-%d-%H:%M:%S'", ",", "time", ".", "gmtime", "(", ")", ")", ")", "num_evaluations", "+=", "1", "if", "(", "max_number_of_evaluations", "is", "not", "None", "and", "num_evaluations", ">=", "max_number_of_evaluations", ")", ":", "return", "final_ops_hook", ".", "final_ops_values", "return", "final_ops_hook", ".", "final_ops_values" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/training/python/training/evaluation.py#L345-L462
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/numpy/files/numpy/core/fromnumeric.py
python
argsort
(a, axis=-1, kind='quicksort', order=None)
return argsort(axis, kind, order)
Returns the indices that would sort an array. Perform an indirect sort along the given axis using the algorithm specified by the `kind` keyword. It returns an array of indices of the same shape as `a` that index data along the given axis in sorted order. Parameters ---------- a : array_like Array to sort. axis : int or None, optional Axis along which to sort. The default is -1 (the last axis). If None, the flattened array is used. kind : {'quicksort', 'mergesort', 'heapsort'}, optional Sorting algorithm. order : list, optional When `a` is an array with fields defined, this argument specifies which fields to compare first, second, etc. Not all fields need be specified. Returns ------- index_array : ndarray, int Array of indices that sort `a` along the specified axis. In other words, ``a[index_array]`` yields a sorted `a`. See Also -------- sort : Describes sorting algorithms used. lexsort : Indirect stable sort with multiple keys. ndarray.sort : Inplace sort. Notes ----- See `sort` for notes on the different sorting algorithms. As of NumPy 1.4.0 `argsort` works with real/complex arrays containing nan values. The enhanced sort order is documented in `sort`. Examples -------- One dimensional array: >>> x = np.array([3, 1, 2]) >>> np.argsort(x) array([1, 2, 0]) Two-dimensional array: >>> x = np.array([[0, 3], [2, 2]]) >>> x array([[0, 3], [2, 2]]) >>> np.argsort(x, axis=0) array([[0, 1], [1, 0]]) >>> np.argsort(x, axis=1) array([[0, 1], [0, 1]]) Sorting with keys: >>> x = np.array([(1, 0), (0, 1)], dtype=[('x', '<i4'), ('y', '<i4')]) >>> x array([(1, 0), (0, 1)], dtype=[('x', '<i4'), ('y', '<i4')]) >>> np.argsort(x, order=('x','y')) array([1, 0]) >>> np.argsort(x, order=('y','x')) array([0, 1])
Returns the indices that would sort an array.
[ "Returns", "the", "indices", "that", "would", "sort", "an", "array", "." ]
def argsort(a, axis=-1, kind='quicksort', order=None): """ Returns the indices that would sort an array. Perform an indirect sort along the given axis using the algorithm specified by the `kind` keyword. It returns an array of indices of the same shape as `a` that index data along the given axis in sorted order. Parameters ---------- a : array_like Array to sort. axis : int or None, optional Axis along which to sort. The default is -1 (the last axis). If None, the flattened array is used. kind : {'quicksort', 'mergesort', 'heapsort'}, optional Sorting algorithm. order : list, optional When `a` is an array with fields defined, this argument specifies which fields to compare first, second, etc. Not all fields need be specified. Returns ------- index_array : ndarray, int Array of indices that sort `a` along the specified axis. In other words, ``a[index_array]`` yields a sorted `a`. See Also -------- sort : Describes sorting algorithms used. lexsort : Indirect stable sort with multiple keys. ndarray.sort : Inplace sort. Notes ----- See `sort` for notes on the different sorting algorithms. As of NumPy 1.4.0 `argsort` works with real/complex arrays containing nan values. The enhanced sort order is documented in `sort`. Examples -------- One dimensional array: >>> x = np.array([3, 1, 2]) >>> np.argsort(x) array([1, 2, 0]) Two-dimensional array: >>> x = np.array([[0, 3], [2, 2]]) >>> x array([[0, 3], [2, 2]]) >>> np.argsort(x, axis=0) array([[0, 1], [1, 0]]) >>> np.argsort(x, axis=1) array([[0, 1], [0, 1]]) Sorting with keys: >>> x = np.array([(1, 0), (0, 1)], dtype=[('x', '<i4'), ('y', '<i4')]) >>> x array([(1, 0), (0, 1)], dtype=[('x', '<i4'), ('y', '<i4')]) >>> np.argsort(x, order=('x','y')) array([1, 0]) >>> np.argsort(x, order=('y','x')) array([0, 1]) """ try: argsort = a.argsort except AttributeError: return _wrapit(a, 'argsort', axis, kind, order) return argsort(axis, kind, order)
[ "def", "argsort", "(", "a", ",", "axis", "=", "-", "1", ",", "kind", "=", "'quicksort'", ",", "order", "=", "None", ")", ":", "try", ":", "argsort", "=", "a", ".", "argsort", "except", "AttributeError", ":", "return", "_wrapit", "(", "a", ",", "'argsort'", ",", "axis", ",", "kind", ",", "order", ")", "return", "argsort", "(", "axis", ",", "kind", ",", "order", ")" ]
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/core/fromnumeric.py#L598-L680
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/distutils/misc_util.py
python
Configuration.add_library
(self,name,sources,**build_info)
Add library to configuration. Parameters ---------- name : str Name of the extension. sources : sequence List of the sources. The list of sources may contain functions (called source generators) which must take an extension instance and a build directory as inputs and return a source file or list of source files or None. If None is returned then no sources are generated. If the Extension instance has no sources after processing all source generators, then no extension module is built. build_info : dict, optional The following keys are allowed: * depends * macros * include_dirs * extra_compiler_args * extra_f77_compiler_args * extra_f90_compiler_args * f2py_options * language
Add library to configuration.
[ "Add", "library", "to", "configuration", "." ]
def add_library(self,name,sources,**build_info): """ Add library to configuration. Parameters ---------- name : str Name of the extension. sources : sequence List of the sources. The list of sources may contain functions (called source generators) which must take an extension instance and a build directory as inputs and return a source file or list of source files or None. If None is returned then no sources are generated. If the Extension instance has no sources after processing all source generators, then no extension module is built. build_info : dict, optional The following keys are allowed: * depends * macros * include_dirs * extra_compiler_args * extra_f77_compiler_args * extra_f90_compiler_args * f2py_options * language """ self._add_library(name, sources, None, build_info) dist = self.get_distribution() if dist is not None: self.warn('distutils distribution has been initialized,'\ ' it may be too late to add a library '+ name)
[ "def", "add_library", "(", "self", ",", "name", ",", "sources", ",", "*", "*", "build_info", ")", ":", "self", ".", "_add_library", "(", "name", ",", "sources", ",", "None", ",", "build_info", ")", "dist", "=", "self", ".", "get_distribution", "(", ")", "if", "dist", "is", "not", "None", ":", "self", ".", "warn", "(", "'distutils distribution has been initialized,'", "' it may be too late to add a library '", "+", "name", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/distutils/misc_util.py#L1461-L1495
deepmind/open_spiel
4ca53bea32bb2875c7385d215424048ae92f78c8
open_spiel/python/mfg/games/crowd_modelling.py
python
MFGCrowdModellingState.__init__
(self, game)
Constructor; should only be called by Game.new_initial_state.
Constructor; should only be called by Game.new_initial_state.
[ "Constructor", ";", "should", "only", "be", "called", "by", "Game", ".", "new_initial_state", "." ]
def __init__(self, game): """Constructor; should only be called by Game.new_initial_state.""" super().__init__(game) self._is_chance_init = True # is true for the first state of the game. self._player_id = pyspiel.PlayerId.CHANCE self._x = None self._t = 0 # We initialize last_action to the neutral action. This makes sure # that the first reward does not include any displacement penalty. self._last_action = self._NEUTRAL_ACTION self.size = game.size self.horizon = game.horizon self.return_value = 0.0 # Represents the current probability distribution over game states. # Initialized with a uniform distribution. self._distribution = [1. / self.size for i in range(self.size)]
[ "def", "__init__", "(", "self", ",", "game", ")", ":", "super", "(", ")", ".", "__init__", "(", "game", ")", "self", ".", "_is_chance_init", "=", "True", "# is true for the first state of the game.", "self", ".", "_player_id", "=", "pyspiel", ".", "PlayerId", ".", "CHANCE", "self", ".", "_x", "=", "None", "self", ".", "_t", "=", "0", "# We initialize last_action to the neutral action. This makes sure", "# that the first reward does not include any displacement penalty.", "self", ".", "_last_action", "=", "self", ".", "_NEUTRAL_ACTION", "self", ".", "size", "=", "game", ".", "size", "self", ".", "horizon", "=", "game", ".", "horizon", "self", ".", "return_value", "=", "0.0", "# Represents the current probability distribution over game states.", "# Initialized with a uniform distribution.", "self", ".", "_distribution", "=", "[", "1.", "/", "self", ".", "size", "for", "i", "in", "range", "(", "self", ".", "size", ")", "]" ]
https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/mfg/games/crowd_modelling.py#L105-L121
microsoft/CNTK
e9396480025b9ca457d26b6f33dd07c474c6aa04
Examples/Image/Detection/FastRCNN/BrainScript/cntk_helpers.py
python
computeAveragePrecision
(recalls, precisions, use_07_metric=False)
return ap
ap = voc_ap(recalls, precisions, [use_07_metric]) Compute VOC AP given precision and recall. If use_07_metric is true, uses the VOC 07 11 point method (default:False).
ap = voc_ap(recalls, precisions, [use_07_metric]) Compute VOC AP given precision and recall. If use_07_metric is true, uses the VOC 07 11 point method (default:False).
[ "ap", "=", "voc_ap", "(", "recalls", "precisions", "[", "use_07_metric", "]", ")", "Compute", "VOC", "AP", "given", "precision", "and", "recall", ".", "If", "use_07_metric", "is", "true", "uses", "the", "VOC", "07", "11", "point", "method", "(", "default", ":", "False", ")", "." ]
def computeAveragePrecision(recalls, precisions, use_07_metric=False): """ ap = voc_ap(recalls, precisions, [use_07_metric]) Compute VOC AP given precision and recall. If use_07_metric is true, uses the VOC 07 11 point method (default:False). """ if use_07_metric: # 11 point metric ap = 0. for t in np.arange(0., 1.1, 0.1): if np.sum(recalls >= t) == 0: p = 0 else: p = np.max(precisions[recalls >= t]) ap = ap + p / 11. else: # correct AP calculation # first append sentinel values at the end mrecalls = np.concatenate(([0.], recalls, [1.])) mprecisions = np.concatenate(([0.], precisions, [0.])) # compute the precision envelope for i in range(mprecisions.size - 1, 0, -1): mprecisions[i - 1] = np.maximum(mprecisions[i - 1], mprecisions[i]) # to calculate area under PR curve, look for points # where X axis (recall) changes value i = np.where(mrecalls[1:] != mrecalls[:-1])[0] # and sum (\Delta recall) * prec ap = np.sum((mrecalls[i + 1] - mrecalls[i]) * mprecisions[i + 1]) return ap
[ "def", "computeAveragePrecision", "(", "recalls", ",", "precisions", ",", "use_07_metric", "=", "False", ")", ":", "if", "use_07_metric", ":", "# 11 point metric", "ap", "=", "0.", "for", "t", "in", "np", ".", "arange", "(", "0.", ",", "1.1", ",", "0.1", ")", ":", "if", "np", ".", "sum", "(", "recalls", ">=", "t", ")", "==", "0", ":", "p", "=", "0", "else", ":", "p", "=", "np", ".", "max", "(", "precisions", "[", "recalls", ">=", "t", "]", ")", "ap", "=", "ap", "+", "p", "/", "11.", "else", ":", "# correct AP calculation", "# first append sentinel values at the end", "mrecalls", "=", "np", ".", "concatenate", "(", "(", "[", "0.", "]", ",", "recalls", ",", "[", "1.", "]", ")", ")", "mprecisions", "=", "np", ".", "concatenate", "(", "(", "[", "0.", "]", ",", "precisions", ",", "[", "0.", "]", ")", ")", "# compute the precision envelope", "for", "i", "in", "range", "(", "mprecisions", ".", "size", "-", "1", ",", "0", ",", "-", "1", ")", ":", "mprecisions", "[", "i", "-", "1", "]", "=", "np", ".", "maximum", "(", "mprecisions", "[", "i", "-", "1", "]", ",", "mprecisions", "[", "i", "]", ")", "# to calculate area under PR curve, look for points", "# where X axis (recall) changes value", "i", "=", "np", ".", "where", "(", "mrecalls", "[", "1", ":", "]", "!=", "mrecalls", "[", ":", "-", "1", "]", ")", "[", "0", "]", "# and sum (\\Delta recall) * prec", "ap", "=", "np", ".", "sum", "(", "(", "mrecalls", "[", "i", "+", "1", "]", "-", "mrecalls", "[", "i", "]", ")", "*", "mprecisions", "[", "i", "+", "1", "]", ")", "return", "ap" ]
https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/Examples/Image/Detection/FastRCNN/BrainScript/cntk_helpers.py#L922-L953
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/functions/Examples/ExamplePeakFunction.py
python
ExamplePeakFunction.setActiveParameter
(self, index, value)
Called by the fitting framework when a parameter value is updated. Only required if the fitting is done over a different parameter set than that declared
Called by the fitting framework when a parameter value is updated. Only required if the fitting is done over a different parameter set than that declared
[ "Called", "by", "the", "fitting", "framework", "when", "a", "parameter", "value", "is", "updated", ".", "Only", "required", "if", "the", "fitting", "is", "done", "over", "a", "different", "parameter", "set", "than", "that", "declared" ]
def setActiveParameter(self, index, value): """ Called by the fitting framework when a parameter value is updated. Only required if the fitting is done over a different parameter set than that declared """ param_value = value if index == 2: param_value = math.sqrt(math.fabs(1.0/value)) else: param_value = value # Final explicit arugment is required to be false here by framework self.setParameter(index, param_value, False) param_value = self.getParameterValue(index) if index == 2: # Sigma. Actually fit to 1/(sigma^2) for stability return math.pow(1./param_value, 2) else: return param_value
[ "def", "setActiveParameter", "(", "self", ",", "index", ",", "value", ")", ":", "param_value", "=", "value", "if", "index", "==", "2", ":", "param_value", "=", "math", ".", "sqrt", "(", "math", ".", "fabs", "(", "1.0", "/", "value", ")", ")", "else", ":", "param_value", "=", "value", "# Final explicit arugment is required to be false here by framework", "self", ".", "setParameter", "(", "index", ",", "param_value", ",", "False", ")", "param_value", "=", "self", ".", "getParameterValue", "(", "index", ")", "if", "index", "==", "2", ":", "# Sigma. Actually fit to 1/(sigma^2) for stability", "return", "math", ".", "pow", "(", "1.", "/", "param_value", ",", "2", ")", "else", ":", "return", "param_value" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/functions/Examples/ExamplePeakFunction.py#L121-L139
macchina-io/macchina.io
ef24ba0e18379c3dd48fb84e6dbf991101cb8db0
platform/JS/V8/v8/third_party/jinja2/filters.py
python
do_map
(*args, **kwargs)
Applies a filter on a sequence of objects or looks up an attribute. This is useful when dealing with lists of objects but you are really only interested in a certain value of it. The basic usage is mapping on an attribute. Imagine you have a list of users but you are only interested in a list of usernames: .. sourcecode:: jinja Users on this page: {{ users|map(attribute='username')|join(', ') }} Alternatively you can let it invoke a filter by passing the name of the filter and the arguments afterwards. A good example would be applying a text conversion filter on a sequence: .. sourcecode:: jinja Users on this page: {{ titles|map('lower')|join(', ') }} .. versionadded:: 2.7
Applies a filter on a sequence of objects or looks up an attribute. This is useful when dealing with lists of objects but you are really only interested in a certain value of it.
[ "Applies", "a", "filter", "on", "a", "sequence", "of", "objects", "or", "looks", "up", "an", "attribute", ".", "This", "is", "useful", "when", "dealing", "with", "lists", "of", "objects", "but", "you", "are", "really", "only", "interested", "in", "a", "certain", "value", "of", "it", "." ]
def do_map(*args, **kwargs): """Applies a filter on a sequence of objects or looks up an attribute. This is useful when dealing with lists of objects but you are really only interested in a certain value of it. The basic usage is mapping on an attribute. Imagine you have a list of users but you are only interested in a list of usernames: .. sourcecode:: jinja Users on this page: {{ users|map(attribute='username')|join(', ') }} Alternatively you can let it invoke a filter by passing the name of the filter and the arguments afterwards. A good example would be applying a text conversion filter on a sequence: .. sourcecode:: jinja Users on this page: {{ titles|map('lower')|join(', ') }} .. versionadded:: 2.7 """ context = args[0] seq = args[1] if len(args) == 2 and 'attribute' in kwargs: attribute = kwargs.pop('attribute') if kwargs: raise FilterArgumentError('Unexpected keyword argument %r' % next(iter(kwargs))) func = make_attrgetter(context.environment, attribute) else: try: name = args[2] args = args[3:] except LookupError: raise FilterArgumentError('map requires a filter argument') func = lambda item: context.environment.call_filter( name, item, args, kwargs, context=context) if seq: for item in seq: yield func(item)
[ "def", "do_map", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "context", "=", "args", "[", "0", "]", "seq", "=", "args", "[", "1", "]", "if", "len", "(", "args", ")", "==", "2", "and", "'attribute'", "in", "kwargs", ":", "attribute", "=", "kwargs", ".", "pop", "(", "'attribute'", ")", "if", "kwargs", ":", "raise", "FilterArgumentError", "(", "'Unexpected keyword argument %r'", "%", "next", "(", "iter", "(", "kwargs", ")", ")", ")", "func", "=", "make_attrgetter", "(", "context", ".", "environment", ",", "attribute", ")", "else", ":", "try", ":", "name", "=", "args", "[", "2", "]", "args", "=", "args", "[", "3", ":", "]", "except", "LookupError", ":", "raise", "FilterArgumentError", "(", "'map requires a filter argument'", ")", "func", "=", "lambda", "item", ":", "context", ".", "environment", ".", "call_filter", "(", "name", ",", "item", ",", "args", ",", "kwargs", ",", "context", "=", "context", ")", "if", "seq", ":", "for", "item", "in", "seq", ":", "yield", "func", "(", "item", ")" ]
https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/v8/third_party/jinja2/filters.py#L808-L850
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/pkg_resources/_vendor/pyparsing.py
python
pyparsing_common.stripHTMLTags
(s, l, tokens)
return pyparsing_common._html_stripper.transformString(tokens[0])
Parse action to remove HTML tags from web page HTML source Example:: # strip HTML links from normal text text = '<td>More info at the <a href="http://pyparsing.wikispaces.com">pyparsing</a> wiki page</td>' td,td_end = makeHTMLTags("TD") table_text = td + SkipTo(td_end).setParseAction(pyparsing_common.stripHTMLTags)("body") + td_end print(table_text.parseString(text).body) # -> 'More info at the pyparsing wiki page'
Parse action to remove HTML tags from web page HTML source
[ "Parse", "action", "to", "remove", "HTML", "tags", "from", "web", "page", "HTML", "source" ]
def stripHTMLTags(s, l, tokens): """ Parse action to remove HTML tags from web page HTML source Example:: # strip HTML links from normal text text = '<td>More info at the <a href="http://pyparsing.wikispaces.com">pyparsing</a> wiki page</td>' td,td_end = makeHTMLTags("TD") table_text = td + SkipTo(td_end).setParseAction(pyparsing_common.stripHTMLTags)("body") + td_end print(table_text.parseString(text).body) # -> 'More info at the pyparsing wiki page' """ return pyparsing_common._html_stripper.transformString(tokens[0])
[ "def", "stripHTMLTags", "(", "s", ",", "l", ",", "tokens", ")", ":", "return", "pyparsing_common", ".", "_html_stripper", ".", "transformString", "(", "tokens", "[", "0", "]", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/pkg_resources/_vendor/pyparsing.py#L5601-L5613
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_windows.py
python
ColourData.SetCustomColour
(*args, **kwargs)
return _windows_.ColourData_SetCustomColour(*args, **kwargs)
SetCustomColour(self, int i, Colour colour) Sets the i'th custom colour for the colour dialog. i should be an integer between 0 and 15. The default custom colours are all invalid colours.
SetCustomColour(self, int i, Colour colour)
[ "SetCustomColour", "(", "self", "int", "i", "Colour", "colour", ")" ]
def SetCustomColour(*args, **kwargs): """ SetCustomColour(self, int i, Colour colour) Sets the i'th custom colour for the colour dialog. i should be an integer between 0 and 15. The default custom colours are all invalid colours. """ return _windows_.ColourData_SetCustomColour(*args, **kwargs)
[ "def", "SetCustomColour", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "ColourData_SetCustomColour", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L2978-L2985
koth/kcws
88efbd36a7022de4e6e90f5a1fb880cf87cfae9f
third_party/setuptools/pkg_resources.py
python
safe_name
(name)
return re.sub('[^A-Za-z0-9.]+', '-', name)
Convert an arbitrary string to a standard distribution name Any runs of non-alphanumeric/. characters are replaced with a single '-'.
Convert an arbitrary string to a standard distribution name
[ "Convert", "an", "arbitrary", "string", "to", "a", "standard", "distribution", "name" ]
def safe_name(name): """Convert an arbitrary string to a standard distribution name Any runs of non-alphanumeric/. characters are replaced with a single '-'. """ return re.sub('[^A-Za-z0-9.]+', '-', name)
[ "def", "safe_name", "(", "name", ")", ":", "return", "re", ".", "sub", "(", "'[^A-Za-z0-9.]+'", ",", "'-'", ",", "name", ")" ]
https://github.com/koth/kcws/blob/88efbd36a7022de4e6e90f5a1fb880cf87cfae9f/third_party/setuptools/pkg_resources.py#L1150-L1155
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/grit/grit/clique.py
python
CustomType.ValidateAndModify
(self, lang, translation)
Returns true if the translation (a tclib.Translation object) is valid, otherwise false. The language is also passed in. This method may modify the translation that is passed in, if it so wishes.
Returns true if the translation (a tclib.Translation object) is valid, otherwise false. The language is also passed in. This method may modify the translation that is passed in, if it so wishes.
[ "Returns", "true", "if", "the", "translation", "(", "a", "tclib", ".", "Translation", "object", ")", "is", "valid", "otherwise", "false", ".", "The", "language", "is", "also", "passed", "in", ".", "This", "method", "may", "modify", "the", "translation", "that", "is", "passed", "in", "if", "it", "so", "wishes", "." ]
def ValidateAndModify(self, lang, translation): '''Returns true if the translation (a tclib.Translation object) is valid, otherwise false. The language is also passed in. This method may modify the translation that is passed in, if it so wishes. ''' raise NotImplementedError()
[ "def", "ValidateAndModify", "(", "self", ",", "lang", ",", "translation", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/grit/grit/clique.py#L250-L255
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/framework/tensor_shape.py
python
TensorShape.assert_is_fully_defined
(self)
Raises an exception if `self` is not fully defined in every dimension. Raises: ValueError: If `self` does not have a known value for every dimension.
Raises an exception if `self` is not fully defined in every dimension.
[ "Raises", "an", "exception", "if", "self", "is", "not", "fully", "defined", "in", "every", "dimension", "." ]
def assert_is_fully_defined(self): """Raises an exception if `self` is not fully defined in every dimension. Raises: ValueError: If `self` does not have a known value for every dimension. """ if not self.is_fully_defined(): raise ValueError("Shape %s is not fully defined" % self)
[ "def", "assert_is_fully_defined", "(", "self", ")", ":", "if", "not", "self", ".", "is_fully_defined", "(", ")", ":", "raise", "ValueError", "(", "\"Shape %s is not fully defined\"", "%", "self", ")" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/framework/tensor_shape.py#L748-L755
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/deps/v8/tools/stats-viewer.py
python
Counter.__init__
(self, data, offset)
Create a new instance. Args: data: the shared data access object containing the counter offset: the byte offset of the start of this counter
Create a new instance.
[ "Create", "a", "new", "instance", "." ]
def __init__(self, data, offset): """Create a new instance. Args: data: the shared data access object containing the counter offset: the byte offset of the start of this counter """ self.data = data self.offset = offset
[ "def", "__init__", "(", "self", ",", "data", ",", "offset", ")", ":", "self", ".", "data", "=", "data", "self", ".", "offset", "=", "offset" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/deps/v8/tools/stats-viewer.py#L333-L341
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py
python
uCSIsBopomofo
(code)
return ret
Check whether the character is part of Bopomofo UCS Block
Check whether the character is part of Bopomofo UCS Block
[ "Check", "whether", "the", "character", "is", "part", "of", "Bopomofo", "UCS", "Block" ]
def uCSIsBopomofo(code): """Check whether the character is part of Bopomofo UCS Block """ ret = libxml2mod.xmlUCSIsBopomofo(code) return ret
[ "def", "uCSIsBopomofo", "(", "code", ")", ":", "ret", "=", "libxml2mod", ".", "xmlUCSIsBopomofo", "(", "code", ")", "return", "ret" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L1366-L1369
kclyu/rpi-webrtc-streamer
e109e418aa9023009b3b59c95eec2de4721125be
tools/telegramBot.py
python
load_config
(config_filename)
If a config file is specified, load the config file. Even though the config file is not specified, we actually use the contents of default config for the _PROG_CONFIG global variable.
If a config file is specified, load the config file.
[ "If", "a", "config", "file", "is", "specified", "load", "the", "config", "file", "." ]
def load_config(config_filename): """ If a config file is specified, load the config file. Even though the config file is not specified, we actually use the contents of default config for the _PROG_CONFIG global variable. """ global _PROG_CONFIG, _LOADED_NOTI_SCHEDULE_DAY, _LOADED_NOTI_SCHEDULE_HOUR with open(config_filename) as fp: loaded_config = yaml.load(fp) for key, value in loaded_config.items(): _PROG_CONFIG[key] = value _LOADED_NOTI_SCHEDULE_HOUR = get_noti_schedule( _PROG_CONFIG[PROG_CONFIG_KEY_NOTI_HOUR_SCHEDULE], PROG_NOTI_HOUR_SCHEDULE) _LOADED_NOTI_SCHEDULE_DAY = get_noti_schedule( _PROG_CONFIG[PROG_CONFIG_KEY_NOTI_DAY_SCHEDULE], PROG_NOTI_DAY_SCHEDULE) logger.debug("Notification Day Schedule: %s" % _LOADED_NOTI_SCHEDULE_DAY ) logger.debug("Notification Hour Schedule: %s" % _LOADED_NOTI_SCHEDULE_HOUR )
[ "def", "load_config", "(", "config_filename", ")", ":", "global", "_PROG_CONFIG", ",", "_LOADED_NOTI_SCHEDULE_DAY", ",", "_LOADED_NOTI_SCHEDULE_HOUR", "with", "open", "(", "config_filename", ")", "as", "fp", ":", "loaded_config", "=", "yaml", ".", "load", "(", "fp", ")", "for", "key", ",", "value", "in", "loaded_config", ".", "items", "(", ")", ":", "_PROG_CONFIG", "[", "key", "]", "=", "value", "_LOADED_NOTI_SCHEDULE_HOUR", "=", "get_noti_schedule", "(", "_PROG_CONFIG", "[", "PROG_CONFIG_KEY_NOTI_HOUR_SCHEDULE", "]", ",", "PROG_NOTI_HOUR_SCHEDULE", ")", "_LOADED_NOTI_SCHEDULE_DAY", "=", "get_noti_schedule", "(", "_PROG_CONFIG", "[", "PROG_CONFIG_KEY_NOTI_DAY_SCHEDULE", "]", ",", "PROG_NOTI_DAY_SCHEDULE", ")", "logger", ".", "debug", "(", "\"Notification Day Schedule: %s\"", "%", "_LOADED_NOTI_SCHEDULE_DAY", ")", "logger", ".", "debug", "(", "\"Notification Hour Schedule: %s\"", "%", "_LOADED_NOTI_SCHEDULE_HOUR", ")" ]
https://github.com/kclyu/rpi-webrtc-streamer/blob/e109e418aa9023009b3b59c95eec2de4721125be/tools/telegramBot.py#L262-L283
calamares/calamares
9f6f82405b3074af7c99dc26487d2e46e4ece3e5
src/modules/initcpiocfg/main.py
python
get_host_initcpio
()
return mklins
Reads the host system mkinitcpio.conf and returns all the lines from that file, or an empty list if it does not exist.
Reads the host system mkinitcpio.conf and returns all the lines from that file, or an empty list if it does not exist.
[ "Reads", "the", "host", "system", "mkinitcpio", ".", "conf", "and", "returns", "all", "the", "lines", "from", "that", "file", "or", "an", "empty", "list", "if", "it", "does", "not", "exist", "." ]
def get_host_initcpio(): """ Reads the host system mkinitcpio.conf and returns all the lines from that file, or an empty list if it does not exist. """ hostfile = "/etc/mkinitcpio.conf" try: with open(hostfile, "r") as mkinitcpio_file: mklins = [x.strip() for x in mkinitcpio_file.readlines()] except FileNotFoundError: libcalamares.utils.debug("Could not open host file '%s'" % hostfile) mklins = [] return mklins
[ "def", "get_host_initcpio", "(", ")", ":", "hostfile", "=", "\"/etc/mkinitcpio.conf\"", "try", ":", "with", "open", "(", "hostfile", ",", "\"r\"", ")", "as", "mkinitcpio_file", ":", "mklins", "=", "[", "x", ".", "strip", "(", ")", "for", "x", "in", "mkinitcpio_file", ".", "readlines", "(", ")", "]", "except", "FileNotFoundError", ":", "libcalamares", ".", "utils", ".", "debug", "(", "\"Could not open host file '%s'\"", "%", "hostfile", ")", "mklins", "=", "[", "]", "return", "mklins" ]
https://github.com/calamares/calamares/blob/9f6f82405b3074af7c99dc26487d2e46e4ece3e5/src/modules/initcpiocfg/main.py#L94-L108
OpenMined/PyDP
a88ee73053aa2bdc1be327a77109dd5907ab41d6
src/pydp/ml/mechanisms/laplace.py
python
Laplace.check_inputs
(self, value)
return True
Checks that all parameters of the mechanism have been initialised correctly, and that the mechanism is ready to be used. Parameters ---------- value : float The value to be checked Returns ------- True if the mechanism is ready to be used. Raises ------ Exception If parameters have not been set correctly, or if `value` falls outside the domain of the mechanism.
Checks that all parameters of the mechanism have been initialised correctly, and that the mechanism is ready to be used. Parameters ---------- value : float The value to be checked Returns ------- True if the mechanism is ready to be used. Raises ------ Exception If parameters have not been set correctly, or if `value` falls outside the domain of the mechanism.
[ "Checks", "that", "all", "parameters", "of", "the", "mechanism", "have", "been", "initialised", "correctly", "and", "that", "the", "mechanism", "is", "ready", "to", "be", "used", ".", "Parameters", "----------", "value", ":", "float", "The", "value", "to", "be", "checked", "Returns", "-------", "True", "if", "the", "mechanism", "is", "ready", "to", "be", "used", ".", "Raises", "------", "Exception", "If", "parameters", "have", "not", "been", "set", "correctly", "or", "if", "value", "falls", "outside", "the", "domain", "of", "the", "mechanism", "." ]
def check_inputs(self, value): """Checks that all parameters of the mechanism have been initialised correctly, and that the mechanism is ready to be used. Parameters ---------- value : float The value to be checked Returns ------- True if the mechanism is ready to be used. Raises ------ Exception If parameters have not been set correctly, or if `value` falls outside the domain of the mechanism. """ super().check_inputs(value) if not isinstance(value, Real): raise TypeError("Value to be randomised must be a number") if self._sensitivity is None: raise ValueError("Sensitivity must be set") return True
[ "def", "check_inputs", "(", "self", ",", "value", ")", ":", "super", "(", ")", ".", "check_inputs", "(", "value", ")", "if", "not", "isinstance", "(", "value", ",", "Real", ")", ":", "raise", "TypeError", "(", "\"Value to be randomised must be a number\"", ")", "if", "self", ".", "_sensitivity", "is", "None", ":", "raise", "ValueError", "(", "\"Sensitivity must be set\"", ")", "return", "True" ]
https://github.com/OpenMined/PyDP/blob/a88ee73053aa2bdc1be327a77109dd5907ab41d6/src/pydp/ml/mechanisms/laplace.py#L80-L103
SpenceKonde/megaTinyCore
1c4a70b18a149fe6bcb551dfa6db11ca50b8997b
megaavr/tools/libs/pymcuprog/nvmserialupdi.py
python
NvmAccessProviderSerial.read
(self, memory_info, offset, numbytes, max_read_chunk=None)
return data
Read the memory in chunks :param memory_info: dictionary for the memory as provided by the DeviceMemoryInfo class :param offset: relative offset in the memory type :param numbytes: number of bytes to read :param max_read_chunk: memory is read im chunks of up to 512b at a time. The -rc parameter can shrink this if needed for compatibility with certain hardware. :return: array of bytes read
Read the memory in chunks
[ "Read", "the", "memory", "in", "chunks" ]
def read(self, memory_info, offset, numbytes, max_read_chunk=None): """ Read the memory in chunks :param memory_info: dictionary for the memory as provided by the DeviceMemoryInfo class :param offset: relative offset in the memory type :param numbytes: number of bytes to read :param max_read_chunk: memory is read im chunks of up to 512b at a time. The -rc parameter can shrink this if needed for compatibility with certain hardware. :return: array of bytes read """ offset += memory_info[DeviceMemoryInfoKeys.ADDRESS] # if reading from flash, we want to read words if it would reduce number of USB serial transactions. # this function is called for everything though, so be careful not to use it for memories read one byte at a time, like fuses data = [] if max_read_chunk is None: read_chunk_size = 0x100 else: read_chunk_size = max_read_chunk use_word_access = False memtype_string = memory_info[DeviceMemoryInfoKeys.NAME] if memtype_string in (MemoryNames.FLASH): if numbytes > 0x100 and max_read_chunk is None: use_word_access = True read_chunk_size = 0x200 elif max_read_chunk is not None: if max_read_chunk > 256: use_word_access = True # SACRIFICES SPEED FOR COMPATIBILITY - above line should happen whenever --limitreadsize=1 command line parameter is not passed, so we can only turn it on for specific tools -> programmer options that have this weird limitation. I couldn't propagate it through this mess! n_chunk = math.ceil(numbytes/read_chunk_size) bar = progress_bar.ProgressBar(n_chunk, hide=n_chunk == 1) while numbytes: if numbytes < read_chunk_size: read_chunk_size = numbytes self.logger.debug("Reading %d bytes from address 0x%06X", read_chunk_size, offset) if use_word_access: data += self.avr.read_data_words(offset, read_chunk_size>> 1) else: data += self.avr.read_data(offset, read_chunk_size) offset += read_chunk_size numbytes -= read_chunk_size bar.step() return data
[ "def", "read", "(", "self", ",", "memory_info", ",", "offset", ",", "numbytes", ",", "max_read_chunk", "=", "None", ")", ":", "offset", "+=", "memory_info", "[", "DeviceMemoryInfoKeys", ".", "ADDRESS", "]", "# if reading from flash, we want to read words if it would reduce number of USB serial transactions.", "# this function is called for everything though, so be careful not to use it for memories read one byte at a time, like fuses", "data", "=", "[", "]", "if", "max_read_chunk", "is", "None", ":", "read_chunk_size", "=", "0x100", "else", ":", "read_chunk_size", "=", "max_read_chunk", "use_word_access", "=", "False", "memtype_string", "=", "memory_info", "[", "DeviceMemoryInfoKeys", ".", "NAME", "]", "if", "memtype_string", "in", "(", "MemoryNames", ".", "FLASH", ")", ":", "if", "numbytes", ">", "0x100", "and", "max_read_chunk", "is", "None", ":", "use_word_access", "=", "True", "read_chunk_size", "=", "0x200", "elif", "max_read_chunk", "is", "not", "None", ":", "if", "max_read_chunk", ">", "256", ":", "use_word_access", "=", "True", "# SACRIFICES SPEED FOR COMPATIBILITY - above line should happen whenever --limitreadsize=1 command line parameter is not passed, so we can only turn it on for specific tools -> programmer options that have this weird limitation. I couldn't propagate it through this mess!", "n_chunk", "=", "math", ".", "ceil", "(", "numbytes", "/", "read_chunk_size", ")", "bar", "=", "progress_bar", ".", "ProgressBar", "(", "n_chunk", ",", "hide", "=", "n_chunk", "==", "1", ")", "while", "numbytes", ":", "if", "numbytes", "<", "read_chunk_size", ":", "read_chunk_size", "=", "numbytes", "self", ".", "logger", ".", "debug", "(", "\"Reading %d bytes from address 0x%06X\"", ",", "read_chunk_size", ",", "offset", ")", "if", "use_word_access", ":", "data", "+=", "self", ".", "avr", ".", "read_data_words", "(", "offset", ",", "read_chunk_size", ">>", "1", ")", "else", ":", "data", "+=", "self", ".", "avr", ".", "read_data", "(", "offset", ",", "read_chunk_size", ")", "offset", "+=", "read_chunk_size", "numbytes", "-=", "read_chunk_size", "bar", ".", "step", "(", ")", "return", "data" ]
https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pymcuprog/nvmserialupdi.py#L180-L226
apache/arrow
af33dd1157eb8d7d9bfac25ebf61445b793b7943
dev/archery/archery/utils/source.py
python
ArrowSources.archive
(self, path, dereference=False, compressor=None, revision=None)
Saves a git archive at path.
Saves a git archive at path.
[ "Saves", "a", "git", "archive", "at", "path", "." ]
def archive(self, path, dereference=False, compressor=None, revision=None): """ Saves a git archive at path. """ if not self.git_backed: raise ValueError("{} is not backed by git".format(self)) rev = revision if revision else "HEAD" archive = git.archive("--prefix=apache-arrow/", rev, git_dir=self.path) # TODO(fsaintjacques): fix dereference for if compressor: archive = compressor(archive) with open(path, "wb") as archive_fd: archive_fd.write(archive)
[ "def", "archive", "(", "self", ",", "path", ",", "dereference", "=", "False", ",", "compressor", "=", "None", ",", "revision", "=", "None", ")", ":", "if", "not", "self", ".", "git_backed", ":", "raise", "ValueError", "(", "\"{} is not backed by git\"", ".", "format", "(", "self", ")", ")", "rev", "=", "revision", "if", "revision", "else", "\"HEAD\"", "archive", "=", "git", ".", "archive", "(", "\"--prefix=apache-arrow/\"", ",", "rev", ",", "git_dir", "=", "self", ".", "path", ")", "# TODO(fsaintjacques): fix dereference for", "if", "compressor", ":", "archive", "=", "compressor", "(", "archive", ")", "with", "open", "(", "path", ",", "\"wb\"", ")", "as", "archive_fd", ":", "archive_fd", ".", "write", "(", "archive", ")" ]
https://github.com/apache/arrow/blob/af33dd1157eb8d7d9bfac25ebf61445b793b7943/dev/archery/archery/utils/source.py#L101-L116
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/sns/connection.py
python
SNSConnection.unsubscribe
(self, subscription)
return self._make_request('Unsubscribe', params)
Allows endpoint owner to delete subscription. Confirmation message will be delivered. :type subscription: string :param subscription: The ARN of the subscription to be deleted.
Allows endpoint owner to delete subscription. Confirmation message will be delivered.
[ "Allows", "endpoint", "owner", "to", "delete", "subscription", ".", "Confirmation", "message", "will", "be", "delivered", "." ]
def unsubscribe(self, subscription): """ Allows endpoint owner to delete subscription. Confirmation message will be delivered. :type subscription: string :param subscription: The ARN of the subscription to be deleted. """ params = {'SubscriptionArn': subscription} return self._make_request('Unsubscribe', params)
[ "def", "unsubscribe", "(", "self", ",", "subscription", ")", ":", "params", "=", "{", "'SubscriptionArn'", ":", "subscription", "}", "return", "self", ".", "_make_request", "(", "'Unsubscribe'", ",", "params", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/sns/connection.py#L398-L408
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/context.py
python
_Context.set_env_config_path
(self, env_config_path)
Check and set env_config_path.
Check and set env_config_path.
[ "Check", "and", "set", "env_config_path", "." ]
def set_env_config_path(self, env_config_path): """Check and set env_config_path.""" if not self._context_handle.enable_dump_ir(): raise ValueError("For 'context.set_context', the argument 'env_config_path' is not supported, please " "enable ENABLE_DUMP_IR with '-D on' and recompile source firstly.") env_config_path = os.path.realpath(env_config_path) if not os.path.isfile(env_config_path): raise ValueError("For 'context.set_context', the 'env_config_path' file %r is not exists, " "please check whether 'env_config_path' is correct." % env_config_path) try: with open(env_config_path, 'r') as f: json.load(f) except (TypeError, ValueError) as exo: raise ValueError(str(exo) + "\nFor 'context.set_context', open or load the 'env_config_path' file {} " "failed, please check whether 'env_config_path' is json file and correct, or may not " "have permission to read it.".format(env_config_path)) self.set_param(ms_ctx_param.env_config_path, env_config_path)
[ "def", "set_env_config_path", "(", "self", ",", "env_config_path", ")", ":", "if", "not", "self", ".", "_context_handle", ".", "enable_dump_ir", "(", ")", ":", "raise", "ValueError", "(", "\"For 'context.set_context', the argument 'env_config_path' is not supported, please \"", "\"enable ENABLE_DUMP_IR with '-D on' and recompile source firstly.\"", ")", "env_config_path", "=", "os", ".", "path", ".", "realpath", "(", "env_config_path", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "env_config_path", ")", ":", "raise", "ValueError", "(", "\"For 'context.set_context', the 'env_config_path' file %r is not exists, \"", "\"please check whether 'env_config_path' is correct.\"", "%", "env_config_path", ")", "try", ":", "with", "open", "(", "env_config_path", ",", "'r'", ")", "as", "f", ":", "json", ".", "load", "(", "f", ")", "except", "(", "TypeError", ",", "ValueError", ")", "as", "exo", ":", "raise", "ValueError", "(", "str", "(", "exo", ")", "+", "\"\\nFor 'context.set_context', open or load the 'env_config_path' file {} \"", "\"failed, please check whether 'env_config_path' is json file and correct, or may not \"", "\"have permission to read it.\"", ".", "format", "(", "env_config_path", ")", ")", "self", ".", "set_param", "(", "ms_ctx_param", ".", "env_config_path", ",", "env_config_path", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/context.py#L303-L319
paranoidninja/Pandoras-Box
91316052a337c3a91da0c6e69f3ba0076436a037
mingw/share/gcc-6.3.0/python/libstdcxx/v6/printers.py
python
SingleObjContainerPrinter._recognize
(self, type)
return gdb.types.apply_type_recognizers(gdb.types.get_type_recognizers(), type) or str(type)
Return TYPE as a string after applying type printers
Return TYPE as a string after applying type printers
[ "Return", "TYPE", "as", "a", "string", "after", "applying", "type", "printers" ]
def _recognize(self, type): """Return TYPE as a string after applying type printers""" global _use_type_printing if not _use_type_printing: return str(type) return gdb.types.apply_type_recognizers(gdb.types.get_type_recognizers(), type) or str(type)
[ "def", "_recognize", "(", "self", ",", "type", ")", ":", "global", "_use_type_printing", "if", "not", "_use_type_printing", ":", "return", "str", "(", "type", ")", "return", "gdb", ".", "types", ".", "apply_type_recognizers", "(", "gdb", ".", "types", ".", "get_type_recognizers", "(", ")", ",", "type", ")", "or", "str", "(", "type", ")" ]
https://github.com/paranoidninja/Pandoras-Box/blob/91316052a337c3a91da0c6e69f3ba0076436a037/mingw/share/gcc-6.3.0/python/libstdcxx/v6/printers.py#L886-L892
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
src/third_party/abseil-cpp-master/abseil-cpp/absl/abseil.podspec.gen.py
python
write_podspec_map
(f, cur_map, depth)
Writes podspec from rule map recursively.
Writes podspec from rule map recursively.
[ "Writes", "podspec", "from", "rule", "map", "recursively", "." ]
def write_podspec_map(f, cur_map, depth): """Writes podspec from rule map recursively.""" for key, value in sorted(cur_map.items()): indent = " " * (depth + 1) f.write("{indent}{var0}.subspec '{key}' do |{var1}|\n".format( indent=indent, key=key, var0=get_spec_var(depth), var1=get_spec_var(depth + 1))) if isinstance(value, dict): write_podspec_map(f, value, depth + 1) else: write_podspec_rule(f, value, depth + 1) f.write("{indent}end\n".format(indent=indent))
[ "def", "write_podspec_map", "(", "f", ",", "cur_map", ",", "depth", ")", ":", "for", "key", ",", "value", "in", "sorted", "(", "cur_map", ".", "items", "(", ")", ")", ":", "indent", "=", "\" \"", "*", "(", "depth", "+", "1", ")", "f", ".", "write", "(", "\"{indent}{var0}.subspec '{key}' do |{var1}|\\n\"", ".", "format", "(", "indent", "=", "indent", ",", "key", "=", "key", ",", "var0", "=", "get_spec_var", "(", "depth", ")", ",", "var1", "=", "get_spec_var", "(", "depth", "+", "1", ")", ")", ")", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "write_podspec_map", "(", "f", ",", "value", ",", "depth", "+", "1", ")", "else", ":", "write_podspec_rule", "(", "f", ",", "value", ",", "depth", "+", "1", ")", "f", ".", "write", "(", "\"{indent}end\\n\"", ".", "format", "(", "indent", "=", "indent", ")", ")" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/abseil-cpp-master/abseil-cpp/absl/abseil.podspec.gen.py#L158-L171
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/profiler/parser/integrator.py
python
AscendTimelineGenerator._get_merged_time_list
(self, time_list, get_interval_time=False, display_name="computation_op")
return merged_res_list, interval_display_list, merged_display_list
Get merged time segment list. The process of merge is, for example, there is a list [[1,5], [2,6], [7,8]], each items in this list contains a start_time and end_time, the merged result is [[1,6], [7,8]].
Get merged time segment list.
[ "Get", "merged", "time", "segment", "list", "." ]
def _get_merged_time_list(self, time_list, get_interval_time=False, display_name="computation_op"): """ Get merged time segment list. The process of merge is, for example, there is a list [[1,5], [2,6], [7,8]], each items in this list contains a start_time and end_time, the merged result is [[1,6], [7,8]]. """ time_merged_segment_list = [] tid = self._tid_dict[display_name][0] pid = self._tid_dict[display_name][1] for time_item in time_list: time_segment = list(map(float, time_item[self._start_time_idx:self._duration_idx + 1])) time_segment[1] += time_segment[0] if not time_merged_segment_list or \ time_segment[0] > time_merged_segment_list[-1]: time_merged_segment_list.extend(time_segment) else: time_merged_segment_list[-1] = max( time_merged_segment_list[-1], time_segment[1] ) # merged_display_list data used for ui page. merged_display_list = [ [display_name, tid, time_merged_segment_list[i * 2], time_merged_segment_list[i * 2 + 1] - time_merged_segment_list[i * 2], pid] for i in range(len(time_merged_segment_list) // 2) ] if get_interval_time: time_merged_segment_list = time_merged_segment_list[1:-1] # merged_res_list data used to compute overlap with other time_list. merged_res_list = [ [display_name, tid, time_merged_segment_list[i * 2], time_merged_segment_list[i * 2 + 1], pid] for i in range(len(time_merged_segment_list) // 2) ] # interval_display_list is interval time used for ui page. interval_display_list = [ [display_name, tid, time_merged_segment_list[i * 2], time_merged_segment_list[i * 2 + 1] - time_merged_segment_list[i * 2], pid] for i in range(len(time_merged_segment_list) // 2) ] return merged_res_list, interval_display_list, merged_display_list
[ "def", "_get_merged_time_list", "(", "self", ",", "time_list", ",", "get_interval_time", "=", "False", ",", "display_name", "=", "\"computation_op\"", ")", ":", "time_merged_segment_list", "=", "[", "]", "tid", "=", "self", ".", "_tid_dict", "[", "display_name", "]", "[", "0", "]", "pid", "=", "self", ".", "_tid_dict", "[", "display_name", "]", "[", "1", "]", "for", "time_item", "in", "time_list", ":", "time_segment", "=", "list", "(", "map", "(", "float", ",", "time_item", "[", "self", ".", "_start_time_idx", ":", "self", ".", "_duration_idx", "+", "1", "]", ")", ")", "time_segment", "[", "1", "]", "+=", "time_segment", "[", "0", "]", "if", "not", "time_merged_segment_list", "or", "time_segment", "[", "0", "]", ">", "time_merged_segment_list", "[", "-", "1", "]", ":", "time_merged_segment_list", ".", "extend", "(", "time_segment", ")", "else", ":", "time_merged_segment_list", "[", "-", "1", "]", "=", "max", "(", "time_merged_segment_list", "[", "-", "1", "]", ",", "time_segment", "[", "1", "]", ")", "# merged_display_list data used for ui page.", "merged_display_list", "=", "[", "[", "display_name", ",", "tid", ",", "time_merged_segment_list", "[", "i", "*", "2", "]", ",", "time_merged_segment_list", "[", "i", "*", "2", "+", "1", "]", "-", "time_merged_segment_list", "[", "i", "*", "2", "]", ",", "pid", "]", "for", "i", "in", "range", "(", "len", "(", "time_merged_segment_list", ")", "//", "2", ")", "]", "if", "get_interval_time", ":", "time_merged_segment_list", "=", "time_merged_segment_list", "[", "1", ":", "-", "1", "]", "# merged_res_list data used to compute overlap with other time_list.", "merged_res_list", "=", "[", "[", "display_name", ",", "tid", ",", "time_merged_segment_list", "[", "i", "*", "2", "]", ",", "time_merged_segment_list", "[", "i", "*", "2", "+", "1", "]", ",", "pid", "]", "for", "i", "in", "range", "(", "len", "(", "time_merged_segment_list", ")", "//", "2", ")", "]", "# interval_display_list is interval time used for ui page.", "interval_display_list", "=", "[", "[", "display_name", ",", "tid", ",", "time_merged_segment_list", "[", "i", "*", "2", "]", ",", "time_merged_segment_list", "[", "i", "*", "2", "+", "1", "]", "-", "time_merged_segment_list", "[", "i", "*", "2", "]", ",", "pid", "]", "for", "i", "in", "range", "(", "len", "(", "time_merged_segment_list", ")", "//", "2", ")", "]", "return", "merged_res_list", ",", "interval_display_list", ",", "merged_display_list" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/profiler/parser/integrator.py#L1459-L1505
LisaAnne/lisa-caffe-public
49b8643ddef23a4f6120017968de30c45e693f59
tools/extra/parse_log.py
python
get_line_type
(line)
return line_type
Return either 'test' or 'train' depending on line type
Return either 'test' or 'train' depending on line type
[ "Return", "either", "test", "or", "train", "depending", "on", "line", "type" ]
def get_line_type(line): """Return either 'test' or 'train' depending on line type """ line_type = None if line.find('Train') != -1: line_type = 'train' elif line.find('Test') != -1: line_type = 'test' return line_type
[ "def", "get_line_type", "(", "line", ")", ":", "line_type", "=", "None", "if", "line", ".", "find", "(", "'Train'", ")", "!=", "-", "1", ":", "line_type", "=", "'train'", "elif", "line", ".", "find", "(", "'Test'", ")", "!=", "-", "1", ":", "line_type", "=", "'test'", "return", "line_type" ]
https://github.com/LisaAnne/lisa-caffe-public/blob/49b8643ddef23a4f6120017968de30c45e693f59/tools/extra/parse_log.py#L16-L25
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/stc.py
python
StyledTextCtrl.GetViewWhiteSpace
(*args, **kwargs)
return _stc.StyledTextCtrl_GetViewWhiteSpace(*args, **kwargs)
GetViewWhiteSpace(self) -> int Are white space characters currently visible? Returns one of SCWS_* constants.
GetViewWhiteSpace(self) -> int
[ "GetViewWhiteSpace", "(", "self", ")", "-", ">", "int" ]
def GetViewWhiteSpace(*args, **kwargs): """ GetViewWhiteSpace(self) -> int Are white space characters currently visible? Returns one of SCWS_* constants. """ return _stc.StyledTextCtrl_GetViewWhiteSpace(*args, **kwargs)
[ "def", "GetViewWhiteSpace", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_GetViewWhiteSpace", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L2169-L2176
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
build/android/android_commands.py
python
AndroidCommands.RunShellCommand
(self, command, timeout_time=20, log_result=True)
return result
Send a command to the adb shell and return the result. Args: command: String containing the shell command to send. Must not include the single quotes as we use them to escape the whole command. timeout_time: Number of seconds to wait for command to respond before retrying, used by AdbInterface.SendShellCommand. log_result: Boolean to indicate whether we should log the result of the shell command. Returns: list containing the lines of output received from running the command
Send a command to the adb shell and return the result.
[ "Send", "a", "command", "to", "the", "adb", "shell", "and", "return", "the", "result", "." ]
def RunShellCommand(self, command, timeout_time=20, log_result=True): """Send a command to the adb shell and return the result. Args: command: String containing the shell command to send. Must not include the single quotes as we use them to escape the whole command. timeout_time: Number of seconds to wait for command to respond before retrying, used by AdbInterface.SendShellCommand. log_result: Boolean to indicate whether we should log the result of the shell command. Returns: list containing the lines of output received from running the command """ logging.info('>>> $' + command) if "'" in command: logging.warning(command + " contains ' quotes") result = self._adb.SendShellCommand("'%s'" % command, timeout_time).splitlines() if log_result: logging.info('\n>>> '.join(result)) return result
[ "def", "RunShellCommand", "(", "self", ",", "command", ",", "timeout_time", "=", "20", ",", "log_result", "=", "True", ")", ":", "logging", ".", "info", "(", "'>>> $'", "+", "command", ")", "if", "\"'\"", "in", "command", ":", "logging", ".", "warning", "(", "command", "+", "\" contains ' quotes\"", ")", "result", "=", "self", ".", "_adb", ".", "SendShellCommand", "(", "\"'%s'\"", "%", "command", ",", "timeout_time", ")", ".", "splitlines", "(", ")", "if", "log_result", ":", "logging", ".", "info", "(", "'\\n>>> '", ".", "join", "(", "result", ")", ")", "return", "result" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/build/android/android_commands.py#L305-L325
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/distributions/python/ops/bijectors/affine_linear_operator.py
python
AffineLinearOperator.__init__
(self, shift=None, scale=None, validate_args=False, name="affine_linear_operator")
Instantiates the `AffineLinearOperator` bijector. Args: shift: Floating-point `Tensor`. scale: Subclass of `LinearOperator`. Represents the (batch) positive definite matrix `M` in `R^{k x k}`. validate_args: Python `bool` indicating whether arguments should be checked for correctness. name: Python `str` name given to ops managed by this object. Raises: TypeError: if `scale` is not a `LinearOperator`. TypeError: if `shift.dtype` does not match `scale.dtype`. ValueError: if not `scale.is_non_singular`.
Instantiates the `AffineLinearOperator` bijector.
[ "Instantiates", "the", "AffineLinearOperator", "bijector", "." ]
def __init__(self, shift=None, scale=None, validate_args=False, name="affine_linear_operator"): """Instantiates the `AffineLinearOperator` bijector. Args: shift: Floating-point `Tensor`. scale: Subclass of `LinearOperator`. Represents the (batch) positive definite matrix `M` in `R^{k x k}`. validate_args: Python `bool` indicating whether arguments should be checked for correctness. name: Python `str` name given to ops managed by this object. Raises: TypeError: if `scale` is not a `LinearOperator`. TypeError: if `shift.dtype` does not match `scale.dtype`. ValueError: if not `scale.is_non_singular`. """ self._graph_parents = [] self._name = name self._validate_args = validate_args graph_parents = [] with self._name_scope("init", values=[shift]): # In the absence of `loc` and `scale`, we'll assume `dtype` is `float32`. dtype = dtypes.float32 if shift is not None: shift = ops.convert_to_tensor(shift, name="shift") graph_parents += [shift] dtype = shift.dtype.base_dtype self._shift = shift if scale is not None: if (shift is not None and shift.dtype.base_dtype != scale.dtype.base_dtype): raise TypeError( "shift.dtype({}) is incompatible with scale.dtype({}).".format( shift.dtype, scale.dtype)) if not isinstance(scale, linear_operator.LinearOperator): raise TypeError("scale is not an instance of tf.LinearOperator") if validate_args and not scale.is_non_singular: raise ValueError("Scale matrix must be non-singular.") graph_parents += scale.graph_parents if scale.tensor_rank is not None: batch_ndims = scale.tensor_rank - 2 else: batch_ndims = scale.tensor_rank_tensor() - 2 graph_parents += [batch_ndims] if scale.dtype is not None: dtype = scale.dtype.base_dtype else: batch_ndims = 0 # We won't need shape inference when scale is None. self._scale = scale self._shaper = _DistributionShape( batch_ndims=batch_ndims, event_ndims=1, validate_args=validate_args) super(AffineLinearOperator, self).__init__( forward_min_event_ndims=1, graph_parents=graph_parents, is_constant_jacobian=True, dtype=dtype, validate_args=validate_args, name=name)
[ "def", "__init__", "(", "self", ",", "shift", "=", "None", ",", "scale", "=", "None", ",", "validate_args", "=", "False", ",", "name", "=", "\"affine_linear_operator\"", ")", ":", "self", ".", "_graph_parents", "=", "[", "]", "self", ".", "_name", "=", "name", "self", ".", "_validate_args", "=", "validate_args", "graph_parents", "=", "[", "]", "with", "self", ".", "_name_scope", "(", "\"init\"", ",", "values", "=", "[", "shift", "]", ")", ":", "# In the absence of `loc` and `scale`, we'll assume `dtype` is `float32`.", "dtype", "=", "dtypes", ".", "float32", "if", "shift", "is", "not", "None", ":", "shift", "=", "ops", ".", "convert_to_tensor", "(", "shift", ",", "name", "=", "\"shift\"", ")", "graph_parents", "+=", "[", "shift", "]", "dtype", "=", "shift", ".", "dtype", ".", "base_dtype", "self", ".", "_shift", "=", "shift", "if", "scale", "is", "not", "None", ":", "if", "(", "shift", "is", "not", "None", "and", "shift", ".", "dtype", ".", "base_dtype", "!=", "scale", ".", "dtype", ".", "base_dtype", ")", ":", "raise", "TypeError", "(", "\"shift.dtype({}) is incompatible with scale.dtype({}).\"", ".", "format", "(", "shift", ".", "dtype", ",", "scale", ".", "dtype", ")", ")", "if", "not", "isinstance", "(", "scale", ",", "linear_operator", ".", "LinearOperator", ")", ":", "raise", "TypeError", "(", "\"scale is not an instance of tf.LinearOperator\"", ")", "if", "validate_args", "and", "not", "scale", ".", "is_non_singular", ":", "raise", "ValueError", "(", "\"Scale matrix must be non-singular.\"", ")", "graph_parents", "+=", "scale", ".", "graph_parents", "if", "scale", ".", "tensor_rank", "is", "not", "None", ":", "batch_ndims", "=", "scale", ".", "tensor_rank", "-", "2", "else", ":", "batch_ndims", "=", "scale", ".", "tensor_rank_tensor", "(", ")", "-", "2", "graph_parents", "+=", "[", "batch_ndims", "]", "if", "scale", ".", "dtype", "is", "not", "None", ":", "dtype", "=", "scale", ".", "dtype", ".", "base_dtype", "else", ":", "batch_ndims", "=", "0", "# We won't need shape inference when scale is None.", "self", ".", "_scale", "=", "scale", "self", ".", "_shaper", "=", "_DistributionShape", "(", "batch_ndims", "=", "batch_ndims", ",", "event_ndims", "=", "1", ",", "validate_args", "=", "validate_args", ")", "super", "(", "AffineLinearOperator", ",", "self", ")", ".", "__init__", "(", "forward_min_event_ndims", "=", "1", ",", "graph_parents", "=", "graph_parents", ",", "is_constant_jacobian", "=", "True", ",", "dtype", "=", "dtype", ",", "validate_args", "=", "validate_args", ",", "name", "=", "name", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/distributions/python/ops/bijectors/affine_linear_operator.py#L100-L165
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/contrib/layers/python/layers/feature_column.py
python
sparse_column_with_hash_bucket
(column_name, hash_bucket_size, combiner="sum")
return _SparseColumnHashed(column_name, hash_bucket_size, combiner)
Creates a _SparseColumn with hashed bucket configuration. Use this when your sparse features are in string format, but you don't have a vocab file that maps each string to an integer ID. output_id = Hash(input_feature_string) % bucket_size Args: column_name: A string defining sparse column name. hash_bucket_size: An int that is > 1. The number of buckets. combiner: A string specifying how to reduce if the sparse column is multivalent. Currently "mean", "sqrtn" and "sum" are supported, with "sum" the default: * "sum": do not normalize features in the column * "mean": do l1 normalization on features in the column * "sqrtn": do l2 normalization on features in the column For more information: `tf.embedding_lookup_sparse`. Returns: A _SparseColumn with hashed bucket configuration Raises: ValueError: hash_bucket_size is not greater than 2.
Creates a _SparseColumn with hashed bucket configuration.
[ "Creates", "a", "_SparseColumn", "with", "hashed", "bucket", "configuration", "." ]
def sparse_column_with_hash_bucket(column_name, hash_bucket_size, combiner="sum"): """Creates a _SparseColumn with hashed bucket configuration. Use this when your sparse features are in string format, but you don't have a vocab file that maps each string to an integer ID. output_id = Hash(input_feature_string) % bucket_size Args: column_name: A string defining sparse column name. hash_bucket_size: An int that is > 1. The number of buckets. combiner: A string specifying how to reduce if the sparse column is multivalent. Currently "mean", "sqrtn" and "sum" are supported, with "sum" the default: * "sum": do not normalize features in the column * "mean": do l1 normalization on features in the column * "sqrtn": do l2 normalization on features in the column For more information: `tf.embedding_lookup_sparse`. Returns: A _SparseColumn with hashed bucket configuration Raises: ValueError: hash_bucket_size is not greater than 2. """ return _SparseColumnHashed(column_name, hash_bucket_size, combiner)
[ "def", "sparse_column_with_hash_bucket", "(", "column_name", ",", "hash_bucket_size", ",", "combiner", "=", "\"sum\"", ")", ":", "return", "_SparseColumnHashed", "(", "column_name", ",", "hash_bucket_size", ",", "combiner", ")" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/layers/python/layers/feature_column.py#L373-L399
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/protobuf/py3/google/protobuf/internal/python_message.py
python
_AddPropertiesForField
(field, cls)
Adds a public property for a protocol message field. Clients can use this property to get and (in the case of non-repeated scalar fields) directly set the value of a protocol message field. Args: field: A FieldDescriptor for this field. cls: The class we're constructing.
Adds a public property for a protocol message field. Clients can use this property to get and (in the case of non-repeated scalar fields) directly set the value of a protocol message field.
[ "Adds", "a", "public", "property", "for", "a", "protocol", "message", "field", ".", "Clients", "can", "use", "this", "property", "to", "get", "and", "(", "in", "the", "case", "of", "non", "-", "repeated", "scalar", "fields", ")", "directly", "set", "the", "value", "of", "a", "protocol", "message", "field", "." ]
def _AddPropertiesForField(field, cls): """Adds a public property for a protocol message field. Clients can use this property to get and (in the case of non-repeated scalar fields) directly set the value of a protocol message field. Args: field: A FieldDescriptor for this field. cls: The class we're constructing. """ # Catch it if we add other types that we should # handle specially here. assert _FieldDescriptor.MAX_CPPTYPE == 10 constant_name = field.name.upper() + '_FIELD_NUMBER' setattr(cls, constant_name, field.number) if field.label == _FieldDescriptor.LABEL_REPEATED: _AddPropertiesForRepeatedField(field, cls) elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: _AddPropertiesForNonRepeatedCompositeField(field, cls) else: _AddPropertiesForNonRepeatedScalarField(field, cls)
[ "def", "_AddPropertiesForField", "(", "field", ",", "cls", ")", ":", "# Catch it if we add other types that we should", "# handle specially here.", "assert", "_FieldDescriptor", ".", "MAX_CPPTYPE", "==", "10", "constant_name", "=", "field", ".", "name", ".", "upper", "(", ")", "+", "'_FIELD_NUMBER'", "setattr", "(", "cls", ",", "constant_name", ",", "field", ".", "number", ")", "if", "field", ".", "label", "==", "_FieldDescriptor", ".", "LABEL_REPEATED", ":", "_AddPropertiesForRepeatedField", "(", "field", ",", "cls", ")", "elif", "field", ".", "cpp_type", "==", "_FieldDescriptor", ".", "CPPTYPE_MESSAGE", ":", "_AddPropertiesForNonRepeatedCompositeField", "(", "field", ",", "cls", ")", "else", ":", "_AddPropertiesForNonRepeatedScalarField", "(", "field", ",", "cls", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py3/google/protobuf/internal/python_message.py#L605-L627
amd/OpenCL-caffe
638543108517265366c18ae5821f3096cf5cf34a
scripts/cpp_lint.py
python
ParseNolintSuppressions
(filename, raw_line, linenum, error)
Updates the global list of error-suppressions. Parses any NOLINT comments on the current line, updating the global error_suppressions store. Reports an error if the NOLINT comment was malformed. Args: filename: str, the name of the input file. raw_line: str, the line of input text, with comments. linenum: int, the number of the current line. error: function, an error handler.
Updates the global list of error-suppressions.
[ "Updates", "the", "global", "list", "of", "error", "-", "suppressions", "." ]
def ParseNolintSuppressions(filename, raw_line, linenum, error): """Updates the global list of error-suppressions. Parses any NOLINT comments on the current line, updating the global error_suppressions store. Reports an error if the NOLINT comment was malformed. Args: filename: str, the name of the input file. raw_line: str, the line of input text, with comments. linenum: int, the number of the current line. error: function, an error handler. """ # FIXME(adonovan): "NOLINT(" is misparsed as NOLINT(*). matched = _RE_SUPPRESSION.search(raw_line) if matched: if matched.group(1) == '_NEXT_LINE': linenum += 1 category = matched.group(2) if category in (None, '(*)'): # => "suppress all" _error_suppressions.setdefault(None, set()).add(linenum) else: if category.startswith('(') and category.endswith(')'): category = category[1:-1] if category in _ERROR_CATEGORIES: _error_suppressions.setdefault(category, set()).add(linenum) else: error(filename, linenum, 'readability/nolint', 5, 'Unknown NOLINT error category: %s' % category)
[ "def", "ParseNolintSuppressions", "(", "filename", ",", "raw_line", ",", "linenum", ",", "error", ")", ":", "# FIXME(adonovan): \"NOLINT(\" is misparsed as NOLINT(*).", "matched", "=", "_RE_SUPPRESSION", ".", "search", "(", "raw_line", ")", "if", "matched", ":", "if", "matched", ".", "group", "(", "1", ")", "==", "'_NEXT_LINE'", ":", "linenum", "+=", "1", "category", "=", "matched", ".", "group", "(", "2", ")", "if", "category", "in", "(", "None", ",", "'(*)'", ")", ":", "# => \"suppress all\"", "_error_suppressions", ".", "setdefault", "(", "None", ",", "set", "(", ")", ")", ".", "add", "(", "linenum", ")", "else", ":", "if", "category", ".", "startswith", "(", "'('", ")", "and", "category", ".", "endswith", "(", "')'", ")", ":", "category", "=", "category", "[", "1", ":", "-", "1", "]", "if", "category", "in", "_ERROR_CATEGORIES", ":", "_error_suppressions", ".", "setdefault", "(", "category", ",", "set", "(", ")", ")", ".", "add", "(", "linenum", ")", "else", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/nolint'", ",", "5", ",", "'Unknown NOLINT error category: %s'", "%", "category", ")" ]
https://github.com/amd/OpenCL-caffe/blob/638543108517265366c18ae5821f3096cf5cf34a/scripts/cpp_lint.py#L464-L492
GJDuck/LowFat
ecf6a0f0fa1b73a27a626cf493cc39e477b6faea
llvm-4.0.0.src/projects/compiler-rt/lib/sanitizer_common/scripts/cpplint.py
python
_CppLintState.ResetErrorCounts
(self)
Sets the module's error statistic back to zero.
Sets the module's error statistic back to zero.
[ "Sets", "the", "module", "s", "error", "statistic", "back", "to", "zero", "." ]
def ResetErrorCounts(self): """Sets the module's error statistic back to zero.""" self.error_count = 0 self.errors_by_category = {}
[ "def", "ResetErrorCounts", "(", "self", ")", ":", "self", ".", "error_count", "=", "0", "self", ".", "errors_by_category", "=", "{", "}" ]
https://github.com/GJDuck/LowFat/blob/ecf6a0f0fa1b73a27a626cf493cc39e477b6faea/llvm-4.0.0.src/projects/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L606-L609
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/ttk.py
python
OptionMenu.__init__
(self, master, variable, default=None, *values, **kwargs)
Construct a themed OptionMenu widget with master as the parent, the resource textvariable set to variable, the initially selected value specified by the default parameter, the menu values given by *values and additional keywords. WIDGET-SPECIFIC OPTIONS style: stylename Menubutton style. direction: 'above', 'below', 'left', 'right', or 'flush' Menubutton direction. command: callback A callback that will be invoked after selecting an item.
Construct a themed OptionMenu widget with master as the parent, the resource textvariable set to variable, the initially selected value specified by the default parameter, the menu values given by *values and additional keywords.
[ "Construct", "a", "themed", "OptionMenu", "widget", "with", "master", "as", "the", "parent", "the", "resource", "textvariable", "set", "to", "variable", "the", "initially", "selected", "value", "specified", "by", "the", "default", "parameter", "the", "menu", "values", "given", "by", "*", "values", "and", "additional", "keywords", "." ]
def __init__(self, master, variable, default=None, *values, **kwargs): """Construct a themed OptionMenu widget with master as the parent, the resource textvariable set to variable, the initially selected value specified by the default parameter, the menu values given by *values and additional keywords. WIDGET-SPECIFIC OPTIONS style: stylename Menubutton style. direction: 'above', 'below', 'left', 'right', or 'flush' Menubutton direction. command: callback A callback that will be invoked after selecting an item. """ kw = {'textvariable': variable, 'style': kwargs.pop('style', None), 'direction': kwargs.pop('direction', None)} Menubutton.__init__(self, master, **kw) self['menu'] = Tkinter.Menu(self, tearoff=False) self._variable = variable self._callback = kwargs.pop('command', None) if kwargs: raise Tkinter.TclError('unknown option -%s' % ( kwargs.iterkeys().next())) self.set_menu(default, *values)
[ "def", "__init__", "(", "self", ",", "master", ",", "variable", ",", "default", "=", "None", ",", "*", "values", ",", "*", "*", "kwargs", ")", ":", "kw", "=", "{", "'textvariable'", ":", "variable", ",", "'style'", ":", "kwargs", ".", "pop", "(", "'style'", ",", "None", ")", ",", "'direction'", ":", "kwargs", ".", "pop", "(", "'direction'", ",", "None", ")", "}", "Menubutton", ".", "__init__", "(", "self", ",", "master", ",", "*", "*", "kw", ")", "self", "[", "'menu'", "]", "=", "Tkinter", ".", "Menu", "(", "self", ",", "tearoff", "=", "False", ")", "self", ".", "_variable", "=", "variable", "self", ".", "_callback", "=", "kwargs", ".", "pop", "(", "'command'", ",", "None", ")", "if", "kwargs", ":", "raise", "Tkinter", ".", "TclError", "(", "'unknown option -%s'", "%", "(", "kwargs", ".", "iterkeys", "(", ")", ".", "next", "(", ")", ")", ")", "self", ".", "set_menu", "(", "default", ",", "*", "values", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/ttk.py#L1557-L1583
microsoft/CNTK
e9396480025b9ca457d26b6f33dd07c474c6aa04
bindings/python/cntk/losses/__init__.py
python
fmeasure
(output, target, beta=1)
return 1 - (1 + beta ** 2) * precision * recall / (beta ** 2 * precision + recall)
This operation computes the f-measure between the output and target. If beta is set as one, its called the f1-scorce or dice similarity coefficient. f1-scorce is monotonic in jaccard distance. f-measure = (1 + beta ** 2) * precision * recall / (beta ** 2 * precision + recall) This loss function is frequently used in semantic segmentation of images. Works with imbalanced classes, for balanced classes you should prefer cross_entropy instead. This operation works with both binary and multiclass classification. Args: output: the output values from the network target: it is usually a one-hot vector where the hot bit corresponds to the label index beta: greater than one weights recall higher than precision, less than one for the opposite. Commonly chosen values are 0.5, 1 or 2. Returns: :class:`~cntk.ops.functions.Function`
This operation computes the f-measure between the output and target. If beta is set as one, its called the f1-scorce or dice similarity coefficient. f1-scorce is monotonic in jaccard distance.
[ "This", "operation", "computes", "the", "f", "-", "measure", "between", "the", "output", "and", "target", ".", "If", "beta", "is", "set", "as", "one", "its", "called", "the", "f1", "-", "scorce", "or", "dice", "similarity", "coefficient", ".", "f1", "-", "scorce", "is", "monotonic", "in", "jaccard", "distance", "." ]
def fmeasure(output, target, beta=1): """ This operation computes the f-measure between the output and target. If beta is set as one, its called the f1-scorce or dice similarity coefficient. f1-scorce is monotonic in jaccard distance. f-measure = (1 + beta ** 2) * precision * recall / (beta ** 2 * precision + recall) This loss function is frequently used in semantic segmentation of images. Works with imbalanced classes, for balanced classes you should prefer cross_entropy instead. This operation works with both binary and multiclass classification. Args: output: the output values from the network target: it is usually a one-hot vector where the hot bit corresponds to the label index beta: greater than one weights recall higher than precision, less than one for the opposite. Commonly chosen values are 0.5, 1 or 2. Returns: :class:`~cntk.ops.functions.Function` """ assert len(target.shape) == len(output.shape) if len(output.shape) == 3: axis = (1, 2) # assumes that the first axis is the class axis else: axis = None correct_predictions = C.reduce_sum(output * target, axis=axis) precision = correct_predictions / C.reduce_sum(output, axis=axis) recall = correct_predictions / C.reduce_sum(target, axis=axis) return 1 - (1 + beta ** 2) * precision * recall / (beta ** 2 * precision + recall)
[ "def", "fmeasure", "(", "output", ",", "target", ",", "beta", "=", "1", ")", ":", "assert", "len", "(", "target", ".", "shape", ")", "==", "len", "(", "output", ".", "shape", ")", "if", "len", "(", "output", ".", "shape", ")", "==", "3", ":", "axis", "=", "(", "1", ",", "2", ")", "# assumes that the first axis is the class axis", "else", ":", "axis", "=", "None", "correct_predictions", "=", "C", ".", "reduce_sum", "(", "output", "*", "target", ",", "axis", "=", "axis", ")", "precision", "=", "correct_predictions", "/", "C", ".", "reduce_sum", "(", "output", ",", "axis", "=", "axis", ")", "recall", "=", "correct_predictions", "/", "C", ".", "reduce_sum", "(", "target", ",", "axis", "=", "axis", ")", "return", "1", "-", "(", "1", "+", "beta", "**", "2", ")", "*", "precision", "*", "recall", "/", "(", "beta", "**", "2", "*", "precision", "+", "recall", ")" ]
https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/bindings/python/cntk/losses/__init__.py#L424-L456
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_controls.py
python
TextAttr.Apply
(*args, **kwargs)
return _controls_.TextAttr_Apply(*args, **kwargs)
Apply(self, TextAttr style, TextAttr compareWith=None) -> bool
Apply(self, TextAttr style, TextAttr compareWith=None) -> bool
[ "Apply", "(", "self", "TextAttr", "style", "TextAttr", "compareWith", "=", "None", ")", "-", ">", "bool" ]
def Apply(*args, **kwargs): """Apply(self, TextAttr style, TextAttr compareWith=None) -> bool""" return _controls_.TextAttr_Apply(*args, **kwargs)
[ "def", "Apply", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "TextAttr_Apply", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L1912-L1914
etodd/lasercrabs
91484d9ac3a47ac38b8f40ec3ff35194714dad8e
assets/script/etodd_blender_fbx/fbx_utils.py
python
elem_props_template_init
(templates, template_type)
return ret
Init a writing template of given type, for *one* element's properties.
Init a writing template of given type, for *one* element's properties.
[ "Init", "a", "writing", "template", "of", "given", "type", "for", "*", "one", "*", "element", "s", "properties", "." ]
def elem_props_template_init(templates, template_type): """ Init a writing template of given type, for *one* element's properties. """ ret = OrderedDict() tmpl = templates.get(template_type) if tmpl is not None: written = tmpl.written[0] props = tmpl.properties ret = OrderedDict((name, [val, ptype, anim, written]) for name, (val, ptype, anim) in props.items()) return ret
[ "def", "elem_props_template_init", "(", "templates", ",", "template_type", ")", ":", "ret", "=", "OrderedDict", "(", ")", "tmpl", "=", "templates", ".", "get", "(", "template_type", ")", "if", "tmpl", "is", "not", "None", ":", "written", "=", "tmpl", ".", "written", "[", "0", "]", "props", "=", "tmpl", ".", "properties", "ret", "=", "OrderedDict", "(", "(", "name", ",", "[", "val", ",", "ptype", ",", "anim", ",", "written", "]", ")", "for", "name", ",", "(", "val", ",", "ptype", ",", "anim", ")", "in", "props", ".", "items", "(", ")", ")", "return", "ret" ]
https://github.com/etodd/lasercrabs/blob/91484d9ac3a47ac38b8f40ec3ff35194714dad8e/assets/script/etodd_blender_fbx/fbx_utils.py#L613-L623
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/plat-mac/gensuitemodule.py
python
processfile
(fullname, output=None, basepkgname=None, edit_modnames=None, creatorsignature=None, dump=None, verbose=None)
Ask an application for its terminology and process that
Ask an application for its terminology and process that
[ "Ask", "an", "application", "for", "its", "terminology", "and", "process", "that" ]
def processfile(fullname, output=None, basepkgname=None, edit_modnames=None, creatorsignature=None, dump=None, verbose=None): """Ask an application for its terminology and process that""" if not is_scriptable(fullname) and verbose: print >>verbose, "Warning: app does not seem scriptable: %s" % fullname if verbose: print >>verbose, "\nASKING FOR aete DICTIONARY IN", repr(fullname) try: aedescobj, launched = OSATerminology.GetAppTerminology(fullname) except MacOS.Error, arg: if arg[0] in (-1701, -192): # errAEDescNotFound, resNotFound if verbose: print >>verbose, "GetAppTerminology failed with errAEDescNotFound/resNotFound, trying manually" aedata, sig = getappterminology(fullname, verbose=verbose) if not creatorsignature: creatorsignature = sig else: raise else: if launched: if verbose: print >>verbose, "Launched", fullname raw = aetools.unpack(aedescobj) if not raw: if verbose: print >>verbose, 'Unpack returned empty value:', raw return if not raw[0].data: if verbose: print >>verbose, 'Unpack returned value without data:', raw return aedata = raw[0] aete = decode(aedata.data, verbose) if dump: dumpaetelist([aete], dump) return compileaete(aete, None, fullname, output=output, basepkgname=basepkgname, creatorsignature=creatorsignature, edit_modnames=edit_modnames, verbose=verbose)
[ "def", "processfile", "(", "fullname", ",", "output", "=", "None", ",", "basepkgname", "=", "None", ",", "edit_modnames", "=", "None", ",", "creatorsignature", "=", "None", ",", "dump", "=", "None", ",", "verbose", "=", "None", ")", ":", "if", "not", "is_scriptable", "(", "fullname", ")", "and", "verbose", ":", "print", ">>", "verbose", ",", "\"Warning: app does not seem scriptable: %s\"", "%", "fullname", "if", "verbose", ":", "print", ">>", "verbose", ",", "\"\\nASKING FOR aete DICTIONARY IN\"", ",", "repr", "(", "fullname", ")", "try", ":", "aedescobj", ",", "launched", "=", "OSATerminology", ".", "GetAppTerminology", "(", "fullname", ")", "except", "MacOS", ".", "Error", ",", "arg", ":", "if", "arg", "[", "0", "]", "in", "(", "-", "1701", ",", "-", "192", ")", ":", "# errAEDescNotFound, resNotFound", "if", "verbose", ":", "print", ">>", "verbose", ",", "\"GetAppTerminology failed with errAEDescNotFound/resNotFound, trying manually\"", "aedata", ",", "sig", "=", "getappterminology", "(", "fullname", ",", "verbose", "=", "verbose", ")", "if", "not", "creatorsignature", ":", "creatorsignature", "=", "sig", "else", ":", "raise", "else", ":", "if", "launched", ":", "if", "verbose", ":", "print", ">>", "verbose", ",", "\"Launched\"", ",", "fullname", "raw", "=", "aetools", ".", "unpack", "(", "aedescobj", ")", "if", "not", "raw", ":", "if", "verbose", ":", "print", ">>", "verbose", ",", "'Unpack returned empty value:'", ",", "raw", "return", "if", "not", "raw", "[", "0", "]", ".", "data", ":", "if", "verbose", ":", "print", ">>", "verbose", ",", "'Unpack returned value without data:'", ",", "raw", "return", "aedata", "=", "raw", "[", "0", "]", "aete", "=", "decode", "(", "aedata", ".", "data", ",", "verbose", ")", "if", "dump", ":", "dumpaetelist", "(", "[", "aete", "]", ",", "dump", ")", "return", "compileaete", "(", "aete", ",", "None", ",", "fullname", ",", "output", "=", "output", ",", "basepkgname", "=", "basepkgname", ",", "creatorsignature", "=", "creatorsignature", ",", "edit_modnames", "=", "edit_modnames", ",", "verbose", "=", "verbose", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/plat-mac/gensuitemodule.py#L186-L225
tiny-dnn/tiny-dnn
c0f576f5cb7b35893f62127cb7aec18f77a3bcc5
third_party/cpplint.py
python
FilesBelongToSameModule
(filename_cc, filename_h)
return files_belong_to_same_module, common_path
Check if these two filenames belong to the same module. The concept of a 'module' here is a as follows: foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the same 'module' if they are in the same directory. some/path/public/xyzzy and some/path/internal/xyzzy are also considered to belong to the same module here. If the filename_cc contains a longer path than the filename_h, for example, '/absolute/path/to/base/sysinfo.cc', and this file would include 'base/sysinfo.h', this function also produces the prefix needed to open the header. This is used by the caller of this function to more robustly open the header file. We don't have access to the real include paths in this context, so we need this guesswork here. Known bugs: tools/base/bar.cc and base/bar.h belong to the same module according to this implementation. Because of this, this function gives some false positives. This should be sufficiently rare in practice. Args: filename_cc: is the path for the source (e.g. .cc) file filename_h: is the path for the header path Returns: Tuple with a bool and a string: bool: True if filename_cc and filename_h belong to the same module. string: the additional prefix needed to open the header file.
Check if these two filenames belong to the same module.
[ "Check", "if", "these", "two", "filenames", "belong", "to", "the", "same", "module", "." ]
def FilesBelongToSameModule(filename_cc, filename_h): """Check if these two filenames belong to the same module. The concept of a 'module' here is a as follows: foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the same 'module' if they are in the same directory. some/path/public/xyzzy and some/path/internal/xyzzy are also considered to belong to the same module here. If the filename_cc contains a longer path than the filename_h, for example, '/absolute/path/to/base/sysinfo.cc', and this file would include 'base/sysinfo.h', this function also produces the prefix needed to open the header. This is used by the caller of this function to more robustly open the header file. We don't have access to the real include paths in this context, so we need this guesswork here. Known bugs: tools/base/bar.cc and base/bar.h belong to the same module according to this implementation. Because of this, this function gives some false positives. This should be sufficiently rare in practice. Args: filename_cc: is the path for the source (e.g. .cc) file filename_h: is the path for the header path Returns: Tuple with a bool and a string: bool: True if filename_cc and filename_h belong to the same module. string: the additional prefix needed to open the header file. """ fileinfo_cc = FileInfo(filename_cc) if not fileinfo_cc.Extension().lstrip('.') in GetNonHeaderExtensions(): return (False, '') fileinfo_h = FileInfo(filename_h) if not fileinfo_h.Extension().lstrip('.') in GetHeaderExtensions(): return (False, '') filename_cc = filename_cc[:-(len(fileinfo_cc.Extension()))] matched_test_suffix = Search(_TEST_FILE_SUFFIX, fileinfo_cc.BaseName()) if matched_test_suffix: filename_cc = filename_cc[:-len(matched_test_suffix.group(1))] filename_cc = filename_cc.replace('/public/', '/') filename_cc = filename_cc.replace('/internal/', '/') filename_h = filename_h[:-(len(fileinfo_h.Extension()))] if filename_h.endswith('-inl'): filename_h = filename_h[:-len('-inl')] filename_h = filename_h.replace('/public/', '/') filename_h = filename_h.replace('/internal/', '/') files_belong_to_same_module = filename_cc.endswith(filename_h) common_path = '' if files_belong_to_same_module: common_path = filename_cc[:-len(filename_h)] return files_belong_to_same_module, common_path
[ "def", "FilesBelongToSameModule", "(", "filename_cc", ",", "filename_h", ")", ":", "fileinfo_cc", "=", "FileInfo", "(", "filename_cc", ")", "if", "not", "fileinfo_cc", ".", "Extension", "(", ")", ".", "lstrip", "(", "'.'", ")", "in", "GetNonHeaderExtensions", "(", ")", ":", "return", "(", "False", ",", "''", ")", "fileinfo_h", "=", "FileInfo", "(", "filename_h", ")", "if", "not", "fileinfo_h", ".", "Extension", "(", ")", ".", "lstrip", "(", "'.'", ")", "in", "GetHeaderExtensions", "(", ")", ":", "return", "(", "False", ",", "''", ")", "filename_cc", "=", "filename_cc", "[", ":", "-", "(", "len", "(", "fileinfo_cc", ".", "Extension", "(", ")", ")", ")", "]", "matched_test_suffix", "=", "Search", "(", "_TEST_FILE_SUFFIX", ",", "fileinfo_cc", ".", "BaseName", "(", ")", ")", "if", "matched_test_suffix", ":", "filename_cc", "=", "filename_cc", "[", ":", "-", "len", "(", "matched_test_suffix", ".", "group", "(", "1", ")", ")", "]", "filename_cc", "=", "filename_cc", ".", "replace", "(", "'/public/'", ",", "'/'", ")", "filename_cc", "=", "filename_cc", ".", "replace", "(", "'/internal/'", ",", "'/'", ")", "filename_h", "=", "filename_h", "[", ":", "-", "(", "len", "(", "fileinfo_h", ".", "Extension", "(", ")", ")", ")", "]", "if", "filename_h", ".", "endswith", "(", "'-inl'", ")", ":", "filename_h", "=", "filename_h", "[", ":", "-", "len", "(", "'-inl'", ")", "]", "filename_h", "=", "filename_h", ".", "replace", "(", "'/public/'", ",", "'/'", ")", "filename_h", "=", "filename_h", ".", "replace", "(", "'/internal/'", ",", "'/'", ")", "files_belong_to_same_module", "=", "filename_cc", ".", "endswith", "(", "filename_h", ")", "common_path", "=", "''", "if", "files_belong_to_same_module", ":", "common_path", "=", "filename_cc", "[", ":", "-", "len", "(", "filename_h", ")", "]", "return", "files_belong_to_same_module", ",", "common_path" ]
https://github.com/tiny-dnn/tiny-dnn/blob/c0f576f5cb7b35893f62127cb7aec18f77a3bcc5/third_party/cpplint.py#L5571-L5626
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/symbol/symbol.py
python
Symbol.expm1
(self, *args, **kwargs)
return op.expm1(self, *args, **kwargs)
Convenience fluent method for :py:func:`expm1`. The arguments are the same as for :py:func:`expm1`, with this array as data.
Convenience fluent method for :py:func:`expm1`.
[ "Convenience", "fluent", "method", "for", ":", "py", ":", "func", ":", "expm1", "." ]
def expm1(self, *args, **kwargs): """Convenience fluent method for :py:func:`expm1`. The arguments are the same as for :py:func:`expm1`, with this array as data. """ return op.expm1(self, *args, **kwargs)
[ "def", "expm1", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "op", ".", "expm1", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/symbol/symbol.py#L2485-L2491
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/fx/operator_schemas.py
python
normalize_module
( root: torch.nn.Module, target: str, args: Tuple[Any], kwargs : Optional[Dict[str, Any]] = None, normalize_to_only_use_kwargs : bool = False)
return None
Returns normalized arguments to PyTorch modules. This means that `args/kwargs` will be matched up to the functional's signature and return exclusively kwargs in positional order if `normalize_to_only_use_kwargs` is True. Also populates default values. Does not support positional-only parameters or varargs parameters (*args, **kwargs). Args: root (nn.Module): root module upon which we query modules target (Callable): Function that we are normalizing args (Tuple[Any]): Tuple of args to the function kwargs (Optional[Dict[str, Any]]): Dict of kwargs to the function normalize_to_only_use_kwargs (bool): Whether to normalize to only use kwargs. Returns: Returns normalized_args_and_kwargs, or `None` if not successful.
Returns normalized arguments to PyTorch modules. This means that `args/kwargs` will be matched up to the functional's signature and return exclusively kwargs in positional order if `normalize_to_only_use_kwargs` is True. Also populates default values. Does not support positional-only parameters or varargs parameters (*args, **kwargs).
[ "Returns", "normalized", "arguments", "to", "PyTorch", "modules", ".", "This", "means", "that", "args", "/", "kwargs", "will", "be", "matched", "up", "to", "the", "functional", "s", "signature", "and", "return", "exclusively", "kwargs", "in", "positional", "order", "if", "normalize_to_only_use_kwargs", "is", "True", ".", "Also", "populates", "default", "values", ".", "Does", "not", "support", "positional", "-", "only", "parameters", "or", "varargs", "parameters", "(", "*", "args", "**", "kwargs", ")", "." ]
def normalize_module( root: torch.nn.Module, target: str, args: Tuple[Any], kwargs : Optional[Dict[str, Any]] = None, normalize_to_only_use_kwargs : bool = False) -> Optional[ArgsKwargsPair]: """ Returns normalized arguments to PyTorch modules. This means that `args/kwargs` will be matched up to the functional's signature and return exclusively kwargs in positional order if `normalize_to_only_use_kwargs` is True. Also populates default values. Does not support positional-only parameters or varargs parameters (*args, **kwargs). Args: root (nn.Module): root module upon which we query modules target (Callable): Function that we are normalizing args (Tuple[Any]): Tuple of args to the function kwargs (Optional[Dict[str, Any]]): Dict of kwargs to the function normalize_to_only_use_kwargs (bool): Whether to normalize to only use kwargs. Returns: Returns normalized_args_and_kwargs, or `None` if not successful. """ try: submod = root.get_submodule(target) except AttributeError: raise RuntimeError(f"Tried to normalize node with target {target} but root did not " f"have that target!") if hasattr(submod.__class__, '__name__'): classname = submod.__class__.__name__ if getattr(torch.nn, classname, None) == submod.__class__: sig = inspect.signature(inspect.unwrap(submod.forward)) if kwargs is None: kwargs = {} new_args_and_kwargs = _args_kwargs_to_normalized_args_kwargs(sig, args, kwargs, normalize_to_only_use_kwargs) return new_args_and_kwargs return None
[ "def", "normalize_module", "(", "root", ":", "torch", ".", "nn", ".", "Module", ",", "target", ":", "str", ",", "args", ":", "Tuple", "[", "Any", "]", ",", "kwargs", ":", "Optional", "[", "Dict", "[", "str", ",", "Any", "]", "]", "=", "None", ",", "normalize_to_only_use_kwargs", ":", "bool", "=", "False", ")", "->", "Optional", "[", "ArgsKwargsPair", "]", ":", "try", ":", "submod", "=", "root", ".", "get_submodule", "(", "target", ")", "except", "AttributeError", ":", "raise", "RuntimeError", "(", "f\"Tried to normalize node with target {target} but root did not \"", "f\"have that target!\"", ")", "if", "hasattr", "(", "submod", ".", "__class__", ",", "'__name__'", ")", ":", "classname", "=", "submod", ".", "__class__", ".", "__name__", "if", "getattr", "(", "torch", ".", "nn", ",", "classname", ",", "None", ")", "==", "submod", ".", "__class__", ":", "sig", "=", "inspect", ".", "signature", "(", "inspect", ".", "unwrap", "(", "submod", ".", "forward", ")", ")", "if", "kwargs", "is", "None", ":", "kwargs", "=", "{", "}", "new_args_and_kwargs", "=", "_args_kwargs_to_normalized_args_kwargs", "(", "sig", ",", "args", ",", "kwargs", ",", "normalize_to_only_use_kwargs", ")", "return", "new_args_and_kwargs", "return", "None" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/fx/operator_schemas.py#L327-L363
lammps/lammps
b75c3065430a75b1b5543a10e10f46d9b4c91913
tools/i-pi/ipi/inputs/normalmodes.py
python
InputNormalModes.__init__
(self, help=None, dimension=None, default=None, dtype=None)
Initializes InputNormalModes. Just calls the parent initialization function with appropriate arguments.
Initializes InputNormalModes.
[ "Initializes", "InputNormalModes", "." ]
def __init__(self, help=None, dimension=None, default=None, dtype=None): """ Initializes InputNormalModes. Just calls the parent initialization function with appropriate arguments. """ super(InputNormalModes,self).__init__(help=help, default=default, dtype=float, dimension="frequency")
[ "def", "__init__", "(", "self", ",", "help", "=", "None", ",", "dimension", "=", "None", ",", "default", "=", "None", ",", "dtype", "=", "None", ")", ":", "super", "(", "InputNormalModes", ",", "self", ")", ".", "__init__", "(", "help", "=", "help", ",", "default", "=", "default", ",", "dtype", "=", "float", ",", "dimension", "=", "\"frequency\"", ")" ]
https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/tools/i-pi/ipi/inputs/normalmodes.py#L56-L62
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py3/IPython/terminal/ipapp.py
python
TerminalIPythonApp._classes_default
(self)
return [ InteractiveShellApp, # ShellApp comes before TerminalApp, because self.__class__, # it will also affect subclasses (e.g. QtConsole) TerminalInteractiveShell, HistoryManager, ProfileDir, PlainTextFormatter, IPCompleter, ScriptMagics, LoggingMagics, StoreMagics, ]
This has to be in a method, for TerminalIPythonApp to be available.
This has to be in a method, for TerminalIPythonApp to be available.
[ "This", "has", "to", "be", "in", "a", "method", "for", "TerminalIPythonApp", "to", "be", "available", "." ]
def _classes_default(self): """This has to be in a method, for TerminalIPythonApp to be available.""" return [ InteractiveShellApp, # ShellApp comes before TerminalApp, because self.__class__, # it will also affect subclasses (e.g. QtConsole) TerminalInteractiveShell, HistoryManager, ProfileDir, PlainTextFormatter, IPCompleter, ScriptMagics, LoggingMagics, StoreMagics, ]
[ "def", "_classes_default", "(", "self", ")", ":", "return", "[", "InteractiveShellApp", ",", "# ShellApp comes before TerminalApp, because", "self", ".", "__class__", ",", "# it will also affect subclasses (e.g. QtConsole)", "TerminalInteractiveShell", ",", "HistoryManager", ",", "ProfileDir", ",", "PlainTextFormatter", ",", "IPCompleter", ",", "ScriptMagics", ",", "LoggingMagics", ",", "StoreMagics", ",", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/terminal/ipapp.py#L196-L209
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/urllib3/util/connection.py
python
is_connection_dropped
(conn)
Returns True if the connection is dropped and should be closed. :param conn: :class:`http.client.HTTPConnection` object. Note: For platforms like AppEngine, this will always return ``False`` to let the platform handle connection recycling transparently for us.
Returns True if the connection is dropped and should be closed.
[ "Returns", "True", "if", "the", "connection", "is", "dropped", "and", "should", "be", "closed", "." ]
def is_connection_dropped(conn): # Platform-specific """ Returns True if the connection is dropped and should be closed. :param conn: :class:`http.client.HTTPConnection` object. Note: For platforms like AppEngine, this will always return ``False`` to let the platform handle connection recycling transparently for us. """ sock = getattr(conn, "sock", False) if sock is False: # Platform-specific: AppEngine return False if sock is None: # Connection already closed (such as by httplib). return True try: # Returns True if readable, which here means it's been dropped return wait_for_read(sock, timeout=0.0) except NoWayToWaitForSocketError: # Platform-specific: AppEngine return False
[ "def", "is_connection_dropped", "(", "conn", ")", ":", "# Platform-specific", "sock", "=", "getattr", "(", "conn", ",", "\"sock\"", ",", "False", ")", "if", "sock", "is", "False", ":", "# Platform-specific: AppEngine", "return", "False", "if", "sock", "is", "None", ":", "# Connection already closed (such as by httplib).", "return", "True", "try", ":", "# Returns True if readable, which here means it's been dropped", "return", "wait_for_read", "(", "sock", ",", "timeout", "=", "0.0", ")", "except", "NoWayToWaitForSocketError", ":", "# Platform-specific: AppEngine", "return", "False" ]
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/urllib3/util/connection.py#L12-L31