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/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/arrayobj.py | python | array_record_getattr | (context, builder, typ, value, attr) | return impl_ret_borrowed(context, builder, resty, res) | Generic getattr() implementation for record arrays: fetch the given
record member, i.e. a subarray. | Generic getattr() implementation for record arrays: fetch the given
record member, i.e. a subarray. | [
"Generic",
"getattr",
"()",
"implementation",
"for",
"record",
"arrays",
":",
"fetch",
"the",
"given",
"record",
"member",
"i",
".",
"e",
".",
"a",
"subarray",
"."
] | def array_record_getattr(context, builder, typ, value, attr):
"""
Generic getattr() implementation for record arrays: fetch the given
record member, i.e. a subarray.
"""
arrayty = make_array(typ)
array = arrayty(context, builder, value)
rectype = typ.dtype
if not isinstance(rectype, types.Record):
raise NotImplementedError("attribute %r of %s not defined"
% (attr, typ))
dtype = rectype.typeof(attr)
offset = rectype.offset(attr)
resty = typ.copy(dtype=dtype, layout='A')
raryty = make_array(resty)
rary = raryty(context, builder)
constoffset = context.get_constant(types.intp, offset)
newdataptr = cgutils.pointer_add(
builder, array.data, constoffset, return_type=rary.data.type,
)
datasize = context.get_abi_sizeof(context.get_data_type(dtype))
populate_array(rary,
data=newdataptr,
shape=array.shape,
strides=array.strides,
itemsize=context.get_constant(types.intp, datasize),
meminfo=array.meminfo,
parent=array.parent)
res = rary._getvalue()
return impl_ret_borrowed(context, builder, resty, res) | [
"def",
"array_record_getattr",
"(",
"context",
",",
"builder",
",",
"typ",
",",
"value",
",",
"attr",
")",
":",
"arrayty",
"=",
"make_array",
"(",
"typ",
")",
"array",
"=",
"arrayty",
"(",
"context",
",",
"builder",
",",
"value",
")",
"rectype",
"=",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/arrayobj.py#L2298-L2333 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py | python | FlagValues.__setitem__ | (self, name, flag) | Registers a new flag variable. | Registers a new flag variable. | [
"Registers",
"a",
"new",
"flag",
"variable",
"."
] | def __setitem__(self, name, flag):
"""Registers a new flag variable."""
fl = self.FlagDict()
if not isinstance(flag, Flag):
raise IllegalFlagValue(flag)
if not isinstance(name, type("")):
raise FlagsError("Flag name must be a string")
if len(name) == 0:
raise FlagsError("Flag name cannot be empty")
# If running under pychecker, duplicate keys are likely to be
# defined. Disable check for duplicate keys when pycheck'ing.
if (name in fl and not flag.allow_override and
not fl[name].allow_override and not _RUNNING_PYCHECKER):
module, module_name = _GetCallingModuleObjectAndName()
if (self.FindModuleDefiningFlag(name) == module_name and
id(module) != self.FindModuleIdDefiningFlag(name)):
# If the flag has already been defined by a module with the same name,
# but a different ID, we can stop here because it indicates that the
# module is simply being imported a subsequent time.
return
raise DuplicateFlagError(name, self)
short_name = flag.short_name
if short_name is not None:
if (short_name in fl and not flag.allow_override and
not fl[short_name].allow_override and not _RUNNING_PYCHECKER):
raise DuplicateFlagError(short_name, self)
fl[short_name] = flag
fl[name] = flag
global _exported_flags
_exported_flags[name] = flag | [
"def",
"__setitem__",
"(",
"self",
",",
"name",
",",
"flag",
")",
":",
"fl",
"=",
"self",
".",
"FlagDict",
"(",
")",
"if",
"not",
"isinstance",
"(",
"flag",
",",
"Flag",
")",
":",
"raise",
"IllegalFlagValue",
"(",
"flag",
")",
"if",
"not",
"isinstanc... | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py#L1020-L1049 | ||
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBData.GetString | (self, error, offset) | return _lldb.SBData_GetString(self, error, offset) | GetString(SBData self, SBError error, lldb::offset_t offset) -> char const * | GetString(SBData self, SBError error, lldb::offset_t offset) -> char const * | [
"GetString",
"(",
"SBData",
"self",
"SBError",
"error",
"lldb",
"::",
"offset_t",
"offset",
")",
"-",
">",
"char",
"const",
"*"
] | def GetString(self, error, offset):
"""GetString(SBData self, SBError error, lldb::offset_t offset) -> char const *"""
return _lldb.SBData_GetString(self, error, offset) | [
"def",
"GetString",
"(",
"self",
",",
"error",
",",
"offset",
")",
":",
"return",
"_lldb",
".",
"SBData_GetString",
"(",
"self",
",",
"error",
",",
"offset",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L3402-L3404 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/tools/gyp/pylib/gyp/generator/msvs.py | python | _GetOutputFilePathAndTool | (spec, msbuild) | return out_file, vc_tool, msbuild_tool | Returns the path and tool to use for this target.
Figures out the path of the file this spec will create and the name of
the VC tool that will create it.
Arguments:
spec: The target dictionary containing the properties of the target.
Returns:
A triple of (file path, name of the vc tool, name of the msbuild tool) | Returns the path and tool to use for this target. | [
"Returns",
"the",
"path",
"and",
"tool",
"to",
"use",
"for",
"this",
"target",
"."
] | def _GetOutputFilePathAndTool(spec, msbuild):
"""Returns the path and tool to use for this target.
Figures out the path of the file this spec will create and the name of
the VC tool that will create it.
Arguments:
spec: The target dictionary containing the properties of the target.
Returns:
A triple of (file path, name of the vc tool, name of the msbuild tool)
"""
# Select a name for the output file.
out_file = ''
vc_tool = ''
msbuild_tool = ''
output_file_map = {
'executable': ('VCLinkerTool', 'Link', '$(OutDir)', '.exe'),
'shared_library': ('VCLinkerTool', 'Link', '$(OutDir)', '.dll'),
'loadable_module': ('VCLinkerTool', 'Link', '$(OutDir)', '.dll'),
'windows_driver': ('VCLinkerTool', 'Link', '$(OutDir)', '.sys'),
'static_library': ('VCLibrarianTool', 'Lib', '$(OutDir)lib\\', '.lib'),
}
output_file_props = output_file_map.get(spec['type'])
if output_file_props and int(spec.get('msvs_auto_output_file', 1)):
vc_tool, msbuild_tool, out_dir, suffix = output_file_props
if spec.get('standalone_static_library', 0):
out_dir = '$(OutDir)'
out_dir = spec.get('product_dir', out_dir)
product_extension = spec.get('product_extension')
if product_extension:
suffix = '.' + product_extension
elif msbuild:
suffix = '$(TargetExt)'
prefix = spec.get('product_prefix', '')
product_name = spec.get('product_name', '$(ProjectName)')
out_file = ntpath.join(out_dir, prefix + product_name + suffix)
return out_file, vc_tool, msbuild_tool | [
"def",
"_GetOutputFilePathAndTool",
"(",
"spec",
",",
"msbuild",
")",
":",
"# Select a name for the output file.",
"out_file",
"=",
"''",
"vc_tool",
"=",
"''",
"msbuild_tool",
"=",
"''",
"output_file_map",
"=",
"{",
"'executable'",
":",
"(",
"'VCLinkerTool'",
",",
... | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/gyp/pylib/gyp/generator/msvs.py#L1301-L1337 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/scipy/linalg.py | python | lu_solve_core | (in_lu, permutation, b, trans) | return mnp.reshape(output, b.shape) | core implementation of lu solve | core implementation of lu solve | [
"core",
"implementation",
"of",
"lu",
"solve"
] | def lu_solve_core(in_lu, permutation, b, trans):
""" core implementation of lu solve"""
m = in_lu.shape[0]
res_shape = b.shape[1:]
prod_result = 1
for sh in res_shape:
prod_result *= sh
x = mnp.reshape(b, (m, prod_result))
trans_str = None
if trans == 0:
trans_str = "N"
x = x[permutation, :]
elif trans == 1:
trans_str = "T"
elif trans == 2:
trans_str = "C"
else:
_raise_value_error("trans error, it's value must be 0, 1, 2")
ms_lu_solve = LUSolver(trans_str)
output = ms_lu_solve(in_lu, x)
return mnp.reshape(output, b.shape) | [
"def",
"lu_solve_core",
"(",
"in_lu",
",",
"permutation",
",",
"b",
",",
"trans",
")",
":",
"m",
"=",
"in_lu",
".",
"shape",
"[",
"0",
"]",
"res_shape",
"=",
"b",
".",
"shape",
"[",
"1",
":",
"]",
"prod_result",
"=",
"1",
"for",
"sh",
"in",
"res_... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/scipy/linalg.py#L423-L443 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/ops/metrics_impl.py | python | recall_at_thresholds | (labels, predictions, thresholds,
weights=None, metrics_collections=None,
updates_collections=None, name=None) | Computes various recall values for different `thresholds` on `predictions`.
The `recall_at_thresholds` function creates four local variables,
`true_positives`, `true_negatives`, `false_positives` and `false_negatives`
for various values of thresholds. `recall[i]` is defined as the total weight
of values in `predictions` above `thresholds[i]` whose corresponding entry in
`labels` is `True`, divided by the total weight of `True` values in `labels`
(`true_positives[i] / (true_positives[i] + false_negatives[i])`).
For estimation of the metric over a stream of data, the function creates an
`update_op` operation that updates these variables and returns the `recall`.
If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.
Args:
labels: The ground truth values, a `Tensor` whose dimensions must match
`predictions`. Will be cast to `bool`.
predictions: A floating point `Tensor` of arbitrary shape and whose values
are in the range `[0, 1]`.
thresholds: A python list or tuple of float thresholds in `[0, 1]`.
weights: Optional `Tensor` whose rank is either 0, or the same rank as
`labels`, and must be broadcastable to `labels` (i.e., all dimensions must
be either `1`, or the same as the corresponding `labels` dimension).
metrics_collections: An optional list of collections that `recall` should be
added to.
updates_collections: An optional list of collections that `update_op` should
be added to.
name: An optional variable_scope name.
Returns:
recall: A float `Tensor` of shape `[len(thresholds)]`.
update_op: An operation that increments the `true_positives`,
`true_negatives`, `false_positives` and `false_negatives` variables that
are used in the computation of `recall`.
Raises:
ValueError: If `predictions` and `labels` have mismatched shapes, or if
`weights` is not `None` and its shape doesn't match `predictions`, or if
either `metrics_collections` or `updates_collections` are not a list or
tuple. | Computes various recall values for different `thresholds` on `predictions`. | [
"Computes",
"various",
"recall",
"values",
"for",
"different",
"thresholds",
"on",
"predictions",
"."
] | def recall_at_thresholds(labels, predictions, thresholds,
weights=None, metrics_collections=None,
updates_collections=None, name=None):
"""Computes various recall values for different `thresholds` on `predictions`.
The `recall_at_thresholds` function creates four local variables,
`true_positives`, `true_negatives`, `false_positives` and `false_negatives`
for various values of thresholds. `recall[i]` is defined as the total weight
of values in `predictions` above `thresholds[i]` whose corresponding entry in
`labels` is `True`, divided by the total weight of `True` values in `labels`
(`true_positives[i] / (true_positives[i] + false_negatives[i])`).
For estimation of the metric over a stream of data, the function creates an
`update_op` operation that updates these variables and returns the `recall`.
If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.
Args:
labels: The ground truth values, a `Tensor` whose dimensions must match
`predictions`. Will be cast to `bool`.
predictions: A floating point `Tensor` of arbitrary shape and whose values
are in the range `[0, 1]`.
thresholds: A python list or tuple of float thresholds in `[0, 1]`.
weights: Optional `Tensor` whose rank is either 0, or the same rank as
`labels`, and must be broadcastable to `labels` (i.e., all dimensions must
be either `1`, or the same as the corresponding `labels` dimension).
metrics_collections: An optional list of collections that `recall` should be
added to.
updates_collections: An optional list of collections that `update_op` should
be added to.
name: An optional variable_scope name.
Returns:
recall: A float `Tensor` of shape `[len(thresholds)]`.
update_op: An operation that increments the `true_positives`,
`true_negatives`, `false_positives` and `false_negatives` variables that
are used in the computation of `recall`.
Raises:
ValueError: If `predictions` and `labels` have mismatched shapes, or if
`weights` is not `None` and its shape doesn't match `predictions`, or if
either `metrics_collections` or `updates_collections` are not a list or
tuple.
"""
with variable_scope.variable_scope(name, 'recall_at_thresholds',
(predictions, labels, weights)):
values, update_ops = _confusion_matrix_at_thresholds(
labels, predictions, thresholds, weights, includes=('tp', 'fn'))
# Avoid division by zero.
epsilon = 1e-7
def compute_recall(tp, fn, name):
return math_ops.div(tp, epsilon + tp + fn, name='recall_' + name)
rec = compute_recall(values['tp'], values['fn'], 'value')
update_op = compute_recall(update_ops['tp'], update_ops['fn'], 'update_op')
if metrics_collections:
ops.add_to_collections(metrics_collections, rec)
if updates_collections:
ops.add_to_collections(updates_collections, update_op)
return rec, update_op | [
"def",
"recall_at_thresholds",
"(",
"labels",
",",
"predictions",
",",
"thresholds",
",",
"weights",
"=",
"None",
",",
"metrics_collections",
"=",
"None",
",",
"updates_collections",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"with",
"variable_scope",
".... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/metrics_impl.py#L2013-L2076 | ||
shader-slang/slang | b8982fcf43b86c1e39dcc3dd19bff2821633eda6 | external/vulkan/registry/vkconventions.py | python | VulkanConventions.is_api_name | (self, name) | return name[0:2].lower() == 'vk' or name[0:6] == 'PFN_vk' | Returns True if name is in the reserved API namespace.
For Vulkan, these are names with a case-insensitive 'vk' prefix, or
a 'PFN_vk' function pointer type prefix. | Returns True if name is in the reserved API namespace.
For Vulkan, these are names with a case-insensitive 'vk' prefix, or
a 'PFN_vk' function pointer type prefix. | [
"Returns",
"True",
"if",
"name",
"is",
"in",
"the",
"reserved",
"API",
"namespace",
".",
"For",
"Vulkan",
"these",
"are",
"names",
"with",
"a",
"case",
"-",
"insensitive",
"vk",
"prefix",
"or",
"a",
"PFN_vk",
"function",
"pointer",
"type",
"prefix",
"."
] | def is_api_name(self, name):
"""Returns True if name is in the reserved API namespace.
For Vulkan, these are names with a case-insensitive 'vk' prefix, or
a 'PFN_vk' function pointer type prefix.
"""
return name[0:2].lower() == 'vk' or name[0:6] == 'PFN_vk' | [
"def",
"is_api_name",
"(",
"self",
",",
"name",
")",
":",
"return",
"name",
"[",
"0",
":",
"2",
"]",
".",
"lower",
"(",
")",
"==",
"'vk'",
"or",
"name",
"[",
"0",
":",
"6",
"]",
"==",
"'PFN_vk'"
] | https://github.com/shader-slang/slang/blob/b8982fcf43b86c1e39dcc3dd19bff2821633eda6/external/vulkan/registry/vkconventions.py#L149-L154 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py3/IPython/extensions/cythonmagic.py | python | load_ipython_extension | (ip) | Load the extension in IPython. | Load the extension in IPython. | [
"Load",
"the",
"extension",
"in",
"IPython",
"."
] | def load_ipython_extension(ip):
"""Load the extension in IPython."""
warnings.warn("""The Cython magic has been moved to the Cython package""") | [
"def",
"load_ipython_extension",
"(",
"ip",
")",
":",
"warnings",
".",
"warn",
"(",
"\"\"\"The Cython magic has been moved to the Cython package\"\"\"",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/extensions/cythonmagic.py#L18-L21 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Tools/offlinedoc/buildpdf.py | python | createpdf_pisa | (pagename) | creates a pdf file from a saved page using pisa (python module) | creates a pdf file from a saved page using pisa (python module) | [
"creates",
"a",
"pdf",
"file",
"from",
"a",
"saved",
"page",
"using",
"pisa",
"(",
"python",
"module",
")"
] | def createpdf_pisa(pagename):
"creates a pdf file from a saved page using pisa (python module)"
import ho.pisa as pisa
if (not exists(pagename+".pdf",image=True)) or OVERWRITE:
infile = open(FOLDER + os.sep + pagename+'.html','ro')
outfile = open(FOLDER + os.sep + pagename+'.pdf','wb')
if VERBOSE: print("Converting " + pagename + " to pdf...")
pdf = pisa.CreatePDF(infile,outfile,FOLDER,link_callback=fetch_resources)
outfile.close()
if pdf.err:
return pdf.err
return 0 | [
"def",
"createpdf_pisa",
"(",
"pagename",
")",
":",
"import",
"ho",
".",
"pisa",
"as",
"pisa",
"if",
"(",
"not",
"exists",
"(",
"pagename",
"+",
"\".pdf\"",
",",
"image",
"=",
"True",
")",
")",
"or",
"OVERWRITE",
":",
"infile",
"=",
"open",
"(",
"FOL... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Tools/offlinedoc/buildpdf.py#L158-L169 | ||
PlatformLab/RAMCloud | b1866af19124325a6dfd8cbc267e2e3ef1f965d1 | scripts/cluster.py | python | Cluster.start_server | (self,
host,
args='',
master=True,
backup=True,
disk=None,
port=server_port,
kill_on_exit=True
) | return server | Start a server on a node.
@param host: (hostname, ip, id) tuple describing the node on which
to start the RAMCloud server.
@param args: Additional command-line args to pass to the server.
(default: '')
@param master: If True then the started server provides a master
service. (default: True)
@param backup: If True then the started server provides a backup
service. (default: True)
@param disk: If backup is True then the started server passes these
additional arguments to select the storage type and
location. (default: self.disk)
@param port: The port the server should listen on.
(default: see server_locator())
@param kill_on_exit:
If False, this server process is not reaped at the end
of the clusterperf test.
(default: True)
@return: Sandbox.Process representing the server process. | Start a server on a node. | [
"Start",
"a",
"server",
"on",
"a",
"node",
"."
] | def start_server(self,
host,
args='',
master=True,
backup=True,
disk=None,
port=server_port,
kill_on_exit=True
):
"""Start a server on a node.
@param host: (hostname, ip, id) tuple describing the node on which
to start the RAMCloud server.
@param args: Additional command-line args to pass to the server.
(default: '')
@param master: If True then the started server provides a master
service. (default: True)
@param backup: If True then the started server provides a backup
service. (default: True)
@param disk: If backup is True then the started server passes these
additional arguments to select the storage type and
location. (default: self.disk)
@param port: The port the server should listen on.
(default: see server_locator())
@param kill_on_exit:
If False, this server process is not reaped at the end
of the clusterperf test.
(default: True)
@return: Sandbox.Process representing the server process.
"""
log_prefix = '%s/server%d.%s' % (
self.log_subdir, self.next_server_id, host[0])
command = ('%s %s -C %s -L %s -r %d -l %s --clusterName __unnamed__ '
'--logFile %s.log --preferredIndex %d %s' %
(prefix_command,
server_binary, self.coordinator_locator,
server_locator(self.transport, host, port),
self.replicas,
self.log_level,
log_prefix,
self.next_server_id,
args))
self.next_server_id += 1
if master and backup:
pass
elif master:
command += ' --masterOnly'
elif backup:
command += ' --backupOnly'
else:
raise Exception('Cannot start a server that is neither a master '
'nor backup')
if backup:
if not disk:
disk = self.disk
command += ' %s' % disk
self.backups_started += 1
if master:
self.masters_started += 1
# Adding redirection for stdout and stderr.
stdout = open(log_prefix + '.out', 'w')
stderr = open(log_prefix + '.err', 'w')
server = self.sandbox.rsh(host[0], command, is_server=True,
locator=server_locator(self.transport, host, port),
kill_on_exit=kill_on_exit, bg=True, stdout=stdout,
stderr=stderr)
if self.verbose:
print('Server started on %s at %s: %s' %
(host[0],
server_locator(self.transport, host, port), command))
return server | [
"def",
"start_server",
"(",
"self",
",",
"host",
",",
"args",
"=",
"''",
",",
"master",
"=",
"True",
",",
"backup",
"=",
"True",
",",
"disk",
"=",
"None",
",",
"port",
"=",
"server_port",
",",
"kill_on_exit",
"=",
"True",
")",
":",
"log_prefix",
"=",... | https://github.com/PlatformLab/RAMCloud/blob/b1866af19124325a6dfd8cbc267e2e3ef1f965d1/scripts/cluster.py#L306-L381 | |
gnuradio/gnuradio | 09c3c4fa4bfb1a02caac74cb5334dfe065391e3b | gr-fec/python/fec/LDPC/Generate_LDPC_matrix_functions.py | python | LDPC_matrix.regular_LDPC_code_contructor | (self, n_p_q) | return H | This function constructs a LDPC parity check matrix
H. The algorithm follows Gallager's approach where we create
p submatrices and stack them together. Reference: Turbo
Coding for Satellite and Wireless Communications, section
9,3.
Note: the matrices computed from this algorithm will never
have full rank. (Reference Gallager's Dissertation.) They
will have rank = (number of rows - p + 1). To convert it
to full rank, use the function get_full_rank_H_matrix | This function constructs a LDPC parity check matrix
H. The algorithm follows Gallager's approach where we create
p submatrices and stack them together. Reference: Turbo
Coding for Satellite and Wireless Communications, section
9,3. | [
"This",
"function",
"constructs",
"a",
"LDPC",
"parity",
"check",
"matrix",
"H",
".",
"The",
"algorithm",
"follows",
"Gallager",
"s",
"approach",
"where",
"we",
"create",
"p",
"submatrices",
"and",
"stack",
"them",
"together",
".",
"Reference",
":",
"Turbo",
... | def regular_LDPC_code_contructor(self, n_p_q):
"""
This function constructs a LDPC parity check matrix
H. The algorithm follows Gallager's approach where we create
p submatrices and stack them together. Reference: Turbo
Coding for Satellite and Wireless Communications, section
9,3.
Note: the matrices computed from this algorithm will never
have full rank. (Reference Gallager's Dissertation.) They
will have rank = (number of rows - p + 1). To convert it
to full rank, use the function get_full_rank_H_matrix
"""
n = n_p_q[0] # codeword length
p = n_p_q[1] # column weight
q = n_p_q[2] # row weight
# TODO: There should probably be other guidelines for n/p/q,
# but I have not found any specifics in the literature....
# For this algorithm, n/p must be an integer, because the
# number of rows in each submatrix must be a whole number.
ratioTest = (n * 1.0) / q
if ratioTest % 1 != 0:
print('\nError in regular_LDPC_code_contructor: The ', end='')
print('ratio of inputs n/q must be a whole number.\n')
return
# First submatrix first:
m = (n * p) / q # number of rows in H matrix
submatrix1 = zeros((m / p, n))
for row in np.arange(m / p):
range1 = row * q
range2 = (row + 1) * q
submatrix1[row, range1:range2] = 1
H = submatrix1
# Create the other submatrices and vertically stack them on.
submatrixNum = 2
newColumnOrder = np.arange(n)
while submatrixNum <= p:
submatrix = zeros((m / p, n))
shuffle(newColumnOrder)
for columnNum in np.arange(n):
submatrix[:, columnNum] = \
submatrix1[:, newColumnOrder[columnNum]]
H = vstack((H, submatrix))
submatrixNum = submatrixNum + 1
# Double check the row weight and column weights.
size = H.shape
rows = size[0]
cols = size[1]
# Check the row weights.
for rowNum in np.arange(rows):
nonzeros = array(H[rowNum, :].nonzero())
if nonzeros.shape[1] != q:
print('Row', rowNum, 'has incorrect weight!')
return
# Check the column weights
for columnNum in np.arange(cols):
nonzeros = array(H[:, columnNum].nonzero())
if nonzeros.shape[1] != p:
print('Row', columnNum, 'has incorrect weight!')
return
return H | [
"def",
"regular_LDPC_code_contructor",
"(",
"self",
",",
"n_p_q",
")",
":",
"n",
"=",
"n_p_q",
"[",
"0",
"]",
"# codeword length",
"p",
"=",
"n_p_q",
"[",
"1",
"]",
"# column weight",
"q",
"=",
"n_p_q",
"[",
"2",
"]",
"# row weight",
"# TODO: There should pr... | https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gr-fec/python/fec/LDPC/Generate_LDPC_matrix_functions.py#L131-L201 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/backend.py | python | is_keras_tensor | (x) | return hasattr(x, '_keras_history') | Returns whether `x` is a Keras tensor.
A "Keras tensor" is a tensor that was returned by a Keras layer,
(`Layer` class) or by `Input`.
Arguments:
x: A candidate tensor.
Returns:
A boolean: Whether the argument is a Keras tensor.
Raises:
ValueError: In case `x` is not a symbolic tensor.
Examples:
```python
>>> import tensorflow as tf
>>> import numpy
>>> from keras import backend as K
>>> from keras.layers import Input, Dense
>>> np_var = numpy.array([1, 2])
>>> K.is_keras_tensor(np_var) # A numpy array is not a symbolic tensor.
ValueError
>>> k_var = tf.compat.v1.placeholder('float32', shape=(1,1))
>>> K.is_keras_tensor(k_var) # A variable indirectly created outside of
keras is not a Keras tensor.
False
>>> keras_var = K.variable(np_var)
>>> K.is_keras_tensor(keras_var) # A variable created with the keras
backend is not a Keras tensor.
False
>>> keras_placeholder = K.placeholder(shape=(2, 4, 5))
>>> K.is_keras_tensor(keras_placeholder) # A placeholder is not a Keras
tensor.
False
>>> keras_input = Input([10])
>>> K.is_keras_tensor(keras_input) # An Input is a Keras tensor.
True
>>> keras_layer_output = Dense(10)(keras_input)
>>> K.is_keras_tensor(keras_layer_output) # Any Keras layer output is a
Keras tensor.
True
``` | Returns whether `x` is a Keras tensor. | [
"Returns",
"whether",
"x",
"is",
"a",
"Keras",
"tensor",
"."
] | def is_keras_tensor(x):
"""Returns whether `x` is a Keras tensor.
A "Keras tensor" is a tensor that was returned by a Keras layer,
(`Layer` class) or by `Input`.
Arguments:
x: A candidate tensor.
Returns:
A boolean: Whether the argument is a Keras tensor.
Raises:
ValueError: In case `x` is not a symbolic tensor.
Examples:
```python
>>> import tensorflow as tf
>>> import numpy
>>> from keras import backend as K
>>> from keras.layers import Input, Dense
>>> np_var = numpy.array([1, 2])
>>> K.is_keras_tensor(np_var) # A numpy array is not a symbolic tensor.
ValueError
>>> k_var = tf.compat.v1.placeholder('float32', shape=(1,1))
>>> K.is_keras_tensor(k_var) # A variable indirectly created outside of
keras is not a Keras tensor.
False
>>> keras_var = K.variable(np_var)
>>> K.is_keras_tensor(keras_var) # A variable created with the keras
backend is not a Keras tensor.
False
>>> keras_placeholder = K.placeholder(shape=(2, 4, 5))
>>> K.is_keras_tensor(keras_placeholder) # A placeholder is not a Keras
tensor.
False
>>> keras_input = Input([10])
>>> K.is_keras_tensor(keras_input) # An Input is a Keras tensor.
True
>>> keras_layer_output = Dense(10)(keras_input)
>>> K.is_keras_tensor(keras_layer_output) # Any Keras layer output is a
Keras tensor.
True
```
"""
if not isinstance(x, (ops.Tensor,
variables_module.Variable,
sparse_tensor.SparseTensor)):
raise ValueError('Unexpectedly found an instance of type `' + str(type(x)) +
'`. Expected a symbolic tensor instance.')
return hasattr(x, '_keras_history') | [
"def",
"is_keras_tensor",
"(",
"x",
")",
":",
"if",
"not",
"isinstance",
"(",
"x",
",",
"(",
"ops",
".",
"Tensor",
",",
"variables_module",
".",
"Variable",
",",
"sparse_tensor",
".",
"SparseTensor",
")",
")",
":",
"raise",
"ValueError",
"(",
"'Unexpectedl... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/backend.py#L932-L982 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/io/sql.py | python | BaseEngine.insert_records | (
self,
table: SQLTable,
con,
frame,
name,
index=True,
schema=None,
chunksize=None,
method=None,
**engine_kwargs,
) | Inserts data into already-prepared table | Inserts data into already-prepared table | [
"Inserts",
"data",
"into",
"already",
"-",
"prepared",
"table"
] | def insert_records(
self,
table: SQLTable,
con,
frame,
name,
index=True,
schema=None,
chunksize=None,
method=None,
**engine_kwargs,
):
"""
Inserts data into already-prepared table
"""
raise AbstractMethodError(self) | [
"def",
"insert_records",
"(",
"self",
",",
"table",
":",
"SQLTable",
",",
"con",
",",
"frame",
",",
"name",
",",
"index",
"=",
"True",
",",
"schema",
"=",
"None",
",",
"chunksize",
"=",
"None",
",",
"method",
"=",
"None",
",",
"*",
"*",
"engine_kwarg... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/io/sql.py#L1301-L1316 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/internals/blocks.py | python | ExtensionBlock.take_nd | (self, indexer, axis=0, new_mgr_locs=None, fill_tuple=None) | return self.make_block_same_class(new_values, new_mgr_locs) | Take values according to indexer and return them as a block. | Take values according to indexer and return them as a block. | [
"Take",
"values",
"according",
"to",
"indexer",
"and",
"return",
"them",
"as",
"a",
"block",
"."
] | def take_nd(self, indexer, axis=0, new_mgr_locs=None, fill_tuple=None):
"""
Take values according to indexer and return them as a block.
"""
if fill_tuple is None:
fill_value = None
else:
fill_value = fill_tuple[0]
# axis doesn't matter; we are really a single-dim object
# but are passed the axis depending on the calling routing
# if its REALLY axis 0, then this will be a reindex and not a take
new_values = self.values.take(indexer, fill_value=fill_value, allow_fill=True)
# Called from three places in managers, all of which satisfy
# this assertion
assert not (self.ndim == 1 and new_mgr_locs is None)
if new_mgr_locs is None:
new_mgr_locs = self.mgr_locs
return self.make_block_same_class(new_values, new_mgr_locs) | [
"def",
"take_nd",
"(",
"self",
",",
"indexer",
",",
"axis",
"=",
"0",
",",
"new_mgr_locs",
"=",
"None",
",",
"fill_tuple",
"=",
"None",
")",
":",
"if",
"fill_tuple",
"is",
"None",
":",
"fill_value",
"=",
"None",
"else",
":",
"fill_value",
"=",
"fill_tu... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/internals/blocks.py#L1826-L1846 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/fractions.py | python | Fraction.__lt__ | (a, b) | return a._richcmp(b, operator.lt) | a < b | a < b | [
"a",
"<",
"b"
] | def __lt__(a, b):
"""a < b"""
return a._richcmp(b, operator.lt) | [
"def",
"__lt__",
"(",
"a",
",",
"b",
")",
":",
"return",
"a",
".",
"_richcmp",
"(",
"b",
",",
"operator",
".",
"lt",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/fractions.py#L610-L612 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/pytables.py | python | Table.table | (self) | return self.storable | return the table group (this is my storable) | return the table group (this is my storable) | [
"return",
"the",
"table",
"group",
"(",
"this",
"is",
"my",
"storable",
")"
] | def table(self):
""" return the table group (this is my storable) """
return self.storable | [
"def",
"table",
"(",
"self",
")",
":",
"return",
"self",
".",
"storable"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/pytables.py#L3263-L3265 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/smtplib.py | python | SMTP.rset | (self) | return self.docmd("rset") | SMTP 'rset' command -- resets session. | SMTP 'rset' command -- resets session. | [
"SMTP",
"rset",
"command",
"--",
"resets",
"session",
"."
] | def rset(self):
"""SMTP 'rset' command -- resets session."""
self.command_encoding = 'ascii'
return self.docmd("rset") | [
"def",
"rset",
"(",
"self",
")",
":",
"self",
".",
"command_encoding",
"=",
"'ascii'",
"return",
"self",
".",
"docmd",
"(",
"\"rset\"",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/smtplib.py#L495-L498 | |
microsoft/checkedc-clang | a173fefde5d7877b7750e7ce96dd08cf18baebf2 | mlir/utils/spirv/gen_spirv_dialect.py | python | get_spirv_grammar_from_json_spec | () | return spirv['operand_kinds'], spirv['instructions'] | Extracts operand kind and instruction grammar from SPIR-V JSON spec.
Returns:
- A list containing all operand kinds' grammar
- A list containing all instructions' grammar | Extracts operand kind and instruction grammar from SPIR-V JSON spec. | [
"Extracts",
"operand",
"kind",
"and",
"instruction",
"grammar",
"from",
"SPIR",
"-",
"V",
"JSON",
"spec",
"."
] | def get_spirv_grammar_from_json_spec():
"""Extracts operand kind and instruction grammar from SPIR-V JSON spec.
Returns:
- A list containing all operand kinds' grammar
- A list containing all instructions' grammar
"""
response = requests.get(SPIRV_JSON_SPEC_URL)
spec = response.content
import json
spirv = json.loads(spec)
return spirv['operand_kinds'], spirv['instructions'] | [
"def",
"get_spirv_grammar_from_json_spec",
"(",
")",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"SPIRV_JSON_SPEC_URL",
")",
"spec",
"=",
"response",
".",
"content",
"import",
"json",
"spirv",
"=",
"json",
".",
"loads",
"(",
"spec",
")",
"return",
"sp... | https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/mlir/utils/spirv/gen_spirv_dialect.py#L60-L73 | |
naver/sling | 5671cd445a2caae0b4dd0332299e4cfede05062c | webkit/Tools/Scripts/webkitpy/thirdparty/BeautifulSoup.py | python | Tag.findAll | (self, name=None, attrs={}, recursive=True, text=None,
limit=None, **kwargs) | return self._findAll(name, attrs, text, limit, generator, **kwargs) | Extracts a list of Tag objects that match the given
criteria. You can specify the name of the Tag and any
attributes you want the Tag to have.
The value of a key-value pair in the 'attrs' map can be a
string, a list of strings, a regular expression object, or a
callable that takes a string and returns whether or not the
string matches for some custom definition of 'matches'. The
same is true of the tag name. | Extracts a list of Tag objects that match the given
criteria. You can specify the name of the Tag and any
attributes you want the Tag to have. | [
"Extracts",
"a",
"list",
"of",
"Tag",
"objects",
"that",
"match",
"the",
"given",
"criteria",
".",
"You",
"can",
"specify",
"the",
"name",
"of",
"the",
"Tag",
"and",
"any",
"attributes",
"you",
"want",
"the",
"Tag",
"to",
"have",
"."
] | def findAll(self, name=None, attrs={}, recursive=True, text=None,
limit=None, **kwargs):
"""Extracts a list of Tag objects that match the given
criteria. You can specify the name of the Tag and any
attributes you want the Tag to have.
The value of a key-value pair in the 'attrs' map can be a
string, a list of strings, a regular expression object, or a
callable that takes a string and returns whether or not the
string matches for some custom definition of 'matches'. The
same is true of the tag name."""
generator = self.recursiveChildGenerator
if not recursive:
generator = self.childGenerator
return self._findAll(name, attrs, text, limit, generator, **kwargs) | [
"def",
"findAll",
"(",
"self",
",",
"name",
"=",
"None",
",",
"attrs",
"=",
"{",
"}",
",",
"recursive",
"=",
"True",
",",
"text",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"generator",
"=",
"self",
".",
"recursive... | https://github.com/naver/sling/blob/5671cd445a2caae0b4dd0332299e4cfede05062c/webkit/Tools/Scripts/webkitpy/thirdparty/BeautifulSoup.py#L832-L846 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBBreakpoint.GetNumLocations | (self) | return _lldb.SBBreakpoint_GetNumLocations(self) | GetNumLocations(self) -> size_t | GetNumLocations(self) -> size_t | [
"GetNumLocations",
"(",
"self",
")",
"-",
">",
"size_t"
] | def GetNumLocations(self):
"""GetNumLocations(self) -> size_t"""
return _lldb.SBBreakpoint_GetNumLocations(self) | [
"def",
"GetNumLocations",
"(",
"self",
")",
":",
"return",
"_lldb",
".",
"SBBreakpoint_GetNumLocations",
"(",
"self",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L1605-L1607 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/autograph/impl/conversion.py | python | _add_self_references | (namespace, autograph_module) | Adds namespace references to the module that exposes the api itself. | Adds namespace references to the module that exposes the api itself. | [
"Adds",
"namespace",
"references",
"to",
"the",
"module",
"that",
"exposes",
"the",
"api",
"itself",
"."
] | def _add_self_references(namespace, autograph_module):
"""Adds namespace references to the module that exposes the api itself."""
global ag_internal
if ag_internal is None:
# Craft a module that exposes parts of the external API as well as certain
# internal modules.
ag_internal = imp.new_module('autograph')
ag_internal.__dict__.update(autograph_module.__dict__)
ag_internal.ConversionOptions = converter.ConversionOptions
ag_internal.STD = converter.STANDARD_OPTIONS
ag_internal.Feature = converter.Feature
ag_internal.utils = utils
ag_internal.FunctionScope = function_wrappers.FunctionScope
ag_internal.with_function_scope = function_wrappers.with_function_scope
# TODO(mdan): Add safeguards against name clashes.
# We don't want to create a submodule because we want the operators to be
# accessible as ag__.<operator>
ag_internal.__dict__.update(special_functions.__dict__)
ag_internal.__dict__.update(operators.__dict__)
_add_reserved_symbol(namespace, 'ag__', ag_internal) | [
"def",
"_add_self_references",
"(",
"namespace",
",",
"autograph_module",
")",
":",
"global",
"ag_internal",
"if",
"ag_internal",
"is",
"None",
":",
"# Craft a module that exposes parts of the external API as well as certain",
"# internal modules.",
"ag_internal",
"=",
"imp",
... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/autograph/impl/conversion.py#L603-L623 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib2to3/btm_matcher.py | python | BottomMatcher.add_fixer | (self, fixer) | Reduces a fixer's pattern tree to a linear path and adds it
to the matcher(a common Aho-Corasick automaton). The fixer is
appended on the matching states and called when they are
reached | Reduces a fixer's pattern tree to a linear path and adds it
to the matcher(a common Aho-Corasick automaton). The fixer is
appended on the matching states and called when they are
reached | [
"Reduces",
"a",
"fixer",
"s",
"pattern",
"tree",
"to",
"a",
"linear",
"path",
"and",
"adds",
"it",
"to",
"the",
"matcher",
"(",
"a",
"common",
"Aho",
"-",
"Corasick",
"automaton",
")",
".",
"The",
"fixer",
"is",
"appended",
"on",
"the",
"matching",
"st... | def add_fixer(self, fixer):
"""Reduces a fixer's pattern tree to a linear path and adds it
to the matcher(a common Aho-Corasick automaton). The fixer is
appended on the matching states and called when they are
reached"""
self.fixers.append(fixer)
tree = reduce_tree(fixer.pattern_tree)
linear = tree.get_linear_subpattern()
match_nodes = self.add(linear, start=self.root)
for match_node in match_nodes:
match_node.fixers.append(fixer) | [
"def",
"add_fixer",
"(",
"self",
",",
"fixer",
")",
":",
"self",
".",
"fixers",
".",
"append",
"(",
"fixer",
")",
"tree",
"=",
"reduce_tree",
"(",
"fixer",
".",
"pattern_tree",
")",
"linear",
"=",
"tree",
".",
"get_linear_subpattern",
"(",
")",
"match_no... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib2to3/btm_matcher.py#L37-L47 | ||
XCSoar/XCSoar | bc64ca71dbe80df6ebecfdee0609eb0dbba2bdcf | build/python/build/verify.py | python | verify_file_digest | (path, expected_digest) | return file_digest(algorithm, path) == expected_digest | Verify the digest of a file, and return True if the digest matches with the given expected digest. | Verify the digest of a file, and return True if the digest matches with the given expected digest. | [
"Verify",
"the",
"digest",
"of",
"a",
"file",
"and",
"return",
"True",
"if",
"the",
"digest",
"matches",
"with",
"the",
"given",
"expected",
"digest",
"."
] | def verify_file_digest(path, expected_digest):
"""Verify the digest of a file, and return True if the digest matches with the given expected digest."""
algorithm = guess_digest_algorithm(expected_digest)
assert(algorithm is not None)
return file_digest(algorithm, path) == expected_digest | [
"def",
"verify_file_digest",
"(",
"path",
",",
"expected_digest",
")",
":",
"algorithm",
"=",
"guess_digest_algorithm",
"(",
"expected_digest",
")",
"assert",
"(",
"algorithm",
"is",
"not",
"None",
")",
"return",
"file_digest",
"(",
"algorithm",
",",
"path",
")"... | https://github.com/XCSoar/XCSoar/blob/bc64ca71dbe80df6ebecfdee0609eb0dbba2bdcf/build/python/build/verify.py#L39-L44 | |
Kitware/VTK | 5b4df4d90a4f31194d97d3c639dd38ea8f81e8b8 | Wrapping/Python/vtkmodules/gtk/GtkVTKRenderWindow.py | python | GtkVTKRenderWindowBase.GetStillUpdateRate | (self) | return self._StillUpdateRate | Mirrors the method with the same name in
vtkRenderWindowInteractor. | Mirrors the method with the same name in
vtkRenderWindowInteractor. | [
"Mirrors",
"the",
"method",
"with",
"the",
"same",
"name",
"in",
"vtkRenderWindowInteractor",
"."
] | def GetStillUpdateRate(self):
"""Mirrors the method with the same name in
vtkRenderWindowInteractor."""
return self._StillUpdateRate | [
"def",
"GetStillUpdateRate",
"(",
"self",
")",
":",
"return",
"self",
".",
"_StillUpdateRate"
] | https://github.com/Kitware/VTK/blob/5b4df4d90a4f31194d97d3c639dd38ea8f81e8b8/Wrapping/Python/vtkmodules/gtk/GtkVTKRenderWindow.py#L115-L118 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Source/ThirdParty/FreeType2/FreeType2-2.4.12/src/tools/docmaker/sources.py | python | SourceProcessor.process_normal_line | ( self, line ) | process a normal line and check whether it is the start of a new block | process a normal line and check whether it is the start of a new block | [
"process",
"a",
"normal",
"line",
"and",
"check",
"whether",
"it",
"is",
"the",
"start",
"of",
"a",
"new",
"block"
] | def process_normal_line( self, line ):
"""process a normal line and check whether it is the start of a new block"""
for f in re_source_block_formats:
if f.start.match( line ):
self.add_block_lines()
self.format = f
self.lineno = fileinput.filelineno()
self.lines.append( line ) | [
"def",
"process_normal_line",
"(",
"self",
",",
"line",
")",
":",
"for",
"f",
"in",
"re_source_block_formats",
":",
"if",
"f",
".",
"start",
".",
"match",
"(",
"line",
")",
":",
"self",
".",
"add_block_lines",
"(",
")",
"self",
".",
"format",
"=",
"f",... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Source/ThirdParty/FreeType2/FreeType2-2.4.12/src/tools/docmaker/sources.py#L322-L330 | ||
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/contrib/slim/quantization/post_training_quantization.py | python | _load_variable_data | (scope, var_name) | return np.array(var_node.get_tensor()) | Load variable value from scope | Load variable value from scope | [
"Load",
"variable",
"value",
"from",
"scope"
] | def _load_variable_data(scope, var_name):
'''
Load variable value from scope
'''
var_node = scope.find_var(var_name)
assert var_node is not None, \
"Cannot find " + var_name + " in scope."
return np.array(var_node.get_tensor()) | [
"def",
"_load_variable_data",
"(",
"scope",
",",
"var_name",
")",
":",
"var_node",
"=",
"scope",
".",
"find_var",
"(",
"var_name",
")",
"assert",
"var_node",
"is",
"not",
"None",
",",
"\"Cannot find \"",
"+",
"var_name",
"+",
"\" in scope.\"",
"return",
"np",
... | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/contrib/slim/quantization/post_training_quantization.py#L45-L52 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/urllib3/packages/ssl_match_hostname/_implementation.py | python | _dnsname_match | (dn, hostname, max_wildcards=1) | return pat.match(hostname) | Matching according to RFC 6125, section 6.4.3
http://tools.ietf.org/html/rfc6125#section-6.4.3 | Matching according to RFC 6125, section 6.4.3 | [
"Matching",
"according",
"to",
"RFC",
"6125",
"section",
"6",
".",
"4",
".",
"3"
] | def _dnsname_match(dn, hostname, max_wildcards=1):
"""Matching according to RFC 6125, section 6.4.3
http://tools.ietf.org/html/rfc6125#section-6.4.3
"""
pats = []
if not dn:
return False
# Ported from python3-syntax:
# leftmost, *remainder = dn.split(r'.')
parts = dn.split(r".")
leftmost = parts[0]
remainder = parts[1:]
wildcards = leftmost.count("*")
if wildcards > max_wildcards:
# Issue #17980: avoid denials of service by refusing more
# than one wildcard per fragment. A survey of established
# policy among SSL implementations showed it to be a
# reasonable choice.
raise CertificateError(
"too many wildcards in certificate DNS name: " + repr(dn)
)
# speed up common case w/o wildcards
if not wildcards:
return dn.lower() == hostname.lower()
# RFC 6125, section 6.4.3, subitem 1.
# The client SHOULD NOT attempt to match a presented identifier in which
# the wildcard character comprises a label other than the left-most label.
if leftmost == "*":
# When '*' is a fragment by itself, it matches a non-empty dotless
# fragment.
pats.append("[^.]+")
elif leftmost.startswith("xn--") or hostname.startswith("xn--"):
# RFC 6125, section 6.4.3, subitem 3.
# The client SHOULD NOT attempt to match a presented identifier
# where the wildcard character is embedded within an A-label or
# U-label of an internationalized domain name.
pats.append(re.escape(leftmost))
else:
# Otherwise, '*' matches any dotless string, e.g. www*
pats.append(re.escape(leftmost).replace(r"\*", "[^.]*"))
# add the remaining fragments, ignore any wildcards
for frag in remainder:
pats.append(re.escape(frag))
pat = re.compile(r"\A" + r"\.".join(pats) + r"\Z", re.IGNORECASE)
return pat.match(hostname) | [
"def",
"_dnsname_match",
"(",
"dn",
",",
"hostname",
",",
"max_wildcards",
"=",
"1",
")",
":",
"pats",
"=",
"[",
"]",
"if",
"not",
"dn",
":",
"return",
"False",
"# Ported from python3-syntax:",
"# leftmost, *remainder = dn.split(r'.')",
"parts",
"=",
"dn",
".",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/urllib3/packages/ssl_match_hostname/_implementation.py#L25-L76 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/pkg_resources/_vendor/pyparsing.py | python | ParserElement.__xor__ | (self, other ) | return Or( [ self, other ] ) | Implementation of ^ operator - returns C{L{Or}} | Implementation of ^ operator - returns C{L{Or}} | [
"Implementation",
"of",
"^",
"operator",
"-",
"returns",
"C",
"{",
"L",
"{",
"Or",
"}}"
] | def __xor__(self, other ):
"""
Implementation of ^ operator - returns C{L{Or}}
"""
if isinstance( other, basestring ):
other = ParserElement._literalStringClass( other )
if not isinstance( other, ParserElement ):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return Or( [ self, other ] ) | [
"def",
"__xor__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"ParserElement",
".",
"_literalStringClass",
"(",
"other",
")",
"if",
"not",
"isinstance",
"(",
"other",
",",
"ParserElement... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/pkg_resources/_vendor/pyparsing.py#L1931-L1941 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/propgrid.py | python | NewFontProperty | (*args, **kwargs) | return _propgrid.NewFontProperty(*args, **kwargs) | NewFontProperty(String label=(*wxPGProperty::sm_wxPG_LABEL), String name=(*wxPGProperty::sm_wxPG_LABEL),
Font value=wxFont()) -> PGProperty | NewFontProperty(String label=(*wxPGProperty::sm_wxPG_LABEL), String name=(*wxPGProperty::sm_wxPG_LABEL),
Font value=wxFont()) -> PGProperty | [
"NewFontProperty",
"(",
"String",
"label",
"=",
"(",
"*",
"wxPGProperty",
"::",
"sm_wxPG_LABEL",
")",
"String",
"name",
"=",
"(",
"*",
"wxPGProperty",
"::",
"sm_wxPG_LABEL",
")",
"Font",
"value",
"=",
"wxFont",
"()",
")",
"-",
">",
"PGProperty"
] | def NewFontProperty(*args, **kwargs):
"""
NewFontProperty(String label=(*wxPGProperty::sm_wxPG_LABEL), String name=(*wxPGProperty::sm_wxPG_LABEL),
Font value=wxFont()) -> PGProperty
"""
return _propgrid.NewFontProperty(*args, **kwargs) | [
"def",
"NewFontProperty",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"NewFontProperty",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L3747-L3752 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/importlib-metadata/py3/importlib_metadata/__init__.py | python | EntryPoints.__getitem__ | (self, name) | Get the EntryPoint in self matching name. | Get the EntryPoint in self matching name. | [
"Get",
"the",
"EntryPoint",
"in",
"self",
"matching",
"name",
"."
] | def __getitem__(self, name): # -> EntryPoint:
"""
Get the EntryPoint in self matching name.
"""
if isinstance(name, int):
warnings.warn(
"Accessing entry points by index is deprecated. "
"Cast to tuple if needed.",
DeprecationWarning,
stacklevel=2,
)
return super().__getitem__(name)
try:
return next(iter(self.select(name=name)))
except StopIteration:
raise KeyError(name) | [
"def",
"__getitem__",
"(",
"self",
",",
"name",
")",
":",
"# -> EntryPoint:",
"if",
"isinstance",
"(",
"name",
",",
"int",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Accessing entry points by index is deprecated. \"",
"\"Cast to tuple if needed.\"",
",",
"DeprecationW... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/importlib-metadata/py3/importlib_metadata/__init__.py#L340-L355 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/grit/grit/gather/txt.py | python | TxtFile.GetCliques | (self) | return [self.clique_] | Returns the MessageClique objects for all translateable portions. | Returns the MessageClique objects for all translateable portions. | [
"Returns",
"the",
"MessageClique",
"objects",
"for",
"all",
"translateable",
"portions",
"."
] | def GetCliques(self):
'''Returns the MessageClique objects for all translateable portions.'''
return [self.clique_] | [
"def",
"GetCliques",
"(",
"self",
")",
":",
"return",
"[",
"self",
".",
"clique_",
"]"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/grit/grit/gather/txt.py#L29-L31 | |
MythTV/mythtv | d282a209cb8be85d036f85a62a8ec971b67d45f4 | mythtv/bindings/python/MythTV/utility/dequebuffer.py | python | DequeBuffer.write | (self, data) | return end | Write provide data into buffer. | Write provide data into buffer. | [
"Write",
"provide",
"data",
"into",
"buffer",
"."
] | def write(self, data):
"""Write provide data into buffer."""
data = BytesIO(data)
data.seek(0, 2)
end = data.tell()
pos = 0
while True:
data.seek(pos)
try:
# grab last entry in buffer
tmp = self._buffer[-1]
except IndexError:
# buffer is empty, add a new block
tmp = self._Buffer()
self._buffer.append(tmp)
# write as much data as possible, and update progress
pos += tmp.write(data.read(tmp.blocksize))
if pos == end:
# no more data to write
break
else:
# add another block, and loop back through
self._buffer.append(self._Buffer())
self._nbytes += end
return end | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"data",
"=",
"BytesIO",
"(",
"data",
")",
"data",
".",
"seek",
"(",
"0",
",",
"2",
")",
"end",
"=",
"data",
".",
"tell",
"(",
")",
"pos",
"=",
"0",
"while",
"True",
":",
"data",
".",
"seek",... | https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/bindings/python/MythTV/utility/dequebuffer.py#L270-L294 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/python/turicreate/data_structures/sarray.py | python | SArray.min | (self) | Get minimum numeric value in SArray.
Returns None on an empty SArray. Raises an exception if called on an
SArray with non-numeric type.
Returns
-------
out : type of SArray
Minimum value of SArray
See Also
--------
max
Examples
--------
>>> turicreate.SArray([14, 62, 83, 72, 77, 96, 5, 25, 69, 66]).min() | Get minimum numeric value in SArray. | [
"Get",
"minimum",
"numeric",
"value",
"in",
"SArray",
"."
] | def min(self):
"""
Get minimum numeric value in SArray.
Returns None on an empty SArray. Raises an exception if called on an
SArray with non-numeric type.
Returns
-------
out : type of SArray
Minimum value of SArray
See Also
--------
max
Examples
--------
>>> turicreate.SArray([14, 62, 83, 72, 77, 96, 5, 25, 69, 66]).min()
"""
with cython_context():
return self.__proxy__.min() | [
"def",
"min",
"(",
"self",
")",
":",
"with",
"cython_context",
"(",
")",
":",
"return",
"self",
".",
"__proxy__",
".",
"min",
"(",
")"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/data_structures/sarray.py#L2164-L2186 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/richtext.py | python | TextAttrDimensionConverter.ConvertPixelsToTenthsMM | (*args, **kwargs) | return _richtext.TextAttrDimensionConverter_ConvertPixelsToTenthsMM(*args, **kwargs) | ConvertPixelsToTenthsMM(self, int pixels) -> int | ConvertPixelsToTenthsMM(self, int pixels) -> int | [
"ConvertPixelsToTenthsMM",
"(",
"self",
"int",
"pixels",
")",
"-",
">",
"int"
] | def ConvertPixelsToTenthsMM(*args, **kwargs):
"""ConvertPixelsToTenthsMM(self, int pixels) -> int"""
return _richtext.TextAttrDimensionConverter_ConvertPixelsToTenthsMM(*args, **kwargs) | [
"def",
"ConvertPixelsToTenthsMM",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"TextAttrDimensionConverter_ConvertPixelsToTenthsMM",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L282-L284 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/os2emxpath.py | python | ismount | (path) | return len(p) == 1 and p[0] in '/\\' | Test whether a path is a mount point (defined as root of drive) | Test whether a path is a mount point (defined as root of drive) | [
"Test",
"whether",
"a",
"path",
"is",
"a",
"mount",
"point",
"(",
"defined",
"as",
"root",
"of",
"drive",
")"
] | def ismount(path):
"""Test whether a path is a mount point (defined as root of drive)"""
unc, rest = splitunc(path)
if unc:
return rest in ("", "/", "\\")
p = splitdrive(path)[1]
return len(p) == 1 and p[0] in '/\\' | [
"def",
"ismount",
"(",
"path",
")",
":",
"unc",
",",
"rest",
"=",
"splitunc",
"(",
"path",
")",
"if",
"unc",
":",
"return",
"rest",
"in",
"(",
"\"\"",
",",
"\"/\"",
",",
"\"\\\\\"",
")",
"p",
"=",
"splitdrive",
"(",
"path",
")",
"[",
"1",
"]",
... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/os2emxpath.py#L109-L115 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/dashboard/dashboard/file_bug.py | python | _AdditionalDetails | (bug_id, alerts) | return comment | Returns a message with additional information to add to a bug. | Returns a message with additional information to add to a bug. | [
"Returns",
"a",
"message",
"with",
"additional",
"information",
"to",
"add",
"to",
"a",
"bug",
"."
] | def _AdditionalDetails(bug_id, alerts):
"""Returns a message with additional information to add to a bug."""
base_url = '%s/group_report' % _GetServerURL()
bug_page_url = '%s?bug_id=%s' % (base_url, bug_id)
alerts_url = '%s?keys=%s' % (base_url, _UrlsafeKeys(alerts))
comment = 'All graphs for this bug:\n %s\n\n' % bug_page_url
comment += 'Original alerts at time of bug-filing:\n %s\n' % alerts_url
bot_names = alert.GetBotNamesFromAlerts(alerts)
if bot_names:
comment += '\n\nBot(s) for this bug\'s original alert(s):\n\n'
comment += '\n'.join(sorted(bot_names))
else:
comment += '\nCould not extract bot names from the list of alerts.'
return comment | [
"def",
"_AdditionalDetails",
"(",
"bug_id",
",",
"alerts",
")",
":",
"base_url",
"=",
"'%s/group_report'",
"%",
"_GetServerURL",
"(",
")",
"bug_page_url",
"=",
"'%s?bug_id=%s'",
"%",
"(",
"base_url",
",",
"bug_id",
")",
"alerts_url",
"=",
"'%s?keys=%s'",
"%",
... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/dashboard/dashboard/file_bug.py#L158-L171 | |
rdkit/rdkit | ede860ae316d12d8568daf5ee800921c3389c84e | rdkit/ML/Data/MLData.py | python | MLQuantDataSet.GetInputData | (self) | return (self.data[:, :-self.nResults]).tolist() | returns the input data
**Note**
_inputData_ means the examples without their result fields
(the last _NResults_ entries) | returns the input data | [
"returns",
"the",
"input",
"data"
] | def GetInputData(self):
""" returns the input data
**Note**
_inputData_ means the examples without their result fields
(the last _NResults_ entries)
"""
return (self.data[:, :-self.nResults]).tolist() | [
"def",
"GetInputData",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"data",
"[",
":",
",",
":",
"-",
"self",
".",
"nResults",
"]",
")",
".",
"tolist",
"(",
")"
] | https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/ML/Data/MLData.py#L253-L262 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | tools/site_compare/drivers/win32/windowing.py | python | WaitForThrobber | (hwnd, rect=None, timeout=20, tick=0.1, done=10) | return -1 | Wait for a browser's "throbber" (loading animation) to complete.
Args:
hwnd: window containing the throbber
rect: rectangle of the throbber, in client coords. If None, whole window
timeout: if the throbber is still throbbing after this long, give up
tick: how often to check the throbber
done: how long the throbber must be unmoving to be considered done
Returns:
Number of seconds waited, -1 if timed out | Wait for a browser's "throbber" (loading animation) to complete. | [
"Wait",
"for",
"a",
"browser",
"s",
"throbber",
"(",
"loading",
"animation",
")",
"to",
"complete",
"."
] | def WaitForThrobber(hwnd, rect=None, timeout=20, tick=0.1, done=10):
"""Wait for a browser's "throbber" (loading animation) to complete.
Args:
hwnd: window containing the throbber
rect: rectangle of the throbber, in client coords. If None, whole window
timeout: if the throbber is still throbbing after this long, give up
tick: how often to check the throbber
done: how long the throbber must be unmoving to be considered done
Returns:
Number of seconds waited, -1 if timed out
"""
if not rect: rect = win32gui.GetClientRect(hwnd)
# last_throbber will hold the results of the preceding scrape;
# we'll compare it against the current scrape to see if we're throbbing
last_throbber = ScrapeWindow(hwnd, rect)
start_clock = time.clock()
timeout_clock = start_clock + timeout
last_changed_clock = start_clock;
while time.clock() < timeout_clock:
time.sleep(tick)
current_throbber = ScrapeWindow(hwnd, rect)
if current_throbber.tostring() != last_throbber.tostring():
last_throbber = current_throbber
last_changed_clock = time.clock()
else:
if time.clock() - last_changed_clock > done:
return last_changed_clock - start_clock
return -1 | [
"def",
"WaitForThrobber",
"(",
"hwnd",
",",
"rect",
"=",
"None",
",",
"timeout",
"=",
"20",
",",
"tick",
"=",
"0.1",
",",
"done",
"=",
"10",
")",
":",
"if",
"not",
"rect",
":",
"rect",
"=",
"win32gui",
".",
"GetClientRect",
"(",
"hwnd",
")",
"# las... | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/tools/site_compare/drivers/win32/windowing.py#L218-L251 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/idl/idl_compatibility_errors.py | python | IDLCompatibilityContext.add_new_command_or_param_type_not_variant_type_error | (self, command_name: str, new_type: str,
file: str, field_name: Optional[str],
is_command_parameter: bool) | Add an error about the new command or parameter type not being a variant type.
Add an error about the new command or parameter type not being a variant type
when the old type is variant. | Add an error about the new command or parameter type not being a variant type. | [
"Add",
"an",
"error",
"about",
"the",
"new",
"command",
"or",
"parameter",
"type",
"not",
"being",
"a",
"variant",
"type",
"."
] | def add_new_command_or_param_type_not_variant_type_error(self, command_name: str, new_type: str,
file: str, field_name: Optional[str],
is_command_parameter: bool) -> None:
# pylint: disable=too-many-arguments,invalid-name
"""
Add an error about the new command or parameter type not being a variant type.
Add an error about the new command or parameter type not being a variant type
when the old type is variant.
"""
if is_command_parameter:
self._add_error(ERROR_ID_NEW_COMMAND_PARAMETER_TYPE_NOT_VARIANT, command_name,
("The '%s' command has field or sub-field '%s' of type '%s' that is "
"not variant while the corresponding old field type is variant.") %
(command_name, field_name, new_type), file)
else:
self._add_error(ERROR_ID_NEW_COMMAND_TYPE_NOT_VARIANT, command_name,
("'%s' or its sub-struct has type '%s' that is not "
"variant while the corresponding "
"old type is variant.") % (command_name, new_type), file) | [
"def",
"add_new_command_or_param_type_not_variant_type_error",
"(",
"self",
",",
"command_name",
":",
"str",
",",
"new_type",
":",
"str",
",",
"file",
":",
"str",
",",
"field_name",
":",
"Optional",
"[",
"str",
"]",
",",
"is_command_parameter",
":",
"bool",
")",... | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl_compatibility_errors.py#L571-L591 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_controls.py | python | TreeCtrl.__init__ | (self, *args, **kwargs) | __init__(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=TR_DEFAULT_STYLE,
Validator validator=DefaultValidator,
String name=TreeCtrlNameStr) -> TreeCtrl | __init__(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=TR_DEFAULT_STYLE,
Validator validator=DefaultValidator,
String name=TreeCtrlNameStr) -> TreeCtrl | [
"__init__",
"(",
"self",
"Window",
"parent",
"int",
"id",
"=",
"-",
"1",
"Point",
"pos",
"=",
"DefaultPosition",
"Size",
"size",
"=",
"DefaultSize",
"long",
"style",
"=",
"TR_DEFAULT_STYLE",
"Validator",
"validator",
"=",
"DefaultValidator",
"String",
"name",
... | def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=TR_DEFAULT_STYLE,
Validator validator=DefaultValidator,
String name=TreeCtrlNameStr) -> TreeCtrl
"""
_controls_.TreeCtrl_swiginit(self,_controls_.new_TreeCtrl(*args, **kwargs))
self._setOORInfo(self);TreeCtrl._setCallbackInfo(self, self, TreeCtrl) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_controls_",
".",
"TreeCtrl_swiginit",
"(",
"self",
",",
"_controls_",
".",
"new_TreeCtrl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"self",
".",
"_setO... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L5184-L5192 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | remoting/host/installer/build-installer-archive.py | python | copyZipIntoArchive | (out_dir, files_root, zip_file) | Expands the zip_file into the out_dir, preserving the directory structure.
Args:
out_dir: Target directory where unzipped files are copied.
files_root: Path prefix which is stripped of zip_file before appending
it to the out_dir.
zip_file: Relative path (and filename) to the zip file. | Expands the zip_file into the out_dir, preserving the directory structure. | [
"Expands",
"the",
"zip_file",
"into",
"the",
"out_dir",
"preserving",
"the",
"directory",
"structure",
"."
] | def copyZipIntoArchive(out_dir, files_root, zip_file):
"""Expands the zip_file into the out_dir, preserving the directory structure.
Args:
out_dir: Target directory where unzipped files are copied.
files_root: Path prefix which is stripped of zip_file before appending
it to the out_dir.
zip_file: Relative path (and filename) to the zip file.
"""
base_zip_name = os.path.basename(zip_file)
# We don't use the 'zipfile' module here because it doesn't restore all the
# file permissions correctly. We use the 'unzip' command manually.
old_dir = os.getcwd();
os.chdir(os.path.dirname(zip_file))
subprocess.call(['unzip', '-qq', '-o', base_zip_name])
os.chdir(old_dir)
# Unzip into correct dir in out_dir.
out_zip_path = remapSrcFile(out_dir, files_root, zip_file)
out_zip_dir = os.path.dirname(out_zip_path)
(src_dir, ignore1) = os.path.splitext(zip_file)
(base_dir_name, ignore2) = os.path.splitext(base_zip_name)
shutil.copytree(src_dir, os.path.join(out_zip_dir, base_dir_name)) | [
"def",
"copyZipIntoArchive",
"(",
"out_dir",
",",
"files_root",
",",
"zip_file",
")",
":",
"base_zip_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"zip_file",
")",
"# We don't use the 'zipfile' module here because it doesn't restore all the",
"# file permissions corr... | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/remoting/host/installer/build-installer-archive.py#L142-L166 | ||
gimli-org/gimli | 17aa2160de9b15ababd9ef99e89b1bc3277bbb23 | pygimli/utils/gps.py | python | GK2toUTM | (ea, no=None, zone=32) | return GKtoUTM(ea, no, zone, gkzone=2) | Transform Gauss-Krueger zone 2 into UTM (for backward compatibility). | Transform Gauss-Krueger zone 2 into UTM (for backward compatibility). | [
"Transform",
"Gauss",
"-",
"Krueger",
"zone",
"2",
"into",
"UTM",
"(",
"for",
"backward",
"compatibility",
")",
"."
] | def GK2toUTM(ea, no=None, zone=32):
"""Transform Gauss-Krueger zone 2 into UTM (for backward compatibility)."""
return GKtoUTM(ea, no, zone, gkzone=2) | [
"def",
"GK2toUTM",
"(",
"ea",
",",
"no",
"=",
"None",
",",
"zone",
"=",
"32",
")",
":",
"return",
"GKtoUTM",
"(",
"ea",
",",
"no",
",",
"zone",
",",
"gkzone",
"=",
"2",
")"
] | https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/utils/gps.py#L207-L209 | |
D-X-Y/caffe-faster-rcnn | eb50c97ff48f3df115d0e85fe0a32b0c7e2aa4cb | python/caffe/pycaffe.py | python | _Net_batch | (self, blobs) | Batch blob lists according to net's batch size.
Parameters
----------
blobs: Keys blob names and values are lists of blobs (of any length).
Naturally, all the lists should have the same length.
Yields
------
batch: {blob name: list of blobs} dict for a single batch. | Batch blob lists according to net's batch size. | [
"Batch",
"blob",
"lists",
"according",
"to",
"net",
"s",
"batch",
"size",
"."
] | def _Net_batch(self, blobs):
"""
Batch blob lists according to net's batch size.
Parameters
----------
blobs: Keys blob names and values are lists of blobs (of any length).
Naturally, all the lists should have the same length.
Yields
------
batch: {blob name: list of blobs} dict for a single batch.
"""
num = len(six.next(six.itervalues(blobs)))
batch_size = six.next(six.itervalues(self.blobs)).shape[0]
remainder = num % batch_size
num_batches = num // batch_size
# Yield full batches.
for b in range(num_batches):
i = b * batch_size
yield {name: blobs[name][i:i + batch_size] for name in blobs}
# Yield last padded batch, if any.
if remainder > 0:
padded_batch = {}
for name in blobs:
padding = np.zeros((batch_size - remainder,)
+ blobs[name].shape[1:])
padded_batch[name] = np.concatenate([blobs[name][-remainder:],
padding])
yield padded_batch | [
"def",
"_Net_batch",
"(",
"self",
",",
"blobs",
")",
":",
"num",
"=",
"len",
"(",
"six",
".",
"next",
"(",
"six",
".",
"itervalues",
"(",
"blobs",
")",
")",
")",
"batch_size",
"=",
"six",
".",
"next",
"(",
"six",
".",
"itervalues",
"(",
"self",
"... | https://github.com/D-X-Y/caffe-faster-rcnn/blob/eb50c97ff48f3df115d0e85fe0a32b0c7e2aa4cb/python/caffe/pycaffe.py#L272-L303 | ||
alexgkendall/caffe-segnet | 344c113bf1832886f1cbe9f33ffe28a3beeaf412 | tools/extra/parse_log.py | python | write_csv | (output_filename, dict_list, delimiter, verbose=False) | Write a CSV file | Write a CSV file | [
"Write",
"a",
"CSV",
"file"
] | def write_csv(output_filename, dict_list, delimiter, verbose=False):
"""Write a CSV file
"""
dialect = csv.excel
dialect.delimiter = delimiter
with open(output_filename, 'w') as f:
dict_writer = csv.DictWriter(f, fieldnames=dict_list[0].keys(),
dialect=dialect)
dict_writer.writeheader()
dict_writer.writerows(dict_list)
if verbose:
print 'Wrote %s' % output_filename | [
"def",
"write_csv",
"(",
"output_filename",
",",
"dict_list",
",",
"delimiter",
",",
"verbose",
"=",
"False",
")",
":",
"dialect",
"=",
"csv",
".",
"excel",
"dialect",
".",
"delimiter",
"=",
"delimiter",
"with",
"open",
"(",
"output_filename",
",",
"'w'",
... | https://github.com/alexgkendall/caffe-segnet/blob/344c113bf1832886f1cbe9f33ffe28a3beeaf412/tools/extra/parse_log.py#L148-L161 | ||
SFTtech/openage | d6a08c53c48dc1e157807471df92197f6ca9e04d | openage/convert/processor/conversion/aoc/pregen_processor.py | python | AoCPregenSubprocessor.generate_exchange_objects | (full_data_set, pregen_converter_group) | Generate objects for market trading (ExchangeResources).
:param full_data_set: GenieObjectContainer instance that
contains all relevant data for the conversion
process.
:type full_data_set: ...dataformat.aoc.genie_object_container.GenieObjectContainer
:param pregen_converter_group: GenieObjectGroup instance that stores
pregenerated API objects for referencing with
ForwardRef
:type pregen_converter_group: ...dataformat.aoc.genie_object_container.GenieObjectGroup | Generate objects for market trading (ExchangeResources). | [
"Generate",
"objects",
"for",
"market",
"trading",
"(",
"ExchangeResources",
")",
"."
] | def generate_exchange_objects(full_data_set, pregen_converter_group):
"""
Generate objects for market trading (ExchangeResources).
:param full_data_set: GenieObjectContainer instance that
contains all relevant data for the conversion
process.
:type full_data_set: ...dataformat.aoc.genie_object_container.GenieObjectContainer
:param pregen_converter_group: GenieObjectGroup instance that stores
pregenerated API objects for referencing with
ForwardRef
:type pregen_converter_group: ...dataformat.aoc.genie_object_container.GenieObjectGroup
"""
pregen_nyan_objects = full_data_set.pregen_nyan_objects
api_objects = full_data_set.nyan_api_objects
# =======================================================================
# Exchange mode Buy
# =======================================================================
exchange_mode_parent = "engine.util.exchange_mode.type.Buy"
exchange_mode_location = "data/util/resource/"
exchange_mode_ref_in_modpack = "util.resource.market_trading.MarketBuyExchangeMode"
exchange_mode_raw_api_object = RawAPIObject(exchange_mode_ref_in_modpack,
"MarketBuyExchangePool",
api_objects,
exchange_mode_location)
exchange_mode_raw_api_object.set_filename("market_trading")
exchange_mode_raw_api_object.add_raw_parent(exchange_mode_parent)
# Fee (30% on top)
exchange_mode_raw_api_object.add_raw_member("fee_multiplier",
1.3,
"engine.util.exchange_mode.ExchangeMode")
pregen_converter_group.add_raw_api_object(exchange_mode_raw_api_object)
pregen_nyan_objects.update({exchange_mode_ref_in_modpack: exchange_mode_raw_api_object})
# =======================================================================
# Exchange mode Sell
# =======================================================================
exchange_mode_parent = "engine.util.exchange_mode.type.Sell"
exchange_mode_location = "data/util/resource/"
exchange_mode_ref_in_modpack = "util.resource.market_trading.MarketSellExchangeMode"
exchange_mode_raw_api_object = RawAPIObject(exchange_mode_ref_in_modpack,
"MarketSellExchangeMode",
api_objects,
exchange_mode_location)
exchange_mode_raw_api_object.set_filename("market_trading")
exchange_mode_raw_api_object.add_raw_parent(exchange_mode_parent)
# Fee (30% reduced)
exchange_mode_raw_api_object.add_raw_member("fee_multiplier",
0.7,
"engine.util.exchange_mode.ExchangeMode")
pregen_converter_group.add_raw_api_object(exchange_mode_raw_api_object)
pregen_nyan_objects.update({exchange_mode_ref_in_modpack: exchange_mode_raw_api_object})
# =======================================================================
# Market Food price pool
# =======================================================================
exchange_pool_parent = "engine.util.price_pool.PricePool"
exchange_pool_location = "data/util/resource/"
exchange_pool_ref_in_modpack = "util.resource.market_trading.MarketFoodPricePool"
exchange_pool_raw_api_object = RawAPIObject(exchange_pool_ref_in_modpack,
"MarketFoodPricePool",
api_objects,
exchange_pool_location)
exchange_pool_raw_api_object.set_filename("market_trading")
exchange_pool_raw_api_object.add_raw_parent(exchange_pool_parent)
pregen_converter_group.add_raw_api_object(exchange_pool_raw_api_object)
pregen_nyan_objects.update({exchange_pool_ref_in_modpack: exchange_pool_raw_api_object})
# =======================================================================
# Market Wood price pool
# =======================================================================
exchange_pool_ref_in_modpack = "util.resource.market_trading.MarketWoodPricePool"
exchange_pool_raw_api_object = RawAPIObject(exchange_pool_ref_in_modpack,
"MarketWoodPricePool",
api_objects,
exchange_pool_location)
exchange_pool_raw_api_object.set_filename("market_trading")
exchange_pool_raw_api_object.add_raw_parent(exchange_pool_parent)
pregen_converter_group.add_raw_api_object(exchange_pool_raw_api_object)
pregen_nyan_objects.update({exchange_pool_ref_in_modpack: exchange_pool_raw_api_object})
# =======================================================================
# Market Stone price pool
# =======================================================================
exchange_pool_ref_in_modpack = "util.resource.market_trading.MarketStonePricePool"
exchange_pool_raw_api_object = RawAPIObject(exchange_pool_ref_in_modpack,
"MarketStonePricePool",
api_objects,
exchange_pool_location)
exchange_pool_raw_api_object.set_filename("market_trading")
exchange_pool_raw_api_object.add_raw_parent(exchange_pool_parent)
pregen_converter_group.add_raw_api_object(exchange_pool_raw_api_object)
pregen_nyan_objects.update({exchange_pool_ref_in_modpack: exchange_pool_raw_api_object})
# =======================================================================
# Exchange rate Food
# =======================================================================
exchange_rate_parent = "engine.util.exchange_rate.ExchangeRate"
exchange_rate_location = "data/util/resource/"
exchange_rate_ref_in_modpack = "util.resource.market_trading.MarketFoodExchangeRate"
exchange_rate_raw_api_object = RawAPIObject(exchange_rate_ref_in_modpack,
"MarketFoodExchangeRate",
api_objects,
exchange_rate_location)
exchange_rate_raw_api_object.set_filename("market_trading")
exchange_rate_raw_api_object.add_raw_parent(exchange_rate_parent)
# Base price
exchange_rate_raw_api_object.add_raw_member("base_price",
1.0,
exchange_rate_parent)
# Price adjust methods
pa_buy_forward_ref = ForwardRef(pregen_converter_group,
"util.resource.market_trading.MarketBuyPriceMode")
pa_sell_forward_ref = ForwardRef(pregen_converter_group,
"util.resource.market_trading.MarketSellPriceMode")
price_adjust = {
api_objects["engine.util.exchange_mode.type.Buy"]: pa_buy_forward_ref,
api_objects["engine.util.exchange_mode.type.Sell"]: pa_sell_forward_ref
}
exchange_rate_raw_api_object.add_raw_member("price_adjust",
price_adjust,
exchange_rate_parent)
# Price pool
pool_forward_ref = ForwardRef(pregen_converter_group,
"util.resource.market_trading.MarketFoodPricePool")
exchange_rate_raw_api_object.add_raw_member("price_pool",
pool_forward_ref,
exchange_rate_parent)
pregen_converter_group.add_raw_api_object(exchange_rate_raw_api_object)
pregen_nyan_objects.update({exchange_rate_ref_in_modpack: exchange_rate_raw_api_object})
# =======================================================================
# Exchange rate Wood
# =======================================================================
exchange_rate_ref_in_modpack = "util.resource.market_trading.MarketWoodExchangeRate"
exchange_rate_raw_api_object = RawAPIObject(exchange_rate_ref_in_modpack,
"MarketWoodExchangeRate",
api_objects,
exchange_rate_location)
exchange_rate_raw_api_object.set_filename("market_trading")
exchange_rate_raw_api_object.add_raw_parent(exchange_rate_parent)
# Base price
exchange_rate_raw_api_object.add_raw_member("base_price",
1.0,
exchange_rate_parent)
# Price adjust methods
pa_buy_forward_ref = ForwardRef(pregen_converter_group,
"util.resource.market_trading.MarketBuyPriceMode")
pa_sell_forward_ref = ForwardRef(pregen_converter_group,
"util.resource.market_trading.MarketSellPriceMode")
price_adjust = {
api_objects["engine.util.exchange_mode.type.Buy"]: pa_buy_forward_ref,
api_objects["engine.util.exchange_mode.type.Sell"]: pa_sell_forward_ref
}
exchange_rate_raw_api_object.add_raw_member("price_adjust",
price_adjust,
exchange_rate_parent)
# Price pool
pool_forward_ref = ForwardRef(pregen_converter_group,
"util.resource.market_trading.MarketWoodPricePool")
exchange_rate_raw_api_object.add_raw_member("price_pool",
pool_forward_ref,
exchange_rate_parent)
pregen_converter_group.add_raw_api_object(exchange_rate_raw_api_object)
pregen_nyan_objects.update({exchange_rate_ref_in_modpack: exchange_rate_raw_api_object})
# =======================================================================
# Exchange rate Stone
# =======================================================================
exchange_rate_ref_in_modpack = "util.resource.market_trading.MarketStoneExchangeRate"
exchange_rate_raw_api_object = RawAPIObject(exchange_rate_ref_in_modpack,
"MarketStoneExchangeRate",
api_objects,
exchange_rate_location)
exchange_rate_raw_api_object.set_filename("market_trading")
exchange_rate_raw_api_object.add_raw_parent(exchange_rate_parent)
# Base price
exchange_rate_raw_api_object.add_raw_member("base_price",
1.3,
exchange_rate_parent)
# Price adjust methods
pa_buy_forward_ref = ForwardRef(pregen_converter_group,
"util.resource.market_trading.MarketBuyPriceMode")
pa_sell_forward_ref = ForwardRef(pregen_converter_group,
"util.resource.market_trading.MarketSellPriceMode")
price_adjust = {
api_objects["engine.util.exchange_mode.type.Buy"]: pa_buy_forward_ref,
api_objects["engine.util.exchange_mode.type.Sell"]: pa_sell_forward_ref
}
exchange_rate_raw_api_object.add_raw_member("price_adjust",
price_adjust,
exchange_rate_parent)
# Price pool
pool_forward_ref = ForwardRef(pregen_converter_group,
"util.resource.market_trading.MarketStonePricePool")
exchange_rate_raw_api_object.add_raw_member("price_pool",
pool_forward_ref,
exchange_rate_parent)
pregen_converter_group.add_raw_api_object(exchange_rate_raw_api_object)
pregen_nyan_objects.update({exchange_rate_ref_in_modpack: exchange_rate_raw_api_object})
# =======================================================================
# Buy Price mode
# =======================================================================
price_mode_parent = "engine.util.price_mode.type.Dynamic"
price_mode_location = "data/util/resource/"
price_mode_ref_in_modpack = "util.resource.market_trading.MarketBuyPriceMode"
price_mode_raw_api_object = RawAPIObject(price_mode_ref_in_modpack,
"MarketBuyPriceMode",
api_objects,
price_mode_location)
price_mode_raw_api_object.set_filename("market_trading")
price_mode_raw_api_object.add_raw_parent(price_mode_parent)
# Min price
price_mode_raw_api_object.add_raw_member("change_value",
0.03,
price_mode_parent)
# Min price
price_mode_raw_api_object.add_raw_member("min_price",
0.3,
price_mode_parent)
# Max price
price_mode_raw_api_object.add_raw_member("max_price",
99.9,
price_mode_parent)
pregen_converter_group.add_raw_api_object(price_mode_raw_api_object)
pregen_nyan_objects.update({price_mode_ref_in_modpack: price_mode_raw_api_object})
# =======================================================================
# Sell Price mode
# =======================================================================
price_mode_parent = "engine.util.price_mode.type.Dynamic"
price_mode_location = "data/util/resource/"
price_mode_ref_in_modpack = "util.resource.market_trading.MarketSellPriceMode"
price_mode_raw_api_object = RawAPIObject(price_mode_ref_in_modpack,
"MarketSellPriceMode",
api_objects,
price_mode_location)
price_mode_raw_api_object.set_filename("market_trading")
price_mode_raw_api_object.add_raw_parent(price_mode_parent)
# Min price
price_mode_raw_api_object.add_raw_member("change_value",
-0.03,
price_mode_parent)
# Min price
price_mode_raw_api_object.add_raw_member("min_price",
0.3,
price_mode_parent)
# Max price
price_mode_raw_api_object.add_raw_member("max_price",
99.9,
price_mode_parent)
pregen_converter_group.add_raw_api_object(price_mode_raw_api_object)
pregen_nyan_objects.update({price_mode_ref_in_modpack: price_mode_raw_api_object}) | [
"def",
"generate_exchange_objects",
"(",
"full_data_set",
",",
"pregen_converter_group",
")",
":",
"pregen_nyan_objects",
"=",
"full_data_set",
".",
"pregen_nyan_objects",
"api_objects",
"=",
"full_data_set",
".",
"nyan_api_objects",
"# ===========================================... | https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/convert/processor/conversion/aoc/pregen_processor.py#L544-L831 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/backend.py | python | _has_nchw_support | () | return not explicitly_on_cpu and gpus_available | Check whether the current scope supports NCHW ops.
TensorFlow does not support NCHW on CPU. Therefore we check if we are not
explicitly put on
CPU, and have GPUs available. In this case there will be soft-placing on the
GPU device.
Returns:
bool: if the current scope device placement would support nchw | Check whether the current scope supports NCHW ops. | [
"Check",
"whether",
"the",
"current",
"scope",
"supports",
"NCHW",
"ops",
"."
] | def _has_nchw_support():
"""Check whether the current scope supports NCHW ops.
TensorFlow does not support NCHW on CPU. Therefore we check if we are not
explicitly put on
CPU, and have GPUs available. In this case there will be soft-placing on the
GPU device.
Returns:
bool: if the current scope device placement would support nchw
"""
explicitly_on_cpu = _is_current_explicit_device('CPU')
gpus_available = bool(_get_available_gpus())
return not explicitly_on_cpu and gpus_available | [
"def",
"_has_nchw_support",
"(",
")",
":",
"explicitly_on_cpu",
"=",
"_is_current_explicit_device",
"(",
"'CPU'",
")",
"gpus_available",
"=",
"bool",
"(",
"_get_available_gpus",
"(",
")",
")",
"return",
"not",
"explicitly_on_cpu",
"and",
"gpus_available"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/backend.py#L635-L648 | |
Tencent/Pebble | 68315f176d9e328a233ace29b7579a829f89879f | tools/blade/src/blade/resource_library_target.py | python | resource_library | (name,
srcs=[],
deps=[],
optimize=[],
extra_cppflags=[],
**kwargs) | scons_resource_library. | scons_resource_library. | [
"scons_resource_library",
"."
] | def resource_library(name,
srcs=[],
deps=[],
optimize=[],
extra_cppflags=[],
**kwargs):
"""scons_resource_library. """
target = ResourceLibrary(name,
srcs,
deps,
optimize,
extra_cppflags,
blade.blade,
kwargs)
blade.blade.register_target(target) | [
"def",
"resource_library",
"(",
"name",
",",
"srcs",
"=",
"[",
"]",
",",
"deps",
"=",
"[",
"]",
",",
"optimize",
"=",
"[",
"]",
",",
"extra_cppflags",
"=",
"[",
"]",
",",
"*",
"*",
"kwargs",
")",
":",
"target",
"=",
"ResourceLibrary",
"(",
"name",
... | https://github.com/Tencent/Pebble/blob/68315f176d9e328a233ace29b7579a829f89879f/tools/blade/src/blade/resource_library_target.py#L140-L154 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_misc.py | python | GetFullHostName | (*args) | return _misc_.GetFullHostName(*args) | GetFullHostName() -> String | GetFullHostName() -> String | [
"GetFullHostName",
"()",
"-",
">",
"String"
] | def GetFullHostName(*args):
"""GetFullHostName() -> String"""
return _misc_.GetFullHostName(*args) | [
"def",
"GetFullHostName",
"(",
"*",
"args",
")",
":",
"return",
"_misc_",
".",
"GetFullHostName",
"(",
"*",
"args",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L393-L395 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/learn/python/learn/datasets/__init__.py | python | load_dataset | (name, size='small', test_with_fake_data=False) | Loads dataset by name.
Args:
name: Name of the dataset to load.
size: Size of the dataset to load.
test_with_fake_data: If true, load with fake dataset.
Returns:
Features and targets for given dataset. Can be numpy or iterator.
Raises:
ValueError: if `name` is not found. | Loads dataset by name. | [
"Loads",
"dataset",
"by",
"name",
"."
] | def load_dataset(name, size='small', test_with_fake_data=False):
"""Loads dataset by name.
Args:
name: Name of the dataset to load.
size: Size of the dataset to load.
test_with_fake_data: If true, load with fake dataset.
Returns:
Features and targets for given dataset. Can be numpy or iterator.
Raises:
ValueError: if `name` is not found.
"""
if name not in DATASETS:
raise ValueError('Name of dataset is not found: %s' % name)
if name == 'dbpedia':
return DATASETS[name](size, test_with_fake_data)
else:
return DATASETS[name]() | [
"def",
"load_dataset",
"(",
"name",
",",
"size",
"=",
"'small'",
",",
"test_with_fake_data",
"=",
"False",
")",
":",
"if",
"name",
"not",
"in",
"DATASETS",
":",
"raise",
"ValueError",
"(",
"'Name of dataset is not found: %s'",
"%",
"name",
")",
"if",
"name",
... | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/learn/python/learn/datasets/__init__.py#L47-L66 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/route53/__init__.py | python | regions | () | return regions | Get all available regions for the Route53 service.
:rtype: list
:return: A list of :class:`boto.regioninfo.RegionInfo` instances | Get all available regions for the Route53 service. | [
"Get",
"all",
"available",
"regions",
"for",
"the",
"Route53",
"service",
"."
] | def regions():
"""
Get all available regions for the Route53 service.
:rtype: list
:return: A list of :class:`boto.regioninfo.RegionInfo` instances
"""
regions = get_regions(
'route53',
region_cls=Route53RegionInfo,
connection_cls=Route53Connection
)
# For historical reasons, we had a "universal" endpoint as well.
regions.append(
Route53RegionInfo(
name='universal',
endpoint='route53.amazonaws.com',
connection_cls=Route53Connection
)
)
return regions | [
"def",
"regions",
"(",
")",
":",
"regions",
"=",
"get_regions",
"(",
"'route53'",
",",
"region_cls",
"=",
"Route53RegionInfo",
",",
"connection_cls",
"=",
"Route53Connection",
")",
"# For historical reasons, we had a \"universal\" endpoint as well.",
"regions",
".",
"appe... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/route53/__init__.py#L47-L69 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/framework/config.py | python | get_device_policy | () | Gets the current device policy.
The device policy controls how operations requiring inputs on a specific
device (e.g., on GPU:0) handle inputs on a different device (e.g. GPU:1).
This function only gets the device policy for the current thread. Any
subsequently started thread will again use the default policy.
Returns:
Current thread device policy | Gets the current device policy. | [
"Gets",
"the",
"current",
"device",
"policy",
"."
] | def get_device_policy():
"""Gets the current device policy.
The device policy controls how operations requiring inputs on a specific
device (e.g., on GPU:0) handle inputs on a different device (e.g. GPU:1).
This function only gets the device policy for the current thread. Any
subsequently started thread will again use the default policy.
Returns:
Current thread device policy
"""
device_policy = context.context().device_policy
if device_policy == context.DEVICE_PLACEMENT_SILENT:
return 'silent'
elif device_policy == context.DEVICE_PLACEMENT_SILENT_FOR_INT32:
return 'silent_for_int32'
elif device_policy == context.DEVICE_PLACEMENT_WARN:
return 'warn'
elif device_policy == context.DEVICE_PLACEMENT_EXPLICIT:
return 'explicit'
else:
# pylint: disable-next=no-value-for-parameter
raise errors.InternalError(
f'Got an invalid device policy: {device_policy!r}.') | [
"def",
"get_device_policy",
"(",
")",
":",
"device_policy",
"=",
"context",
".",
"context",
"(",
")",
".",
"device_policy",
"if",
"device_policy",
"==",
"context",
".",
"DEVICE_PLACEMENT_SILENT",
":",
"return",
"'silent'",
"elif",
"device_policy",
"==",
"context",... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/framework/config.py#L278-L302 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/email/_policybase.py | python | _PolicyBase.__add__ | (self, other) | return self.clone(**other.__dict__) | Non-default values from right operand override those from left.
The object returned is a new instance of the subclass. | Non-default values from right operand override those from left. | [
"Non",
"-",
"default",
"values",
"from",
"right",
"operand",
"override",
"those",
"from",
"left",
"."
] | def __add__(self, other):
"""Non-default values from right operand override those from left.
The object returned is a new instance of the subclass.
"""
return self.clone(**other.__dict__) | [
"def",
"__add__",
"(",
"self",
",",
"other",
")",
":",
"return",
"self",
".",
"clone",
"(",
"*",
"*",
"other",
".",
"__dict__",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/email/_policybase.py#L85-L91 | |
nyuwireless-unipd/ns3-mmwave | 4ff9e87e8079764e04cbeccd8e85bff15ae16fb3 | utils/grid.py | python | ScaleRenderer.get_height | (self) | return self.__height | ! Get Height
@param self: this object
@return height | ! Get Height | [
"!",
"Get",
"Height"
] | def get_height(self):
"""! Get Height
@param self: this object
@return height
"""
return self.__height | [
"def",
"get_height",
"(",
"self",
")",
":",
"return",
"self",
".",
"__height"
] | https://github.com/nyuwireless-unipd/ns3-mmwave/blob/4ff9e87e8079764e04cbeccd8e85bff15ae16fb3/utils/grid.py#L931-L936 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/s3transfer/futures.py | python | ExecutorFuture.add_done_callback | (self, fn) | Adds a callback to be completed once future is done
:parm fn: A callable that takes no arguments. Note that is different
than concurrent.futures.Future.add_done_callback that requires
a single argument for the future. | Adds a callback to be completed once future is done | [
"Adds",
"a",
"callback",
"to",
"be",
"completed",
"once",
"future",
"is",
"done"
] | def add_done_callback(self, fn):
"""Adds a callback to be completed once future is done
:parm fn: A callable that takes no arguments. Note that is different
than concurrent.futures.Future.add_done_callback that requires
a single argument for the future.
"""
# The done callback for concurrent.futures.Future will always pass a
# the future in as the only argument. So we need to create the
# proper signature wrapper that will invoke the callback provided.
def done_callback(future_passed_to_callback):
return fn()
self._future.add_done_callback(done_callback) | [
"def",
"add_done_callback",
"(",
"self",
",",
"fn",
")",
":",
"# The done callback for concurrent.futures.Future will always pass a",
"# the future in as the only argument. So we need to create the",
"# proper signature wrapper that will invoke the callback provided.",
"def",
"done_callback"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/s3transfer/futures.py#L494-L506 | ||
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | FWCore/Skeletons/python/utils.py | python | test_env | (tdir, tmpl) | Test user environment, look-up if user has run cmsenv, otherwise
provide meaningful error message back to the user. | Test user environment, look-up if user has run cmsenv, otherwise
provide meaningful error message back to the user. | [
"Test",
"user",
"environment",
"look",
"-",
"up",
"if",
"user",
"has",
"run",
"cmsenv",
"otherwise",
"provide",
"meaningful",
"error",
"message",
"back",
"to",
"the",
"user",
"."
] | def test_env(tdir, tmpl):
"""
Test user environment, look-up if user has run cmsenv, otherwise
provide meaningful error message back to the user.
"""
if not tdir or not os.path.isdir(tdir):
print("Unable to access template dir: %s" % tdir)
sys.exit(1)
if not os.listdir(tdir):
print("No template files found in template dir %s" % tdir)
sys.exit(0)
if not tmpl:
msg = "No template type is provided, "
msg += "see available templates via --templates option"
print(msg)
sys.exit(1) | [
"def",
"test_env",
"(",
"tdir",
",",
"tmpl",
")",
":",
"if",
"not",
"tdir",
"or",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"tdir",
")",
":",
"print",
"(",
"\"Unable to access template dir: %s\"",
"%",
"tdir",
")",
"sys",
".",
"exit",
"(",
"1",
")... | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/FWCore/Skeletons/python/utils.py#L53-L68 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/asyncio/protocols.py | python | Protocol.data_received | (self, data) | Called when some data is received.
The argument is a bytes object. | Called when some data is received. | [
"Called",
"when",
"some",
"data",
"is",
"received",
"."
] | def data_received(self, data):
"""Called when some data is received.
The argument is a bytes object.
""" | [
"def",
"data_received",
"(",
"self",
",",
"data",
")",
":"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/asyncio/protocols.py#L90-L94 | ||
wujian16/Cornell-MOE | df299d1be882d2af9796d7a68b3f9505cac7a53e | moe/optimal_learning/python/cpp_wrappers/knowledge_gradient.py | python | PosteriorMean.compute_grad_posterior_mean | (self, force_monte_carlo=False) | return cpp_utils.uncppify(grad_kg, (1, self.dim-self._num_fidelity)) | r"""Compute the gradient of knowledge gradient at ``points_to_sample`` wrt ``points_to_sample``, with ``points_being_sampled`` concurrent samples.
.. Note:: These comments were copied from
:meth:`moe.optimal_learning.python.interfaces.expected_improvement_interface.ExpectedImprovementInterface.compute_grad_expected_improvement`
``points_to_sample`` is the "q" and ``points_being_sampled`` is the "p" in q,p-EI.
In general, the expressions for gradients of EI are complex and difficult to evaluate; hence we use
Monte-Carlo simulation to approximate it. When faster (e.g., analytic) techniques are available, we will prefer them.
The MC computation of grad EI is similar to the computation of EI (decsribed in
compute_expected_improvement). We differentiate ``y = \mu + Lw`` wrt ``points_to_sample``;
only terms from the gradient of ``\mu`` and ``L`` contribute. In EI, we computed:
``improvement_per_step = max(max(best_so_far - y), 0.0)``
and noted that only the smallest component of ``y`` may contribute (if it is > 0.0).
Call this index ``winner``. Thus in computing grad EI, we only add gradient terms
that are attributable to the ``winner``-th component of ``y``.
:param force_monte_carlo: whether to force monte carlo evaluation (vs using fast/accurate analytic eval when possible)
:type force_monte_carlo: boolean
:return: gradient of EI, ``\pderiv{EI(Xq \cup Xp)}{Xq_{i,d}}`` where ``Xq`` is ``points_to_sample``
and ``Xp`` is ``points_being_sampled`` (grad EI from sampling ``points_to_sample`` with
``points_being_sampled`` concurrent experiments wrt each dimension of the points in ``points_to_sample``)
:rtype: array of float64 with shape (num_to_sample, dim) | r"""Compute the gradient of knowledge gradient at ``points_to_sample`` wrt ``points_to_sample``, with ``points_being_sampled`` concurrent samples. | [
"r",
"Compute",
"the",
"gradient",
"of",
"knowledge",
"gradient",
"at",
"points_to_sample",
"wrt",
"points_to_sample",
"with",
"points_being_sampled",
"concurrent",
"samples",
"."
] | def compute_grad_posterior_mean(self, force_monte_carlo=False):
r"""Compute the gradient of knowledge gradient at ``points_to_sample`` wrt ``points_to_sample``, with ``points_being_sampled`` concurrent samples.
.. Note:: These comments were copied from
:meth:`moe.optimal_learning.python.interfaces.expected_improvement_interface.ExpectedImprovementInterface.compute_grad_expected_improvement`
``points_to_sample`` is the "q" and ``points_being_sampled`` is the "p" in q,p-EI.
In general, the expressions for gradients of EI are complex and difficult to evaluate; hence we use
Monte-Carlo simulation to approximate it. When faster (e.g., analytic) techniques are available, we will prefer them.
The MC computation of grad EI is similar to the computation of EI (decsribed in
compute_expected_improvement). We differentiate ``y = \mu + Lw`` wrt ``points_to_sample``;
only terms from the gradient of ``\mu`` and ``L`` contribute. In EI, we computed:
``improvement_per_step = max(max(best_so_far - y), 0.0)``
and noted that only the smallest component of ``y`` may contribute (if it is > 0.0).
Call this index ``winner``. Thus in computing grad EI, we only add gradient terms
that are attributable to the ``winner``-th component of ``y``.
:param force_monte_carlo: whether to force monte carlo evaluation (vs using fast/accurate analytic eval when possible)
:type force_monte_carlo: boolean
:return: gradient of EI, ``\pderiv{EI(Xq \cup Xp)}{Xq_{i,d}}`` where ``Xq`` is ``points_to_sample``
and ``Xp`` is ``points_being_sampled`` (grad EI from sampling ``points_to_sample`` with
``points_being_sampled`` concurrent experiments wrt each dimension of the points in ``points_to_sample``)
:rtype: array of float64 with shape (num_to_sample, dim)
"""
grad_kg = C_GP.compute_grad_posterior_mean(
self._gaussian_process._gaussian_process,
self._num_fidelity,
cpp_utils.cppify(self._points_to_sample),
)
return cpp_utils.uncppify(grad_kg, (1, self.dim-self._num_fidelity)) | [
"def",
"compute_grad_posterior_mean",
"(",
"self",
",",
"force_monte_carlo",
"=",
"False",
")",
":",
"grad_kg",
"=",
"C_GP",
".",
"compute_grad_posterior_mean",
"(",
"self",
".",
"_gaussian_process",
".",
"_gaussian_process",
",",
"self",
".",
"_num_fidelity",
",",
... | https://github.com/wujian16/Cornell-MOE/blob/df299d1be882d2af9796d7a68b3f9505cac7a53e/moe/optimal_learning/python/cpp_wrappers/knowledge_gradient.py#L184-L216 | |
H-uru/Plasma | c2140ea046e82e9c199e257a7f2e7edb42602871 | Scripts/Python/plasma/Plasma.py | python | PtAvatarExitAFK | () | Tells the local avatar to exit AwayFromKeyboard idle loop (netpropagated) | Tells the local avatar to exit AwayFromKeyboard idle loop (netpropagated) | [
"Tells",
"the",
"local",
"avatar",
"to",
"exit",
"AwayFromKeyboard",
"idle",
"loop",
"(",
"netpropagated",
")"
] | def PtAvatarExitAFK():
"""Tells the local avatar to exit AwayFromKeyboard idle loop (netpropagated)"""
pass | [
"def",
"PtAvatarExitAFK",
"(",
")",
":",
"pass"
] | https://github.com/H-uru/Plasma/blob/c2140ea046e82e9c199e257a7f2e7edb42602871/Scripts/Python/plasma/Plasma.py#L85-L87 | ||
kevinlin311tw/caffe-cvprw15 | 45c2a1bf0368569c54e0be4edf8d34285cf79e70 | scripts/cpp_lint.py | python | UpdateIncludeState | (filename, include_state, io=codecs) | return True | Fill up the include_state with new includes found from the file.
Args:
filename: the name of the header to read.
include_state: an _IncludeState instance in which the headers are inserted.
io: The io factory to use to read the file. Provided for testability.
Returns:
True if a header was succesfully added. False otherwise. | Fill up the include_state with new includes found from the file. | [
"Fill",
"up",
"the",
"include_state",
"with",
"new",
"includes",
"found",
"from",
"the",
"file",
"."
] | def UpdateIncludeState(filename, include_state, io=codecs):
"""Fill up the include_state with new includes found from the file.
Args:
filename: the name of the header to read.
include_state: an _IncludeState instance in which the headers are inserted.
io: The io factory to use to read the file. Provided for testability.
Returns:
True if a header was succesfully added. False otherwise.
"""
headerfile = None
try:
headerfile = io.open(filename, 'r', 'utf8', 'replace')
except IOError:
return False
linenum = 0
for line in headerfile:
linenum += 1
clean_line = CleanseComments(line)
match = _RE_PATTERN_INCLUDE.search(clean_line)
if match:
include = match.group(2)
# The value formatting is cute, but not really used right now.
# What matters here is that the key is in include_state.
include_state.setdefault(include, '%s:%d' % (filename, linenum))
return True | [
"def",
"UpdateIncludeState",
"(",
"filename",
",",
"include_state",
",",
"io",
"=",
"codecs",
")",
":",
"headerfile",
"=",
"None",
"try",
":",
"headerfile",
"=",
"io",
".",
"open",
"(",
"filename",
",",
"'r'",
",",
"'utf8'",
",",
"'replace'",
")",
"excep... | https://github.com/kevinlin311tw/caffe-cvprw15/blob/45c2a1bf0368569c54e0be4edf8d34285cf79e70/scripts/cpp_lint.py#L4454-L4480 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/distutils/command/install_lib.py | python | install_lib.get_outputs | (self) | return pure_outputs + bytecode_outputs + ext_outputs | Return the list of files that would be installed if this command
were actually run. Not affected by the "dry-run" flag or whether
modules have actually been built yet. | Return the list of files that would be installed if this command
were actually run. Not affected by the "dry-run" flag or whether
modules have actually been built yet. | [
"Return",
"the",
"list",
"of",
"files",
"that",
"would",
"be",
"installed",
"if",
"this",
"command",
"were",
"actually",
"run",
".",
"Not",
"affected",
"by",
"the",
"dry",
"-",
"run",
"flag",
"or",
"whether",
"modules",
"have",
"actually",
"been",
"built",... | def get_outputs(self):
"""Return the list of files that would be installed if this command
were actually run. Not affected by the "dry-run" flag or whether
modules have actually been built yet.
"""
pure_outputs = \
self._mutate_outputs(self.distribution.has_pure_modules(),
'build_py', 'build_lib',
self.install_dir)
if self.compile:
bytecode_outputs = self._bytecode_filenames(pure_outputs)
else:
bytecode_outputs = []
ext_outputs = \
self._mutate_outputs(self.distribution.has_ext_modules(),
'build_ext', 'build_lib',
self.install_dir)
return pure_outputs + bytecode_outputs + ext_outputs | [
"def",
"get_outputs",
"(",
"self",
")",
":",
"pure_outputs",
"=",
"self",
".",
"_mutate_outputs",
"(",
"self",
".",
"distribution",
".",
"has_pure_modules",
"(",
")",
",",
"'build_py'",
",",
"'build_lib'",
",",
"self",
".",
"install_dir",
")",
"if",
"self",
... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/distutils/command/install_lib.py#L182-L201 | |
dmlc/xgboost | 2775c2a1abd4b5b759ff517617434c8b9aeb4cc0 | python-package/xgboost/rabit.py | python | _init_rabit | () | internal library initializer. | internal library initializer. | [
"internal",
"library",
"initializer",
"."
] | def _init_rabit() -> None:
"""internal library initializer."""
if _LIB is not None:
_LIB.RabitGetRank.restype = ctypes.c_int
_LIB.RabitGetWorldSize.restype = ctypes.c_int
_LIB.RabitIsDistributed.restype = ctypes.c_int
_LIB.RabitVersionNumber.restype = ctypes.c_int | [
"def",
"_init_rabit",
"(",
")",
"->",
"None",
":",
"if",
"_LIB",
"is",
"not",
"None",
":",
"_LIB",
".",
"RabitGetRank",
".",
"restype",
"=",
"ctypes",
".",
"c_int",
"_LIB",
".",
"RabitGetWorldSize",
".",
"restype",
"=",
"ctypes",
".",
"c_int",
"_LIB",
... | https://github.com/dmlc/xgboost/blob/2775c2a1abd4b5b759ff517617434c8b9aeb4cc0/python-package/xgboost/rabit.py#L13-L19 | ||
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_internal/utils/misc.py | python | protect_pip_from_modification_on_windows | (modifying_pip) | Protection of pip.exe from modification on Windows
On Windows, any operation modifying pip should be run as:
python -m pip ... | Protection of pip.exe from modification on Windows | [
"Protection",
"of",
"pip",
".",
"exe",
"from",
"modification",
"on",
"Windows"
] | def protect_pip_from_modification_on_windows(modifying_pip):
"""Protection of pip.exe from modification on Windows
On Windows, any operation modifying pip should be run as:
python -m pip ...
"""
pip_names = [
"pip.exe",
"pip{}.exe".format(sys.version_info[0]),
"pip{}.{}.exe".format(*sys.version_info[:2])
]
# See https://github.com/pypa/pip/issues/1299 for more discussion
should_show_use_python_msg = (
modifying_pip and
WINDOWS and
os.path.basename(sys.argv[0]) in pip_names
)
if should_show_use_python_msg:
new_command = [
sys.executable, "-m", "pip"
] + sys.argv[1:]
raise CommandError(
'To modify pip, please run the following command:\n{}'
.format(" ".join(new_command))
) | [
"def",
"protect_pip_from_modification_on_windows",
"(",
"modifying_pip",
")",
":",
"pip_names",
"=",
"[",
"\"pip.exe\"",
",",
"\"pip{}.exe\"",
".",
"format",
"(",
"sys",
".",
"version_info",
"[",
"0",
"]",
")",
",",
"\"pip{}.{}.exe\"",
".",
"format",
"(",
"*",
... | https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_internal/utils/misc.py#L1014-L1040 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/flatnotebook.py | python | LightColour | (color, percent) | return wx.Colour(r, g, b) | Brighten input colour by percent. | Brighten input colour by percent. | [
"Brighten",
"input",
"colour",
"by",
"percent",
"."
] | def LightColour(color, percent):
""" Brighten input colour by percent. """
end_color = wx.WHITE
rd = end_color.Red() - color.Red()
gd = end_color.Green() - color.Green()
bd = end_color.Blue() - color.Blue()
high = 100
# We take the percent way of the color from color -. white
i = percent
r = color.Red() + ((i*rd*100)/high)/100
g = color.Green() + ((i*gd*100)/high)/100
b = color.Blue() + ((i*bd*100)/high)/100
return wx.Colour(r, g, b) | [
"def",
"LightColour",
"(",
"color",
",",
"percent",
")",
":",
"end_color",
"=",
"wx",
".",
"WHITE",
"rd",
"=",
"end_color",
".",
"Red",
"(",
")",
"-",
"color",
".",
"Red",
"(",
")",
"gd",
"=",
"end_color",
".",
"Green",
"(",
")",
"-",
"color",
".... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/flatnotebook.py#L660-L676 | |
s5z/zsim | fb4d6e0475a25cffd23f0687ede2d43d96b4a99f | misc/cpplint.py | python | CheckIncludeLine | (filename, clean_lines, linenum, include_state, error) | Check rules that are applicable to #include lines.
Strings on #include lines are NOT removed from elided line, to make
certain tasks easier. However, to prevent false positives, checks
applicable to #include lines in CheckLanguage must be put here.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
include_state: An _IncludeState instance in which the headers are inserted.
error: The function to call with any errors found. | Check rules that are applicable to #include lines. | [
"Check",
"rules",
"that",
"are",
"applicable",
"to",
"#include",
"lines",
"."
] | def CheckIncludeLine(filename, clean_lines, linenum, include_state, error):
"""Check rules that are applicable to #include lines.
Strings on #include lines are NOT removed from elided line, to make
certain tasks easier. However, to prevent false positives, checks
applicable to #include lines in CheckLanguage must be put here.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
include_state: An _IncludeState instance in which the headers are inserted.
error: The function to call with any errors found.
"""
fileinfo = FileInfo(filename)
line = clean_lines.lines[linenum]
# dsm: Disable, I don't care
# "include" should use the new style "foo/bar.h" instead of just "bar.h"
#if _RE_PATTERN_INCLUDE_NEW_STYLE.search(line):
# error(filename, linenum, 'build/include', 4,
# 'Include the directory when naming .h files')
# we shouldn't include a file more than once. actually, there are a
# handful of instances where doing so is okay, but in general it's
# not.
match = _RE_PATTERN_INCLUDE.search(line)
if match:
include = match.group(2)
is_system = (match.group(1) == '<')
if include in include_state:
error(filename, linenum, 'build/include', 4,
'"%s" already included at %s:%s' %
(include, filename, include_state[include]))
else:
include_state[include] = linenum
# We want to ensure that headers appear in the right order:
# 1) for foo.cc, foo.h (preferred location)
# 2) c system files
# 3) cpp system files
# 4) for foo.cc, foo.h (deprecated location)
# 5) other google headers
#
# We classify each include statement as one of those 5 types
# using a number of techniques. The include_state object keeps
# track of the highest type seen, and complains if we see a
# lower type after that.
error_message = include_state.CheckNextIncludeOrder(
_ClassifyInclude(fileinfo, include, is_system))
if error_message:
error(filename, linenum, 'build/include_order', 4,
'%s. Should be: %s.h, c system, c++ system, other.' %
(error_message, fileinfo.BaseName()))
if not include_state.IsInAlphabeticalOrder(include):
error(filename, linenum, 'build/include_alpha', 4,
'Include "%s" not in alphabetical order' % include)
# Look for any of the stream classes that are part of standard C++.
match = _RE_PATTERN_INCLUDE.match(line)
if match:
include = match.group(2)
if Match(r'(f|ind|io|i|o|parse|pf|stdio|str|)?stream$', include):
# Many unit tests use cout, so we exempt them.
if not _IsTestFilename(filename):
error(filename, linenum, 'readability/streams', 3,
'Streams are highly discouraged.') | [
"def",
"CheckIncludeLine",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"include_state",
",",
"error",
")",
":",
"fileinfo",
"=",
"FileInfo",
"(",
"filename",
")",
"line",
"=",
"clean_lines",
".",
"lines",
"[",
"linenum",
"]",
"# dsm: Disable, I d... | https://github.com/s5z/zsim/blob/fb4d6e0475a25cffd23f0687ede2d43d96b4a99f/misc/cpplint.py#L3016-L3083 | ||
hfinkel/llvm-project-cxxjit | 91084ef018240bbb8e24235ff5cd8c355a9c1a1e | clang/bindings/python/clang/cindex.py | python | Type.get_size | (self) | return conf.lib.clang_Type_getSizeOf(self) | Retrieve the size of the record. | Retrieve the size of the record. | [
"Retrieve",
"the",
"size",
"of",
"the",
"record",
"."
] | def get_size(self):
"""
Retrieve the size of the record.
"""
return conf.lib.clang_Type_getSizeOf(self) | [
"def",
"get_size",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_Type_getSizeOf",
"(",
"self",
")"
] | https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/clang/bindings/python/clang/cindex.py#L2378-L2382 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/setuptools/package_index.py | python | distros_for_filename | (filename, metadata=None) | return distros_for_location(
normalize_path(filename), os.path.basename(filename), metadata
) | Yield possible egg or source distribution objects based on a filename | Yield possible egg or source distribution objects based on a filename | [
"Yield",
"possible",
"egg",
"or",
"source",
"distribution",
"objects",
"based",
"on",
"a",
"filename"
] | def distros_for_filename(filename, metadata=None):
"""Yield possible egg or source distribution objects based on a filename"""
return distros_for_location(
normalize_path(filename), os.path.basename(filename), metadata
) | [
"def",
"distros_for_filename",
"(",
"filename",
",",
"metadata",
"=",
"None",
")",
":",
"return",
"distros_for_location",
"(",
"normalize_path",
"(",
"filename",
")",
",",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
",",
"metadata",
")"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/setuptools/package_index.py#L143-L147 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/src/robotsim.py | python | RigidObjectModel.getContactParameters | (self) | return _robotsim.RigidObjectModel_getContactParameters(self) | r"""
getContactParameters(RigidObjectModel self) -> ContactParameters
Returns a copy of the ContactParameters of this rigid object.
.. note::
To change the contact parameters, you should call
``p=object.getContactParameters()``, change the desired properties in
p, and then call ``object.setContactParameters(p)`` | r"""
getContactParameters(RigidObjectModel self) -> ContactParameters | [
"r",
"getContactParameters",
"(",
"RigidObjectModel",
"self",
")",
"-",
">",
"ContactParameters"
] | def getContactParameters(self) -> "ContactParameters":
r"""
getContactParameters(RigidObjectModel self) -> ContactParameters
Returns a copy of the ContactParameters of this rigid object.
.. note::
To change the contact parameters, you should call
``p=object.getContactParameters()``, change the desired properties in
p, and then call ``object.setContactParameters(p)``
"""
return _robotsim.RigidObjectModel_getContactParameters(self) | [
"def",
"getContactParameters",
"(",
"self",
")",
"->",
"\"ContactParameters\"",
":",
"return",
"_robotsim",
".",
"RigidObjectModel_getContactParameters",
"(",
"self",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/robotsim.py#L5650-L5664 | |
rapidsai/cudf | d5b2448fc69f17509304d594f029d0df56984962 | python/cudf/cudf/core/dataframe.py | python | DataFrame.nunique | (self, axis=0, dropna=True) | return cudf.Series(super().nunique(method="sort", dropna=dropna)) | Count number of distinct elements in specified axis.
Return Series with number of distinct elements. Can ignore NaN values.
Parameters
----------
axis : {0 or 'index', 1 or 'columns'}, default 0
The axis to use. 0 or 'index' for row-wise, 1 or 'columns' for
column-wise.
dropna : bool, default True
Don't include NaN in the counts.
Returns
-------
Series
Examples
--------
>>> import cudf
>>> df = cudf.DataFrame({'A': [4, 5, 6], 'B': [4, 1, 1]})
>>> df.nunique()
A 3
B 2
dtype: int64 | Count number of distinct elements in specified axis.
Return Series with number of distinct elements. Can ignore NaN values. | [
"Count",
"number",
"of",
"distinct",
"elements",
"in",
"specified",
"axis",
".",
"Return",
"Series",
"with",
"number",
"of",
"distinct",
"elements",
".",
"Can",
"ignore",
"NaN",
"values",
"."
] | def nunique(self, axis=0, dropna=True):
"""
Count number of distinct elements in specified axis.
Return Series with number of distinct elements. Can ignore NaN values.
Parameters
----------
axis : {0 or 'index', 1 or 'columns'}, default 0
The axis to use. 0 or 'index' for row-wise, 1 or 'columns' for
column-wise.
dropna : bool, default True
Don't include NaN in the counts.
Returns
-------
Series
Examples
--------
>>> import cudf
>>> df = cudf.DataFrame({'A': [4, 5, 6], 'B': [4, 1, 1]})
>>> df.nunique()
A 3
B 2
dtype: int64
"""
if axis != 0:
raise NotImplementedError("axis parameter is not supported yet.")
return cudf.Series(super().nunique(method="sort", dropna=dropna)) | [
"def",
"nunique",
"(",
"self",
",",
"axis",
"=",
"0",
",",
"dropna",
"=",
"True",
")",
":",
"if",
"axis",
"!=",
"0",
":",
"raise",
"NotImplementedError",
"(",
"\"axis parameter is not supported yet.\"",
")",
"return",
"cudf",
".",
"Series",
"(",
"super",
"... | https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/dataframe.py#L6053-L6082 | |
interpretml/interpret | 29466bffc04505fe4f836a83fcfebfd313ac8454 | python/interpret-core/interpret/glassbox/ebm/postprocessing.py | python | multiclass_postprocess2 | (
n_classes, n_samples, additive_terms, intercept, bin_counts
) | Postprocesses multiclass model graphs with desired properties. | Postprocesses multiclass model graphs with desired properties. | [
"Postprocesses",
"multiclass",
"model",
"graphs",
"with",
"desired",
"properties",
"."
] | def multiclass_postprocess2(
n_classes, n_samples, additive_terms, intercept, bin_counts
):
""" Postprocesses multiclass model graphs with desired properties.
"""
# our existing implementation has a bug where it always uses the simpler method of taking
# the mean of the class scores. Copy this behavior for now since it's a lot simpler when
# moving to the generator unify_columns function. Also, this method generalizes to tensors
# TODO: we can probably do all the classes together, and that would make it generalize to interactions as well
for i in range(len(additive_terms)):
for k in range(n_classes):
mean = np.sum(np.multiply(additive_terms[i][:, k], bin_counts[i])) / n_samples
additive_terms[i][:, k] = np.subtract(additive_terms[i][:, k], mean)
intercept[k] += mean | [
"def",
"multiclass_postprocess2",
"(",
"n_classes",
",",
"n_samples",
",",
"additive_terms",
",",
"intercept",
",",
"bin_counts",
")",
":",
"# our existing implementation has a bug where it always uses the simpler method of taking ",
"# the mean of the class scores. Copy this behavior... | https://github.com/interpretml/interpret/blob/29466bffc04505fe4f836a83fcfebfd313ac8454/python/interpret-core/interpret/glassbox/ebm/postprocessing.py#L77-L93 | ||
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | RewrapResponse.fromTpm | (buf) | return buf.createObj(RewrapResponse) | Returns new RewrapResponse object constructed from its marshaled
representation in the given TpmBuffer buffer | Returns new RewrapResponse object constructed from its marshaled
representation in the given TpmBuffer buffer | [
"Returns",
"new",
"RewrapResponse",
"object",
"constructed",
"from",
"its",
"marshaled",
"representation",
"in",
"the",
"given",
"TpmBuffer",
"buffer"
] | def fromTpm(buf):
""" Returns new RewrapResponse object constructed from its marshaled
representation in the given TpmBuffer buffer
"""
return buf.createObj(RewrapResponse) | [
"def",
"fromTpm",
"(",
"buf",
")",
":",
"return",
"buf",
".",
"createObj",
"(",
"RewrapResponse",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L10473-L10477 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/operations/_grad_ops.py | python | SliceGrad.__init__ | (self) | Initialize SliceGrad | Initialize SliceGrad | [
"Initialize",
"SliceGrad"
] | def __init__(self):
"""Initialize SliceGrad"""
self.init_prim_io_names(inputs=['dy', 'x', 'begin', 'size'], outputs=['dx']) | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"init_prim_io_names",
"(",
"inputs",
"=",
"[",
"'dy'",
",",
"'x'",
",",
"'begin'",
",",
"'size'",
"]",
",",
"outputs",
"=",
"[",
"'dx'",
"]",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/operations/_grad_ops.py#L1851-L1853 | ||
larroy/clearskies_core | 3574ddf0edc8555454c7044126e786a6c29444dc | tools/gyp/pylib/gyp/MSVSSettings.py | python | _Type.ValidateMSVS | (self, value) | Verifies that the value is legal for MSVS.
Args:
value: the value to check for this type.
Raises:
ValueError if value is not valid for MSVS. | Verifies that the value is legal for MSVS. | [
"Verifies",
"that",
"the",
"value",
"is",
"legal",
"for",
"MSVS",
"."
] | def ValidateMSVS(self, value):
"""Verifies that the value is legal for MSVS.
Args:
value: the value to check for this type.
Raises:
ValueError if value is not valid for MSVS.
""" | [
"def",
"ValidateMSVS",
"(",
"self",
",",
"value",
")",
":"
] | https://github.com/larroy/clearskies_core/blob/3574ddf0edc8555454c7044126e786a6c29444dc/tools/gyp/pylib/gyp/MSVSSettings.py#L70-L78 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py2/numpy/ma/core.py | python | MaskedArray.tobytes | (self, fill_value=None, order='C') | return self.filled(fill_value).tobytes(order=order) | Return the array data as a string containing the raw bytes in the array.
The array is filled with a fill value before the string conversion.
.. versionadded:: 1.9.0
Parameters
----------
fill_value : scalar, optional
Value used to fill in the masked values. Default is None, in which
case `MaskedArray.fill_value` is used.
order : {'C','F','A'}, optional
Order of the data item in the copy. Default is 'C'.
- 'C' -- C order (row major).
- 'F' -- Fortran order (column major).
- 'A' -- Any, current order of array.
- None -- Same as 'A'.
See Also
--------
ndarray.tobytes
tolist, tofile
Notes
-----
As for `ndarray.tobytes`, information about the shape, dtype, etc.,
but also about `fill_value`, will be lost.
Examples
--------
>>> x = np.ma.array(np.array([[1, 2], [3, 4]]), mask=[[0, 1], [1, 0]])
>>> x.tobytes()
'\\x01\\x00\\x00\\x00?B\\x0f\\x00?B\\x0f\\x00\\x04\\x00\\x00\\x00' | Return the array data as a string containing the raw bytes in the array. | [
"Return",
"the",
"array",
"data",
"as",
"a",
"string",
"containing",
"the",
"raw",
"bytes",
"in",
"the",
"array",
"."
] | def tobytes(self, fill_value=None, order='C'):
"""
Return the array data as a string containing the raw bytes in the array.
The array is filled with a fill value before the string conversion.
.. versionadded:: 1.9.0
Parameters
----------
fill_value : scalar, optional
Value used to fill in the masked values. Default is None, in which
case `MaskedArray.fill_value` is used.
order : {'C','F','A'}, optional
Order of the data item in the copy. Default is 'C'.
- 'C' -- C order (row major).
- 'F' -- Fortran order (column major).
- 'A' -- Any, current order of array.
- None -- Same as 'A'.
See Also
--------
ndarray.tobytes
tolist, tofile
Notes
-----
As for `ndarray.tobytes`, information about the shape, dtype, etc.,
but also about `fill_value`, will be lost.
Examples
--------
>>> x = np.ma.array(np.array([[1, 2], [3, 4]]), mask=[[0, 1], [1, 0]])
>>> x.tobytes()
'\\x01\\x00\\x00\\x00?B\\x0f\\x00?B\\x0f\\x00\\x04\\x00\\x00\\x00'
"""
return self.filled(fill_value).tobytes(order=order) | [
"def",
"tobytes",
"(",
"self",
",",
"fill_value",
"=",
"None",
",",
"order",
"=",
"'C'",
")",
":",
"return",
"self",
".",
"filled",
"(",
"fill_value",
")",
".",
"tobytes",
"(",
"order",
"=",
"order",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/ma/core.py#L5894-L5932 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pip/_vendor/requests/packages/urllib3/connectionpool.py | python | HTTPConnectionPool._new_conn | (self) | return conn | Return a fresh :class:`HTTPConnection`. | Return a fresh :class:`HTTPConnection`. | [
"Return",
"a",
"fresh",
":",
"class",
":",
"HTTPConnection",
"."
] | def _new_conn(self):
"""
Return a fresh :class:`HTTPConnection`.
"""
self.num_connections += 1
log.info("Starting new HTTP connection (%d): %s" %
(self.num_connections, self.host))
conn = self.ConnectionCls(host=self.host, port=self.port,
timeout=self.timeout.connect_timeout,
strict=self.strict, **self.conn_kw)
return conn | [
"def",
"_new_conn",
"(",
"self",
")",
":",
"self",
".",
"num_connections",
"+=",
"1",
"log",
".",
"info",
"(",
"\"Starting new HTTP connection (%d): %s\"",
"%",
"(",
"self",
".",
"num_connections",
",",
"self",
".",
"host",
")",
")",
"conn",
"=",
"self",
"... | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/requests/packages/urllib3/connectionpool.py#L197-L208 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/fileinput.py | python | lineno | () | return _state.lineno() | Return the cumulative line number of the line that has just been read.
Before the first line has been read, returns 0. After the last line
of the last file has been read, returns the line number of that line. | Return the cumulative line number of the line that has just been read.
Before the first line has been read, returns 0. After the last line
of the last file has been read, returns the line number of that line. | [
"Return",
"the",
"cumulative",
"line",
"number",
"of",
"the",
"line",
"that",
"has",
"just",
"been",
"read",
".",
"Before",
"the",
"first",
"line",
"has",
"been",
"read",
"returns",
"0",
".",
"After",
"the",
"last",
"line",
"of",
"the",
"last",
"file",
... | def lineno():
"""
Return the cumulative line number of the line that has just been read.
Before the first line has been read, returns 0. After the last line
of the last file has been read, returns the line number of that line.
"""
if not _state:
raise RuntimeError("no active input()")
return _state.lineno() | [
"def",
"lineno",
"(",
")",
":",
"if",
"not",
"_state",
":",
"raise",
"RuntimeError",
"(",
"\"no active input()\"",
")",
"return",
"_state",
".",
"lineno",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/fileinput.py#L128-L136 | |
gem5/gem5 | 141cc37c2d4b93959d4c249b8f7e6a8b2ef75338 | ext/ply/example/GardenSnake/GardenSnake.py | python | p_stmt_compound | (p) | stmt : compound_stmt | stmt : compound_stmt | [
"stmt",
":",
"compound_stmt"
] | def p_stmt_compound(p):
"""stmt : compound_stmt"""
p[0] = [p[1]] | [
"def",
"p_stmt_compound",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"[",
"p",
"[",
"1",
"]",
"]"
] | https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/ext/ply/example/GardenSnake/GardenSnake.py#L413-L415 | ||
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | v8_5_1/tools/release/auto_tag.py | python | CalculateTagRevision.LastLKGR | (self, min_rev, max_rev) | return None | Finds the newest lkgr between min_rev (inclusive) and max_rev
(exclusive). | Finds the newest lkgr between min_rev (inclusive) and max_rev
(exclusive). | [
"Finds",
"the",
"newest",
"lkgr",
"between",
"min_rev",
"(",
"inclusive",
")",
"and",
"max_rev",
"(",
"exclusive",
")",
"."
] | def LastLKGR(self, min_rev, max_rev):
"""Finds the newest lkgr between min_rev (inclusive) and max_rev
(exclusive).
"""
for lkgr in self["lkgrs"]:
# LKGRs are reverse sorted.
if int(min_rev) <= int(lkgr) and int(lkgr) < int(max_rev):
return lkgr
return None | [
"def",
"LastLKGR",
"(",
"self",
",",
"min_rev",
",",
"max_rev",
")",
":",
"for",
"lkgr",
"in",
"self",
"[",
"\"lkgrs\"",
"]",
":",
"# LKGRs are reverse sorted.",
"if",
"int",
"(",
"min_rev",
")",
"<=",
"int",
"(",
"lkgr",
")",
"and",
"int",
"(",
"lkgr"... | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/v8_5_1/tools/release/auto_tag.py#L104-L112 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/distutils/misc_util.py | python | gpaths | (paths, local_path='', include_non_existing=True) | return _fix_paths(paths, local_path, include_non_existing) | Apply glob to paths and prepend local_path if needed. | Apply glob to paths and prepend local_path if needed. | [
"Apply",
"glob",
"to",
"paths",
"and",
"prepend",
"local_path",
"if",
"needed",
"."
] | def gpaths(paths, local_path='', include_non_existing=True):
"""Apply glob to paths and prepend local_path if needed.
"""
if is_string(paths):
paths = (paths,)
return _fix_paths(paths, local_path, include_non_existing) | [
"def",
"gpaths",
"(",
"paths",
",",
"local_path",
"=",
"''",
",",
"include_non_existing",
"=",
"True",
")",
":",
"if",
"is_string",
"(",
"paths",
")",
":",
"paths",
"=",
"(",
"paths",
",",
")",
"return",
"_fix_paths",
"(",
"paths",
",",
"local_path",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/distutils/misc_util.py#L303-L308 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/metrics/histograms/update_histogram_enum.py | python | UpdateHistogramDefinitions | (histogram_enum_name, source_enum_values,
source_enum_path, document) | Updates the enum node named |histogram_enum_name| based on the definition
stored in |source_enum_values|. Existing items for which |source_enum_values|
doesn't contain any corresponding data will be preserved. |source_enum_path|
will be used to insert a comment. | Updates the enum node named |histogram_enum_name| based on the definition
stored in |source_enum_values|. Existing items for which |source_enum_values|
doesn't contain any corresponding data will be preserved. |source_enum_path|
will be used to insert a comment. | [
"Updates",
"the",
"enum",
"node",
"named",
"|histogram_enum_name|",
"based",
"on",
"the",
"definition",
"stored",
"in",
"|source_enum_values|",
".",
"Existing",
"items",
"for",
"which",
"|source_enum_values|",
"doesn",
"t",
"contain",
"any",
"corresponding",
"data",
... | def UpdateHistogramDefinitions(histogram_enum_name, source_enum_values,
source_enum_path, document):
"""Updates the enum node named |histogram_enum_name| based on the definition
stored in |source_enum_values|. Existing items for which |source_enum_values|
doesn't contain any corresponding data will be preserved. |source_enum_path|
will be used to insert a comment.
"""
# Get a dom of <enum name=|histogram_enum_name| ...> node in |document|.
for enum_node in document.getElementsByTagName('enum'):
if enum_node.attributes['name'].value == histogram_enum_name:
break
else:
raise UserError('No {0} enum node found'.format(histogram_enum_name))
new_item_nodes = {}
new_comments = []
# Add a "Generated from (...)" comment.
new_comments.append(
document.createComment(' Generated from {0} '.format(source_enum_path)))
# Create item nodes for each of the enum values.
for value, label in source_enum_values.iteritems():
new_item_nodes[value] = CreateEnumItemNode(document, value, label)
# Scan existing nodes in |enum_node| for old values and preserve them.
# - Preserve comments other than the 'Generated from' comment. NOTE:
# this does not preserve the order of the comments in relation to the
# old values.
# - Drop anything else.
SOURCE_COMMENT_REGEX = re.compile('^ Generated from ')
for child in enum_node.childNodes:
if child.nodeName == 'int':
value = int(child.attributes['value'].value)
if not source_enum_values.has_key(value):
new_item_nodes[value] = child
# Preserve existing non-generated comments.
elif (child.nodeType == minidom.Node.COMMENT_NODE and
SOURCE_COMMENT_REGEX.match(child.data) is None):
new_comments.append(child)
# Update |enum_node|. First, remove everything existing.
while enum_node.hasChildNodes():
enum_node.removeChild(enum_node.lastChild)
# Add comments at the top.
for comment in new_comments:
enum_node.appendChild(comment)
# Add in the new enums.
for value in sorted(new_item_nodes.iterkeys()):
enum_node.appendChild(new_item_nodes[value]) | [
"def",
"UpdateHistogramDefinitions",
"(",
"histogram_enum_name",
",",
"source_enum_values",
",",
"source_enum_path",
",",
"document",
")",
":",
"# Get a dom of <enum name=|histogram_enum_name| ...> node in |document|.",
"for",
"enum_node",
"in",
"document",
".",
"getElementsByTag... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/metrics/histograms/update_histogram_enum.py#L95-L146 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/fastparquet/schema.py | python | SchemaHelper.schema_element | (self, name) | return root | Get the schema element with the given name or path | Get the schema element with the given name or path | [
"Get",
"the",
"schema",
"element",
"with",
"the",
"given",
"name",
"or",
"path"
] | def schema_element(self, name):
"""Get the schema element with the given name or path"""
root = self.root
if isinstance(name, text_type):
name = name.split('.')
for part in name:
root = root.children[part]
return root | [
"def",
"schema_element",
"(",
"self",
",",
"name",
")",
":",
"root",
"=",
"self",
".",
"root",
"if",
"isinstance",
"(",
"name",
",",
"text_type",
")",
":",
"name",
"=",
"name",
".",
"split",
"(",
"'.'",
")",
"for",
"part",
"in",
"name",
":",
"root"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/fastparquet/schema.py#L97-L104 | |
generalized-intelligence/GAAS | 29ab17d3e8a4ba18edef3a57c36d8db6329fac73 | algorithms/src/SystemManagement/json_request_response_lib/src/third_party/nlohmann_json/third_party/cpplint/cpplint.py | python | CheckForCopyright | (filename, lines, error) | Logs an error if no Copyright message appears at the top of the file. | Logs an error if no Copyright message appears at the top of the file. | [
"Logs",
"an",
"error",
"if",
"no",
"Copyright",
"message",
"appears",
"at",
"the",
"top",
"of",
"the",
"file",
"."
] | def CheckForCopyright(filename, lines, error):
"""Logs an error if no Copyright message appears at the top of the file."""
# We'll say it should occur by line 10. Don't forget there's a
# dummy line at the front.
for line in xrange(1, min(len(lines), 11)):
if re.search(r'Copyright', lines[line], re.I): break
else: # means no copyright line was found
error(filename, 0, 'legal/copyright', 5,
'No copyright message found. '
'You should have a line: "Copyright [year] <Copyright Owner>"') | [
"def",
"CheckForCopyright",
"(",
"filename",
",",
"lines",
",",
"error",
")",
":",
"# We'll say it should occur by line 10. Don't forget there's a",
"# dummy line at the front.",
"for",
"line",
"in",
"xrange",
"(",
"1",
",",
"min",
"(",
"len",
"(",
"lines",
")",
","... | https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/algorithms/src/SystemManagement/json_request_response_lib/src/third_party/nlohmann_json/third_party/cpplint/cpplint.py#L1972-L1982 | ||
kevinlin311tw/cvpr16-deepbit | c60fb3233d7d534cfcee9d3ed47d77af437ee32a | scripts/cpp_lint.py | python | FileInfo.Split | (self) | return (project,) + os.path.splitext(rest) | Splits the file into the directory, basename, and extension.
For 'chrome/browser/browser.cc', Split() would
return ('chrome/browser', 'browser', '.cc')
Returns:
A tuple of (directory, basename, extension). | Splits the file into the directory, basename, and extension. | [
"Splits",
"the",
"file",
"into",
"the",
"directory",
"basename",
"and",
"extension",
"."
] | def Split(self):
"""Splits the file into the directory, basename, and extension.
For 'chrome/browser/browser.cc', Split() would
return ('chrome/browser', 'browser', '.cc')
Returns:
A tuple of (directory, basename, extension).
"""
googlename = self.RepositoryName()
project, rest = os.path.split(googlename)
return (project,) + os.path.splitext(rest) | [
"def",
"Split",
"(",
"self",
")",
":",
"googlename",
"=",
"self",
".",
"RepositoryName",
"(",
")",
"project",
",",
"rest",
"=",
"os",
".",
"path",
".",
"split",
"(",
"googlename",
")",
"return",
"(",
"project",
",",
")",
"+",
"os",
".",
"path",
"."... | https://github.com/kevinlin311tw/cvpr16-deepbit/blob/c60fb3233d7d534cfcee9d3ed47d77af437ee32a/scripts/cpp_lint.py#L930-L942 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/eclib/ctrlbox.py | python | ControlBar.AddStretchSpacer | (self) | Add an expanding spacer to the bar that will stretch and
contract when the window changes size. | Add an expanding spacer to the bar that will stretch and
contract when the window changes size. | [
"Add",
"an",
"expanding",
"spacer",
"to",
"the",
"bar",
"that",
"will",
"stretch",
"and",
"contract",
"when",
"the",
"window",
"changes",
"size",
"."
] | def AddStretchSpacer(self):
"""Add an expanding spacer to the bar that will stretch and
contract when the window changes size.
"""
self._sizer.AddStretchSpacer(2) | [
"def",
"AddStretchSpacer",
"(",
"self",
")",
":",
"self",
".",
"_sizer",
".",
"AddStretchSpacer",
"(",
"2",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/eclib/ctrlbox.py#L445-L450 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/__init__.py | python | connect_sdb | (aws_access_key_id=None, aws_secret_access_key=None, **kwargs) | return SDBConnection(aws_access_key_id, aws_secret_access_key, **kwargs) | :type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto.sdb.connection.SDBConnection`
:return: A connection to Amazon's SDB | :type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID | [
":",
"type",
"aws_access_key_id",
":",
"string",
":",
"param",
"aws_access_key_id",
":",
"Your",
"AWS",
"Access",
"Key",
"ID"
] | def connect_sdb(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
"""
:type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto.sdb.connection.SDBConnection`
:return: A connection to Amazon's SDB
"""
from boto.sdb.connection import SDBConnection
return SDBConnection(aws_access_key_id, aws_secret_access_key, **kwargs) | [
"def",
"connect_sdb",
"(",
"aws_access_key_id",
"=",
"None",
",",
"aws_secret_access_key",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"boto",
".",
"sdb",
".",
"connection",
"import",
"SDBConnection",
"return",
"SDBConnection",
"(",
"aws_access_key_i... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/__init__.py#L228-L240 | |
google-ar/WebARonTango | e86965d2cbc652156b480e0fcf77c716745578cd | chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py | python | BoolArgument.GetValidGLArg | (self, func) | return 'true' | Gets a valid GL value for this argument. | Gets a valid GL value for this argument. | [
"Gets",
"a",
"valid",
"GL",
"value",
"for",
"this",
"argument",
"."
] | def GetValidGLArg(self, func):
"""Gets a valid GL value for this argument."""
return 'true' | [
"def",
"GetValidGLArg",
"(",
"self",
",",
"func",
")",
":",
"return",
"'true'"
] | https://github.com/google-ar/WebARonTango/blob/e86965d2cbc652156b480e0fcf77c716745578cd/chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py#L8664-L8666 | |
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/peacock/ExodusViewer/plugins/ColorbarPlugin.py | python | ColorbarPlugin._callbackColorBarToggle | (self, value) | Callback for the colorbar toggle. | Callback for the colorbar toggle. | [
"Callback",
"for",
"the",
"colorbar",
"toggle",
"."
] | def _callbackColorBarToggle(self, value):
"""
Callback for the colorbar toggle.
"""
self.store(self.ColorBarToggle)
self.updateOptions()
self.windowRequiresUpdate.emit() | [
"def",
"_callbackColorBarToggle",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"store",
"(",
"self",
".",
"ColorBarToggle",
")",
"self",
".",
"updateOptions",
"(",
")",
"self",
".",
"windowRequiresUpdate",
".",
"emit",
"(",
")"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/ExodusViewer/plugins/ColorbarPlugin.py#L369-L375 | ||
TGAC/KAT | e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216 | deps/boost/tools/build/src/build/virtual_target.py | python | Action.actualize_source_type | (self, sources, prop_set) | return result | Helper for 'actualize_sources'.
For each passed source, actualizes it with the appropriate scanner.
Returns the actualized virtual targets. | Helper for 'actualize_sources'.
For each passed source, actualizes it with the appropriate scanner.
Returns the actualized virtual targets. | [
"Helper",
"for",
"actualize_sources",
".",
"For",
"each",
"passed",
"source",
"actualizes",
"it",
"with",
"the",
"appropriate",
"scanner",
".",
"Returns",
"the",
"actualized",
"virtual",
"targets",
"."
] | def actualize_source_type (self, sources, prop_set):
""" Helper for 'actualize_sources'.
For each passed source, actualizes it with the appropriate scanner.
Returns the actualized virtual targets.
"""
assert is_iterable_typed(sources, VirtualTarget)
assert isinstance(prop_set, property_set.PropertySet)
result = []
for i in sources:
scanner = None
# FIXME: what's this?
# if isinstance (i, str):
# i = self.manager_.get_object (i)
if i.type ():
scanner = b2.build.type.get_scanner (i.type (), prop_set)
r = i.actualize (scanner)
result.append (r)
return result | [
"def",
"actualize_source_type",
"(",
"self",
",",
"sources",
",",
"prop_set",
")",
":",
"assert",
"is_iterable_typed",
"(",
"sources",
",",
"VirtualTarget",
")",
"assert",
"isinstance",
"(",
"prop_set",
",",
"property_set",
".",
"PropertySet",
")",
"result",
"="... | https://github.com/TGAC/KAT/blob/e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216/deps/boost/tools/build/src/build/virtual_target.py#L863-L884 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/robotsim.py | python | WorldModel.makeRigidObject | (self, name) | return _robotsim.WorldModel_makeRigidObject(self, name) | makeRigidObject(WorldModel self, char const * name) -> RigidObjectModel
Creates a new empty rigid object. | makeRigidObject(WorldModel self, char const * name) -> RigidObjectModel | [
"makeRigidObject",
"(",
"WorldModel",
"self",
"char",
"const",
"*",
"name",
")",
"-",
">",
"RigidObjectModel"
] | def makeRigidObject(self, name):
"""
makeRigidObject(WorldModel self, char const * name) -> RigidObjectModel
Creates a new empty rigid object.
"""
return _robotsim.WorldModel_makeRigidObject(self, name) | [
"def",
"makeRigidObject",
"(",
"self",
",",
"name",
")",
":",
"return",
"_robotsim",
".",
"WorldModel_makeRigidObject",
"(",
"self",
",",
"name",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/robotsim.py#L5936-L5945 | |
google/clif | cab24d6a105609a65c95a36a1712ae3c20c7b5df | clif/pybind11/function.py | python | _generate_function | (
module_name: str, func_decl: ast_pb2.FuncDecl,
capsule_types: Set[str],
class_decl: Optional[ast_pb2.ClassDecl] = None,
) | Generates pybind11 bindings code for ast_pb2.FuncDecl. | Generates pybind11 bindings code for ast_pb2.FuncDecl. | [
"Generates",
"pybind11",
"bindings",
"code",
"for",
"ast_pb2",
".",
"FuncDecl",
"."
] | def _generate_function(
module_name: str, func_decl: ast_pb2.FuncDecl,
capsule_types: Set[str],
class_decl: Optional[ast_pb2.ClassDecl] = None,
) -> Generator[str, None, None]:
"""Generates pybind11 bindings code for ast_pb2.FuncDecl."""
if lambdas.needs_lambda(func_decl, capsule_types, class_decl):
yield from lambdas.generate_lambda(
module_name, func_decl, capsule_types, class_decl)
elif operators.needs_operator_overloading(func_decl):
yield from operators.generate_operator(module_name, func_decl)
else:
yield from _generate_simple_function(module_name, func_decl, class_decl) | [
"def",
"_generate_function",
"(",
"module_name",
":",
"str",
",",
"func_decl",
":",
"ast_pb2",
".",
"FuncDecl",
",",
"capsule_types",
":",
"Set",
"[",
"str",
"]",
",",
"class_decl",
":",
"Optional",
"[",
"ast_pb2",
".",
"ClassDecl",
"]",
"=",
"None",
",",
... | https://github.com/google/clif/blob/cab24d6a105609a65c95a36a1712ae3c20c7b5df/clif/pybind11/function.py#L55-L67 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/aui.py | python | AuiPaneInfo.HasCaption | (*args, **kwargs) | return _aui.AuiPaneInfo_HasCaption(*args, **kwargs) | HasCaption(self) -> bool | HasCaption(self) -> bool | [
"HasCaption",
"(",
"self",
")",
"-",
">",
"bool"
] | def HasCaption(*args, **kwargs):
"""HasCaption(self) -> bool"""
return _aui.AuiPaneInfo_HasCaption(*args, **kwargs) | [
"def",
"HasCaption",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiPaneInfo_HasCaption",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/aui.py#L301-L303 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/mws/connection.py | python | MWSConnection.get_order | (self, request, response, **kw) | return self._post_request(request, kw, response) | Returns an order for each AmazonOrderId that you specify. | Returns an order for each AmazonOrderId that you specify. | [
"Returns",
"an",
"order",
"for",
"each",
"AmazonOrderId",
"that",
"you",
"specify",
"."
] | def get_order(self, request, response, **kw):
"""Returns an order for each AmazonOrderId that you specify.
"""
return self._post_request(request, kw, response) | [
"def",
"get_order",
"(",
"self",
",",
"request",
",",
"response",
",",
"*",
"*",
"kw",
")",
":",
"return",
"self",
".",
"_post_request",
"(",
"request",
",",
"kw",
",",
"response",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/mws/connection.py#L746-L749 | |
lammps/lammps | b75c3065430a75b1b5543a10e10f46d9b4c91913 | doc/src/_ext/tab_or_note.py | python | replace_tabs_handler | (app, docname, source) | When builder is not 'html', remove 'tabs' directive
and replace any 'tab' directive with 'admonition | When builder is not 'html', remove 'tabs' directive
and replace any 'tab' directive with 'admonition | [
"When",
"builder",
"is",
"not",
"html",
"remove",
"tabs",
"directive",
"and",
"replace",
"any",
"tab",
"directive",
"with",
"admonition"
] | def replace_tabs_handler(app, docname, source):
""" When builder is not 'html', remove 'tabs' directive
and replace any 'tab' directive with 'admonition'"""
if app.builder.name != 'html':
for i in range(len(source)):
source[i] = source[i].replace('.. tabs::','').replace('.. tab::','.. admonition::') | [
"def",
"replace_tabs_handler",
"(",
"app",
",",
"docname",
",",
"source",
")",
":",
"if",
"app",
".",
"builder",
".",
"name",
"!=",
"'html'",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"source",
")",
")",
":",
"source",
"[",
"i",
"]",
"=",
... | https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/doc/src/_ext/tab_or_note.py#L2-L7 | ||
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/buildscripts/resmokelib/logging/loggers.py | python | ExecutorRootLogger.new_job_logger | (self, test_kind, job_num) | return JobLogger(test_kind, job_num, self, self.fixture_root_logger) | Create a new child JobLogger. | Create a new child JobLogger. | [
"Create",
"a",
"new",
"child",
"JobLogger",
"."
] | def new_job_logger(self, test_kind, job_num):
"""Create a new child JobLogger."""
return JobLogger(test_kind, job_num, self, self.fixture_root_logger) | [
"def",
"new_job_logger",
"(",
"self",
",",
"test_kind",
",",
"job_num",
")",
":",
"return",
"JobLogger",
"(",
"test_kind",
",",
"job_num",
",",
"self",
",",
"self",
".",
"fixture_root_logger",
")"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/resmokelib/logging/loggers.py#L144-L146 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_controls.py | python | BitmapButton.Create | (*args, **kwargs) | return _controls_.BitmapButton_Create(*args, **kwargs) | Create(self, Window parent, int id=-1, Bitmap bitmap=wxNullBitmap,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=BU_AUTODRAW, Validator validator=DefaultValidator,
String name=ButtonNameStr) -> bool
Acutally create the GUI BitmapButton for 2-phase creation. | Create(self, Window parent, int id=-1, Bitmap bitmap=wxNullBitmap,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=BU_AUTODRAW, Validator validator=DefaultValidator,
String name=ButtonNameStr) -> bool | [
"Create",
"(",
"self",
"Window",
"parent",
"int",
"id",
"=",
"-",
"1",
"Bitmap",
"bitmap",
"=",
"wxNullBitmap",
"Point",
"pos",
"=",
"DefaultPosition",
"Size",
"size",
"=",
"DefaultSize",
"long",
"style",
"=",
"BU_AUTODRAW",
"Validator",
"validator",
"=",
"D... | def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, Bitmap bitmap=wxNullBitmap,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=BU_AUTODRAW, Validator validator=DefaultValidator,
String name=ButtonNameStr) -> bool
Acutally create the GUI BitmapButton for 2-phase creation.
"""
return _controls_.BitmapButton_Create(*args, **kwargs) | [
"def",
"Create",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"BitmapButton_Create",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L307-L316 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2.py | python | xmlDoc.htmlDocDump | (self, f) | return ret | Dump an HTML document to an open FILE. | Dump an HTML document to an open FILE. | [
"Dump",
"an",
"HTML",
"document",
"to",
"an",
"open",
"FILE",
"."
] | def htmlDocDump(self, f):
"""Dump an HTML document to an open FILE. """
ret = libxml2mod.htmlDocDump(f, self._o)
return ret | [
"def",
"htmlDocDump",
"(",
"self",
",",
"f",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"htmlDocDump",
"(",
"f",
",",
"self",
".",
"_o",
")",
"return",
"ret"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2.py#L4003-L4006 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/nn_impl.py | python | separable_conv2d_v2 | (
input,
depthwise_filter,
pointwise_filter,
strides,
padding,
data_format=None,
dilations=None,
name=None,
) | return separable_conv2d(
input,
depthwise_filter,
pointwise_filter,
strides,
padding,
rate=dilations,
name=name,
data_format=data_format) | 2-D convolution with separable filters.
Performs a depthwise convolution that acts separately on channels followed by
a pointwise convolution that mixes channels. Note that this is separability
between dimensions `[1, 2]` and `3`, not spatial separability between
dimensions `1` and `2`.
In detail, with the default NHWC format,
output[b, i, j, k] = sum_{di, dj, q, r}
input[b, strides[1] * i + di, strides[2] * j + dj, q] *
depthwise_filter[di, dj, q, r] *
pointwise_filter[0, 0, q * channel_multiplier + r, k]
`strides` controls the strides for the depthwise convolution only, since
the pointwise convolution has implicit strides of `[1, 1, 1, 1]`. Must have
`strides[0] = strides[3] = 1`. For the most common case of the same
horizontal and vertical strides, `strides = [1, stride, stride, 1]`.
If any value in `rate` is greater than 1, we perform atrous depthwise
convolution, in which case all values in the `strides` tensor must be equal
to 1.
Args:
input: 4-D `Tensor` with shape according to `data_format`.
depthwise_filter: 4-D `Tensor` with shape `[filter_height, filter_width,
in_channels, channel_multiplier]`. Contains `in_channels` convolutional
filters of depth 1.
pointwise_filter: 4-D `Tensor` with shape `[1, 1, channel_multiplier *
in_channels, out_channels]`. Pointwise filter to mix channels after
`depthwise_filter` has convolved spatially.
strides: 1-D of size 4. The strides for the depthwise convolution for each
dimension of `input`.
padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm. See
the "returns" section of `tf.nn.convolution` for details.
data_format: The data format for input. Either "NHWC" (default) or "NCHW".
dilations: 1-D of size 2. The dilation rate in which we sample input values
across the `height` and `width` dimensions in atrous convolution. If it is
greater than 1, then all values of strides must be 1.
name: A name for this operation (optional).
Returns:
A 4-D `Tensor` with shape according to 'data_format'. For
example, with data_format="NHWC", shape is [batch, out_height,
out_width, out_channels]. | 2-D convolution with separable filters. | [
"2",
"-",
"D",
"convolution",
"with",
"separable",
"filters",
"."
] | def separable_conv2d_v2(
input,
depthwise_filter,
pointwise_filter,
strides,
padding,
data_format=None,
dilations=None,
name=None,
):
"""2-D convolution with separable filters.
Performs a depthwise convolution that acts separately on channels followed by
a pointwise convolution that mixes channels. Note that this is separability
between dimensions `[1, 2]` and `3`, not spatial separability between
dimensions `1` and `2`.
In detail, with the default NHWC format,
output[b, i, j, k] = sum_{di, dj, q, r}
input[b, strides[1] * i + di, strides[2] * j + dj, q] *
depthwise_filter[di, dj, q, r] *
pointwise_filter[0, 0, q * channel_multiplier + r, k]
`strides` controls the strides for the depthwise convolution only, since
the pointwise convolution has implicit strides of `[1, 1, 1, 1]`. Must have
`strides[0] = strides[3] = 1`. For the most common case of the same
horizontal and vertical strides, `strides = [1, stride, stride, 1]`.
If any value in `rate` is greater than 1, we perform atrous depthwise
convolution, in which case all values in the `strides` tensor must be equal
to 1.
Args:
input: 4-D `Tensor` with shape according to `data_format`.
depthwise_filter: 4-D `Tensor` with shape `[filter_height, filter_width,
in_channels, channel_multiplier]`. Contains `in_channels` convolutional
filters of depth 1.
pointwise_filter: 4-D `Tensor` with shape `[1, 1, channel_multiplier *
in_channels, out_channels]`. Pointwise filter to mix channels after
`depthwise_filter` has convolved spatially.
strides: 1-D of size 4. The strides for the depthwise convolution for each
dimension of `input`.
padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm. See
the "returns" section of `tf.nn.convolution` for details.
data_format: The data format for input. Either "NHWC" (default) or "NCHW".
dilations: 1-D of size 2. The dilation rate in which we sample input values
across the `height` and `width` dimensions in atrous convolution. If it is
greater than 1, then all values of strides must be 1.
name: A name for this operation (optional).
Returns:
A 4-D `Tensor` with shape according to 'data_format'. For
example, with data_format="NHWC", shape is [batch, out_height,
out_width, out_channels].
"""
return separable_conv2d(
input,
depthwise_filter,
pointwise_filter,
strides,
padding,
rate=dilations,
name=name,
data_format=data_format) | [
"def",
"separable_conv2d_v2",
"(",
"input",
",",
"depthwise_filter",
",",
"pointwise_filter",
",",
"strides",
",",
"padding",
",",
"data_format",
"=",
"None",
",",
"dilations",
"=",
"None",
",",
"name",
"=",
"None",
",",
")",
":",
"return",
"separable_conv2d",... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/nn_impl.py#L985-L1048 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pkg_resources/__init__.py | python | _bypass_ensure_directory | (path) | Sandbox-bypassing version of ensure_directory() | Sandbox-bypassing version of ensure_directory() | [
"Sandbox",
"-",
"bypassing",
"version",
"of",
"ensure_directory",
"()"
] | def _bypass_ensure_directory(path):
"""Sandbox-bypassing version of ensure_directory()"""
if not WRITE_SUPPORT:
raise IOError('"os.mkdir" not supported on this platform.')
dirname, filename = split(path)
if dirname and filename and not isdir(dirname):
_bypass_ensure_directory(dirname)
try:
mkdir(dirname, 0o755)
except FileExistsError:
pass | [
"def",
"_bypass_ensure_directory",
"(",
"path",
")",
":",
"if",
"not",
"WRITE_SUPPORT",
":",
"raise",
"IOError",
"(",
"'\"os.mkdir\" not supported on this platform.'",
")",
"dirname",
",",
"filename",
"=",
"split",
"(",
"path",
")",
"if",
"dirname",
"and",
"filena... | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pkg_resources/__init__.py#L3166-L3176 | ||
2shou/TextGrocery | 8a4e41349a9b0175d9a73bc32a6b2eb6bfb51430 | tgrocery/learner/learner.py | python | train | (data_file_name, learner_opts="", liblinear_opts="") | return m | Return a :class:`LearnerModel`.
*data_file_name* is the file path of the LIBSVM-format data. *learner_opts* is a
:class:`str`. Refer to :ref:`learner_param`. *liblinear_opts* is a :class:`str` of
LIBLINEAR's parameters. Refer to LIBLINEAR's document. | Return a :class:`LearnerModel`. | [
"Return",
"a",
":",
"class",
":",
"LearnerModel",
"."
] | def train(data_file_name, learner_opts="", liblinear_opts=""):
"""
Return a :class:`LearnerModel`.
*data_file_name* is the file path of the LIBSVM-format data. *learner_opts* is a
:class:`str`. Refer to :ref:`learner_param`. *liblinear_opts* is a :class:`str` of
LIBLINEAR's parameters. Refer to LIBLINEAR's document.
"""
learner_prob = LearnerProblem(data_file_name)
learner_param = LearnerParameter(learner_opts, liblinear_opts)
idf = None
if learner_param.inverse_document_frequency:
idf = learner_prob.compute_idf()
learner_prob.normalize(learner_param, idf)
m = liblinear_train(learner_prob, learner_param)
if not learner_param.cross_validation:
m.x_space = None # This is required to reduce the memory usage...
m = LearnerModel(m, learner_param, idf)
return m | [
"def",
"train",
"(",
"data_file_name",
",",
"learner_opts",
"=",
"\"\"",
",",
"liblinear_opts",
"=",
"\"\"",
")",
":",
"learner_prob",
"=",
"LearnerProblem",
"(",
"data_file_name",
")",
"learner_param",
"=",
"LearnerParameter",
"(",
"learner_opts",
",",
"liblinear... | https://github.com/2shou/TextGrocery/blob/8a4e41349a9b0175d9a73bc32a6b2eb6bfb51430/tgrocery/learner/learner.py#L376-L398 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/dircache.py | python | reset | () | Reset the cache completely. | Reset the cache completely. | [
"Reset",
"the",
"cache",
"completely",
"."
] | def reset():
"""Reset the cache completely."""
global cache
cache = {} | [
"def",
"reset",
"(",
")",
":",
"global",
"cache",
"cache",
"=",
"{",
"}"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/dircache.py#L16-L19 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/data_flow_ops.py | python | BaseStagingArea._check_put_dtypes | (self, vals, indices=None) | return tensors, indices | Validate and convert `vals` to a list of `Tensor`s.
The `vals` argument can be a Tensor, a list or tuple of tensors, or a
dictionary with tensor values.
If `vals` is a list, then the appropriate indices associated with the
values must be provided.
If it is a dictionary, the staging area must have been constructed with a
`names` attribute and the dictionary keys must match the staging area names.
`indices` will be inferred from the dictionary keys.
If the staging area was constructed with a `names` attribute, `vals` must
be a dictionary.
Checks that the dtype and shape of each value matches that
of the staging area.
Args:
vals: A tensor, a list or tuple of tensors, or a dictionary.
Returns:
A (tensors, indices) tuple where `tensors` is a list of `Tensor` objects
and `indices` is a list of indices associed with the tensors.
Raises:
ValueError: If `vals` or `indices` is invalid. | Validate and convert `vals` to a list of `Tensor`s. | [
"Validate",
"and",
"convert",
"vals",
"to",
"a",
"list",
"of",
"Tensor",
"s",
"."
] | def _check_put_dtypes(self, vals, indices=None):
"""Validate and convert `vals` to a list of `Tensor`s.
The `vals` argument can be a Tensor, a list or tuple of tensors, or a
dictionary with tensor values.
If `vals` is a list, then the appropriate indices associated with the
values must be provided.
If it is a dictionary, the staging area must have been constructed with a
`names` attribute and the dictionary keys must match the staging area names.
`indices` will be inferred from the dictionary keys.
If the staging area was constructed with a `names` attribute, `vals` must
be a dictionary.
Checks that the dtype and shape of each value matches that
of the staging area.
Args:
vals: A tensor, a list or tuple of tensors, or a dictionary.
Returns:
A (tensors, indices) tuple where `tensors` is a list of `Tensor` objects
and `indices` is a list of indices associed with the tensors.
Raises:
ValueError: If `vals` or `indices` is invalid.
"""
if isinstance(vals, dict):
if not self._names:
raise ValueError(
"Staging areas must have names to enqueue a dictionary")
if not set(vals.keys()).issubset(self._names):
raise ValueError("Keys in dictionary to put do not match names "
"of staging area. Dictionary: (%s), Queue: (%s)" %
(sorted(vals.keys()), sorted(self._names)))
# The order of values in `self._names` indicates the order in which the
# tensors in the dictionary `vals` must be listed.
vals, indices, _ = zip(*[(vals[k], i, k)
for i, k in enumerate(self._names)
if k in vals])
else:
if self._names:
raise ValueError("You must enqueue a dictionary in a staging area "
"with names")
if indices is None:
raise ValueError("Indices must be supplied when inserting a list "
"of tensors")
if len(indices) != len(vals):
raise ValueError("Number of indices '%s' doesn't match "
"number of values '%s'")
if not isinstance(vals, (list, tuple)):
vals = [vals]
indices = [0]
# Sanity check number of values
if not len(vals) <= len(self._dtypes):
raise ValueError("Unexpected number of inputs '%s' vs '%s'" %
(len(vals), len(self._dtypes)))
tensors = []
for val, i in zip(vals, indices):
dtype, shape = self._dtypes[i], self._shapes[i]
# Check dtype
if val.dtype != dtype:
raise ValueError("Datatypes do not match. '%s' != '%s'" %
(str(val.dtype), str(dtype)))
# Check shape
val.get_shape().assert_is_compatible_with(shape)
tensors.append(
ops.convert_to_tensor(val, dtype=dtype, name="component_%d" % i))
return tensors, indices | [
"def",
"_check_put_dtypes",
"(",
"self",
",",
"vals",
",",
"indices",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"vals",
",",
"dict",
")",
":",
"if",
"not",
"self",
".",
"_names",
":",
"raise",
"ValueError",
"(",
"\"Staging areas must have names to enqu... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/data_flow_ops.py#L1630-L1708 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.