nwo stringlengths 5 86 | sha stringlengths 40 40 | path stringlengths 4 189 | language stringclasses 1 value | identifier stringlengths 1 94 | parameters stringlengths 2 4.03k | argument_list stringclasses 1 value | return_statement stringlengths 0 11.5k | docstring stringlengths 1 33.2k | docstring_summary stringlengths 0 5.15k | docstring_tokens list | function stringlengths 34 151k | function_tokens list | url stringlengths 90 278 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/traceback.py | python | TracebackException._load_lines | (self) | Private API. force all lines in the stack to be loaded. | Private API. force all lines in the stack to be loaded. | [
"Private",
"API",
".",
"force",
"all",
"lines",
"in",
"the",
"stack",
"to",
"be",
"loaded",
"."
] | def _load_lines(self):
"""Private API. force all lines in the stack to be loaded."""
for frame in self.stack:
frame.line
if self.__context__:
self.__context__._load_lines()
if self.__cause__:
self.__cause__._load_lines() | [
"def",
"_load_lines",
"(",
"self",
")",
":",
"for",
"frame",
"in",
"self",
".",
"stack",
":",
"frame",
".",
"line",
"if",
"self",
".",
"__context__",
":",
"self",
".",
"__context__",
".",
"_load_lines",
"(",
")",
"if",
"self",
".",
"__cause__",
":",
"self",
".",
"__cause__",
".",
"_load_lines",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/traceback.py#L528-L535 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | third_party/closure_linter/closure_linter/checkerbase.py | python | LintRulesBase.Initialize | (self, checker, limited_doc_checks, is_html) | Initializes to prepare to check a file.
Args:
checker: Class to report errors to.
limited_doc_checks: Whether doc checking is relaxed for this file.
is_html: Whether the file is an HTML file with extracted contents. | Initializes to prepare to check a file. | [
"Initializes",
"to",
"prepare",
"to",
"check",
"a",
"file",
"."
] | def Initialize(self, checker, limited_doc_checks, is_html):
"""Initializes to prepare to check a file.
Args:
checker: Class to report errors to.
limited_doc_checks: Whether doc checking is relaxed for this file.
is_html: Whether the file is an HTML file with extracted contents.
"""
self.__checker = checker
self._limited_doc_checks = limited_doc_checks
self._is_html = is_html | [
"def",
"Initialize",
"(",
"self",
",",
"checker",
",",
"limited_doc_checks",
",",
"is_html",
")",
":",
"self",
".",
"__checker",
"=",
"checker",
"self",
".",
"_limited_doc_checks",
"=",
"limited_doc_checks",
"self",
".",
"_is_html",
"=",
"is_html"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/closure_linter/closure_linter/checkerbase.py#L48-L58 | ||
hfinkel/llvm-project-cxxjit | 91084ef018240bbb8e24235ff5cd8c355a9c1a1e | lldb/utils/vim-lldb/python-vim-lldb/vim_panes.py | python | bufwinnr | (name) | return int(vim.eval("bufwinnr('%s')" % name)) | Returns window number corresponding with buffer name | Returns window number corresponding with buffer name | [
"Returns",
"window",
"number",
"corresponding",
"with",
"buffer",
"name"
] | def bufwinnr(name):
""" Returns window number corresponding with buffer name """
return int(vim.eval("bufwinnr('%s')" % name)) | [
"def",
"bufwinnr",
"(",
"name",
")",
":",
"return",
"int",
"(",
"vim",
".",
"eval",
"(",
"\"bufwinnr('%s')\"",
"%",
"name",
")",
")"
] | https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/lldb/utils/vim-lldb/python-vim-lldb/vim_panes.py#L118-L120 | |
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | DQM/Integration/python/config/FrontierCondition_GT_autoExpress_cfi.py | python | Tier0Handler._queryTier0DataSvc | ( self, url ) | return json.loads( ''.join(stdoutdata).replace( "'", '"').replace(' None', ' "None"') ) | Queries Tier0DataSvc.
url: Tier0DataSvc URL.
@returns: dictionary, from whence the required information must be retrieved according to the API call.
Raises if connection error, bad response, or timeout after retries occur. | Queries Tier0DataSvc.
url: Tier0DataSvc URL. | [
"Queries",
"Tier0DataSvc",
".",
"url",
":",
"Tier0DataSvc",
"URL",
"."
] | def _queryTier0DataSvc( self, url ):
"""
Queries Tier0DataSvc.
url: Tier0DataSvc URL.
@returns: dictionary, from whence the required information must be retrieved according to the API call.
Raises if connection error, bad response, or timeout after retries occur.
"""
userAgent = "User-Agent: DQMIntegration/2.0 python/%d.%d.%d PycURL/%s" % ( sys.version_info[ :3 ] + ( pycurl.version_info()[ 1 ], ) )
proxy = ""
if self._proxy: proxy = ' --proxy %s ' % self._proxy
debug = " -s -S "
if self._debug: debug = " -v "
cmd = '/usr/bin/curl -k -L --user-agent "%s" %s --connect-timeout %i --retry %i %s %s ' % (userAgent, proxy, self._timeOut, self._retries, debug, url)
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdoutdata, stderrdata) = process.communicate()
retcode = process.returncode
if retcode != 0 or stderrdata:
msg = "looks like curl returned an error: retcode=%s" % (retcode,)
msg += ' msg = "'+str(stderrdata)+'"'
raise Tier0Error(msg)
return json.loads( ''.join(stdoutdata).replace( "'", '"').replace(' None', ' "None"') ) | [
"def",
"_queryTier0DataSvc",
"(",
"self",
",",
"url",
")",
":",
"userAgent",
"=",
"\"User-Agent: DQMIntegration/2.0 python/%d.%d.%d PycURL/%s\"",
"%",
"(",
"sys",
".",
"version_info",
"[",
":",
"3",
"]",
"+",
"(",
"pycurl",
".",
"version_info",
"(",
")",
"[",
"1",
"]",
",",
")",
")",
"proxy",
"=",
"\"\"",
"if",
"self",
".",
"_proxy",
":",
"proxy",
"=",
"' --proxy %s '",
"%",
"self",
".",
"_proxy",
"debug",
"=",
"\" -s -S \"",
"if",
"self",
".",
"_debug",
":",
"debug",
"=",
"\" -v \"",
"cmd",
"=",
"'/usr/bin/curl -k -L --user-agent \"%s\" %s --connect-timeout %i --retry %i %s %s '",
"%",
"(",
"userAgent",
",",
"proxy",
",",
"self",
".",
"_timeOut",
",",
"self",
".",
"_retries",
",",
"debug",
",",
"url",
")",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"(",
"stdoutdata",
",",
"stderrdata",
")",
"=",
"process",
".",
"communicate",
"(",
")",
"retcode",
"=",
"process",
".",
"returncode",
"if",
"retcode",
"!=",
"0",
"or",
"stderrdata",
":",
"msg",
"=",
"\"looks like curl returned an error: retcode=%s\"",
"%",
"(",
"retcode",
",",
")",
"msg",
"+=",
"' msg = \"'",
"+",
"str",
"(",
"stderrdata",
")",
"+",
"'\"'",
"raise",
"Tier0Error",
"(",
"msg",
")",
"return",
"json",
".",
"loads",
"(",
"''",
".",
"join",
"(",
"stdoutdata",
")",
".",
"replace",
"(",
"\"'\"",
",",
"'\"'",
")",
".",
"replace",
"(",
"' None'",
",",
"' \"None\"'",
")",
")"
] | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/DQM/Integration/python/config/FrontierCondition_GT_autoExpress_cfi.py#L81-L108 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/docutils/statemachine.py | python | State.add_initial_transitions | (self) | Make and add transitions listed in `self.initial_transitions`. | Make and add transitions listed in `self.initial_transitions`. | [
"Make",
"and",
"add",
"transitions",
"listed",
"in",
"self",
".",
"initial_transitions",
"."
] | def add_initial_transitions(self):
"""Make and add transitions listed in `self.initial_transitions`."""
if self.initial_transitions:
names, transitions = self.make_transitions(
self.initial_transitions)
self.add_transitions(names, transitions) | [
"def",
"add_initial_transitions",
"(",
"self",
")",
":",
"if",
"self",
".",
"initial_transitions",
":",
"names",
",",
"transitions",
"=",
"self",
".",
"make_transitions",
"(",
"self",
".",
"initial_transitions",
")",
"self",
".",
"add_transitions",
"(",
"names",
",",
"transitions",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/statemachine.py#L645-L650 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/ma/core.py | python | masked_inside | (x, v1, v2, copy=True) | return masked_where(condition, x, copy=copy) | Mask an array inside a given interval.
Shortcut to ``masked_where``, where `condition` is True for `x` inside
the interval [v1,v2] (v1 <= x <= v2). The boundaries `v1` and `v2`
can be given in either order.
See Also
--------
masked_where : Mask where a condition is met.
Notes
-----
The array `x` is prefilled with its filling value.
Examples
--------
>>> import numpy.ma as ma
>>> x = [0.31, 1.2, 0.01, 0.2, -0.4, -1.1]
>>> ma.masked_inside(x, -0.3, 0.3)
masked_array(data=[0.31, 1.2, --, --, -0.4, -1.1],
mask=[False, False, True, True, False, False],
fill_value=1e+20)
The order of `v1` and `v2` doesn't matter.
>>> ma.masked_inside(x, 0.3, -0.3)
masked_array(data=[0.31, 1.2, --, --, -0.4, -1.1],
mask=[False, False, True, True, False, False],
fill_value=1e+20) | Mask an array inside a given interval. | [
"Mask",
"an",
"array",
"inside",
"a",
"given",
"interval",
"."
] | def masked_inside(x, v1, v2, copy=True):
"""
Mask an array inside a given interval.
Shortcut to ``masked_where``, where `condition` is True for `x` inside
the interval [v1,v2] (v1 <= x <= v2). The boundaries `v1` and `v2`
can be given in either order.
See Also
--------
masked_where : Mask where a condition is met.
Notes
-----
The array `x` is prefilled with its filling value.
Examples
--------
>>> import numpy.ma as ma
>>> x = [0.31, 1.2, 0.01, 0.2, -0.4, -1.1]
>>> ma.masked_inside(x, -0.3, 0.3)
masked_array(data=[0.31, 1.2, --, --, -0.4, -1.1],
mask=[False, False, True, True, False, False],
fill_value=1e+20)
The order of `v1` and `v2` doesn't matter.
>>> ma.masked_inside(x, 0.3, -0.3)
masked_array(data=[0.31, 1.2, --, --, -0.4, -1.1],
mask=[False, False, True, True, False, False],
fill_value=1e+20)
"""
if v2 < v1:
(v1, v2) = (v2, v1)
xf = filled(x)
condition = (xf >= v1) & (xf <= v2)
return masked_where(condition, x, copy=copy) | [
"def",
"masked_inside",
"(",
"x",
",",
"v1",
",",
"v2",
",",
"copy",
"=",
"True",
")",
":",
"if",
"v2",
"<",
"v1",
":",
"(",
"v1",
",",
"v2",
")",
"=",
"(",
"v2",
",",
"v1",
")",
"xf",
"=",
"filled",
"(",
"x",
")",
"condition",
"=",
"(",
"xf",
">=",
"v1",
")",
"&",
"(",
"xf",
"<=",
"v2",
")",
"return",
"masked_where",
"(",
"condition",
",",
"x",
",",
"copy",
"=",
"copy",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/ma/core.py#L2114-L2151 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/ops/nn_grad.py | python | _BiasAddGradGrad | (op, received_grad) | return array_ops.tile(expanded_grad, tile_mults) | Gradient for the BiasAddGrad op.
Args:
op: BiasAddGrad op for which we are calculating gradients.
received_grad: The gradients passed to the BiasAddGrad op.
Returns:
A single gradient Tensor for the input to BiasAddGrad (which
is the gradient of the bias term in BiasAdd) | Gradient for the BiasAddGrad op. | [
"Gradient",
"for",
"the",
"BiasAddGrad",
"op",
"."
] | def _BiasAddGradGrad(op, received_grad):
"""Gradient for the BiasAddGrad op.
Args:
op: BiasAddGrad op for which we are calculating gradients.
received_grad: The gradients passed to the BiasAddGrad op.
Returns:
A single gradient Tensor for the input to BiasAddGrad (which
is the gradient of the bias term in BiasAdd)
"""
try:
data_format = op.get_attr("data_format")
except ValueError:
data_format = None
shape = array_ops.shape(op.inputs[0])
rank = array_ops.rank(op.inputs[0])
bias_shape = array_ops.shape(received_grad)
if data_format == b"NCHW":
expanded_shape = array_ops.concat(
0,
[array_ops.ones_like(shape[:-3]), bias_shape, array_ops.ones_like(shape[-2:])]
)
tile_mults = array_ops.concat(0, [shape[:-3], [1], shape[-2:]])
else:
expanded_shape = array_ops.concat(0, [array_ops.ones_like(shape[:-1]), bias_shape])
tile_mults = array_ops.concat(0, [shape[:-1], [1]])
expanded_grad = array_ops.reshape(received_grad, expanded_shape)
return array_ops.tile(expanded_grad, tile_mults) | [
"def",
"_BiasAddGradGrad",
"(",
"op",
",",
"received_grad",
")",
":",
"try",
":",
"data_format",
"=",
"op",
".",
"get_attr",
"(",
"\"data_format\"",
")",
"except",
"ValueError",
":",
"data_format",
"=",
"None",
"shape",
"=",
"array_ops",
".",
"shape",
"(",
"op",
".",
"inputs",
"[",
"0",
"]",
")",
"rank",
"=",
"array_ops",
".",
"rank",
"(",
"op",
".",
"inputs",
"[",
"0",
"]",
")",
"bias_shape",
"=",
"array_ops",
".",
"shape",
"(",
"received_grad",
")",
"if",
"data_format",
"==",
"b\"NCHW\"",
":",
"expanded_shape",
"=",
"array_ops",
".",
"concat",
"(",
"0",
",",
"[",
"array_ops",
".",
"ones_like",
"(",
"shape",
"[",
":",
"-",
"3",
"]",
")",
",",
"bias_shape",
",",
"array_ops",
".",
"ones_like",
"(",
"shape",
"[",
"-",
"2",
":",
"]",
")",
"]",
")",
"tile_mults",
"=",
"array_ops",
".",
"concat",
"(",
"0",
",",
"[",
"shape",
"[",
":",
"-",
"3",
"]",
",",
"[",
"1",
"]",
",",
"shape",
"[",
"-",
"2",
":",
"]",
"]",
")",
"else",
":",
"expanded_shape",
"=",
"array_ops",
".",
"concat",
"(",
"0",
",",
"[",
"array_ops",
".",
"ones_like",
"(",
"shape",
"[",
":",
"-",
"1",
"]",
")",
",",
"bias_shape",
"]",
")",
"tile_mults",
"=",
"array_ops",
".",
"concat",
"(",
"0",
",",
"[",
"shape",
"[",
":",
"-",
"1",
"]",
",",
"[",
"1",
"]",
"]",
")",
"expanded_grad",
"=",
"array_ops",
".",
"reshape",
"(",
"received_grad",
",",
"expanded_shape",
")",
"return",
"array_ops",
".",
"tile",
"(",
"expanded_grad",
",",
"tile_mults",
")"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/nn_grad.py#L207-L241 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/network/session.py | python | looks_like_ci | () | return any(name in os.environ for name in CI_ENVIRONMENT_VARIABLES) | Return whether it looks like pip is running under CI. | Return whether it looks like pip is running under CI. | [
"Return",
"whether",
"it",
"looks",
"like",
"pip",
"is",
"running",
"under",
"CI",
"."
] | def looks_like_ci():
# type: () -> bool
"""
Return whether it looks like pip is running under CI.
"""
# We don't use the method of checking for a tty (e.g. using isatty())
# because some CI systems mimic a tty (e.g. Travis CI). Thus that
# method doesn't provide definitive information in either direction.
return any(name in os.environ for name in CI_ENVIRONMENT_VARIABLES) | [
"def",
"looks_like_ci",
"(",
")",
":",
"# type: () -> bool",
"# We don't use the method of checking for a tty (e.g. using isatty())",
"# because some CI systems mimic a tty (e.g. Travis CI). Thus that",
"# method doesn't provide definitive information in either direction.",
"return",
"any",
"(",
"name",
"in",
"os",
".",
"environ",
"for",
"name",
"in",
"CI_ENVIRONMENT_VARIABLES",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/network/session.py#L88-L96 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/tornado/tornado-6/tornado/tcpserver.py | python | TCPServer.stop | (self) | Stops listening for new connections.
Requests currently in progress may still continue after the
server is stopped. | Stops listening for new connections. | [
"Stops",
"listening",
"for",
"new",
"connections",
"."
] | def stop(self) -> None:
"""Stops listening for new connections.
Requests currently in progress may still continue after the
server is stopped.
"""
if self._stopped:
return
self._stopped = True
for fd, sock in self._sockets.items():
assert sock.fileno() == fd
# Unregister socket from IOLoop
self._handlers.pop(fd)()
sock.close() | [
"def",
"stop",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"_stopped",
":",
"return",
"self",
".",
"_stopped",
"=",
"True",
"for",
"fd",
",",
"sock",
"in",
"self",
".",
"_sockets",
".",
"items",
"(",
")",
":",
"assert",
"sock",
".",
"fileno",
"(",
")",
"==",
"fd",
"# Unregister socket from IOLoop",
"self",
".",
"_handlers",
".",
"pop",
"(",
"fd",
")",
"(",
")",
"sock",
".",
"close",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/tornado/tornado-6/tornado/tcpserver.py#L250-L263 | ||
albertz/openlierox | d316c14a8eb57848ef56e9bfa7b23a56f694a51b | tools/DedicatedServerVideo/gdata/Crypto/PublicKey/pubkey.py | python | pubkey.publickey | (self) | return self | publickey(): object
Return a new key object containing only the public information. | publickey(): object
Return a new key object containing only the public information. | [
"publickey",
"()",
":",
"object",
"Return",
"a",
"new",
"key",
"object",
"containing",
"only",
"the",
"public",
"information",
"."
] | def publickey (self):
"""publickey(): object
Return a new key object containing only the public information.
"""
return self | [
"def",
"publickey",
"(",
"self",
")",
":",
"return",
"self"
] | https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/Crypto/PublicKey/pubkey.py#L162-L166 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py2/IPython/core/interactiveshell.py | python | InteractiveShell.restore_sys_module_state | (self) | Restore the state of the sys module. | Restore the state of the sys module. | [
"Restore",
"the",
"state",
"of",
"the",
"sys",
"module",
"."
] | def restore_sys_module_state(self):
"""Restore the state of the sys module."""
try:
for k, v in iteritems(self._orig_sys_module_state):
setattr(sys, k, v)
except AttributeError:
pass
# Reset what what done in self.init_sys_modules
if self._orig_sys_modules_main_mod is not None:
sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod | [
"def",
"restore_sys_module_state",
"(",
"self",
")",
":",
"try",
":",
"for",
"k",
",",
"v",
"in",
"iteritems",
"(",
"self",
".",
"_orig_sys_module_state",
")",
":",
"setattr",
"(",
"sys",
",",
"k",
",",
"v",
")",
"except",
"AttributeError",
":",
"pass",
"# Reset what what done in self.init_sys_modules",
"if",
"self",
".",
"_orig_sys_modules_main_mod",
"is",
"not",
"None",
":",
"sys",
".",
"modules",
"[",
"self",
".",
"_orig_sys_modules_main_name",
"]",
"=",
"self",
".",
"_orig_sys_modules_main_mod"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/core/interactiveshell.py#L754-L763 | ||
ThePhD/sol2 | 50b62c9346750b7c2c406c9e4c546f96b0bf021d | documentation/source/conf.py | python | generate_doxygen_xml | (app) | Run the doxygen make commands if we're on the ReadTheDocs server | Run the doxygen make commands if we're on the ReadTheDocs server | [
"Run",
"the",
"doxygen",
"make",
"commands",
"if",
"we",
"re",
"on",
"the",
"ReadTheDocs",
"server"
] | def generate_doxygen_xml(app):
"""Run the doxygen make commands if we're on the ReadTheDocs server"""
read_the_docs_build = os.environ.get('READTHEDOCS', None) == 'True'
if read_the_docs_build:
run_cmake_doxygen() | [
"def",
"generate_doxygen_xml",
"(",
"app",
")",
":",
"read_the_docs_build",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'READTHEDOCS'",
",",
"None",
")",
"==",
"'True'",
"if",
"read_the_docs_build",
":",
"run_cmake_doxygen",
"(",
")"
] | https://github.com/ThePhD/sol2/blob/50b62c9346750b7c2c406c9e4c546f96b0bf021d/documentation/source/conf.py#L340-L346 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_gdi.py | python | DC.GetResolution | (*args, **kwargs) | return _gdi_.DC_GetResolution(*args, **kwargs) | GetResolution(self) -> int | GetResolution(self) -> int | [
"GetResolution",
"(",
"self",
")",
"-",
">",
"int"
] | def GetResolution(*args, **kwargs):
"""GetResolution(self) -> int"""
return _gdi_.DC_GetResolution(*args, **kwargs) | [
"def",
"GetResolution",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"DC_GetResolution",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L4207-L4209 | |
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/msvs.py | python | _AddConfigurationToMSVSProject | (p, spec, config_type, config_name, config) | Adds a configuration to the MSVS project.
Many settings in a vcproj file are specific to a configuration. This
function the main part of the vcproj file that's configuration specific.
Arguments:
p: The target project being generated.
spec: The target dictionary containing the properties of the target.
config_type: The configuration type, a number as defined by Microsoft.
config_name: The name of the configuration.
config: The dictionnary that defines the special processing to be done
for this configuration. | Adds a configuration to the MSVS project. | [
"Adds",
"a",
"configuration",
"to",
"the",
"MSVS",
"project",
"."
] | def _AddConfigurationToMSVSProject(p, spec, config_type, config_name, config):
"""Adds a configuration to the MSVS project.
Many settings in a vcproj file are specific to a configuration. This
function the main part of the vcproj file that's configuration specific.
Arguments:
p: The target project being generated.
spec: The target dictionary containing the properties of the target.
config_type: The configuration type, a number as defined by Microsoft.
config_name: The name of the configuration.
config: The dictionnary that defines the special processing to be done
for this configuration.
"""
# Get the information for this configuration
include_dirs, resource_include_dirs = _GetIncludeDirs(config)
libraries = _GetLibraries(spec)
out_file, vc_tool, _ = _GetOutputFilePathAndTool(spec, msbuild=False)
defines = _GetDefines(config)
defines = [_EscapeCppDefineForMSVS(d) for d in defines]
disabled_warnings = _GetDisabledWarnings(config)
prebuild = config.get('msvs_prebuild')
postbuild = config.get('msvs_postbuild')
def_file = _GetModuleDefinition(spec)
precompiled_header = config.get('msvs_precompiled_header')
# Prepare the list of tools as a dictionary.
tools = dict()
# Add in user specified msvs_settings.
msvs_settings = config.get('msvs_settings', {})
MSVSSettings.ValidateMSVSSettings(msvs_settings)
for tool in msvs_settings:
settings = config['msvs_settings'][tool]
for setting in settings:
_ToolAppend(tools, tool, setting, settings[setting])
# Add the information to the appropriate tool
_ToolAppend(tools, 'VCCLCompilerTool',
'AdditionalIncludeDirectories', include_dirs)
_ToolAppend(tools, 'VCResourceCompilerTool',
'AdditionalIncludeDirectories', resource_include_dirs)
# Add in libraries.
_ToolAppend(tools, 'VCLinkerTool', 'AdditionalDependencies', libraries)
if out_file:
_ToolAppend(tools, vc_tool, 'OutputFile', out_file, only_if_unset=True)
# Add defines.
_ToolAppend(tools, 'VCCLCompilerTool', 'PreprocessorDefinitions', defines)
_ToolAppend(tools, 'VCResourceCompilerTool', 'PreprocessorDefinitions',
defines)
# Change program database directory to prevent collisions.
_ToolAppend(tools, 'VCCLCompilerTool', 'ProgramDataBaseFileName',
'$(IntDir)$(ProjectName)\\vc80.pdb', only_if_unset=True)
# Add disabled warnings.
_ToolAppend(tools, 'VCCLCompilerTool',
'DisableSpecificWarnings', disabled_warnings)
# Add Pre-build.
_ToolAppend(tools, 'VCPreBuildEventTool', 'CommandLine', prebuild)
# Add Post-build.
_ToolAppend(tools, 'VCPostBuildEventTool', 'CommandLine', postbuild)
# Turn on precompiled headers if appropriate.
if precompiled_header:
precompiled_header = os.path.split(precompiled_header)[1]
_ToolAppend(tools, 'VCCLCompilerTool', 'UsePrecompiledHeader', '2')
_ToolAppend(tools, 'VCCLCompilerTool',
'PrecompiledHeaderThrough', precompiled_header)
_ToolAppend(tools, 'VCCLCompilerTool',
'ForcedIncludeFiles', precompiled_header)
# Loadable modules don't generate import libraries;
# tell dependent projects to not expect one.
if spec['type'] == 'loadable_module':
_ToolAppend(tools, 'VCLinkerTool', 'IgnoreImportLibrary', 'true')
# Set the module definition file if any.
if def_file:
_ToolAppend(tools, 'VCLinkerTool', 'ModuleDefinitionFile', def_file)
_AddConfigurationToMSVS(p, spec, tools, config, config_type, config_name) | [
"def",
"_AddConfigurationToMSVSProject",
"(",
"p",
",",
"spec",
",",
"config_type",
",",
"config_name",
",",
"config",
")",
":",
"# Get the information for this configuration",
"include_dirs",
",",
"resource_include_dirs",
"=",
"_GetIncludeDirs",
"(",
"config",
")",
"libraries",
"=",
"_GetLibraries",
"(",
"spec",
")",
"out_file",
",",
"vc_tool",
",",
"_",
"=",
"_GetOutputFilePathAndTool",
"(",
"spec",
",",
"msbuild",
"=",
"False",
")",
"defines",
"=",
"_GetDefines",
"(",
"config",
")",
"defines",
"=",
"[",
"_EscapeCppDefineForMSVS",
"(",
"d",
")",
"for",
"d",
"in",
"defines",
"]",
"disabled_warnings",
"=",
"_GetDisabledWarnings",
"(",
"config",
")",
"prebuild",
"=",
"config",
".",
"get",
"(",
"'msvs_prebuild'",
")",
"postbuild",
"=",
"config",
".",
"get",
"(",
"'msvs_postbuild'",
")",
"def_file",
"=",
"_GetModuleDefinition",
"(",
"spec",
")",
"precompiled_header",
"=",
"config",
".",
"get",
"(",
"'msvs_precompiled_header'",
")",
"# Prepare the list of tools as a dictionary.",
"tools",
"=",
"dict",
"(",
")",
"# Add in user specified msvs_settings.",
"msvs_settings",
"=",
"config",
".",
"get",
"(",
"'msvs_settings'",
",",
"{",
"}",
")",
"MSVSSettings",
".",
"ValidateMSVSSettings",
"(",
"msvs_settings",
")",
"for",
"tool",
"in",
"msvs_settings",
":",
"settings",
"=",
"config",
"[",
"'msvs_settings'",
"]",
"[",
"tool",
"]",
"for",
"setting",
"in",
"settings",
":",
"_ToolAppend",
"(",
"tools",
",",
"tool",
",",
"setting",
",",
"settings",
"[",
"setting",
"]",
")",
"# Add the information to the appropriate tool",
"_ToolAppend",
"(",
"tools",
",",
"'VCCLCompilerTool'",
",",
"'AdditionalIncludeDirectories'",
",",
"include_dirs",
")",
"_ToolAppend",
"(",
"tools",
",",
"'VCResourceCompilerTool'",
",",
"'AdditionalIncludeDirectories'",
",",
"resource_include_dirs",
")",
"# Add in libraries.",
"_ToolAppend",
"(",
"tools",
",",
"'VCLinkerTool'",
",",
"'AdditionalDependencies'",
",",
"libraries",
")",
"if",
"out_file",
":",
"_ToolAppend",
"(",
"tools",
",",
"vc_tool",
",",
"'OutputFile'",
",",
"out_file",
",",
"only_if_unset",
"=",
"True",
")",
"# Add defines.",
"_ToolAppend",
"(",
"tools",
",",
"'VCCLCompilerTool'",
",",
"'PreprocessorDefinitions'",
",",
"defines",
")",
"_ToolAppend",
"(",
"tools",
",",
"'VCResourceCompilerTool'",
",",
"'PreprocessorDefinitions'",
",",
"defines",
")",
"# Change program database directory to prevent collisions.",
"_ToolAppend",
"(",
"tools",
",",
"'VCCLCompilerTool'",
",",
"'ProgramDataBaseFileName'",
",",
"'$(IntDir)$(ProjectName)\\\\vc80.pdb'",
",",
"only_if_unset",
"=",
"True",
")",
"# Add disabled warnings.",
"_ToolAppend",
"(",
"tools",
",",
"'VCCLCompilerTool'",
",",
"'DisableSpecificWarnings'",
",",
"disabled_warnings",
")",
"# Add Pre-build.",
"_ToolAppend",
"(",
"tools",
",",
"'VCPreBuildEventTool'",
",",
"'CommandLine'",
",",
"prebuild",
")",
"# Add Post-build.",
"_ToolAppend",
"(",
"tools",
",",
"'VCPostBuildEventTool'",
",",
"'CommandLine'",
",",
"postbuild",
")",
"# Turn on precompiled headers if appropriate.",
"if",
"precompiled_header",
":",
"precompiled_header",
"=",
"os",
".",
"path",
".",
"split",
"(",
"precompiled_header",
")",
"[",
"1",
"]",
"_ToolAppend",
"(",
"tools",
",",
"'VCCLCompilerTool'",
",",
"'UsePrecompiledHeader'",
",",
"'2'",
")",
"_ToolAppend",
"(",
"tools",
",",
"'VCCLCompilerTool'",
",",
"'PrecompiledHeaderThrough'",
",",
"precompiled_header",
")",
"_ToolAppend",
"(",
"tools",
",",
"'VCCLCompilerTool'",
",",
"'ForcedIncludeFiles'",
",",
"precompiled_header",
")",
"# Loadable modules don't generate import libraries;",
"# tell dependent projects to not expect one.",
"if",
"spec",
"[",
"'type'",
"]",
"==",
"'loadable_module'",
":",
"_ToolAppend",
"(",
"tools",
",",
"'VCLinkerTool'",
",",
"'IgnoreImportLibrary'",
",",
"'true'",
")",
"# Set the module definition file if any.",
"if",
"def_file",
":",
"_ToolAppend",
"(",
"tools",
",",
"'VCLinkerTool'",
",",
"'ModuleDefinitionFile'",
",",
"def_file",
")",
"_AddConfigurationToMSVS",
"(",
"p",
",",
"spec",
",",
"tools",
",",
"config",
",",
"config_type",
",",
"config_name",
")"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/msvs.py#L1013-L1087 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py | python | Misc.winfo_fpixels | (self, number) | return self.tk.getdouble(self.tk.call(
'winfo', 'fpixels', self._w, number)) | Return the number of pixels for the given distance NUMBER
(e.g. "3c") as float. | Return the number of pixels for the given distance NUMBER
(e.g. "3c") as float. | [
"Return",
"the",
"number",
"of",
"pixels",
"for",
"the",
"given",
"distance",
"NUMBER",
"(",
"e",
".",
"g",
".",
"3c",
")",
"as",
"float",
"."
] | def winfo_fpixels(self, number):
"""Return the number of pixels for the given distance NUMBER
(e.g. "3c") as float."""
return self.tk.getdouble(self.tk.call(
'winfo', 'fpixels', self._w, number)) | [
"def",
"winfo_fpixels",
"(",
"self",
",",
"number",
")",
":",
"return",
"self",
".",
"tk",
".",
"getdouble",
"(",
"self",
".",
"tk",
".",
"call",
"(",
"'winfo'",
",",
"'fpixels'",
",",
"self",
".",
"_w",
",",
"number",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py#L989-L993 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/dataview.py | python | DataViewRenderer.GetVariantType | (*args, **kwargs) | return _dataview.DataViewRenderer_GetVariantType(*args, **kwargs) | GetVariantType(self) -> String | GetVariantType(self) -> String | [
"GetVariantType",
"(",
"self",
")",
"-",
">",
"String"
] | def GetVariantType(*args, **kwargs):
"""GetVariantType(self) -> String"""
return _dataview.DataViewRenderer_GetVariantType(*args, **kwargs) | [
"def",
"GetVariantType",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewRenderer_GetVariantType",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/dataview.py#L1160-L1162 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/richtext.py | python | RichTextBuffer.BeginFontSize | (*args, **kwargs) | return _richtext.RichTextBuffer_BeginFontSize(*args, **kwargs) | BeginFontSize(self, int pointSize) -> bool | BeginFontSize(self, int pointSize) -> bool | [
"BeginFontSize",
"(",
"self",
"int",
"pointSize",
")",
"-",
">",
"bool"
] | def BeginFontSize(*args, **kwargs):
"""BeginFontSize(self, int pointSize) -> bool"""
return _richtext.RichTextBuffer_BeginFontSize(*args, **kwargs) | [
"def",
"BeginFontSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextBuffer_BeginFontSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L2357-L2359 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/grid.py | python | GridEditorCreatedEvent.SetControl | (*args, **kwargs) | return _grid.GridEditorCreatedEvent_SetControl(*args, **kwargs) | SetControl(self, Control ctrl) | SetControl(self, Control ctrl) | [
"SetControl",
"(",
"self",
"Control",
"ctrl",
")"
] | def SetControl(*args, **kwargs):
"""SetControl(self, Control ctrl)"""
return _grid.GridEditorCreatedEvent_SetControl(*args, **kwargs) | [
"def",
"SetControl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"GridEditorCreatedEvent_SetControl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/grid.py#L2487-L2489 | |
SmileiPIC/Smilei | 07dcb51200029e10f626e1546558c1ae7599c8b1 | validation/plot_logs.py | python | switchPlots.on_pick | (self,event) | This method is used to make markers pickable. | This method is used to make markers pickable. | [
"This",
"method",
"is",
"used",
"to",
"make",
"markers",
"pickable",
"."
] | def on_pick(self,event):
"""
This method is used to make markers pickable.
"""
if self.plottype == "summary":
pass
elif self.plottype == "benchmark":
marker_indexes = event.ind
print("\n Selected points: {}".format(marker_indexes))
D = self.data[self.ind]
for k in marker_indexes:
print(" > Commit: {}".format(D["commits"][k]))
print(" Branch: {}".format(D["branches"][k]))
print(" Date: {}".format(D["date"][k]))
print(" Link: https://llrgit.in2p3.fr/smilei/smilei/-/commit/{}".format(D["commit_ids"][k]))
print(" ----------------------------------------------------------------------")
print(" Timers | Times (s) | Min (s) | Mean (s) | Max (s) |")
print(" ----------------------------------------------------------------------")
for label, d, min, mean, max in zip(
D["labels"]+["Total"],
D["processed_data"]+[D["time_in_timeloop"]],
D["min_times"],
D["mean_times"],
D["max_times"]
):
print(" {0:15} | {1:.4e} | {2:.4e} | {3:.4e} | {4:.4e} |".format(label, d[k], min, mean, max))
else:
raise Exception("Impossible") | [
"def",
"on_pick",
"(",
"self",
",",
"event",
")",
":",
"if",
"self",
".",
"plottype",
"==",
"\"summary\"",
":",
"pass",
"elif",
"self",
".",
"plottype",
"==",
"\"benchmark\"",
":",
"marker_indexes",
"=",
"event",
".",
"ind",
"print",
"(",
"\"\\n Selected points: {}\"",
".",
"format",
"(",
"marker_indexes",
")",
")",
"D",
"=",
"self",
".",
"data",
"[",
"self",
".",
"ind",
"]",
"for",
"k",
"in",
"marker_indexes",
":",
"print",
"(",
"\" > Commit: {}\"",
".",
"format",
"(",
"D",
"[",
"\"commits\"",
"]",
"[",
"k",
"]",
")",
")",
"print",
"(",
"\" Branch: {}\"",
".",
"format",
"(",
"D",
"[",
"\"branches\"",
"]",
"[",
"k",
"]",
")",
")",
"print",
"(",
"\" Date: {}\"",
".",
"format",
"(",
"D",
"[",
"\"date\"",
"]",
"[",
"k",
"]",
")",
")",
"print",
"(",
"\" Link: https://llrgit.in2p3.fr/smilei/smilei/-/commit/{}\"",
".",
"format",
"(",
"D",
"[",
"\"commit_ids\"",
"]",
"[",
"k",
"]",
")",
")",
"print",
"(",
"\" ----------------------------------------------------------------------\"",
")",
"print",
"(",
"\" Timers | Times (s) | Min (s) | Mean (s) | Max (s) |\"",
")",
"print",
"(",
"\" ----------------------------------------------------------------------\"",
")",
"for",
"label",
",",
"d",
",",
"min",
",",
"mean",
",",
"max",
"in",
"zip",
"(",
"D",
"[",
"\"labels\"",
"]",
"+",
"[",
"\"Total\"",
"]",
",",
"D",
"[",
"\"processed_data\"",
"]",
"+",
"[",
"D",
"[",
"\"time_in_timeloop\"",
"]",
"]",
",",
"D",
"[",
"\"min_times\"",
"]",
",",
"D",
"[",
"\"mean_times\"",
"]",
",",
"D",
"[",
"\"max_times\"",
"]",
")",
":",
"print",
"(",
"\" {0:15} | {1:.4e} | {2:.4e} | {3:.4e} | {4:.4e} |\"",
".",
"format",
"(",
"label",
",",
"d",
"[",
"k",
"]",
",",
"min",
",",
"mean",
",",
"max",
")",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"Impossible\"",
")"
] | https://github.com/SmileiPIC/Smilei/blob/07dcb51200029e10f626e1546558c1ae7599c8b1/validation/plot_logs.py#L197-L226 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/plat-mac/pimp.py | python | PimpPackage_binary.unpackPackageOnly | (self, output=None) | We don't unpack binary packages until installing | We don't unpack binary packages until installing | [
"We",
"don",
"t",
"unpack",
"binary",
"packages",
"until",
"installing"
] | def unpackPackageOnly(self, output=None):
"""We don't unpack binary packages until installing"""
pass | [
"def",
"unpackPackageOnly",
"(",
"self",
",",
"output",
"=",
"None",
")",
":",
"pass"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/plat-mac/pimp.py#L793-L795 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | tools/site_compare/commands/compare2.py | python | ExecuteCompare2 | (command) | Executes the Compare2 command. | Executes the Compare2 command. | [
"Executes",
"the",
"Compare2",
"command",
"."
] | def ExecuteCompare2(command):
"""Executes the Compare2 command."""
if command["--url"]:
url_list = [command["--url"]]
else:
startline = command["--startline"]
if command["--count"]:
endline = startline+command["--count"]
else:
endline = command["--endline"]
url_list = [url.strip() for url in
open(command["--list"], "r").readlines()[startline:endline]]
log_file = open(command["--logfile"], "w")
outdir = command["--outdir"]
if not outdir: outdir = tempfile.gettempdir()
scrape_info_list = []
class ScrapeInfo(object):
"""Helper class to hold information about a scrape."""
__slots__ = ["browser_path", "scraper", "outdir", "result"]
for index in xrange(1, 3):
scrape_info = ScrapeInfo()
scrape_info.browser_path = command["--browser%d" % index]
scrape_info.scraper = scrapers.GetScraper(
(command["--browser"], command["--browser%dver" % index]))
if command["--browser%dname" % index]:
scrape_info.outdir = os.path.join(outdir,
command["--browser%dname" % index])
else:
scrape_info.outdir = os.path.join(outdir, str(index))
drivers.windowing.PreparePath(scrape_info.outdir)
scrape_info_list.append(scrape_info)
compare = operators.GetOperator("equals_with_mask")
for url in url_list:
success = True
for scrape_info in scrape_info_list:
scrape_info.result = scrape_info.scraper.Scrape(
[url], scrape_info.outdir, command["--size"], (0, 0),
command["--timeout"], path=scrape_info.browser_path)
if not scrape_info.result:
scrape_info.result = "success"
else:
success = False
result = "unknown"
if success:
result = "equal"
file1 = drivers.windowing.URLtoFilename(
url, scrape_info_list[0].outdir, ".bmp")
file2 = drivers.windowing.URLtoFilename(
url, scrape_info_list[1].outdir, ".bmp")
comparison_result = compare.Compare(file1, file2,
maskdir=command["--maskdir"])
if comparison_result is not None:
result = "not-equal"
if command["--diffdir"]:
comparison_result[1].save(
drivers.windowing.URLtoFilename(url, command["--diffdir"], ".bmp"))
# TODO(jhaas): maybe use the logging module rather than raw file writes
log_file.write("%s %s %s %s\n" % (url,
scrape_info_list[0].result,
scrape_info_list[1].result,
result)) | [
"def",
"ExecuteCompare2",
"(",
"command",
")",
":",
"if",
"command",
"[",
"\"--url\"",
"]",
":",
"url_list",
"=",
"[",
"command",
"[",
"\"--url\"",
"]",
"]",
"else",
":",
"startline",
"=",
"command",
"[",
"\"--startline\"",
"]",
"if",
"command",
"[",
"\"--count\"",
"]",
":",
"endline",
"=",
"startline",
"+",
"command",
"[",
"\"--count\"",
"]",
"else",
":",
"endline",
"=",
"command",
"[",
"\"--endline\"",
"]",
"url_list",
"=",
"[",
"url",
".",
"strip",
"(",
")",
"for",
"url",
"in",
"open",
"(",
"command",
"[",
"\"--list\"",
"]",
",",
"\"r\"",
")",
".",
"readlines",
"(",
")",
"[",
"startline",
":",
"endline",
"]",
"]",
"log_file",
"=",
"open",
"(",
"command",
"[",
"\"--logfile\"",
"]",
",",
"\"w\"",
")",
"outdir",
"=",
"command",
"[",
"\"--outdir\"",
"]",
"if",
"not",
"outdir",
":",
"outdir",
"=",
"tempfile",
".",
"gettempdir",
"(",
")",
"scrape_info_list",
"=",
"[",
"]",
"class",
"ScrapeInfo",
"(",
"object",
")",
":",
"\"\"\"Helper class to hold information about a scrape.\"\"\"",
"__slots__",
"=",
"[",
"\"browser_path\"",
",",
"\"scraper\"",
",",
"\"outdir\"",
",",
"\"result\"",
"]",
"for",
"index",
"in",
"xrange",
"(",
"1",
",",
"3",
")",
":",
"scrape_info",
"=",
"ScrapeInfo",
"(",
")",
"scrape_info",
".",
"browser_path",
"=",
"command",
"[",
"\"--browser%d\"",
"%",
"index",
"]",
"scrape_info",
".",
"scraper",
"=",
"scrapers",
".",
"GetScraper",
"(",
"(",
"command",
"[",
"\"--browser\"",
"]",
",",
"command",
"[",
"\"--browser%dver\"",
"%",
"index",
"]",
")",
")",
"if",
"command",
"[",
"\"--browser%dname\"",
"%",
"index",
"]",
":",
"scrape_info",
".",
"outdir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"outdir",
",",
"command",
"[",
"\"--browser%dname\"",
"%",
"index",
"]",
")",
"else",
":",
"scrape_info",
".",
"outdir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"outdir",
",",
"str",
"(",
"index",
")",
")",
"drivers",
".",
"windowing",
".",
"PreparePath",
"(",
"scrape_info",
".",
"outdir",
")",
"scrape_info_list",
".",
"append",
"(",
"scrape_info",
")",
"compare",
"=",
"operators",
".",
"GetOperator",
"(",
"\"equals_with_mask\"",
")",
"for",
"url",
"in",
"url_list",
":",
"success",
"=",
"True",
"for",
"scrape_info",
"in",
"scrape_info_list",
":",
"scrape_info",
".",
"result",
"=",
"scrape_info",
".",
"scraper",
".",
"Scrape",
"(",
"[",
"url",
"]",
",",
"scrape_info",
".",
"outdir",
",",
"command",
"[",
"\"--size\"",
"]",
",",
"(",
"0",
",",
"0",
")",
",",
"command",
"[",
"\"--timeout\"",
"]",
",",
"path",
"=",
"scrape_info",
".",
"browser_path",
")",
"if",
"not",
"scrape_info",
".",
"result",
":",
"scrape_info",
".",
"result",
"=",
"\"success\"",
"else",
":",
"success",
"=",
"False",
"result",
"=",
"\"unknown\"",
"if",
"success",
":",
"result",
"=",
"\"equal\"",
"file1",
"=",
"drivers",
".",
"windowing",
".",
"URLtoFilename",
"(",
"url",
",",
"scrape_info_list",
"[",
"0",
"]",
".",
"outdir",
",",
"\".bmp\"",
")",
"file2",
"=",
"drivers",
".",
"windowing",
".",
"URLtoFilename",
"(",
"url",
",",
"scrape_info_list",
"[",
"1",
"]",
".",
"outdir",
",",
"\".bmp\"",
")",
"comparison_result",
"=",
"compare",
".",
"Compare",
"(",
"file1",
",",
"file2",
",",
"maskdir",
"=",
"command",
"[",
"\"--maskdir\"",
"]",
")",
"if",
"comparison_result",
"is",
"not",
"None",
":",
"result",
"=",
"\"not-equal\"",
"if",
"command",
"[",
"\"--diffdir\"",
"]",
":",
"comparison_result",
"[",
"1",
"]",
".",
"save",
"(",
"drivers",
".",
"windowing",
".",
"URLtoFilename",
"(",
"url",
",",
"command",
"[",
"\"--diffdir\"",
"]",
",",
"\".bmp\"",
")",
")",
"# TODO(jhaas): maybe use the logging module rather than raw file writes",
"log_file",
".",
"write",
"(",
"\"%s %s %s %s\\n\"",
"%",
"(",
"url",
",",
"scrape_info_list",
"[",
"0",
"]",
".",
"result",
",",
"scrape_info_list",
"[",
"1",
"]",
".",
"result",
",",
"result",
")",
")"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/tools/site_compare/commands/compare2.py#L92-L170 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | HeaderColumn.GetTitle | (*args, **kwargs) | return _core_.HeaderColumn_GetTitle(*args, **kwargs) | GetTitle(self) -> String | GetTitle(self) -> String | [
"GetTitle",
"(",
"self",
")",
"-",
">",
"String"
] | def GetTitle(*args, **kwargs):
"""GetTitle(self) -> String"""
return _core_.HeaderColumn_GetTitle(*args, **kwargs) | [
"def",
"GetTitle",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"HeaderColumn_GetTitle",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L16380-L16382 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/aui/auibar.py | python | AuiToolBar.GetOverflowState | (self) | return self._overflow_state | Returns the state of the overflow button. | Returns the state of the overflow button. | [
"Returns",
"the",
"state",
"of",
"the",
"overflow",
"button",
"."
] | def GetOverflowState(self):
""" Returns the state of the overflow button. """
return self._overflow_state | [
"def",
"GetOverflowState",
"(",
"self",
")",
":",
"return",
"self",
".",
"_overflow_state"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/auibar.py#L3181-L3184 | |
martinmoene/variant-lite | f1af3518e4c28f12b09839b9d2ee37984cbf137a | script/upload-conan.py | python | createConanPackage | ( args ) | Create conan package and upload it. | Create conan package and upload it. | [
"Create",
"conan",
"package",
"and",
"upload",
"it",
"."
] | def createConanPackage( args ):
"""Create conan package and upload it."""
cmd = tpl_conan_create.format(usr=args.user, chn=args.channel)
if args.verbose:
print( "> {}".format(cmd) )
if not args.dry_run:
subprocess.call( cmd, shell=False ) | [
"def",
"createConanPackage",
"(",
"args",
")",
":",
"cmd",
"=",
"tpl_conan_create",
".",
"format",
"(",
"usr",
"=",
"args",
".",
"user",
",",
"chn",
"=",
"args",
".",
"channel",
")",
"if",
"args",
".",
"verbose",
":",
"print",
"(",
"\"> {}\"",
".",
"format",
"(",
"cmd",
")",
")",
"if",
"not",
"args",
".",
"dry_run",
":",
"subprocess",
".",
"call",
"(",
"cmd",
",",
"shell",
"=",
"False",
")"
] | https://github.com/martinmoene/variant-lite/blob/f1af3518e4c28f12b09839b9d2ee37984cbf137a/script/upload-conan.py#L38-L44 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/distlib/_backport/sysconfig.py | python | get_config_h_filename | () | return os.path.join(inc_dir, 'pyconfig.h') | Return the path of pyconfig.h. | Return the path of pyconfig.h. | [
"Return",
"the",
"path",
"of",
"pyconfig",
".",
"h",
"."
] | def get_config_h_filename():
"""Return the path of pyconfig.h."""
if _PYTHON_BUILD:
if os.name == "nt":
inc_dir = os.path.join(_PROJECT_BASE, "PC")
else:
inc_dir = _PROJECT_BASE
else:
inc_dir = get_path('platinclude')
return os.path.join(inc_dir, 'pyconfig.h') | [
"def",
"get_config_h_filename",
"(",
")",
":",
"if",
"_PYTHON_BUILD",
":",
"if",
"os",
".",
"name",
"==",
"\"nt\"",
":",
"inc_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"_PROJECT_BASE",
",",
"\"PC\"",
")",
"else",
":",
"inc_dir",
"=",
"_PROJECT_BASE",
"else",
":",
"inc_dir",
"=",
"get_path",
"(",
"'platinclude'",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"inc_dir",
",",
"'pyconfig.h'",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/distlib/_backport/sysconfig.py#L417-L426 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/feature_column/feature_column_v2.py | python | IdentityCategoricalColumn._get_config | (self) | return dict(zip(self._fields, self)) | See 'FeatureColumn` base class. | See 'FeatureColumn` base class. | [
"See",
"FeatureColumn",
"base",
"class",
"."
] | def _get_config(self):
"""See 'FeatureColumn` base class."""
return dict(zip(self._fields, self)) | [
"def",
"_get_config",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"zip",
"(",
"self",
".",
"_fields",
",",
"self",
")",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/feature_column/feature_column_v2.py#L3904-L3906 | |
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | src/pybind/mgr/rook/rook_cluster.py | python | RookCluster.describe_pods | (self,
service_type: Optional[str],
service_id: Optional[str],
nodename: Optional[str]) | return pods_summary | Go query the k8s API about deployment, containers related to this
filesystem
Example Rook Pod labels for a mgr daemon:
Labels: app=rook-ceph-mgr
pod-template-hash=2171958073
rook_cluster=rook
And MDS containers additionally have `rook_filesystem` label
Label filter is rook_cluster=<cluster namespace>
rook_file_system=<self.fs_name> | Go query the k8s API about deployment, containers related to this
filesystem | [
"Go",
"query",
"the",
"k8s",
"API",
"about",
"deployment",
"containers",
"related",
"to",
"this",
"filesystem"
] | def describe_pods(self,
service_type: Optional[str],
service_id: Optional[str],
nodename: Optional[str]) -> List[Dict[str, Any]]:
"""
Go query the k8s API about deployment, containers related to this
filesystem
Example Rook Pod labels for a mgr daemon:
Labels: app=rook-ceph-mgr
pod-template-hash=2171958073
rook_cluster=rook
And MDS containers additionally have `rook_filesystem` label
Label filter is rook_cluster=<cluster namespace>
rook_file_system=<self.fs_name>
"""
def predicate(item):
# type: (client.V1Pod) -> bool
metadata = item.metadata
if service_type is not None:
if metadata.labels['app'] != "rook-ceph-{0}".format(service_type):
return False
if service_id is not None:
try:
k, v = {
"mds": ("rook_file_system", service_id),
"osd": ("ceph-osd-id", service_id),
"mon": ("mon", service_id),
"mgr": ("mgr", service_id),
"nfs": ("nfs", service_id),
"rgw": ("ceph_rgw", service_id),
}[service_type]
except KeyError:
raise orchestrator.OrchestratorValidationError(
'{} not supported'.format(service_type))
if metadata.labels[k] != v:
return False
if nodename is not None:
if item.spec.node_name != nodename:
return False
return True
refreshed = datetime_now()
pods = [i for i in self.rook_pods.items if predicate(i)]
pods_summary = []
prefix = 'sha256:'
for p in pods:
d = p.to_dict()
image_name = None
for c in d['spec']['containers']:
# look at the first listed container in the pod...
image_name = c['image']
break
ls = d['status'].get('container_statuses')
if not ls:
# ignore pods with no containers
continue
image_id = ls[0]['image_id']
image_id = image_id.split(prefix)[1] if prefix in image_id else image_id
s = {
"name": d['metadata']['name'],
"hostname": d['spec']['node_name'],
"labels": d['metadata']['labels'],
'phase': d['status']['phase'],
'container_image_name': image_name,
'container_image_id': image_id,
'refreshed': refreshed,
# these may get set below...
'started': None,
'created': None,
}
# note: we want UTC
if d['metadata'].get('creation_timestamp', None):
s['created'] = d['metadata']['creation_timestamp'].astimezone(
tz=datetime.timezone.utc)
if d['status'].get('start_time', None):
s['started'] = d['status']['start_time'].astimezone(
tz=datetime.timezone.utc)
pods_summary.append(s)
return pods_summary | [
"def",
"describe_pods",
"(",
"self",
",",
"service_type",
":",
"Optional",
"[",
"str",
"]",
",",
"service_id",
":",
"Optional",
"[",
"str",
"]",
",",
"nodename",
":",
"Optional",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"def",
"predicate",
"(",
"item",
")",
":",
"# type: (client.V1Pod) -> bool",
"metadata",
"=",
"item",
".",
"metadata",
"if",
"service_type",
"is",
"not",
"None",
":",
"if",
"metadata",
".",
"labels",
"[",
"'app'",
"]",
"!=",
"\"rook-ceph-{0}\"",
".",
"format",
"(",
"service_type",
")",
":",
"return",
"False",
"if",
"service_id",
"is",
"not",
"None",
":",
"try",
":",
"k",
",",
"v",
"=",
"{",
"\"mds\"",
":",
"(",
"\"rook_file_system\"",
",",
"service_id",
")",
",",
"\"osd\"",
":",
"(",
"\"ceph-osd-id\"",
",",
"service_id",
")",
",",
"\"mon\"",
":",
"(",
"\"mon\"",
",",
"service_id",
")",
",",
"\"mgr\"",
":",
"(",
"\"mgr\"",
",",
"service_id",
")",
",",
"\"nfs\"",
":",
"(",
"\"nfs\"",
",",
"service_id",
")",
",",
"\"rgw\"",
":",
"(",
"\"ceph_rgw\"",
",",
"service_id",
")",
",",
"}",
"[",
"service_type",
"]",
"except",
"KeyError",
":",
"raise",
"orchestrator",
".",
"OrchestratorValidationError",
"(",
"'{} not supported'",
".",
"format",
"(",
"service_type",
")",
")",
"if",
"metadata",
".",
"labels",
"[",
"k",
"]",
"!=",
"v",
":",
"return",
"False",
"if",
"nodename",
"is",
"not",
"None",
":",
"if",
"item",
".",
"spec",
".",
"node_name",
"!=",
"nodename",
":",
"return",
"False",
"return",
"True",
"refreshed",
"=",
"datetime_now",
"(",
")",
"pods",
"=",
"[",
"i",
"for",
"i",
"in",
"self",
".",
"rook_pods",
".",
"items",
"if",
"predicate",
"(",
"i",
")",
"]",
"pods_summary",
"=",
"[",
"]",
"prefix",
"=",
"'sha256:'",
"for",
"p",
"in",
"pods",
":",
"d",
"=",
"p",
".",
"to_dict",
"(",
")",
"image_name",
"=",
"None",
"for",
"c",
"in",
"d",
"[",
"'spec'",
"]",
"[",
"'containers'",
"]",
":",
"# look at the first listed container in the pod...",
"image_name",
"=",
"c",
"[",
"'image'",
"]",
"break",
"ls",
"=",
"d",
"[",
"'status'",
"]",
".",
"get",
"(",
"'container_statuses'",
")",
"if",
"not",
"ls",
":",
"# ignore pods with no containers",
"continue",
"image_id",
"=",
"ls",
"[",
"0",
"]",
"[",
"'image_id'",
"]",
"image_id",
"=",
"image_id",
".",
"split",
"(",
"prefix",
")",
"[",
"1",
"]",
"if",
"prefix",
"in",
"image_id",
"else",
"image_id",
"s",
"=",
"{",
"\"name\"",
":",
"d",
"[",
"'metadata'",
"]",
"[",
"'name'",
"]",
",",
"\"hostname\"",
":",
"d",
"[",
"'spec'",
"]",
"[",
"'node_name'",
"]",
",",
"\"labels\"",
":",
"d",
"[",
"'metadata'",
"]",
"[",
"'labels'",
"]",
",",
"'phase'",
":",
"d",
"[",
"'status'",
"]",
"[",
"'phase'",
"]",
",",
"'container_image_name'",
":",
"image_name",
",",
"'container_image_id'",
":",
"image_id",
",",
"'refreshed'",
":",
"refreshed",
",",
"# these may get set below...",
"'started'",
":",
"None",
",",
"'created'",
":",
"None",
",",
"}",
"# note: we want UTC",
"if",
"d",
"[",
"'metadata'",
"]",
".",
"get",
"(",
"'creation_timestamp'",
",",
"None",
")",
":",
"s",
"[",
"'created'",
"]",
"=",
"d",
"[",
"'metadata'",
"]",
"[",
"'creation_timestamp'",
"]",
".",
"astimezone",
"(",
"tz",
"=",
"datetime",
".",
"timezone",
".",
"utc",
")",
"if",
"d",
"[",
"'status'",
"]",
".",
"get",
"(",
"'start_time'",
",",
"None",
")",
":",
"s",
"[",
"'started'",
"]",
"=",
"d",
"[",
"'status'",
"]",
"[",
"'start_time'",
"]",
".",
"astimezone",
"(",
"tz",
"=",
"datetime",
".",
"timezone",
".",
"utc",
")",
"pods_summary",
".",
"append",
"(",
"s",
")",
"return",
"pods_summary"
] | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/pybind/mgr/rook/rook_cluster.py#L747-L837 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/estimators/estimator.py | python | BaseEstimator.evaluate | (self,
x=None,
y=None,
input_fn=None,
feed_fn=None,
batch_size=None,
steps=None,
metrics=None,
name=None,
checkpoint_path=None,
hooks=None,
log_progress=True) | return eval_results | See `Evaluable`.
Raises:
ValueError: If at least one of `x` or `y` is provided, and at least one of
`input_fn` or `feed_fn` is provided.
Or if `metrics` is not `None` or `dict`. | See `Evaluable`. | [
"See",
"Evaluable",
"."
] | def evaluate(self,
x=None,
y=None,
input_fn=None,
feed_fn=None,
batch_size=None,
steps=None,
metrics=None,
name=None,
checkpoint_path=None,
hooks=None,
log_progress=True):
# pylint: disable=g-doc-args,g-doc-return-or-yield
"""See `Evaluable`.
Raises:
ValueError: If at least one of `x` or `y` is provided, and at least one of
`input_fn` or `feed_fn` is provided.
Or if `metrics` is not `None` or `dict`.
"""
_verify_input_args(x, y, input_fn, feed_fn, batch_size)
if x is not None:
return SKCompat(self).score(x, y, batch_size, steps, metrics, name)
if metrics is not None and not isinstance(metrics, dict):
raise ValueError('Metrics argument should be None or dict. '
'Got %s.' % metrics)
eval_results, global_step = self._evaluate_model(
input_fn=input_fn,
feed_fn=feed_fn,
steps=steps,
metrics=metrics,
name=name,
checkpoint_path=checkpoint_path,
hooks=hooks,
log_progress=log_progress)
if eval_results is not None:
eval_results.update({'global_step': global_step})
return eval_results | [
"def",
"evaluate",
"(",
"self",
",",
"x",
"=",
"None",
",",
"y",
"=",
"None",
",",
"input_fn",
"=",
"None",
",",
"feed_fn",
"=",
"None",
",",
"batch_size",
"=",
"None",
",",
"steps",
"=",
"None",
",",
"metrics",
"=",
"None",
",",
"name",
"=",
"None",
",",
"checkpoint_path",
"=",
"None",
",",
"hooks",
"=",
"None",
",",
"log_progress",
"=",
"True",
")",
":",
"# pylint: disable=g-doc-args,g-doc-return-or-yield",
"_verify_input_args",
"(",
"x",
",",
"y",
",",
"input_fn",
",",
"feed_fn",
",",
"batch_size",
")",
"if",
"x",
"is",
"not",
"None",
":",
"return",
"SKCompat",
"(",
"self",
")",
".",
"score",
"(",
"x",
",",
"y",
",",
"batch_size",
",",
"steps",
",",
"metrics",
",",
"name",
")",
"if",
"metrics",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"metrics",
",",
"dict",
")",
":",
"raise",
"ValueError",
"(",
"'Metrics argument should be None or dict. '",
"'Got %s.'",
"%",
"metrics",
")",
"eval_results",
",",
"global_step",
"=",
"self",
".",
"_evaluate_model",
"(",
"input_fn",
"=",
"input_fn",
",",
"feed_fn",
"=",
"feed_fn",
",",
"steps",
"=",
"steps",
",",
"metrics",
"=",
"metrics",
",",
"name",
"=",
"name",
",",
"checkpoint_path",
"=",
"checkpoint_path",
",",
"hooks",
"=",
"hooks",
",",
"log_progress",
"=",
"log_progress",
")",
"if",
"eval_results",
"is",
"not",
"None",
":",
"eval_results",
".",
"update",
"(",
"{",
"'global_step'",
":",
"global_step",
"}",
")",
"return",
"eval_results"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/estimators/estimator.py#L582-L621 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Path/PathScripts/PathThreadMilling.py | python | internalThreadCommands | (loc, cmd, zStart, zFinal, pitch, radius, leadInOut) | return path | internalThreadCommands(loc, cmd, zStart, zFinal, pitch, radius) ... returns the g-code to mill the given internal thread | internalThreadCommands(loc, cmd, zStart, zFinal, pitch, radius) ... returns the g-code to mill the given internal thread | [
"internalThreadCommands",
"(",
"loc",
"cmd",
"zStart",
"zFinal",
"pitch",
"radius",
")",
"...",
"returns",
"the",
"g",
"-",
"code",
"to",
"mill",
"the",
"given",
"internal",
"thread"
] | def internalThreadCommands(loc, cmd, zStart, zFinal, pitch, radius, leadInOut):
"""internalThreadCommands(loc, cmd, zStart, zFinal, pitch, radius) ... returns the g-code to mill the given internal thread"""
thread = _InternalThread(cmd, zStart, zFinal, pitch)
yMin = loc.y - radius
yMax = loc.y + radius
path = []
# at this point the tool is at a safe height (depending on the previous thread), so we can move
# into position first, and then drop to the start height. If there is any material in the way this
# op hasn't been setup properly.
path.append(Path.Command("G0", {"X": loc.x, "Y": loc.y}))
path.append(Path.Command("G0", {"Z": thread.zStart}))
if leadInOut:
path.append(Path.Command(thread.cmd, {"Y": yMax, "J": (yMax - loc.y) / 2}))
else:
path.append(Path.Command("G1", {"Y": yMax}))
z = thread.zStart
r = -radius
i = 0
while True:
z = thread.zStart + i * thread.hPitch
if thread.overshoots(z):
break
if 0 == (i & 0x01):
y = yMin
else:
y = yMax
path.append(Path.Command(thread.cmd, {"Y": y, "Z": z + thread.hPitch, "J": r}))
r = -r
i = i + 1
z = thread.zStart + i * thread.hPitch
if PathGeom.isRoughly(z, thread.zFinal):
x = loc.x
else:
n = math.fabs(thread.zFinal - thread.zStart) / thread.hPitch
k = n - int(n)
dy = math.cos(k * math.pi)
dx = math.sin(k * math.pi)
y = thread.adjustY(loc.y, r * dy)
x = thread.adjustX(loc.x, r * dx)
path.append(
Path.Command(thread.cmd, {"X": x, "Y": y, "Z": thread.zFinal, "J": r})
)
if leadInOut:
path.append(
Path.Command(
thread.cmd,
{"X": loc.x, "Y": loc.y, "I": (loc.x - x) / 2, "J": (loc.y - y) / 2},
)
)
else:
path.append(Path.Command("G1", {"X": loc.x, "Y": loc.y}))
return path | [
"def",
"internalThreadCommands",
"(",
"loc",
",",
"cmd",
",",
"zStart",
",",
"zFinal",
",",
"pitch",
",",
"radius",
",",
"leadInOut",
")",
":",
"thread",
"=",
"_InternalThread",
"(",
"cmd",
",",
"zStart",
",",
"zFinal",
",",
"pitch",
")",
"yMin",
"=",
"loc",
".",
"y",
"-",
"radius",
"yMax",
"=",
"loc",
".",
"y",
"+",
"radius",
"path",
"=",
"[",
"]",
"# at this point the tool is at a safe height (depending on the previous thread), so we can move",
"# into position first, and then drop to the start height. If there is any material in the way this",
"# op hasn't been setup properly.",
"path",
".",
"append",
"(",
"Path",
".",
"Command",
"(",
"\"G0\"",
",",
"{",
"\"X\"",
":",
"loc",
".",
"x",
",",
"\"Y\"",
":",
"loc",
".",
"y",
"}",
")",
")",
"path",
".",
"append",
"(",
"Path",
".",
"Command",
"(",
"\"G0\"",
",",
"{",
"\"Z\"",
":",
"thread",
".",
"zStart",
"}",
")",
")",
"if",
"leadInOut",
":",
"path",
".",
"append",
"(",
"Path",
".",
"Command",
"(",
"thread",
".",
"cmd",
",",
"{",
"\"Y\"",
":",
"yMax",
",",
"\"J\"",
":",
"(",
"yMax",
"-",
"loc",
".",
"y",
")",
"/",
"2",
"}",
")",
")",
"else",
":",
"path",
".",
"append",
"(",
"Path",
".",
"Command",
"(",
"\"G1\"",
",",
"{",
"\"Y\"",
":",
"yMax",
"}",
")",
")",
"z",
"=",
"thread",
".",
"zStart",
"r",
"=",
"-",
"radius",
"i",
"=",
"0",
"while",
"True",
":",
"z",
"=",
"thread",
".",
"zStart",
"+",
"i",
"*",
"thread",
".",
"hPitch",
"if",
"thread",
".",
"overshoots",
"(",
"z",
")",
":",
"break",
"if",
"0",
"==",
"(",
"i",
"&",
"0x01",
")",
":",
"y",
"=",
"yMin",
"else",
":",
"y",
"=",
"yMax",
"path",
".",
"append",
"(",
"Path",
".",
"Command",
"(",
"thread",
".",
"cmd",
",",
"{",
"\"Y\"",
":",
"y",
",",
"\"Z\"",
":",
"z",
"+",
"thread",
".",
"hPitch",
",",
"\"J\"",
":",
"r",
"}",
")",
")",
"r",
"=",
"-",
"r",
"i",
"=",
"i",
"+",
"1",
"z",
"=",
"thread",
".",
"zStart",
"+",
"i",
"*",
"thread",
".",
"hPitch",
"if",
"PathGeom",
".",
"isRoughly",
"(",
"z",
",",
"thread",
".",
"zFinal",
")",
":",
"x",
"=",
"loc",
".",
"x",
"else",
":",
"n",
"=",
"math",
".",
"fabs",
"(",
"thread",
".",
"zFinal",
"-",
"thread",
".",
"zStart",
")",
"/",
"thread",
".",
"hPitch",
"k",
"=",
"n",
"-",
"int",
"(",
"n",
")",
"dy",
"=",
"math",
".",
"cos",
"(",
"k",
"*",
"math",
".",
"pi",
")",
"dx",
"=",
"math",
".",
"sin",
"(",
"k",
"*",
"math",
".",
"pi",
")",
"y",
"=",
"thread",
".",
"adjustY",
"(",
"loc",
".",
"y",
",",
"r",
"*",
"dy",
")",
"x",
"=",
"thread",
".",
"adjustX",
"(",
"loc",
".",
"x",
",",
"r",
"*",
"dx",
")",
"path",
".",
"append",
"(",
"Path",
".",
"Command",
"(",
"thread",
".",
"cmd",
",",
"{",
"\"X\"",
":",
"x",
",",
"\"Y\"",
":",
"y",
",",
"\"Z\"",
":",
"thread",
".",
"zFinal",
",",
"\"J\"",
":",
"r",
"}",
")",
")",
"if",
"leadInOut",
":",
"path",
".",
"append",
"(",
"Path",
".",
"Command",
"(",
"thread",
".",
"cmd",
",",
"{",
"\"X\"",
":",
"loc",
".",
"x",
",",
"\"Y\"",
":",
"loc",
".",
"y",
",",
"\"I\"",
":",
"(",
"loc",
".",
"x",
"-",
"x",
")",
"/",
"2",
",",
"\"J\"",
":",
"(",
"loc",
".",
"y",
"-",
"y",
")",
"/",
"2",
"}",
",",
")",
")",
"else",
":",
"path",
".",
"append",
"(",
"Path",
".",
"Command",
"(",
"\"G1\"",
",",
"{",
"\"X\"",
":",
"loc",
".",
"x",
",",
"\"Y\"",
":",
"loc",
".",
"y",
"}",
")",
")",
"return",
"path"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathThreadMilling.py#L115-L171 | |
apache/arrow | af33dd1157eb8d7d9bfac25ebf61445b793b7943 | python/pyarrow/orc.py | python | ORCFile.writer | (self) | return self.reader.writer() | Name of the writer that wrote this file.
If the writer is unknown then its Writer ID
(a number) is returned | Name of the writer that wrote this file.
If the writer is unknown then its Writer ID
(a number) is returned | [
"Name",
"of",
"the",
"writer",
"that",
"wrote",
"this",
"file",
".",
"If",
"the",
"writer",
"is",
"unknown",
"then",
"its",
"Writer",
"ID",
"(",
"a",
"number",
")",
"is",
"returned"
] | def writer(self):
"""Name of the writer that wrote this file.
If the writer is unknown then its Writer ID
(a number) is returned"""
return self.reader.writer() | [
"def",
"writer",
"(",
"self",
")",
":",
"return",
"self",
".",
"reader",
".",
"writer",
"(",
")"
] | https://github.com/apache/arrow/blob/af33dd1157eb8d7d9bfac25ebf61445b793b7943/python/pyarrow/orc.py#L83-L87 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/ma/core.py | python | reshape | (a, new_shape, order='C') | Returns an array containing the same data with a new shape.
Refer to `MaskedArray.reshape` for full documentation.
See Also
--------
MaskedArray.reshape : equivalent function | Returns an array containing the same data with a new shape. | [
"Returns",
"an",
"array",
"containing",
"the",
"same",
"data",
"with",
"a",
"new",
"shape",
"."
] | def reshape(a, new_shape, order='C'):
"""
Returns an array containing the same data with a new shape.
Refer to `MaskedArray.reshape` for full documentation.
See Also
--------
MaskedArray.reshape : equivalent function
"""
# We can't use 'frommethod', it whine about some parameters. Dmmit.
try:
return a.reshape(new_shape, order=order)
except AttributeError:
_tmp = narray(a, copy=False).reshape(new_shape, order=order)
return _tmp.view(MaskedArray) | [
"def",
"reshape",
"(",
"a",
",",
"new_shape",
",",
"order",
"=",
"'C'",
")",
":",
"# We can't use 'frommethod', it whine about some parameters. Dmmit.",
"try",
":",
"return",
"a",
".",
"reshape",
"(",
"new_shape",
",",
"order",
"=",
"order",
")",
"except",
"AttributeError",
":",
"_tmp",
"=",
"narray",
"(",
"a",
",",
"copy",
"=",
"False",
")",
".",
"reshape",
"(",
"new_shape",
",",
"order",
"=",
"order",
")",
"return",
"_tmp",
".",
"view",
"(",
"MaskedArray",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/ma/core.py#L7142-L7158 | ||
ros-planning/moveit | ee48dc5cedc981d0869352aa3db0b41469c2735c | moveit_commander/src/moveit_commander/move_group.py | python | MoveGroupCommander.clear_trajectory_constraints | (self) | Specify that no trajectory constraints are to be used during motion planning | Specify that no trajectory constraints are to be used during motion planning | [
"Specify",
"that",
"no",
"trajectory",
"constraints",
"are",
"to",
"be",
"used",
"during",
"motion",
"planning"
] | def clear_trajectory_constraints(self):
""" Specify that no trajectory constraints are to be used during motion planning """
self._g.clear_trajectory_constraints() | [
"def",
"clear_trajectory_constraints",
"(",
"self",
")",
":",
"self",
".",
"_g",
".",
"clear_trajectory_constraints",
"(",
")"
] | https://github.com/ros-planning/moveit/blob/ee48dc5cedc981d0869352aa3db0b41469c2735c/moveit_commander/src/moveit_commander/move_group.py#L520-L522 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/contrib/slim/python/slim/nets/alexnet.py | python | alexnet_v2 | (inputs,
num_classes=1000,
dropout_keep_prob=0.5,
is_training=True,
spatial_squeeze=True,
scope='alexnet_v2') | AlexNet version 2.
Described in: http://arxiv.org/pdf/1404.5997v2.pdf
Parameters from:
github.com/akrizhevsky/cuda-convnet2/blob/master/layers/
layers-imagenet-1gpu.cfg
Note: All the fully_connected layers have been transformed to conv2d layers.
To use in classification mode, resize input to 224x224. To use in fully
convolutional mode, set spatial_squeeze to false.
The LRN layers have been removed and change the initializers from
random_normal_initializer to xavier_initializer.
Args:
inputs: a tensor of size [batch_size, height, width, channels].
num_classes: number of predicted classes.
dropout_keep_prob: the probability that activations are kept in the dropout
layers during training.
is_training: whether or not the model is being trained.
spatial_squeeze: whether or not should squeeze the spatial dimensions of the
outputs. Useful to remove unnecessary dimensions for classification.
scope: Optional scope for the variables.
Returns:
the last op containing the log predictions and end_points dict. | AlexNet version 2. | [
"AlexNet",
"version",
"2",
"."
] | def alexnet_v2(inputs,
num_classes=1000,
dropout_keep_prob=0.5,
is_training=True,
spatial_squeeze=True,
scope='alexnet_v2'):
"""AlexNet version 2.
Described in: http://arxiv.org/pdf/1404.5997v2.pdf
Parameters from:
github.com/akrizhevsky/cuda-convnet2/blob/master/layers/
layers-imagenet-1gpu.cfg
Note: All the fully_connected layers have been transformed to conv2d layers.
To use in classification mode, resize input to 224x224. To use in fully
convolutional mode, set spatial_squeeze to false.
The LRN layers have been removed and change the initializers from
random_normal_initializer to xavier_initializer.
Args:
inputs: a tensor of size [batch_size, height, width, channels].
num_classes: number of predicted classes.
dropout_keep_prob: the probability that activations are kept in the dropout
layers during training.
is_training: whether or not the model is being trained.
spatial_squeeze: whether or not should squeeze the spatial dimensions of the
outputs. Useful to remove unnecessary dimensions for classification.
scope: Optional scope for the variables.
Returns:
the last op containing the log predictions and end_points dict.
"""
with tf.variable_op_scope([inputs], scope, 'alexnet_v2') as sc:
end_points_collection = sc.name + '_end_points'
# Collect outputs for conv2d, fully_connected and max_pool2d.
with slim.arg_scope([slim.conv2d, slim.fully_connected, slim.max_pool2d],
outputs_collections=[end_points_collection]):
net = slim.conv2d(inputs, 64, [11, 11], 4, padding='VALID',
scope='conv1')
net = slim.max_pool2d(net, [3, 3], 2, scope='pool1')
net = slim.conv2d(net, 192, [5, 5], scope='conv2')
net = slim.max_pool2d(net, [3, 3], 2, scope='pool2')
net = slim.conv2d(net, 384, [3, 3], scope='conv3')
net = slim.conv2d(net, 384, [3, 3], scope='conv4')
net = slim.conv2d(net, 256, [3, 3], scope='conv5')
net = slim.max_pool2d(net, [3, 3], 2, scope='pool5')
# Use conv2d instead of fully_connected layers.
with slim.arg_scope([slim.conv2d],
weights_initializer=trunc_normal(0.005),
biases_initializer=tf.constant_initializer(0.1)):
net = slim.conv2d(net, 4096, [5, 5], padding='VALID',
scope='fc6')
net = slim.dropout(net, dropout_keep_prob, is_training=is_training,
scope='dropout6')
net = slim.conv2d(net, 4096, [1, 1], scope='fc7')
net = slim.dropout(net, dropout_keep_prob, is_training=is_training,
scope='dropout7')
net = slim.conv2d(net, num_classes, [1, 1],
activation_fn=None,
normalizer_fn=None,
biases_initializer=tf.zeros_initializer,
scope='fc8')
# Convert end_points_collection into a end_point dict.
end_points = dict(tf.get_collection(end_points_collection))
if spatial_squeeze:
net = tf.squeeze(net, [1, 2], name='fc8/squeezed')
end_points[sc.name + '/fc8'] = net
return net, end_points | [
"def",
"alexnet_v2",
"(",
"inputs",
",",
"num_classes",
"=",
"1000",
",",
"dropout_keep_prob",
"=",
"0.5",
",",
"is_training",
"=",
"True",
",",
"spatial_squeeze",
"=",
"True",
",",
"scope",
"=",
"'alexnet_v2'",
")",
":",
"with",
"tf",
".",
"variable_op_scope",
"(",
"[",
"inputs",
"]",
",",
"scope",
",",
"'alexnet_v2'",
")",
"as",
"sc",
":",
"end_points_collection",
"=",
"sc",
".",
"name",
"+",
"'_end_points'",
"# Collect outputs for conv2d, fully_connected and max_pool2d.",
"with",
"slim",
".",
"arg_scope",
"(",
"[",
"slim",
".",
"conv2d",
",",
"slim",
".",
"fully_connected",
",",
"slim",
".",
"max_pool2d",
"]",
",",
"outputs_collections",
"=",
"[",
"end_points_collection",
"]",
")",
":",
"net",
"=",
"slim",
".",
"conv2d",
"(",
"inputs",
",",
"64",
",",
"[",
"11",
",",
"11",
"]",
",",
"4",
",",
"padding",
"=",
"'VALID'",
",",
"scope",
"=",
"'conv1'",
")",
"net",
"=",
"slim",
".",
"max_pool2d",
"(",
"net",
",",
"[",
"3",
",",
"3",
"]",
",",
"2",
",",
"scope",
"=",
"'pool1'",
")",
"net",
"=",
"slim",
".",
"conv2d",
"(",
"net",
",",
"192",
",",
"[",
"5",
",",
"5",
"]",
",",
"scope",
"=",
"'conv2'",
")",
"net",
"=",
"slim",
".",
"max_pool2d",
"(",
"net",
",",
"[",
"3",
",",
"3",
"]",
",",
"2",
",",
"scope",
"=",
"'pool2'",
")",
"net",
"=",
"slim",
".",
"conv2d",
"(",
"net",
",",
"384",
",",
"[",
"3",
",",
"3",
"]",
",",
"scope",
"=",
"'conv3'",
")",
"net",
"=",
"slim",
".",
"conv2d",
"(",
"net",
",",
"384",
",",
"[",
"3",
",",
"3",
"]",
",",
"scope",
"=",
"'conv4'",
")",
"net",
"=",
"slim",
".",
"conv2d",
"(",
"net",
",",
"256",
",",
"[",
"3",
",",
"3",
"]",
",",
"scope",
"=",
"'conv5'",
")",
"net",
"=",
"slim",
".",
"max_pool2d",
"(",
"net",
",",
"[",
"3",
",",
"3",
"]",
",",
"2",
",",
"scope",
"=",
"'pool5'",
")",
"# Use conv2d instead of fully_connected layers.",
"with",
"slim",
".",
"arg_scope",
"(",
"[",
"slim",
".",
"conv2d",
"]",
",",
"weights_initializer",
"=",
"trunc_normal",
"(",
"0.005",
")",
",",
"biases_initializer",
"=",
"tf",
".",
"constant_initializer",
"(",
"0.1",
")",
")",
":",
"net",
"=",
"slim",
".",
"conv2d",
"(",
"net",
",",
"4096",
",",
"[",
"5",
",",
"5",
"]",
",",
"padding",
"=",
"'VALID'",
",",
"scope",
"=",
"'fc6'",
")",
"net",
"=",
"slim",
".",
"dropout",
"(",
"net",
",",
"dropout_keep_prob",
",",
"is_training",
"=",
"is_training",
",",
"scope",
"=",
"'dropout6'",
")",
"net",
"=",
"slim",
".",
"conv2d",
"(",
"net",
",",
"4096",
",",
"[",
"1",
",",
"1",
"]",
",",
"scope",
"=",
"'fc7'",
")",
"net",
"=",
"slim",
".",
"dropout",
"(",
"net",
",",
"dropout_keep_prob",
",",
"is_training",
"=",
"is_training",
",",
"scope",
"=",
"'dropout7'",
")",
"net",
"=",
"slim",
".",
"conv2d",
"(",
"net",
",",
"num_classes",
",",
"[",
"1",
",",
"1",
"]",
",",
"activation_fn",
"=",
"None",
",",
"normalizer_fn",
"=",
"None",
",",
"biases_initializer",
"=",
"tf",
".",
"zeros_initializer",
",",
"scope",
"=",
"'fc8'",
")",
"# Convert end_points_collection into a end_point dict.",
"end_points",
"=",
"dict",
"(",
"tf",
".",
"get_collection",
"(",
"end_points_collection",
")",
")",
"if",
"spatial_squeeze",
":",
"net",
"=",
"tf",
".",
"squeeze",
"(",
"net",
",",
"[",
"1",
",",
"2",
"]",
",",
"name",
"=",
"'fc8/squeezed'",
")",
"end_points",
"[",
"sc",
".",
"name",
"+",
"'/fc8'",
"]",
"=",
"net",
"return",
"net",
",",
"end_points"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/slim/python/slim/nets/alexnet.py#L51-L120 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/estimator/canned/head.py | python | _multi_class_head_with_softmax_cross_entropy_loss | (n_classes,
weight_column=None,
label_vocabulary=None) | return _MultiClassHeadWithSoftmaxCrossEntropyLoss(n_classes, weight_column,
label_vocabulary) | Creates a '_Head' for multi class classification.
This head expects to be fed integer labels specifying the class index.
Args:
n_classes: Number of classes, must be greater than 2 (for 2 classes, use
`_BinaryLogisticHeadWithSigmoidCrossEntropyLoss`).
weight_column: A string or a `_NumericColumn` created by
`tf.feature_column.numeric_column` defining feature column representing
weights. It is used to down weight or boost examples during training. It
will be multiplied by the loss of the example.
label_vocabulary: A list of strings represents possible label values. If it
is not given, that means labels are already encoded as integer within
[0, n_classes). If given, labels must be string type and have any value in
`label_vocabulary`. Also there will be errors if vocabulary is not
provided and labels are string.
Returns:
An instance of `_Head` for multi class classification.
Raises:
ValueError: if `n_classes`, `metric_class_ids` or `label_keys` is invalid. | Creates a '_Head' for multi class classification. | [
"Creates",
"a",
"_Head",
"for",
"multi",
"class",
"classification",
"."
] | def _multi_class_head_with_softmax_cross_entropy_loss(n_classes,
weight_column=None,
label_vocabulary=None):
"""Creates a '_Head' for multi class classification.
This head expects to be fed integer labels specifying the class index.
Args:
n_classes: Number of classes, must be greater than 2 (for 2 classes, use
`_BinaryLogisticHeadWithSigmoidCrossEntropyLoss`).
weight_column: A string or a `_NumericColumn` created by
`tf.feature_column.numeric_column` defining feature column representing
weights. It is used to down weight or boost examples during training. It
will be multiplied by the loss of the example.
label_vocabulary: A list of strings represents possible label values. If it
is not given, that means labels are already encoded as integer within
[0, n_classes). If given, labels must be string type and have any value in
`label_vocabulary`. Also there will be errors if vocabulary is not
provided and labels are string.
Returns:
An instance of `_Head` for multi class classification.
Raises:
ValueError: if `n_classes`, `metric_class_ids` or `label_keys` is invalid.
"""
if label_vocabulary is not None and not isinstance(label_vocabulary,
(list, tuple)):
raise ValueError('label_vocabulary should be a list. Given type: {}'.format(
type(label_vocabulary)))
return _MultiClassHeadWithSoftmaxCrossEntropyLoss(n_classes, weight_column,
label_vocabulary) | [
"def",
"_multi_class_head_with_softmax_cross_entropy_loss",
"(",
"n_classes",
",",
"weight_column",
"=",
"None",
",",
"label_vocabulary",
"=",
"None",
")",
":",
"if",
"label_vocabulary",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"label_vocabulary",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"raise",
"ValueError",
"(",
"'label_vocabulary should be a list. Given type: {}'",
".",
"format",
"(",
"type",
"(",
"label_vocabulary",
")",
")",
")",
"return",
"_MultiClassHeadWithSoftmaxCrossEntropyLoss",
"(",
"n_classes",
",",
"weight_column",
",",
"label_vocabulary",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/estimator/canned/head.py#L283-L315 | |
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBCommunication.AdoptFileDesriptor | (self, fd, owns_fd) | return _lldb.SBCommunication_AdoptFileDesriptor(self, fd, owns_fd) | AdoptFileDesriptor(SBCommunication self, int fd, bool owns_fd) -> lldb::ConnectionStatus | AdoptFileDesriptor(SBCommunication self, int fd, bool owns_fd) -> lldb::ConnectionStatus | [
"AdoptFileDesriptor",
"(",
"SBCommunication",
"self",
"int",
"fd",
"bool",
"owns_fd",
")",
"-",
">",
"lldb",
"::",
"ConnectionStatus"
] | def AdoptFileDesriptor(self, fd, owns_fd):
"""AdoptFileDesriptor(SBCommunication self, int fd, bool owns_fd) -> lldb::ConnectionStatus"""
return _lldb.SBCommunication_AdoptFileDesriptor(self, fd, owns_fd) | [
"def",
"AdoptFileDesriptor",
"(",
"self",
",",
"fd",
",",
"owns_fd",
")",
":",
"return",
"_lldb",
".",
"SBCommunication_AdoptFileDesriptor",
"(",
"self",
",",
"fd",
",",
"owns_fd",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L3032-L3034 | |
francinexue/xuefu | b6ff79747a42e020588c0c0a921048e08fe4680c | api/ctpx/ctptd.py | python | CtpTd.onRspFromFutureToBankByFuture | (self, ReqTransferField, RspInfoField, requestId, final) | 期货发起期货资金转银行应答 | 期货发起期货资金转银行应答 | [
"期货发起期货资金转银行应答"
] | def onRspFromFutureToBankByFuture(self, ReqTransferField, RspInfoField, requestId, final):
"""期货发起期货资金转银行应答"""
pass | [
"def",
"onRspFromFutureToBankByFuture",
"(",
"self",
",",
"ReqTransferField",
",",
"RspInfoField",
",",
"requestId",
",",
"final",
")",
":",
"pass"
] | https://github.com/francinexue/xuefu/blob/b6ff79747a42e020588c0c0a921048e08fe4680c/api/ctpx/ctptd.py#L527-L529 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | GetLocalTime | (*args) | return _misc_.GetLocalTime(*args) | GetLocalTime() -> long | GetLocalTime() -> long | [
"GetLocalTime",
"()",
"-",
">",
"long"
] | def GetLocalTime(*args):
"""GetLocalTime() -> long"""
return _misc_.GetLocalTime(*args) | [
"def",
"GetLocalTime",
"(",
"*",
"args",
")",
":",
"return",
"_misc_",
".",
"GetLocalTime",
"(",
"*",
"args",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L4785-L4787 | |
Slicer/Slicer | ba9fadf332cb0303515b68d8d06a344c82e3e3e5 | Modules/Scripted/DICOMLib/DICOMUtils.py | python | refreshDICOMWidget | () | return True | Refresh DICOM browser from database.
It is useful when the database is changed via a database object that is
different from the one stored in the DICOM browser. There may be multiple
database connection (through different database objects) in the same process. | Refresh DICOM browser from database.
It is useful when the database is changed via a database object that is
different from the one stored in the DICOM browser. There may be multiple
database connection (through different database objects) in the same process. | [
"Refresh",
"DICOM",
"browser",
"from",
"database",
".",
"It",
"is",
"useful",
"when",
"the",
"database",
"is",
"changed",
"via",
"a",
"database",
"object",
"that",
"is",
"different",
"from",
"the",
"one",
"stored",
"in",
"the",
"DICOM",
"browser",
".",
"There",
"may",
"be",
"multiple",
"database",
"connection",
"(",
"through",
"different",
"database",
"objects",
")",
"in",
"the",
"same",
"process",
"."
] | def refreshDICOMWidget():
""" Refresh DICOM browser from database.
It is useful when the database is changed via a database object that is
different from the one stored in the DICOM browser. There may be multiple
database connection (through different database objects) in the same process.
"""
try:
slicer.modules.DICOMInstance.browserWidget.dicomBrowser.dicomTableManager().updateTableViews()
except AttributeError:
logging.error('DICOM module or browser cannot be accessed')
return False
return True | [
"def",
"refreshDICOMWidget",
"(",
")",
":",
"try",
":",
"slicer",
".",
"modules",
".",
"DICOMInstance",
".",
"browserWidget",
".",
"dicomBrowser",
".",
"dicomTableManager",
"(",
")",
".",
"updateTableViews",
"(",
")",
"except",
"AttributeError",
":",
"logging",
".",
"error",
"(",
"'DICOM module or browser cannot be accessed'",
")",
"return",
"False",
"return",
"True"
] | https://github.com/Slicer/Slicer/blob/ba9fadf332cb0303515b68d8d06a344c82e3e3e5/Modules/Scripted/DICOMLib/DICOMUtils.py#L672-L683 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/grid.py | python | GridCellEditor.IsAcceptedKey | (*args, **kwargs) | return _grid.GridCellEditor_IsAcceptedKey(*args, **kwargs) | IsAcceptedKey(self, KeyEvent event) -> bool | IsAcceptedKey(self, KeyEvent event) -> bool | [
"IsAcceptedKey",
"(",
"self",
"KeyEvent",
"event",
")",
"-",
">",
"bool"
] | def IsAcceptedKey(*args, **kwargs):
"""IsAcceptedKey(self, KeyEvent event) -> bool"""
return _grid.GridCellEditor_IsAcceptedKey(*args, **kwargs) | [
"def",
"IsAcceptedKey",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"GridCellEditor_IsAcceptedKey",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/grid.py#L320-L322 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/ftplib.py | python | FTP.rename | (self, fromname, toname) | return self.voidcmd('RNTO ' + toname) | Rename a file. | Rename a file. | [
"Rename",
"a",
"file",
"."
] | def rename(self, fromname, toname):
'''Rename a file.'''
resp = self.sendcmd('RNFR ' + fromname)
if resp[0] != '3':
raise error_reply(resp)
return self.voidcmd('RNTO ' + toname) | [
"def",
"rename",
"(",
"self",
",",
"fromname",
",",
"toname",
")",
":",
"resp",
"=",
"self",
".",
"sendcmd",
"(",
"'RNFR '",
"+",
"fromname",
")",
"if",
"resp",
"[",
"0",
"]",
"!=",
"'3'",
":",
"raise",
"error_reply",
"(",
"resp",
")",
"return",
"self",
".",
"voidcmd",
"(",
"'RNTO '",
"+",
"toname",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/ftplib.py#L599-L604 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/backend_config.py | python | floatx | () | return _FLOATX | Returns the default float type, as a string.
E.g. 'float16', 'float32', 'float64'.
Returns:
String, the current default float type.
Example:
```python
keras.backend.floatx() >>> 'float32'
``` | Returns the default float type, as a string. | [
"Returns",
"the",
"default",
"float",
"type",
"as",
"a",
"string",
"."
] | def floatx():
"""Returns the default float type, as a string.
E.g. 'float16', 'float32', 'float64'.
Returns:
String, the current default float type.
Example:
```python
keras.backend.floatx() >>> 'float32'
```
"""
return _FLOATX | [
"def",
"floatx",
"(",
")",
":",
"return",
"_FLOATX"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/backend_config.py#L61-L74 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/matrix-diagonal-sum.py | python | Solution.diagonalSum | (self, mat) | return sum(mat[i][i]+mat[~i][i] for i in xrange(len(mat))) - (mat[len(mat)//2][len(mat)//2] if len(mat)%2 == 1 else 0) | :type mat: List[List[int]]
:rtype: int | :type mat: List[List[int]]
:rtype: int | [
":",
"type",
"mat",
":",
"List",
"[",
"List",
"[",
"int",
"]]",
":",
"rtype",
":",
"int"
] | def diagonalSum(self, mat):
"""
:type mat: List[List[int]]
:rtype: int
"""
return sum(mat[i][i]+mat[~i][i] for i in xrange(len(mat))) - (mat[len(mat)//2][len(mat)//2] if len(mat)%2 == 1 else 0) | [
"def",
"diagonalSum",
"(",
"self",
",",
"mat",
")",
":",
"return",
"sum",
"(",
"mat",
"[",
"i",
"]",
"[",
"i",
"]",
"+",
"mat",
"[",
"~",
"i",
"]",
"[",
"i",
"]",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"mat",
")",
")",
")",
"-",
"(",
"mat",
"[",
"len",
"(",
"mat",
")",
"//",
"2",
"]",
"[",
"len",
"(",
"mat",
")",
"//",
"2",
"]",
"if",
"len",
"(",
"mat",
")",
"%",
"2",
"==",
"1",
"else",
"0",
")"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/matrix-diagonal-sum.py#L5-L10 | |
libornovax/master_thesis_code | 6eca474ed3cae673afde010caef338cf7349f839 | scripts/compute_pr_curve.py | python | PRPlotter._add_curve | (self, tps, fps, fns, fnsr, fpsd, category) | Puts a new PR curve into the plot.
Input:
tps: np.array of true positives' counts (length N)
fps: np.array of false positives' counts (length N)
fns: np.array of false negatives' counts (length N)
fnsr: np.array of false negatives' counts on required gt (length N)
fpsd: np.array of false negatives' counts outside of don't care regions (length N)
category: Object category (label), which the curve corresponds to | Puts a new PR curve into the plot. | [
"Puts",
"a",
"new",
"PR",
"curve",
"into",
"the",
"plot",
"."
] | def _add_curve(self, tps, fps, fns, fnsr, fpsd, category):
"""
Puts a new PR curve into the plot.
Input:
tps: np.array of true positives' counts (length N)
fps: np.array of false positives' counts (length N)
fns: np.array of false negatives' counts (length N)
fnsr: np.array of false negatives' counts on required gt (length N)
fpsd: np.array of false negatives' counts outside of don't care regions (length N)
category: Object category (label), which the curve corresponds to
"""
# Compute the precision and recall for the PR curve
precisions, recalls = pr_curve_points(tps, fps, fns)
precisionsr, recallsr = pr_curve_points(tps, fps, fnsr)
precisionsd, recallsd = pr_curve_points(tps, fpsd, fns)
precisionsrd, recallsrd = pr_curve_points(tps, fpsd, fnsr)
plt.plot(precisions, recalls, label=category, color=COLORS[category], linewidth=2)
plt.plot(precisionsd, recallsd, label=category+' - don\'t care', color=COLORS[category])
plt.plot(precisionsr, recallsr, label=category+' - required', color=COLORS[category],
linestyle='--')
plt.plot(precisionsrd, recallsrd, label=category+' - required, don\'t care',
color=COLORS[category], linestyle=':')
self.categories.append(category)
self.precisions.append(precisions)
self.recalls.append(recalls)
self.precisionsr.append(precisionsr)
self.recallsr.append(recallsr)
self.precisionsd.append(precisionsd)
self.recallsd.append(recallsd)
self.precisionsrd.append(precisionsrd)
self.recallsrd.append(recallsrd)
self.tps.append(tps)
self.fps.append(fps)
self.fns.append(fns)
self.fnsr.append(fnsr)
self.fpsd.append(fpsd) | [
"def",
"_add_curve",
"(",
"self",
",",
"tps",
",",
"fps",
",",
"fns",
",",
"fnsr",
",",
"fpsd",
",",
"category",
")",
":",
"# Compute the precision and recall for the PR curve",
"precisions",
",",
"recalls",
"=",
"pr_curve_points",
"(",
"tps",
",",
"fps",
",",
"fns",
")",
"precisionsr",
",",
"recallsr",
"=",
"pr_curve_points",
"(",
"tps",
",",
"fps",
",",
"fnsr",
")",
"precisionsd",
",",
"recallsd",
"=",
"pr_curve_points",
"(",
"tps",
",",
"fpsd",
",",
"fns",
")",
"precisionsrd",
",",
"recallsrd",
"=",
"pr_curve_points",
"(",
"tps",
",",
"fpsd",
",",
"fnsr",
")",
"plt",
".",
"plot",
"(",
"precisions",
",",
"recalls",
",",
"label",
"=",
"category",
",",
"color",
"=",
"COLORS",
"[",
"category",
"]",
",",
"linewidth",
"=",
"2",
")",
"plt",
".",
"plot",
"(",
"precisionsd",
",",
"recallsd",
",",
"label",
"=",
"category",
"+",
"' - don\\'t care'",
",",
"color",
"=",
"COLORS",
"[",
"category",
"]",
")",
"plt",
".",
"plot",
"(",
"precisionsr",
",",
"recallsr",
",",
"label",
"=",
"category",
"+",
"' - required'",
",",
"color",
"=",
"COLORS",
"[",
"category",
"]",
",",
"linestyle",
"=",
"'--'",
")",
"plt",
".",
"plot",
"(",
"precisionsrd",
",",
"recallsrd",
",",
"label",
"=",
"category",
"+",
"' - required, don\\'t care'",
",",
"color",
"=",
"COLORS",
"[",
"category",
"]",
",",
"linestyle",
"=",
"':'",
")",
"self",
".",
"categories",
".",
"append",
"(",
"category",
")",
"self",
".",
"precisions",
".",
"append",
"(",
"precisions",
")",
"self",
".",
"recalls",
".",
"append",
"(",
"recalls",
")",
"self",
".",
"precisionsr",
".",
"append",
"(",
"precisionsr",
")",
"self",
".",
"recallsr",
".",
"append",
"(",
"recallsr",
")",
"self",
".",
"precisionsd",
".",
"append",
"(",
"precisionsd",
")",
"self",
".",
"recallsd",
".",
"append",
"(",
"recallsd",
")",
"self",
".",
"precisionsrd",
".",
"append",
"(",
"precisionsrd",
")",
"self",
".",
"recallsrd",
".",
"append",
"(",
"recallsrd",
")",
"self",
".",
"tps",
".",
"append",
"(",
"tps",
")",
"self",
".",
"fps",
".",
"append",
"(",
"fps",
")",
"self",
".",
"fns",
".",
"append",
"(",
"fns",
")",
"self",
".",
"fnsr",
".",
"append",
"(",
"fnsr",
")",
"self",
".",
"fpsd",
".",
"append",
"(",
"fpsd",
")"
] | https://github.com/libornovax/master_thesis_code/blob/6eca474ed3cae673afde010caef338cf7349f839/scripts/compute_pr_curve.py#L238-L276 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/frame.py | python | DataFrame.combine | (self, other, func, fill_value=None, overwrite=True) | return self._constructor(result, index=new_index,
columns=new_columns) | Perform column-wise combine with another DataFrame based on a
passed function.
Combines a DataFrame with `other` DataFrame using `func`
to element-wise combine columns. The row and column indexes of the
resulting DataFrame will be the union of the two.
Parameters
----------
other : DataFrame
The DataFrame to merge column-wise.
func : function
Function that takes two series as inputs and return a Series or a
scalar. Used to merge the two dataframes column by columns.
fill_value : scalar value, default None
The value to fill NaNs with prior to passing any column to the
merge func.
overwrite : boolean, default True
If True, columns in `self` that do not exist in `other` will be
overwritten with NaNs.
Returns
-------
result : DataFrame
See Also
--------
DataFrame.combine_first : Combine two DataFrame objects and default to
non-null values in frame calling the method.
Examples
--------
Combine using a simple function that chooses the smaller column.
>>> df1 = pd.DataFrame({'A': [0, 0], 'B': [4, 4]})
>>> df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3]})
>>> take_smaller = lambda s1, s2: s1 if s1.sum() < s2.sum() else s2
>>> df1.combine(df2, take_smaller)
A B
0 0 3
1 0 3
Example using a true element-wise combine function.
>>> df1 = pd.DataFrame({'A': [5, 0], 'B': [2, 4]})
>>> df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3]})
>>> df1.combine(df2, np.minimum)
A B
0 1 2
1 0 3
Using `fill_value` fills Nones prior to passing the column to the
merge function.
>>> df1 = pd.DataFrame({'A': [0, 0], 'B': [None, 4]})
>>> df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3]})
>>> df1.combine(df2, take_smaller, fill_value=-5)
A B
0 0 -5.0
1 0 4.0
However, if the same element in both dataframes is None, that None
is preserved
>>> df1 = pd.DataFrame({'A': [0, 0], 'B': [None, 4]})
>>> df2 = pd.DataFrame({'A': [1, 1], 'B': [None, 3]})
>>> df1.combine(df2, take_smaller, fill_value=-5)
A B
0 0 NaN
1 0 3.0
Example that demonstrates the use of `overwrite` and behavior when
the axis differ between the dataframes.
>>> df1 = pd.DataFrame({'A': [0, 0], 'B': [4, 4]})
>>> df2 = pd.DataFrame({'B': [3, 3], 'C': [-10, 1],}, index=[1, 2])
>>> df1.combine(df2, take_smaller)
A B C
0 NaN NaN NaN
1 NaN 3.0 -10.0
2 NaN 3.0 1.0
>>> df1.combine(df2, take_smaller, overwrite=False)
A B C
0 0.0 NaN NaN
1 0.0 3.0 -10.0
2 NaN 3.0 1.0
Demonstrating the preference of the passed in dataframe.
>>> df2 = pd.DataFrame({'B': [3, 3], 'C': [1, 1],}, index=[1, 2])
>>> df2.combine(df1, take_smaller)
A B C
0 0.0 NaN NaN
1 0.0 3.0 NaN
2 NaN 3.0 NaN
>>> df2.combine(df1, take_smaller, overwrite=False)
A B C
0 0.0 NaN NaN
1 0.0 3.0 1.0
2 NaN 3.0 1.0 | Perform column-wise combine with another DataFrame based on a
passed function. | [
"Perform",
"column",
"-",
"wise",
"combine",
"with",
"another",
"DataFrame",
"based",
"on",
"a",
"passed",
"function",
"."
] | def combine(self, other, func, fill_value=None, overwrite=True):
"""
Perform column-wise combine with another DataFrame based on a
passed function.
Combines a DataFrame with `other` DataFrame using `func`
to element-wise combine columns. The row and column indexes of the
resulting DataFrame will be the union of the two.
Parameters
----------
other : DataFrame
The DataFrame to merge column-wise.
func : function
Function that takes two series as inputs and return a Series or a
scalar. Used to merge the two dataframes column by columns.
fill_value : scalar value, default None
The value to fill NaNs with prior to passing any column to the
merge func.
overwrite : boolean, default True
If True, columns in `self` that do not exist in `other` will be
overwritten with NaNs.
Returns
-------
result : DataFrame
See Also
--------
DataFrame.combine_first : Combine two DataFrame objects and default to
non-null values in frame calling the method.
Examples
--------
Combine using a simple function that chooses the smaller column.
>>> df1 = pd.DataFrame({'A': [0, 0], 'B': [4, 4]})
>>> df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3]})
>>> take_smaller = lambda s1, s2: s1 if s1.sum() < s2.sum() else s2
>>> df1.combine(df2, take_smaller)
A B
0 0 3
1 0 3
Example using a true element-wise combine function.
>>> df1 = pd.DataFrame({'A': [5, 0], 'B': [2, 4]})
>>> df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3]})
>>> df1.combine(df2, np.minimum)
A B
0 1 2
1 0 3
Using `fill_value` fills Nones prior to passing the column to the
merge function.
>>> df1 = pd.DataFrame({'A': [0, 0], 'B': [None, 4]})
>>> df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3]})
>>> df1.combine(df2, take_smaller, fill_value=-5)
A B
0 0 -5.0
1 0 4.0
However, if the same element in both dataframes is None, that None
is preserved
>>> df1 = pd.DataFrame({'A': [0, 0], 'B': [None, 4]})
>>> df2 = pd.DataFrame({'A': [1, 1], 'B': [None, 3]})
>>> df1.combine(df2, take_smaller, fill_value=-5)
A B
0 0 NaN
1 0 3.0
Example that demonstrates the use of `overwrite` and behavior when
the axis differ between the dataframes.
>>> df1 = pd.DataFrame({'A': [0, 0], 'B': [4, 4]})
>>> df2 = pd.DataFrame({'B': [3, 3], 'C': [-10, 1],}, index=[1, 2])
>>> df1.combine(df2, take_smaller)
A B C
0 NaN NaN NaN
1 NaN 3.0 -10.0
2 NaN 3.0 1.0
>>> df1.combine(df2, take_smaller, overwrite=False)
A B C
0 0.0 NaN NaN
1 0.0 3.0 -10.0
2 NaN 3.0 1.0
Demonstrating the preference of the passed in dataframe.
>>> df2 = pd.DataFrame({'B': [3, 3], 'C': [1, 1],}, index=[1, 2])
>>> df2.combine(df1, take_smaller)
A B C
0 0.0 NaN NaN
1 0.0 3.0 NaN
2 NaN 3.0 NaN
>>> df2.combine(df1, take_smaller, overwrite=False)
A B C
0 0.0 NaN NaN
1 0.0 3.0 1.0
2 NaN 3.0 1.0
"""
other_idxlen = len(other.index) # save for compare
this, other = self.align(other, copy=False)
new_index = this.index
if other.empty and len(new_index) == len(self.index):
return self.copy()
if self.empty and len(other) == other_idxlen:
return other.copy()
# sorts if possible
new_columns = this.columns.union(other.columns)
do_fill = fill_value is not None
result = {}
for col in new_columns:
series = this[col]
otherSeries = other[col]
this_dtype = series.dtype
other_dtype = otherSeries.dtype
this_mask = isna(series)
other_mask = isna(otherSeries)
# don't overwrite columns unecessarily
# DO propagate if this column is not in the intersection
if not overwrite and other_mask.all():
result[col] = this[col].copy()
continue
if do_fill:
series = series.copy()
otherSeries = otherSeries.copy()
series[this_mask] = fill_value
otherSeries[other_mask] = fill_value
if col not in self.columns:
# If self DataFrame does not have col in other DataFrame,
# try to promote series, which is all NaN, as other_dtype.
new_dtype = other_dtype
try:
series = series.astype(new_dtype, copy=False)
except ValueError:
# e.g. new_dtype is integer types
pass
else:
# if we have different dtypes, possibly promote
new_dtype = find_common_type([this_dtype, other_dtype])
if not is_dtype_equal(this_dtype, new_dtype):
series = series.astype(new_dtype)
if not is_dtype_equal(other_dtype, new_dtype):
otherSeries = otherSeries.astype(new_dtype)
arr = func(series, otherSeries)
arr = maybe_downcast_to_dtype(arr, this_dtype)
result[col] = arr
# convert_objects just in case
return self._constructor(result, index=new_index,
columns=new_columns) | [
"def",
"combine",
"(",
"self",
",",
"other",
",",
"func",
",",
"fill_value",
"=",
"None",
",",
"overwrite",
"=",
"True",
")",
":",
"other_idxlen",
"=",
"len",
"(",
"other",
".",
"index",
")",
"# save for compare",
"this",
",",
"other",
"=",
"self",
".",
"align",
"(",
"other",
",",
"copy",
"=",
"False",
")",
"new_index",
"=",
"this",
".",
"index",
"if",
"other",
".",
"empty",
"and",
"len",
"(",
"new_index",
")",
"==",
"len",
"(",
"self",
".",
"index",
")",
":",
"return",
"self",
".",
"copy",
"(",
")",
"if",
"self",
".",
"empty",
"and",
"len",
"(",
"other",
")",
"==",
"other_idxlen",
":",
"return",
"other",
".",
"copy",
"(",
")",
"# sorts if possible",
"new_columns",
"=",
"this",
".",
"columns",
".",
"union",
"(",
"other",
".",
"columns",
")",
"do_fill",
"=",
"fill_value",
"is",
"not",
"None",
"result",
"=",
"{",
"}",
"for",
"col",
"in",
"new_columns",
":",
"series",
"=",
"this",
"[",
"col",
"]",
"otherSeries",
"=",
"other",
"[",
"col",
"]",
"this_dtype",
"=",
"series",
".",
"dtype",
"other_dtype",
"=",
"otherSeries",
".",
"dtype",
"this_mask",
"=",
"isna",
"(",
"series",
")",
"other_mask",
"=",
"isna",
"(",
"otherSeries",
")",
"# don't overwrite columns unecessarily",
"# DO propagate if this column is not in the intersection",
"if",
"not",
"overwrite",
"and",
"other_mask",
".",
"all",
"(",
")",
":",
"result",
"[",
"col",
"]",
"=",
"this",
"[",
"col",
"]",
".",
"copy",
"(",
")",
"continue",
"if",
"do_fill",
":",
"series",
"=",
"series",
".",
"copy",
"(",
")",
"otherSeries",
"=",
"otherSeries",
".",
"copy",
"(",
")",
"series",
"[",
"this_mask",
"]",
"=",
"fill_value",
"otherSeries",
"[",
"other_mask",
"]",
"=",
"fill_value",
"if",
"col",
"not",
"in",
"self",
".",
"columns",
":",
"# If self DataFrame does not have col in other DataFrame,",
"# try to promote series, which is all NaN, as other_dtype.",
"new_dtype",
"=",
"other_dtype",
"try",
":",
"series",
"=",
"series",
".",
"astype",
"(",
"new_dtype",
",",
"copy",
"=",
"False",
")",
"except",
"ValueError",
":",
"# e.g. new_dtype is integer types",
"pass",
"else",
":",
"# if we have different dtypes, possibly promote",
"new_dtype",
"=",
"find_common_type",
"(",
"[",
"this_dtype",
",",
"other_dtype",
"]",
")",
"if",
"not",
"is_dtype_equal",
"(",
"this_dtype",
",",
"new_dtype",
")",
":",
"series",
"=",
"series",
".",
"astype",
"(",
"new_dtype",
")",
"if",
"not",
"is_dtype_equal",
"(",
"other_dtype",
",",
"new_dtype",
")",
":",
"otherSeries",
"=",
"otherSeries",
".",
"astype",
"(",
"new_dtype",
")",
"arr",
"=",
"func",
"(",
"series",
",",
"otherSeries",
")",
"arr",
"=",
"maybe_downcast_to_dtype",
"(",
"arr",
",",
"this_dtype",
")",
"result",
"[",
"col",
"]",
"=",
"arr",
"# convert_objects just in case",
"return",
"self",
".",
"_constructor",
"(",
"result",
",",
"index",
"=",
"new_index",
",",
"columns",
"=",
"new_columns",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/frame.py#L5122-L5288 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py2/numpy/lib/nanfunctions.py | python | nanmean | (a, axis=None, dtype=None, out=None, keepdims=np._NoValue) | return avg | Compute the arithmetic mean along the specified axis, ignoring NaNs.
Returns the average of the array elements. The average is taken over
the flattened array by default, otherwise over the specified axis.
`float64` intermediate and return values are used for integer inputs.
For all-NaN slices, NaN is returned and a `RuntimeWarning` is raised.
.. versionadded:: 1.8.0
Parameters
----------
a : array_like
Array containing numbers whose mean is desired. If `a` is not an
array, a conversion is attempted.
axis : {int, tuple of int, None}, optional
Axis or axes along which the means are computed. The default is to compute
the mean of the flattened array.
dtype : data-type, optional
Type to use in computing the mean. For integer inputs, the default
is `float64`; for inexact inputs, it is the same as the input
dtype.
out : ndarray, optional
Alternate output array in which to place the result. The default
is ``None``; if provided, it must have the same shape as the
expected output, but the type will be cast if necessary. See
`doc.ufuncs` for details.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the original `a`.
If the value is anything but the default, then
`keepdims` will be passed through to the `mean` or `sum` methods
of sub-classes of `ndarray`. If the sub-classes methods
does not implement `keepdims` any exceptions will be raised.
Returns
-------
m : ndarray, see dtype parameter above
If `out=None`, returns a new array containing the mean values,
otherwise a reference to the output array is returned. Nan is
returned for slices that contain only NaNs.
See Also
--------
average : Weighted average
mean : Arithmetic mean taken while not ignoring NaNs
var, nanvar
Notes
-----
The arithmetic mean is the sum of the non-NaN elements along the axis
divided by the number of non-NaN elements.
Note that for floating-point input, the mean is computed using the same
precision the input has. Depending on the input data, this can cause
the results to be inaccurate, especially for `float32`. Specifying a
higher-precision accumulator using the `dtype` keyword can alleviate
this issue.
Examples
--------
>>> a = np.array([[1, np.nan], [3, 4]])
>>> np.nanmean(a)
2.6666666666666665
>>> np.nanmean(a, axis=0)
array([ 2., 4.])
>>> np.nanmean(a, axis=1)
array([ 1., 3.5]) | Compute the arithmetic mean along the specified axis, ignoring NaNs. | [
"Compute",
"the",
"arithmetic",
"mean",
"along",
"the",
"specified",
"axis",
"ignoring",
"NaNs",
"."
] | def nanmean(a, axis=None, dtype=None, out=None, keepdims=np._NoValue):
"""
Compute the arithmetic mean along the specified axis, ignoring NaNs.
Returns the average of the array elements. The average is taken over
the flattened array by default, otherwise over the specified axis.
`float64` intermediate and return values are used for integer inputs.
For all-NaN slices, NaN is returned and a `RuntimeWarning` is raised.
.. versionadded:: 1.8.0
Parameters
----------
a : array_like
Array containing numbers whose mean is desired. If `a` is not an
array, a conversion is attempted.
axis : {int, tuple of int, None}, optional
Axis or axes along which the means are computed. The default is to compute
the mean of the flattened array.
dtype : data-type, optional
Type to use in computing the mean. For integer inputs, the default
is `float64`; for inexact inputs, it is the same as the input
dtype.
out : ndarray, optional
Alternate output array in which to place the result. The default
is ``None``; if provided, it must have the same shape as the
expected output, but the type will be cast if necessary. See
`doc.ufuncs` for details.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the original `a`.
If the value is anything but the default, then
`keepdims` will be passed through to the `mean` or `sum` methods
of sub-classes of `ndarray`. If the sub-classes methods
does not implement `keepdims` any exceptions will be raised.
Returns
-------
m : ndarray, see dtype parameter above
If `out=None`, returns a new array containing the mean values,
otherwise a reference to the output array is returned. Nan is
returned for slices that contain only NaNs.
See Also
--------
average : Weighted average
mean : Arithmetic mean taken while not ignoring NaNs
var, nanvar
Notes
-----
The arithmetic mean is the sum of the non-NaN elements along the axis
divided by the number of non-NaN elements.
Note that for floating-point input, the mean is computed using the same
precision the input has. Depending on the input data, this can cause
the results to be inaccurate, especially for `float32`. Specifying a
higher-precision accumulator using the `dtype` keyword can alleviate
this issue.
Examples
--------
>>> a = np.array([[1, np.nan], [3, 4]])
>>> np.nanmean(a)
2.6666666666666665
>>> np.nanmean(a, axis=0)
array([ 2., 4.])
>>> np.nanmean(a, axis=1)
array([ 1., 3.5])
"""
arr, mask = _replace_nan(a, 0)
if mask is None:
return np.mean(arr, axis=axis, dtype=dtype, out=out, keepdims=keepdims)
if dtype is not None:
dtype = np.dtype(dtype)
if dtype is not None and not issubclass(dtype.type, np.inexact):
raise TypeError("If a is inexact, then dtype must be inexact")
if out is not None and not issubclass(out.dtype.type, np.inexact):
raise TypeError("If a is inexact, then out must be inexact")
cnt = np.sum(~mask, axis=axis, dtype=np.intp, keepdims=keepdims)
tot = np.sum(arr, axis=axis, dtype=dtype, out=out, keepdims=keepdims)
avg = _divide_by_count(tot, cnt, out=out)
isbad = (cnt == 0)
if isbad.any():
warnings.warn("Mean of empty slice", RuntimeWarning, stacklevel=2)
# NaN is the only possible bad value, so no further
# action is needed to handle bad results.
return avg | [
"def",
"nanmean",
"(",
"a",
",",
"axis",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"out",
"=",
"None",
",",
"keepdims",
"=",
"np",
".",
"_NoValue",
")",
":",
"arr",
",",
"mask",
"=",
"_replace_nan",
"(",
"a",
",",
"0",
")",
"if",
"mask",
"is",
"None",
":",
"return",
"np",
".",
"mean",
"(",
"arr",
",",
"axis",
"=",
"axis",
",",
"dtype",
"=",
"dtype",
",",
"out",
"=",
"out",
",",
"keepdims",
"=",
"keepdims",
")",
"if",
"dtype",
"is",
"not",
"None",
":",
"dtype",
"=",
"np",
".",
"dtype",
"(",
"dtype",
")",
"if",
"dtype",
"is",
"not",
"None",
"and",
"not",
"issubclass",
"(",
"dtype",
".",
"type",
",",
"np",
".",
"inexact",
")",
":",
"raise",
"TypeError",
"(",
"\"If a is inexact, then dtype must be inexact\"",
")",
"if",
"out",
"is",
"not",
"None",
"and",
"not",
"issubclass",
"(",
"out",
".",
"dtype",
".",
"type",
",",
"np",
".",
"inexact",
")",
":",
"raise",
"TypeError",
"(",
"\"If a is inexact, then out must be inexact\"",
")",
"cnt",
"=",
"np",
".",
"sum",
"(",
"~",
"mask",
",",
"axis",
"=",
"axis",
",",
"dtype",
"=",
"np",
".",
"intp",
",",
"keepdims",
"=",
"keepdims",
")",
"tot",
"=",
"np",
".",
"sum",
"(",
"arr",
",",
"axis",
"=",
"axis",
",",
"dtype",
"=",
"dtype",
",",
"out",
"=",
"out",
",",
"keepdims",
"=",
"keepdims",
")",
"avg",
"=",
"_divide_by_count",
"(",
"tot",
",",
"cnt",
",",
"out",
"=",
"out",
")",
"isbad",
"=",
"(",
"cnt",
"==",
"0",
")",
"if",
"isbad",
".",
"any",
"(",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Mean of empty slice\"",
",",
"RuntimeWarning",
",",
"stacklevel",
"=",
"2",
")",
"# NaN is the only possible bad value, so no further",
"# action is needed to handle bad results.",
"return",
"avg"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/lib/nanfunctions.py#L829-L923 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/apitools/apitools/gen/gen_client_lib.py | python | DescriptorGenerator.WriteIntermediateInit | (self, out) | Write a simple __init__.py for an intermediate directory. | Write a simple __init__.py for an intermediate directory. | [
"Write",
"a",
"simple",
"__init__",
".",
"py",
"for",
"an",
"intermediate",
"directory",
"."
] | def WriteIntermediateInit(self, out):
"""Write a simple __init__.py for an intermediate directory."""
printer = self._GetPrinter(out)
printer('#!/usr/bin/env python')
printer('"""Shared __init__.py for apitools."""')
printer()
printer('from pkgutil import extend_path')
printer('__path__ = extend_path(__path__, __name__)') | [
"def",
"WriteIntermediateInit",
"(",
"self",
",",
"out",
")",
":",
"printer",
"=",
"self",
".",
"_GetPrinter",
"(",
"out",
")",
"printer",
"(",
"'#!/usr/bin/env python'",
")",
"printer",
"(",
"'\"\"\"Shared __init__.py for apitools.\"\"\"'",
")",
"printer",
"(",
")",
"printer",
"(",
"'from pkgutil import extend_path'",
")",
"printer",
"(",
"'__path__ = extend_path(__path__, __name__)'",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/apitools/apitools/gen/gen_client_lib.py#L174-L181 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/ultimatelistctrl.py | python | UltimateListCtrl.GetFirstGradientColour | (self) | return self._mainWin.GetFirstGradientColour() | Returns the first gradient colour for gradient-style selections. | Returns the first gradient colour for gradient-style selections. | [
"Returns",
"the",
"first",
"gradient",
"colour",
"for",
"gradient",
"-",
"style",
"selections",
"."
] | def GetFirstGradientColour(self):
""" Returns the first gradient colour for gradient-style selections. """
return self._mainWin.GetFirstGradientColour() | [
"def",
"GetFirstGradientColour",
"(",
"self",
")",
":",
"return",
"self",
".",
"_mainWin",
".",
"GetFirstGradientColour",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L13181-L13184 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros_comm/rosbag/src/rosbag/bag.py | python | Bag.write | (self, topic, msg, t=None, raw=False) | Write a message to the bag.
@param topic: name of topic
@type topic: str
@param msg: message to add to bag, or tuple (if raw)
@type msg: Message or tuple of raw message data
@param t: ROS time of message publication, if None specifed, use current time [optional]
@type t: U{genpy.Time}
@param raw: if True, msg is in raw format, i.e. (msg_type, serialized_bytes, md5sum, pytype)
@type raw: bool
@raise ValueError: if arguments are invalid or bag is closed | Write a message to the bag. | [
"Write",
"a",
"message",
"to",
"the",
"bag",
"."
] | def write(self, topic, msg, t=None, raw=False):
"""
Write a message to the bag.
@param topic: name of topic
@type topic: str
@param msg: message to add to bag, or tuple (if raw)
@type msg: Message or tuple of raw message data
@param t: ROS time of message publication, if None specifed, use current time [optional]
@type t: U{genpy.Time}
@param raw: if True, msg is in raw format, i.e. (msg_type, serialized_bytes, md5sum, pytype)
@type raw: bool
@raise ValueError: if arguments are invalid or bag is closed
"""
if not self._file:
raise ValueError('I/O operation on closed bag')
if not topic:
raise ValueError('topic is invalid')
if not msg:
raise ValueError('msg is invalid')
if t is None:
t = genpy.Time.from_sec(time.time())
# Seek to end (in case previous operation was a read)
self._file.seek(0, os.SEEK_END)
# Open a chunk, if needed
if not self._chunk_open:
self._start_writing_chunk(t)
# Unpack raw
if raw:
if len(msg) == 5:
msg_type, serialized_bytes, md5sum, pos, pytype = msg
elif len(msg) == 4:
msg_type, serialized_bytes, md5sum, pytype = msg
else:
raise ValueError('msg must be of length 4 or 5')
# Write connection record, if necessary (currently using a connection per topic; ignoring message connection header)
if topic in self._topic_connections:
connection_info = self._topic_connections[topic]
conn_id = connection_info.id
else:
conn_id = len(self._connections)
if raw:
if pytype is None:
try:
pytype = genpy.message.get_message_class(msg_type)
except Exception:
pytype = None
if pytype is None:
raise ROSBagException('cannot locate message class and no message class provided for [%s]' % msg_type)
if pytype._md5sum != md5sum:
print('WARNING: md5sum of loaded type [%s] does not match that specified' % msg_type, file=sys.stderr)
#raise ROSBagException('md5sum of loaded type does not match that of data being recorded')
header = { 'topic' : topic, 'type' : msg_type, 'md5sum' : md5sum, 'message_definition' : pytype._full_text }
else:
if issubclass(msg.__class__, google.protobuf.message.Message):
roslib.message.add_rosmsg_interface_for_protobuf(msg.__class__)
header = { 'topic' : topic, 'type' : msg.__class__._type, 'md5sum' : msg.__class__._md5sum, 'message_definition' : 'protobuf' }
else:
header = { 'topic' : topic, 'type' : msg.__class__._type, 'md5sum' : msg.__class__._md5sum, 'message_definition' : msg._full_text }
connection_info = _ConnectionInfo(conn_id, topic, header)
self._write_connection_record(connection_info)
self._connections[conn_id] = connection_info
self._topic_connections[topic] = connection_info
# Create an index entry
index_entry = _IndexEntry200(t, self._curr_chunk_info.pos, self._get_chunk_offset())
# Update the indexes and current chunk info
if conn_id not in self._curr_chunk_connection_indexes:
# This is the first message on this connection in the chunk
self._curr_chunk_connection_indexes[conn_id] = [index_entry]
self._curr_chunk_info.connection_counts[conn_id] = 1
else:
curr_chunk_connection_index = self._curr_chunk_connection_indexes[conn_id]
if index_entry >= curr_chunk_connection_index[-1]:
# Test if we're writing chronologically. Can skip binary search if so.
curr_chunk_connection_index.append(index_entry)
else:
bisect.insort_right(curr_chunk_connection_index, index_entry)
self._curr_chunk_info.connection_counts[conn_id] += 1
if conn_id not in self._connection_indexes:
self._connection_indexes[conn_id] = [index_entry]
else:
bisect.insort_right(self._connection_indexes[conn_id], index_entry)
# Update the chunk start/end times
if t > self._curr_chunk_info.end_time:
self._curr_chunk_info.end_time = t
elif t < self._curr_chunk_info.start_time:
self._curr_chunk_info.start_time = t
if not raw:
# Serialize the message to the buffer
self._buffer.seek(0)
self._buffer.truncate(0)
msg.serialize(self._buffer)
serialized_bytes = self._buffer.getvalue()
# Write message data record
self._write_message_data_record(conn_id, t, serialized_bytes)
# Check if we want to stop this chunk
chunk_size = self._get_chunk_offset()
if chunk_size > self._chunk_threshold:
self._stop_writing_chunk() | [
"def",
"write",
"(",
"self",
",",
"topic",
",",
"msg",
",",
"t",
"=",
"None",
",",
"raw",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"_file",
":",
"raise",
"ValueError",
"(",
"'I/O operation on closed bag'",
")",
"if",
"not",
"topic",
":",
"raise",
"ValueError",
"(",
"'topic is invalid'",
")",
"if",
"not",
"msg",
":",
"raise",
"ValueError",
"(",
"'msg is invalid'",
")",
"if",
"t",
"is",
"None",
":",
"t",
"=",
"genpy",
".",
"Time",
".",
"from_sec",
"(",
"time",
".",
"time",
"(",
")",
")",
"# Seek to end (in case previous operation was a read)",
"self",
".",
"_file",
".",
"seek",
"(",
"0",
",",
"os",
".",
"SEEK_END",
")",
"# Open a chunk, if needed",
"if",
"not",
"self",
".",
"_chunk_open",
":",
"self",
".",
"_start_writing_chunk",
"(",
"t",
")",
"# Unpack raw",
"if",
"raw",
":",
"if",
"len",
"(",
"msg",
")",
"==",
"5",
":",
"msg_type",
",",
"serialized_bytes",
",",
"md5sum",
",",
"pos",
",",
"pytype",
"=",
"msg",
"elif",
"len",
"(",
"msg",
")",
"==",
"4",
":",
"msg_type",
",",
"serialized_bytes",
",",
"md5sum",
",",
"pytype",
"=",
"msg",
"else",
":",
"raise",
"ValueError",
"(",
"'msg must be of length 4 or 5'",
")",
"# Write connection record, if necessary (currently using a connection per topic; ignoring message connection header)",
"if",
"topic",
"in",
"self",
".",
"_topic_connections",
":",
"connection_info",
"=",
"self",
".",
"_topic_connections",
"[",
"topic",
"]",
"conn_id",
"=",
"connection_info",
".",
"id",
"else",
":",
"conn_id",
"=",
"len",
"(",
"self",
".",
"_connections",
")",
"if",
"raw",
":",
"if",
"pytype",
"is",
"None",
":",
"try",
":",
"pytype",
"=",
"genpy",
".",
"message",
".",
"get_message_class",
"(",
"msg_type",
")",
"except",
"Exception",
":",
"pytype",
"=",
"None",
"if",
"pytype",
"is",
"None",
":",
"raise",
"ROSBagException",
"(",
"'cannot locate message class and no message class provided for [%s]'",
"%",
"msg_type",
")",
"if",
"pytype",
".",
"_md5sum",
"!=",
"md5sum",
":",
"print",
"(",
"'WARNING: md5sum of loaded type [%s] does not match that specified'",
"%",
"msg_type",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"#raise ROSBagException('md5sum of loaded type does not match that of data being recorded')",
"header",
"=",
"{",
"'topic'",
":",
"topic",
",",
"'type'",
":",
"msg_type",
",",
"'md5sum'",
":",
"md5sum",
",",
"'message_definition'",
":",
"pytype",
".",
"_full_text",
"}",
"else",
":",
"if",
"issubclass",
"(",
"msg",
".",
"__class__",
",",
"google",
".",
"protobuf",
".",
"message",
".",
"Message",
")",
":",
"roslib",
".",
"message",
".",
"add_rosmsg_interface_for_protobuf",
"(",
"msg",
".",
"__class__",
")",
"header",
"=",
"{",
"'topic'",
":",
"topic",
",",
"'type'",
":",
"msg",
".",
"__class__",
".",
"_type",
",",
"'md5sum'",
":",
"msg",
".",
"__class__",
".",
"_md5sum",
",",
"'message_definition'",
":",
"'protobuf'",
"}",
"else",
":",
"header",
"=",
"{",
"'topic'",
":",
"topic",
",",
"'type'",
":",
"msg",
".",
"__class__",
".",
"_type",
",",
"'md5sum'",
":",
"msg",
".",
"__class__",
".",
"_md5sum",
",",
"'message_definition'",
":",
"msg",
".",
"_full_text",
"}",
"connection_info",
"=",
"_ConnectionInfo",
"(",
"conn_id",
",",
"topic",
",",
"header",
")",
"self",
".",
"_write_connection_record",
"(",
"connection_info",
")",
"self",
".",
"_connections",
"[",
"conn_id",
"]",
"=",
"connection_info",
"self",
".",
"_topic_connections",
"[",
"topic",
"]",
"=",
"connection_info",
"# Create an index entry",
"index_entry",
"=",
"_IndexEntry200",
"(",
"t",
",",
"self",
".",
"_curr_chunk_info",
".",
"pos",
",",
"self",
".",
"_get_chunk_offset",
"(",
")",
")",
"# Update the indexes and current chunk info ",
"if",
"conn_id",
"not",
"in",
"self",
".",
"_curr_chunk_connection_indexes",
":",
"# This is the first message on this connection in the chunk",
"self",
".",
"_curr_chunk_connection_indexes",
"[",
"conn_id",
"]",
"=",
"[",
"index_entry",
"]",
"self",
".",
"_curr_chunk_info",
".",
"connection_counts",
"[",
"conn_id",
"]",
"=",
"1",
"else",
":",
"curr_chunk_connection_index",
"=",
"self",
".",
"_curr_chunk_connection_indexes",
"[",
"conn_id",
"]",
"if",
"index_entry",
">=",
"curr_chunk_connection_index",
"[",
"-",
"1",
"]",
":",
"# Test if we're writing chronologically. Can skip binary search if so.",
"curr_chunk_connection_index",
".",
"append",
"(",
"index_entry",
")",
"else",
":",
"bisect",
".",
"insort_right",
"(",
"curr_chunk_connection_index",
",",
"index_entry",
")",
"self",
".",
"_curr_chunk_info",
".",
"connection_counts",
"[",
"conn_id",
"]",
"+=",
"1",
"if",
"conn_id",
"not",
"in",
"self",
".",
"_connection_indexes",
":",
"self",
".",
"_connection_indexes",
"[",
"conn_id",
"]",
"=",
"[",
"index_entry",
"]",
"else",
":",
"bisect",
".",
"insort_right",
"(",
"self",
".",
"_connection_indexes",
"[",
"conn_id",
"]",
",",
"index_entry",
")",
"# Update the chunk start/end times",
"if",
"t",
">",
"self",
".",
"_curr_chunk_info",
".",
"end_time",
":",
"self",
".",
"_curr_chunk_info",
".",
"end_time",
"=",
"t",
"elif",
"t",
"<",
"self",
".",
"_curr_chunk_info",
".",
"start_time",
":",
"self",
".",
"_curr_chunk_info",
".",
"start_time",
"=",
"t",
"if",
"not",
"raw",
":",
"# Serialize the message to the buffer",
"self",
".",
"_buffer",
".",
"seek",
"(",
"0",
")",
"self",
".",
"_buffer",
".",
"truncate",
"(",
"0",
")",
"msg",
".",
"serialize",
"(",
"self",
".",
"_buffer",
")",
"serialized_bytes",
"=",
"self",
".",
"_buffer",
".",
"getvalue",
"(",
")",
"# Write message data record",
"self",
".",
"_write_message_data_record",
"(",
"conn_id",
",",
"t",
",",
"serialized_bytes",
")",
"# Check if we want to stop this chunk",
"chunk_size",
"=",
"self",
".",
"_get_chunk_offset",
"(",
")",
"if",
"chunk_size",
">",
"self",
".",
"_chunk_threshold",
":",
"self",
".",
"_stop_writing_chunk",
"(",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rosbag/src/rosbag/bag.py#L289-L406 | ||
google/clif | cab24d6a105609a65c95a36a1712ae3c20c7b5df | clif/python/pytd2proto.py | python | _TypeEntry.set_nested_type | (self, pyname, cpp_name) | Set the C++ type for a Python type, checking for conflicts.
This is usually used to add a specific mapping for which there is only
one C++ type, such as a class definition in a clif file -- in such cases,
there should only be a single C++ type.
Args:
pyname: str, the Python name for the type. No dots allowed. If
the name already exists, then `cpp_name` must match the pre-existing
entry.
cpp_name: str, the C++ type name. | Set the C++ type for a Python type, checking for conflicts. | [
"Set",
"the",
"C",
"++",
"type",
"for",
"a",
"Python",
"type",
"checking",
"for",
"conflicts",
"."
] | def set_nested_type(self, pyname, cpp_name):
"""Set the C++ type for a Python type, checking for conflicts.
This is usually used to add a specific mapping for which there is only
one C++ type, such as a class definition in a clif file -- in such cases,
there should only be a single C++ type.
Args:
pyname: str, the Python name for the type. No dots allowed. If
the name already exists, then `cpp_name` must match the pre-existing
entry.
cpp_name: str, the C++ type name.
"""
assert '.' not in pyname, ('pyname {!r} cannot contain dots: you probably '
'meant to use _TypeTable').format(pyname)
try:
existing = self._types[pyname]
except KeyError:
entry = self._create_child_entry(pyname, cpp_name)
self._types[pyname] = entry
else:
desired_cpp_names = [cpp_name]
existing_cpp_names = existing._cpp_names # pylint: disable=protected-access
if existing_cpp_names != desired_cpp_names:
raise ValueError(
'Python type {!r}: existing C++ types {!r} don\'t match desired '
'types {!r}'.format(pyname, existing_cpp_names, desired_cpp_names)) | [
"def",
"set_nested_type",
"(",
"self",
",",
"pyname",
",",
"cpp_name",
")",
":",
"assert",
"'.'",
"not",
"in",
"pyname",
",",
"(",
"'pyname {!r} cannot contain dots: you probably '",
"'meant to use _TypeTable'",
")",
".",
"format",
"(",
"pyname",
")",
"try",
":",
"existing",
"=",
"self",
".",
"_types",
"[",
"pyname",
"]",
"except",
"KeyError",
":",
"entry",
"=",
"self",
".",
"_create_child_entry",
"(",
"pyname",
",",
"cpp_name",
")",
"self",
".",
"_types",
"[",
"pyname",
"]",
"=",
"entry",
"else",
":",
"desired_cpp_names",
"=",
"[",
"cpp_name",
"]",
"existing_cpp_names",
"=",
"existing",
".",
"_cpp_names",
"# pylint: disable=protected-access",
"if",
"existing_cpp_names",
"!=",
"desired_cpp_names",
":",
"raise",
"ValueError",
"(",
"'Python type {!r}: existing C++ types {!r} don\\'t match desired '",
"'types {!r}'",
".",
"format",
"(",
"pyname",
",",
"existing_cpp_names",
",",
"desired_cpp_names",
")",
")"
] | https://github.com/google/clif/blob/cab24d6a105609a65c95a36a1712ae3c20c7b5df/clif/python/pytd2proto.py#L1229-L1255 | ||
bastibl/gr-ieee802-15-4 | 1a2999ce2778df279870f028a4ce15d94e60fbd9 | docs/doxygen/update_pydoc.py | python | utoascii | (text) | return str(out) | Convert unicode text into ascii and escape quotes and backslashes. | Convert unicode text into ascii and escape quotes and backslashes. | [
"Convert",
"unicode",
"text",
"into",
"ascii",
"and",
"escape",
"quotes",
"and",
"backslashes",
"."
] | def utoascii(text):
"""
Convert unicode text into ascii and escape quotes and backslashes.
"""
if text is None:
return ''
out = text.encode('ascii', 'replace')
# swig will require us to replace blackslash with 4 backslashes
# TODO: evaluate what this should be for pybind11
out = out.replace(b'\\', b'\\\\\\\\')
out = out.replace(b'"', b'\\"').decode('ascii')
return str(out) | [
"def",
"utoascii",
"(",
"text",
")",
":",
"if",
"text",
"is",
"None",
":",
"return",
"''",
"out",
"=",
"text",
".",
"encode",
"(",
"'ascii'",
",",
"'replace'",
")",
"# swig will require us to replace blackslash with 4 backslashes",
"# TODO: evaluate what this should be for pybind11",
"out",
"=",
"out",
".",
"replace",
"(",
"b'\\\\'",
",",
"b'\\\\\\\\\\\\\\\\'",
")",
"out",
"=",
"out",
".",
"replace",
"(",
"b'\"'",
",",
"b'\\\\\"'",
")",
".",
"decode",
"(",
"'ascii'",
")",
"return",
"str",
"(",
"out",
")"
] | https://github.com/bastibl/gr-ieee802-15-4/blob/1a2999ce2778df279870f028a4ce15d94e60fbd9/docs/doxygen/update_pydoc.py#L70-L81 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/idlelib/SearchEngine.py | python | SearchEngine.search_text | (self, text, prog=None, ok=0) | return res | Search a text widget for the pattern.
If prog is given, it should be the precompiled pattern.
Return a tuple (lineno, matchobj); None if not found.
This obeys the wrap and direction (back) settings.
The search starts at the selection (if there is one) or
at the insert mark (otherwise). If the search is forward,
it starts at the right of the selection; for a backward
search, it starts at the left end. An empty match exactly
at either end of the selection (or at the insert mark if
there is no selection) is ignored unless the ok flag is true
-- this is done to guarantee progress.
If the search is allowed to wrap around, it will return the
original selection if (and only if) it is the only match. | Search a text widget for the pattern. | [
"Search",
"a",
"text",
"widget",
"for",
"the",
"pattern",
"."
] | def search_text(self, text, prog=None, ok=0):
"""Search a text widget for the pattern.
If prog is given, it should be the precompiled pattern.
Return a tuple (lineno, matchobj); None if not found.
This obeys the wrap and direction (back) settings.
The search starts at the selection (if there is one) or
at the insert mark (otherwise). If the search is forward,
it starts at the right of the selection; for a backward
search, it starts at the left end. An empty match exactly
at either end of the selection (or at the insert mark if
there is no selection) is ignored unless the ok flag is true
-- this is done to guarantee progress.
If the search is allowed to wrap around, it will return the
original selection if (and only if) it is the only match.
"""
if not prog:
prog = self.getprog()
if not prog:
return None # Compilation failed -- stop
wrap = self.wrapvar.get()
first, last = get_selection(text)
if self.isback():
if ok:
start = last
else:
start = first
line, col = get_line_col(start)
res = self.search_backward(text, prog, line, col, wrap, ok)
else:
if ok:
start = first
else:
start = last
line, col = get_line_col(start)
res = self.search_forward(text, prog, line, col, wrap, ok)
return res | [
"def",
"search_text",
"(",
"self",
",",
"text",
",",
"prog",
"=",
"None",
",",
"ok",
"=",
"0",
")",
":",
"if",
"not",
"prog",
":",
"prog",
"=",
"self",
".",
"getprog",
"(",
")",
"if",
"not",
"prog",
":",
"return",
"None",
"# Compilation failed -- stop",
"wrap",
"=",
"self",
".",
"wrapvar",
".",
"get",
"(",
")",
"first",
",",
"last",
"=",
"get_selection",
"(",
"text",
")",
"if",
"self",
".",
"isback",
"(",
")",
":",
"if",
"ok",
":",
"start",
"=",
"last",
"else",
":",
"start",
"=",
"first",
"line",
",",
"col",
"=",
"get_line_col",
"(",
"start",
")",
"res",
"=",
"self",
".",
"search_backward",
"(",
"text",
",",
"prog",
",",
"line",
",",
"col",
",",
"wrap",
",",
"ok",
")",
"else",
":",
"if",
"ok",
":",
"start",
"=",
"first",
"else",
":",
"start",
"=",
"last",
"line",
",",
"col",
"=",
"get_line_col",
"(",
"start",
")",
"res",
"=",
"self",
".",
"search_forward",
"(",
"text",
",",
"prog",
",",
"line",
",",
"col",
",",
"wrap",
",",
"ok",
")",
"return",
"res"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/idlelib/SearchEngine.py#L94-L134 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros_comm/roslaunch/src/roslaunch/pmon.py | python | ProcessMonitor.do_main_thread_jobs | (self) | Execute tasks that need to be run in the main thread. Must be
called from main thread. | Execute tasks that need to be run in the main thread. Must be
called from main thread. | [
"Execute",
"tasks",
"that",
"need",
"to",
"be",
"run",
"in",
"the",
"main",
"thread",
".",
"Must",
"be",
"called",
"from",
"main",
"thread",
"."
] | def do_main_thread_jobs(self):
"""
Execute tasks that need to be run in the main thread. Must be
called from main thread.
"""
#not entirely threadsafe
sigs = [s for s in self.reacquire_signals]
for s in sigs:
_signal_chain[s] = signal.signal(s, rl_signal)
self.reacquire_signals.remove(s) | [
"def",
"do_main_thread_jobs",
"(",
"self",
")",
":",
"#not entirely threadsafe",
"sigs",
"=",
"[",
"s",
"for",
"s",
"in",
"self",
".",
"reacquire_signals",
"]",
"for",
"s",
"in",
"sigs",
":",
"_signal_chain",
"[",
"s",
"]",
"=",
"signal",
".",
"signal",
"(",
"s",
",",
"rl_signal",
")",
"self",
".",
"reacquire_signals",
".",
"remove",
"(",
"s",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/roslaunch/src/roslaunch/pmon.py#L410-L419 | ||
facebook/folly | 744a0a698074d1b013813065fe60f545aa2c9b94 | build/fbcode_builder/getdeps/buildopts.py | python | BuildOptions.get_context_generator | (self, host_tuple=None) | return ContextGenerator(
{
"os": host_type.ostype,
"distro": host_type.distro,
"distro_vers": host_type.distrovers,
"fb": "on" if self.facebook_internal else "off",
"fbsource": "on" if self.fbsource_dir else "off",
"test": "off",
"shared_libs": "on" if self.shared_libs else "off",
}
) | Create a manifest ContextGenerator for the specified target platform. | Create a manifest ContextGenerator for the specified target platform. | [
"Create",
"a",
"manifest",
"ContextGenerator",
"for",
"the",
"specified",
"target",
"platform",
"."
] | def get_context_generator(self, host_tuple=None):
"""Create a manifest ContextGenerator for the specified target platform."""
if host_tuple is None:
host_type = self.host_type
elif isinstance(host_tuple, HostType):
host_type = host_tuple
else:
host_type = HostType.from_tuple_string(host_tuple)
return ContextGenerator(
{
"os": host_type.ostype,
"distro": host_type.distro,
"distro_vers": host_type.distrovers,
"fb": "on" if self.facebook_internal else "off",
"fbsource": "on" if self.fbsource_dir else "off",
"test": "off",
"shared_libs": "on" if self.shared_libs else "off",
}
) | [
"def",
"get_context_generator",
"(",
"self",
",",
"host_tuple",
"=",
"None",
")",
":",
"if",
"host_tuple",
"is",
"None",
":",
"host_type",
"=",
"self",
".",
"host_type",
"elif",
"isinstance",
"(",
"host_tuple",
",",
"HostType",
")",
":",
"host_type",
"=",
"host_tuple",
"else",
":",
"host_type",
"=",
"HostType",
".",
"from_tuple_string",
"(",
"host_tuple",
")",
"return",
"ContextGenerator",
"(",
"{",
"\"os\"",
":",
"host_type",
".",
"ostype",
",",
"\"distro\"",
":",
"host_type",
".",
"distro",
",",
"\"distro_vers\"",
":",
"host_type",
".",
"distrovers",
",",
"\"fb\"",
":",
"\"on\"",
"if",
"self",
".",
"facebook_internal",
"else",
"\"off\"",
",",
"\"fbsource\"",
":",
"\"on\"",
"if",
"self",
".",
"fbsource_dir",
"else",
"\"off\"",
",",
"\"test\"",
":",
"\"off\"",
",",
"\"shared_libs\"",
":",
"\"on\"",
"if",
"self",
".",
"shared_libs",
"else",
"\"off\"",
",",
"}",
")"
] | https://github.com/facebook/folly/blob/744a0a698074d1b013813065fe60f545aa2c9b94/build/fbcode_builder/getdeps/buildopts.py#L178-L197 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/propgrid.py | python | PGProperty.GetIndexInParent | (*args, **kwargs) | return _propgrid.PGProperty_GetIndexInParent(*args, **kwargs) | GetIndexInParent(self) -> int | GetIndexInParent(self) -> int | [
"GetIndexInParent",
"(",
"self",
")",
"-",
">",
"int"
] | def GetIndexInParent(*args, **kwargs):
"""GetIndexInParent(self) -> int"""
return _propgrid.PGProperty_GetIndexInParent(*args, **kwargs) | [
"def",
"GetIndexInParent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PGProperty_GetIndexInParent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/propgrid.py#L647-L649 | |
seqan/seqan | f5f658343c366c9c3d44ba358ffc9317e78a09ed | apps/ngs_roi/tool_shed/roi_details.py | python | DetailedRoiGenerator.run | (self) | return 0 | Run report generation, return status code.
:return: integer with the result. | Run report generation, return status code. | [
"Run",
"report",
"generation",
"return",
"status",
"code",
"."
] | def run(self):
"""Run report generation, return status code.
:return: integer with the result.
"""
print >>sys.stderr, 'Loading ROI'
records = ngs_roi.io.load(self.args.in_file, self.args.max_rois)
keys = records[0].data_keys
self.writeHtml(keys, records)
self.writePlots(records)
return 0 | [
"def",
"run",
"(",
"self",
")",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"'Loading ROI'",
"records",
"=",
"ngs_roi",
".",
"io",
".",
"load",
"(",
"self",
".",
"args",
".",
"in_file",
",",
"self",
".",
"args",
".",
"max_rois",
")",
"keys",
"=",
"records",
"[",
"0",
"]",
".",
"data_keys",
"self",
".",
"writeHtml",
"(",
"keys",
",",
"records",
")",
"self",
".",
"writePlots",
"(",
"records",
")",
"return",
"0"
] | https://github.com/seqan/seqan/blob/f5f658343c366c9c3d44ba358ffc9317e78a09ed/apps/ngs_roi/tool_shed/roi_details.py#L71-L82 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/summary_ops_v2.py | python | graph_v1 | (param, step=None, name=None) | Writes a TensorFlow graph to the summary interface.
The graph summary is, strictly speaking, not a summary. Conditions
like `tf.summary.should_record_summaries` do not apply. Only
a single graph can be associated with a particular run. If multiple
graphs are written, then only the last one will be considered by
TensorBoard.
When not using eager execution mode, the user should consider passing
the `graph` parameter to `tf.compat.v1.summary.initialize` instead of
calling this function. Otherwise special care needs to be taken when
using the graph to record the graph.
Args:
param: A `tf.Tensor` containing a serialized graph proto. When
eager execution is enabled, this function will automatically
coerce `tf.Graph`, `tf.compat.v1.GraphDef`, and string types.
step: The global step variable. This doesn't have useful semantics
for graph summaries, but is used anyway, due to the structure of
event log files. This defaults to the global step.
name: A name for the operation (optional).
Returns:
The created `tf.Operation` or a `tf.no_op` if summary writing has
not been enabled for this context.
Raises:
TypeError: If `param` isn't already a `tf.Tensor` in graph mode. | Writes a TensorFlow graph to the summary interface. | [
"Writes",
"a",
"TensorFlow",
"graph",
"to",
"the",
"summary",
"interface",
"."
] | def graph_v1(param, step=None, name=None):
"""Writes a TensorFlow graph to the summary interface.
The graph summary is, strictly speaking, not a summary. Conditions
like `tf.summary.should_record_summaries` do not apply. Only
a single graph can be associated with a particular run. If multiple
graphs are written, then only the last one will be considered by
TensorBoard.
When not using eager execution mode, the user should consider passing
the `graph` parameter to `tf.compat.v1.summary.initialize` instead of
calling this function. Otherwise special care needs to be taken when
using the graph to record the graph.
Args:
param: A `tf.Tensor` containing a serialized graph proto. When
eager execution is enabled, this function will automatically
coerce `tf.Graph`, `tf.compat.v1.GraphDef`, and string types.
step: The global step variable. This doesn't have useful semantics
for graph summaries, but is used anyway, due to the structure of
event log files. This defaults to the global step.
name: A name for the operation (optional).
Returns:
The created `tf.Operation` or a `tf.no_op` if summary writing has
not been enabled for this context.
Raises:
TypeError: If `param` isn't already a `tf.Tensor` in graph mode.
"""
if not context.executing_eagerly() and not isinstance(param, ops.Tensor):
raise TypeError("graph() needs a argument `param` to be tf.Tensor "
"(e.g. tf.placeholder) in graph mode, but received "
f"param={param} of type {type(param).__name__}.")
writer = _summary_state.writer
if writer is None:
return control_flow_ops.no_op()
with ops.device("cpu:0"):
if isinstance(param, (ops.Graph, graph_pb2.GraphDef)):
tensor = ops.convert_to_tensor(_serialize_graph(param), dtypes.string)
else:
tensor = array_ops.identity(param)
return gen_summary_ops.write_graph_summary(
writer._resource, _choose_step(step), tensor, name=name) | [
"def",
"graph_v1",
"(",
"param",
",",
"step",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"not",
"context",
".",
"executing_eagerly",
"(",
")",
"and",
"not",
"isinstance",
"(",
"param",
",",
"ops",
".",
"Tensor",
")",
":",
"raise",
"TypeError",
"(",
"\"graph() needs a argument `param` to be tf.Tensor \"",
"\"(e.g. tf.placeholder) in graph mode, but received \"",
"f\"param={param} of type {type(param).__name__}.\"",
")",
"writer",
"=",
"_summary_state",
".",
"writer",
"if",
"writer",
"is",
"None",
":",
"return",
"control_flow_ops",
".",
"no_op",
"(",
")",
"with",
"ops",
".",
"device",
"(",
"\"cpu:0\"",
")",
":",
"if",
"isinstance",
"(",
"param",
",",
"(",
"ops",
".",
"Graph",
",",
"graph_pb2",
".",
"GraphDef",
")",
")",
":",
"tensor",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"_serialize_graph",
"(",
"param",
")",
",",
"dtypes",
".",
"string",
")",
"else",
":",
"tensor",
"=",
"array_ops",
".",
"identity",
"(",
"param",
")",
"return",
"gen_summary_ops",
".",
"write_graph_summary",
"(",
"writer",
".",
"_resource",
",",
"_choose_step",
"(",
"step",
")",
",",
"tensor",
",",
"name",
"=",
"name",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/summary_ops_v2.py#L965-L1008 | ||
MegEngine/MegEngine | ce9ad07a27ec909fb8db4dd67943d24ba98fb93a | imperative/python/megengine/traced_module/traced_module.py | python | InternalGraph.top_graph | (self) | return None | r"""Get the parent graph of this graph.
Returns:
An ``InternalGraph``. | r"""Get the parent graph of this graph. | [
"r",
"Get",
"the",
"parent",
"graph",
"of",
"this",
"graph",
"."
] | def top_graph(self):
r"""Get the parent graph of this graph.
Returns:
An ``InternalGraph``.
"""
if self._top_graph:
return self._top_graph()
return None | [
"def",
"top_graph",
"(",
"self",
")",
":",
"if",
"self",
".",
"_top_graph",
":",
"return",
"self",
".",
"_top_graph",
"(",
")",
"return",
"None"
] | https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/traced_module/traced_module.py#L635-L643 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/s3transfer/tasks.py | python | SubmissionTask._submit | (self, transfer_future, **kwargs) | The submition method to be implemented
:type transfer_future: s3transfer.futures.TransferFuture
:param transfer_future: The transfer future associated with the
transfer request that tasks are being submitted for
:param kwargs: Any additional keyword arguments you want to be passed
in | The submition method to be implemented | [
"The",
"submition",
"method",
"to",
"be",
"implemented"
] | def _submit(self, transfer_future, **kwargs):
"""The submition method to be implemented
:type transfer_future: s3transfer.futures.TransferFuture
:param transfer_future: The transfer future associated with the
transfer request that tasks are being submitted for
:param kwargs: Any additional keyword arguments you want to be passed
in
"""
raise NotImplementedError('_submit() must be implemented') | [
"def",
"_submit",
"(",
"self",
",",
"transfer_future",
",",
"*",
"*",
"kwargs",
")",
":",
"raise",
"NotImplementedError",
"(",
"'_submit() must be implemented'",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/s3transfer/tasks.py#L280-L290 | ||
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/build/android/gyp/util/jar_info_utils.py | python | ReadAarSourceInfo | (info_path) | Returns the source= path from an .aar's source.info file. | Returns the source= path from an .aar's source.info file. | [
"Returns",
"the",
"source",
"=",
"path",
"from",
"an",
".",
"aar",
"s",
"source",
".",
"info",
"file",
"."
] | def ReadAarSourceInfo(info_path):
"""Returns the source= path from an .aar's source.info file."""
# The .info looks like: "source=path/to/.aar\n".
with open(info_path) as f:
return f.read().rstrip().split('=', 1)[1] | [
"def",
"ReadAarSourceInfo",
"(",
"info_path",
")",
":",
"# The .info looks like: \"source=path/to/.aar\\n\".",
"with",
"open",
"(",
"info_path",
")",
"as",
"f",
":",
"return",
"f",
".",
"read",
"(",
")",
".",
"rstrip",
"(",
")",
".",
"split",
"(",
"'='",
",",
"1",
")",
"[",
"1",
"]"
] | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/android/gyp/util/jar_info_utils.py#L16-L20 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/asyncio/selector_events.py | python | BaseSelectorEventLoop._remove_writer | (self, fd) | Remove a writer callback. | Remove a writer callback. | [
"Remove",
"a",
"writer",
"callback",
"."
] | def _remove_writer(self, fd):
"""Remove a writer callback."""
if self.is_closed():
return False
try:
key = self._selector.get_key(fd)
except KeyError:
return False
else:
mask, (reader, writer) = key.events, key.data
# Remove both writer and connector.
mask &= ~selectors.EVENT_WRITE
if not mask:
self._selector.unregister(fd)
else:
self._selector.modify(fd, mask, (reader, None))
if writer is not None:
writer.cancel()
return True
else:
return False | [
"def",
"_remove_writer",
"(",
"self",
",",
"fd",
")",
":",
"if",
"self",
".",
"is_closed",
"(",
")",
":",
"return",
"False",
"try",
":",
"key",
"=",
"self",
".",
"_selector",
".",
"get_key",
"(",
"fd",
")",
"except",
"KeyError",
":",
"return",
"False",
"else",
":",
"mask",
",",
"(",
"reader",
",",
"writer",
")",
"=",
"key",
".",
"events",
",",
"key",
".",
"data",
"# Remove both writer and connector.",
"mask",
"&=",
"~",
"selectors",
".",
"EVENT_WRITE",
"if",
"not",
"mask",
":",
"self",
".",
"_selector",
".",
"unregister",
"(",
"fd",
")",
"else",
":",
"self",
".",
"_selector",
".",
"modify",
"(",
"fd",
",",
"mask",
",",
"(",
"reader",
",",
"None",
")",
")",
"if",
"writer",
"is",
"not",
"None",
":",
"writer",
".",
"cancel",
"(",
")",
"return",
"True",
"else",
":",
"return",
"False"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/asyncio/selector_events.py#L310-L331 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/keras/mixed_precision/autocast_variable.py | python | AutoCastVariable.gather_nd | (self, indices, name=None) | return math_ops.cast(val, self._cast_dtype) | Gather slices of the variable into a Tensor. | Gather slices of the variable into a Tensor. | [
"Gather",
"slices",
"of",
"the",
"variable",
"into",
"a",
"Tensor",
"."
] | def gather_nd(self, indices, name=None):
"""Gather slices of the variable into a Tensor."""
val = self._variable.gather_nd(indices, name=name)
return math_ops.cast(val, self._cast_dtype) | [
"def",
"gather_nd",
"(",
"self",
",",
"indices",
",",
"name",
"=",
"None",
")",
":",
"val",
"=",
"self",
".",
"_variable",
".",
"gather_nd",
"(",
"indices",
",",
"name",
"=",
"name",
")",
"return",
"math_ops",
".",
"cast",
"(",
"val",
",",
"self",
".",
"_cast_dtype",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/mixed_precision/autocast_variable.py#L125-L128 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/shutil.py | python | _get_gid | (name) | return None | Returns a gid, given a group name. | Returns a gid, given a group name. | [
"Returns",
"a",
"gid",
"given",
"a",
"group",
"name",
"."
] | def _get_gid(name):
"""Returns a gid, given a group name."""
if getgrnam is None or name is None:
return None
try:
result = getgrnam(name)
except KeyError:
result = None
if result is not None:
return result[2]
return None | [
"def",
"_get_gid",
"(",
"name",
")",
":",
"if",
"getgrnam",
"is",
"None",
"or",
"name",
"is",
"None",
":",
"return",
"None",
"try",
":",
"result",
"=",
"getgrnam",
"(",
"name",
")",
"except",
"KeyError",
":",
"result",
"=",
"None",
"if",
"result",
"is",
"not",
"None",
":",
"return",
"result",
"[",
"2",
"]",
"return",
"None"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/shutil.py#L593-L603 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/rospkg/manifest.py | python | _check_rosdeps | (n, filename) | Validator for stack rosdeps.
:raises: :exc:`InvalidManifest` If validation fails | Validator for stack rosdeps. | [
"Validator",
"for",
"stack",
"rosdeps",
"."
] | def _check_rosdeps(n, filename):
"""
Validator for stack rosdeps.
:raises: :exc:`InvalidManifest` If validation fails
"""
try:
nodes = _get_nodes_by_name(n, 'rosdep')
rosdeps = [e.attributes for e in nodes]
names = [d['name'].value for d in rosdeps]
return [RosDep(n) for n in names]
except KeyError:
raise InvalidManifest("invalid rosdep tag in [%s]"%(filename)) | [
"def",
"_check_rosdeps",
"(",
"n",
",",
"filename",
")",
":",
"try",
":",
"nodes",
"=",
"_get_nodes_by_name",
"(",
"n",
",",
"'rosdep'",
")",
"rosdeps",
"=",
"[",
"e",
".",
"attributes",
"for",
"e",
"in",
"nodes",
"]",
"names",
"=",
"[",
"d",
"[",
"'name'",
"]",
".",
"value",
"for",
"d",
"in",
"rosdeps",
"]",
"return",
"[",
"RosDep",
"(",
"n",
")",
"for",
"n",
"in",
"names",
"]",
"except",
"KeyError",
":",
"raise",
"InvalidManifest",
"(",
"\"invalid rosdep tag in [%s]\"",
"%",
"(",
"filename",
")",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/rospkg/manifest.py#L131-L143 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/utils/input_fn_utils.py | python | build_parsing_serving_input_fn | (feature_spec, default_batch_size=None) | return input_fn | Build an input_fn appropriate for serving, expecting fed tf.Examples.
Creates an input_fn that expects a serialized tf.Example fed into a string
placeholder. The function parses the tf.Example according to the provided
feature_spec, and returns all parsed Tensors as features. This input_fn is
for use at serving time, so the labels return value is always None.
Args:
feature_spec: a dict of string to `VarLenFeature`/`FixedLenFeature`.
default_batch_size: the number of query examples expected per batch.
Leave unset for variable batch size (recommended).
Returns:
An input_fn suitable for use in serving. | Build an input_fn appropriate for serving, expecting fed tf.Examples. | [
"Build",
"an",
"input_fn",
"appropriate",
"for",
"serving",
"expecting",
"fed",
"tf",
".",
"Examples",
"."
] | def build_parsing_serving_input_fn(feature_spec, default_batch_size=None):
"""Build an input_fn appropriate for serving, expecting fed tf.Examples.
Creates an input_fn that expects a serialized tf.Example fed into a string
placeholder. The function parses the tf.Example according to the provided
feature_spec, and returns all parsed Tensors as features. This input_fn is
for use at serving time, so the labels return value is always None.
Args:
feature_spec: a dict of string to `VarLenFeature`/`FixedLenFeature`.
default_batch_size: the number of query examples expected per batch.
Leave unset for variable batch size (recommended).
Returns:
An input_fn suitable for use in serving.
"""
def input_fn():
"""An input_fn that expects a serialized tf.Example."""
serialized_tf_example = array_ops.placeholder(dtype=dtypes.string,
shape=[default_batch_size],
name='input_example_tensor')
inputs = {'examples': serialized_tf_example}
features = parsing_ops.parse_example(serialized_tf_example, feature_spec)
labels = None # these are not known in serving!
return InputFnOps(features, labels, inputs)
return input_fn | [
"def",
"build_parsing_serving_input_fn",
"(",
"feature_spec",
",",
"default_batch_size",
"=",
"None",
")",
":",
"def",
"input_fn",
"(",
")",
":",
"\"\"\"An input_fn that expects a serialized tf.Example.\"\"\"",
"serialized_tf_example",
"=",
"array_ops",
".",
"placeholder",
"(",
"dtype",
"=",
"dtypes",
".",
"string",
",",
"shape",
"=",
"[",
"default_batch_size",
"]",
",",
"name",
"=",
"'input_example_tensor'",
")",
"inputs",
"=",
"{",
"'examples'",
":",
"serialized_tf_example",
"}",
"features",
"=",
"parsing_ops",
".",
"parse_example",
"(",
"serialized_tf_example",
",",
"feature_spec",
")",
"labels",
"=",
"None",
"# these are not known in serving!",
"return",
"InputFnOps",
"(",
"features",
",",
"labels",
",",
"inputs",
")",
"return",
"input_fn"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/utils/input_fn_utils.py#L69-L94 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | third_party/mesa/MesaLib/src/mapi/glapi/gen-es/gl_parse_header.py | python | HeaderParser._postprocess_dict | (self, hdict) | return hlist | Post-process a header dict and return an ordered list. | Post-process a header dict and return an ordered list. | [
"Post",
"-",
"process",
"a",
"header",
"dict",
"and",
"return",
"an",
"ordered",
"list",
"."
] | def _postprocess_dict(self, hdict):
"""Post-process a header dict and return an ordered list."""
hlist = []
largest = 0
for key, cat in hdict.iteritems():
size = len(cat["enums"]) + len(cat["types"]) + len(cat["functions"])
# ignore empty category
if not size:
continue
cat["enums"].sort(self._cmp_enum)
# remove duplicates
dup = []
for i in xrange(1, len(cat["enums"])):
if cat["enums"][i] == cat["enums"][i - 1]:
dup.insert(0, i)
for i in dup:
e = cat["enums"].pop(i)
if self.verbose:
print "remove duplicate enum %s" % e[0]
cat["types"].sort(self._cmp_type)
cat["functions"].sort(self._cmp_function)
# largest category comes first
if size > largest:
hlist.insert(0, (key, cat))
largest = size
else:
hlist.append((key, cat))
return hlist | [
"def",
"_postprocess_dict",
"(",
"self",
",",
"hdict",
")",
":",
"hlist",
"=",
"[",
"]",
"largest",
"=",
"0",
"for",
"key",
",",
"cat",
"in",
"hdict",
".",
"iteritems",
"(",
")",
":",
"size",
"=",
"len",
"(",
"cat",
"[",
"\"enums\"",
"]",
")",
"+",
"len",
"(",
"cat",
"[",
"\"types\"",
"]",
")",
"+",
"len",
"(",
"cat",
"[",
"\"functions\"",
"]",
")",
"# ignore empty category",
"if",
"not",
"size",
":",
"continue",
"cat",
"[",
"\"enums\"",
"]",
".",
"sort",
"(",
"self",
".",
"_cmp_enum",
")",
"# remove duplicates",
"dup",
"=",
"[",
"]",
"for",
"i",
"in",
"xrange",
"(",
"1",
",",
"len",
"(",
"cat",
"[",
"\"enums\"",
"]",
")",
")",
":",
"if",
"cat",
"[",
"\"enums\"",
"]",
"[",
"i",
"]",
"==",
"cat",
"[",
"\"enums\"",
"]",
"[",
"i",
"-",
"1",
"]",
":",
"dup",
".",
"insert",
"(",
"0",
",",
"i",
")",
"for",
"i",
"in",
"dup",
":",
"e",
"=",
"cat",
"[",
"\"enums\"",
"]",
".",
"pop",
"(",
"i",
")",
"if",
"self",
".",
"verbose",
":",
"print",
"\"remove duplicate enum %s\"",
"%",
"e",
"[",
"0",
"]",
"cat",
"[",
"\"types\"",
"]",
".",
"sort",
"(",
"self",
".",
"_cmp_type",
")",
"cat",
"[",
"\"functions\"",
"]",
".",
"sort",
"(",
"self",
".",
"_cmp_function",
")",
"# largest category comes first",
"if",
"size",
">",
"largest",
":",
"hlist",
".",
"insert",
"(",
"0",
",",
"(",
"key",
",",
"cat",
")",
")",
"largest",
"=",
"size",
"else",
":",
"hlist",
".",
"append",
"(",
"(",
"key",
",",
"cat",
")",
")",
"return",
"hlist"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/mesa/MesaLib/src/mapi/glapi/gen-es/gl_parse_header.py#L271-L301 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/numpy/math_ops.py | python | exp2 | (x, dtype=None) | return _apply_tensor_op(lambda x: F.tensor_pow(2, x), x, dtype=dtype) | Calculates ``2**p`` for all p in the input array.
Note:
Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
not supported.
On GPU, the supported dtypes are np.float16, and np.float32.
Args:
x (Tensor): input values.
dtype (:class:`mindspore.dtype`, optional): Defaults to :class:`None`. Overrides the dtype of the
output Tensor.
Returns:
Tensor or scalar, element-wise 2 to the power `x`.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import mindspore.numpy as np
>>> x = np.array([2, 3]).astype(np.float32)
>>> output = np.exp2(x)
>>> print(output)
[4. 8.] | Calculates ``2**p`` for all p in the input array. | [
"Calculates",
"2",
"**",
"p",
"for",
"all",
"p",
"in",
"the",
"input",
"array",
"."
] | def exp2(x, dtype=None):
"""
Calculates ``2**p`` for all p in the input array.
Note:
Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
not supported.
On GPU, the supported dtypes are np.float16, and np.float32.
Args:
x (Tensor): input values.
dtype (:class:`mindspore.dtype`, optional): Defaults to :class:`None`. Overrides the dtype of the
output Tensor.
Returns:
Tensor or scalar, element-wise 2 to the power `x`.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import mindspore.numpy as np
>>> x = np.array([2, 3]).astype(np.float32)
>>> output = np.exp2(x)
>>> print(output)
[4. 8.]
"""
return _apply_tensor_op(lambda x: F.tensor_pow(2, x), x, dtype=dtype) | [
"def",
"exp2",
"(",
"x",
",",
"dtype",
"=",
"None",
")",
":",
"return",
"_apply_tensor_op",
"(",
"lambda",
"x",
":",
"F",
".",
"tensor_pow",
"(",
"2",
",",
"x",
")",
",",
"x",
",",
"dtype",
"=",
"dtype",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/numpy/math_ops.py#L2810-L2837 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/flatmenu.py | python | FlatMenuBar.GetRendererManager | (self) | return self._rendererMgr | Returns the :class:`FlatMenuBar` renderer manager. | Returns the :class:`FlatMenuBar` renderer manager. | [
"Returns",
"the",
":",
"class",
":",
"FlatMenuBar",
"renderer",
"manager",
"."
] | def GetRendererManager(self):
"""
Returns the :class:`FlatMenuBar` renderer manager.
"""
return self._rendererMgr | [
"def",
"GetRendererManager",
"(",
"self",
")",
":",
"return",
"self",
".",
"_rendererMgr"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatmenu.py#L2584-L2589 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/ttk.py | python | Scrollbar.__init__ | (self, master=None, **kw) | Construct a Ttk Scrollbar with parent master.
STANDARD OPTIONS
class, cursor, style, takefocus
WIDGET-SPECIFIC OPTIONS
command, orient | Construct a Ttk Scrollbar with parent master. | [
"Construct",
"a",
"Ttk",
"Scrollbar",
"with",
"parent",
"master",
"."
] | def __init__(self, master=None, **kw):
"""Construct a Ttk Scrollbar with parent master.
STANDARD OPTIONS
class, cursor, style, takefocus
WIDGET-SPECIFIC OPTIONS
command, orient
"""
Widget.__init__(self, master, "ttk::scrollbar", kw) | [
"def",
"__init__",
"(",
"self",
",",
"master",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"Widget",
".",
"__init__",
"(",
"self",
",",
"master",
",",
"\"ttk::scrollbar\"",
",",
"kw",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/ttk.py#L1101-L1112 | ||
xhzdeng/crpn | a5aef0f80dbe486103123f740c634fb01e6cc9a1 | caffe-fast-rcnn/python/caffe/coord_map.py | python | compose | (base_map, next_map) | return ax, a1 * a2, a1 * b2 + b1 | Compose a base coord map with scale a1, shift b1 with a further coord map
with scale a2, shift b2. The scales multiply and the further shift, b2,
is scaled by base coord scale a1. | Compose a base coord map with scale a1, shift b1 with a further coord map
with scale a2, shift b2. The scales multiply and the further shift, b2,
is scaled by base coord scale a1. | [
"Compose",
"a",
"base",
"coord",
"map",
"with",
"scale",
"a1",
"shift",
"b1",
"with",
"a",
"further",
"coord",
"map",
"with",
"scale",
"a2",
"shift",
"b2",
".",
"The",
"scales",
"multiply",
"and",
"the",
"further",
"shift",
"b2",
"is",
"scaled",
"by",
"base",
"coord",
"scale",
"a1",
"."
] | def compose(base_map, next_map):
"""
Compose a base coord map with scale a1, shift b1 with a further coord map
with scale a2, shift b2. The scales multiply and the further shift, b2,
is scaled by base coord scale a1.
"""
ax1, a1, b1 = base_map
ax2, a2, b2 = next_map
if ax1 is None:
ax = ax2
elif ax2 is None or ax1 == ax2:
ax = ax1
else:
raise AxisMismatchException
return ax, a1 * a2, a1 * b2 + b1 | [
"def",
"compose",
"(",
"base_map",
",",
"next_map",
")",
":",
"ax1",
",",
"a1",
",",
"b1",
"=",
"base_map",
"ax2",
",",
"a2",
",",
"b2",
"=",
"next_map",
"if",
"ax1",
"is",
"None",
":",
"ax",
"=",
"ax2",
"elif",
"ax2",
"is",
"None",
"or",
"ax1",
"==",
"ax2",
":",
"ax",
"=",
"ax1",
"else",
":",
"raise",
"AxisMismatchException",
"return",
"ax",
",",
"a1",
"*",
"a2",
",",
"a1",
"*",
"b2",
"+",
"b1"
] | https://github.com/xhzdeng/crpn/blob/a5aef0f80dbe486103123f740c634fb01e6cc9a1/caffe-fast-rcnn/python/caffe/coord_map.py#L89-L103 | |
plumonito/dtslam | 5994bb9cf7a11981b830370db206bceb654c085d | 3rdparty/opencv-git/3rdparty/jinja2/filters.py | python | do_rejectattr | (*args, **kwargs) | return _select_or_reject(args, kwargs, lambda x: not x, True) | Filters a sequence of objects by appying a test to either the object
or the attribute and rejecting the ones with the test succeeding.
.. sourcecode:: jinja
{{ users|rejectattr("is_active") }}
{{ users|rejectattr("email", "none") }}
.. versionadded:: 2.7 | Filters a sequence of objects by appying a test to either the object
or the attribute and rejecting the ones with the test succeeding. | [
"Filters",
"a",
"sequence",
"of",
"objects",
"by",
"appying",
"a",
"test",
"to",
"either",
"the",
"object",
"or",
"the",
"attribute",
"and",
"rejecting",
"the",
"ones",
"with",
"the",
"test",
"succeeding",
"."
] | def do_rejectattr(*args, **kwargs):
"""Filters a sequence of objects by appying a test to either the object
or the attribute and rejecting the ones with the test succeeding.
.. sourcecode:: jinja
{{ users|rejectattr("is_active") }}
{{ users|rejectattr("email", "none") }}
.. versionadded:: 2.7
"""
return _select_or_reject(args, kwargs, lambda x: not x, True) | [
"def",
"do_rejectattr",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_select_or_reject",
"(",
"args",
",",
"kwargs",
",",
"lambda",
"x",
":",
"not",
"x",
",",
"True",
")"
] | https://github.com/plumonito/dtslam/blob/5994bb9cf7a11981b830370db206bceb654c085d/3rdparty/opencv-git/3rdparty/jinja2/filters.py#L893-L904 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/wsgiref/handlers.py | python | BaseHandler._convert_string_type | (self, value, title) | Convert/check value type. | Convert/check value type. | [
"Convert",
"/",
"check",
"value",
"type",
"."
] | def _convert_string_type(self, value, title):
"""Convert/check value type."""
if type(value) is str:
return value
raise AssertionError(
"{0} must be of type str (got {1})".format(title, repr(value))
) | [
"def",
"_convert_string_type",
"(",
"self",
",",
"value",
",",
"title",
")",
":",
"if",
"type",
"(",
"value",
")",
"is",
"str",
":",
"return",
"value",
"raise",
"AssertionError",
"(",
"\"{0} must be of type str (got {1})\"",
".",
"format",
"(",
"title",
",",
"repr",
"(",
"value",
")",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/wsgiref/handlers.py#L253-L259 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/keras/python/keras/engine/training.py | python | Model._predict_loop | (self, f, ins, batch_size=32, verbose=0) | return outs | Abstract method to loop over some data in batches.
Arguments:
f: Keras function returning a list of tensors.
ins: list of tensors to be fed to `f`.
batch_size: integer batch size.
verbose: verbosity mode.
Returns:
Array of predictions (if the model has a single output)
or list of arrays of predictions
(if the model has multiple outputs). | Abstract method to loop over some data in batches. | [
"Abstract",
"method",
"to",
"loop",
"over",
"some",
"data",
"in",
"batches",
"."
] | def _predict_loop(self, f, ins, batch_size=32, verbose=0):
"""Abstract method to loop over some data in batches.
Arguments:
f: Keras function returning a list of tensors.
ins: list of tensors to be fed to `f`.
batch_size: integer batch size.
verbose: verbosity mode.
Returns:
Array of predictions (if the model has a single output)
or list of arrays of predictions
(if the model has multiple outputs).
"""
if ins and hasattr(ins[0], 'shape'):
samples = ins[0].shape[0]
else:
# May happen if we are running `predict` without Numpy input data,
# i.e. if all inputs to the models are data tensors
# instead of placeholders.
# In that case we will run `predict` over a single batch.
samples = batch_size
verbose = 2
outs = []
if verbose == 1:
progbar = Progbar(target=samples)
batches = _make_batches(samples, batch_size)
index_array = np.arange(samples)
for batch_index, (batch_start, batch_end) in enumerate(batches):
batch_ids = index_array[batch_start:batch_end]
if ins and isinstance(ins[-1], float):
# Do not slice the training phase flag.
ins_batch = _slice_arrays(ins[:-1], batch_ids) + [ins[-1]]
else:
ins_batch = _slice_arrays(ins, batch_ids)
batch_outs = f(ins_batch)
if not isinstance(batch_outs, list):
batch_outs = [batch_outs]
if batch_index == 0:
for batch_out in batch_outs:
shape = (samples,) + batch_out.shape[1:]
outs.append(np.zeros(shape, dtype=batch_out.dtype))
for i, batch_out in enumerate(batch_outs):
outs[i][batch_start:batch_end] = batch_out
if verbose == 1:
progbar.update(batch_end)
if len(outs) == 1:
return outs[0]
return outs | [
"def",
"_predict_loop",
"(",
"self",
",",
"f",
",",
"ins",
",",
"batch_size",
"=",
"32",
",",
"verbose",
"=",
"0",
")",
":",
"if",
"ins",
"and",
"hasattr",
"(",
"ins",
"[",
"0",
"]",
",",
"'shape'",
")",
":",
"samples",
"=",
"ins",
"[",
"0",
"]",
".",
"shape",
"[",
"0",
"]",
"else",
":",
"# May happen if we are running `predict` without Numpy input data,",
"# i.e. if all inputs to the models are data tensors",
"# instead of placeholders.",
"# In that case we will run `predict` over a single batch.",
"samples",
"=",
"batch_size",
"verbose",
"=",
"2",
"outs",
"=",
"[",
"]",
"if",
"verbose",
"==",
"1",
":",
"progbar",
"=",
"Progbar",
"(",
"target",
"=",
"samples",
")",
"batches",
"=",
"_make_batches",
"(",
"samples",
",",
"batch_size",
")",
"index_array",
"=",
"np",
".",
"arange",
"(",
"samples",
")",
"for",
"batch_index",
",",
"(",
"batch_start",
",",
"batch_end",
")",
"in",
"enumerate",
"(",
"batches",
")",
":",
"batch_ids",
"=",
"index_array",
"[",
"batch_start",
":",
"batch_end",
"]",
"if",
"ins",
"and",
"isinstance",
"(",
"ins",
"[",
"-",
"1",
"]",
",",
"float",
")",
":",
"# Do not slice the training phase flag.",
"ins_batch",
"=",
"_slice_arrays",
"(",
"ins",
"[",
":",
"-",
"1",
"]",
",",
"batch_ids",
")",
"+",
"[",
"ins",
"[",
"-",
"1",
"]",
"]",
"else",
":",
"ins_batch",
"=",
"_slice_arrays",
"(",
"ins",
",",
"batch_ids",
")",
"batch_outs",
"=",
"f",
"(",
"ins_batch",
")",
"if",
"not",
"isinstance",
"(",
"batch_outs",
",",
"list",
")",
":",
"batch_outs",
"=",
"[",
"batch_outs",
"]",
"if",
"batch_index",
"==",
"0",
":",
"for",
"batch_out",
"in",
"batch_outs",
":",
"shape",
"=",
"(",
"samples",
",",
")",
"+",
"batch_out",
".",
"shape",
"[",
"1",
":",
"]",
"outs",
".",
"append",
"(",
"np",
".",
"zeros",
"(",
"shape",
",",
"dtype",
"=",
"batch_out",
".",
"dtype",
")",
")",
"for",
"i",
",",
"batch_out",
"in",
"enumerate",
"(",
"batch_outs",
")",
":",
"outs",
"[",
"i",
"]",
"[",
"batch_start",
":",
"batch_end",
"]",
"=",
"batch_out",
"if",
"verbose",
"==",
"1",
":",
"progbar",
".",
"update",
"(",
"batch_end",
")",
"if",
"len",
"(",
"outs",
")",
"==",
"1",
":",
"return",
"outs",
"[",
"0",
"]",
"return",
"outs"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/keras/python/keras/engine/training.py#L1104-L1154 | |
openmm/openmm | cb293447c4fc8b03976dfe11399f107bab70f3d9 | wrappers/python/openmm/app/internal/charmm/topologyobjects.py | python | _CmapGrid.switch_range | (self) | return newgrid | Returns a grid object whose range is 0 to 360 degrees in both dimensions
instead of -180 to 180 degrees (or -180 to 180 degrees if the range is
already 0 to 360 degrees) | Returns a grid object whose range is 0 to 360 degrees in both dimensions
instead of -180 to 180 degrees (or -180 to 180 degrees if the range is
already 0 to 360 degrees) | [
"Returns",
"a",
"grid",
"object",
"whose",
"range",
"is",
"0",
"to",
"360",
"degrees",
"in",
"both",
"dimensions",
"instead",
"of",
"-",
"180",
"to",
"180",
"degrees",
"(",
"or",
"-",
"180",
"to",
"180",
"degrees",
"if",
"the",
"range",
"is",
"already",
"0",
"to",
"360",
"degrees",
")"
] | def switch_range(self):
"""
Returns a grid object whose range is 0 to 360 degrees in both dimensions
instead of -180 to 180 degrees (or -180 to 180 degrees if the range is
already 0 to 360 degrees)
"""
res = self.resolution
mid = res // 2
newgrid = _CmapGrid(res)
for i in range(res):
for j in range(res):
# Start from the middle
newgrid[i, j] = self[(i+mid)%res, (j+mid)%res]
return newgrid | [
"def",
"switch_range",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"resolution",
"mid",
"=",
"res",
"//",
"2",
"newgrid",
"=",
"_CmapGrid",
"(",
"res",
")",
"for",
"i",
"in",
"range",
"(",
"res",
")",
":",
"for",
"j",
"in",
"range",
"(",
"res",
")",
":",
"# Start from the middle",
"newgrid",
"[",
"i",
",",
"j",
"]",
"=",
"self",
"[",
"(",
"i",
"+",
"mid",
")",
"%",
"res",
",",
"(",
"j",
"+",
"mid",
")",
"%",
"res",
"]",
"return",
"newgrid"
] | https://github.com/openmm/openmm/blob/cb293447c4fc8b03976dfe11399f107bab70f3d9/wrappers/python/openmm/app/internal/charmm/topologyobjects.py#L1240-L1253 | |
plumonito/dtslam | 5994bb9cf7a11981b830370db206bceb654c085d | 3rdparty/opencv-git/modules/java/generator/gen_java.py | python | JavaWrapperGenerator.isSmartClass | (self, classname) | return classname in self.classes and self.classes[classname].base | Check if class stores Ptr<T>* instead of T* in nativeObj field | Check if class stores Ptr<T>* instead of T* in nativeObj field | [
"Check",
"if",
"class",
"stores",
"Ptr<T",
">",
"*",
"instead",
"of",
"T",
"*",
"in",
"nativeObj",
"field"
] | def isSmartClass(self, classname):
'''
Check if class stores Ptr<T>* instead of T* in nativeObj field
'''
return classname in self.classes and self.classes[classname].base | [
"def",
"isSmartClass",
"(",
"self",
",",
"classname",
")",
":",
"return",
"classname",
"in",
"self",
".",
"classes",
"and",
"self",
".",
"classes",
"[",
"classname",
"]",
".",
"base"
] | https://github.com/plumonito/dtslam/blob/5994bb9cf7a11981b830370db206bceb654c085d/3rdparty/opencv-git/modules/java/generator/gen_java.py#L1565-L1569 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/draftobjects/pathtwistedarray.py | python | PathTwistedArray.set_properties | (self, obj) | Set properties only if they don't exist. | Set properties only if they don't exist. | [
"Set",
"properties",
"only",
"if",
"they",
"don",
"t",
"exist",
"."
] | def set_properties(self, obj):
"""Set properties only if they don't exist."""
if hasattr(obj, "PropertiesList"):
properties = obj.PropertiesList
else:
properties = []
if "Base" not in properties:
obj.addProperty("App::PropertyLink",
"Base",
"Objects",
QT_TRANSLATE_NOOP("App::Property","The base object that will be duplicated."))
obj.Base = None
if "PathObject" not in properties:
obj.addProperty("App::PropertyLink",
"PathObject",
"Objects",
QT_TRANSLATE_NOOP("App::Property","The object along which the copies will be distributed. It must contain 'Edges'."))
obj.PathObject = None
if "Count" not in properties:
obj.addProperty("App::PropertyInteger",
"Count",
"Objects",
QT_TRANSLATE_NOOP("App::Property","Number of copies to create."))
obj.Count = 15
if "RotationFactor" not in properties:
obj.addProperty("App::PropertyFloat",
"RotationFactor",
"Objects",
QT_TRANSLATE_NOOP("App::Property","Rotation factor of the twisted array."))
obj.RotationFactor = 0.25
if self.use_link and "ExpandArray" not in properties:
obj.addProperty("App::PropertyBool",
"ExpandArray",
"Objects",
QT_TRANSLATE_NOOP("App::Property","Show the individual array elements (only for Link arrays)"))
obj.ExpandArray = False
obj.setPropertyStatus('Shape', 'Transient') | [
"def",
"set_properties",
"(",
"self",
",",
"obj",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"\"PropertiesList\"",
")",
":",
"properties",
"=",
"obj",
".",
"PropertiesList",
"else",
":",
"properties",
"=",
"[",
"]",
"if",
"\"Base\"",
"not",
"in",
"properties",
":",
"obj",
".",
"addProperty",
"(",
"\"App::PropertyLink\"",
",",
"\"Base\"",
",",
"\"Objects\"",
",",
"QT_TRANSLATE_NOOP",
"(",
"\"App::Property\"",
",",
"\"The base object that will be duplicated.\"",
")",
")",
"obj",
".",
"Base",
"=",
"None",
"if",
"\"PathObject\"",
"not",
"in",
"properties",
":",
"obj",
".",
"addProperty",
"(",
"\"App::PropertyLink\"",
",",
"\"PathObject\"",
",",
"\"Objects\"",
",",
"QT_TRANSLATE_NOOP",
"(",
"\"App::Property\"",
",",
"\"The object along which the copies will be distributed. It must contain 'Edges'.\"",
")",
")",
"obj",
".",
"PathObject",
"=",
"None",
"if",
"\"Count\"",
"not",
"in",
"properties",
":",
"obj",
".",
"addProperty",
"(",
"\"App::PropertyInteger\"",
",",
"\"Count\"",
",",
"\"Objects\"",
",",
"QT_TRANSLATE_NOOP",
"(",
"\"App::Property\"",
",",
"\"Number of copies to create.\"",
")",
")",
"obj",
".",
"Count",
"=",
"15",
"if",
"\"RotationFactor\"",
"not",
"in",
"properties",
":",
"obj",
".",
"addProperty",
"(",
"\"App::PropertyFloat\"",
",",
"\"RotationFactor\"",
",",
"\"Objects\"",
",",
"QT_TRANSLATE_NOOP",
"(",
"\"App::Property\"",
",",
"\"Rotation factor of the twisted array.\"",
")",
")",
"obj",
".",
"RotationFactor",
"=",
"0.25",
"if",
"self",
".",
"use_link",
"and",
"\"ExpandArray\"",
"not",
"in",
"properties",
":",
"obj",
".",
"addProperty",
"(",
"\"App::PropertyBool\"",
",",
"\"ExpandArray\"",
",",
"\"Objects\"",
",",
"QT_TRANSLATE_NOOP",
"(",
"\"App::Property\"",
",",
"\"Show the individual array elements (only for Link arrays)\"",
")",
")",
"obj",
".",
"ExpandArray",
"=",
"False",
"obj",
".",
"setPropertyStatus",
"(",
"'Shape'",
",",
"'Transient'",
")"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftobjects/pathtwistedarray.py#L75-L116 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | build/android/valgrind_tools.py | python | MemcheckTool.GetFilesForTool | (self) | return ['tools/valgrind/android/vg-chrome-wrapper.sh',
'tools/valgrind/memcheck/suppressions.txt',
'tools/valgrind/memcheck/suppressions_android.txt'] | Returns a list of file names for the tool. | Returns a list of file names for the tool. | [
"Returns",
"a",
"list",
"of",
"file",
"names",
"for",
"the",
"tool",
"."
] | def GetFilesForTool(self):
"""Returns a list of file names for the tool."""
return ['tools/valgrind/android/vg-chrome-wrapper.sh',
'tools/valgrind/memcheck/suppressions.txt',
'tools/valgrind/memcheck/suppressions_android.txt'] | [
"def",
"GetFilesForTool",
"(",
"self",
")",
":",
"return",
"[",
"'tools/valgrind/android/vg-chrome-wrapper.sh'",
",",
"'tools/valgrind/memcheck/suppressions.txt'",
",",
"'tools/valgrind/memcheck/suppressions_android.txt'",
"]"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/build/android/valgrind_tools.py#L124-L128 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py | python | LineReader.readline | (self) | Read a line from elyxer.file | Read a line from elyxer.file | [
"Read",
"a",
"line",
"from",
"elyxer",
".",
"file"
] | def readline(self):
"Read a line from elyxer.file"
self.current = self.file.readline()
if not isinstance(self.file, codecs.StreamReaderWriter):
self.current = self.current.decode('utf-8')
if len(self.current) == 0:
self.depleted = True
self.current = self.current.rstrip('\n\r')
self.linenumber += 1
self.mustread = False
Trace.prefix = 'Line ' + unicode(self.linenumber) + ': '
if self.linenumber % 1000 == 0:
Trace.message('Parsing') | [
"def",
"readline",
"(",
"self",
")",
":",
"self",
".",
"current",
"=",
"self",
".",
"file",
".",
"readline",
"(",
")",
"if",
"not",
"isinstance",
"(",
"self",
".",
"file",
",",
"codecs",
".",
"StreamReaderWriter",
")",
":",
"self",
".",
"current",
"=",
"self",
".",
"current",
".",
"decode",
"(",
"'utf-8'",
")",
"if",
"len",
"(",
"self",
".",
"current",
")",
"==",
"0",
":",
"self",
".",
"depleted",
"=",
"True",
"self",
".",
"current",
"=",
"self",
".",
"current",
".",
"rstrip",
"(",
"'\\n\\r'",
")",
"self",
".",
"linenumber",
"+=",
"1",
"self",
".",
"mustread",
"=",
"False",
"Trace",
".",
"prefix",
"=",
"'Line '",
"+",
"unicode",
"(",
"self",
".",
"linenumber",
")",
"+",
"': '",
"if",
"self",
".",
"linenumber",
"%",
"1000",
"==",
"0",
":",
"Trace",
".",
"message",
"(",
"'Parsing'",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py#L1754-L1766 | ||
PrincetonUniversity/athena-public-version | 9c266692b9423743d8e23509b3ab266a232a92d2 | tst/style/cpplint.py | python | CleansedLines._CollapseStrings | (elided) | return collapsed | Collapses strings and chars on a line to simple "" or '' blocks.
We nix strings first so we're not fooled by text like '"http://"'
Args:
elided: The line being processed.
Returns:
The line with collapsed strings. | Collapses strings and chars on a line to simple "" or '' blocks. | [
"Collapses",
"strings",
"and",
"chars",
"on",
"a",
"line",
"to",
"simple",
"or",
"blocks",
"."
] | def _CollapseStrings(elided):
"""Collapses strings and chars on a line to simple "" or '' blocks.
We nix strings first so we're not fooled by text like '"http://"'
Args:
elided: The line being processed.
Returns:
The line with collapsed strings.
"""
if _RE_PATTERN_INCLUDE.match(elided):
return elided
# Remove escaped characters first to make quote/single quote collapsing
# basic. Things that look like escaped characters shouldn't occur
# outside of strings and chars.
elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided)
# Replace quoted strings and digit separators. Both single quotes
# and double quotes are processed in the same loop, otherwise
# nested quotes wouldn't work.
collapsed = ''
while True:
# Find the first quote character
match = Match(r'^([^\'"]*)([\'"])(.*)$', elided)
if not match:
collapsed += elided
break
head, quote, tail = match.groups()
if quote == '"':
# Collapse double quoted strings
second_quote = tail.find('"')
if second_quote >= 0:
collapsed += head + '""'
elided = tail[second_quote + 1:]
else:
# Unmatched double quote, don't bother processing the rest
# of the line since this is probably a multiline string.
collapsed += elided
break
else:
# Found single quote, check nearby text to eliminate digit separators.
#
# There is no special handling for floating point here, because
# the integer/fractional/exponent parts would all be parsed
# correctly as long as there are digits on both sides of the
# separator. So we are fine as long as we don't see something
# like "0.'3" (gcc 4.9.0 will not allow this literal).
if Search(r'\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$', head):
match_literal = Match(r'^((?:\'?[0-9a-zA-Z_])*)(.*)$', "'" + tail)
collapsed += head + match_literal.group(1).replace("'", '')
elided = match_literal.group(2)
else:
second_quote = tail.find('\'')
if second_quote >= 0:
collapsed += head + "''"
elided = tail[second_quote + 1:]
else:
# Unmatched single quote
collapsed += elided
break
return collapsed | [
"def",
"_CollapseStrings",
"(",
"elided",
")",
":",
"if",
"_RE_PATTERN_INCLUDE",
".",
"match",
"(",
"elided",
")",
":",
"return",
"elided",
"# Remove escaped characters first to make quote/single quote collapsing",
"# basic. Things that look like escaped characters shouldn't occur",
"# outside of strings and chars.",
"elided",
"=",
"_RE_PATTERN_CLEANSE_LINE_ESCAPES",
".",
"sub",
"(",
"''",
",",
"elided",
")",
"# Replace quoted strings and digit separators. Both single quotes",
"# and double quotes are processed in the same loop, otherwise",
"# nested quotes wouldn't work.",
"collapsed",
"=",
"''",
"while",
"True",
":",
"# Find the first quote character",
"match",
"=",
"Match",
"(",
"r'^([^\\'\"]*)([\\'\"])(.*)$'",
",",
"elided",
")",
"if",
"not",
"match",
":",
"collapsed",
"+=",
"elided",
"break",
"head",
",",
"quote",
",",
"tail",
"=",
"match",
".",
"groups",
"(",
")",
"if",
"quote",
"==",
"'\"'",
":",
"# Collapse double quoted strings",
"second_quote",
"=",
"tail",
".",
"find",
"(",
"'\"'",
")",
"if",
"second_quote",
">=",
"0",
":",
"collapsed",
"+=",
"head",
"+",
"'\"\"'",
"elided",
"=",
"tail",
"[",
"second_quote",
"+",
"1",
":",
"]",
"else",
":",
"# Unmatched double quote, don't bother processing the rest",
"# of the line since this is probably a multiline string.",
"collapsed",
"+=",
"elided",
"break",
"else",
":",
"# Found single quote, check nearby text to eliminate digit separators.",
"#",
"# There is no special handling for floating point here, because",
"# the integer/fractional/exponent parts would all be parsed",
"# correctly as long as there are digits on both sides of the",
"# separator. So we are fine as long as we don't see something",
"# like \"0.'3\" (gcc 4.9.0 will not allow this literal).",
"if",
"Search",
"(",
"r'\\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$'",
",",
"head",
")",
":",
"match_literal",
"=",
"Match",
"(",
"r'^((?:\\'?[0-9a-zA-Z_])*)(.*)$'",
",",
"\"'\"",
"+",
"tail",
")",
"collapsed",
"+=",
"head",
"+",
"match_literal",
".",
"group",
"(",
"1",
")",
".",
"replace",
"(",
"\"'\"",
",",
"''",
")",
"elided",
"=",
"match_literal",
".",
"group",
"(",
"2",
")",
"else",
":",
"second_quote",
"=",
"tail",
".",
"find",
"(",
"'\\''",
")",
"if",
"second_quote",
">=",
"0",
":",
"collapsed",
"+=",
"head",
"+",
"\"''\"",
"elided",
"=",
"tail",
"[",
"second_quote",
"+",
"1",
":",
"]",
"else",
":",
"# Unmatched single quote",
"collapsed",
"+=",
"elided",
"break",
"return",
"collapsed"
] | https://github.com/PrincetonUniversity/athena-public-version/blob/9c266692b9423743d8e23509b3ab266a232a92d2/tst/style/cpplint.py#L1683-L1747 | |
Kitware/ParaView | f760af9124ff4634b23ebbeab95a4f56e0261955 | Wrapping/Python/paraview/simple.py | python | GetCameraTrack | (view=None) | return cue | Returns the camera animation track for the given view. If no view is
specified, active view will be used. If no existing camera animation track
is found, a new one will be created. | Returns the camera animation track for the given view. If no view is
specified, active view will be used. If no existing camera animation track
is found, a new one will be created. | [
"Returns",
"the",
"camera",
"animation",
"track",
"for",
"the",
"given",
"view",
".",
"If",
"no",
"view",
"is",
"specified",
"active",
"view",
"will",
"be",
"used",
".",
"If",
"no",
"existing",
"camera",
"animation",
"track",
"is",
"found",
"a",
"new",
"one",
"will",
"be",
"created",
"."
] | def GetCameraTrack(view=None):
"""Returns the camera animation track for the given view. If no view is
specified, active view will be used. If no existing camera animation track
is found, a new one will be created."""
if not view:
view = GetActiveView()
if not view:
raise ValueError ("No view specified")
scene = GetAnimationScene()
for cue in scene.Cues:
if cue.AnimatedProxy == view and\
cue.GetXMLName() == "CameraAnimationCue":
return cue
# no cue was found, create a new one.
cue = CameraAnimationCue()
cue.AnimatedProxy = view
scene.Cues.append(cue)
return cue | [
"def",
"GetCameraTrack",
"(",
"view",
"=",
"None",
")",
":",
"if",
"not",
"view",
":",
"view",
"=",
"GetActiveView",
"(",
")",
"if",
"not",
"view",
":",
"raise",
"ValueError",
"(",
"\"No view specified\"",
")",
"scene",
"=",
"GetAnimationScene",
"(",
")",
"for",
"cue",
"in",
"scene",
".",
"Cues",
":",
"if",
"cue",
".",
"AnimatedProxy",
"==",
"view",
"and",
"cue",
".",
"GetXMLName",
"(",
")",
"==",
"\"CameraAnimationCue\"",
":",
"return",
"cue",
"# no cue was found, create a new one.",
"cue",
"=",
"CameraAnimationCue",
"(",
")",
"cue",
".",
"AnimatedProxy",
"=",
"view",
"scene",
".",
"Cues",
".",
"append",
"(",
"cue",
")",
"return",
"cue"
] | https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/Wrapping/Python/paraview/simple.py#L2177-L2194 | |
albertz/openlierox | d316c14a8eb57848ef56e9bfa7b23a56f694a51b | tools/DedicatedServerVideo/gdata/tlslite/mathtls.py | python | MAC_SSL.update | (self, msg) | Update this hashing object with the string msg. | Update this hashing object with the string msg. | [
"Update",
"this",
"hashing",
"object",
"with",
"the",
"string",
"msg",
"."
] | def update(self, msg):
"""Update this hashing object with the string msg.
"""
self.inner.update(msg) | [
"def",
"update",
"(",
"self",
",",
"msg",
")",
":",
"self",
".",
"inner",
".",
"update",
"(",
"msg",
")"
] | https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/tlslite/mathtls.py#L138-L141 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/linalg/linear_operator_algebra.py | python | adjoint | (lin_op_a, name=None) | Get the adjoint associated to lin_op_a.
Args:
lin_op_a: The LinearOperator to take the adjoint of.
name: Name to use for this operation.
Returns:
A LinearOperator that represents the adjoint of `lin_op_a`.
Raises:
NotImplementedError: If no Adjoint method is defined for the LinearOperator
type of `lin_op_a`. | Get the adjoint associated to lin_op_a. | [
"Get",
"the",
"adjoint",
"associated",
"to",
"lin_op_a",
"."
] | def adjoint(lin_op_a, name=None):
"""Get the adjoint associated to lin_op_a.
Args:
lin_op_a: The LinearOperator to take the adjoint of.
name: Name to use for this operation.
Returns:
A LinearOperator that represents the adjoint of `lin_op_a`.
Raises:
NotImplementedError: If no Adjoint method is defined for the LinearOperator
type of `lin_op_a`.
"""
adjoint_fn = _registered_adjoint(type(lin_op_a))
if adjoint_fn is None:
raise ValueError("No adjoint registered for {}".format(
type(lin_op_a)))
with ops.name_scope(name, "Adjoint"):
return adjoint_fn(lin_op_a) | [
"def",
"adjoint",
"(",
"lin_op_a",
",",
"name",
"=",
"None",
")",
":",
"adjoint_fn",
"=",
"_registered_adjoint",
"(",
"type",
"(",
"lin_op_a",
")",
")",
"if",
"adjoint_fn",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"No adjoint registered for {}\"",
".",
"format",
"(",
"type",
"(",
"lin_op_a",
")",
")",
")",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"\"Adjoint\"",
")",
":",
"return",
"adjoint_fn",
"(",
"lin_op_a",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/linalg/linear_operator_algebra.py#L72-L92 | ||
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/gluon/nn/basic_layers.py | python | Sequential.add | (self, *blocks) | Adds block on top of the stack. | Adds block on top of the stack. | [
"Adds",
"block",
"on",
"top",
"of",
"the",
"stack",
"."
] | def add(self, *blocks):
"""Adds block on top of the stack."""
for block in blocks:
self._layers.append(block)
self.register_child(block) | [
"def",
"add",
"(",
"self",
",",
"*",
"blocks",
")",
":",
"for",
"block",
"in",
"blocks",
":",
"self",
".",
"_layers",
".",
"append",
"(",
"block",
")",
"self",
".",
"register_child",
"(",
"block",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/gluon/nn/basic_layers.py#L49-L53 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/plat-mac/findertools.py | python | update | (file) | return finder.update(file_alias) | Update the display of the specified object(s) to match
their on-disk representation. Specify file by name, fsref or fsspec. | Update the display of the specified object(s) to match
their on-disk representation. Specify file by name, fsref or fsspec. | [
"Update",
"the",
"display",
"of",
"the",
"specified",
"object",
"(",
"s",
")",
"to",
"match",
"their",
"on",
"-",
"disk",
"representation",
".",
"Specify",
"file",
"by",
"name",
"fsref",
"or",
"fsspec",
"."
] | def update(file):
"""Update the display of the specified object(s) to match
their on-disk representation. Specify file by name, fsref or fsspec."""
finder = _getfinder()
fsr = Carbon.File.FSRef(file)
file_alias = fsr.FSNewAliasMinimal()
return finder.update(file_alias) | [
"def",
"update",
"(",
"file",
")",
":",
"finder",
"=",
"_getfinder",
"(",
")",
"fsr",
"=",
"Carbon",
".",
"File",
".",
"FSRef",
"(",
"file",
")",
"file_alias",
"=",
"fsr",
".",
"FSNewAliasMinimal",
"(",
")",
"return",
"finder",
".",
"update",
"(",
"file_alias",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/plat-mac/findertools.py#L115-L121 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/external/boost/boost_1_68_0/libs/mpl/preprocessed/fix_boost_mpl_preprocess.py | python | check_header_comment | (filename) | return True | Checks if the header-comment of the given file needs fixing. | Checks if the header-comment of the given file needs fixing. | [
"Checks",
"if",
"the",
"header",
"-",
"comment",
"of",
"the",
"given",
"file",
"needs",
"fixing",
"."
] | def check_header_comment(filename):
"""Checks if the header-comment of the given file needs fixing."""
# Check input file.
name = os.path.basename( filename )
# Read content of input file.
sourcefile = open( filename, "rU" )
content = sourcefile.read()
sourcefile.close()
# Search content for '$Id$'.
match = re.search(r'\$Id\$', content)
if match == None:
# Make sure that the correct value for '$Id$' was already set.
match = re.search(r'\$Id: ' + name + r'\s+[^$]+\$', content)
if match != None:
# The given file needs no fixing.
return False
# The given file needs fixing.
return True | [
"def",
"check_header_comment",
"(",
"filename",
")",
":",
"# Check input file.",
"name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
"# Read content of input file.",
"sourcefile",
"=",
"open",
"(",
"filename",
",",
"\"rU\"",
")",
"content",
"=",
"sourcefile",
".",
"read",
"(",
")",
"sourcefile",
".",
"close",
"(",
")",
"# Search content for '$Id$'.",
"match",
"=",
"re",
".",
"search",
"(",
"r'\\$Id\\$'",
",",
"content",
")",
"if",
"match",
"==",
"None",
":",
"# Make sure that the correct value for '$Id$' was already set.",
"match",
"=",
"re",
".",
"search",
"(",
"r'\\$Id: '",
"+",
"name",
"+",
"r'\\s+[^$]+\\$'",
",",
"content",
")",
"if",
"match",
"!=",
"None",
":",
"# The given file needs no fixing.",
"return",
"False",
"# The given file needs fixing.",
"return",
"True"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/boost/boost_1_68_0/libs/mpl/preprocessed/fix_boost_mpl_preprocess.py#L19-L36 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/math/autodiff/ad.py | python | finite_differences_hessian | (f,x,h) | return g/h**2 | Performs forward differences to approximate the Hessian of f(x) w.r.t.
x. | Performs forward differences to approximate the Hessian of f(x) w.r.t.
x. | [
"Performs",
"forward",
"differences",
"to",
"approximate",
"the",
"Hessian",
"of",
"f",
"(",
"x",
")",
"w",
".",
"r",
".",
"t",
".",
"x",
"."
] | def finite_differences_hessian(f,x,h):
"""Performs forward differences to approximate the Hessian of f(x) w.r.t.
x.
"""
f0 = f(x)
g = np.empty((_size(f0),_size(x),_size(x)))
if hasattr(x,'__iter__'):
xtemp = x.astype(float,copy=True)
fx = []
for i in range(len(x)):
xtemp[i] += h
fx.append(np.copy(f(xtemp)))
xtemp[i] = x[i]
for i in range(len(x)):
xtemp[i] -= h
g[:,i,i] = (fx[i] - 2*f0 + f(xtemp))
xtemp[i] = x[i]
xtemp[i] += h
for j in range(i):
xtemp[j] += h
g[:,j,i] = g[:,i,j] = (f(xtemp) - fx[i]) - (fx[j] - f0)
xtemp[j] = x[j]
xtemp[i] = x[i]
else:
fx = f(x+h)
g[:,0,0] = (fx - 2*f0 + f(x-h))
return g/h**2 | [
"def",
"finite_differences_hessian",
"(",
"f",
",",
"x",
",",
"h",
")",
":",
"f0",
"=",
"f",
"(",
"x",
")",
"g",
"=",
"np",
".",
"empty",
"(",
"(",
"_size",
"(",
"f0",
")",
",",
"_size",
"(",
"x",
")",
",",
"_size",
"(",
"x",
")",
")",
")",
"if",
"hasattr",
"(",
"x",
",",
"'__iter__'",
")",
":",
"xtemp",
"=",
"x",
".",
"astype",
"(",
"float",
",",
"copy",
"=",
"True",
")",
"fx",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"x",
")",
")",
":",
"xtemp",
"[",
"i",
"]",
"+=",
"h",
"fx",
".",
"append",
"(",
"np",
".",
"copy",
"(",
"f",
"(",
"xtemp",
")",
")",
")",
"xtemp",
"[",
"i",
"]",
"=",
"x",
"[",
"i",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"x",
")",
")",
":",
"xtemp",
"[",
"i",
"]",
"-=",
"h",
"g",
"[",
":",
",",
"i",
",",
"i",
"]",
"=",
"(",
"fx",
"[",
"i",
"]",
"-",
"2",
"*",
"f0",
"+",
"f",
"(",
"xtemp",
")",
")",
"xtemp",
"[",
"i",
"]",
"=",
"x",
"[",
"i",
"]",
"xtemp",
"[",
"i",
"]",
"+=",
"h",
"for",
"j",
"in",
"range",
"(",
"i",
")",
":",
"xtemp",
"[",
"j",
"]",
"+=",
"h",
"g",
"[",
":",
",",
"j",
",",
"i",
"]",
"=",
"g",
"[",
":",
",",
"i",
",",
"j",
"]",
"=",
"(",
"f",
"(",
"xtemp",
")",
"-",
"fx",
"[",
"i",
"]",
")",
"-",
"(",
"fx",
"[",
"j",
"]",
"-",
"f0",
")",
"xtemp",
"[",
"j",
"]",
"=",
"x",
"[",
"j",
"]",
"xtemp",
"[",
"i",
"]",
"=",
"x",
"[",
"i",
"]",
"else",
":",
"fx",
"=",
"f",
"(",
"x",
"+",
"h",
")",
"g",
"[",
":",
",",
"0",
",",
"0",
"]",
"=",
"(",
"fx",
"-",
"2",
"*",
"f0",
"+",
"f",
"(",
"x",
"-",
"h",
")",
")",
"return",
"g",
"/",
"h",
"**",
"2"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/math/autodiff/ad.py#L1118-L1144 | |
Cantera/cantera | 0119484b261967ccb55a0066c020599cacc312e4 | interfaces/cython/cantera/composite.py | python | SolutionArray.append | (self, state=None, normalize=True, **kwargs) | Append an element to the array with the specified state. Elements can
only be appended in cases where the array of states is one-dimensional.
The state may be specified in one of three ways:
- as the array of [temperature, density, mass fractions] which is
returned by `Solution.state`::
mystates.append(gas.state)
- as a tuple of three elements that corresponds to any of the full-state
setters of `Solution`, e.g. `TPY` or `HPX`::
mystates.append(TPX=(300, 101325, 'O2:1.0, N2:3.76'))
- as separate keywords for each of the elements corresponding to one of
the full-state setters::
mystates.append(T=300, P=101325, X={'O2':1.0, 'N2':3.76})
By default, the mass or mole fractions will be normalized i.e negative values
are truncated and the mass or mole fractions sum up to 1.0. If this
is not desired, the ``normalize`` argument can be set to ``False``. | Append an element to the array with the specified state. Elements can
only be appended in cases where the array of states is one-dimensional. | [
"Append",
"an",
"element",
"to",
"the",
"array",
"with",
"the",
"specified",
"state",
".",
"Elements",
"can",
"only",
"be",
"appended",
"in",
"cases",
"where",
"the",
"array",
"of",
"states",
"is",
"one",
"-",
"dimensional",
"."
] | def append(self, state=None, normalize=True, **kwargs):
"""
Append an element to the array with the specified state. Elements can
only be appended in cases where the array of states is one-dimensional.
The state may be specified in one of three ways:
- as the array of [temperature, density, mass fractions] which is
returned by `Solution.state`::
mystates.append(gas.state)
- as a tuple of three elements that corresponds to any of the full-state
setters of `Solution`, e.g. `TPY` or `HPX`::
mystates.append(TPX=(300, 101325, 'O2:1.0, N2:3.76'))
- as separate keywords for each of the elements corresponding to one of
the full-state setters::
mystates.append(T=300, P=101325, X={'O2':1.0, 'N2':3.76})
By default, the mass or mole fractions will be normalized i.e negative values
are truncated and the mass or mole fractions sum up to 1.0. If this
is not desired, the ``normalize`` argument can be set to ``False``.
"""
if len(self._shape) != 1:
raise IndexError("Can only append to 1D SolutionArray")
# This check must go before we start appending to any arrays so that
# array lengths don't get out of sync.
missing_extra_kwargs = self._extra.keys() - kwargs.keys()
if missing_extra_kwargs:
raise TypeError(
"Missing keyword arguments for extra values: "
"'{}'".format(", ".join(missing_extra_kwargs))
)
# For the checks of the state below, the kwargs dictionary can
# only contain keywords that match properties of the state. Here
# we pop any kwargs that have to do with the extra items so they
# aren't included in that check. They are put into a temporary
# storage so that appending can be done at the end of the function
# all at once.
extra_temp = {}
for name in self._extra:
extra_temp[name] = kwargs.pop(name)
if state is not None:
self._phase.state = state
elif len(kwargs) == 1:
attr, value = kwargs.popitem()
if frozenset(attr) not in self._phase._full_states:
raise KeyError(
"'{}' does not specify a full thermodynamic state".format(attr)
)
if normalize or attr.endswith("Q"):
setattr(self._phase, attr, value)
else:
if attr.endswith("X"):
self._phase.set_unnormalized_mole_fractions(value[-1])
elif attr.endswith("Y"):
self._phase.set_unnormalized_mass_fractions(value[-1])
attr = attr[:-1]
value = value[:-1]
setattr(self._phase, attr, value)
else:
try:
attr = self._phase._full_states[frozenset(kwargs)]
except KeyError:
raise KeyError(
"{} is not a valid combination of properties for setting "
"the thermodynamic state".format(tuple(kwargs))
) from None
if normalize or attr.endswith("Q"):
setattr(self._phase, attr, list(kwargs.values()))
else:
if attr.endswith("X"):
self._phase.set_unnormalized_mole_fractions(kwargs.pop("X"))
elif attr.endswith("Y"):
self._phase.set_unnormalized_mass_fractions(kwargs.pop("Y"))
attr = attr[:-1]
setattr(self._phase, attr, list(kwargs.values()))
for name, value in self._extra.items():
new = extra_temp[name]
if len(value):
if (value.ndim == 1 and hasattr(new, '__len__') and
not isinstance(new, str)):
raise ValueError(
"Encountered incompatible value '{}' for extra column '{}'."
"".format(new, name))
elif value.ndim > 1 and value.shape[1:] != np.array(new).shape:
raise ValueError(
"Shape of new element does not match existing extra "
"column '{}'".format(name))
# Casting to a list before appending is ~5x faster than using
# np.append when appending a single item.
v = value.tolist()
v.append(new)
extra_temp[name] = np.array(v)
for name, value in extra_temp.items():
self._extra[name] = value
self._states.append(self._phase.state)
self._indices.append(len(self._indices))
self._shape = (len(self._indices),) | [
"def",
"append",
"(",
"self",
",",
"state",
"=",
"None",
",",
"normalize",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"self",
".",
"_shape",
")",
"!=",
"1",
":",
"raise",
"IndexError",
"(",
"\"Can only append to 1D SolutionArray\"",
")",
"# This check must go before we start appending to any arrays so that",
"# array lengths don't get out of sync.",
"missing_extra_kwargs",
"=",
"self",
".",
"_extra",
".",
"keys",
"(",
")",
"-",
"kwargs",
".",
"keys",
"(",
")",
"if",
"missing_extra_kwargs",
":",
"raise",
"TypeError",
"(",
"\"Missing keyword arguments for extra values: \"",
"\"'{}'\"",
".",
"format",
"(",
"\", \"",
".",
"join",
"(",
"missing_extra_kwargs",
")",
")",
")",
"# For the checks of the state below, the kwargs dictionary can",
"# only contain keywords that match properties of the state. Here",
"# we pop any kwargs that have to do with the extra items so they",
"# aren't included in that check. They are put into a temporary",
"# storage so that appending can be done at the end of the function",
"# all at once.",
"extra_temp",
"=",
"{",
"}",
"for",
"name",
"in",
"self",
".",
"_extra",
":",
"extra_temp",
"[",
"name",
"]",
"=",
"kwargs",
".",
"pop",
"(",
"name",
")",
"if",
"state",
"is",
"not",
"None",
":",
"self",
".",
"_phase",
".",
"state",
"=",
"state",
"elif",
"len",
"(",
"kwargs",
")",
"==",
"1",
":",
"attr",
",",
"value",
"=",
"kwargs",
".",
"popitem",
"(",
")",
"if",
"frozenset",
"(",
"attr",
")",
"not",
"in",
"self",
".",
"_phase",
".",
"_full_states",
":",
"raise",
"KeyError",
"(",
"\"'{}' does not specify a full thermodynamic state\"",
".",
"format",
"(",
"attr",
")",
")",
"if",
"normalize",
"or",
"attr",
".",
"endswith",
"(",
"\"Q\"",
")",
":",
"setattr",
"(",
"self",
".",
"_phase",
",",
"attr",
",",
"value",
")",
"else",
":",
"if",
"attr",
".",
"endswith",
"(",
"\"X\"",
")",
":",
"self",
".",
"_phase",
".",
"set_unnormalized_mole_fractions",
"(",
"value",
"[",
"-",
"1",
"]",
")",
"elif",
"attr",
".",
"endswith",
"(",
"\"Y\"",
")",
":",
"self",
".",
"_phase",
".",
"set_unnormalized_mass_fractions",
"(",
"value",
"[",
"-",
"1",
"]",
")",
"attr",
"=",
"attr",
"[",
":",
"-",
"1",
"]",
"value",
"=",
"value",
"[",
":",
"-",
"1",
"]",
"setattr",
"(",
"self",
".",
"_phase",
",",
"attr",
",",
"value",
")",
"else",
":",
"try",
":",
"attr",
"=",
"self",
".",
"_phase",
".",
"_full_states",
"[",
"frozenset",
"(",
"kwargs",
")",
"]",
"except",
"KeyError",
":",
"raise",
"KeyError",
"(",
"\"{} is not a valid combination of properties for setting \"",
"\"the thermodynamic state\"",
".",
"format",
"(",
"tuple",
"(",
"kwargs",
")",
")",
")",
"from",
"None",
"if",
"normalize",
"or",
"attr",
".",
"endswith",
"(",
"\"Q\"",
")",
":",
"setattr",
"(",
"self",
".",
"_phase",
",",
"attr",
",",
"list",
"(",
"kwargs",
".",
"values",
"(",
")",
")",
")",
"else",
":",
"if",
"attr",
".",
"endswith",
"(",
"\"X\"",
")",
":",
"self",
".",
"_phase",
".",
"set_unnormalized_mole_fractions",
"(",
"kwargs",
".",
"pop",
"(",
"\"X\"",
")",
")",
"elif",
"attr",
".",
"endswith",
"(",
"\"Y\"",
")",
":",
"self",
".",
"_phase",
".",
"set_unnormalized_mass_fractions",
"(",
"kwargs",
".",
"pop",
"(",
"\"Y\"",
")",
")",
"attr",
"=",
"attr",
"[",
":",
"-",
"1",
"]",
"setattr",
"(",
"self",
".",
"_phase",
",",
"attr",
",",
"list",
"(",
"kwargs",
".",
"values",
"(",
")",
")",
")",
"for",
"name",
",",
"value",
"in",
"self",
".",
"_extra",
".",
"items",
"(",
")",
":",
"new",
"=",
"extra_temp",
"[",
"name",
"]",
"if",
"len",
"(",
"value",
")",
":",
"if",
"(",
"value",
".",
"ndim",
"==",
"1",
"and",
"hasattr",
"(",
"new",
",",
"'__len__'",
")",
"and",
"not",
"isinstance",
"(",
"new",
",",
"str",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"Encountered incompatible value '{}' for extra column '{}'.\"",
"\"\"",
".",
"format",
"(",
"new",
",",
"name",
")",
")",
"elif",
"value",
".",
"ndim",
">",
"1",
"and",
"value",
".",
"shape",
"[",
"1",
":",
"]",
"!=",
"np",
".",
"array",
"(",
"new",
")",
".",
"shape",
":",
"raise",
"ValueError",
"(",
"\"Shape of new element does not match existing extra \"",
"\"column '{}'\"",
".",
"format",
"(",
"name",
")",
")",
"# Casting to a list before appending is ~5x faster than using",
"# np.append when appending a single item.",
"v",
"=",
"value",
".",
"tolist",
"(",
")",
"v",
".",
"append",
"(",
"new",
")",
"extra_temp",
"[",
"name",
"]",
"=",
"np",
".",
"array",
"(",
"v",
")",
"for",
"name",
",",
"value",
"in",
"extra_temp",
".",
"items",
"(",
")",
":",
"self",
".",
"_extra",
"[",
"name",
"]",
"=",
"value",
"self",
".",
"_states",
".",
"append",
"(",
"self",
".",
"_phase",
".",
"state",
")",
"self",
".",
"_indices",
".",
"append",
"(",
"len",
"(",
"self",
".",
"_indices",
")",
")",
"self",
".",
"_shape",
"=",
"(",
"len",
"(",
"self",
".",
"_indices",
")",
",",
")"
] | https://github.com/Cantera/cantera/blob/0119484b261967ccb55a0066c020599cacc312e4/interfaces/cython/cantera/composite.py#L648-L757 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/autocomp/htmlcomp.py | python | Completer.OnCompletionInserted | (self, pos, text) | Handle adjusting caret position after some insertions.
@param pos: position caret was at before insertion
@param text: text that was inserted | Handle adjusting caret position after some insertions.
@param pos: position caret was at before insertion
@param text: text that was inserted | [
"Handle",
"adjusting",
"caret",
"position",
"after",
"some",
"insertions",
".",
"@param",
"pos",
":",
"position",
"caret",
"was",
"at",
"before",
"insertion",
"@param",
"text",
":",
"text",
"that",
"was",
"inserted"
] | def OnCompletionInserted(self, pos, text):
"""Handle adjusting caret position after some insertions.
@param pos: position caret was at before insertion
@param text: text that was inserted
"""
buff = self.GetBuffer()
if text.strip().startswith(u"</"):
buff.SetCurrentPos(pos) # move caret back between the tags
# HACK: SetCurrentPos causes text to be selected
buff.SetSelection(pos, pos) | [
"def",
"OnCompletionInserted",
"(",
"self",
",",
"pos",
",",
"text",
")",
":",
"buff",
"=",
"self",
".",
"GetBuffer",
"(",
")",
"if",
"text",
".",
"strip",
"(",
")",
".",
"startswith",
"(",
"u\"</\"",
")",
":",
"buff",
".",
"SetCurrentPos",
"(",
"pos",
")",
"# move caret back between the tags",
"# HACK: SetCurrentPos causes text to be selected",
"buff",
".",
"SetSelection",
"(",
"pos",
",",
"pos",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/autocomp/htmlcomp.py#L164-L174 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/auto_bisect/bisect_perf_regression.py | python | BisectPerformanceMetrics._SyncRevision | (self, depot, revision, sync_client) | return source_control.SyncToRevision(revision, sync_client) | Syncs depot to particular revision.
Args:
depot: The depot that's being used at the moment (src, webkit, etc.)
revision: The revision to sync to.
sync_client: Program used to sync, e.g. "gclient". Can be None.
Returns:
True if successful, False otherwise. | Syncs depot to particular revision. | [
"Syncs",
"depot",
"to",
"particular",
"revision",
"."
] | def _SyncRevision(self, depot, revision, sync_client):
"""Syncs depot to particular revision.
Args:
depot: The depot that's being used at the moment (src, webkit, etc.)
revision: The revision to sync to.
sync_client: Program used to sync, e.g. "gclient". Can be None.
Returns:
True if successful, False otherwise.
"""
self.depot_registry.ChangeToDepotDir(depot)
if sync_client:
self.PerformPreBuildCleanup()
# When using gclient to sync, you need to specify the depot you
# want so that all the dependencies sync properly as well.
# i.e. gclient sync src@<SHA1>
if sync_client == 'gclient' and revision:
revision = '%s@%s' % (bisect_utils.DEPOT_DEPS_NAME[depot]['src'],
revision)
if depot == 'chromium' and self.opts.target_platform == 'android-chrome':
return self._SyncRevisionsForAndroidChrome(revision)
return source_control.SyncToRevision(revision, sync_client) | [
"def",
"_SyncRevision",
"(",
"self",
",",
"depot",
",",
"revision",
",",
"sync_client",
")",
":",
"self",
".",
"depot_registry",
".",
"ChangeToDepotDir",
"(",
"depot",
")",
"if",
"sync_client",
":",
"self",
".",
"PerformPreBuildCleanup",
"(",
")",
"# When using gclient to sync, you need to specify the depot you",
"# want so that all the dependencies sync properly as well.",
"# i.e. gclient sync src@<SHA1>",
"if",
"sync_client",
"==",
"'gclient'",
"and",
"revision",
":",
"revision",
"=",
"'%s@%s'",
"%",
"(",
"bisect_utils",
".",
"DEPOT_DEPS_NAME",
"[",
"depot",
"]",
"[",
"'src'",
"]",
",",
"revision",
")",
"if",
"depot",
"==",
"'chromium'",
"and",
"self",
".",
"opts",
".",
"target_platform",
"==",
"'android-chrome'",
":",
"return",
"self",
".",
"_SyncRevisionsForAndroidChrome",
"(",
"revision",
")",
"return",
"source_control",
".",
"SyncToRevision",
"(",
"revision",
",",
"sync_client",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/auto_bisect/bisect_perf_regression.py#L1543-L1568 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqt/mantidqt/widgets/workspacedisplay/matrix/model.py | python | MatrixWorkspaceDisplayModel.supports | (cls, ws) | Checks that the provided workspace is supported by this display.
:param ws: Workspace to be checked for support
:raises ValueError: if the workspace is not supported | Checks that the provided workspace is supported by this display.
:param ws: Workspace to be checked for support
:raises ValueError: if the workspace is not supported | [
"Checks",
"that",
"the",
"provided",
"workspace",
"is",
"supported",
"by",
"this",
"display",
".",
":",
"param",
"ws",
":",
"Workspace",
"to",
"be",
"checked",
"for",
"support",
":",
"raises",
"ValueError",
":",
"if",
"the",
"workspace",
"is",
"not",
"supported"
] | def supports(cls, ws):
"""
Checks that the provided workspace is supported by this display.
:param ws: Workspace to be checked for support
:raises ValueError: if the workspace is not supported
"""
if not any(isinstance(ws, allowed_type) for allowed_type in cls.ALLOWED_WORKSPACE_TYPES):
raise ValueError("The workspace type is not supported: {0}".format(ws)) | [
"def",
"supports",
"(",
"cls",
",",
"ws",
")",
":",
"if",
"not",
"any",
"(",
"isinstance",
"(",
"ws",
",",
"allowed_type",
")",
"for",
"allowed_type",
"in",
"cls",
".",
"ALLOWED_WORKSPACE_TYPES",
")",
":",
"raise",
"ValueError",
"(",
"\"The workspace type is not supported: {0}\"",
".",
"format",
"(",
"ws",
")",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/workspacedisplay/matrix/model.py#L24-L31 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | GridSizer.CalcRowsCols | (self) | return (rows, cols) | CalcRowsCols() -> (rows, cols)
Calculates how many rows and columns will be in the sizer based
on the current number of items and also the rows, cols specified
in the constructor. | CalcRowsCols() -> (rows, cols) | [
"CalcRowsCols",
"()",
"-",
">",
"(",
"rows",
"cols",
")"
] | def CalcRowsCols(self):
"""
CalcRowsCols() -> (rows, cols)
Calculates how many rows and columns will be in the sizer based
on the current number of items and also the rows, cols specified
in the constructor.
"""
nitems = len(self.GetChildren())
rows = self.GetRows()
cols = self.GetCols()
assert rows != 0 or cols != 0, "Grid sizer must have either rows or columns fixed"
if cols != 0:
rows = (nitems + cols - 1) / cols
elif rows != 0:
cols = (nitems + rows - 1) / rows
return (rows, cols) | [
"def",
"CalcRowsCols",
"(",
"self",
")",
":",
"nitems",
"=",
"len",
"(",
"self",
".",
"GetChildren",
"(",
")",
")",
"rows",
"=",
"self",
".",
"GetRows",
"(",
")",
"cols",
"=",
"self",
".",
"GetCols",
"(",
")",
"assert",
"rows",
"!=",
"0",
"or",
"cols",
"!=",
"0",
",",
"\"Grid sizer must have either rows or columns fixed\"",
"if",
"cols",
"!=",
"0",
":",
"rows",
"=",
"(",
"nitems",
"+",
"cols",
"-",
"1",
")",
"/",
"cols",
"elif",
"rows",
"!=",
"0",
":",
"cols",
"=",
"(",
"nitems",
"+",
"rows",
"-",
"1",
")",
"/",
"rows",
"return",
"(",
"rows",
",",
"cols",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L15273-L15289 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/urllib3/contrib/_securetransport/low_level.py | python | _cert_array_from_pem | (pem_bundle) | return cert_array | Given a bundle of certs in PEM format, turns them into a CFArray of certs
that can be used to validate a cert chain. | Given a bundle of certs in PEM format, turns them into a CFArray of certs
that can be used to validate a cert chain. | [
"Given",
"a",
"bundle",
"of",
"certs",
"in",
"PEM",
"format",
"turns",
"them",
"into",
"a",
"CFArray",
"of",
"certs",
"that",
"can",
"be",
"used",
"to",
"validate",
"a",
"cert",
"chain",
"."
] | def _cert_array_from_pem(pem_bundle):
"""
Given a bundle of certs in PEM format, turns them into a CFArray of certs
that can be used to validate a cert chain.
"""
# Normalize the PEM bundle's line endings.
pem_bundle = pem_bundle.replace(b"\r\n", b"\n")
der_certs = [
base64.b64decode(match.group(1)) for match in _PEM_CERTS_RE.finditer(pem_bundle)
]
if not der_certs:
raise ssl.SSLError("No root certificates specified")
cert_array = CoreFoundation.CFArrayCreateMutable(
CoreFoundation.kCFAllocatorDefault,
0,
ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks),
)
if not cert_array:
raise ssl.SSLError("Unable to allocate memory!")
try:
for der_bytes in der_certs:
certdata = _cf_data_from_bytes(der_bytes)
if not certdata:
raise ssl.SSLError("Unable to allocate memory!")
cert = Security.SecCertificateCreateWithData(
CoreFoundation.kCFAllocatorDefault, certdata
)
CoreFoundation.CFRelease(certdata)
if not cert:
raise ssl.SSLError("Unable to build cert object!")
CoreFoundation.CFArrayAppendValue(cert_array, cert)
CoreFoundation.CFRelease(cert)
except Exception:
# We need to free the array before the exception bubbles further.
# We only want to do that if an error occurs: otherwise, the caller
# should free.
CoreFoundation.CFRelease(cert_array)
return cert_array | [
"def",
"_cert_array_from_pem",
"(",
"pem_bundle",
")",
":",
"# Normalize the PEM bundle's line endings.",
"pem_bundle",
"=",
"pem_bundle",
".",
"replace",
"(",
"b\"\\r\\n\"",
",",
"b\"\\n\"",
")",
"der_certs",
"=",
"[",
"base64",
".",
"b64decode",
"(",
"match",
".",
"group",
"(",
"1",
")",
")",
"for",
"match",
"in",
"_PEM_CERTS_RE",
".",
"finditer",
"(",
"pem_bundle",
")",
"]",
"if",
"not",
"der_certs",
":",
"raise",
"ssl",
".",
"SSLError",
"(",
"\"No root certificates specified\"",
")",
"cert_array",
"=",
"CoreFoundation",
".",
"CFArrayCreateMutable",
"(",
"CoreFoundation",
".",
"kCFAllocatorDefault",
",",
"0",
",",
"ctypes",
".",
"byref",
"(",
"CoreFoundation",
".",
"kCFTypeArrayCallBacks",
")",
",",
")",
"if",
"not",
"cert_array",
":",
"raise",
"ssl",
".",
"SSLError",
"(",
"\"Unable to allocate memory!\"",
")",
"try",
":",
"for",
"der_bytes",
"in",
"der_certs",
":",
"certdata",
"=",
"_cf_data_from_bytes",
"(",
"der_bytes",
")",
"if",
"not",
"certdata",
":",
"raise",
"ssl",
".",
"SSLError",
"(",
"\"Unable to allocate memory!\"",
")",
"cert",
"=",
"Security",
".",
"SecCertificateCreateWithData",
"(",
"CoreFoundation",
".",
"kCFAllocatorDefault",
",",
"certdata",
")",
"CoreFoundation",
".",
"CFRelease",
"(",
"certdata",
")",
"if",
"not",
"cert",
":",
"raise",
"ssl",
".",
"SSLError",
"(",
"\"Unable to build cert object!\"",
")",
"CoreFoundation",
".",
"CFArrayAppendValue",
"(",
"cert_array",
",",
"cert",
")",
"CoreFoundation",
".",
"CFRelease",
"(",
"cert",
")",
"except",
"Exception",
":",
"# We need to free the array before the exception bubbles further.",
"# We only want to do that if an error occurs: otherwise, the caller",
"# should free.",
"CoreFoundation",
".",
"CFRelease",
"(",
"cert_array",
")",
"return",
"cert_array"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/urllib3/contrib/_securetransport/low_level.py#L105-L147 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/traitlets/py2/traitlets/config/configurable.py | python | Configurable.class_get_trait_help | (cls, trait, inst=None) | return '\n'.join(lines) | Get the help string for a single trait.
If `inst` is given, it's current trait values will be used in place of
the class default. | Get the help string for a single trait. | [
"Get",
"the",
"help",
"string",
"for",
"a",
"single",
"trait",
"."
] | def class_get_trait_help(cls, trait, inst=None):
"""Get the help string for a single trait.
If `inst` is given, it's current trait values will be used in place of
the class default.
"""
assert inst is None or isinstance(inst, cls)
lines = []
header = "--%s.%s=<%s>" % (cls.__name__, trait.name, trait.__class__.__name__)
lines.append(header)
if inst is not None:
lines.append(indent('Current: %r' % getattr(inst, trait.name), 4))
else:
try:
dvr = trait.default_value_repr()
except Exception:
dvr = None # ignore defaults we can't construct
if dvr is not None:
if len(dvr) > 64:
dvr = dvr[:61]+'...'
lines.append(indent('Default: %s' % dvr, 4))
if 'Enum' in trait.__class__.__name__:
# include Enum choices
lines.append(indent('Choices: %r' % (trait.values,)))
help = trait.help
if help != '':
help = '\n'.join(wrap_paragraphs(help, 76))
lines.append(indent(help, 4))
return '\n'.join(lines) | [
"def",
"class_get_trait_help",
"(",
"cls",
",",
"trait",
",",
"inst",
"=",
"None",
")",
":",
"assert",
"inst",
"is",
"None",
"or",
"isinstance",
"(",
"inst",
",",
"cls",
")",
"lines",
"=",
"[",
"]",
"header",
"=",
"\"--%s.%s=<%s>\"",
"%",
"(",
"cls",
".",
"__name__",
",",
"trait",
".",
"name",
",",
"trait",
".",
"__class__",
".",
"__name__",
")",
"lines",
".",
"append",
"(",
"header",
")",
"if",
"inst",
"is",
"not",
"None",
":",
"lines",
".",
"append",
"(",
"indent",
"(",
"'Current: %r'",
"%",
"getattr",
"(",
"inst",
",",
"trait",
".",
"name",
")",
",",
"4",
")",
")",
"else",
":",
"try",
":",
"dvr",
"=",
"trait",
".",
"default_value_repr",
"(",
")",
"except",
"Exception",
":",
"dvr",
"=",
"None",
"# ignore defaults we can't construct",
"if",
"dvr",
"is",
"not",
"None",
":",
"if",
"len",
"(",
"dvr",
")",
">",
"64",
":",
"dvr",
"=",
"dvr",
"[",
":",
"61",
"]",
"+",
"'...'",
"lines",
".",
"append",
"(",
"indent",
"(",
"'Default: %s'",
"%",
"dvr",
",",
"4",
")",
")",
"if",
"'Enum'",
"in",
"trait",
".",
"__class__",
".",
"__name__",
":",
"# include Enum choices",
"lines",
".",
"append",
"(",
"indent",
"(",
"'Choices: %r'",
"%",
"(",
"trait",
".",
"values",
",",
")",
")",
")",
"help",
"=",
"trait",
".",
"help",
"if",
"help",
"!=",
"''",
":",
"help",
"=",
"'\\n'",
".",
"join",
"(",
"wrap_paragraphs",
"(",
"help",
",",
"76",
")",
")",
"lines",
".",
"append",
"(",
"indent",
"(",
"help",
",",
"4",
")",
")",
"return",
"'\\n'",
".",
"join",
"(",
"lines",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/traitlets/py2/traitlets/config/configurable.py#L221-L250 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/ops/variable_scope.py | python | VariableScope._get_partitioned_variable | (self,
var_store,
name,
shape=None,
dtype=None,
initializer=None,
regularizer=None,
trainable=True,
collections=None,
caching_device=None,
partitioner=None,
validate_shape=True) | Gets an existing variable with this name or create a new one. | Gets an existing variable with this name or create a new one. | [
"Gets",
"an",
"existing",
"variable",
"with",
"this",
"name",
"or",
"create",
"a",
"new",
"one",
"."
] | def _get_partitioned_variable(self,
var_store,
name,
shape=None,
dtype=None,
initializer=None,
regularizer=None,
trainable=True,
collections=None,
caching_device=None,
partitioner=None,
validate_shape=True):
"""Gets an existing variable with this name or create a new one."""
if initializer is None:
initializer = self._initializer
if regularizer is None:
regularizer = self._regularizer
if caching_device is None:
caching_device = self._caching_device
if partitioner is None:
partitioner = self._partitioner
if dtype is None:
dtype = self._dtype
if self._custom_getter is not None:
raise ValueError(
"Private access to _get_partitioned_variable is not allowed when "
"a custom getter is set. Current custom getter: %s. "
"It is likely that you're using create_partitioned_variables. "
"If so, consider instead using get_variable with a non-empty "
"partitioner parameter instead." % self._custom_getter)
if partitioner is None:
raise ValueError("No partitioner was specified")
# This allows the variable scope name to be used as the variable name if
# this function is invoked with an empty name arg, for backward
# compatibility with create_partitioned_variables().
full_name_list = []
if self.name:
full_name_list.append(self.name)
if name:
full_name_list.append(name)
full_name = "/".join(full_name_list)
# Variable names only depend on variable_scope (full_name here),
# not name_scope, so we reset it below for the time of variable creation.
with ops.name_scope(None):
# pylint: disable=protected-access
return var_store._get_partitioned_variable(
full_name, shape=shape, dtype=dtype, initializer=initializer,
regularizer=regularizer, reuse=self.reuse, trainable=trainable,
collections=collections, caching_device=caching_device,
partitioner=partitioner, validate_shape=validate_shape) | [
"def",
"_get_partitioned_variable",
"(",
"self",
",",
"var_store",
",",
"name",
",",
"shape",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"initializer",
"=",
"None",
",",
"regularizer",
"=",
"None",
",",
"trainable",
"=",
"True",
",",
"collections",
"=",
"None",
",",
"caching_device",
"=",
"None",
",",
"partitioner",
"=",
"None",
",",
"validate_shape",
"=",
"True",
")",
":",
"if",
"initializer",
"is",
"None",
":",
"initializer",
"=",
"self",
".",
"_initializer",
"if",
"regularizer",
"is",
"None",
":",
"regularizer",
"=",
"self",
".",
"_regularizer",
"if",
"caching_device",
"is",
"None",
":",
"caching_device",
"=",
"self",
".",
"_caching_device",
"if",
"partitioner",
"is",
"None",
":",
"partitioner",
"=",
"self",
".",
"_partitioner",
"if",
"dtype",
"is",
"None",
":",
"dtype",
"=",
"self",
".",
"_dtype",
"if",
"self",
".",
"_custom_getter",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"Private access to _get_partitioned_variable is not allowed when \"",
"\"a custom getter is set. Current custom getter: %s. \"",
"\"It is likely that you're using create_partitioned_variables. \"",
"\"If so, consider instead using get_variable with a non-empty \"",
"\"partitioner parameter instead.\"",
"%",
"self",
".",
"_custom_getter",
")",
"if",
"partitioner",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"No partitioner was specified\"",
")",
"# This allows the variable scope name to be used as the variable name if",
"# this function is invoked with an empty name arg, for backward",
"# compatibility with create_partitioned_variables().",
"full_name_list",
"=",
"[",
"]",
"if",
"self",
".",
"name",
":",
"full_name_list",
".",
"append",
"(",
"self",
".",
"name",
")",
"if",
"name",
":",
"full_name_list",
".",
"append",
"(",
"name",
")",
"full_name",
"=",
"\"/\"",
".",
"join",
"(",
"full_name_list",
")",
"# Variable names only depend on variable_scope (full_name here),",
"# not name_scope, so we reset it below for the time of variable creation.",
"with",
"ops",
".",
"name_scope",
"(",
"None",
")",
":",
"# pylint: disable=protected-access",
"return",
"var_store",
".",
"_get_partitioned_variable",
"(",
"full_name",
",",
"shape",
"=",
"shape",
",",
"dtype",
"=",
"dtype",
",",
"initializer",
"=",
"initializer",
",",
"regularizer",
"=",
"regularizer",
",",
"reuse",
"=",
"self",
".",
"reuse",
",",
"trainable",
"=",
"trainable",
",",
"collections",
"=",
"collections",
",",
"caching_device",
"=",
"caching_device",
",",
"partitioner",
"=",
"partitioner",
",",
"validate_shape",
"=",
"validate_shape",
")"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/variable_scope.py#L702-L755 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/dataflow.py | python | DataFlowAnalysis.op_SLICE_1 | (self, info, inst) | TOS = TOS1[TOS:] | TOS = TOS1[TOS:] | [
"TOS",
"=",
"TOS1",
"[",
"TOS",
":",
"]"
] | def op_SLICE_1(self, info, inst):
"""
TOS = TOS1[TOS:]
"""
tos = info.pop()
tos1 = info.pop()
res = info.make_temp()
slicevar = info.make_temp()
indexvar = info.make_temp()
nonevar = info.make_temp()
info.append(inst, base=tos1, start=tos, res=res, slicevar=slicevar,
indexvar=indexvar, nonevar=nonevar)
info.push(res) | [
"def",
"op_SLICE_1",
"(",
"self",
",",
"info",
",",
"inst",
")",
":",
"tos",
"=",
"info",
".",
"pop",
"(",
")",
"tos1",
"=",
"info",
".",
"pop",
"(",
")",
"res",
"=",
"info",
".",
"make_temp",
"(",
")",
"slicevar",
"=",
"info",
".",
"make_temp",
"(",
")",
"indexvar",
"=",
"info",
".",
"make_temp",
"(",
")",
"nonevar",
"=",
"info",
".",
"make_temp",
"(",
")",
"info",
".",
"append",
"(",
"inst",
",",
"base",
"=",
"tos1",
",",
"start",
"=",
"tos",
",",
"res",
"=",
"res",
",",
"slicevar",
"=",
"slicevar",
",",
"indexvar",
"=",
"indexvar",
",",
"nonevar",
"=",
"nonevar",
")",
"info",
".",
"push",
"(",
"res",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/dataflow.py#L469-L481 | ||
root-project/root | fcd3583bb14852bf2e8cd2415717cbaac0e75896 | interpreter/llvm/src/utils/benchmark/mingw.py | python | main | () | Invoked when the script is run directly by the python interpreter | Invoked when the script is run directly by the python interpreter | [
"Invoked",
"when",
"the",
"script",
"is",
"run",
"directly",
"by",
"the",
"python",
"interpreter"
] | def main():
'''
Invoked when the script is run directly by the python interpreter
'''
parser = argparse.ArgumentParser(
description = 'Downloads a specific version of MinGW',
formatter_class = argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument('--location',
help = 'the location to download the compiler to',
default = os.path.join(tempfile.gettempdir(), 'mingw-builds'))
parser.add_argument('--arch', required = True, choices = ['i686', 'x86_64'],
help = 'the target MinGW architecture string')
parser.add_argument('--version', type = str2ver,
help = 'the version of GCC to download')
parser.add_argument('--threading', choices = ['posix', 'win32'],
help = 'the threading type of the compiler')
parser.add_argument('--exceptions', choices = ['sjlj', 'seh', 'dwarf'],
help = 'the method to throw exceptions')
parser.add_argument('--revision', type=int,
help = 'the revision of the MinGW release')
group = parser.add_mutually_exclusive_group()
group.add_argument('-v', '--verbose', action='store_true',
help='increase the script output verbosity')
group.add_argument('-q', '--quiet', action='store_true',
help='only print errors and warning')
args = parser.parse_args()
# Create the logger
logger = logging.getLogger('mingw')
handler = logging.StreamHandler()
formatter = logging.Formatter('%(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
if args.quiet:
logger.setLevel(logging.WARN)
if args.verbose:
logger.setLevel(logging.DEBUG)
# Get MinGW
root_dir = root(location = args.location, arch = args.arch,
version = args.version, threading = args.threading,
exceptions = args.exceptions, revision = args.revision,
log = logger)
sys.stdout.write('%s\n' % os.path.join(root_dir, 'bin')) | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Downloads a specific version of MinGW'",
",",
"formatter_class",
"=",
"argparse",
".",
"ArgumentDefaultsHelpFormatter",
")",
"parser",
".",
"add_argument",
"(",
"'--location'",
",",
"help",
"=",
"'the location to download the compiler to'",
",",
"default",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tempfile",
".",
"gettempdir",
"(",
")",
",",
"'mingw-builds'",
")",
")",
"parser",
".",
"add_argument",
"(",
"'--arch'",
",",
"required",
"=",
"True",
",",
"choices",
"=",
"[",
"'i686'",
",",
"'x86_64'",
"]",
",",
"help",
"=",
"'the target MinGW architecture string'",
")",
"parser",
".",
"add_argument",
"(",
"'--version'",
",",
"type",
"=",
"str2ver",
",",
"help",
"=",
"'the version of GCC to download'",
")",
"parser",
".",
"add_argument",
"(",
"'--threading'",
",",
"choices",
"=",
"[",
"'posix'",
",",
"'win32'",
"]",
",",
"help",
"=",
"'the threading type of the compiler'",
")",
"parser",
".",
"add_argument",
"(",
"'--exceptions'",
",",
"choices",
"=",
"[",
"'sjlj'",
",",
"'seh'",
",",
"'dwarf'",
"]",
",",
"help",
"=",
"'the method to throw exceptions'",
")",
"parser",
".",
"add_argument",
"(",
"'--revision'",
",",
"type",
"=",
"int",
",",
"help",
"=",
"'the revision of the MinGW release'",
")",
"group",
"=",
"parser",
".",
"add_mutually_exclusive_group",
"(",
")",
"group",
".",
"add_argument",
"(",
"'-v'",
",",
"'--verbose'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'increase the script output verbosity'",
")",
"group",
".",
"add_argument",
"(",
"'-q'",
",",
"'--quiet'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'only print errors and warning'",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"# Create the logger",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'mingw'",
")",
"handler",
"=",
"logging",
".",
"StreamHandler",
"(",
")",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"'%(message)s'",
")",
"handler",
".",
"setFormatter",
"(",
"formatter",
")",
"logger",
".",
"addHandler",
"(",
"handler",
")",
"logger",
".",
"setLevel",
"(",
"logging",
".",
"INFO",
")",
"if",
"args",
".",
"quiet",
":",
"logger",
".",
"setLevel",
"(",
"logging",
".",
"WARN",
")",
"if",
"args",
".",
"verbose",
":",
"logger",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"# Get MinGW",
"root_dir",
"=",
"root",
"(",
"location",
"=",
"args",
".",
"location",
",",
"arch",
"=",
"args",
".",
"arch",
",",
"version",
"=",
"args",
".",
"version",
",",
"threading",
"=",
"args",
".",
"threading",
",",
"exceptions",
"=",
"args",
".",
"exceptions",
",",
"revision",
"=",
"args",
".",
"revision",
",",
"log",
"=",
"logger",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"'%s\\n'",
"%",
"os",
".",
"path",
".",
"join",
"(",
"root_dir",
",",
"'bin'",
")",
")"
] | https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/interpreter/llvm/src/utils/benchmark/mingw.py#L261-L307 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/saved_model/load.py | python | Loader._retrieve_all_filtered_nodes | (self) | return all_filtered_nodes | Traverses through the object graph to get the IDs of all nodes to load.
As a side-effect, if node_filters is a dictionary that contains already-
created objects, then the children tracked by those objects will be
added to node_filters.
Returns:
List of all nodes to load, or None if all nodes should be loaded. | Traverses through the object graph to get the IDs of all nodes to load. | [
"Traverses",
"through",
"the",
"object",
"graph",
"to",
"get",
"the",
"IDs",
"of",
"all",
"nodes",
"to",
"load",
"."
] | def _retrieve_all_filtered_nodes(self):
"""Traverses through the object graph to get the IDs of all nodes to load.
As a side-effect, if node_filters is a dictionary that contains already-
created objects, then the children tracked by those objects will be
added to node_filters.
Returns:
List of all nodes to load, or None if all nodes should be loaded.
"""
if self._node_filters is None:
return None # All nodes should be loaded.
all_filtered_nodes = set()
nodes_to_visit = list(self._node_filters)
while nodes_to_visit:
node_path = nodes_to_visit.pop(0)
node_id = self._node_path_to_id[node_path]
if node_id in all_filtered_nodes:
continue
all_filtered_nodes.add(node_id)
node, setter = self._loaded_nodes.get(node_id, (None, None))
if node is not None:
if not isinstance(node, base.Trackable):
raise TypeError(
"Error when processing dictionary values passed to nodes_to_load."
f"Object at {node_path} is expected to be a checkpointable (i.e. "
"'trackable') TensorFlow object (e.g. tf.Variable, tf.Module or "
"Keras layer).")
node._maybe_initialize_trackable() # pylint: disable=protected-access
for reference in self._proto.nodes[node_id].children:
child_object, _ = self._loaded_nodes.get(
reference.node_id, (None, None))
# See if node already tracks the child reference, in which case add the
# child to the loaded_nodes dict.
if child_object is None and node is not None:
child_object = node._lookup_dependency(reference.local_name) # pylint: disable=protected-access
if isinstance(child_object, data_structures.TrackableDataStructure):
# Make setattr a noop to avoid overwriting already existing data
# structures.
setter = lambda *args: None
self._loaded_nodes[reference.node_id] = (child_object, setter)
child_path = "{}.{}".format(node_path, reference.local_name)
self._node_path_to_id[child_path] = reference.node_id
nodes_to_visit.append(child_path)
if 0 in all_filtered_nodes:
return None
return all_filtered_nodes | [
"def",
"_retrieve_all_filtered_nodes",
"(",
"self",
")",
":",
"if",
"self",
".",
"_node_filters",
"is",
"None",
":",
"return",
"None",
"# All nodes should be loaded.",
"all_filtered_nodes",
"=",
"set",
"(",
")",
"nodes_to_visit",
"=",
"list",
"(",
"self",
".",
"_node_filters",
")",
"while",
"nodes_to_visit",
":",
"node_path",
"=",
"nodes_to_visit",
".",
"pop",
"(",
"0",
")",
"node_id",
"=",
"self",
".",
"_node_path_to_id",
"[",
"node_path",
"]",
"if",
"node_id",
"in",
"all_filtered_nodes",
":",
"continue",
"all_filtered_nodes",
".",
"add",
"(",
"node_id",
")",
"node",
",",
"setter",
"=",
"self",
".",
"_loaded_nodes",
".",
"get",
"(",
"node_id",
",",
"(",
"None",
",",
"None",
")",
")",
"if",
"node",
"is",
"not",
"None",
":",
"if",
"not",
"isinstance",
"(",
"node",
",",
"base",
".",
"Trackable",
")",
":",
"raise",
"TypeError",
"(",
"\"Error when processing dictionary values passed to nodes_to_load.\"",
"f\"Object at {node_path} is expected to be a checkpointable (i.e. \"",
"\"'trackable') TensorFlow object (e.g. tf.Variable, tf.Module or \"",
"\"Keras layer).\"",
")",
"node",
".",
"_maybe_initialize_trackable",
"(",
")",
"# pylint: disable=protected-access",
"for",
"reference",
"in",
"self",
".",
"_proto",
".",
"nodes",
"[",
"node_id",
"]",
".",
"children",
":",
"child_object",
",",
"_",
"=",
"self",
".",
"_loaded_nodes",
".",
"get",
"(",
"reference",
".",
"node_id",
",",
"(",
"None",
",",
"None",
")",
")",
"# See if node already tracks the child reference, in which case add the",
"# child to the loaded_nodes dict.",
"if",
"child_object",
"is",
"None",
"and",
"node",
"is",
"not",
"None",
":",
"child_object",
"=",
"node",
".",
"_lookup_dependency",
"(",
"reference",
".",
"local_name",
")",
"# pylint: disable=protected-access",
"if",
"isinstance",
"(",
"child_object",
",",
"data_structures",
".",
"TrackableDataStructure",
")",
":",
"# Make setattr a noop to avoid overwriting already existing data",
"# structures.",
"setter",
"=",
"lambda",
"*",
"args",
":",
"None",
"self",
".",
"_loaded_nodes",
"[",
"reference",
".",
"node_id",
"]",
"=",
"(",
"child_object",
",",
"setter",
")",
"child_path",
"=",
"\"{}.{}\"",
".",
"format",
"(",
"node_path",
",",
"reference",
".",
"local_name",
")",
"self",
".",
"_node_path_to_id",
"[",
"child_path",
"]",
"=",
"reference",
".",
"node_id",
"nodes_to_visit",
".",
"append",
"(",
"child_path",
")",
"if",
"0",
"in",
"all_filtered_nodes",
":",
"return",
"None",
"return",
"all_filtered_nodes"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/saved_model/load.py#L216-L271 | |
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | python/mxnet/context.py | python | gpu_memory_info | (device_id=0) | return (free.value, total.value) | Query CUDA for the free and total bytes of GPU global memory.
Parameters
----------
device_id : int, optional
The device id of the GPU device.
Raises
------
Will raise an exception on any CUDA error.
Returns
-------
(free, total) : (int, int)
The number of GPUs. | Query CUDA for the free and total bytes of GPU global memory. | [
"Query",
"CUDA",
"for",
"the",
"free",
"and",
"total",
"bytes",
"of",
"GPU",
"global",
"memory",
"."
] | def gpu_memory_info(device_id=0):
"""Query CUDA for the free and total bytes of GPU global memory.
Parameters
----------
device_id : int, optional
The device id of the GPU device.
Raises
------
Will raise an exception on any CUDA error.
Returns
-------
(free, total) : (int, int)
The number of GPUs.
"""
free = ctypes.c_uint64()
total = ctypes.c_uint64()
dev_id = ctypes.c_int(device_id)
check_call(_LIB.MXGetGPUMemoryInformation64(dev_id, ctypes.byref(free), ctypes.byref(total)))
return (free.value, total.value) | [
"def",
"gpu_memory_info",
"(",
"device_id",
"=",
"0",
")",
":",
"free",
"=",
"ctypes",
".",
"c_uint64",
"(",
")",
"total",
"=",
"ctypes",
".",
"c_uint64",
"(",
")",
"dev_id",
"=",
"ctypes",
".",
"c_int",
"(",
"device_id",
")",
"check_call",
"(",
"_LIB",
".",
"MXGetGPUMemoryInformation64",
"(",
"dev_id",
",",
"ctypes",
".",
"byref",
"(",
"free",
")",
",",
"ctypes",
".",
"byref",
"(",
"total",
")",
")",
")",
"return",
"(",
"free",
".",
"value",
",",
"total",
".",
"value",
")"
] | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/context.py#L279-L301 | |
gemrb/gemrb | 730206eed8d1dd358ca5e69a62f9e099aa22ffc6 | gemrb/GUIScripts/Actor.py | python | Actor.ClassNames | (self) | return self.__classnames | Returns a list will all the class names. | Returns a list will all the class names. | [
"Returns",
"a",
"list",
"will",
"all",
"the",
"class",
"names",
"."
] | def ClassNames (self):
"""Returns a list will all the class names."""
if self.__classnames == None:
self.__classnames = GUICommon.GetClassRowName (self.classid, "class").split("_")
if self.IsDualSwap():
self.__classnames.reverse()
return self.__classnames | [
"def",
"ClassNames",
"(",
"self",
")",
":",
"if",
"self",
".",
"__classnames",
"==",
"None",
":",
"self",
".",
"__classnames",
"=",
"GUICommon",
".",
"GetClassRowName",
"(",
"self",
".",
"classid",
",",
"\"class\"",
")",
".",
"split",
"(",
"\"_\"",
")",
"if",
"self",
".",
"IsDualSwap",
"(",
")",
":",
"self",
".",
"__classnames",
".",
"reverse",
"(",
")",
"return",
"self",
".",
"__classnames"
] | https://github.com/gemrb/gemrb/blob/730206eed8d1dd358ca5e69a62f9e099aa22ffc6/gemrb/GUIScripts/Actor.py#L74-L81 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/Finder/Standard_Suite.py | python | Standard_Suite_Events.quit | (self, _no_object=None, _attributes={}, **_arguments) | quit: Quit the Finder
Keyword argument _attributes: AppleEvent attribute dictionary | quit: Quit the Finder
Keyword argument _attributes: AppleEvent attribute dictionary | [
"quit",
":",
"Quit",
"the",
"Finder",
"Keyword",
"argument",
"_attributes",
":",
"AppleEvent",
"attribute",
"dictionary"
] | def quit(self, _no_object=None, _attributes={}, **_arguments):
"""quit: Quit the Finder
Keyword argument _attributes: AppleEvent attribute dictionary
"""
_code = 'aevt'
_subcode = 'quit'
if _arguments: raise TypeError, 'No optional args expected'
if _no_object is not None: raise TypeError, 'No direct arg expected'
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.get('errn', 0):
raise aetools.Error, aetools.decodeerror(_arguments)
# XXXX Optionally decode result
if _arguments.has_key('----'):
return _arguments['----'] | [
"def",
"quit",
"(",
"self",
",",
"_no_object",
"=",
"None",
",",
"_attributes",
"=",
"{",
"}",
",",
"*",
"*",
"_arguments",
")",
":",
"_code",
"=",
"'aevt'",
"_subcode",
"=",
"'quit'",
"if",
"_arguments",
":",
"raise",
"TypeError",
",",
"'No optional args expected'",
"if",
"_no_object",
"is",
"not",
"None",
":",
"raise",
"TypeError",
",",
"'No direct arg expected'",
"_reply",
",",
"_arguments",
",",
"_attributes",
"=",
"self",
".",
"send",
"(",
"_code",
",",
"_subcode",
",",
"_arguments",
",",
"_attributes",
")",
"if",
"_arguments",
".",
"get",
"(",
"'errn'",
",",
"0",
")",
":",
"raise",
"aetools",
".",
"Error",
",",
"aetools",
".",
"decodeerror",
"(",
"_arguments",
")",
"# XXXX Optionally decode result",
"if",
"_arguments",
".",
"has_key",
"(",
"'----'",
")",
":",
"return",
"_arguments",
"[",
"'----'",
"]"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/Finder/Standard_Suite.py#L280-L297 | ||
albertz/openlierox | d316c14a8eb57848ef56e9bfa7b23a56f694a51b | tools/DedicatedServerVideo/gdata/spreadsheet/text_db.py | python | Table.SetFields | (self, fields) | Changes the contents of the cells in the first row of this worksheet.
Args:
fields: list of strings The names in the list comprise the
first row of the worksheet. These names are converted into XML
tags by the server. To avoid changes during the translation
process I recommend using all lowercase alphabetic names. For
example ['somelongname', 'theothername'] | Changes the contents of the cells in the first row of this worksheet. | [
"Changes",
"the",
"contents",
"of",
"the",
"cells",
"in",
"the",
"first",
"row",
"of",
"this",
"worksheet",
"."
] | def SetFields(self, fields):
"""Changes the contents of the cells in the first row of this worksheet.
Args:
fields: list of strings The names in the list comprise the
first row of the worksheet. These names are converted into XML
tags by the server. To avoid changes during the translation
process I recommend using all lowercase alphabetic names. For
example ['somelongname', 'theothername']
"""
# TODO: If the table already had fields, we might want to clear out the,
# current column headers.
self.fields = fields
i = 0
for column_name in fields:
i = i + 1
# TODO: speed this up by using a batch request to update cells.
self.client._GetSpreadsheetsClient().UpdateCell(1, i, column_name,
self.spreadsheet_key, self.worksheet_id) | [
"def",
"SetFields",
"(",
"self",
",",
"fields",
")",
":",
"# TODO: If the table already had fields, we might want to clear out the,",
"# current column headers.",
"self",
".",
"fields",
"=",
"fields",
"i",
"=",
"0",
"for",
"column_name",
"in",
"fields",
":",
"i",
"=",
"i",
"+",
"1",
"# TODO: speed this up by using a batch request to update cells.",
"self",
".",
"client",
".",
"_GetSpreadsheetsClient",
"(",
")",
".",
"UpdateCell",
"(",
"1",
",",
"i",
",",
"column_name",
",",
"self",
".",
"spreadsheet_key",
",",
"self",
".",
"worksheet_id",
")"
] | https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/spreadsheet/text_db.py#L311-L329 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.