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
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/mimify.py
python
mime_encode
(line, header)
return newline + line
Code a single line as quoted-printable. If header is set, quote some extra characters.
Code a single line as quoted-printable. If header is set, quote some extra characters.
[ "Code", "a", "single", "line", "as", "quoted", "-", "printable", ".", "If", "header", "is", "set", "quote", "some", "extra", "characters", "." ]
def mime_encode(line, header): """Code a single line as quoted-printable. If header is set, quote some extra characters.""" if header: reg = mime_header_char else: reg = mime_char newline = '' pos = 0 if len(line) >= 5 and line[:5] == 'From ': # quote 'From ' at the start of a line for stupid mailers newline = ('=%02x' % ord('F')).upper() pos = 1 while 1: res = reg.search(line, pos) if res is None: break newline = newline + line[pos:res.start(0)] + \ ('=%02x' % ord(res.group(0))).upper() pos = res.end(0) line = newline + line[pos:] newline = '' while len(line) >= 75: i = 73 while line[i] == '=' or line[i-1] == '=': i = i - 1 i = i + 1 newline = newline + line[:i] + '=\n' line = line[i:] return newline + line
[ "def", "mime_encode", "(", "line", ",", "header", ")", ":", "if", "header", ":", "reg", "=", "mime_header_char", "else", ":", "reg", "=", "mime_char", "newline", "=", "''", "pos", "=", "0", "if", "len", "(", "line", ")", ">=", "5", "and", "line", "...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/mimify.py#L228-L258
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBStringList.__len__
(self)
return self.GetSize()
Return the number of strings in a lldb.SBStringList object.
Return the number of strings in a lldb.SBStringList object.
[ "Return", "the", "number", "of", "strings", "in", "a", "lldb", ".", "SBStringList", "object", "." ]
def __len__(self): '''Return the number of strings in a lldb.SBStringList object.''' return self.GetSize()
[ "def", "__len__", "(", "self", ")", ":", "return", "self", ".", "GetSize", "(", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L9647-L9649
olliw42/storm32bgc
99d62a6130ae2950514022f50eb669c45a8cc1ba
old/betacopter/old/betacopter36dev-v005/modules/uavcan/libuavcan/dsdl_compiler/pyuavcan/uavcan/__init__.py
python
Namespace._namespaces
(self)
return set(self.__namespaces)
Returns the top-level namespaces in this object
Returns the top-level namespaces in this object
[ "Returns", "the", "top", "-", "level", "namespaces", "in", "this", "object" ]
def _namespaces(self): "Returns the top-level namespaces in this object" return set(self.__namespaces)
[ "def", "_namespaces", "(", "self", ")", ":", "return", "set", "(", "self", ".", "__namespaces", ")" ]
https://github.com/olliw42/storm32bgc/blob/99d62a6130ae2950514022f50eb669c45a8cc1ba/old/betacopter/old/betacopter36dev-v005/modules/uavcan/libuavcan/dsdl_compiler/pyuavcan/uavcan/__init__.py#L42-L44
ledger/ledger
8e79216887cf3c342dfca1ffa52cf4e6389d6de4
contrib/non-profit-audit-reports/ooolib2/__init__.py
python
Calc.get_meta_value
(self, metaname)
return self.meta.get_meta_value(metaname)
Get meta data value for a given metaname
Get meta data value for a given metaname
[ "Get", "meta", "data", "value", "for", "a", "given", "metaname" ]
def get_meta_value(self, metaname): "Get meta data value for a given metaname" return self.meta.get_meta_value(metaname)
[ "def", "get_meta_value", "(", "self", ",", "metaname", ")", ":", "return", "self", ".", "meta", ".", "get_meta_value", "(", "metaname", ")" ]
https://github.com/ledger/ledger/blob/8e79216887cf3c342dfca1ffa52cf4e6389d6de4/contrib/non-profit-audit-reports/ooolib2/__init__.py#L951-L953
DanielSWolf/rhubarb-lip-sync
5cface0af3b6e4e58c0b829c51561d784fb9f52f
rhubarb/lib/webrtc-8d2248ff/tools/autoroller/roll_chromium_revision.py
python
ReadRemoteCrCommit
(revision)
return _ReadGitilesContent(CHROMIUM_COMMIT_TEMPLATE % revision)
Reads a remote Chromium commit message. Returns a string.
Reads a remote Chromium commit message. Returns a string.
[ "Reads", "a", "remote", "Chromium", "commit", "message", ".", "Returns", "a", "string", "." ]
def ReadRemoteCrCommit(revision): """Reads a remote Chromium commit message. Returns a string.""" return _ReadGitilesContent(CHROMIUM_COMMIT_TEMPLATE % revision)
[ "def", "ReadRemoteCrCommit", "(", "revision", ")", ":", "return", "_ReadGitilesContent", "(", "CHROMIUM_COMMIT_TEMPLATE", "%", "revision", ")" ]
https://github.com/DanielSWolf/rhubarb-lip-sync/blob/5cface0af3b6e4e58c0b829c51561d784fb9f52f/rhubarb/lib/webrtc-8d2248ff/tools/autoroller/roll_chromium_revision.py#L155-L157
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/nn/probability/distribution/exponential.py
python
Exponential._log_survival
(self, value, rate=None)
return self.select(comp, zeros, sf)
r""" Log survival_function of Exponential distributions. Args: value (Tensor): The value to be evaluated. rate (Tensor): The rate of the distribution. Default: self.rate. Note: `value` must be greater or equal to zero. .. math:: log_survival_function(x) = -1 * \lambda * x if x >= 0 else 0
r""" Log survival_function of Exponential distributions.
[ "r", "Log", "survival_function", "of", "Exponential", "distributions", "." ]
def _log_survival(self, value, rate=None): r""" Log survival_function of Exponential distributions. Args: value (Tensor): The value to be evaluated. rate (Tensor): The rate of the distribution. Default: self.rate. Note: `value` must be greater or equal to zero. .. math:: log_survival_function(x) = -1 * \lambda * x if x >= 0 else 0 """ value = self._check_value(value, 'value') value = self.cast(value, self.dtype) rate = self._check_param_type(rate) sf = -1. * rate * value zeros = self.fill(self.dtypeop(sf), self.shape(sf), 0.0) comp = self.less(value, zeros) return self.select(comp, zeros, sf)
[ "def", "_log_survival", "(", "self", ",", "value", ",", "rate", "=", "None", ")", ":", "value", "=", "self", ".", "_check_value", "(", "value", ",", "'value'", ")", "value", "=", "self", ".", "cast", "(", "value", ",", "self", ".", "dtype", ")", "r...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/probability/distribution/exponential.py#L300-L320
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/xml/dom/expatbuilder.py
python
ExpatBuilder.parseString
(self, string)
return doc
Parse a document from a string, returning the document node.
Parse a document from a string, returning the document node.
[ "Parse", "a", "document", "from", "a", "string", "returning", "the", "document", "node", "." ]
def parseString(self, string): """Parse a document from a string, returning the document node.""" parser = self.getParser() try: parser.Parse(string, True) self._setup_subset(string) except ParseEscape: pass doc = self.document self.reset() self._parser = None return doc
[ "def", "parseString", "(", "self", ",", "string", ")", ":", "parser", "=", "self", ".", "getParser", "(", ")", "try", ":", "parser", ".", "Parse", "(", "string", ",", "True", ")", "self", ".", "_setup_subset", "(", "string", ")", "except", "ParseEscape...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/xml/dom/expatbuilder.py#L219-L230
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/site_compare/operators/__init__.py
python
GetOperator
(operator)
return module
Given an operator by name, returns its module. Args: operator: string describing the comparison Returns: module
Given an operator by name, returns its module.
[ "Given", "an", "operator", "by", "name", "returns", "its", "module", "." ]
def GetOperator(operator): """Given an operator by name, returns its module. Args: operator: string describing the comparison Returns: module """ # TODO(jhaas): come up with a happy way of integrating multiple operators # with different, possibly divergent and possibly convergent, operators. module = __import__(operator, globals(), locals(), ['']) return module
[ "def", "GetOperator", "(", "operator", ")", ":", "# TODO(jhaas): come up with a happy way of integrating multiple operators", "# with different, possibly divergent and possibly convergent, operators.", "module", "=", "__import__", "(", "operator", ",", "globals", "(", ")", ",", "...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/site_compare/operators/__init__.py#L8-L23
bareos/bareos
56a10bb368b0a81e977bb51304033fe49d59efb0
core/src/plugins/filed/python/ldap/BareosFdPluginLDAP.py
python
BareosFdPluginLDAP.parse_plugin_definition
(self, plugindef)
return bareosfd.bRC_OK
Parses the plugin arguments and validates the options.
Parses the plugin arguments and validates the options.
[ "Parses", "the", "plugin", "arguments", "and", "validates", "the", "options", "." ]
def parse_plugin_definition(self, plugindef): """ Parses the plugin arguments and validates the options. """ bareosfd.DebugMessage( 100, "parse_plugin_definition() was called in module %s\n" % (__name__) ) super(BareosFdPluginLDAP, self).parse_plugin_definition(plugindef) return bareosfd.bRC_OK
[ "def", "parse_plugin_definition", "(", "self", ",", "plugindef", ")", ":", "bareosfd", ".", "DebugMessage", "(", "100", ",", "\"parse_plugin_definition() was called in module %s\\n\"", "%", "(", "__name__", ")", ")", "super", "(", "BareosFdPluginLDAP", ",", "self", ...
https://github.com/bareos/bareos/blob/56a10bb368b0a81e977bb51304033fe49d59efb0/core/src/plugins/filed/python/ldap/BareosFdPluginLDAP.py#L75-L84
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/number-of-subsequences-that-satisfy-the-given-sum-condition.py
python
Solution.numSubseq
(self, nums, target)
return result
:type nums: List[int] :type target: int :rtype: int
:type nums: List[int] :type target: int :rtype: int
[ ":", "type", "nums", ":", "List", "[", "int", "]", ":", "type", "target", ":", "int", ":", "rtype", ":", "int" ]
def numSubseq(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ MOD = 10**9 + 7 nums.sort() result = 0 left, right = 0, len(nums)-1 while left <= right: if nums[left]+nums[right] > target: right -= 1 else: result = (result+pow(2, right-left, MOD))%MOD left += 1 return result
[ "def", "numSubseq", "(", "self", ",", "nums", ",", "target", ")", ":", "MOD", "=", "10", "**", "9", "+", "7", "nums", ".", "sort", "(", ")", "result", "=", "0", "left", ",", "right", "=", "0", ",", "len", "(", "nums", ")", "-", "1", "while", ...
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/number-of-subsequences-that-satisfy-the-given-sum-condition.py#L5-L21
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/OpenSCAD/tokrules.py
python
t_newline
(t)
r'\n+
r'\n+
[ "r", "\\", "n", "+" ]
def t_newline(t): r'\n+' t.lexer.lineno += len(t.value)
[ "def", "t_newline", "(", "t", ")", ":", "t", ".", "lexer", ".", "lineno", "+=", "len", "(", "t", ".", "value", ")" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/OpenSCAD/tokrules.py#L129-L131
rrwick/Unicycler
96ffea71e3a78d63ade19d6124946773e65cf129
ez_setup.py
python
_clean_check
(cmd, target)
Run the command to download target. If the command fails, clean up before re-raising the error.
Run the command to download target.
[ "Run", "the", "command", "to", "download", "target", "." ]
def _clean_check(cmd, target): """ Run the command to download target. If the command fails, clean up before re-raising the error. """ try: subprocess.check_call(cmd) except subprocess.CalledProcessError: if os.access(target, os.F_OK): os.unlink(target) raise
[ "def", "_clean_check", "(", "cmd", ",", "target", ")", ":", "try", ":", "subprocess", ".", "check_call", "(", "cmd", ")", "except", "subprocess", ".", "CalledProcessError", ":", "if", "os", ".", "access", "(", "target", ",", "os", ".", "F_OK", ")", ":"...
https://github.com/rrwick/Unicycler/blob/96ffea71e3a78d63ade19d6124946773e65cf129/ez_setup.py#L223-L234
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/package_index.py
python
PyPIConfig.__init__
(self)
Load from ~/.pypirc
Load from ~/.pypirc
[ "Load", "from", "~", "/", ".", "pypirc" ]
def __init__(self): """ Load from ~/.pypirc """ defaults = dict.fromkeys(['username', 'password', 'repository'], '') configparser.RawConfigParser.__init__(self, defaults) rc = os.path.join(os.path.expanduser('~'), '.pypirc') if os.path.exists(rc): self.read(rc)
[ "def", "__init__", "(", "self", ")", ":", "defaults", "=", "dict", ".", "fromkeys", "(", "[", "'username'", ",", "'password'", ",", "'repository'", "]", ",", "''", ")", "configparser", ".", "RawConfigParser", ".", "__init__", "(", "self", ",", "defaults", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/package_index.py#L1013-L1022
macchina-io/macchina.io
ef24ba0e18379c3dd48fb84e6dbf991101cb8db0
platform/JS/V8/tools/gyp/pylib/gyp/ordered_dict.py
python
OrderedDict.fromkeys
(cls, iterable, value=None)
return d
OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S and values equal to v (which defaults to None).
OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S and values equal to v (which defaults to None).
[ "OD", ".", "fromkeys", "(", "S", "[", "v", "]", ")", "-", ">", "New", "ordered", "dictionary", "with", "keys", "from", "S", "and", "values", "equal", "to", "v", "(", "which", "defaults", "to", "None", ")", "." ]
def fromkeys(cls, iterable, value=None): '''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S and values equal to v (which defaults to None). ''' d = cls() for key in iterable: d[key] = value return d
[ "def", "fromkeys", "(", "cls", ",", "iterable", ",", "value", "=", "None", ")", ":", "d", "=", "cls", "(", ")", "for", "key", "in", "iterable", ":", "d", "[", "key", "]", "=", "value", "return", "d" ]
https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/pylib/gyp/ordered_dict.py#L254-L262
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/urllib.py
python
FancyURLopener.http_error_302
(self, url, fp, errcode, errmsg, headers, data=None)
return result
Error 302 -- relocated (temporarily).
Error 302 -- relocated (temporarily).
[ "Error", "302", "--", "relocated", "(", "temporarily", ")", "." ]
def http_error_302(self, url, fp, errcode, errmsg, headers, data=None): """Error 302 -- relocated (temporarily).""" self.tries += 1 if self.maxtries and self.tries >= self.maxtries: if hasattr(self, "http_error_500"): meth = self.http_error_500 else: meth = self.http_error_default self.tries = 0 return meth(url, fp, 500, "Internal Server Error: Redirect Recursion", headers) result = self.redirect_internal(url, fp, errcode, errmsg, headers, data) self.tries = 0 return result
[ "def", "http_error_302", "(", "self", ",", "url", ",", "fp", ",", "errcode", ",", "errmsg", ",", "headers", ",", "data", "=", "None", ")", ":", "self", ".", "tries", "+=", "1", "if", "self", ".", "maxtries", "and", "self", ".", "tries", ">=", "self...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/urllib.py#L623-L637
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/geometry/tf/src/tf/transformations.py
python
projection_from_matrix
(matrix, pseudo=False)
Return projection plane and perspective point from projection matrix. Return values are same as arguments for projection_matrix function: point, normal, direction, perspective, and pseudo. >>> point = numpy.random.random(3) - 0.5 >>> normal = numpy.random.random(3) - 0.5 >>> direct = numpy.random.random(3) - 0.5 >>> persp = numpy.random.random(3) - 0.5 >>> P0 = projection_matrix(point, normal) >>> result = projection_from_matrix(P0) >>> P1 = projection_matrix(*result) >>> is_same_transform(P0, P1) True >>> P0 = projection_matrix(point, normal, direct) >>> result = projection_from_matrix(P0) >>> P1 = projection_matrix(*result) >>> is_same_transform(P0, P1) True >>> P0 = projection_matrix(point, normal, perspective=persp, pseudo=False) >>> result = projection_from_matrix(P0, pseudo=False) >>> P1 = projection_matrix(*result) >>> is_same_transform(P0, P1) True >>> P0 = projection_matrix(point, normal, perspective=persp, pseudo=True) >>> result = projection_from_matrix(P0, pseudo=True) >>> P1 = projection_matrix(*result) >>> is_same_transform(P0, P1) True
Return projection plane and perspective point from projection matrix.
[ "Return", "projection", "plane", "and", "perspective", "point", "from", "projection", "matrix", "." ]
def projection_from_matrix(matrix, pseudo=False): """Return projection plane and perspective point from projection matrix. Return values are same as arguments for projection_matrix function: point, normal, direction, perspective, and pseudo. >>> point = numpy.random.random(3) - 0.5 >>> normal = numpy.random.random(3) - 0.5 >>> direct = numpy.random.random(3) - 0.5 >>> persp = numpy.random.random(3) - 0.5 >>> P0 = projection_matrix(point, normal) >>> result = projection_from_matrix(P0) >>> P1 = projection_matrix(*result) >>> is_same_transform(P0, P1) True >>> P0 = projection_matrix(point, normal, direct) >>> result = projection_from_matrix(P0) >>> P1 = projection_matrix(*result) >>> is_same_transform(P0, P1) True >>> P0 = projection_matrix(point, normal, perspective=persp, pseudo=False) >>> result = projection_from_matrix(P0, pseudo=False) >>> P1 = projection_matrix(*result) >>> is_same_transform(P0, P1) True >>> P0 = projection_matrix(point, normal, perspective=persp, pseudo=True) >>> result = projection_from_matrix(P0, pseudo=True) >>> P1 = projection_matrix(*result) >>> is_same_transform(P0, P1) True """ M = numpy.array(matrix, dtype=numpy.float64, copy=False) M33 = M[:3, :3] l, V = numpy.linalg.eig(M) i = numpy.where(abs(numpy.real(l) - 1.0) < 1e-8)[0] if not pseudo and len(i): # point: any eigenvector corresponding to eigenvalue 1 point = numpy.real(V[:, i[-1]]).squeeze() point /= point[3] # direction: unit eigenvector corresponding to eigenvalue 0 l, V = numpy.linalg.eig(M33) i = numpy.where(abs(numpy.real(l)) < 1e-8)[0] if not len(i): raise ValueError("no eigenvector corresponding to eigenvalue 0") direction = numpy.real(V[:, i[0]]).squeeze() direction /= vector_norm(direction) # normal: unit eigenvector of M33.T corresponding to eigenvalue 0 l, V = numpy.linalg.eig(M33.T) i = numpy.where(abs(numpy.real(l)) < 1e-8)[0] if len(i): # parallel projection normal = numpy.real(V[:, i[0]]).squeeze() normal /= vector_norm(normal) return point, normal, direction, None, False else: # orthogonal projection, where normal equals direction vector return point, direction, None, None, False else: # perspective projection i = numpy.where(abs(numpy.real(l)) > 1e-8)[0] if not len(i): raise ValueError( "no eigenvector not corresponding to eigenvalue 0") point = numpy.real(V[:, i[-1]]).squeeze() point /= point[3] normal = - M[3, :3] perspective = M[:3, 3] / numpy.dot(point[:3], normal) if pseudo: perspective -= normal return point, normal, None, perspective, pseudo
[ "def", "projection_from_matrix", "(", "matrix", ",", "pseudo", "=", "False", ")", ":", "M", "=", "numpy", ".", "array", "(", "matrix", ",", "dtype", "=", "numpy", ".", "float64", ",", "copy", "=", "False", ")", "M33", "=", "M", "[", ":", "3", ",", ...
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/geometry/tf/src/tf/transformations.py#L499-L569
OpenLightingProject/ola
d1433a1bed73276fbe55ce18c03b1c208237decc
python/ola/rpc/StreamRpcChannel.py
python
StreamRpcChannel._HandleFailedReponse
(self, message)
Handle a Failed Response message. Args: message: The RpcMessage object.
Handle a Failed Response message.
[ "Handle", "a", "Failed", "Response", "message", "." ]
def _HandleFailedReponse(self, message): """Handle a Failed Response message. Args: message: The RpcMessage object. """ response = self._outstanding_responses.get(message.id, None) if response: response.controller.SetFailed(message.buffer) self._InvokeCallback(response)
[ "def", "_HandleFailedReponse", "(", "self", ",", "message", ")", ":", "response", "=", "self", ".", "_outstanding_responses", ".", "get", "(", "message", ".", "id", ",", "None", ")", "if", "response", ":", "response", ".", "controller", ".", "SetFailed", "...
https://github.com/OpenLightingProject/ola/blob/d1433a1bed73276fbe55ce18c03b1c208237decc/python/ola/rpc/StreamRpcChannel.py#L342-L351
JarveeLee/SynthText_Chinese_version
4b2cbc7d14741f21d0bb17966a339ab3574b09a8
colorize3_poisson.py
python
Colorize.drop_shadow
(self, alpha, theta, shift, size, op=0.80)
return shadow.astype('uint8')
alpha : alpha layer whose shadow need to be cast theta : [0,2pi] -- the shadow direction shift : shift in pixels of the shadow size : size of the GaussianBlur filter op : opacity of the shadow (multiplying factor) @return : alpha of the shadow layer (it is assumed that the color is black/white)
alpha : alpha layer whose shadow need to be cast theta : [0,2pi] -- the shadow direction shift : shift in pixels of the shadow size : size of the GaussianBlur filter op : opacity of the shadow (multiplying factor)
[ "alpha", ":", "alpha", "layer", "whose", "shadow", "need", "to", "be", "cast", "theta", ":", "[", "0", "2pi", "]", "--", "the", "shadow", "direction", "shift", ":", "shift", "in", "pixels", "of", "the", "shadow", "size", ":", "size", "of", "the", "Ga...
def drop_shadow(self, alpha, theta, shift, size, op=0.80): """ alpha : alpha layer whose shadow need to be cast theta : [0,2pi] -- the shadow direction shift : shift in pixels of the shadow size : size of the GaussianBlur filter op : opacity of the shadow (multiplying factor) @return : alpha of the shadow layer (it is assumed that the color is black/white) """ if size%2==0: size -= 1 size = max(1,size) shadow = cv.GaussianBlur(alpha,(size,size),0) [dx,dy] = shift * np.array([-np.sin(theta), np.cos(theta)]) shadow = op*sii.shift(shadow, shift=[dx,dy],mode='constant',cval=0) return shadow.astype('uint8')
[ "def", "drop_shadow", "(", "self", ",", "alpha", ",", "theta", ",", "shift", ",", "size", ",", "op", "=", "0.80", ")", ":", "if", "size", "%", "2", "==", "0", ":", "size", "-=", "1", "size", "=", "max", "(", "1", ",", "size", ")", "shadow", "...
https://github.com/JarveeLee/SynthText_Chinese_version/blob/4b2cbc7d14741f21d0bb17966a339ab3574b09a8/colorize3_poisson.py#L156-L173
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/tpu/tpu_feed.py
python
InfeedQueue.set_configuration_from_input_tensors
(self, input_tensors)
Sets the shapes and types of the queue tuple elements. input_tensors is a list of Tensors whose types and shapes are used to set the queue configuration. Args: input_tensors: list of Tensors of the same types and shapes as the desired queue Tuple. Raises: ValueError: if input_tensors is not a list of length self.number_of_tuple_elements
Sets the shapes and types of the queue tuple elements.
[ "Sets", "the", "shapes", "and", "types", "of", "the", "queue", "tuple", "elements", "." ]
def set_configuration_from_input_tensors(self, input_tensors): """Sets the shapes and types of the queue tuple elements. input_tensors is a list of Tensors whose types and shapes are used to set the queue configuration. Args: input_tensors: list of Tensors of the same types and shapes as the desired queue Tuple. Raises: ValueError: if input_tensors is not a list of length self.number_of_tuple_elements """ if len(input_tensors) != self.number_of_tuple_elements: raise ValueError("input_tensors is %s, but should be a list of %d Tensors" % (str(input_tensors), self.number_of_tuple_elements)) self.set_tuple_shapes([t.shape for t in input_tensors]) self.set_tuple_types([t.dtype for t in input_tensors])
[ "def", "set_configuration_from_input_tensors", "(", "self", ",", "input_tensors", ")", ":", "if", "len", "(", "input_tensors", ")", "!=", "self", ".", "number_of_tuple_elements", ":", "raise", "ValueError", "(", "\"input_tensors is %s, but should be a list of %d Tensors\"",...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/tpu/tpu_feed.py#L364-L382
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/training/device_setter.py
python
_ReplicaDeviceChooser.device_function
(self, op)
return spec.to_string()
Chose a device for `op`. Args: op: an `Operation`. Returns: The device to use for the `Operation`.
Chose a device for `op`.
[ "Chose", "a", "device", "for", "op", "." ]
def device_function(self, op): """Chose a device for `op`. Args: op: an `Operation`. Returns: The device to use for the `Operation`. """ if not self._merge_devices and op.device: return op.device current_device = pydev.DeviceSpec.from_string(op.device or "") spec = pydev.DeviceSpec() if self._ps_tasks and self._ps_device: node_def = op if isinstance(op, node_def_pb2.NodeDef) else op.node_def if node_def.op in self._ps_ops: device_string = "%s/task:%d" % (self._ps_device, self._next_task()) if self._merge_devices: spec = pydev.DeviceSpec.from_string(device_string) spec.merge_from(current_device) return spec.to_string() else: return device_string if self._worker_device: if not self._merge_devices: return self._worker_device spec = pydev.DeviceSpec.from_string(self._worker_device) if not self._merge_devices: return "" spec.merge_from(current_device) return spec.to_string()
[ "def", "device_function", "(", "self", ",", "op", ")", ":", "if", "not", "self", ".", "_merge_devices", "and", "op", ".", "device", ":", "return", "op", ".", "device", "current_device", "=", "pydev", ".", "DeviceSpec", ".", "from_string", "(", "op", ".",...
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/training/device_setter.py#L65-L97
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/valgrind/common.py
python
NormalizeWindowsPath
(path)
If we're using Cygwin Python, turn the path into a Windows path. Don't turn forward slashes into backslashes for easier copy-pasting and escaping. TODO(rnk): If we ever want to cut out the subprocess invocation, we can use _winreg to get the root Cygwin directory from the registry key: HKEY_LOCAL_MACHINE\SOFTWARE\Cygwin\setup\rootdir.
If we're using Cygwin Python, turn the path into a Windows path.
[ "If", "we", "re", "using", "Cygwin", "Python", "turn", "the", "path", "into", "a", "Windows", "path", "." ]
def NormalizeWindowsPath(path): """If we're using Cygwin Python, turn the path into a Windows path. Don't turn forward slashes into backslashes for easier copy-pasting and escaping. TODO(rnk): If we ever want to cut out the subprocess invocation, we can use _winreg to get the root Cygwin directory from the registry key: HKEY_LOCAL_MACHINE\SOFTWARE\Cygwin\setup\rootdir. """ if sys.platform.startswith("cygwin"): p = subprocess.Popen(["cygpath", "-m", path], stdout=subprocess.PIPE, stderr=subprocess.PIPE) (out, err) = p.communicate() if err: logging.warning("WARNING: cygpath error: %s", err) return out.strip() else: return path
[ "def", "NormalizeWindowsPath", "(", "path", ")", ":", "if", "sys", ".", "platform", ".", "startswith", "(", "\"cygwin\"", ")", ":", "p", "=", "subprocess", ".", "Popen", "(", "[", "\"cygpath\"", ",", "\"-m\"", ",", "path", "]", ",", "stdout", "=", "sub...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/valgrind/common.py#L210-L229
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/utils/deprecation.py
python
deprecated._decorate_fun
(self, fun)
return wrapped
Decorate function fun
Decorate function fun
[ "Decorate", "function", "fun" ]
def _decorate_fun(self, fun): """Decorate function fun""" msg = "Function %s is deprecated" % fun.__name__ if self.extra: msg += "; %s" % self.extra @functools.wraps(fun) def wrapped(*args, **kwargs): warnings.warn(msg, category=FutureWarning) return fun(*args, **kwargs) wrapped.__doc__ = self._update_doc(wrapped.__doc__) # Add a reference to the wrapped function so that we can introspect # on function arguments in Python 2 (already works in Python 3) wrapped.__wrapped__ = fun return wrapped
[ "def", "_decorate_fun", "(", "self", ",", "fun", ")", ":", "msg", "=", "\"Function %s is deprecated\"", "%", "fun", ".", "__name__", "if", "self", ".", "extra", ":", "msg", "+=", "\"; %s\"", "%", "self", ".", "extra", "@", "functools", ".", "wraps", "(",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/utils/deprecation.py#L78-L95
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
chrome/common/extensions/docs/examples/apps/hello-python/oauth2/__init__.py
python
Request.to_postdata
(self)
return urllib.urlencode(self, True).replace('+', '%20')
Serialize as post data for a POST request.
Serialize as post data for a POST request.
[ "Serialize", "as", "post", "data", "for", "a", "POST", "request", "." ]
def to_postdata(self): """Serialize as post data for a POST request.""" # tell urlencode to deal with sequence values and map them correctly # to resulting querystring. for example self["k"] = ["v1", "v2"] will # result in 'k=v1&k=v2' and not k=%5B%27v1%27%2C+%27v2%27%5D return urllib.urlencode(self, True).replace('+', '%20')
[ "def", "to_postdata", "(", "self", ")", ":", "# tell urlencode to deal with sequence values and map them correctly", "# to resulting querystring. for example self[\"k\"] = [\"v1\", \"v2\"] will", "# result in 'k=v1&k=v2' and not k=%5B%27v1%27%2C+%27v2%27%5D", "return", "urllib", ".", "urlenc...
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/chrome/common/extensions/docs/examples/apps/hello-python/oauth2/__init__.py#L323-L328
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/stats/morestats.py
python
levene
(*args, **kwds)
return LeveneResult(W, pval)
Perform Levene test for equal variances. The Levene test tests the null hypothesis that all input samples are from populations with equal variances. Levene's test is an alternative to Bartlett's test `bartlett` in the case where there are significant deviations from normality. Parameters ---------- sample1, sample2, ... : array_like The sample data, possibly with different lengths. Only one-dimensional samples are accepted. center : {'mean', 'median', 'trimmed'}, optional Which function of the data to use in the test. The default is 'median'. proportiontocut : float, optional When `center` is 'trimmed', this gives the proportion of data points to cut from each end. (See `scipy.stats.trim_mean`.) Default is 0.05. Returns ------- statistic : float The test statistic. pvalue : float The p-value for the test. Notes ----- Three variations of Levene's test are possible. The possibilities and their recommended usages are: * 'median' : Recommended for skewed (non-normal) distributions> * 'mean' : Recommended for symmetric, moderate-tailed distributions. * 'trimmed' : Recommended for heavy-tailed distributions. The test version using the mean was proposed in the original article of Levene ([2]_) while the median and trimmed mean have been studied by Brown and Forsythe ([3]_), sometimes also referred to as Brown-Forsythe test. References ---------- .. [1] https://www.itl.nist.gov/div898/handbook/eda/section3/eda35a.htm .. [2] Levene, H. (1960). In Contributions to Probability and Statistics: Essays in Honor of Harold Hotelling, I. Olkin et al. eds., Stanford University Press, pp. 278-292. .. [3] Brown, M. B. and Forsythe, A. B. (1974), Journal of the American Statistical Association, 69, 364-367
Perform Levene test for equal variances.
[ "Perform", "Levene", "test", "for", "equal", "variances", "." ]
def levene(*args, **kwds): """ Perform Levene test for equal variances. The Levene test tests the null hypothesis that all input samples are from populations with equal variances. Levene's test is an alternative to Bartlett's test `bartlett` in the case where there are significant deviations from normality. Parameters ---------- sample1, sample2, ... : array_like The sample data, possibly with different lengths. Only one-dimensional samples are accepted. center : {'mean', 'median', 'trimmed'}, optional Which function of the data to use in the test. The default is 'median'. proportiontocut : float, optional When `center` is 'trimmed', this gives the proportion of data points to cut from each end. (See `scipy.stats.trim_mean`.) Default is 0.05. Returns ------- statistic : float The test statistic. pvalue : float The p-value for the test. Notes ----- Three variations of Levene's test are possible. The possibilities and their recommended usages are: * 'median' : Recommended for skewed (non-normal) distributions> * 'mean' : Recommended for symmetric, moderate-tailed distributions. * 'trimmed' : Recommended for heavy-tailed distributions. The test version using the mean was proposed in the original article of Levene ([2]_) while the median and trimmed mean have been studied by Brown and Forsythe ([3]_), sometimes also referred to as Brown-Forsythe test. References ---------- .. [1] https://www.itl.nist.gov/div898/handbook/eda/section3/eda35a.htm .. [2] Levene, H. (1960). In Contributions to Probability and Statistics: Essays in Honor of Harold Hotelling, I. Olkin et al. eds., Stanford University Press, pp. 278-292. .. [3] Brown, M. B. and Forsythe, A. B. (1974), Journal of the American Statistical Association, 69, 364-367 """ # Handle keyword arguments. center = 'median' proportiontocut = 0.05 for kw, value in kwds.items(): if kw not in ['center', 'proportiontocut']: raise TypeError("levene() got an unexpected keyword " "argument '%s'" % kw) if kw == 'center': center = value else: proportiontocut = value k = len(args) if k < 2: raise ValueError("Must enter at least two input sample vectors.") # check for 1d input for j in range(k): if np.asanyarray(args[j]).ndim > 1: raise ValueError('Samples must be one-dimensional.') Ni = zeros(k) Yci = zeros(k, 'd') if center not in ['mean', 'median', 'trimmed']: raise ValueError("Keyword argument <center> must be 'mean', 'median'" " or 'trimmed'.") if center == 'median': func = lambda x: np.median(x, axis=0) elif center == 'mean': func = lambda x: np.mean(x, axis=0) else: # center == 'trimmed' args = tuple(stats.trimboth(np.sort(arg), proportiontocut) for arg in args) func = lambda x: np.mean(x, axis=0) for j in range(k): Ni[j] = len(args[j]) Yci[j] = func(args[j]) Ntot = np.sum(Ni, axis=0) # compute Zij's Zij = [None] * k for i in range(k): Zij[i] = abs(asarray(args[i]) - Yci[i]) # compute Zbari Zbari = zeros(k, 'd') Zbar = 0.0 for i in range(k): Zbari[i] = np.mean(Zij[i], axis=0) Zbar += Zbari[i] * Ni[i] Zbar /= Ntot numer = (Ntot - k) * np.sum(Ni * (Zbari - Zbar)**2, axis=0) # compute denom_variance dvar = 0.0 for i in range(k): dvar += np.sum((Zij[i] - Zbari[i])**2, axis=0) denom = (k - 1.0) * dvar W = numer / denom pval = distributions.f.sf(W, k-1, Ntot-k) # 1 - cdf return LeveneResult(W, pval)
[ "def", "levene", "(", "*", "args", ",", "*", "*", "kwds", ")", ":", "# Handle keyword arguments.", "center", "=", "'median'", "proportiontocut", "=", "0.05", "for", "kw", ",", "value", "in", "kwds", ".", "items", "(", ")", ":", "if", "kw", "not", "in",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/stats/morestats.py#L2229-L2347
OpenXRay/xray-15
1390dfb08ed20997d7e8c95147ea8e8cb71f5e86
cs/sdk/3d_sdk/maya/ver-2008/devkit/plug-ins/scripted/motionTraceCmd.py
python
motionTrace.redoIt
(self)
This method performs the action of the command. This method iterates over all selected items and prints out connected plug and dependency node type information.
This method performs the action of the command. This method iterates over all selected items and prints out connected plug and dependency node type information.
[ "This", "method", "performs", "the", "action", "of", "the", "command", ".", "This", "method", "iterates", "over", "all", "selected", "items", "and", "prints", "out", "connected", "plug", "and", "dependency", "node", "type", "information", "." ]
def redoIt(self): """ This method performs the action of the command. This method iterates over all selected items and prints out connected plug and dependency node type information. """ picked = OpenMaya.MObjectArray() dependNode = OpenMaya.MObject() # Selected dependency node # Create a selection list iterator slist = OpenMaya.MSelectionList() OpenMaya.MGlobal.getActiveSelectionList(slist) iter = OpenMaya.MItSelectionList(slist) # Iterate over all selected dependency nodes # and save them in a list while not iter.isDone(): # Get the selected dependency node iter.getDependNode(dependNode) picked.append(dependNode) iter.next() # sample the animation using start, end, by values pointArrays = [ OpenMaya.MPointArray() for i in range(picked.length()) ] time = self.__start while (time <= self.__end): timeval = OpenMaya.MTime(time) OpenMaya.MGlobal.viewFrame(timeval) # Iterate over selected dependency nodes for i in range(picked.length()): # Get the selected dependency node dependNode = picked[i] # Create a function set for the dependency node fnDependNode = OpenMaya.MFnDependencyNode(dependNode) # Get the translation attribute values txAttr = fnDependNode.attribute("translateX") txPlug = OpenMaya.MPlug(dependNode, txAttr) tx = txPlug.asDouble() tyAttr = fnDependNode.attribute("translateY") tyPlug = OpenMaya.MPlug(dependNode, tyAttr) ty = tyPlug.asDouble() tzAttr = fnDependNode.attribute("translateZ") tzPlug = OpenMaya.MPlug(dependNode, tzAttr) tz = tzPlug.asDouble() print "adding", tx, ty, tz, "\n" pointArrays[i].append(OpenMaya.MPoint(tx, ty, tz)) time += self.__by # make a path curve for each selected object for i in range(picked.length()): self.__jMakeCurve(pointArrays[i])
[ "def", "redoIt", "(", "self", ")", ":", "picked", "=", "OpenMaya", ".", "MObjectArray", "(", ")", "dependNode", "=", "OpenMaya", ".", "MObject", "(", ")", "# Selected dependency node", "# Create a selection list iterator", "slist", "=", "OpenMaya", ".", "MSelectio...
https://github.com/OpenXRay/xray-15/blob/1390dfb08ed20997d7e8c95147ea8e8cb71f5e86/cs/sdk/3d_sdk/maya/ver-2008/devkit/plug-ins/scripted/motionTraceCmd.py#L111-L170
Smorodov/Multitarget-tracker
bee300e8bfd660c86cbeb6892c65a5b7195c9381
thirdparty/pybind11/tools/clang/cindex.py
python
Cursor.brief_comment
(self)
return conf.lib.clang_Cursor_getBriefCommentText(self)
Returns the brief comment text associated with that Cursor
Returns the brief comment text associated with that Cursor
[ "Returns", "the", "brief", "comment", "text", "associated", "with", "that", "Cursor" ]
def brief_comment(self): """Returns the brief comment text associated with that Cursor""" return conf.lib.clang_Cursor_getBriefCommentText(self)
[ "def", "brief_comment", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_Cursor_getBriefCommentText", "(", "self", ")" ]
https://github.com/Smorodov/Multitarget-tracker/blob/bee300e8bfd660c86cbeb6892c65a5b7195c9381/thirdparty/pybind11/tools/clang/cindex.py#L1607-L1609
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
BookCtrlBase.AddPage
(*args, **kwargs)
return _core_.BookCtrlBase_AddPage(*args, **kwargs)
AddPage(self, Window page, String text, bool select=False, int imageId=-1) -> bool
AddPage(self, Window page, String text, bool select=False, int imageId=-1) -> bool
[ "AddPage", "(", "self", "Window", "page", "String", "text", "bool", "select", "=", "False", "int", "imageId", "=", "-", "1", ")", "-", ">", "bool" ]
def AddPage(*args, **kwargs): """AddPage(self, Window page, String text, bool select=False, int imageId=-1) -> bool""" return _core_.BookCtrlBase_AddPage(*args, **kwargs)
[ "def", "AddPage", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "BookCtrlBase_AddPage", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L13622-L13624
Yijunmaverick/GenerativeFaceCompletion
f72dea0fa27c779fef7b65d2f01e82bcc23a0eb2
python/caffe/io.py
python
resize_image
(im, new_dims, interp_order=1)
return resized_im.astype(np.float32)
Resize an image array with interpolation. Parameters ---------- im : (H x W x K) ndarray new_dims : (height, width) tuple of new dimensions. interp_order : interpolation order, default is linear. Returns ------- im : resized ndarray with shape (new_dims[0], new_dims[1], K)
Resize an image array with interpolation.
[ "Resize", "an", "image", "array", "with", "interpolation", "." ]
def resize_image(im, new_dims, interp_order=1): """ Resize an image array with interpolation. Parameters ---------- im : (H x W x K) ndarray new_dims : (height, width) tuple of new dimensions. interp_order : interpolation order, default is linear. Returns ------- im : resized ndarray with shape (new_dims[0], new_dims[1], K) """ if im.shape[-1] == 1 or im.shape[-1] == 3: im_min, im_max = im.min(), im.max() if im_max > im_min: # skimage is fast but only understands {1,3} channel images # in [0, 1]. im_std = (im - im_min) / (im_max - im_min) resized_std = resize(im_std, new_dims, order=interp_order) resized_im = resized_std * (im_max - im_min) + im_min else: # the image is a constant -- avoid divide by 0 ret = np.empty((new_dims[0], new_dims[1], im.shape[-1]), dtype=np.float32) ret.fill(im_min) return ret else: # ndimage interpolates anything but more slowly. scale = tuple(np.array(new_dims, dtype=float) / np.array(im.shape[:2])) resized_im = zoom(im, scale + (1,), order=interp_order) return resized_im.astype(np.float32)
[ "def", "resize_image", "(", "im", ",", "new_dims", ",", "interp_order", "=", "1", ")", ":", "if", "im", ".", "shape", "[", "-", "1", "]", "==", "1", "or", "im", ".", "shape", "[", "-", "1", "]", "==", "3", ":", "im_min", ",", "im_max", "=", "...
https://github.com/Yijunmaverick/GenerativeFaceCompletion/blob/f72dea0fa27c779fef7b65d2f01e82bcc23a0eb2/python/caffe/io.py#L305-L337
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_misc.py
python
DateTime.GetAmPmStrings
(*args, **kwargs)
return _misc_.DateTime_GetAmPmStrings(*args, **kwargs)
GetAmPmStrings() -> (am, pm) Get the AM and PM strings in the current locale (may be empty)
GetAmPmStrings() -> (am, pm)
[ "GetAmPmStrings", "()", "-", ">", "(", "am", "pm", ")" ]
def GetAmPmStrings(*args, **kwargs): """ GetAmPmStrings() -> (am, pm) Get the AM and PM strings in the current locale (may be empty) """ return _misc_.DateTime_GetAmPmStrings(*args, **kwargs)
[ "def", "GetAmPmStrings", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "DateTime_GetAmPmStrings", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L3742-L3748
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/extern/aui/auibook.py
python
AuiTabCtrl.OnLeaveWindow
(self, event)
Handles the ``wx.EVT_LEAVE_WINDOW`` event for :class:`AuiTabCtrl`. :param `event`: a :class:`MouseEvent` event to be processed.
Handles the ``wx.EVT_LEAVE_WINDOW`` event for :class:`AuiTabCtrl`.
[ "Handles", "the", "wx", ".", "EVT_LEAVE_WINDOW", "event", "for", ":", "class", ":", "AuiTabCtrl", "." ]
def OnLeaveWindow(self, event): """ Handles the ``wx.EVT_LEAVE_WINDOW`` event for :class:`AuiTabCtrl`. :param `event`: a :class:`MouseEvent` event to be processed. """ if self._hover_button: self._hover_button.cur_state = AUI_BUTTON_STATE_NORMAL self._hover_button = None self.Refresh() self.Update()
[ "def", "OnLeaveWindow", "(", "self", ",", "event", ")", ":", "if", "self", ".", "_hover_button", ":", "self", ".", "_hover_button", ".", "cur_state", "=", "AUI_BUTTON_STATE_NORMAL", "self", ".", "_hover_button", "=", "None", "self", ".", "Refresh", "(", ")",...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/auibook.py#L2261-L2272
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
media/webrtc/trunk/tools/gyp/pylib/gyp/generator/msvs.py
python
_GenerateProject
(project, options, version, generator_flags)
Generates a vcproj file. Arguments: project: the MSVSProject object. options: global generator options. version: the MSVSVersion object. generator_flags: dict of generator-specific flags. Returns: A list of source files that cannot be found on disk.
Generates a vcproj file.
[ "Generates", "a", "vcproj", "file", "." ]
def _GenerateProject(project, options, version, generator_flags): """Generates a vcproj file. Arguments: project: the MSVSProject object. options: global generator options. version: the MSVSVersion object. generator_flags: dict of generator-specific flags. Returns: A list of source files that cannot be found on disk. """ default_config = _GetDefaultConfiguration(project.spec) # Skip emitting anything if told to with msvs_existing_vcproj option. if default_config.get('msvs_existing_vcproj'): return [] if version.UsesVcxproj(): return _GenerateMSBuildProject(project, options, version, generator_flags) else: return _GenerateMSVSProject(project, options, version, generator_flags)
[ "def", "_GenerateProject", "(", "project", ",", "options", ",", "version", ",", "generator_flags", ")", ":", "default_config", "=", "_GetDefaultConfiguration", "(", "project", ".", "spec", ")", "# Skip emitting anything if told to with msvs_existing_vcproj option.", "if", ...
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/msvs.py#L860-L880
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/distutils/filelist.py
python
translate_pattern
(pattern, anchor=1, prefix=None, is_regex=0)
return re.compile(pattern_re)
Translate a shell-like wildcard pattern to a compiled regular expression. Return the compiled regex. If 'is_regex' true, then 'pattern' is directly compiled to a regex (if it's a string) or just returned as-is (assumes it's a regex object).
Translate a shell-like wildcard pattern to a compiled regular expression.
[ "Translate", "a", "shell", "-", "like", "wildcard", "pattern", "to", "a", "compiled", "regular", "expression", "." ]
def translate_pattern(pattern, anchor=1, prefix=None, is_regex=0): """Translate a shell-like wildcard pattern to a compiled regular expression. Return the compiled regex. If 'is_regex' true, then 'pattern' is directly compiled to a regex (if it's a string) or just returned as-is (assumes it's a regex object). """ if is_regex: if isinstance(pattern, str): return re.compile(pattern) else: return pattern if pattern: pattern_re = glob_to_re(pattern) else: pattern_re = '' if prefix is not None: # ditch end of pattern character empty_pattern = glob_to_re('') prefix_re = glob_to_re(prefix)[:-len(empty_pattern)] sep = os.sep if os.sep == '\\': sep = r'\\' pattern_re = "^" + sep.join((prefix_re, ".*" + pattern_re)) else: # no prefix -- respect anchor flag if anchor: pattern_re = "^" + pattern_re return re.compile(pattern_re)
[ "def", "translate_pattern", "(", "pattern", ",", "anchor", "=", "1", ",", "prefix", "=", "None", ",", "is_regex", "=", "0", ")", ":", "if", "is_regex", ":", "if", "isinstance", "(", "pattern", ",", "str", ")", ":", "return", "re", ".", "compile", "("...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/distutils/filelist.py#L312-L343
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/appdirs.py
python
user_log_dir
(appname=None, appauthor=None, version=None, opinion=True)
return path
r"""Return full path to the user-specific log dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "opinion" (boolean) can be False to disable the appending of "Logs" to the base app data dir for Windows, and "log" to the base cache dir for Unix. See discussion below. Typical user cache directories are: Mac OS X: ~/Library/Logs/<AppName> Unix: ~/.cache/<AppName>/log # or under $XDG_CACHE_HOME if defined Win XP: C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>\Logs Vista: C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>\Logs On Windows the only suggestion in the MSDN docs is that local settings go in the `CSIDL_LOCAL_APPDATA` directory. (Note: I'm interested in examples of what some windows apps use for a logs dir.) OPINION: This function appends "Logs" to the `CSIDL_LOCAL_APPDATA` value for Windows and appends "log" to the user cache dir for Unix. This can be disabled with the `opinion=False` option.
r"""Return full path to the user-specific log dir for this application.
[ "r", "Return", "full", "path", "to", "the", "user", "-", "specific", "log", "dir", "for", "this", "application", "." ]
def user_log_dir(appname=None, appauthor=None, version=None, opinion=True): r"""Return full path to the user-specific log dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "opinion" (boolean) can be False to disable the appending of "Logs" to the base app data dir for Windows, and "log" to the base cache dir for Unix. See discussion below. Typical user cache directories are: Mac OS X: ~/Library/Logs/<AppName> Unix: ~/.cache/<AppName>/log # or under $XDG_CACHE_HOME if defined Win XP: C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>\Logs Vista: C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>\Logs On Windows the only suggestion in the MSDN docs is that local settings go in the `CSIDL_LOCAL_APPDATA` directory. (Note: I'm interested in examples of what some windows apps use for a logs dir.) OPINION: This function appends "Logs" to the `CSIDL_LOCAL_APPDATA` value for Windows and appends "log" to the user cache dir for Unix. This can be disabled with the `opinion=False` option. """ if system == "darwin": path = os.path.join( os.path.expanduser('~/Library/Logs'), appname) elif system == "win32": path = user_data_dir(appname, appauthor, version) version = False if opinion: path = os.path.join(path, "Logs") else: path = user_cache_dir(appname, appauthor, version) version = False if opinion: path = os.path.join(path, "log") if appname and version: path = os.path.join(path, version) return path
[ "def", "user_log_dir", "(", "appname", "=", "None", ",", "appauthor", "=", "None", ",", "version", "=", "None", ",", "opinion", "=", "True", ")", ":", "if", "system", "==", "\"darwin\"", ":", "path", "=", "os", ".", "path", ".", "join", "(", "os", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/appdirs.py#L314-L362
Vipermdl/OCR_detection_IC15
8eebd353d6fac97f5832a138d7af3bd3071670db
trainer/trainer.py
python
Trainer._valid_epoch
(self)
return { 'val_loss': total_val_loss / len(self.valid_data_loader), 'val_metrics': (total_val_metrics / len(self.valid_data_loader)).tolist() }
Validate after training an epoch :return: A log that contains information about validation Note: The validation metrics in log must have the key 'val_metrics'.
Validate after training an epoch
[ "Validate", "after", "training", "an", "epoch" ]
def _valid_epoch(self): """ Validate after training an epoch :return: A log that contains information about validation Note: The validation metrics in log must have the key 'val_metrics'. """ self.model.eval() total_val_loss = 0 total_val_metrics = np.zeros(len(self.metrics)) with torch.no_grad(): for batch_idx, gt in enumerate(self.valid_data_loader): img, score_map, geo_map, training_mask, transcript = gt img, score_map, geo_map, training_mask = self._to_tensor(img, score_map, geo_map, training_mask) recog_map = None pred_score_map, pred_geo_map, pred_recog_map = self.model(img) loss = self.loss(score_map, pred_score_map, geo_map, pred_geo_map, pred_recog_map, recog_map, training_mask) total_val_loss += loss.item() output = (pred_score_map, pred_geo_map, pred_recog_map) target = (score_map, geo_map, recog_map) #total_val_metrics += self._eval_metrics(output, target, training_mask) #TODO: should add AP metric self.visdom.plot('val_loss', total_val_loss / len(self.valid_data_loader)) return { 'val_loss': total_val_loss / len(self.valid_data_loader), 'val_metrics': (total_val_metrics / len(self.valid_data_loader)).tolist() }
[ "def", "_valid_epoch", "(", "self", ")", ":", "self", ".", "model", ".", "eval", "(", ")", "total_val_loss", "=", "0", "total_val_metrics", "=", "np", ".", "zeros", "(", "len", "(", "self", ".", "metrics", ")", ")", "with", "torch", ".", "no_grad", "...
https://github.com/Vipermdl/OCR_detection_IC15/blob/8eebd353d6fac97f5832a138d7af3bd3071670db/trainer/trainer.py#L97-L129
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/flatmenu.py
python
FlatMenuBar.SetLCDMonitor
(self, lcd=True)
Sets whether the PC monitor is an LCD or not. :param bool `lcd`: ``True`` to use the settings appropriate for a LCD monitor, ``False`` otherwise.
Sets whether the PC monitor is an LCD or not.
[ "Sets", "whether", "the", "PC", "monitor", "is", "an", "LCD", "or", "not", "." ]
def SetLCDMonitor(self, lcd=True): """ Sets whether the PC monitor is an LCD or not. :param bool `lcd`: ``True`` to use the settings appropriate for a LCD monitor, ``False`` otherwise. """ if self._isLCD == lcd: return self._isLCD = lcd self.Refresh()
[ "def", "SetLCDMonitor", "(", "self", ",", "lcd", "=", "True", ")", ":", "if", "self", ".", "_isLCD", "==", "lcd", ":", "return", "self", ".", "_isLCD", "=", "lcd", "self", ".", "Refresh", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatmenu.py#L2966-L2978
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/tools/gyp/pylib/gyp/xcode_emulation.py
python
XcodeSettings.GetProductType
(self)
Returns the PRODUCT_TYPE of this target.
Returns the PRODUCT_TYPE of this target.
[ "Returns", "the", "PRODUCT_TYPE", "of", "this", "target", "." ]
def GetProductType(self): """Returns the PRODUCT_TYPE of this target.""" if self._IsIosAppExtension(): assert self._IsBundle(), ('ios_app_extension flag requires mac_bundle ' '(target %s)' % self.spec['target_name']) return 'com.apple.product-type.app-extension' if self._IsIosWatchKitExtension(): assert self._IsBundle(), ('ios_watchkit_extension flag requires ' 'mac_bundle (target %s)' % self.spec['target_name']) return 'com.apple.product-type.watchkit-extension' if self._IsIosWatchApp(): assert self._IsBundle(), ('ios_watch_app flag requires mac_bundle ' '(target %s)' % self.spec['target_name']) return 'com.apple.product-type.application.watchapp' if self._IsXCUiTest(): assert self._IsBundle(), ('mac_xcuitest_bundle flag requires mac_bundle ' '(target %s)' % self.spec['target_name']) return 'com.apple.product-type.bundle.ui-testing' if self._IsBundle(): return { 'executable': 'com.apple.product-type.application', 'loadable_module': 'com.apple.product-type.bundle', 'shared_library': 'com.apple.product-type.framework', }[self.spec['type']] else: return { 'executable': 'com.apple.product-type.tool', 'loadable_module': 'com.apple.product-type.library.dynamic', 'shared_library': 'com.apple.product-type.library.dynamic', 'static_library': 'com.apple.product-type.library.static', }[self.spec['type']]
[ "def", "GetProductType", "(", "self", ")", ":", "if", "self", ".", "_IsIosAppExtension", "(", ")", ":", "assert", "self", ".", "_IsBundle", "(", ")", ",", "(", "'ios_app_extension flag requires mac_bundle '", "'(target %s)'", "%", "self", ".", "spec", "[", "'t...
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/gyp/pylib/gyp/xcode_emulation.py#L380-L410
tangzhenyu/Scene-Text-Understanding
0f7ffc7aea5971a50cdc03d33d0a41075285948b
ctpn_crnn_ocr/CTPN/caffe/scripts/cpp_lint.py
python
IsErrorSuppressedByNolint
(category, linenum)
return (linenum in _error_suppressions.get(category, set()) or linenum in _error_suppressions.get(None, set()))
Returns true if the specified error category is suppressed on this line. Consults the global error_suppressions map populated by ParseNolintSuppressions/ResetNolintSuppressions. Args: category: str, the category of the error. linenum: int, the current line number. Returns: bool, True iff the error should be suppressed due to a NOLINT comment.
Returns true if the specified error category is suppressed on this line.
[ "Returns", "true", "if", "the", "specified", "error", "category", "is", "suppressed", "on", "this", "line", "." ]
def IsErrorSuppressedByNolint(category, linenum): """Returns true if the specified error category is suppressed on this line. Consults the global error_suppressions map populated by ParseNolintSuppressions/ResetNolintSuppressions. Args: category: str, the category of the error. linenum: int, the current line number. Returns: bool, True iff the error should be suppressed due to a NOLINT comment. """ return (linenum in _error_suppressions.get(category, set()) or linenum in _error_suppressions.get(None, set()))
[ "def", "IsErrorSuppressedByNolint", "(", "category", ",", "linenum", ")", ":", "return", "(", "linenum", "in", "_error_suppressions", ".", "get", "(", "category", ",", "set", "(", ")", ")", "or", "linenum", "in", "_error_suppressions", ".", "get", "(", "None...
https://github.com/tangzhenyu/Scene-Text-Understanding/blob/0f7ffc7aea5971a50cdc03d33d0a41075285948b/ctpn_crnn_ocr/CTPN/caffe/scripts/cpp_lint.py#L500-L513
JarveeLee/SynthText_Chinese_version
4b2cbc7d14741f21d0bb17966a339ab3574b09a8
poisson_reconstruct.py
python
blit_images
(im_top,im_back,scale_grad=1.0,mode='max')
return im_res.astype('uint8')
combine images using poission editing. IM_TOP and IM_BACK should be of the same size.
combine images using poission editing. IM_TOP and IM_BACK should be of the same size.
[ "combine", "images", "using", "poission", "editing", ".", "IM_TOP", "and", "IM_BACK", "should", "be", "of", "the", "same", "size", "." ]
def blit_images(im_top,im_back,scale_grad=1.0,mode='max'): """ combine images using poission editing. IM_TOP and IM_BACK should be of the same size. """ assert np.all(im_top.shape==im_back.shape) im_top = im_top.copy().astype('float32') im_back = im_back.copy().astype('float32') im_res = np.zeros_like(im_top) # frac of gradients which come from source: for ch in xrange(im_top.shape[2]): ims = im_top[:,:,ch] imd = im_back[:,:,ch] [gxs,gys] = get_grads(ims) [gxd,gyd] = get_grads(imd) gxs *= scale_grad gys *= scale_grad gxs_idx = gxs!=0 gys_idx = gys!=0 # mix the source and target gradients: if mode=='max': gx = gxs.copy() gxm = (np.abs(gxd))>np.abs(gxs) gx[gxm] = gxd[gxm] gy = gys.copy() gym = np.abs(gyd)>np.abs(gys) gy[gym] = gyd[gym] # get gradient mixture statistics: f_gx = np.sum((gx[gxs_idx]==gxs[gxs_idx]).flat) / (np.sum(gxs_idx.flat)+1e-6) f_gy = np.sum((gy[gys_idx]==gys[gys_idx]).flat) / (np.sum(gys_idx.flat)+1e-6) if min(f_gx, f_gy) <= 0.35: m = 'max' if scale_grad > 1: m = 'blend' return blit_images(im_top, im_back, scale_grad=1.5, mode=m) elif mode=='src': gx,gy = gxd.copy(), gyd.copy() gx[gxs_idx] = gxs[gxs_idx] gy[gys_idx] = gys[gys_idx] elif mode=='blend': # from recursive call: # just do an alpha blend gx = gxs+gxd gy = gys+gyd im_res[:,:,ch] = np.clip(poisson_solve(gx,gy,imd),0,255) return im_res.astype('uint8')
[ "def", "blit_images", "(", "im_top", ",", "im_back", ",", "scale_grad", "=", "1.0", ",", "mode", "=", "'max'", ")", ":", "assert", "np", ".", "all", "(", "im_top", ".", "shape", "==", "im_back", ".", "shape", ")", "im_top", "=", "im_top", ".", "copy"...
https://github.com/JarveeLee/SynthText_Chinese_version/blob/4b2cbc7d14741f21d0bb17966a339ab3574b09a8/poisson_reconstruct.py#L90-L145
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/core/setup_common.py
python
long_double_representation
(lines)
Given a binary dump as given by GNU od -b, look for long double representation.
Given a binary dump as given by GNU od -b, look for long double representation.
[ "Given", "a", "binary", "dump", "as", "given", "by", "GNU", "od", "-", "b", "look", "for", "long", "double", "representation", "." ]
def long_double_representation(lines): """Given a binary dump as given by GNU od -b, look for long double representation.""" # Read contains a list of 32 items, each item is a byte (in octal # representation, as a string). We 'slide' over the output until read is of # the form before_seq + content + after_sequence, where content is the long double # representation: # - content is 12 bytes: 80 bits Intel representation # - content is 16 bytes: 80 bits Intel representation (64 bits) or quad precision # - content is 8 bytes: same as double (not implemented yet) read = [''] * 32 saw = None for line in lines: # we skip the first word, as od -b output an index at the beginning of # each line for w in line.split()[1:]: read.pop(0) read.append(w) # If the end of read is equal to the after_sequence, read contains # the long double if read[-8:] == _AFTER_SEQ: saw = copy.copy(read) # if the content was 12 bytes, we only have 32 - 8 - 12 = 12 # "before" bytes. In other words the first 4 "before" bytes went # past the sliding window. if read[:12] == _BEFORE_SEQ[4:]: if read[12:-8] == _INTEL_EXTENDED_12B: return 'INTEL_EXTENDED_12_BYTES_LE' if read[12:-8] == _MOTOROLA_EXTENDED_12B: return 'MOTOROLA_EXTENDED_12_BYTES_BE' # if the content was 16 bytes, we are left with 32-8-16 = 16 # "before" bytes, so 8 went past the sliding window. elif read[:8] == _BEFORE_SEQ[8:]: if read[8:-8] == _INTEL_EXTENDED_16B: return 'INTEL_EXTENDED_16_BYTES_LE' elif read[8:-8] == _IEEE_QUAD_PREC_BE: return 'IEEE_QUAD_BE' elif read[8:-8] == _IEEE_QUAD_PREC_LE: return 'IEEE_QUAD_LE' elif read[8:-8] == _IBM_DOUBLE_DOUBLE_LE: return 'IBM_DOUBLE_DOUBLE_LE' elif read[8:-8] == _IBM_DOUBLE_DOUBLE_BE: return 'IBM_DOUBLE_DOUBLE_BE' # if the content was 8 bytes, left with 32-8-8 = 16 bytes elif read[:16] == _BEFORE_SEQ: if read[16:-8] == _IEEE_DOUBLE_LE: return 'IEEE_DOUBLE_LE' elif read[16:-8] == _IEEE_DOUBLE_BE: return 'IEEE_DOUBLE_BE' if saw is not None: raise ValueError("Unrecognized format (%s)" % saw) else: # We never detected the after_sequence raise ValueError("Could not lock sequences (%s)" % saw)
[ "def", "long_double_representation", "(", "lines", ")", ":", "# Read contains a list of 32 items, each item is a byte (in octal", "# representation, as a string). We 'slide' over the output until read is of", "# the form before_seq + content + after_sequence, where content is the long double", "# ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/core/setup_common.py#L346-L402
alexozer/jankdrone
c4b403eb254b41b832ab2bdfade12ba59c99e5dc
shm/lib/pyratemp/pyratemp.py
python
EvalPseudoSandbox.f_default
(self, expr, default=None)
``default()`` for the sandboxed code. Try to evaluate an expression and return the result or a fallback-/default-value; the `default`-value is used if `expr` does not exist/is invalid/results in None. This is very useful for optional data. :Parameter: - expr: "eval-expression" - default: fallback-value if eval(expr) fails or is None. :Returns: the eval-result or the "fallback"-value. :Note: the eval-expression has to be quoted! (like in eval) :Example: see module-docstring
``default()`` for the sandboxed code.
[ "default", "()", "for", "the", "sandboxed", "code", "." ]
def f_default(self, expr, default=None): """``default()`` for the sandboxed code. Try to evaluate an expression and return the result or a fallback-/default-value; the `default`-value is used if `expr` does not exist/is invalid/results in None. This is very useful for optional data. :Parameter: - expr: "eval-expression" - default: fallback-value if eval(expr) fails or is None. :Returns: the eval-result or the "fallback"-value. :Note: the eval-expression has to be quoted! (like in eval) :Example: see module-docstring """ try: r = self.eval(expr, self.vars_ptr) if r is None: return default return r #TODO: which exceptions should be catched here? except (NameError, LookupError, TypeError, AttributeError): return default
[ "def", "f_default", "(", "self", ",", "expr", ",", "default", "=", "None", ")", ":", "try", ":", "r", "=", "self", ".", "eval", "(", "expr", ",", "self", ".", "vars_ptr", ")", "if", "r", "is", "None", ":", "return", "default", "return", "r", "#TO...
https://github.com/alexozer/jankdrone/blob/c4b403eb254b41b832ab2bdfade12ba59c99e5dc/shm/lib/pyratemp/pyratemp.py#L968-L993
psi4/psi4
be533f7f426b6ccc263904e55122899b16663395
psi4/driver/procrouting/proc.py
python
run_ccenergy
(name, **kwargs)
return ccwfn
Function encoding sequence of PSI module calls for a CCSD, CC2, and CC3 calculation.
Function encoding sequence of PSI module calls for a CCSD, CC2, and CC3 calculation.
[ "Function", "encoding", "sequence", "of", "PSI", "module", "calls", "for", "a", "CCSD", "CC2", "and", "CC3", "calculation", "." ]
def run_ccenergy(name, **kwargs): """Function encoding sequence of PSI module calls for a CCSD, CC2, and CC3 calculation. """ optstash = p4util.OptionsState( ['TRANSQT2', 'WFN'], ['CCSORT', 'WFN'], ['CCENERGY', 'WFN']) if name == 'ccsd': core.set_local_option('TRANSQT2', 'WFN', 'CCSD') core.set_local_option('CCSORT', 'WFN', 'CCSD') core.set_local_option('CCTRANSORT', 'WFN', 'CCSD') core.set_local_option('CCENERGY', 'WFN', 'CCSD') elif name == 'ccsd(t)': core.set_local_option('TRANSQT2', 'WFN', 'CCSD_T') core.set_local_option('CCSORT', 'WFN', 'CCSD_T') core.set_local_option('CCTRANSORT', 'WFN', 'CCSD_T') core.set_local_option('CCENERGY', 'WFN', 'CCSD_T') elif name == 'a-ccsd(t)': core.set_local_option('TRANSQT2', 'WFN', 'CCSD_AT') core.set_local_option('CCSORT', 'WFN', 'CCSD_AT') core.set_local_option('CCTRANSORT', 'WFN', 'CCSD_AT') core.set_local_option('CCENERGY', 'WFN', 'CCSD_AT') core.set_local_option('CCHBAR', 'WFN', 'CCSD_AT') core.set_local_option('CCLAMBDA', 'WFN', 'CCSD_AT') elif name == 'cc2': core.set_local_option('TRANSQT2', 'WFN', 'CC2') core.set_local_option('CCSORT', 'WFN', 'CC2') core.set_local_option('CCTRANSORT', 'WFN', 'CC2') core.set_local_option('CCENERGY', 'WFN', 'CC2') elif name == 'cc3': core.set_local_option('TRANSQT2', 'WFN', 'CC3') core.set_local_option('CCSORT', 'WFN', 'CC3') core.set_local_option('CCTRANSORT', 'WFN', 'CC3') core.set_local_option('CCENERGY', 'WFN', 'CC3') elif name == 'eom-cc2': core.set_local_option('TRANSQT2', 'WFN', 'EOM_CC2') core.set_local_option('CCSORT', 'WFN', 'EOM_CC2') core.set_local_option('CCTRANSORT', 'WFN', 'EOM_CC2') core.set_local_option('CCENERGY', 'WFN', 'EOM_CC2') elif name == 'eom-ccsd': core.set_local_option('TRANSQT2', 'WFN', 'EOM_CCSD') core.set_local_option('CCSORT', 'WFN', 'EOM_CCSD') core.set_local_option('CCTRANSORT', 'WFN', 'EOM_CCSD') core.set_local_option('CCENERGY', 'WFN', 'EOM_CCSD') # Call a plain energy('ccenergy') and have full control over options, incl. wfn elif name == 'ccenergy': pass # Bypass routine scf if user did something special to get it to converge ref_wfn = kwargs.get('ref_wfn', None) if ref_wfn is None: ref_wfn = scf_helper(name, **kwargs) # C1 certified if core.get_global_option("CC_TYPE") == "DF": aux_basis = core.BasisSet.build(ref_wfn.molecule(), "DF_BASIS_CC", core.get_global_option("DF_BASIS_CC"), "RIFIT", core.get_global_option("BASIS")) ref_wfn.set_basisset("DF_BASIS_CC", aux_basis) # Ensure IWL files have been written proc_util.check_iwl_file_from_scf_type(core.get_global_option('SCF_TYPE'), ref_wfn) # Obtain semicanonical orbitals if (core.get_option('SCF', 'REFERENCE') == 'ROHF') and \ ((name in ['ccsd(t)', 'a-ccsd(t)', 'cc2', 'cc3', 'eom-cc2', 'eom-cc3']) or core.get_option('CCTRANSORT', 'SEMICANONICAL')): ref_wfn.semicanonicalize() if core.get_global_option('RUN_CCTRANSORT'): core.cctransort(ref_wfn) else: try: from psi4.driver.pasture import addins addins.ccsort_transqt2(ref_wfn) except: raise PastureRequiredError("RUN_CCTRANSORT") ccwfn = core.ccenergy(ref_wfn) if core.get_global_option('PE'): ccwfn.pe_state = ref_wfn.pe_state if name == 'a-ccsd(t)': core.cchbar(ref_wfn) lambdawfn = core.cclambda(ref_wfn) for k, v in lambdawfn.variables().items(): ccwfn.set_variable(k, v) optstash.restore() return ccwfn
[ "def", "run_ccenergy", "(", "name", ",", "*", "*", "kwargs", ")", ":", "optstash", "=", "p4util", ".", "OptionsState", "(", "[", "'TRANSQT2'", ",", "'WFN'", "]", ",", "[", "'CCSORT'", ",", "'WFN'", "]", ",", "[", "'CCENERGY'", ",", "'WFN'", "]", ")",...
https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/procrouting/proc.py#L2683-L2775
moflow/moflow
2dfb27c799c90c6caf1477508eca3eec616ef7d2
bap/libtracewrap/libtrace/protobuf/python/google/protobuf/descriptor.py
python
_NestedDescriptorBase.GetTopLevelContainingType
(self)
return desc
Returns the root if this is a nested type, or itself if its the root.
Returns the root if this is a nested type, or itself if its the root.
[ "Returns", "the", "root", "if", "this", "is", "a", "nested", "type", "or", "itself", "if", "its", "the", "root", "." ]
def GetTopLevelContainingType(self): """Returns the root if this is a nested type, or itself if its the root.""" desc = self while desc.containing_type is not None: desc = desc.containing_type return desc
[ "def", "GetTopLevelContainingType", "(", "self", ")", ":", "desc", "=", "self", "while", "desc", ".", "containing_type", "is", "not", "None", ":", "desc", "=", "desc", ".", "containing_type", "return", "desc" ]
https://github.com/moflow/moflow/blob/2dfb27c799c90c6caf1477508eca3eec616ef7d2/bap/libtracewrap/libtrace/protobuf/python/google/protobuf/descriptor.py#L150-L155
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
python/peacock/base/Preferences.py
python
Preferences.addColor
(self, name, caption, default, tooltip)
Convenience function to add a color preference.
Convenience function to add a color preference.
[ "Convenience", "function", "to", "add", "a", "color", "preference", "." ]
def addColor(self, name, caption, default, tooltip): """ Convenience function to add a color preference. """ self.addWidget(ColorPreferenceWidget(name, caption, default, tooltip, self._key))
[ "def", "addColor", "(", "self", ",", "name", ",", "caption", ",", "default", ",", "tooltip", ")", ":", "self", ".", "addWidget", "(", "ColorPreferenceWidget", "(", "name", ",", "caption", ",", "default", ",", "tooltip", ",", "self", ".", "_key", ")", "...
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/base/Preferences.py#L213-L217
neoml-lib/neoml
a0d370fba05269a1b2258cef126f77bbd2054a3e
NeoML/Python/neoml/Dnn/FullyConnected.py
python
FullyConnected.free_term
(self)
return Blob.Blob(self._internal.get_free_term())
Gets the free term vector, of element_count length.
Gets the free term vector, of element_count length.
[ "Gets", "the", "free", "term", "vector", "of", "element_count", "length", "." ]
def free_term(self): """Gets the free term vector, of element_count length. """ return Blob.Blob(self._internal.get_free_term())
[ "def", "free_term", "(", "self", ")", ":", "return", "Blob", ".", "Blob", "(", "self", ".", "_internal", ".", "get_free_term", "(", ")", ")" ]
https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/Dnn/FullyConnected.py#L125-L128
nucleic/atom
9f0cb2a8101dd63c354a98ebc7489b2c616dc82a
atom/delegator.py
python
Delegator.clone
(self)
return clone
Create a clone of the declarative property. This method also creates a clone of the internal delegate for mode handlers which use the original delegate as the context.
Create a clone of the declarative property.
[ "Create", "a", "clone", "of", "the", "declarative", "property", "." ]
def clone(self): """Create a clone of the declarative property. This method also creates a clone of the internal delegate for mode handlers which use the original delegate as the context. """ clone = super(Delegator, self).clone() delegate = self.delegate clone.delegate = delegate_clone = delegate.clone() mode, old = clone.post_getattr_mode if old is delegate: clone.set_post_getattr_mode(mode, delegate_clone) mode, old = clone.post_setattr_mode if old is delegate: clone.set_post_setattr_mode(mode, delegate_clone) mode, old = clone.default_value_mode if old is delegate: clone.set_default_value_mode(mode, delegate_clone) mode, old = clone.validate_mode if old is delegate: clone.set_validate_mode(mode, delegate_clone) mode, old = clone.post_validate_mode if old is delegate: clone.set_post_validate_mode(mode, delegate_clone) return clone
[ "def", "clone", "(", "self", ")", ":", "clone", "=", "super", "(", "Delegator", ",", "self", ")", ".", "clone", "(", ")", "delegate", "=", "self", ".", "delegate", "clone", ".", "delegate", "=", "delegate_clone", "=", "delegate", ".", "clone", "(", "...
https://github.com/nucleic/atom/blob/9f0cb2a8101dd63c354a98ebc7489b2c616dc82a/atom/delegator.py#L124-L155
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_controls.py
python
TextCtrl.EmulateKeyPress
(*args, **kwargs)
return _controls_.TextCtrl_EmulateKeyPress(*args, **kwargs)
EmulateKeyPress(self, KeyEvent event) -> bool
EmulateKeyPress(self, KeyEvent event) -> bool
[ "EmulateKeyPress", "(", "self", "KeyEvent", "event", ")", "-", ">", "bool" ]
def EmulateKeyPress(*args, **kwargs): """EmulateKeyPress(self, KeyEvent event) -> bool""" return _controls_.TextCtrl_EmulateKeyPress(*args, **kwargs)
[ "def", "EmulateKeyPress", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "TextCtrl_EmulateKeyPress", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L2039-L2041
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/_stc_utf8_methods.py
python
GetSelectedTextUTF8
(self)
return text
Retrieve the selected text as UTF8. In an ansi build of wxPython the text retrieved from the document is assumed to be in the current default encoding.
Retrieve the selected text as UTF8. In an ansi build of wxPython the text retrieved from the document is assumed to be in the current default encoding.
[ "Retrieve", "the", "selected", "text", "as", "UTF8", ".", "In", "an", "ansi", "build", "of", "wxPython", "the", "text", "retrieved", "from", "the", "document", "is", "assumed", "to", "be", "in", "the", "current", "default", "encoding", "." ]
def GetSelectedTextUTF8(self): """ Retrieve the selected text as UTF8. In an ansi build of wxPython the text retrieved from the document is assumed to be in the current default encoding. """ text = self.GetSelectedTextRaw() if not wx.USE_UNICODE: u = text.decode(wx.GetDefaultPyEncoding()) text = u.encode('utf-8') return text
[ "def", "GetSelectedTextUTF8", "(", "self", ")", ":", "text", "=", "self", ".", "GetSelectedTextRaw", "(", ")", "if", "not", "wx", ".", "USE_UNICODE", ":", "u", "=", "text", ".", "decode", "(", "wx", ".", "GetDefaultPyEncoding", "(", ")", ")", "text", "...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/_stc_utf8_methods.py#L54-L64
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/ops/gradients.py
python
_GatherInputs
(to_ops, reached_ops)
return inputs
List all inputs of to_ops that are in reached_ops. Args: to_ops: list of Operations. reached_ops: list of booleans, indexed by operation id. Returns: The list of all inputs of to_ops that are in reached_ops. That list includes all elements of to_ops.
List all inputs of to_ops that are in reached_ops.
[ "List", "all", "inputs", "of", "to_ops", "that", "are", "in", "reached_ops", "." ]
def _GatherInputs(to_ops, reached_ops): """List all inputs of to_ops that are in reached_ops. Args: to_ops: list of Operations. reached_ops: list of booleans, indexed by operation id. Returns: The list of all inputs of to_ops that are in reached_ops. That list includes all elements of to_ops. """ inputs = [] queue = collections.deque() queue.extend(to_ops) while queue: op = queue.popleft() # We are interested in this op. if reached_ops[op._id]: inputs.append(op) # Clear the boolean so we won't add the inputs again. reached_ops[op._id] = False for inp in op.inputs: queue.append(inp.op) return inputs
[ "def", "_GatherInputs", "(", "to_ops", ",", "reached_ops", ")", ":", "inputs", "=", "[", "]", "queue", "=", "collections", ".", "deque", "(", ")", "queue", ".", "extend", "(", "to_ops", ")", "while", "queue", ":", "op", "=", "queue", ".", "popleft", ...
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/gradients.py#L119-L142
goldeneye-source/ges-code
2630cd8ef3d015af53c72ec2e19fc1f7e7fe8d9d
thirdparty/protobuf-2.3.0/python/google/protobuf/internal/encoder.py
python
MessageSetItemEncoder
(field_number)
return EncodeField
Encoder for extensions of MessageSet. The message set message looks like this: message MessageSet { repeated group Item = 1 { required int32 type_id = 2; required string message = 3; } }
Encoder for extensions of MessageSet.
[ "Encoder", "for", "extensions", "of", "MessageSet", "." ]
def MessageSetItemEncoder(field_number): """Encoder for extensions of MessageSet. The message set message looks like this: message MessageSet { repeated group Item = 1 { required int32 type_id = 2; required string message = 3; } } """ start_bytes = "".join([ TagBytes(1, wire_format.WIRETYPE_START_GROUP), TagBytes(2, wire_format.WIRETYPE_VARINT), _VarintBytes(field_number), TagBytes(3, wire_format.WIRETYPE_LENGTH_DELIMITED)]) end_bytes = TagBytes(1, wire_format.WIRETYPE_END_GROUP) local_EncodeVarint = _EncodeVarint def EncodeField(write, value): write(start_bytes) local_EncodeVarint(write, value.ByteSize()) value._InternalSerialize(write) return write(end_bytes) return EncodeField
[ "def", "MessageSetItemEncoder", "(", "field_number", ")", ":", "start_bytes", "=", "\"\"", ".", "join", "(", "[", "TagBytes", "(", "1", ",", "wire_format", ".", "WIRETYPE_START_GROUP", ")", ",", "TagBytes", "(", "2", ",", "wire_format", ".", "WIRETYPE_VARINT",...
https://github.com/goldeneye-source/ges-code/blob/2630cd8ef3d015af53c72ec2e19fc1f7e7fe8d9d/thirdparty/protobuf-2.3.0/python/google/protobuf/internal/encoder.py#L661-L686
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py
python
Canvas.postscript
(self, cnf={}, **kw)
return self.tk.call((self._w, 'postscript') + self._options(cnf, kw))
Print the contents of the canvas to a postscript file. Valid options: colormap, colormode, file, fontmap, height, pageanchor, pageheight, pagewidth, pagex, pagey, rotate, width, x, y.
Print the contents of the canvas to a postscript file. Valid options: colormap, colormode, file, fontmap, height, pageanchor, pageheight, pagewidth, pagex, pagey, rotate, width, x, y.
[ "Print", "the", "contents", "of", "the", "canvas", "to", "a", "postscript", "file", ".", "Valid", "options", ":", "colormap", "colormode", "file", "fontmap", "height", "pageanchor", "pageheight", "pagewidth", "pagex", "pagey", "rotate", "width", "x", "y", "." ...
def postscript(self, cnf={}, **kw): """Print the contents of the canvas to a postscript file. Valid options: colormap, colormode, file, fontmap, height, pageanchor, pageheight, pagewidth, pagex, pagey, rotate, width, x, y.""" return self.tk.call((self._w, 'postscript') + self._options(cnf, kw))
[ "def", "postscript", "(", "self", ",", "cnf", "=", "{", "}", ",", "*", "*", "kw", ")", ":", "return", "self", ".", "tk", ".", "call", "(", "(", "self", ".", "_w", ",", "'postscript'", ")", "+", "self", ".", "_options", "(", "cnf", ",", "kw", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py#L2592-L2598
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_windows.py
python
PageSetupDialogData.SetPrintData
(*args, **kwargs)
return _windows_.PageSetupDialogData_SetPrintData(*args, **kwargs)
SetPrintData(self, PrintData printData)
SetPrintData(self, PrintData printData)
[ "SetPrintData", "(", "self", "PrintData", "printData", ")" ]
def SetPrintData(*args, **kwargs): """SetPrintData(self, PrintData printData)""" return _windows_.PageSetupDialogData_SetPrintData(*args, **kwargs)
[ "def", "SetPrintData", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "PageSetupDialogData_SetPrintData", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L4979-L4981
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/unicode_support.py
python
_PyUnicode_ExtendedCase
(typingctx, index)
return sig, details
Accessor function for the _PyUnicode_ExtendedCase array, binds to numba_get_PyUnicode_ExtendedCase which wraps the array and does the lookup
Accessor function for the _PyUnicode_ExtendedCase array, binds to numba_get_PyUnicode_ExtendedCase which wraps the array and does the lookup
[ "Accessor", "function", "for", "the", "_PyUnicode_ExtendedCase", "array", "binds", "to", "numba_get_PyUnicode_ExtendedCase", "which", "wraps", "the", "array", "and", "does", "the", "lookup" ]
def _PyUnicode_ExtendedCase(typingctx, index): """ Accessor function for the _PyUnicode_ExtendedCase array, binds to numba_get_PyUnicode_ExtendedCase which wraps the array and does the lookup """ if not isinstance(index, types.Integer): raise TypingError("Expected an index") def details(context, builder, signature, args): ll_Py_UCS4 = context.get_value_type(_Py_UCS4) ll_intc = context.get_value_type(types.intc) fnty = lc.Type.function(ll_Py_UCS4, [ll_intc]) fn = builder.module.get_or_insert_function( fnty, name="numba_get_PyUnicode_ExtendedCase") return builder.call(fn, [args[0]]) sig = _Py_UCS4(types.intc) return sig, details
[ "def", "_PyUnicode_ExtendedCase", "(", "typingctx", ",", "index", ")", ":", "if", "not", "isinstance", "(", "index", ",", "types", ".", "Integer", ")", ":", "raise", "TypingError", "(", "\"Expected an index\"", ")", "def", "details", "(", "context", ",", "bu...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/unicode_support.py#L155-L172
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/dataset/transforms/py_transforms.py
python
RandomOrder.__call__
(self, img)
return util.random_order(img, self.transforms)
Call method. Args: img (PIL image): Image to apply transformations in a random order. Returns: img (PIL image), Transformed image.
Call method.
[ "Call", "method", "." ]
def __call__(self, img): """ Call method. Args: img (PIL image): Image to apply transformations in a random order. Returns: img (PIL image), Transformed image. """ return util.random_order(img, self.transforms)
[ "def", "__call__", "(", "self", ",", "img", ")", ":", "return", "util", ".", "random_order", "(", "img", ",", "self", ".", "transforms", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/dataset/transforms/py_transforms.py#L328-L338
artyom-beilis/cppcms
463a9a68e0bc15e2d01e8b8d72cc4fcc7f2b3264
contrib/integration/session/python/cppcms.py
python
Cookie.expires_defined
(self)
return Loader.capi.cppcms_capi_cookie_expires_defined(self.d)
Returns if expires present in the cookie
Returns if expires present in the cookie
[ "Returns", "if", "expires", "present", "in", "the", "cookie" ]
def expires_defined(self): """Returns if expires present in the cookie""" return Loader.capi.cppcms_capi_cookie_expires_defined(self.d)
[ "def", "expires_defined", "(", "self", ")", ":", "return", "Loader", ".", "capi", ".", "cppcms_capi_cookie_expires_defined", "(", "self", ".", "d", ")" ]
https://github.com/artyom-beilis/cppcms/blob/463a9a68e0bc15e2d01e8b8d72cc4fcc7f2b3264/contrib/integration/session/python/cppcms.py#L237-L239
Illumina/manta
75b5c38d4fcd2f6961197b28a41eb61856f2d976
src/python/lib/sharedWorkflow.py
python
lister
(x)
return list(x)
Convert input into a list, whether it's already iterable or not. Make an exception for individual strings to be returned as a list of one string, instead of being chopped into letters Also, convert None type to empty list:
Convert input into a list, whether it's already iterable or not. Make an exception for individual strings to be returned as a list of one string, instead of being chopped into letters Also, convert None type to empty list:
[ "Convert", "input", "into", "a", "list", "whether", "it", "s", "already", "iterable", "or", "not", ".", "Make", "an", "exception", "for", "individual", "strings", "to", "be", "returned", "as", "a", "list", "of", "one", "string", "instead", "of", "being", ...
def lister(x): """ Convert input into a list, whether it's already iterable or not. Make an exception for individual strings to be returned as a list of one string, instead of being chopped into letters Also, convert None type to empty list: """ # special handling in case a single string is given: if x is None : return [] if (isString(x) or (not isIterable(x))) : return [x] return list(x)
[ "def", "lister", "(", "x", ")", ":", "# special handling in case a single string is given:", "if", "x", "is", "None", ":", "return", "[", "]", "if", "(", "isString", "(", "x", ")", "or", "(", "not", "isIterable", "(", "x", ")", ")", ")", ":", "return", ...
https://github.com/Illumina/manta/blob/75b5c38d4fcd2f6961197b28a41eb61856f2d976/src/python/lib/sharedWorkflow.py#L44-L54
mhammond/pywin32
44afd86ba8485194df93234639243252deeb40d5
com/win32com/client/gencache.py
python
MakeModuleForTypelibInterface
( typelib_ob, progressInstance=None, bForDemand=bForDemandDefault, bBuildHidden=1 )
return GetModuleForTypelib(guid, lcid, major, minor)
Generate support for a type library. Given a PyITypeLib interface generate and import the necessary support files. This is useful for getting makepy support for a typelibrary that is not registered - the caller can locate and load the type library itself, rather than relying on COM to find it. Returns the Python module. Params typelib_ob -- The type library itself progressInstance -- Instance to use as progress indicator, or None to use the GUI progress bar.
Generate support for a type library.
[ "Generate", "support", "for", "a", "type", "library", "." ]
def MakeModuleForTypelibInterface( typelib_ob, progressInstance=None, bForDemand=bForDemandDefault, bBuildHidden=1 ): """Generate support for a type library. Given a PyITypeLib interface generate and import the necessary support files. This is useful for getting makepy support for a typelibrary that is not registered - the caller can locate and load the type library itself, rather than relying on COM to find it. Returns the Python module. Params typelib_ob -- The type library itself progressInstance -- Instance to use as progress indicator, or None to use the GUI progress bar. """ from . import makepy try: makepy.GenerateFromTypeLibSpec( typelib_ob, progressInstance=progressInstance, bForDemand=bForDemandDefault, bBuildHidden=bBuildHidden, ) except pywintypes.com_error: return None tla = typelib_ob.GetLibAttr() guid = tla[0] lcid = tla[1] major = tla[3] minor = tla[4] return GetModuleForTypelib(guid, lcid, major, minor)
[ "def", "MakeModuleForTypelibInterface", "(", "typelib_ob", ",", "progressInstance", "=", "None", ",", "bForDemand", "=", "bForDemandDefault", ",", "bBuildHidden", "=", "1", ")", ":", "from", ".", "import", "makepy", "try", ":", "makepy", ".", "GenerateFromTypeLibS...
https://github.com/mhammond/pywin32/blob/44afd86ba8485194df93234639243252deeb40d5/com/win32com/client/gencache.py#L324-L356
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/distributed/fleet/elastic/manager.py
python
ElasticManager._parse_np
(self, np: str)
return min_np, max_np
np format is "MIN" or "MIN:MAX"
np format is "MIN" or "MIN:MAX"
[ "np", "format", "is", "MIN", "or", "MIN", ":", "MAX" ]
def _parse_np(self, np: str): """ np format is "MIN" or "MIN:MAX" """ np_str = np or os.getenv('PADDLE_ELASTIC_NP', "0") np_dict = np_str.split(":") min_np = max_np = 0 if len(np_dict) == 1: # Fault tolerant min_np = int(np_dict[0]) min_np = 1 if min_np <= 0 else min_np max_np = 1 elif len(np_dict) == 2: # Elastic min_np = int(np_dict[0]) max_np = int(np_dict[1]) min_np = 1 if min_np <= 0 else min_np max_np = min_np if min_np > max_np else max_np else: raise ValueError( f'the np={np} needs to be in "MIN" or "MIN:MAX" format') return min_np, max_np
[ "def", "_parse_np", "(", "self", ",", "np", ":", "str", ")", ":", "np_str", "=", "np", "or", "os", ".", "getenv", "(", "'PADDLE_ELASTIC_NP'", ",", "\"0\"", ")", "np_dict", "=", "np_str", ".", "split", "(", "\":\"", ")", "min_np", "=", "max_np", "=", ...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/distributed/fleet/elastic/manager.py#L357-L379
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/html.py
python
HtmlWindow.SetBorders
(*args, **kwargs)
return _html.HtmlWindow_SetBorders(*args, **kwargs)
SetBorders(self, int b)
SetBorders(self, int b)
[ "SetBorders", "(", "self", "int", "b", ")" ]
def SetBorders(*args, **kwargs): """SetBorders(self, int b)""" return _html.HtmlWindow_SetBorders(*args, **kwargs)
[ "def", "SetBorders", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_html", ".", "HtmlWindow_SetBorders", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/html.py#L1037-L1039
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
packages/seacas/scripts/exomerge3.py
python
ExodusModel._get_closest_point_distance
(self, points, sorting_coord=0, trials=0)
return dist
Return the distance between the two closest points.
Return the distance between the two closest points.
[ "Return", "the", "distance", "between", "the", "two", "closest", "points", "." ]
def _get_closest_point_distance(self, points, sorting_coord=0, trials=0): """Return the distance between the two closest points.""" # handle cases of 3 or less points by brute force point_count = len(points) if point_count <= 3: return self._get_closest_point_distance_brute(points) # find min and max values for the sorting coord low = min(x[sorting_coord] for x in points) high = max(x[sorting_coord] for x in points) # if min and max values are the same, change the coord and try again mid = (low + high) / 2.0 if low == mid or mid == high: if trials >= 2: return self._get_closest_point_distance_brute(points) return self._get_closest_point_distance(points, (sorting_coord + 1) % 3, trials + 1) # sort into two lists low_points = [x for x in points if x[sorting_coord] <= mid] high_points = [x for x in points if x[sorting_coord] > mid] assert len(low_points) < point_count assert len(high_points) < point_count # find closest pair within each set dist = min(self._get_closest_point_distance(low_points), self._get_closest_point_distance(high_points)) del low_points del high_points # find points sufficiently close to centerline mid_low = mid - dist mid_high = mid - dist mid_points = [ x for x in points if x[sorting_coord] >= mid_low and x[sorting_coord] <= mid_high ] if len(mid_points) == point_count: return self._get_closest_point_distance_brute(points) dist = min( dist, self._get_closest_point_distance(mid_points, (sorting_coord + 1) % 3)) return dist
[ "def", "_get_closest_point_distance", "(", "self", ",", "points", ",", "sorting_coord", "=", "0", ",", "trials", "=", "0", ")", ":", "# handle cases of 3 or less points by brute force", "point_count", "=", "len", "(", "points", ")", "if", "point_count", "<=", "3",...
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exomerge3.py#L8201-L8241
zerotier/libzt
41eb9aebc80a5f1c816fa26a06cefde9de906676
src/bindings/python/sockets.py
python
handle_error
(err)
Convert libzt error code to exception
Convert libzt error code to exception
[ "Convert", "libzt", "error", "code", "to", "exception" ]
def handle_error(err): """Convert libzt error code to exception""" if err == libzt.ZTS_ERR_SOCKET: if errno() == libzt.ZTS_EAGAIN: raise BlockingIOError() if errno() == libzt.ZTS_EINPROGRESS: raise BlockingIOError() if errno() == libzt.ZTS_EALREADY: raise BlockingIOError() if errno() == libzt.ZTS_ECONNABORTED: raise ConnectionAbortedError() if errno() == libzt.ZTS_ECONNREFUSED: raise ConnectionRefusedError() if errno() == libzt.ZTS_ECONNRESET: raise ConnectionResetError() if errno() == libzt.ZTS_ETIMEDOUT: raise TimeoutError() raise Exception("ZTS_ERR_SOCKET (" + str(err) + ")") if err == libzt.ZTS_ERR_SERVICE: raise Exception("ZTS_ERR_SERVICE (" + str(err) + ")") if err == libzt.ZTS_ERR_ARG: raise Exception("ZTS_ERR_ARG (" + str(err) + ")") # ZTS_ERR_NO_RESULT isn't strictly an error # if (err == libzt.ZTS_ERR_NO_RESULT): # raise Exception('ZTS_ERR_NO_RESULT (' + err + ')') if err == libzt.ZTS_ERR_GENERAL: raise Exception("ZTS_ERR_GENERAL (" + str(err) + ")")
[ "def", "handle_error", "(", "err", ")", ":", "if", "err", "==", "libzt", ".", "ZTS_ERR_SOCKET", ":", "if", "errno", "(", ")", "==", "libzt", ".", "ZTS_EAGAIN", ":", "raise", "BlockingIOError", "(", ")", "if", "errno", "(", ")", "==", "libzt", ".", "Z...
https://github.com/zerotier/libzt/blob/41eb9aebc80a5f1c816fa26a06cefde9de906676/src/bindings/python/sockets.py#L6-L32
Ewenwan/MVision
97b394dfa48cb21c82cd003b1a952745e413a17f
deepLearning/07_gbrbm.py
python
GBRBM.get_reconstruction_cost
(self)
return mse
Compute the mse of the original input and the reconstruction
Compute the mse of the original input and the reconstruction
[ "Compute", "the", "mse", "of", "the", "original", "input", "and", "the", "reconstruction" ]
def get_reconstruction_cost(self): """Compute the mse of the original input and the reconstruction""" activation_h = self.propup(self.input) activation_v = self.propdown(activation_h) mse = tf.reduce_mean(tf.reduce_sum(tf.square(self.input - activation_v), axis=1)) return mse
[ "def", "get_reconstruction_cost", "(", "self", ")", ":", "activation_h", "=", "self", ".", "propup", "(", "self", ".", "input", ")", "activation_v", "=", "self", ".", "propdown", "(", "activation_h", ")", "mse", "=", "tf", ".", "reduce_mean", "(", "tf", ...
https://github.com/Ewenwan/MVision/blob/97b394dfa48cb21c82cd003b1a952745e413a17f/deepLearning/07_gbrbm.py#L64-L69
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/collections.py
python
OrderedDict.popitem
(self, last=True)
return key, value
od.popitem() -> (k, v), return and remove a (key, value) pair. Pairs are returned in LIFO order if last is true or FIFO order if false.
od.popitem() -> (k, v), return and remove a (key, value) pair. Pairs are returned in LIFO order if last is true or FIFO order if false.
[ "od", ".", "popitem", "()", "-", ">", "(", "k", "v", ")", "return", "and", "remove", "a", "(", "key", "value", ")", "pair", ".", "Pairs", "are", "returned", "in", "LIFO", "order", "if", "last", "is", "true", "or", "FIFO", "order", "if", "false", ...
def popitem(self, last=True): '''od.popitem() -> (k, v), return and remove a (key, value) pair. Pairs are returned in LIFO order if last is true or FIFO order if false. ''' if not self: raise KeyError('dictionary is empty') key = next(reversed(self) if last else iter(self)) value = self.pop(key) return key, value
[ "def", "popitem", "(", "self", ",", "last", "=", "True", ")", ":", "if", "not", "self", ":", "raise", "KeyError", "(", "'dictionary is empty'", ")", "key", "=", "next", "(", "reversed", "(", "self", ")", "if", "last", "else", "iter", "(", "self", ")"...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/collections.py#L170-L179
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/telemetry/android/android_story.py
python
AndroidStory.Run
(self, shared_state)
Execute the interactions with the applications.
Execute the interactions with the applications.
[ "Execute", "the", "interactions", "with", "the", "applications", "." ]
def Run(self, shared_state): """Execute the interactions with the applications.""" raise NotImplementedError
[ "def", "Run", "(", "self", ",", "shared_state", ")", ":", "raise", "NotImplementedError" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/android/android_story.py#L26-L28
microsoft/checkedc-clang
a173fefde5d7877b7750e7ce96dd08cf18baebf2
libcxx/utils/gdb/libcxx/printers.py
python
_prettify_typename
(gdb_type)
return result
Returns a pretty name for the type, or None if no name can be found. Arguments: gdb_type(gdb.Type): A type object. Returns: A string, without type_defs, libc++ namespaces, and common substitutions applied.
Returns a pretty name for the type, or None if no name can be found.
[ "Returns", "a", "pretty", "name", "for", "the", "type", "or", "None", "if", "no", "name", "can", "be", "found", "." ]
def _prettify_typename(gdb_type): """Returns a pretty name for the type, or None if no name can be found. Arguments: gdb_type(gdb.Type): A type object. Returns: A string, without type_defs, libc++ namespaces, and common substitutions applied. """ type_without_typedefs = gdb_type.strip_typedefs() typename = type_without_typedefs.name or type_without_typedefs.tag or \ str(type_without_typedefs) result = _remove_cxx_namespace(typename) for find_str, subst_str in _common_substitutions: result = re.sub(find_str, subst_str, result) return result
[ "def", "_prettify_typename", "(", "gdb_type", ")", ":", "type_without_typedefs", "=", "gdb_type", ".", "strip_typedefs", "(", ")", "typename", "=", "type_without_typedefs", ".", "name", "or", "type_without_typedefs", ".", "tag", "or", "str", "(", "type_without_typed...
https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/libcxx/utils/gdb/libcxx/printers.py#L77-L94
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/plan/motionplanning.py
python
CSpaceInterface.sample
(self)
return _motionplanning.CSpaceInterface_sample(self)
Samples a configuration. Returns: (:obj:`object`):
Samples a configuration.
[ "Samples", "a", "configuration", "." ]
def sample(self): """ Samples a configuration. Returns: (:obj:`object`): """ return _motionplanning.CSpaceInterface_sample(self)
[ "def", "sample", "(", "self", ")", ":", "return", "_motionplanning", ".", "CSpaceInterface_sample", "(", "self", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/plan/motionplanning.py#L497-L504
webmproject/libwebm
ee0bab576c338c9807249b99588e352b7268cb62
PRESUBMIT.py
python
_RunShfmtCheckCmd
(input_api, output_api, bash_file)
return output_api.PresubmitError("%s\n%s (%4.2fs) failed\n%s" % (name, " ".join(cmd), duration, output[1]))
shfmt command wrapper.
shfmt command wrapper.
[ "shfmt", "command", "wrapper", "." ]
def _RunShfmtCheckCmd(input_api, output_api, bash_file): """shfmt command wrapper.""" cmd = [ "shfmt", "-i", _BASH_INDENTATION, "-bn", "-ci", "-sr", "-kp", "-d", bash_file ] name = "Check %s file." % bash_file start = input_api.time.time() output, rc = subprocess2.communicate( cmd, stdout=None, stderr=subprocess2.PIPE, universal_newlines=True) duration = input_api.time.time() - start if rc == 0: return output_api.PresubmitResult("%s\n%s (%4.2fs)\n" % (name, " ".join(cmd), duration)) return output_api.PresubmitError("%s\n%s (%4.2fs) failed\n%s" % (name, " ".join(cmd), duration, output[1]))
[ "def", "_RunShfmtCheckCmd", "(", "input_api", ",", "output_api", ",", "bash_file", ")", ":", "cmd", "=", "[", "\"shfmt\"", ",", "\"-i\"", ",", "_BASH_INDENTATION", ",", "\"-bn\"", ",", "\"-ci\"", ",", "\"-sr\"", ",", "\"-kp\"", ",", "\"-d\"", ",", "bash_file...
https://github.com/webmproject/libwebm/blob/ee0bab576c338c9807249b99588e352b7268cb62/PRESUBMIT.py#L104-L119
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/utils/validation.py
python
_check_large_sparse
(X, accept_large_sparse=False)
Raise a ValueError if X has 64bit indices and accept_large_sparse=False
Raise a ValueError if X has 64bit indices and accept_large_sparse=False
[ "Raise", "a", "ValueError", "if", "X", "has", "64bit", "indices", "and", "accept_large_sparse", "=", "False" ]
def _check_large_sparse(X, accept_large_sparse=False): """Raise a ValueError if X has 64bit indices and accept_large_sparse=False """ if not accept_large_sparse: supported_indices = ["int32"] if X.getformat() == "coo": index_keys = ['col', 'row'] elif X.getformat() in ["csr", "csc", "bsr"]: index_keys = ['indices', 'indptr'] else: return for key in index_keys: indices_datatype = getattr(X, key).dtype if (indices_datatype not in supported_indices): raise ValueError("Only sparse matrices with 32-bit integer" " indices are accepted. Got %s indices." % indices_datatype)
[ "def", "_check_large_sparse", "(", "X", ",", "accept_large_sparse", "=", "False", ")", ":", "if", "not", "accept_large_sparse", ":", "supported_indices", "=", "[", "\"int32\"", "]", "if", "X", ".", "getformat", "(", ")", "==", "\"coo\"", ":", "index_keys", "...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/utils/validation.py#L617-L633
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/ttk.py
python
Treeview.detach
(self, *items)
Unlinks all of the specified items from the tree. The items and all of their descendants are still present, and may be reinserted at another point in the tree, but will not be displayed. The root item may not be detached.
Unlinks all of the specified items from the tree.
[ "Unlinks", "all", "of", "the", "specified", "items", "from", "the", "tree", "." ]
def detach(self, *items): """Unlinks all of the specified items from the tree. The items and all of their descendants are still present, and may be reinserted at another point in the tree, but will not be displayed. The root item may not be detached.""" self.tk.call(self._w, "detach", items)
[ "def", "detach", "(", "self", ",", "*", "items", ")", ":", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "\"detach\"", ",", "items", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/ttk.py#L1220-L1226
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Fem/femtools/tokrules.py
python
t_INT
(t)
return t
r'\d+
r'\d+
[ "r", "\\", "d", "+" ]
def t_INT(t): r'\d+' t.value = int(t.value) return t
[ "def", "t_INT", "(", "t", ")", ":", "t", ".", "value", "=", "int", "(", "t", ".", "value", ")", "return", "t" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Fem/femtools/tokrules.py#L60-L63
dmlc/nnvm
dab5ce8ab6adbf4edd8bd2fa89f1a99f343b6e38
python/nnvm/compiler/param_dict.py
python
load_param_dict
(param_bytes)
return param_dict
Load parameter dictionary to binary bytes. Parameters ---------- param_bytes: bytearray Serialized parameters. Returns ------- params : dict of str to NDArray The parameter dictionary.
Load parameter dictionary to binary bytes.
[ "Load", "parameter", "dictionary", "to", "binary", "bytes", "." ]
def load_param_dict(param_bytes): """Load parameter dictionary to binary bytes. Parameters ---------- param_bytes: bytearray Serialized parameters. Returns ------- params : dict of str to NDArray The parameter dictionary. """ if isinstance(param_bytes, (bytes, str)): param_bytes = bytearray(param_bytes) load_mod = _load_param_dict(param_bytes) size = load_mod(0) param_dict = {} for i in range(size): key = load_mod(1, i) dltensor_handle = ctypes.cast(load_mod(2, i), TVMArrayHandle) param_dict[key] = tvm.nd.NDArray(dltensor_handle, False) return param_dict
[ "def", "load_param_dict", "(", "param_bytes", ")", ":", "if", "isinstance", "(", "param_bytes", ",", "(", "bytes", ",", "str", ")", ")", ":", "param_bytes", "=", "bytearray", "(", "param_bytes", ")", "load_mod", "=", "_load_param_dict", "(", "param_bytes", "...
https://github.com/dmlc/nnvm/blob/dab5ce8ab6adbf4edd8bd2fa89f1a99f343b6e38/python/nnvm/compiler/param_dict.py#L47-L69
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemWebCommunicator/AWS/common-code/lib/AWSIoTPythonSDK/core/protocol/paho/client.py
python
Client.configIAMCredentials
(self, srcAWSAccessKeyID, srcAWSSecretAccessKey, srcAWSSessionToken)
Make custom settings for IAM credentials for websocket connection srcAWSAccessKeyID - AWS IAM access key srcAWSSecretAccessKey - AWS IAM secret key srcAWSSessionToken - AWS Session Token
Make custom settings for IAM credentials for websocket connection srcAWSAccessKeyID - AWS IAM access key srcAWSSecretAccessKey - AWS IAM secret key srcAWSSessionToken - AWS Session Token
[ "Make", "custom", "settings", "for", "IAM", "credentials", "for", "websocket", "connection", "srcAWSAccessKeyID", "-", "AWS", "IAM", "access", "key", "srcAWSSecretAccessKey", "-", "AWS", "IAM", "secret", "key", "srcAWSSessionToken", "-", "AWS", "Session", "Token" ]
def configIAMCredentials(self, srcAWSAccessKeyID, srcAWSSecretAccessKey, srcAWSSessionToken): """ Make custom settings for IAM credentials for websocket connection srcAWSAccessKeyID - AWS IAM access key srcAWSSecretAccessKey - AWS IAM secret key srcAWSSessionToken - AWS Session Token """ self._AWSAccessKeyIDCustomConfig = srcAWSAccessKeyID self._AWSSecretAccessKeyCustomConfig = srcAWSSecretAccessKey self._AWSSessionTokenCustomConfig = srcAWSSessionToken
[ "def", "configIAMCredentials", "(", "self", ",", "srcAWSAccessKeyID", ",", "srcAWSSecretAccessKey", ",", "srcAWSSessionToken", ")", ":", "self", ".", "_AWSAccessKeyIDCustomConfig", "=", "srcAWSAccessKeyID", "self", ".", "_AWSSecretAccessKeyCustomConfig", "=", "srcAWSSecretA...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemWebCommunicator/AWS/common-code/lib/AWSIoTPythonSDK/core/protocol/paho/client.py#L527-L536
apple/swift
469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893
utils/swift_build_support/swift_build_support/products/product.py
python
ProductBuilder.__init__
(self, product_class, args, toolchain, workspace)
Create a product builder for the given product class. Parameters ---------- product_class : class A subtype of `Product` which describes the product being built by this builder. args : `argparse.Namespace` The arguments passed by the user to the invocation of the script. A builder should consider this argument read-only. toolchain : `swift_build_support.toolchain.Toolchain` The toolchain being used to build the product. The toolchain will point to the tools that the builder should use to build (like the compiler or the linker). workspace : `swift_build_support.workspace.Workspace` The workspace where the source code and the build directories have to be located. A builder should use the workspace to access its own source/build directory, as well as other products source/build directories.
Create a product builder for the given product class.
[ "Create", "a", "product", "builder", "for", "the", "given", "product", "class", "." ]
def __init__(self, product_class, args, toolchain, workspace): """ Create a product builder for the given product class. Parameters ---------- product_class : class A subtype of `Product` which describes the product being built by this builder. args : `argparse.Namespace` The arguments passed by the user to the invocation of the script. A builder should consider this argument read-only. toolchain : `swift_build_support.toolchain.Toolchain` The toolchain being used to build the product. The toolchain will point to the tools that the builder should use to build (like the compiler or the linker). workspace : `swift_build_support.workspace.Workspace` The workspace where the source code and the build directories have to be located. A builder should use the workspace to access its own source/build directory, as well as other products source/build directories. """ pass
[ "def", "__init__", "(", "self", ",", "product_class", ",", "args", ",", "toolchain", ",", "workspace", ")", ":", "pass" ]
https://github.com/apple/swift/blob/469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893/utils/swift_build_support/swift_build_support/products/product.py#L394-L416
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/stc.py
python
StyledTextCtrl.GetPrintWrapMode
(*args, **kwargs)
return _stc.StyledTextCtrl_GetPrintWrapMode(*args, **kwargs)
GetPrintWrapMode(self) -> int Is printing line wrapped?
GetPrintWrapMode(self) -> int
[ "GetPrintWrapMode", "(", "self", ")", "-", ">", "int" ]
def GetPrintWrapMode(*args, **kwargs): """ GetPrintWrapMode(self) -> int Is printing line wrapped? """ return _stc.StyledTextCtrl_GetPrintWrapMode(*args, **kwargs)
[ "def", "GetPrintWrapMode", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_GetPrintWrapMode", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L5208-L5214
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/pyfakefs/pyfakefs/fake_tempfile.py
python
FakeTempfileModule.NamedTemporaryFile
(self, mode='w+b', bufsize=-1, suffix='', prefix=None, dir=None, delete=True)
return obj
Return a file-like object with name that is deleted on close(). Python 2.4.1 tempfile.NamedTemporaryFile.__doc__ = >This function operates exactly as TemporaryFile() does, except that >the file is guaranteed to have a visible name in the file system. That >name can be retrieved from the name member of the file object. Args: mode: optional string, see above bufsize: optional int, see above suffix: optional string, see above prefix: optional string, see above dir: optional string, see above delete: optional bool, see above Returns: a file-like object including obj.name
Return a file-like object with name that is deleted on close().
[ "Return", "a", "file", "-", "like", "object", "with", "name", "that", "is", "deleted", "on", "close", "()", "." ]
def NamedTemporaryFile(self, mode='w+b', bufsize=-1, suffix='', prefix=None, dir=None, delete=True): """Return a file-like object with name that is deleted on close(). Python 2.4.1 tempfile.NamedTemporaryFile.__doc__ = >This function operates exactly as TemporaryFile() does, except that >the file is guaranteed to have a visible name in the file system. That >name can be retrieved from the name member of the file object. Args: mode: optional string, see above bufsize: optional int, see above suffix: optional string, see above prefix: optional string, see above dir: optional string, see above delete: optional bool, see above Returns: a file-like object including obj.name """ # pylint: disable-msg=C6002 # TODO: bufsiz unused? temp = self.mkstemp(suffix=suffix, prefix=prefix, dir=dir) filename = temp[1] mock_open = fake_filesystem.FakeFileOpen( self._filesystem, delete_on_close=delete) obj = mock_open(filename, mode) obj.name = filename return obj
[ "def", "NamedTemporaryFile", "(", "self", ",", "mode", "=", "'w+b'", ",", "bufsize", "=", "-", "1", ",", "suffix", "=", "''", ",", "prefix", "=", "None", ",", "dir", "=", "None", ",", "delete", "=", "True", ")", ":", "# pylint: disable-msg=C6002", "# T...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/pyfakefs/pyfakefs/fake_tempfile.py#L123-L150
taichi-dev/taichi
973c04d6ba40f34e9e3bd5a28ae0ee0802f136a6
python/taichi/ui/gui.py
python
hex_to_rgb
(color)
return r / 255, g / 255, b / 255
Convert hex color format to rgb color format. Args: color (int): The hex representation of color. Returns: The rgb representation of color.
Convert hex color format to rgb color format.
[ "Convert", "hex", "color", "format", "to", "rgb", "color", "format", "." ]
def hex_to_rgb(color): """Convert hex color format to rgb color format. Args: color (int): The hex representation of color. Returns: The rgb representation of color. """ r, g, b = (color >> 16) & 0xff, (color >> 8) & 0xff, color & 0xff return r / 255, g / 255, b / 255
[ "def", "hex_to_rgb", "(", "color", ")", ":", "r", ",", "g", ",", "b", "=", "(", "color", ">>", "16", ")", "&", "0xff", ",", "(", "color", ">>", "8", ")", "&", "0xff", ",", "color", "&", "0xff", "return", "r", "/", "255", ",", "g", "/", "255...
https://github.com/taichi-dev/taichi/blob/973c04d6ba40f34e9e3bd5a28ae0ee0802f136a6/python/taichi/ui/gui.py#L866-L877
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
gpu/command_buffer/build_gles2_cmd_buffer.py
python
DELnHandler.WriteImmediateCmdHelper
(self, func, file)
Overrriden from TypeHandler.
Overrriden from TypeHandler.
[ "Overrriden", "from", "TypeHandler", "." ]
def WriteImmediateCmdHelper(self, func, file): """Overrriden from TypeHandler.""" code = """ void %(name)s(%(typed_args)s) { const uint32 size = gles2::%(name)s::ComputeSize(n); gles2::%(name)s* c = GetImmediateCmdSpaceTotalSize<gles2::%(name)s>(size); if (c) { c->Init(%(args)s); } } """ file.Write(code % { "name": func.name, "typed_args": func.MakeTypedOriginalArgString(""), "args": func.MakeOriginalArgString(""), })
[ "def", "WriteImmediateCmdHelper", "(", "self", ",", "func", ",", "file", ")", ":", "code", "=", "\"\"\" void %(name)s(%(typed_args)s) {\n const uint32 size = gles2::%(name)s::ComputeSize(n);\n gles2::%(name)s* c =\n GetImmediateCmdSpaceTotalSize<gles2::%(name)s>(size);\n if ...
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/gpu/command_buffer/build_gles2_cmd_buffer.py#L3292-L3308
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/keras/_impl/keras/backend.py
python
min
(x, axis=None, keepdims=False)
return math_ops.reduce_min(x, axis=axis, keep_dims=keepdims)
Minimum value in a tensor. Arguments: x: A tensor or variable. axis: An integer, the axis to find minimum values. keepdims: A boolean, whether to keep the dimensions or not. If `keepdims` is `False`, the rank of the tensor is reduced by 1. If `keepdims` is `True`, the reduced dimension is retained with length 1. Returns: A tensor with miminum values of `x`.
Minimum value in a tensor.
[ "Minimum", "value", "in", "a", "tensor", "." ]
def min(x, axis=None, keepdims=False): """Minimum value in a tensor. Arguments: x: A tensor or variable. axis: An integer, the axis to find minimum values. keepdims: A boolean, whether to keep the dimensions or not. If `keepdims` is `False`, the rank of the tensor is reduced by 1. If `keepdims` is `True`, the reduced dimension is retained with length 1. Returns: A tensor with miminum values of `x`. """ return math_ops.reduce_min(x, axis=axis, keep_dims=keepdims)
[ "def", "min", "(", "x", ",", "axis", "=", "None", ",", "keepdims", "=", "False", ")", ":", "return", "math_ops", ".", "reduce_min", "(", "x", ",", "axis", "=", "axis", ",", "keep_dims", "=", "keepdims", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/keras/_impl/keras/backend.py#L1374-L1388
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/propgrid.py
python
PropertyGrid.GetSortFunction
(*args, **kwargs)
return _propgrid.PropertyGrid_GetSortFunction(*args, **kwargs)
GetSortFunction(self) -> PGSortCallback
GetSortFunction(self) -> PGSortCallback
[ "GetSortFunction", "(", "self", ")", "-", ">", "PGSortCallback" ]
def GetSortFunction(*args, **kwargs): """GetSortFunction(self) -> PGSortCallback""" return _propgrid.PropertyGrid_GetSortFunction(*args, **kwargs)
[ "def", "GetSortFunction", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PropertyGrid_GetSortFunction", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L2283-L2285
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/debug/cli/curses_ui.py
python
CursesUI._screen_terminate
(self)
Terminate the curses screen.
Terminate the curses screen.
[ "Terminate", "the", "curses", "screen", "." ]
def _screen_terminate(self): """Terminate the curses screen.""" self._stdscr.keypad(0) curses.nocbreak() curses.echo() curses.endwin() try: # Remove SIGINT handler. signal.signal(signal.SIGINT, signal.SIG_DFL) except ValueError: # Can't catch signals unless you're the main thread. pass
[ "def", "_screen_terminate", "(", "self", ")", ":", "self", ".", "_stdscr", ".", "keypad", "(", "0", ")", "curses", ".", "nocbreak", "(", ")", "curses", ".", "echo", "(", ")", "curses", ".", "endwin", "(", ")", "try", ":", "# Remove SIGINT handler.", "s...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/debug/cli/curses_ui.py#L465-L478
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/bz2.py
python
decompress
(data)
return b"".join(results)
Decompress a block of data. For incremental decompression, use a BZ2Decompressor object instead.
Decompress a block of data.
[ "Decompress", "a", "block", "of", "data", "." ]
def decompress(data): """Decompress a block of data. For incremental decompression, use a BZ2Decompressor object instead. """ results = [] while data: decomp = BZ2Decompressor() try: res = decomp.decompress(data) except OSError: if results: break # Leftover data is not a valid bzip2 stream; ignore it. else: raise # Error on the first iteration; bail out. results.append(res) if not decomp.eof: raise ValueError("Compressed data ended before the " "end-of-stream marker was reached") data = decomp.unused_data return b"".join(results)
[ "def", "decompress", "(", "data", ")", ":", "results", "=", "[", "]", "while", "data", ":", "decomp", "=", "BZ2Decompressor", "(", ")", "try", ":", "res", "=", "decomp", ".", "decompress", "(", "data", ")", "except", "OSError", ":", "if", "results", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/bz2.py#L338-L358
pgRouting/osm2pgrouting
8491929fc4037d308f271e84d59bb96da3c28aa2
tools/cpplint.py
python
NestingState.InExternC
(self)
return self.stack and isinstance(self.stack[-1], _ExternCInfo)
Check if we are currently one level inside an 'extern "C"' block. Returns: True if top of the stack is an extern block, False otherwise.
Check if we are currently one level inside an 'extern "C"' block.
[ "Check", "if", "we", "are", "currently", "one", "level", "inside", "an", "extern", "C", "block", "." ]
def InExternC(self): """Check if we are currently one level inside an 'extern "C"' block. Returns: True if top of the stack is an extern block, False otherwise. """ return self.stack and isinstance(self.stack[-1], _ExternCInfo)
[ "def", "InExternC", "(", "self", ")", ":", "return", "self", ".", "stack", "and", "isinstance", "(", "self", ".", "stack", "[", "-", "1", "]", ",", "_ExternCInfo", ")" ]
https://github.com/pgRouting/osm2pgrouting/blob/8491929fc4037d308f271e84d59bb96da3c28aa2/tools/cpplint.py#L2240-L2246
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/bintrees/bintrees/treemixin.py
python
TreeMixin.prev_item
(self, key)
return walker.prev_item(key)
Get predecessor (k,v) pair of key, raises KeyError if key is min key or key does not exist.
Get predecessor (k,v) pair of key, raises KeyError if key is min key or key does not exist.
[ "Get", "predecessor", "(", "k", "v", ")", "pair", "of", "key", "raises", "KeyError", "if", "key", "is", "min", "key", "or", "key", "does", "not", "exist", "." ]
def prev_item(self, key): """ Get predecessor (k,v) pair of key, raises KeyError if key is min key or key does not exist. """ if self.count == 0: raise KeyError("Tree is empty") walker = self.get_walker() return walker.prev_item(key)
[ "def", "prev_item", "(", "self", ",", "key", ")", ":", "if", "self", ".", "count", "==", "0", ":", "raise", "KeyError", "(", "\"Tree is empty\"", ")", "walker", "=", "self", ".", "get_walker", "(", ")", "return", "walker", ".", "prev_item", "(", "key",...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/bintrees/bintrees/treemixin.py#L487-L494
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_op_impl/_custom_op/correction_mul_grad.py
python
_correction_mul_grad_tbe
()
return
CorrectionMulGrad TBE register
CorrectionMulGrad TBE register
[ "CorrectionMulGrad", "TBE", "register" ]
def _correction_mul_grad_tbe(): """CorrectionMulGrad TBE register""" return
[ "def", "_correction_mul_grad_tbe", "(", ")", ":", "return" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/_custom_op/correction_mul_grad.py#L46-L48
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/compiler/tf2xla/python/xla.py
python
_shift_right_arithmetic_helper
(x, y, name=None)
return output
Performs an integer right arithmetic shift irrespective of input type.
Performs an integer right arithmetic shift irrespective of input type.
[ "Performs", "an", "integer", "right", "arithmetic", "shift", "irrespective", "of", "input", "type", "." ]
def _shift_right_arithmetic_helper(x, y, name=None): """Performs an integer right arithmetic shift irrespective of input type.""" assert y.dtype == x.dtype dtype = x.dtype unsigned = dtype in _UNSIGNED_TO_SIGNED_TABLE if unsigned: signed_dtype = _UNSIGNED_TO_SIGNED_TABLE[dtype] x = math_ops.cast(x, signed_dtype) y = math_ops.cast(y, signed_dtype) output = bitwise_ops.right_shift(x, y, name=name) if unsigned: output = math_ops.cast(output, dtype) return output
[ "def", "_shift_right_arithmetic_helper", "(", "x", ",", "y", ",", "name", "=", "None", ")", ":", "assert", "y", ".", "dtype", "==", "x", ".", "dtype", "dtype", "=", "x", ".", "dtype", "unsigned", "=", "dtype", "in", "_UNSIGNED_TO_SIGNED_TABLE", "if", "un...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/compiler/tf2xla/python/xla.py#L159-L171
openmm/openmm
cb293447c4fc8b03976dfe11399f107bab70f3d9
wrappers/python/openmm/app/amberinpcrdfile.py
python
AmberInpcrdFile.getVelocities
(self, asNumpy=False)
return self.velocities
Get the atomic velocities. Parameters ---------- asNumpy : bool=False if true, the vectors are returned as numpy arrays instead of Vec3s
Get the atomic velocities.
[ "Get", "the", "atomic", "velocities", "." ]
def getVelocities(self, asNumpy=False): """Get the atomic velocities. Parameters ---------- asNumpy : bool=False if true, the vectors are returned as numpy arrays instead of Vec3s """ if self.velocities is None: raise AttributeError('velocities not found in %s' % self.file) if asNumpy: if self._numpyVelocities is None: self._numpyVelocities = Quantity(np.array(self.velocities.value_in_unit(nanometers/picoseconds)), nanometers/picoseconds) return self._numpyVelocities return self.velocities
[ "def", "getVelocities", "(", "self", ",", "asNumpy", "=", "False", ")", ":", "if", "self", ".", "velocities", "is", "None", ":", "raise", "AttributeError", "(", "'velocities not found in %s'", "%", "self", ".", "file", ")", "if", "asNumpy", ":", "if", "sel...
https://github.com/openmm/openmm/blob/cb293447c4fc8b03976dfe11399f107bab70f3d9/wrappers/python/openmm/app/amberinpcrdfile.py#L105-L119
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Code/Tools/waf-1.7.13/waflib/Tools/fc.py
python
fc.scan
(self)
return (tmp.nodes, tmp.names)
scanner for fortran dependencies
scanner for fortran dependencies
[ "scanner", "for", "fortran", "dependencies" ]
def scan(self): """scanner for fortran dependencies""" tmp = fc_scan.fortran_parser(self.generator.includes_nodes) tmp.task = self tmp.start(self.inputs[0]) if Logs.verbose: Logs.debug('deps: deps for %r: %r; unresolved %r' % (self.inputs, tmp.nodes, tmp.names)) return (tmp.nodes, tmp.names)
[ "def", "scan", "(", "self", ")", ":", "tmp", "=", "fc_scan", ".", "fortran_parser", "(", "self", ".", "generator", ".", "includes_nodes", ")", "tmp", ".", "task", "=", "self", "tmp", ".", "start", "(", "self", ".", "inputs", "[", "0", "]", ")", "if...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/Tools/fc.py#L62-L69
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBFunction.GetDisplayName
(self)
return _lldb.SBFunction_GetDisplayName(self)
GetDisplayName(self) -> str
GetDisplayName(self) -> str
[ "GetDisplayName", "(", "self", ")", "-", ">", "str" ]
def GetDisplayName(self): """GetDisplayName(self) -> str""" return _lldb.SBFunction_GetDisplayName(self)
[ "def", "GetDisplayName", "(", "self", ")", ":", "return", "_lldb", ".", "SBFunction_GetDisplayName", "(", "self", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L4936-L4938
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/python_gflags/gflags.py
python
FlagValues.AddValidator
(self, validator)
Register new flags validator to be checked. Args: validator: gflags_validators.Validator Raises: AttributeError: if validators work with a non-existing flag.
Register new flags validator to be checked.
[ "Register", "new", "flags", "validator", "to", "be", "checked", "." ]
def AddValidator(self, validator): """Register new flags validator to be checked. Args: validator: gflags_validators.Validator Raises: AttributeError: if validators work with a non-existing flag. """ for flag_name in validator.GetFlagsNames(): flag = self.FlagDict()[flag_name] flag.validators.append(validator)
[ "def", "AddValidator", "(", "self", ",", "validator", ")", ":", "for", "flag_name", "in", "validator", ".", "GetFlagsNames", "(", ")", ":", "flag", "=", "self", ".", "FlagDict", "(", ")", "[", "flag_name", "]", "flag", ".", "validators", ".", "append", ...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/python_gflags/gflags.py#L1748-L1758
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/closure_linter/closure_linter/requireprovidesorter.py
python
RequireProvideSorter.CheckRequires
(self, token)
return None
Checks alphabetization of goog.require statements. Iterates over tokens in given token stream, identifies goog.require tokens, and checks that they occur in alphabetical order by the dependency being required. Args: token: A token in the token stream before any goog.require tokens. Returns: A tuple containing the first require token in the token stream and a list of required dependencies sorted alphabetically. For example: (JavaScriptToken, ['object.a', 'object.b', ...]) None is returned if all goog.require statements are already sorted.
Checks alphabetization of goog.require statements.
[ "Checks", "alphabetization", "of", "goog", ".", "require", "statements", "." ]
def CheckRequires(self, token): """Checks alphabetization of goog.require statements. Iterates over tokens in given token stream, identifies goog.require tokens, and checks that they occur in alphabetical order by the dependency being required. Args: token: A token in the token stream before any goog.require tokens. Returns: A tuple containing the first require token in the token stream and a list of required dependencies sorted alphabetically. For example: (JavaScriptToken, ['object.a', 'object.b', ...]) None is returned if all goog.require statements are already sorted. """ require_tokens = self._GetRequireOrProvideTokens(token, 'goog.require') require_strings = self._GetRequireOrProvideTokenStrings(require_tokens) sorted_require_strings = sorted(require_strings) if require_strings != sorted_require_strings: return (require_tokens[0], sorted_require_strings) return None
[ "def", "CheckRequires", "(", "self", ",", "token", ")", ":", "require_tokens", "=", "self", ".", "_GetRequireOrProvideTokens", "(", "token", ",", "'goog.require'", ")", "require_strings", "=", "self", ".", "_GetRequireOrProvideTokenStrings", "(", "require_tokens", "...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/closure_linter/closure_linter/requireprovidesorter.py#L71-L94
Z3Prover/z3
d745d03afdfdf638d66093e2bfbacaf87187f35b
src/api/python/z3/z3.py
python
SortRef.__eq__
(self, other)
return Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast)
Return `True` if `self` and `other` are the same Z3 sort. >>> p = Bool('p') >>> p.sort() == BoolSort() True >>> p.sort() == IntSort() False
Return `True` if `self` and `other` are the same Z3 sort.
[ "Return", "True", "if", "self", "and", "other", "are", "the", "same", "Z3", "sort", "." ]
def __eq__(self, other): """Return `True` if `self` and `other` are the same Z3 sort. >>> p = Bool('p') >>> p.sort() == BoolSort() True >>> p.sort() == IntSort() False """ if other is None: return False return Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast)
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "if", "other", "is", "None", ":", "return", "False", "return", "Z3_is_eq_sort", "(", "self", ".", "ctx_ref", "(", ")", ",", "self", ".", "ast", ",", "other", ".", "ast", ")" ]
https://github.com/Z3Prover/z3/blob/d745d03afdfdf638d66093e2bfbacaf87187f35b/src/api/python/z3/z3.py#L617-L628
GrammaTech/gtirb
415dd72e1e3c475004d013723c16cdcb29c0826e
python/gtirb/ir.py
python
IR.byte_intervals
(self)
return itertools.chain.from_iterable( m.byte_intervals for m in self.modules )
The :class:`ByteInterval`\\s in this IR.
The :class:`ByteInterval`\\s in this IR.
[ "The", ":", "class", ":", "ByteInterval", "\\\\", "s", "in", "this", "IR", "." ]
def byte_intervals(self) -> typing.Iterator[ByteInterval]: """The :class:`ByteInterval`\\s in this IR.""" return itertools.chain.from_iterable( m.byte_intervals for m in self.modules )
[ "def", "byte_intervals", "(", "self", ")", "->", "typing", ".", "Iterator", "[", "ByteInterval", "]", ":", "return", "itertools", ".", "chain", ".", "from_iterable", "(", "m", ".", "byte_intervals", "for", "m", "in", "self", ".", "modules", ")" ]
https://github.com/GrammaTech/gtirb/blob/415dd72e1e3c475004d013723c16cdcb29c0826e/python/gtirb/ir.py#L210-L215
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/ipaddress.py
python
ip_interface
(address)
Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Interface or IPv6Interface object. Raises: ValueError: if the string passed isn't either a v4 or a v6 address. Notes: The IPv?Interface classes describe an Address on a particular Network, so they're basically a combination of both the Address and Network classes.
Take an IP string/int and return an object of the correct type.
[ "Take", "an", "IP", "string", "/", "int", "and", "return", "an", "object", "of", "the", "correct", "type", "." ]
def ip_interface(address): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Interface or IPv6Interface object. Raises: ValueError: if the string passed isn't either a v4 or a v6 address. Notes: The IPv?Interface classes describe an Address on a particular Network, so they're basically a combination of both the Address and Network classes. """ try: return IPv4Interface(address) except (AddressValueError, NetmaskValueError): pass try: return IPv6Interface(address) except (AddressValueError, NetmaskValueError): pass raise ValueError('%r does not appear to be an IPv4 or IPv6 interface' % address)
[ "def", "ip_interface", "(", "address", ")", ":", "try", ":", "return", "IPv4Interface", "(", "address", ")", "except", "(", "AddressValueError", ",", "NetmaskValueError", ")", ":", "pass", "try", ":", "return", "IPv6Interface", "(", "address", ")", "except", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/ipaddress.py#L87-L119
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py2/pkg_resources/_vendor/pyparsing.py
python
ParserElement.setDebug
( self, flag=True )
return self
Enable display of debugging messages while doing pattern matching. Set C{flag} to True to enable, False to disable. Example:: wd = Word(alphas).setName("alphaword") integer = Word(nums).setName("numword") term = wd | integer # turn on debugging for wd wd.setDebug() OneOrMore(term).parseString("abc 123 xyz 890") prints:: Match alphaword at loc 0(1,1) Matched alphaword -> ['abc'] Match alphaword at loc 3(1,4) Exception raised:Expected alphaword (at char 4), (line:1, col:5) Match alphaword at loc 7(1,8) Matched alphaword -> ['xyz'] Match alphaword at loc 11(1,12) Exception raised:Expected alphaword (at char 12), (line:1, col:13) Match alphaword at loc 15(1,16) Exception raised:Expected alphaword (at char 15), (line:1, col:16) The output shown is that produced by the default debug actions - custom debug actions can be specified using L{setDebugActions}. Prior to attempting to match the C{wd} expression, the debugging message C{"Match <exprname> at loc <n>(<line>,<col>)"} is shown. Then if the parse succeeds, a C{"Matched"} message is shown, or an C{"Exception raised"} message is shown. Also note the use of L{setName} to assign a human-readable name to the expression, which makes debugging and exception messages easier to understand - for instance, the default name created for the C{Word} expression without calling C{setName} is C{"W:(ABCD...)"}.
Enable display of debugging messages while doing pattern matching. Set C{flag} to True to enable, False to disable.
[ "Enable", "display", "of", "debugging", "messages", "while", "doing", "pattern", "matching", ".", "Set", "C", "{", "flag", "}", "to", "True", "to", "enable", "False", "to", "disable", "." ]
def setDebug( self, flag=True ): """ Enable display of debugging messages while doing pattern matching. Set C{flag} to True to enable, False to disable. Example:: wd = Word(alphas).setName("alphaword") integer = Word(nums).setName("numword") term = wd | integer # turn on debugging for wd wd.setDebug() OneOrMore(term).parseString("abc 123 xyz 890") prints:: Match alphaword at loc 0(1,1) Matched alphaword -> ['abc'] Match alphaword at loc 3(1,4) Exception raised:Expected alphaword (at char 4), (line:1, col:5) Match alphaword at loc 7(1,8) Matched alphaword -> ['xyz'] Match alphaword at loc 11(1,12) Exception raised:Expected alphaword (at char 12), (line:1, col:13) Match alphaword at loc 15(1,16) Exception raised:Expected alphaword (at char 15), (line:1, col:16) The output shown is that produced by the default debug actions - custom debug actions can be specified using L{setDebugActions}. Prior to attempting to match the C{wd} expression, the debugging message C{"Match <exprname> at loc <n>(<line>,<col>)"} is shown. Then if the parse succeeds, a C{"Matched"} message is shown, or an C{"Exception raised"} message is shown. Also note the use of L{setName} to assign a human-readable name to the expression, which makes debugging and exception messages easier to understand - for instance, the default name created for the C{Word} expression without calling C{setName} is C{"W:(ABCD...)"}. """ if flag: self.setDebugActions( _defaultStartDebugAction, _defaultSuccessDebugAction, _defaultExceptionDebugAction ) else: self.debug = False return self
[ "def", "setDebug", "(", "self", ",", "flag", "=", "True", ")", ":", "if", "flag", ":", "self", ".", "setDebugActions", "(", "_defaultStartDebugAction", ",", "_defaultSuccessDebugAction", ",", "_defaultExceptionDebugAction", ")", "else", ":", "self", ".", "debug"...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/pkg_resources/_vendor/pyparsing.py#L2112-L2151
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/asyncio/base_events.py
python
BaseEventLoop._make_ssl_transport
( self, rawsock, protocol, sslcontext, waiter=None, *, server_side=False, server_hostname=None, extra=None, server=None, ssl_handshake_timeout=None, call_connection_made=True)
Create SSL transport.
Create SSL transport.
[ "Create", "SSL", "transport", "." ]
def _make_ssl_transport( self, rawsock, protocol, sslcontext, waiter=None, *, server_side=False, server_hostname=None, extra=None, server=None, ssl_handshake_timeout=None, call_connection_made=True): """Create SSL transport.""" raise NotImplementedError
[ "def", "_make_ssl_transport", "(", "self", ",", "rawsock", ",", "protocol", ",", "sslcontext", ",", "waiter", "=", "None", ",", "*", ",", "server_side", "=", "False", ",", "server_hostname", "=", "None", ",", "extra", "=", "None", ",", "server", "=", "No...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/asyncio/base_events.py#L434-L441
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Util/asn1.py
python
DerSetOf.encode
(self)
return DerObject.encode(self)
Return this SET OF DER element, fully encoded as a binary string.
Return this SET OF DER element, fully encoded as a binary string.
[ "Return", "this", "SET", "OF", "DER", "element", "fully", "encoded", "as", "a", "binary", "string", "." ]
def encode(self): """Return this SET OF DER element, fully encoded as a binary string. """ # Elements in the set must be ordered in lexicographic order ordered = [] for item in self._seq: if _is_number(item): bys = DerInteger(item).encode() elif isinstance(item, DerObject): bys = item.encode() else: bys = item ordered.append(bys) ordered.sort() self.payload = b''.join(ordered) return DerObject.encode(self)
[ "def", "encode", "(", "self", ")", ":", "# Elements in the set must be ordered in lexicographic order", "ordered", "=", "[", "]", "for", "item", "in", "self", ".", "_seq", ":", "if", "_is_number", "(", "item", ")", ":", "bys", "=", "DerInteger", "(", "item", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Util/asn1.py#L923-L940
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/internals/managers.py
python
BlockManager.is_consolidated
(self)
return self._is_consolidated
Return True if more than one block with the same dtype
Return True if more than one block with the same dtype
[ "Return", "True", "if", "more", "than", "one", "block", "with", "the", "same", "dtype" ]
def is_consolidated(self): """ Return True if more than one block with the same dtype """ if not self._known_consolidated: self._consolidate_check() return self._is_consolidated
[ "def", "is_consolidated", "(", "self", ")", ":", "if", "not", "self", ".", "_known_consolidated", ":", "self", ".", "_consolidate_check", "(", ")", "return", "self", ".", "_is_consolidated" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/internals/managers.py#L591-L597
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPMS_EMPTY.fromTpm
(buf)
return buf.createObj(TPMS_EMPTY)
Returns new TPMS_EMPTY object constructed from its marshaled representation in the given TpmBuffer buffer
Returns new TPMS_EMPTY object constructed from its marshaled representation in the given TpmBuffer buffer
[ "Returns", "new", "TPMS_EMPTY", "object", "constructed", "from", "its", "marshaled", "representation", "in", "the", "given", "TpmBuffer", "buffer" ]
def fromTpm(buf): """ Returns new TPMS_EMPTY object constructed from its marshaled representation in the given TpmBuffer buffer """ return buf.createObj(TPMS_EMPTY)
[ "def", "fromTpm", "(", "buf", ")", ":", "return", "buf", ".", "createObj", "(", "TPMS_EMPTY", ")" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L3569-L3573
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/setuptools/dist.py
python
Distribution.has_contents_for
(self,package)
Return true if 'exclude_package(package)' would do something
Return true if 'exclude_package(package)' would do something
[ "Return", "true", "if", "exclude_package", "(", "package", ")", "would", "do", "something" ]
def has_contents_for(self,package): """Return true if 'exclude_package(package)' would do something""" pfx = package+'.' for p in self.iter_distribution_names(): if p==package or p.startswith(pfx): return True
[ "def", "has_contents_for", "(", "self", ",", "package", ")", ":", "pfx", "=", "package", "+", "'.'", "for", "p", "in", "self", ".", "iter_distribution_names", "(", ")", ":", "if", "p", "==", "package", "or", "p", ".", "startswith", "(", "pfx", ")", "...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/setuptools/dist.py#L492-L499
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/ribbon/art_aui.py
python
RibbonAUIArtProvider.GetBarTabWidth
(self, dc, wnd, label, bitmap, ideal=None, small_begin_need_separator=None, small_must_have_separator=None, minimum=None)
return ideal, small_begin_need_separator, small_must_have_separator, minimum
Calculate the ideal and minimum width (in pixels) of a tab in a ribbon bar. :param `dc`: A device context to use when one is required for size calculations; :param `wnd`: The window onto which the tab will eventually be drawn; :param `label`: The tab's label (or an empty string if it has none); :param `bitmap`: The tab's icon (or :class:`NullBitmap` if it has none); :param `ideal`: The ideal width (in pixels) of the tab; :param `small_begin_need_separator`: A size less than the size, at which a tab separator should begin to be drawn (i.e. drawn, but still fairly transparent); :param `small_must_have_separator`: A size less than the size, at which a tab separator must be drawn (i.e. drawn at full opacity); :param `minimum`: A size less than the size, and greater than or equal to zero, which is the minimum pixel width for the tab.
Calculate the ideal and minimum width (in pixels) of a tab in a ribbon bar.
[ "Calculate", "the", "ideal", "and", "minimum", "width", "(", "in", "pixels", ")", "of", "a", "tab", "in", "a", "ribbon", "bar", "." ]
def GetBarTabWidth(self, dc, wnd, label, bitmap, ideal=None, small_begin_need_separator=None, small_must_have_separator=None, minimum=None): """ Calculate the ideal and minimum width (in pixels) of a tab in a ribbon bar. :param `dc`: A device context to use when one is required for size calculations; :param `wnd`: The window onto which the tab will eventually be drawn; :param `label`: The tab's label (or an empty string if it has none); :param `bitmap`: The tab's icon (or :class:`NullBitmap` if it has none); :param `ideal`: The ideal width (in pixels) of the tab; :param `small_begin_need_separator`: A size less than the size, at which a tab separator should begin to be drawn (i.e. drawn, but still fairly transparent); :param `small_must_have_separator`: A size less than the size, at which a tab separator must be drawn (i.e. drawn at full opacity); :param `minimum`: A size less than the size, and greater than or equal to zero, which is the minimum pixel width for the tab. """ width = mini = 0 if self._flags & RIBBON_BAR_SHOW_PAGE_LABELS and label.strip(): dc.SetFont(self._tab_active_label_font) width += dc.GetTextExtent(label)[0] mini += min(30, width) # enough for a few chars if bitmap.IsOk(): # gap between label and bitmap width += 4 mini += 2 if self._flags & RIBBON_BAR_SHOW_PAGE_ICONS and bitmap.IsOk(): width += bitmap.GetWidth() mini += bitmap.GetWidth() ideal = width + 16 small_begin_need_separator = mini small_must_have_separator = mini minimum = mini return ideal, small_begin_need_separator, small_must_have_separator, minimum
[ "def", "GetBarTabWidth", "(", "self", ",", "dc", ",", "wnd", ",", "label", ",", "bitmap", ",", "ideal", "=", "None", ",", "small_begin_need_separator", "=", "None", ",", "small_must_have_separator", "=", "None", ",", "minimum", "=", "None", ")", ":", "widt...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ribbon/art_aui.py#L461-L501
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/variables.py
python
Variable._OverloadOperator
(operator)
Defer an operator overload to `ops.Tensor`. We pull the operator out of ops.Tensor dynamically to avoid ordering issues. Args: operator: string. The operator name.
Defer an operator overload to `ops.Tensor`.
[ "Defer", "an", "operator", "overload", "to", "ops", ".", "Tensor", "." ]
def _OverloadOperator(operator): # pylint: disable=invalid-name """Defer an operator overload to `ops.Tensor`. We pull the operator out of ops.Tensor dynamically to avoid ordering issues. Args: operator: string. The operator name. """ def _run_op(a, *args): # pylint: disable=protected-access return getattr(ops.Tensor, operator)(a._AsTensor(), *args) # Propagate __doc__ to wrapper try: _run_op.__doc__ = getattr(ops.Tensor, operator).__doc__ except AttributeError: pass setattr(Variable, operator, _run_op)
[ "def", "_OverloadOperator", "(", "operator", ")", ":", "# pylint: disable=invalid-name", "def", "_run_op", "(", "a", ",", "*", "args", ")", ":", "# pylint: disable=protected-access", "return", "getattr", "(", "ops", ".", "Tensor", ",", "operator", ")", "(", "a",...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/variables.py#L748-L766