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
sequence | function
stringlengths 34
151k
| function_tokens
sequence | url
stringlengths 90
278
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | tools/caffe_converter/compare_layers.py | python | main | () | Entrypoint for compare_layers | Entrypoint for compare_layers | [
"Entrypoint",
"for",
"compare_layers"
] | def main():
"""Entrypoint for compare_layers"""
parser = argparse.ArgumentParser(
description='Tool for testing caffe to mxnet conversion layer by layer')
parser.add_argument('--image_url', type=str,
default='https://github.com/dmlc/web-data/raw/master/mxnet/doc/'\
'tutorials/python/predict_image/cat.jpg',
help='input image to test inference, can be either file path or url')
parser.add_argument('--caffe_prototxt_path', type=str,
default='./model.prototxt',
help='path to caffe prototxt')
parser.add_argument('--caffe_model_path', type=str,
default='./model.caffemodel',
help='path to caffe weights')
parser.add_argument('--caffe_mean', type=str,
default='./model_mean.binaryproto',
help='path to caffe mean file')
parser.add_argument('--mean_diff_allowed', type=int, default=1e-03,
help='mean difference allowed between caffe blob and mxnet blob')
parser.add_argument('--max_diff_allowed', type=int, default=1e-01,
help='max difference allowed between caffe blob and mxnet blob')
parser.add_argument('--gpu', type=int, default=-1, help='the gpu id used for predict')
args = parser.parse_args()
convert_and_compare_caffe_to_mxnet(args.image_url, args.gpu, args.caffe_prototxt_path,
args.caffe_model_path, args.caffe_mean,
args.mean_diff_allowed, args.max_diff_allowed) | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Tool for testing caffe to mxnet conversion layer by layer'",
")",
"parser",
".",
"add_argument",
"(",
"'--image_url'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"'https://github.com/dmlc/web-data/raw/master/mxnet/doc/'",
"'tutorials/python/predict_image/cat.jpg'",
",",
"help",
"=",
"'input image to test inference, can be either file path or url'",
")",
"parser",
".",
"add_argument",
"(",
"'--caffe_prototxt_path'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"'./model.prototxt'",
",",
"help",
"=",
"'path to caffe prototxt'",
")",
"parser",
".",
"add_argument",
"(",
"'--caffe_model_path'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"'./model.caffemodel'",
",",
"help",
"=",
"'path to caffe weights'",
")",
"parser",
".",
"add_argument",
"(",
"'--caffe_mean'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"'./model_mean.binaryproto'",
",",
"help",
"=",
"'path to caffe mean file'",
")",
"parser",
".",
"add_argument",
"(",
"'--mean_diff_allowed'",
",",
"type",
"=",
"int",
",",
"default",
"=",
"1e-03",
",",
"help",
"=",
"'mean difference allowed between caffe blob and mxnet blob'",
")",
"parser",
".",
"add_argument",
"(",
"'--max_diff_allowed'",
",",
"type",
"=",
"int",
",",
"default",
"=",
"1e-01",
",",
"help",
"=",
"'max difference allowed between caffe blob and mxnet blob'",
")",
"parser",
".",
"add_argument",
"(",
"'--gpu'",
",",
"type",
"=",
"int",
",",
"default",
"=",
"-",
"1",
",",
"help",
"=",
"'the gpu id used for predict'",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"convert_and_compare_caffe_to_mxnet",
"(",
"args",
".",
"image_url",
",",
"args",
".",
"gpu",
",",
"args",
".",
"caffe_prototxt_path",
",",
"args",
".",
"caffe_model_path",
",",
"args",
".",
"caffe_mean",
",",
"args",
".",
"mean_diff_allowed",
",",
"args",
".",
"max_diff_allowed",
")"
] | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/tools/caffe_converter/compare_layers.py#L333-L359 |
||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/protobuf/py3/google/protobuf/internal/well_known_types.py | python | Timestamp.FromDatetime | (self, dt) | Converts datetime to Timestamp. | Converts datetime to Timestamp. | [
"Converts",
"datetime",
"to",
"Timestamp",
"."
] | def FromDatetime(self, dt):
"""Converts datetime to Timestamp."""
# Using this guide: http://wiki.python.org/moin/WorkingWithTime
# And this conversion guide: http://docs.python.org/library/time.html
# Turn the date parameter into a tuple (struct_time) that can then be
# manipulated into a long value of seconds. During the conversion from
# struct_time to long, the source date in UTC, and so it follows that the
# correct transformation is calendar.timegm()
self.seconds = calendar.timegm(dt.utctimetuple())
self.nanos = dt.microsecond * _NANOS_PER_MICROSECOND | [
"def",
"FromDatetime",
"(",
"self",
",",
"dt",
")",
":",
"# Using this guide: http://wiki.python.org/moin/WorkingWithTime",
"# And this conversion guide: http://docs.python.org/library/time.html",
"# Turn the date parameter into a tuple (struct_time) that can then be",
"# manipulated into a long value of seconds. During the conversion from",
"# struct_time to long, the source date in UTC, and so it follows that the",
"# correct transformation is calendar.timegm()",
"self",
".",
"seconds",
"=",
"calendar",
".",
"timegm",
"(",
"dt",
".",
"utctimetuple",
"(",
")",
")",
"self",
".",
"nanos",
"=",
"dt",
".",
"microsecond",
"*",
"_NANOS_PER_MICROSECOND"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py3/google/protobuf/internal/well_known_types.py#L245-L255 |
||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/keras/optimizer_v1.py | python | TFOptimizer._clip_gradients | (self, grads) | return grads | Clip gradients according to the clipnorm and clipvalue attributes. | Clip gradients according to the clipnorm and clipvalue attributes. | [
"Clip",
"gradients",
"according",
"to",
"the",
"clipnorm",
"and",
"clipvalue",
"attributes",
"."
] | def _clip_gradients(self, grads):
"""Clip gradients according to the clipnorm and clipvalue attributes."""
# TFOptimizer wrapper has no gradient clipping options.
return grads | [
"def",
"_clip_gradients",
"(",
"self",
",",
"grads",
")",
":",
"# TFOptimizer wrapper has no gradient clipping options.",
"return",
"grads"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/optimizer_v1.py#L777-L780 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/richtext.py | python | RichTextLine.GetAbsoluteRange | (*args, **kwargs) | return _richtext.RichTextLine_GetAbsoluteRange(*args, **kwargs) | GetAbsoluteRange(self) -> RichTextRange | GetAbsoluteRange(self) -> RichTextRange | [
"GetAbsoluteRange",
"(",
"self",
")",
"-",
">",
"RichTextRange"
] | def GetAbsoluteRange(*args, **kwargs):
"""GetAbsoluteRange(self) -> RichTextRange"""
return _richtext.RichTextLine_GetAbsoluteRange(*args, **kwargs) | [
"def",
"GetAbsoluteRange",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextLine_GetAbsoluteRange",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L1915-L1917 |
|
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/httplib2/upload-diffs.py | python | SubversionVCS.GetStatus | (self, filename) | return status | Returns the status of a file. | Returns the status of a file. | [
"Returns",
"the",
"status",
"of",
"a",
"file",
"."
] | def GetStatus(self, filename):
"""Returns the status of a file."""
if not self.options.revision:
status = RunShell(["svn", "status", "--ignore-externals",
self._EscapeFilename(filename)])
if not status:
ErrorExit("svn status returned no output for %s" % filename)
status_lines = status.splitlines()
# If file is in a cl, the output will begin with
# "\n--- Changelist 'cl_name':\n". See
# http://svn.collab.net/repos/svn/trunk/notes/changelist-design.txt
if (len(status_lines) == 3 and
not status_lines[0] and
status_lines[1].startswith("--- Changelist")):
status = status_lines[2]
else:
status = status_lines[0]
# If we have a revision to diff against we need to run "svn list"
# for the old and the new revision and compare the results to get
# the correct status for a file.
else:
dirname, relfilename = os.path.split(filename)
if dirname not in self.svnls_cache:
cmd = ["svn", "list", "-r", self.rev_start,
self._EscapeFilename(dirname) or "."]
out, err, returncode = RunShellWithReturnCodeAndStderr(cmd)
if returncode:
# Directory might not yet exist at start revison
# svn: Unable to find repository location for 'abc' in revision nnn
if re.match('^svn: Unable to find repository location for .+ in revision \d+', err):
old_files = ()
else:
ErrorExit("Failed to get status for %s:\n%s" % (filename, err))
else:
old_files = out.splitlines()
args = ["svn", "list"]
if self.rev_end:
args += ["-r", self.rev_end]
cmd = args + [self._EscapeFilename(dirname) or "."]
out, returncode = RunShellWithReturnCode(cmd)
if returncode:
ErrorExit("Failed to run command %s" % cmd)
self.svnls_cache[dirname] = (old_files, out.splitlines())
old_files, new_files = self.svnls_cache[dirname]
if relfilename in old_files and relfilename not in new_files:
status = "D "
elif relfilename in old_files and relfilename in new_files:
status = "M "
else:
status = "A "
return status | [
"def",
"GetStatus",
"(",
"self",
",",
"filename",
")",
":",
"if",
"not",
"self",
".",
"options",
".",
"revision",
":",
"status",
"=",
"RunShell",
"(",
"[",
"\"svn\"",
",",
"\"status\"",
",",
"\"--ignore-externals\"",
",",
"self",
".",
"_EscapeFilename",
"(",
"filename",
")",
"]",
")",
"if",
"not",
"status",
":",
"ErrorExit",
"(",
"\"svn status returned no output for %s\"",
"%",
"filename",
")",
"status_lines",
"=",
"status",
".",
"splitlines",
"(",
")",
"# If file is in a cl, the output will begin with",
"# \"\\n--- Changelist 'cl_name':\\n\". See",
"# http://svn.collab.net/repos/svn/trunk/notes/changelist-design.txt",
"if",
"(",
"len",
"(",
"status_lines",
")",
"==",
"3",
"and",
"not",
"status_lines",
"[",
"0",
"]",
"and",
"status_lines",
"[",
"1",
"]",
".",
"startswith",
"(",
"\"--- Changelist\"",
")",
")",
":",
"status",
"=",
"status_lines",
"[",
"2",
"]",
"else",
":",
"status",
"=",
"status_lines",
"[",
"0",
"]",
"# If we have a revision to diff against we need to run \"svn list\"",
"# for the old and the new revision and compare the results to get",
"# the correct status for a file.",
"else",
":",
"dirname",
",",
"relfilename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"filename",
")",
"if",
"dirname",
"not",
"in",
"self",
".",
"svnls_cache",
":",
"cmd",
"=",
"[",
"\"svn\"",
",",
"\"list\"",
",",
"\"-r\"",
",",
"self",
".",
"rev_start",
",",
"self",
".",
"_EscapeFilename",
"(",
"dirname",
")",
"or",
"\".\"",
"]",
"out",
",",
"err",
",",
"returncode",
"=",
"RunShellWithReturnCodeAndStderr",
"(",
"cmd",
")",
"if",
"returncode",
":",
"# Directory might not yet exist at start revison",
"# svn: Unable to find repository location for 'abc' in revision nnn",
"if",
"re",
".",
"match",
"(",
"'^svn: Unable to find repository location for .+ in revision \\d+'",
",",
"err",
")",
":",
"old_files",
"=",
"(",
")",
"else",
":",
"ErrorExit",
"(",
"\"Failed to get status for %s:\\n%s\"",
"%",
"(",
"filename",
",",
"err",
")",
")",
"else",
":",
"old_files",
"=",
"out",
".",
"splitlines",
"(",
")",
"args",
"=",
"[",
"\"svn\"",
",",
"\"list\"",
"]",
"if",
"self",
".",
"rev_end",
":",
"args",
"+=",
"[",
"\"-r\"",
",",
"self",
".",
"rev_end",
"]",
"cmd",
"=",
"args",
"+",
"[",
"self",
".",
"_EscapeFilename",
"(",
"dirname",
")",
"or",
"\".\"",
"]",
"out",
",",
"returncode",
"=",
"RunShellWithReturnCode",
"(",
"cmd",
")",
"if",
"returncode",
":",
"ErrorExit",
"(",
"\"Failed to run command %s\"",
"%",
"cmd",
")",
"self",
".",
"svnls_cache",
"[",
"dirname",
"]",
"=",
"(",
"old_files",
",",
"out",
".",
"splitlines",
"(",
")",
")",
"old_files",
",",
"new_files",
"=",
"self",
".",
"svnls_cache",
"[",
"dirname",
"]",
"if",
"relfilename",
"in",
"old_files",
"and",
"relfilename",
"not",
"in",
"new_files",
":",
"status",
"=",
"\"D \"",
"elif",
"relfilename",
"in",
"old_files",
"and",
"relfilename",
"in",
"new_files",
":",
"status",
"=",
"\"M \"",
"else",
":",
"status",
"=",
"\"A \"",
"return",
"status"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/httplib2/upload-diffs.py#L1085-L1135 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/thrift/transport/TTransport.py | python | TMemoryBuffer.__init__ | (self, value=None, offset=0) | value -- a value to read from for stringio
If value is set, this will be a transport for reading,
otherwise, it is for writing | value -- a value to read from for stringio | [
"value",
"--",
"a",
"value",
"to",
"read",
"from",
"for",
"stringio"
] | def __init__(self, value=None, offset=0):
"""value -- a value to read from for stringio
If value is set, this will be a transport for reading,
otherwise, it is for writing"""
if value is not None:
self._buffer = BufferIO(value)
else:
self._buffer = BufferIO()
if offset:
self._buffer.seek(offset) | [
"def",
"__init__",
"(",
"self",
",",
"value",
"=",
"None",
",",
"offset",
"=",
"0",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"self",
".",
"_buffer",
"=",
"BufferIO",
"(",
"value",
")",
"else",
":",
"self",
".",
"_buffer",
"=",
"BufferIO",
"(",
")",
"if",
"offset",
":",
"self",
".",
"_buffer",
".",
"seek",
"(",
"offset",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/thrift/transport/TTransport.py#L210-L220 |
||
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPMS_ATTEST.initFromTpm | (self, buf) | TpmMarshaller method | TpmMarshaller method | [
"TpmMarshaller",
"method"
] | def initFromTpm(self, buf):
""" TpmMarshaller method """
self.magic = buf.readInt()
type = buf.readShort()
self.qualifiedSigner = buf.readSizedByteBuf()
self.extraData = buf.readSizedByteBuf()
self.clockInfo = TPMS_CLOCK_INFO.fromTpm(buf)
self.firmwareVersion = buf.readInt64()
self.attested = UnionFactory.create('TPMU_ATTEST', type)
self.attested.initFromTpm(buf) | [
"def",
"initFromTpm",
"(",
"self",
",",
"buf",
")",
":",
"self",
".",
"magic",
"=",
"buf",
".",
"readInt",
"(",
")",
"type",
"=",
"buf",
".",
"readShort",
"(",
")",
"self",
".",
"qualifiedSigner",
"=",
"buf",
".",
"readSizedByteBuf",
"(",
")",
"self",
".",
"extraData",
"=",
"buf",
".",
"readSizedByteBuf",
"(",
")",
"self",
".",
"clockInfo",
"=",
"TPMS_CLOCK_INFO",
".",
"fromTpm",
"(",
"buf",
")",
"self",
".",
"firmwareVersion",
"=",
"buf",
".",
"readInt64",
"(",
")",
"self",
".",
"attested",
"=",
"UnionFactory",
".",
"create",
"(",
"'TPMU_ATTEST'",
",",
"type",
")",
"self",
".",
"attested",
".",
"initFromTpm",
"(",
"buf",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L5451-L5460 |
||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/keras/backend.py | python | print_tensor | (x, message='', summarize=3) | Prints `message` and the tensor value when evaluated.
Note that `print_tensor` returns a new tensor identical to `x`
which should be used in the following code. Otherwise the
print operation is not taken into account during evaluation.
Example:
>>> x = tf.constant([[1.0, 2.0], [3.0, 4.0]])
>>> _ = tf.keras.backend.print_tensor(x)
[[1 2]
[3 4]]
Args:
x: Tensor to print.
message: Message to print jointly with the tensor.
summarize: The first and last `summarize` elements within each dimension
are recursively printed per Tensor. If None, then the first 3 and last
3 elements of each dimension are printed for each tensor. If set to
-1, it will print all elements of every tensor.
Returns:
The same tensor `x`, unchanged. | Prints `message` and the tensor value when evaluated. | [
"Prints",
"message",
"and",
"the",
"tensor",
"value",
"when",
"evaluated",
"."
] | def print_tensor(x, message='', summarize=3):
"""Prints `message` and the tensor value when evaluated.
Note that `print_tensor` returns a new tensor identical to `x`
which should be used in the following code. Otherwise the
print operation is not taken into account during evaluation.
Example:
>>> x = tf.constant([[1.0, 2.0], [3.0, 4.0]])
>>> _ = tf.keras.backend.print_tensor(x)
[[1 2]
[3 4]]
Args:
x: Tensor to print.
message: Message to print jointly with the tensor.
summarize: The first and last `summarize` elements within each dimension
are recursively printed per Tensor. If None, then the first 3 and last
3 elements of each dimension are printed for each tensor. If set to
-1, it will print all elements of every tensor.
Returns:
The same tensor `x`, unchanged.
"""
if isinstance(x, ops.Tensor) and hasattr(x, 'graph'):
with get_graph().as_default():
op = logging_ops.print_v2(
message, x, output_stream=sys.stdout, summarize=summarize)
with ops.control_dependencies([op]):
return array_ops.identity(x)
else:
logging_ops.print_v2(
message, x, output_stream=sys.stdout, summarize=summarize)
return x | [
"def",
"print_tensor",
"(",
"x",
",",
"message",
"=",
"''",
",",
"summarize",
"=",
"3",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"ops",
".",
"Tensor",
")",
"and",
"hasattr",
"(",
"x",
",",
"'graph'",
")",
":",
"with",
"get_graph",
"(",
")",
".",
"as_default",
"(",
")",
":",
"op",
"=",
"logging_ops",
".",
"print_v2",
"(",
"message",
",",
"x",
",",
"output_stream",
"=",
"sys",
".",
"stdout",
",",
"summarize",
"=",
"summarize",
")",
"with",
"ops",
".",
"control_dependencies",
"(",
"[",
"op",
"]",
")",
":",
"return",
"array_ops",
".",
"identity",
"(",
"x",
")",
"else",
":",
"logging_ops",
".",
"print_v2",
"(",
"message",
",",
"x",
",",
"output_stream",
"=",
"sys",
".",
"stdout",
",",
"summarize",
"=",
"summarize",
")",
"return",
"x"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/backend.py#L3846-L3880 |
||
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/bitstring/bitstring.py | python | Bits.__copy__ | (self) | return self | Return a new copy of the Bits for the copy module. | Return a new copy of the Bits for the copy module. | [
"Return",
"a",
"new",
"copy",
"of",
"the",
"Bits",
"for",
"the",
"copy",
"module",
"."
] | def __copy__(self):
"""Return a new copy of the Bits for the copy module."""
# Note that if you want a new copy (different ID), use _copy instead.
# The copy can return self as it's immutable.
return self | [
"def",
"__copy__",
"(",
"self",
")",
":",
"# Note that if you want a new copy (different ID), use _copy instead.",
"# The copy can return self as it's immutable.",
"return",
"self"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/bitstring/bitstring.py#L839-L843 |
|
mapnik/mapnik | f3da900c355e1d15059c4a91b00203dcc9d9f0ef | scons/scons-local-4.1.0/SCons/Tool/intelc.py | python | check_abi | (abi) | return abi | Check for valid ABI (application binary interface) name,
and map into canonical one | Check for valid ABI (application binary interface) name,
and map into canonical one | [
"Check",
"for",
"valid",
"ABI",
"(",
"application",
"binary",
"interface",
")",
"name",
"and",
"map",
"into",
"canonical",
"one"
] | def check_abi(abi):
"""Check for valid ABI (application binary interface) name,
and map into canonical one"""
if not abi:
return None
abi = abi.lower()
# valid_abis maps input name to canonical name
if is_windows:
valid_abis = {'ia32' : 'ia32',
'x86' : 'ia32',
'ia64' : 'ia64',
'em64t' : 'em64t',
'amd64' : 'em64t'}
if is_linux:
valid_abis = {'ia32' : 'ia32',
'x86' : 'ia32',
'x86_64' : 'x86_64',
'em64t' : 'x86_64',
'amd64' : 'x86_64'}
if is_mac:
valid_abis = {'ia32' : 'ia32',
'x86' : 'ia32',
'x86_64' : 'x86_64',
'em64t' : 'x86_64'}
try:
abi = valid_abis[abi]
except KeyError:
raise SCons.Errors.UserError("Intel compiler: Invalid ABI %s, valid values are %s"% \
(abi, list(valid_abis.keys())))
return abi | [
"def",
"check_abi",
"(",
"abi",
")",
":",
"if",
"not",
"abi",
":",
"return",
"None",
"abi",
"=",
"abi",
".",
"lower",
"(",
")",
"# valid_abis maps input name to canonical name",
"if",
"is_windows",
":",
"valid_abis",
"=",
"{",
"'ia32'",
":",
"'ia32'",
",",
"'x86'",
":",
"'ia32'",
",",
"'ia64'",
":",
"'ia64'",
",",
"'em64t'",
":",
"'em64t'",
",",
"'amd64'",
":",
"'em64t'",
"}",
"if",
"is_linux",
":",
"valid_abis",
"=",
"{",
"'ia32'",
":",
"'ia32'",
",",
"'x86'",
":",
"'ia32'",
",",
"'x86_64'",
":",
"'x86_64'",
",",
"'em64t'",
":",
"'x86_64'",
",",
"'amd64'",
":",
"'x86_64'",
"}",
"if",
"is_mac",
":",
"valid_abis",
"=",
"{",
"'ia32'",
":",
"'ia32'",
",",
"'x86'",
":",
"'ia32'",
",",
"'x86_64'",
":",
"'x86_64'",
",",
"'em64t'",
":",
"'x86_64'",
"}",
"try",
":",
"abi",
"=",
"valid_abis",
"[",
"abi",
"]",
"except",
"KeyError",
":",
"raise",
"SCons",
".",
"Errors",
".",
"UserError",
"(",
"\"Intel compiler: Invalid ABI %s, valid values are %s\"",
"%",
"(",
"abi",
",",
"list",
"(",
"valid_abis",
".",
"keys",
"(",
")",
")",
")",
")",
"return",
"abi"
] | https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Tool/intelc.py#L87-L116 |
|
intel/llvm | e6d0547e9d99b5a56430c4749f6c7e328bf221ab | lldb/third_party/Python/module/ptyprocess-0.6.0/ptyprocess/ptyprocess.py | python | PtyProcessUnicode.readline | (self) | return self.decoder.decode(b, final=False) | Read one line from the pseudoterminal, and return it as unicode.
Can block if there is nothing to read. Raises :exc:`EOFError` if the
terminal was closed. | Read one line from the pseudoterminal, and return it as unicode. | [
"Read",
"one",
"line",
"from",
"the",
"pseudoterminal",
"and",
"return",
"it",
"as",
"unicode",
"."
] | def readline(self):
"""Read one line from the pseudoterminal, and return it as unicode.
Can block if there is nothing to read. Raises :exc:`EOFError` if the
terminal was closed.
"""
b = super(PtyProcessUnicode, self).readline()
return self.decoder.decode(b, final=False) | [
"def",
"readline",
"(",
"self",
")",
":",
"b",
"=",
"super",
"(",
"PtyProcessUnicode",
",",
"self",
")",
".",
"readline",
"(",
")",
"return",
"self",
".",
"decoder",
".",
"decode",
"(",
"b",
",",
"final",
"=",
"False",
")"
] | https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/lldb/third_party/Python/module/ptyprocess-0.6.0/ptyprocess/ptyprocess.py#L821-L828 |
|
baidu/sofa-pbrpc | fb1a1cbf0b3b0e09706eefdbca8335f48df2f5aa | python/sofa/pbrpc/client.py | python | Controller.SetTimeout | (self, timeout) | Set timeout of a positive float expressing seconds. | Set timeout of a positive float expressing seconds. | [
"Set",
"timeout",
"of",
"a",
"positive",
"float",
"expressing",
"seconds",
"."
] | def SetTimeout(self, timeout):
"""Set timeout of a positive float expressing seconds.
"""
if timeout <= 0:
raise Error('Invalid timeout value, should be a positive float.')
self.timeout = timeout | [
"def",
"SetTimeout",
"(",
"self",
",",
"timeout",
")",
":",
"if",
"timeout",
"<=",
"0",
":",
"raise",
"Error",
"(",
"'Invalid timeout value, should be a positive float.'",
")",
"self",
".",
"timeout",
"=",
"timeout"
] | https://github.com/baidu/sofa-pbrpc/blob/fb1a1cbf0b3b0e09706eefdbca8335f48df2f5aa/python/sofa/pbrpc/client.py#L59-L64 |
||
eric612/Caffe-YOLOv3-Windows | 6736ca6e16781789b828cc64218ff77cc3454e5d | examples/pycaffe/layers/pascal_multilabel_datalayers.py | python | load_pascal_annotation | (index, pascal_root) | return {'boxes': boxes,
'gt_classes': gt_classes,
'gt_overlaps': overlaps,
'flipped': False,
'index': index} | This code is borrowed from Ross Girshick's FAST-RCNN code
(https://github.com/rbgirshick/fast-rcnn).
It parses the PASCAL .xml metadata files.
See publication for further details: (http://arxiv.org/abs/1504.08083).
Thanks Ross! | This code is borrowed from Ross Girshick's FAST-RCNN code
(https://github.com/rbgirshick/fast-rcnn).
It parses the PASCAL .xml metadata files.
See publication for further details: (http://arxiv.org/abs/1504.08083). | [
"This",
"code",
"is",
"borrowed",
"from",
"Ross",
"Girshick",
"s",
"FAST",
"-",
"RCNN",
"code",
"(",
"https",
":",
"//",
"github",
".",
"com",
"/",
"rbgirshick",
"/",
"fast",
"-",
"rcnn",
")",
".",
"It",
"parses",
"the",
"PASCAL",
".",
"xml",
"metadata",
"files",
".",
"See",
"publication",
"for",
"further",
"details",
":",
"(",
"http",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1504",
".",
"08083",
")",
"."
] | def load_pascal_annotation(index, pascal_root):
"""
This code is borrowed from Ross Girshick's FAST-RCNN code
(https://github.com/rbgirshick/fast-rcnn).
It parses the PASCAL .xml metadata files.
See publication for further details: (http://arxiv.org/abs/1504.08083).
Thanks Ross!
"""
classes = ('__background__', # always index 0
'aeroplane', 'bicycle', 'bird', 'boat',
'bottle', 'bus', 'car', 'cat', 'chair',
'cow', 'diningtable', 'dog', 'horse',
'motorbike', 'person', 'pottedplant',
'sheep', 'sofa', 'train', 'tvmonitor')
class_to_ind = dict(zip(classes, xrange(21)))
filename = osp.join(pascal_root, 'Annotations', index + '.xml')
# print 'Loading: {}'.format(filename)
def get_data_from_tag(node, tag):
return node.getElementsByTagName(tag)[0].childNodes[0].data
with open(filename) as f:
data = minidom.parseString(f.read())
objs = data.getElementsByTagName('object')
num_objs = len(objs)
boxes = np.zeros((num_objs, 4), dtype=np.uint16)
gt_classes = np.zeros((num_objs), dtype=np.int32)
overlaps = np.zeros((num_objs, 21), dtype=np.float32)
# Load object bounding boxes into a data frame.
for ix, obj in enumerate(objs):
# Make pixel indexes 0-based
x1 = float(get_data_from_tag(obj, 'xmin')) - 1
y1 = float(get_data_from_tag(obj, 'ymin')) - 1
x2 = float(get_data_from_tag(obj, 'xmax')) - 1
y2 = float(get_data_from_tag(obj, 'ymax')) - 1
cls = class_to_ind[
str(get_data_from_tag(obj, "name")).lower().strip()]
boxes[ix, :] = [x1, y1, x2, y2]
gt_classes[ix] = cls
overlaps[ix, cls] = 1.0
overlaps = scipy.sparse.csr_matrix(overlaps)
return {'boxes': boxes,
'gt_classes': gt_classes,
'gt_overlaps': overlaps,
'flipped': False,
'index': index} | [
"def",
"load_pascal_annotation",
"(",
"index",
",",
"pascal_root",
")",
":",
"classes",
"=",
"(",
"'__background__'",
",",
"# always index 0",
"'aeroplane'",
",",
"'bicycle'",
",",
"'bird'",
",",
"'boat'",
",",
"'bottle'",
",",
"'bus'",
",",
"'car'",
",",
"'cat'",
",",
"'chair'",
",",
"'cow'",
",",
"'diningtable'",
",",
"'dog'",
",",
"'horse'",
",",
"'motorbike'",
",",
"'person'",
",",
"'pottedplant'",
",",
"'sheep'",
",",
"'sofa'",
",",
"'train'",
",",
"'tvmonitor'",
")",
"class_to_ind",
"=",
"dict",
"(",
"zip",
"(",
"classes",
",",
"xrange",
"(",
"21",
")",
")",
")",
"filename",
"=",
"osp",
".",
"join",
"(",
"pascal_root",
",",
"'Annotations'",
",",
"index",
"+",
"'.xml'",
")",
"# print 'Loading: {}'.format(filename)",
"def",
"get_data_from_tag",
"(",
"node",
",",
"tag",
")",
":",
"return",
"node",
".",
"getElementsByTagName",
"(",
"tag",
")",
"[",
"0",
"]",
".",
"childNodes",
"[",
"0",
"]",
".",
"data",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"data",
"=",
"minidom",
".",
"parseString",
"(",
"f",
".",
"read",
"(",
")",
")",
"objs",
"=",
"data",
".",
"getElementsByTagName",
"(",
"'object'",
")",
"num_objs",
"=",
"len",
"(",
"objs",
")",
"boxes",
"=",
"np",
".",
"zeros",
"(",
"(",
"num_objs",
",",
"4",
")",
",",
"dtype",
"=",
"np",
".",
"uint16",
")",
"gt_classes",
"=",
"np",
".",
"zeros",
"(",
"(",
"num_objs",
")",
",",
"dtype",
"=",
"np",
".",
"int32",
")",
"overlaps",
"=",
"np",
".",
"zeros",
"(",
"(",
"num_objs",
",",
"21",
")",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"# Load object bounding boxes into a data frame.",
"for",
"ix",
",",
"obj",
"in",
"enumerate",
"(",
"objs",
")",
":",
"# Make pixel indexes 0-based",
"x1",
"=",
"float",
"(",
"get_data_from_tag",
"(",
"obj",
",",
"'xmin'",
")",
")",
"-",
"1",
"y1",
"=",
"float",
"(",
"get_data_from_tag",
"(",
"obj",
",",
"'ymin'",
")",
")",
"-",
"1",
"x2",
"=",
"float",
"(",
"get_data_from_tag",
"(",
"obj",
",",
"'xmax'",
")",
")",
"-",
"1",
"y2",
"=",
"float",
"(",
"get_data_from_tag",
"(",
"obj",
",",
"'ymax'",
")",
")",
"-",
"1",
"cls",
"=",
"class_to_ind",
"[",
"str",
"(",
"get_data_from_tag",
"(",
"obj",
",",
"\"name\"",
")",
")",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"]",
"boxes",
"[",
"ix",
",",
":",
"]",
"=",
"[",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
"]",
"gt_classes",
"[",
"ix",
"]",
"=",
"cls",
"overlaps",
"[",
"ix",
",",
"cls",
"]",
"=",
"1.0",
"overlaps",
"=",
"scipy",
".",
"sparse",
".",
"csr_matrix",
"(",
"overlaps",
")",
"return",
"{",
"'boxes'",
":",
"boxes",
",",
"'gt_classes'",
":",
"gt_classes",
",",
"'gt_overlaps'",
":",
"overlaps",
",",
"'flipped'",
":",
"False",
",",
"'index'",
":",
"index",
"}"
] | https://github.com/eric612/Caffe-YOLOv3-Windows/blob/6736ca6e16781789b828cc64218ff77cc3454e5d/examples/pycaffe/layers/pascal_multilabel_datalayers.py#L140-L193 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/jedi/jedi/evaluate/context/iterable.py | python | ComprehensionMixin._get_comp_for | (self) | return self._get_comprehension().children[1] | return CompFor('for a in b') | return CompFor('for a in b') | [
"return",
"CompFor",
"(",
"for",
"a",
"in",
"b",
")"
] | def _get_comp_for(self):
"return CompFor('for a in b')"
return self._get_comprehension().children[1] | [
"def",
"_get_comp_for",
"(",
"self",
")",
":",
"return",
"self",
".",
"_get_comprehension",
"(",
")",
".",
"children",
"[",
"1",
"]"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/jedi/jedi/evaluate/context/iterable.py#L118-L120 |
|
eerolanguage/clang | 91360bee004a1cbdb95fe5eb605ef243152da41b | bindings/python/clang/cindex.py | python | SourceRange.__contains__ | (self, other) | return False | Useful to detect the Token/Lexer bug | Useful to detect the Token/Lexer bug | [
"Useful",
"to",
"detect",
"the",
"Token",
"/",
"Lexer",
"bug"
] | def __contains__(self, other):
"""Useful to detect the Token/Lexer bug"""
if not isinstance(other, SourceLocation):
return False
if other.file is None and self.start.file is None:
pass
elif ( self.start.file.name != other.file.name or
other.file.name != self.end.file.name):
# same file name
return False
# same file, in between lines
if self.start.line < other.line < self.end.line:
return True
elif self.start.line == other.line:
# same file first line
if self.start.column <= other.column:
return True
elif other.line == self.end.line:
# same file last line
if other.column <= self.end.column:
return True
return False | [
"def",
"__contains__",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"SourceLocation",
")",
":",
"return",
"False",
"if",
"other",
".",
"file",
"is",
"None",
"and",
"self",
".",
"start",
".",
"file",
"is",
"None",
":",
"pass",
"elif",
"(",
"self",
".",
"start",
".",
"file",
".",
"name",
"!=",
"other",
".",
"file",
".",
"name",
"or",
"other",
".",
"file",
".",
"name",
"!=",
"self",
".",
"end",
".",
"file",
".",
"name",
")",
":",
"# same file name",
"return",
"False",
"# same file, in between lines",
"if",
"self",
".",
"start",
".",
"line",
"<",
"other",
".",
"line",
"<",
"self",
".",
"end",
".",
"line",
":",
"return",
"True",
"elif",
"self",
".",
"start",
".",
"line",
"==",
"other",
".",
"line",
":",
"# same file first line",
"if",
"self",
".",
"start",
".",
"column",
"<=",
"other",
".",
"column",
":",
"return",
"True",
"elif",
"other",
".",
"line",
"==",
"self",
".",
"end",
".",
"line",
":",
"# same file last line",
"if",
"other",
".",
"column",
"<=",
"self",
".",
"end",
".",
"column",
":",
"return",
"True",
"return",
"False"
] | https://github.com/eerolanguage/clang/blob/91360bee004a1cbdb95fe5eb605ef243152da41b/bindings/python/clang/cindex.py#L269-L290 |
|
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/variables.py | python | RefVariable.scatter_min | (self, sparse_delta, use_locking=False, name=None) | return gen_state_ops.scatter_min(
self._variable,
sparse_delta.indices,
sparse_delta.values,
use_locking=use_locking,
name=name) | Updates this variable with the min of `tf.IndexedSlices` and itself.
Args:
sparse_delta: `tf.IndexedSlices` to use as an argument of min with this
variable.
use_locking: If `True`, use locking during the operation.
name: the name of the operation.
Returns:
A `Tensor` that will hold the new value of this variable after
the scattered minimization has completed.
Raises:
TypeError: if `sparse_delta` is not an `IndexedSlices`. | Updates this variable with the min of `tf.IndexedSlices` and itself. | [
"Updates",
"this",
"variable",
"with",
"the",
"min",
"of",
"tf",
".",
"IndexedSlices",
"and",
"itself",
"."
] | def scatter_min(self, sparse_delta, use_locking=False, name=None):
"""Updates this variable with the min of `tf.IndexedSlices` and itself.
Args:
sparse_delta: `tf.IndexedSlices` to use as an argument of min with this
variable.
use_locking: If `True`, use locking during the operation.
name: the name of the operation.
Returns:
A `Tensor` that will hold the new value of this variable after
the scattered minimization has completed.
Raises:
TypeError: if `sparse_delta` is not an `IndexedSlices`.
"""
if not isinstance(sparse_delta, indexed_slices.IndexedSlices):
raise TypeError("sparse_delta is not IndexedSlices: %s" % sparse_delta)
return gen_state_ops.scatter_min(
self._variable,
sparse_delta.indices,
sparse_delta.values,
use_locking=use_locking,
name=name) | [
"def",
"scatter_min",
"(",
"self",
",",
"sparse_delta",
",",
"use_locking",
"=",
"False",
",",
"name",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"sparse_delta",
",",
"indexed_slices",
".",
"IndexedSlices",
")",
":",
"raise",
"TypeError",
"(",
"\"sparse_delta is not IndexedSlices: %s\"",
"%",
"sparse_delta",
")",
"return",
"gen_state_ops",
".",
"scatter_min",
"(",
"self",
".",
"_variable",
",",
"sparse_delta",
".",
"indices",
",",
"sparse_delta",
".",
"values",
",",
"use_locking",
"=",
"use_locking",
",",
"name",
"=",
"name",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/variables.py#L2172-L2195 |
|
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Path/PathScripts/PathOpGui.py | python | TaskPanelPage.onDirtyChanged | (self, callback) | onDirtyChanged(callback) ... set callback when dirty state changes. | onDirtyChanged(callback) ... set callback when dirty state changes. | [
"onDirtyChanged",
"(",
"callback",
")",
"...",
"set",
"callback",
"when",
"dirty",
"state",
"changes",
"."
] | def onDirtyChanged(self, callback):
"""onDirtyChanged(callback) ... set callback when dirty state changes."""
self.signalDirtyChanged = callback | [
"def",
"onDirtyChanged",
"(",
"self",
",",
"callback",
")",
":",
"self",
".",
"signalDirtyChanged",
"=",
"callback"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathOpGui.py#L224-L226 |
||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/formats/format.py | python | DataFrameFormatter.to_latex | (
self,
buf: Optional[FilePathOrBuffer[str]] = None,
column_format: Optional[str] = None,
longtable: bool = False,
encoding: Optional[str] = None,
multicolumn: bool = False,
multicolumn_format: Optional[str] = None,
multirow: bool = False,
caption: Optional[str] = None,
label: Optional[str] = None,
) | return LatexFormatter(
self,
column_format=column_format,
longtable=longtable,
multicolumn=multicolumn,
multicolumn_format=multicolumn_format,
multirow=multirow,
caption=caption,
label=label,
).get_result(buf=buf, encoding=encoding) | Render a DataFrame to a LaTeX tabular/longtable environment output. | Render a DataFrame to a LaTeX tabular/longtable environment output. | [
"Render",
"a",
"DataFrame",
"to",
"a",
"LaTeX",
"tabular",
"/",
"longtable",
"environment",
"output",
"."
] | def to_latex(
self,
buf: Optional[FilePathOrBuffer[str]] = None,
column_format: Optional[str] = None,
longtable: bool = False,
encoding: Optional[str] = None,
multicolumn: bool = False,
multicolumn_format: Optional[str] = None,
multirow: bool = False,
caption: Optional[str] = None,
label: Optional[str] = None,
) -> Optional[str]:
"""
Render a DataFrame to a LaTeX tabular/longtable environment output.
"""
from pandas.io.formats.latex import LatexFormatter
return LatexFormatter(
self,
column_format=column_format,
longtable=longtable,
multicolumn=multicolumn,
multicolumn_format=multicolumn_format,
multirow=multirow,
caption=caption,
label=label,
).get_result(buf=buf, encoding=encoding) | [
"def",
"to_latex",
"(",
"self",
",",
"buf",
":",
"Optional",
"[",
"FilePathOrBuffer",
"[",
"str",
"]",
"]",
"=",
"None",
",",
"column_format",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"longtable",
":",
"bool",
"=",
"False",
",",
"encoding",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"multicolumn",
":",
"bool",
"=",
"False",
",",
"multicolumn_format",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"multirow",
":",
"bool",
"=",
"False",
",",
"caption",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"label",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"from",
"pandas",
".",
"io",
".",
"formats",
".",
"latex",
"import",
"LatexFormatter",
"return",
"LatexFormatter",
"(",
"self",
",",
"column_format",
"=",
"column_format",
",",
"longtable",
"=",
"longtable",
",",
"multicolumn",
"=",
"multicolumn",
",",
"multicolumn_format",
"=",
"multicolumn_format",
",",
"multirow",
"=",
"multirow",
",",
"caption",
"=",
"caption",
",",
"label",
"=",
"label",
",",
")",
".",
"get_result",
"(",
"buf",
"=",
"buf",
",",
"encoding",
"=",
"encoding",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/formats/format.py#L916-L943 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/linalg/basic.py | python | pinv2 | (a, cond=None, rcond=None, return_rank=False, check_finite=True) | Compute the (Moore-Penrose) pseudo-inverse of a matrix.
Calculate a generalized inverse of a matrix using its
singular-value decomposition and including all 'large' singular
values.
Parameters
----------
a : (M, N) array_like
Matrix to be pseudo-inverted.
cond, rcond : float or None
Cutoff for 'small' singular values.
Singular values smaller than ``rcond*largest_singular_value``
are considered zero.
If None or -1, suitable machine precision is used.
return_rank : bool, optional
if True, return the effective rank of the matrix
check_finite : bool, optional
Whether to check that the input matrix contains only finite numbers.
Disabling may give a performance gain, but may result in problems
(crashes, non-termination) if the inputs do contain infinities or NaNs.
Returns
-------
B : (N, M) ndarray
The pseudo-inverse of matrix `a`.
rank : int
The effective rank of the matrix. Returned if return_rank == True
Raises
------
LinAlgError
If SVD computation does not converge.
Examples
--------
>>> from scipy import linalg
>>> a = np.random.randn(9, 6)
>>> B = linalg.pinv2(a)
>>> np.allclose(a, np.dot(a, np.dot(B, a)))
True
>>> np.allclose(B, np.dot(B, np.dot(a, B)))
True | Compute the (Moore-Penrose) pseudo-inverse of a matrix. | [
"Compute",
"the",
"(",
"Moore",
"-",
"Penrose",
")",
"pseudo",
"-",
"inverse",
"of",
"a",
"matrix",
"."
] | def pinv2(a, cond=None, rcond=None, return_rank=False, check_finite=True):
"""
Compute the (Moore-Penrose) pseudo-inverse of a matrix.
Calculate a generalized inverse of a matrix using its
singular-value decomposition and including all 'large' singular
values.
Parameters
----------
a : (M, N) array_like
Matrix to be pseudo-inverted.
cond, rcond : float or None
Cutoff for 'small' singular values.
Singular values smaller than ``rcond*largest_singular_value``
are considered zero.
If None or -1, suitable machine precision is used.
return_rank : bool, optional
if True, return the effective rank of the matrix
check_finite : bool, optional
Whether to check that the input matrix contains only finite numbers.
Disabling may give a performance gain, but may result in problems
(crashes, non-termination) if the inputs do contain infinities or NaNs.
Returns
-------
B : (N, M) ndarray
The pseudo-inverse of matrix `a`.
rank : int
The effective rank of the matrix. Returned if return_rank == True
Raises
------
LinAlgError
If SVD computation does not converge.
Examples
--------
>>> from scipy import linalg
>>> a = np.random.randn(9, 6)
>>> B = linalg.pinv2(a)
>>> np.allclose(a, np.dot(a, np.dot(B, a)))
True
>>> np.allclose(B, np.dot(B, np.dot(a, B)))
True
"""
a = _asarray_validated(a, check_finite=check_finite)
u, s, vh = decomp_svd.svd(a, full_matrices=False, check_finite=False)
if rcond is not None:
cond = rcond
if cond in [None, -1]:
t = u.dtype.char.lower()
factor = {'f': 1E3, 'd': 1E6}
cond = factor[t] * np.finfo(t).eps
rank = np.sum(s > cond * np.max(s))
u = u[:, :rank]
u /= s[:rank]
B = np.transpose(np.conjugate(np.dot(u, vh[:rank])))
if return_rank:
return B, rank
else:
return B | [
"def",
"pinv2",
"(",
"a",
",",
"cond",
"=",
"None",
",",
"rcond",
"=",
"None",
",",
"return_rank",
"=",
"False",
",",
"check_finite",
"=",
"True",
")",
":",
"a",
"=",
"_asarray_validated",
"(",
"a",
",",
"check_finite",
"=",
"check_finite",
")",
"u",
",",
"s",
",",
"vh",
"=",
"decomp_svd",
".",
"svd",
"(",
"a",
",",
"full_matrices",
"=",
"False",
",",
"check_finite",
"=",
"False",
")",
"if",
"rcond",
"is",
"not",
"None",
":",
"cond",
"=",
"rcond",
"if",
"cond",
"in",
"[",
"None",
",",
"-",
"1",
"]",
":",
"t",
"=",
"u",
".",
"dtype",
".",
"char",
".",
"lower",
"(",
")",
"factor",
"=",
"{",
"'f'",
":",
"1E3",
",",
"'d'",
":",
"1E6",
"}",
"cond",
"=",
"factor",
"[",
"t",
"]",
"*",
"np",
".",
"finfo",
"(",
"t",
")",
".",
"eps",
"rank",
"=",
"np",
".",
"sum",
"(",
"s",
">",
"cond",
"*",
"np",
".",
"max",
"(",
"s",
")",
")",
"u",
"=",
"u",
"[",
":",
",",
":",
"rank",
"]",
"u",
"/=",
"s",
"[",
":",
"rank",
"]",
"B",
"=",
"np",
".",
"transpose",
"(",
"np",
".",
"conjugate",
"(",
"np",
".",
"dot",
"(",
"u",
",",
"vh",
"[",
":",
"rank",
"]",
")",
")",
")",
"if",
"return_rank",
":",
"return",
"B",
",",
"rank",
"else",
":",
"return",
"B"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/linalg/basic.py#L985-L1051 |
||
bh107/bohrium | 5b83e7117285fefc7779ed0e9acb0f8e74c7e068 | bridge/bh107/bh107/array_create.py | python | array | (obj, dtype=None, copy=False) | Create an BhArray.
Parameters
----------
obj : array_like
An array, any object exposing the array interface, an
object whose __array__ method returns an array, or any
(nested) sequence.
dtype : data-type, optional
The desired data-type for the array. If not given, then
the type will be determined as the minimum type required
to hold the objects in the sequence. This argument can only
be used to 'upcast' the array. For downcasting, use the
.astype(t) method.
copy : bool, optional
If true, then the object is copied. Otherwise, a copy
will only be made if obj isn't a BhArray of the correct dtype already
Returns
-------
out : BhArray
An array of dtype.
See Also
--------
empty, empty_like, zeros, zeros_like, ones, ones_like, fill
Examples
--------
>>> bh.array([1, 2, 3])
array([1, 2, 3])
Upcasting:
>>> bh.array([1, 2, 3.0])
array([ 1., 2., 3.])
More than one dimension:
>>> bh.array([[1, 2], [3, 4]])
array([[1, 2],
[3, 4]])
Type provided:
>>> bh.array([1, 2, 3], dtype=complex)
array([ 1.+0.j, 2.+0.j, 3.+0.j]) | Create an BhArray. | [
"Create",
"an",
"BhArray",
"."
] | def array(obj, dtype=None, copy=False):
"""
Create an BhArray.
Parameters
----------
obj : array_like
An array, any object exposing the array interface, an
object whose __array__ method returns an array, or any
(nested) sequence.
dtype : data-type, optional
The desired data-type for the array. If not given, then
the type will be determined as the minimum type required
to hold the objects in the sequence. This argument can only
be used to 'upcast' the array. For downcasting, use the
.astype(t) method.
copy : bool, optional
If true, then the object is copied. Otherwise, a copy
will only be made if obj isn't a BhArray of the correct dtype already
Returns
-------
out : BhArray
An array of dtype.
See Also
--------
empty, empty_like, zeros, zeros_like, ones, ones_like, fill
Examples
--------
>>> bh.array([1, 2, 3])
array([1, 2, 3])
Upcasting:
>>> bh.array([1, 2, 3.0])
array([ 1., 2., 3.])
More than one dimension:
>>> bh.array([[1, 2], [3, 4]])
array([[1, 2],
[3, 4]])
Type provided:
>>> bh.array([1, 2, 3], dtype=complex)
array([ 1.+0.j, 2.+0.j, 3.+0.j])
"""
if isinstance(obj, bharray.BhArray):
if dtype is None:
dtype = obj.dtype
return obj.astype(dtype, always_copy=copy)
else:
return bharray.BhArray.from_object(obj) | [
"def",
"array",
"(",
"obj",
",",
"dtype",
"=",
"None",
",",
"copy",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"bharray",
".",
"BhArray",
")",
":",
"if",
"dtype",
"is",
"None",
":",
"dtype",
"=",
"obj",
".",
"dtype",
"return",
"obj",
".",
"astype",
"(",
"dtype",
",",
"always_copy",
"=",
"copy",
")",
"else",
":",
"return",
"bharray",
".",
"BhArray",
".",
"from_object",
"(",
"obj",
")"
] | https://github.com/bh107/bohrium/blob/5b83e7117285fefc7779ed0e9acb0f8e74c7e068/bridge/bh107/bh107/array_create.py#L13-L69 |
||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/communication/management.py | python | _check_parallel_envs | () | Check whether parallel environment variables have been exported or not.
Raises:
RuntimeError: If parallel environment variables have not been exported or have been exported to wrong values. | Check whether parallel environment variables have been exported or not. | [
"Check",
"whether",
"parallel",
"environment",
"variables",
"have",
"been",
"exported",
"or",
"not",
"."
] | def _check_parallel_envs():
"""
Check whether parallel environment variables have been exported or not.
Raises:
RuntimeError: If parallel environment variables have not been exported or have been exported to wrong values.
"""
if not GlobalComm.CHECK_ENVS:
return
import os
rank_id_str = os.getenv("RANK_ID")
if not rank_id_str:
raise RuntimeError("Environment variables RANK_ID has not been exported, please export variables 'RANK_ID'.")
try:
int(rank_id_str)
except ValueError:
print("Environment variables 'RANK_ID' should be number, but got the type : {}".format(type(rank_id_str)))
finally:
pass
rank_table_file_str = os.getenv("MINDSPORE_HCCL_CONFIG_PATH")
rank_table_file_str_old = os.getenv("RANK_TABLE_FILE")
if not rank_table_file_str and not rank_table_file_str_old:
raise RuntimeError("Get hccl rank_table_file failed, "
"please export MINDSPORE_HCCL_CONFIG_PATH or RANK_TABLE_FILE.") | [
"def",
"_check_parallel_envs",
"(",
")",
":",
"if",
"not",
"GlobalComm",
".",
"CHECK_ENVS",
":",
"return",
"import",
"os",
"rank_id_str",
"=",
"os",
".",
"getenv",
"(",
"\"RANK_ID\"",
")",
"if",
"not",
"rank_id_str",
":",
"raise",
"RuntimeError",
"(",
"\"Environment variables RANK_ID has not been exported, please export variables 'RANK_ID'.\"",
")",
"try",
":",
"int",
"(",
"rank_id_str",
")",
"except",
"ValueError",
":",
"print",
"(",
"\"Environment variables 'RANK_ID' should be number, but got the type : {}\"",
".",
"format",
"(",
"type",
"(",
"rank_id_str",
")",
")",
")",
"finally",
":",
"pass",
"rank_table_file_str",
"=",
"os",
".",
"getenv",
"(",
"\"MINDSPORE_HCCL_CONFIG_PATH\"",
")",
"rank_table_file_str_old",
"=",
"os",
".",
"getenv",
"(",
"\"RANK_TABLE_FILE\"",
")",
"if",
"not",
"rank_table_file_str",
"and",
"not",
"rank_table_file_str_old",
":",
"raise",
"RuntimeError",
"(",
"\"Get hccl rank_table_file failed, \"",
"\"please export MINDSPORE_HCCL_CONFIG_PATH or RANK_TABLE_FILE.\"",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/communication/management.py#L59-L82 |
||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/index/collector.py | python | _match_vcs_scheme | (url) | return None | Look for VCS schemes in the URL.
Returns the matched VCS scheme, or None if there's no match. | Look for VCS schemes in the URL. | [
"Look",
"for",
"VCS",
"schemes",
"in",
"the",
"URL",
"."
] | def _match_vcs_scheme(url):
# type: (str) -> Optional[str]
"""Look for VCS schemes in the URL.
Returns the matched VCS scheme, or None if there's no match.
"""
for scheme in vcs.schemes:
if url.lower().startswith(scheme) and url[len(scheme)] in '+:':
return scheme
return None | [
"def",
"_match_vcs_scheme",
"(",
"url",
")",
":",
"# type: (str) -> Optional[str]",
"for",
"scheme",
"in",
"vcs",
".",
"schemes",
":",
"if",
"url",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"scheme",
")",
"and",
"url",
"[",
"len",
"(",
"scheme",
")",
"]",
"in",
"'+:'",
":",
"return",
"scheme",
"return",
"None"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/index/collector.py#L109-L127 |
|
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | toolkit/components/telemetry/histogram_tools.py | python | Histogram.kind | (self) | return self._kind | Return the kind of the histogram.
Will be one of 'boolean', 'flag', 'count', 'enumerated', 'linear', or 'exponential'. | Return the kind of the histogram.
Will be one of 'boolean', 'flag', 'count', 'enumerated', 'linear', or 'exponential'. | [
"Return",
"the",
"kind",
"of",
"the",
"histogram",
".",
"Will",
"be",
"one",
"of",
"boolean",
"flag",
"count",
"enumerated",
"linear",
"or",
"exponential",
"."
] | def kind(self):
"""Return the kind of the histogram.
Will be one of 'boolean', 'flag', 'count', 'enumerated', 'linear', or 'exponential'."""
return self._kind | [
"def",
"kind",
"(",
"self",
")",
":",
"return",
"self",
".",
"_kind"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/toolkit/components/telemetry/histogram_tools.py#L100-L103 |
|
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/fx/experimental/partitioner_utils.py | python | get_extra_size_of | (node: Node, nodes: Set[Node]) | return total_size_of_input_nodes | Given a node and a set of nodes,
this function return the extra size that needed
if this node is included in this set. | Given a node and a set of nodes,
this function return the extra size that needed
if this node is included in this set. | [
"Given",
"a",
"node",
"and",
"a",
"set",
"of",
"nodes",
"this",
"function",
"return",
"the",
"extra",
"size",
"that",
"needed",
"if",
"this",
"node",
"is",
"included",
"in",
"this",
"set",
"."
] | def get_extra_size_of(node: Node, nodes: Set[Node]) -> int:
"""Given a node and a set of nodes,
this function return the extra size that needed
if this node is included in this set.
"""
# Find all its input nodes
input_nodes: Dict[Node, None] = {}
map_arg(node.args, lambda n: input_nodes.setdefault(n))
map_arg(node.kwargs, lambda n: input_nodes.setdefault(n))
# Calculate total size of related nodes
total_size_of_input_nodes = 0
for n in input_nodes:
# Make sure this node hasn't been in this set yet
if n not in nodes:
size_bytes = getattr(n, "size_bytes", None)
if size_bytes:
total_size_of_input_nodes += size_bytes.output_size
else:
raise RuntimeError("node has no size_bytes attr")
# Don't forget the op node itself
size_bytes = getattr(node, "size_bytes", None)
if size_bytes:
total_size_of_input_nodes += size_bytes.total_size
else:
raise RuntimeError("node has no size_bytes attr")
return total_size_of_input_nodes | [
"def",
"get_extra_size_of",
"(",
"node",
":",
"Node",
",",
"nodes",
":",
"Set",
"[",
"Node",
"]",
")",
"->",
"int",
":",
"# Find all its input nodes",
"input_nodes",
":",
"Dict",
"[",
"Node",
",",
"None",
"]",
"=",
"{",
"}",
"map_arg",
"(",
"node",
".",
"args",
",",
"lambda",
"n",
":",
"input_nodes",
".",
"setdefault",
"(",
"n",
")",
")",
"map_arg",
"(",
"node",
".",
"kwargs",
",",
"lambda",
"n",
":",
"input_nodes",
".",
"setdefault",
"(",
"n",
")",
")",
"# Calculate total size of related nodes",
"total_size_of_input_nodes",
"=",
"0",
"for",
"n",
"in",
"input_nodes",
":",
"# Make sure this node hasn't been in this set yet",
"if",
"n",
"not",
"in",
"nodes",
":",
"size_bytes",
"=",
"getattr",
"(",
"n",
",",
"\"size_bytes\"",
",",
"None",
")",
"if",
"size_bytes",
":",
"total_size_of_input_nodes",
"+=",
"size_bytes",
".",
"output_size",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"node has no size_bytes attr\"",
")",
"# Don't forget the op node itself",
"size_bytes",
"=",
"getattr",
"(",
"node",
",",
"\"size_bytes\"",
",",
"None",
")",
"if",
"size_bytes",
":",
"total_size_of_input_nodes",
"+=",
"size_bytes",
".",
"total_size",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"node has no size_bytes attr\"",
")",
"return",
"total_size_of_input_nodes"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/fx/experimental/partitioner_utils.py#L100-L125 |
|
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/random.py | python | WichmannHill.seed | (self, a=None) | Initialize internal state from hashable object.
None or no argument seeds from current time or from an operating
system specific randomness source if available.
If a is not None or an int or long, hash(a) is used instead.
If a is an int or long, a is used directly. Distinct values between
0 and 27814431486575L inclusive are guaranteed to yield distinct
internal states (this guarantee is specific to the default
Wichmann-Hill generator). | Initialize internal state from hashable object. | [
"Initialize",
"internal",
"state",
"from",
"hashable",
"object",
"."
] | def seed(self, a=None):
"""Initialize internal state from hashable object.
None or no argument seeds from current time or from an operating
system specific randomness source if available.
If a is not None or an int or long, hash(a) is used instead.
If a is an int or long, a is used directly. Distinct values between
0 and 27814431486575L inclusive are guaranteed to yield distinct
internal states (this guarantee is specific to the default
Wichmann-Hill generator).
"""
if a is None:
try:
a = long(_hexlify(_urandom(16)), 16)
except NotImplementedError:
import time
a = long(time.time() * 256) # use fractional seconds
if not isinstance(a, (int, long)):
a = hash(a)
a, x = divmod(a, 30268)
a, y = divmod(a, 30306)
a, z = divmod(a, 30322)
self._seed = int(x)+1, int(y)+1, int(z)+1
self.gauss_next = None | [
"def",
"seed",
"(",
"self",
",",
"a",
"=",
"None",
")",
":",
"if",
"a",
"is",
"None",
":",
"try",
":",
"a",
"=",
"long",
"(",
"_hexlify",
"(",
"_urandom",
"(",
"16",
")",
")",
",",
"16",
")",
"except",
"NotImplementedError",
":",
"import",
"time",
"a",
"=",
"long",
"(",
"time",
".",
"time",
"(",
")",
"*",
"256",
")",
"# use fractional seconds",
"if",
"not",
"isinstance",
"(",
"a",
",",
"(",
"int",
",",
"long",
")",
")",
":",
"a",
"=",
"hash",
"(",
"a",
")",
"a",
",",
"x",
"=",
"divmod",
"(",
"a",
",",
"30268",
")",
"a",
",",
"y",
"=",
"divmod",
"(",
"a",
",",
"30306",
")",
"a",
",",
"z",
"=",
"divmod",
"(",
"a",
",",
"30322",
")",
"self",
".",
"_seed",
"=",
"int",
"(",
"x",
")",
"+",
"1",
",",
"int",
"(",
"y",
")",
"+",
"1",
",",
"int",
"(",
"z",
")",
"+",
"1",
"self",
".",
"gauss_next",
"=",
"None"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/random.py#L653-L682 |
||
lighttransport/nanort | 74063967336311f54ede5dffdfa242123825033b | deps/cpplint.py | python | PrintUsage | (message) | Prints a brief usage string and exits, optionally with an error message.
Args:
message: The optional error message. | Prints a brief usage string and exits, optionally with an error message. | [
"Prints",
"a",
"brief",
"usage",
"string",
"and",
"exits",
"optionally",
"with",
"an",
"error",
"message",
"."
] | def PrintUsage(message):
"""Prints a brief usage string and exits, optionally with an error message.
Args:
message: The optional error message.
"""
sys.stderr.write(_USAGE)
if message:
sys.exit('\nFATAL ERROR: ' + message)
else:
sys.exit(1) | [
"def",
"PrintUsage",
"(",
"message",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"_USAGE",
")",
"if",
"message",
":",
"sys",
".",
"exit",
"(",
"'\\nFATAL ERROR: '",
"+",
"message",
")",
"else",
":",
"sys",
".",
"exit",
"(",
"1",
")"
] | https://github.com/lighttransport/nanort/blob/74063967336311f54ede5dffdfa242123825033b/deps/cpplint.py#L6212-L6222 |
||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/propgrid.py | python | PropertyGridEvent.GetColumn | (*args, **kwargs) | return _propgrid.PropertyGridEvent_GetColumn(*args, **kwargs) | GetColumn(self) -> int | GetColumn(self) -> int | [
"GetColumn",
"(",
"self",
")",
"-",
">",
"int"
] | def GetColumn(*args, **kwargs):
"""GetColumn(self) -> int"""
return _propgrid.PropertyGridEvent_GetColumn(*args, **kwargs) | [
"def",
"GetColumn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PropertyGridEvent_GetColumn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/propgrid.py#L2509-L2511 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/linalg/_interpolative_backend.py | python | idz_findrank | (eps, m, n, matveca) | return k | Estimate rank of a complex matrix to a specified relative precision using
random matrix-vector multiplication.
:param eps:
Relative precision.
:type eps: float
:param m:
Matrix row dimension.
:type m: int
:param n:
Matrix column dimension.
:type n: int
:param matveca:
Function to apply the matrix adjoint to a vector, with call signature
`y = matveca(x)`, where `x` and `y` are the input and output vectors,
respectively.
:type matveca: function
:return:
Rank estimate.
:rtype: int | Estimate rank of a complex matrix to a specified relative precision using
random matrix-vector multiplication. | [
"Estimate",
"rank",
"of",
"a",
"complex",
"matrix",
"to",
"a",
"specified",
"relative",
"precision",
"using",
"random",
"matrix",
"-",
"vector",
"multiplication",
"."
] | def idz_findrank(eps, m, n, matveca):
"""
Estimate rank of a complex matrix to a specified relative precision using
random matrix-vector multiplication.
:param eps:
Relative precision.
:type eps: float
:param m:
Matrix row dimension.
:type m: int
:param n:
Matrix column dimension.
:type n: int
:param matveca:
Function to apply the matrix adjoint to a vector, with call signature
`y = matveca(x)`, where `x` and `y` are the input and output vectors,
respectively.
:type matveca: function
:return:
Rank estimate.
:rtype: int
"""
k, ra, ier = _id.idz_findrank(eps, m, n, matveca)
if ier:
raise _RETCODE_ERROR
return k | [
"def",
"idz_findrank",
"(",
"eps",
",",
"m",
",",
"n",
",",
"matveca",
")",
":",
"k",
",",
"ra",
",",
"ier",
"=",
"_id",
".",
"idz_findrank",
"(",
"eps",
",",
"m",
",",
"n",
",",
"matveca",
")",
"if",
"ier",
":",
"raise",
"_RETCODE_ERROR",
"return",
"k"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/linalg/_interpolative_backend.py#L1421-L1448 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | RealPoint.__sub__ | (*args, **kwargs) | return _core_.RealPoint___sub__(*args, **kwargs) | __sub__(self, RealPoint pt) -> RealPoint
Subtract pt's properties from this and return the result. | __sub__(self, RealPoint pt) -> RealPoint | [
"__sub__",
"(",
"self",
"RealPoint",
"pt",
")",
"-",
">",
"RealPoint"
] | def __sub__(*args, **kwargs):
"""
__sub__(self, RealPoint pt) -> RealPoint
Subtract pt's properties from this and return the result.
"""
return _core_.RealPoint___sub__(*args, **kwargs) | [
"def",
"__sub__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"RealPoint___sub__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L1119-L1125 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/sparse/generate_sparsetools.py | python | parse_routine | (name, args, types) | return thunk_code, method_code | Generate thunk and method code for a given routine.
Parameters
----------
name : str
Name of the C++ routine
args : str
Argument list specification (in format explained above)
types : list
List of types to instantiate, as returned `get_thunk_type_set` | Generate thunk and method code for a given routine. | [
"Generate",
"thunk",
"and",
"method",
"code",
"for",
"a",
"given",
"routine",
"."
] | def parse_routine(name, args, types):
"""
Generate thunk and method code for a given routine.
Parameters
----------
name : str
Name of the C++ routine
args : str
Argument list specification (in format explained above)
types : list
List of types to instantiate, as returned `get_thunk_type_set`
"""
ret_spec = args[0]
arg_spec = args[1:]
def get_arglist(I_type, T_type):
"""
Generate argument list for calling the C++ function
"""
args = []
next_is_writeable = False
j = 0
for t in arg_spec:
const = '' if next_is_writeable else 'const '
next_is_writeable = False
if t == '*':
next_is_writeable = True
continue
elif t == 'i':
args.append("*(%s*)a[%d]" % (const + I_type, j))
elif t == 'I':
args.append("(%s*)a[%d]" % (const + I_type, j))
elif t == 'T':
args.append("(%s*)a[%d]" % (const + T_type, j))
elif t == 'B':
args.append("(npy_bool_wrapper*)a[%d]" % (j,))
elif t == 'V':
if const:
raise ValueError("'V' argument must be an output arg")
args.append("(std::vector<%s>*)a[%d]" % (I_type, j,))
elif t == 'W':
if const:
raise ValueError("'W' argument must be an output arg")
args.append("(std::vector<%s>*)a[%d]" % (T_type, j,))
else:
raise ValueError("Invalid spec character %r" % (t,))
j += 1
return ", ".join(args)
# Generate thunk code: a giant switch statement with different
# type combinations inside.
thunk_content = """int j = get_thunk_case(I_typenum, T_typenum);
switch (j) {"""
for j, I_typenum, T_typenum, I_type, T_type in types:
arglist = get_arglist(I_type, T_type)
if T_type is None:
dispatch = "%s" % (I_type,)
else:
dispatch = "%s,%s" % (I_type, T_type)
if 'B' in arg_spec:
dispatch += ",npy_bool_wrapper"
piece = """
case %(j)s:"""
if ret_spec == 'v':
piece += """
(void)%(name)s<%(dispatch)s>(%(arglist)s);
return 0;"""
else:
piece += """
return %(name)s<%(dispatch)s>(%(arglist)s);"""
thunk_content += piece % dict(j=j, I_type=I_type, T_type=T_type,
I_typenum=I_typenum, T_typenum=T_typenum,
arglist=arglist, name=name,
dispatch=dispatch)
thunk_content += """
default:
throw std::runtime_error("internal error: invalid argument typenums");
}"""
thunk_code = THUNK_TEMPLATE % dict(name=name,
thunk_content=thunk_content)
# Generate method code
method_code = METHOD_TEMPLATE % dict(name=name,
ret_spec=ret_spec,
arg_spec=arg_spec)
return thunk_code, method_code | [
"def",
"parse_routine",
"(",
"name",
",",
"args",
",",
"types",
")",
":",
"ret_spec",
"=",
"args",
"[",
"0",
"]",
"arg_spec",
"=",
"args",
"[",
"1",
":",
"]",
"def",
"get_arglist",
"(",
"I_type",
",",
"T_type",
")",
":",
"\"\"\"\n Generate argument list for calling the C++ function\n \"\"\"",
"args",
"=",
"[",
"]",
"next_is_writeable",
"=",
"False",
"j",
"=",
"0",
"for",
"t",
"in",
"arg_spec",
":",
"const",
"=",
"''",
"if",
"next_is_writeable",
"else",
"'const '",
"next_is_writeable",
"=",
"False",
"if",
"t",
"==",
"'*'",
":",
"next_is_writeable",
"=",
"True",
"continue",
"elif",
"t",
"==",
"'i'",
":",
"args",
".",
"append",
"(",
"\"*(%s*)a[%d]\"",
"%",
"(",
"const",
"+",
"I_type",
",",
"j",
")",
")",
"elif",
"t",
"==",
"'I'",
":",
"args",
".",
"append",
"(",
"\"(%s*)a[%d]\"",
"%",
"(",
"const",
"+",
"I_type",
",",
"j",
")",
")",
"elif",
"t",
"==",
"'T'",
":",
"args",
".",
"append",
"(",
"\"(%s*)a[%d]\"",
"%",
"(",
"const",
"+",
"T_type",
",",
"j",
")",
")",
"elif",
"t",
"==",
"'B'",
":",
"args",
".",
"append",
"(",
"\"(npy_bool_wrapper*)a[%d]\"",
"%",
"(",
"j",
",",
")",
")",
"elif",
"t",
"==",
"'V'",
":",
"if",
"const",
":",
"raise",
"ValueError",
"(",
"\"'V' argument must be an output arg\"",
")",
"args",
".",
"append",
"(",
"\"(std::vector<%s>*)a[%d]\"",
"%",
"(",
"I_type",
",",
"j",
",",
")",
")",
"elif",
"t",
"==",
"'W'",
":",
"if",
"const",
":",
"raise",
"ValueError",
"(",
"\"'W' argument must be an output arg\"",
")",
"args",
".",
"append",
"(",
"\"(std::vector<%s>*)a[%d]\"",
"%",
"(",
"T_type",
",",
"j",
",",
")",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Invalid spec character %r\"",
"%",
"(",
"t",
",",
")",
")",
"j",
"+=",
"1",
"return",
"\", \"",
".",
"join",
"(",
"args",
")",
"# Generate thunk code: a giant switch statement with different",
"# type combinations inside.",
"thunk_content",
"=",
"\"\"\"int j = get_thunk_case(I_typenum, T_typenum);\n switch (j) {\"\"\"",
"for",
"j",
",",
"I_typenum",
",",
"T_typenum",
",",
"I_type",
",",
"T_type",
"in",
"types",
":",
"arglist",
"=",
"get_arglist",
"(",
"I_type",
",",
"T_type",
")",
"if",
"T_type",
"is",
"None",
":",
"dispatch",
"=",
"\"%s\"",
"%",
"(",
"I_type",
",",
")",
"else",
":",
"dispatch",
"=",
"\"%s,%s\"",
"%",
"(",
"I_type",
",",
"T_type",
")",
"if",
"'B'",
"in",
"arg_spec",
":",
"dispatch",
"+=",
"\",npy_bool_wrapper\"",
"piece",
"=",
"\"\"\"\n case %(j)s:\"\"\"",
"if",
"ret_spec",
"==",
"'v'",
":",
"piece",
"+=",
"\"\"\"\n (void)%(name)s<%(dispatch)s>(%(arglist)s);\n return 0;\"\"\"",
"else",
":",
"piece",
"+=",
"\"\"\"\n return %(name)s<%(dispatch)s>(%(arglist)s);\"\"\"",
"thunk_content",
"+=",
"piece",
"%",
"dict",
"(",
"j",
"=",
"j",
",",
"I_type",
"=",
"I_type",
",",
"T_type",
"=",
"T_type",
",",
"I_typenum",
"=",
"I_typenum",
",",
"T_typenum",
"=",
"T_typenum",
",",
"arglist",
"=",
"arglist",
",",
"name",
"=",
"name",
",",
"dispatch",
"=",
"dispatch",
")",
"thunk_content",
"+=",
"\"\"\"\n default:\n throw std::runtime_error(\"internal error: invalid argument typenums\");\n }\"\"\"",
"thunk_code",
"=",
"THUNK_TEMPLATE",
"%",
"dict",
"(",
"name",
"=",
"name",
",",
"thunk_content",
"=",
"thunk_content",
")",
"# Generate method code",
"method_code",
"=",
"METHOD_TEMPLATE",
"%",
"dict",
"(",
"name",
"=",
"name",
",",
"ret_spec",
"=",
"ret_spec",
",",
"arg_spec",
"=",
"arg_spec",
")",
"return",
"thunk_code",
",",
"method_code"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/sparse/generate_sparsetools.py#L236-L328 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/requests/utils.py | python | address_in_network | (ip, net) | return (ipaddr & netmask) == (network & netmask) | This function allows you to check if an IP belongs to a network subnet
Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24
returns False if ip = 192.168.1.1 and net = 192.168.100.0/24
:rtype: bool | This function allows you to check if an IP belongs to a network subnet | [
"This",
"function",
"allows",
"you",
"to",
"check",
"if",
"an",
"IP",
"belongs",
"to",
"a",
"network",
"subnet"
] | def address_in_network(ip, net):
"""This function allows you to check if an IP belongs to a network subnet
Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24
returns False if ip = 192.168.1.1 and net = 192.168.100.0/24
:rtype: bool
"""
ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0]
netaddr, bits = net.split('/')
netmask = struct.unpack('=L', socket.inet_aton(dotted_netmask(int(bits))))[0]
network = struct.unpack('=L', socket.inet_aton(netaddr))[0] & netmask
return (ipaddr & netmask) == (network & netmask) | [
"def",
"address_in_network",
"(",
"ip",
",",
"net",
")",
":",
"ipaddr",
"=",
"struct",
".",
"unpack",
"(",
"'=L'",
",",
"socket",
".",
"inet_aton",
"(",
"ip",
")",
")",
"[",
"0",
"]",
"netaddr",
",",
"bits",
"=",
"net",
".",
"split",
"(",
"'/'",
")",
"netmask",
"=",
"struct",
".",
"unpack",
"(",
"'=L'",
",",
"socket",
".",
"inet_aton",
"(",
"dotted_netmask",
"(",
"int",
"(",
"bits",
")",
")",
")",
")",
"[",
"0",
"]",
"network",
"=",
"struct",
".",
"unpack",
"(",
"'=L'",
",",
"socket",
".",
"inet_aton",
"(",
"netaddr",
")",
")",
"[",
"0",
"]",
"&",
"netmask",
"return",
"(",
"ipaddr",
"&",
"netmask",
")",
"==",
"(",
"network",
"&",
"netmask",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/requests/utils.py#L626-L638 |
|
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/nn/parallel/comm.py | python | broadcast_coalesced | (tensors, devices, buffer_size=10485760) | return torch._C._broadcast_coalesced(tensors, devices, buffer_size) | Broadcasts a sequence tensors to the specified GPUs.
Small tensors are first coalesced into a buffer to reduce the number
of synchronizations.
Args:
tensors (sequence): tensors to broadcast. Must be on the same device,
either CPU or GPU.
devices (Iterable[torch.device, str or int]): an iterable of GPU
devices, among which to broadcast.
buffer_size (int): maximum size of the buffer used for coalescing
Returns:
A tuple containing copies of :attr:`tensor`, placed on :attr:`devices`. | Broadcasts a sequence tensors to the specified GPUs.
Small tensors are first coalesced into a buffer to reduce the number
of synchronizations. | [
"Broadcasts",
"a",
"sequence",
"tensors",
"to",
"the",
"specified",
"GPUs",
".",
"Small",
"tensors",
"are",
"first",
"coalesced",
"into",
"a",
"buffer",
"to",
"reduce",
"the",
"number",
"of",
"synchronizations",
"."
] | def broadcast_coalesced(tensors, devices, buffer_size=10485760):
"""Broadcasts a sequence tensors to the specified GPUs.
Small tensors are first coalesced into a buffer to reduce the number
of synchronizations.
Args:
tensors (sequence): tensors to broadcast. Must be on the same device,
either CPU or GPU.
devices (Iterable[torch.device, str or int]): an iterable of GPU
devices, among which to broadcast.
buffer_size (int): maximum size of the buffer used for coalescing
Returns:
A tuple containing copies of :attr:`tensor`, placed on :attr:`devices`.
"""
devices = [_get_device_index(d) for d in devices]
tensors = [_handle_complex(t) for t in tensors]
return torch._C._broadcast_coalesced(tensors, devices, buffer_size) | [
"def",
"broadcast_coalesced",
"(",
"tensors",
",",
"devices",
",",
"buffer_size",
"=",
"10485760",
")",
":",
"devices",
"=",
"[",
"_get_device_index",
"(",
"d",
")",
"for",
"d",
"in",
"devices",
"]",
"tensors",
"=",
"[",
"_handle_complex",
"(",
"t",
")",
"for",
"t",
"in",
"tensors",
"]",
"return",
"torch",
".",
"_C",
".",
"_broadcast_coalesced",
"(",
"tensors",
",",
"devices",
",",
"buffer_size",
")"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/nn/parallel/comm.py#L41-L58 |
|
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/idlelib/run.py | python | MyRPCServer.handle_error | (self, request, client_address) | Override RPCServer method for IDLE
Interrupt the MainThread and exit server if link is dropped. | Override RPCServer method for IDLE | [
"Override",
"RPCServer",
"method",
"for",
"IDLE"
] | def handle_error(self, request, client_address):
"""Override RPCServer method for IDLE
Interrupt the MainThread and exit server if link is dropped.
"""
global quitting
try:
raise
except SystemExit:
raise
except EOFError:
global exit_now
exit_now = True
thread.interrupt_main()
except:
erf = sys.__stderr__
print>>erf, '\n' + '-'*40
print>>erf, 'Unhandled server exception!'
print>>erf, 'Thread: %s' % threading.currentThread().getName()
print>>erf, 'Client Address: ', client_address
print>>erf, 'Request: ', repr(request)
traceback.print_exc(file=erf)
print>>erf, '\n*** Unrecoverable, server exiting!'
print>>erf, '-'*40
quitting = True
thread.interrupt_main() | [
"def",
"handle_error",
"(",
"self",
",",
"request",
",",
"client_address",
")",
":",
"global",
"quitting",
"try",
":",
"raise",
"except",
"SystemExit",
":",
"raise",
"except",
"EOFError",
":",
"global",
"exit_now",
"exit_now",
"=",
"True",
"thread",
".",
"interrupt_main",
"(",
")",
"except",
":",
"erf",
"=",
"sys",
".",
"__stderr__",
"print",
">>",
"erf",
",",
"'\\n'",
"+",
"'-'",
"*",
"40",
"print",
">>",
"erf",
",",
"'Unhandled server exception!'",
"print",
">>",
"erf",
",",
"'Thread: %s'",
"%",
"threading",
".",
"currentThread",
"(",
")",
".",
"getName",
"(",
")",
"print",
">>",
"erf",
",",
"'Client Address: '",
",",
"client_address",
"print",
">>",
"erf",
",",
"'Request: '",
",",
"repr",
"(",
"request",
")",
"traceback",
".",
"print_exc",
"(",
"file",
"=",
"erf",
")",
"print",
">>",
"erf",
",",
"'\\n*** Unrecoverable, server exiting!'",
"print",
">>",
"erf",
",",
"'-'",
"*",
"40",
"quitting",
"=",
"True",
"thread",
".",
"interrupt_main",
"(",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/idlelib/run.py#L226-L252 |
||
faasm/faasm | b3bc196d887adbd0bb9802bcb93323543bad59cb | faasmcli/faasmcli/tasks/docker_tasks.py | python | pull | (ctx, c) | Pull container images | Pull container images | [
"Pull",
"container",
"images"
] | def pull(ctx, c):
"""
Pull container images
"""
faasm_ver = get_faasm_version()
_check_valid_containers(c)
for container in c:
run(
"docker pull faasm/{}:{}".format(container, faasm_ver),
shell=True,
check=True,
cwd=PROJ_ROOT,
) | [
"def",
"pull",
"(",
"ctx",
",",
"c",
")",
":",
"faasm_ver",
"=",
"get_faasm_version",
"(",
")",
"_check_valid_containers",
"(",
"c",
")",
"for",
"container",
"in",
"c",
":",
"run",
"(",
"\"docker pull faasm/{}:{}\"",
".",
"format",
"(",
"container",
",",
"faasm_ver",
")",
",",
"shell",
"=",
"True",
",",
"check",
"=",
"True",
",",
"cwd",
"=",
"PROJ_ROOT",
",",
")"
] | https://github.com/faasm/faasm/blob/b3bc196d887adbd0bb9802bcb93323543bad59cb/faasmcli/faasmcli/tasks/docker_tasks.py#L98-L112 |
||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Source/ThirdParty/CEF3/pristine/cef_source/tools/cef_parser.py | python | obj_function.get_attrib | (self, name) | return None | Return the first or only value for specified attribute. | Return the first or only value for specified attribute. | [
"Return",
"the",
"first",
"or",
"only",
"value",
"for",
"specified",
"attribute",
"."
] | def get_attrib(self, name):
""" Return the first or only value for specified attribute. """
if name in self.attribs:
if isinstance(self.attribs[name], list):
# the value is a list
return self.attribs[name][0]
else:
# the value is a string
return self.attribs[name]
return None | [
"def",
"get_attrib",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"self",
".",
"attribs",
":",
"if",
"isinstance",
"(",
"self",
".",
"attribs",
"[",
"name",
"]",
",",
"list",
")",
":",
"# the value is a list",
"return",
"self",
".",
"attribs",
"[",
"name",
"]",
"[",
"0",
"]",
"else",
":",
"# the value is a string",
"return",
"self",
".",
"attribs",
"[",
"name",
"]",
"return",
"None"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Source/ThirdParty/CEF3/pristine/cef_source/tools/cef_parser.py#L1115-L1124 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/difflib.py | python | SequenceMatcher.ratio | (self) | return _calculate_ratio(matches, len(self.a) + len(self.b)) | Return a measure of the sequences' similarity (float in [0,1]).
Where T is the total number of elements in both sequences, and
M is the number of matches, this is 2.0*M / T.
Note that this is 1 if the sequences are identical, and 0 if
they have nothing in common.
.ratio() is expensive to compute if you haven't already computed
.get_matching_blocks() or .get_opcodes(), in which case you may
want to try .quick_ratio() or .real_quick_ratio() first to get an
upper bound.
>>> s = SequenceMatcher(None, "abcd", "bcde")
>>> s.ratio()
0.75
>>> s.quick_ratio()
0.75
>>> s.real_quick_ratio()
1.0 | Return a measure of the sequences' similarity (float in [0,1]). | [
"Return",
"a",
"measure",
"of",
"the",
"sequences",
"similarity",
"(",
"float",
"in",
"[",
"0",
"1",
"]",
")",
"."
] | def ratio(self):
"""Return a measure of the sequences' similarity (float in [0,1]).
Where T is the total number of elements in both sequences, and
M is the number of matches, this is 2.0*M / T.
Note that this is 1 if the sequences are identical, and 0 if
they have nothing in common.
.ratio() is expensive to compute if you haven't already computed
.get_matching_blocks() or .get_opcodes(), in which case you may
want to try .quick_ratio() or .real_quick_ratio() first to get an
upper bound.
>>> s = SequenceMatcher(None, "abcd", "bcde")
>>> s.ratio()
0.75
>>> s.quick_ratio()
0.75
>>> s.real_quick_ratio()
1.0
"""
matches = reduce(lambda sum, triple: sum + triple[-1],
self.get_matching_blocks(), 0)
return _calculate_ratio(matches, len(self.a) + len(self.b)) | [
"def",
"ratio",
"(",
"self",
")",
":",
"matches",
"=",
"reduce",
"(",
"lambda",
"sum",
",",
"triple",
":",
"sum",
"+",
"triple",
"[",
"-",
"1",
"]",
",",
"self",
".",
"get_matching_blocks",
"(",
")",
",",
"0",
")",
"return",
"_calculate_ratio",
"(",
"matches",
",",
"len",
"(",
"self",
".",
"a",
")",
"+",
"len",
"(",
"self",
".",
"b",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/difflib.py#L634-L658 |
|
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/closure_linter/closure_linter/checkerbase.py | python | CheckerBase._LintPass | (self, token) | Checks an individual token for lint warnings/errors.
Used to encapsulate the logic needed to check an individual token so that it
can be passed to _ExecutePass.
Args:
token: The token to check. | Checks an individual token for lint warnings/errors. | [
"Checks",
"an",
"individual",
"token",
"for",
"lint",
"warnings",
"/",
"errors",
"."
] | def _LintPass(self, token):
"""Checks an individual token for lint warnings/errors.
Used to encapsulate the logic needed to check an individual token so that it
can be passed to _ExecutePass.
Args:
token: The token to check.
"""
self._lint_rules.CheckToken(token, self._state_tracker) | [
"def",
"_LintPass",
"(",
"self",
",",
"token",
")",
":",
"self",
".",
"_lint_rules",
".",
"CheckToken",
"(",
"token",
",",
"self",
".",
"_state_tracker",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/closure_linter/closure_linter/checkerbase.py#L249-L258 |
||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/manifest.py | python | Manifest.add_many | (self, items) | Add a list of files to the manifest.
:param items: The pathnames to add. These can be relative to the base. | Add a list of files to the manifest. | [
"Add",
"a",
"list",
"of",
"files",
"to",
"the",
"manifest",
"."
] | def add_many(self, items):
"""
Add a list of files to the manifest.
:param items: The pathnames to add. These can be relative to the base.
"""
for item in items:
self.add(item) | [
"def",
"add_many",
"(",
"self",
",",
"items",
")",
":",
"for",
"item",
"in",
"items",
":",
"self",
".",
"add",
"(",
"item",
")"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/manifest.py#L87-L94 |
||
gambitproject/gambit | 4cef39b74773a3d9fd391deb8225aa59642038ee | src/pygambit/qre.py | python | sym_compute_lhs | (game, point) | return lhs | Compute the LHS for the set of equations for a symmetric logit QRE
of a symmetric game. | Compute the LHS for the set of equations for a symmetric logit QRE
of a symmetric game. | [
"Compute",
"the",
"LHS",
"for",
"the",
"set",
"of",
"equations",
"for",
"a",
"symmetric",
"logit",
"QRE",
"of",
"a",
"symmetric",
"game",
"."
] | def sym_compute_lhs(game, point):
"""
Compute the LHS for the set of equations for a symmetric logit QRE
of a symmetric game.
"""
profile = game.mixed_strategy_profile(
point=[math.exp(x) for x in point[:-1]]
)
logprofile = point[:-1]
lam = point[-1]
lhs = numpy.zeros(len(profile))
for (st, cont) in enumerate(game.choices):
if st == 0:
# sum-to-one equation
lhs[st] = -1.0 + sum(profile)
else:
lhs[st] = (logprofile[st] - logprofile[0] -
lam * (profile.strategy_value(st) -
profile.strategy_value(0)))
return lhs | [
"def",
"sym_compute_lhs",
"(",
"game",
",",
"point",
")",
":",
"profile",
"=",
"game",
".",
"mixed_strategy_profile",
"(",
"point",
"=",
"[",
"math",
".",
"exp",
"(",
"x",
")",
"for",
"x",
"in",
"point",
"[",
":",
"-",
"1",
"]",
"]",
")",
"logprofile",
"=",
"point",
"[",
":",
"-",
"1",
"]",
"lam",
"=",
"point",
"[",
"-",
"1",
"]",
"lhs",
"=",
"numpy",
".",
"zeros",
"(",
"len",
"(",
"profile",
")",
")",
"for",
"(",
"st",
",",
"cont",
")",
"in",
"enumerate",
"(",
"game",
".",
"choices",
")",
":",
"if",
"st",
"==",
"0",
":",
"# sum-to-one equation",
"lhs",
"[",
"st",
"]",
"=",
"-",
"1.0",
"+",
"sum",
"(",
"profile",
")",
"else",
":",
"lhs",
"[",
"st",
"]",
"=",
"(",
"logprofile",
"[",
"st",
"]",
"-",
"logprofile",
"[",
"0",
"]",
"-",
"lam",
"*",
"(",
"profile",
".",
"strategy_value",
"(",
"st",
")",
"-",
"profile",
".",
"strategy_value",
"(",
"0",
")",
")",
")",
"return",
"lhs"
] | https://github.com/gambitproject/gambit/blob/4cef39b74773a3d9fd391deb8225aa59642038ee/src/pygambit/qre.py#L34-L55 |
|
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/apitools/samples/storage_sample/storage/storage_v1.py | python | DefaultObjectAccessControlsInsert.RunWithArgs | (self, bucket) | Creates a new default object ACL entry on the specified bucket.
Args:
bucket: The name of the bucket.
Flags:
domain: The domain associated with the entity, if any.
email: The email address associated with the entity, if any.
entity: The entity holding the permission, in one of the following
forms: - user-userId - user-email - group-groupId - group-email -
domain-domain - project-team-projectId - allUsers -
allAuthenticatedUsers Examples: - The user [email protected] would be
[email protected]. - The group [email protected] would be
[email protected]. - To refer to all members of the
Google Apps for Business domain example.com, the entity would be
domain-example.com.
entityId: The ID for the entity, if any.
etag: HTTP 1.1 Entity tag for the access-control entry.
generation: The content generation of the object.
id: The ID of the access-control entry.
kind: The kind of item this is. For object access control entries, this
is always storage#objectAccessControl.
object: The name of the object.
projectTeam: The project team associated with the entity, if any.
role: The access permission for the entity. Can be READER or OWNER.
selfLink: The link to this access-control entry. | Creates a new default object ACL entry on the specified bucket. | [
"Creates",
"a",
"new",
"default",
"object",
"ACL",
"entry",
"on",
"the",
"specified",
"bucket",
"."
] | def RunWithArgs(self, bucket):
"""Creates a new default object ACL entry on the specified bucket.
Args:
bucket: The name of the bucket.
Flags:
domain: The domain associated with the entity, if any.
email: The email address associated with the entity, if any.
entity: The entity holding the permission, in one of the following
forms: - user-userId - user-email - group-groupId - group-email -
domain-domain - project-team-projectId - allUsers -
allAuthenticatedUsers Examples: - The user [email protected] would be
[email protected]. - The group [email protected] would be
[email protected]. - To refer to all members of the
Google Apps for Business domain example.com, the entity would be
domain-example.com.
entityId: The ID for the entity, if any.
etag: HTTP 1.1 Entity tag for the access-control entry.
generation: The content generation of the object.
id: The ID of the access-control entry.
kind: The kind of item this is. For object access control entries, this
is always storage#objectAccessControl.
object: The name of the object.
projectTeam: The project team associated with the entity, if any.
role: The access permission for the entity. Can be READER or OWNER.
selfLink: The link to this access-control entry.
"""
client = GetClientFromFlags()
global_params = GetGlobalParamsFromFlags()
request = messages.ObjectAccessControl(
bucket=bucket.decode('utf8'),
)
if FLAGS['domain'].present:
request.domain = FLAGS.domain.decode('utf8')
if FLAGS['email'].present:
request.email = FLAGS.email.decode('utf8')
if FLAGS['entity'].present:
request.entity = FLAGS.entity.decode('utf8')
if FLAGS['entityId'].present:
request.entityId = FLAGS.entityId.decode('utf8')
if FLAGS['etag'].present:
request.etag = FLAGS.etag.decode('utf8')
if FLAGS['generation'].present:
request.generation = int(FLAGS.generation)
if FLAGS['id'].present:
request.id = FLAGS.id.decode('utf8')
if FLAGS['kind'].present:
request.kind = FLAGS.kind.decode('utf8')
if FLAGS['object'].present:
request.object = FLAGS.object.decode('utf8')
if FLAGS['projectTeam'].present:
request.projectTeam = apitools_base.JsonToMessage(messages.ObjectAccessControl.ProjectTeamValue, FLAGS.projectTeam)
if FLAGS['role'].present:
request.role = FLAGS.role.decode('utf8')
if FLAGS['selfLink'].present:
request.selfLink = FLAGS.selfLink.decode('utf8')
result = client.defaultObjectAccessControls.Insert(
request, global_params=global_params)
print apitools_base_cli.FormatOutput(result) | [
"def",
"RunWithArgs",
"(",
"self",
",",
"bucket",
")",
":",
"client",
"=",
"GetClientFromFlags",
"(",
")",
"global_params",
"=",
"GetGlobalParamsFromFlags",
"(",
")",
"request",
"=",
"messages",
".",
"ObjectAccessControl",
"(",
"bucket",
"=",
"bucket",
".",
"decode",
"(",
"'utf8'",
")",
",",
")",
"if",
"FLAGS",
"[",
"'domain'",
"]",
".",
"present",
":",
"request",
".",
"domain",
"=",
"FLAGS",
".",
"domain",
".",
"decode",
"(",
"'utf8'",
")",
"if",
"FLAGS",
"[",
"'email'",
"]",
".",
"present",
":",
"request",
".",
"email",
"=",
"FLAGS",
".",
"email",
".",
"decode",
"(",
"'utf8'",
")",
"if",
"FLAGS",
"[",
"'entity'",
"]",
".",
"present",
":",
"request",
".",
"entity",
"=",
"FLAGS",
".",
"entity",
".",
"decode",
"(",
"'utf8'",
")",
"if",
"FLAGS",
"[",
"'entityId'",
"]",
".",
"present",
":",
"request",
".",
"entityId",
"=",
"FLAGS",
".",
"entityId",
".",
"decode",
"(",
"'utf8'",
")",
"if",
"FLAGS",
"[",
"'etag'",
"]",
".",
"present",
":",
"request",
".",
"etag",
"=",
"FLAGS",
".",
"etag",
".",
"decode",
"(",
"'utf8'",
")",
"if",
"FLAGS",
"[",
"'generation'",
"]",
".",
"present",
":",
"request",
".",
"generation",
"=",
"int",
"(",
"FLAGS",
".",
"generation",
")",
"if",
"FLAGS",
"[",
"'id'",
"]",
".",
"present",
":",
"request",
".",
"id",
"=",
"FLAGS",
".",
"id",
".",
"decode",
"(",
"'utf8'",
")",
"if",
"FLAGS",
"[",
"'kind'",
"]",
".",
"present",
":",
"request",
".",
"kind",
"=",
"FLAGS",
".",
"kind",
".",
"decode",
"(",
"'utf8'",
")",
"if",
"FLAGS",
"[",
"'object'",
"]",
".",
"present",
":",
"request",
".",
"object",
"=",
"FLAGS",
".",
"object",
".",
"decode",
"(",
"'utf8'",
")",
"if",
"FLAGS",
"[",
"'projectTeam'",
"]",
".",
"present",
":",
"request",
".",
"projectTeam",
"=",
"apitools_base",
".",
"JsonToMessage",
"(",
"messages",
".",
"ObjectAccessControl",
".",
"ProjectTeamValue",
",",
"FLAGS",
".",
"projectTeam",
")",
"if",
"FLAGS",
"[",
"'role'",
"]",
".",
"present",
":",
"request",
".",
"role",
"=",
"FLAGS",
".",
"role",
".",
"decode",
"(",
"'utf8'",
")",
"if",
"FLAGS",
"[",
"'selfLink'",
"]",
".",
"present",
":",
"request",
".",
"selfLink",
"=",
"FLAGS",
".",
"selfLink",
".",
"decode",
"(",
"'utf8'",
")",
"result",
"=",
"client",
".",
"defaultObjectAccessControls",
".",
"Insert",
"(",
"request",
",",
"global_params",
"=",
"global_params",
")",
"print",
"apitools_base_cli",
".",
"FormatOutput",
"(",
"result",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/apitools/samples/storage_sample/storage/storage_v1.py#L1242-L1301 |
||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | gpu/command_buffer/build_gles2_cmd_buffer.py | python | Argument.WriteDestinationInitalizationValidatationIfNeeded | (self, file, func) | Writes the client side destintion initialization validation if needed. | Writes the client side destintion initialization validation if needed. | [
"Writes",
"the",
"client",
"side",
"destintion",
"initialization",
"validation",
"if",
"needed",
"."
] | def WriteDestinationInitalizationValidatationIfNeeded(self, file, func):
"""Writes the client side destintion initialization validation if needed."""
parts = self.type.split(" ")
if len(parts) > 1:
return
if parts[0] in self.need_validation_:
file.Write(
" GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
("OPTIONAL_" if self.optional else "", self.type[:-1], self.name)) | [
"def",
"WriteDestinationInitalizationValidatationIfNeeded",
"(",
"self",
",",
"file",
",",
"func",
")",
":",
"parts",
"=",
"self",
".",
"type",
".",
"split",
"(",
"\" \"",
")",
"if",
"len",
"(",
"parts",
")",
">",
"1",
":",
"return",
"if",
"parts",
"[",
"0",
"]",
"in",
"self",
".",
"need_validation_",
":",
"file",
".",
"Write",
"(",
"\" GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\\n\"",
"%",
"(",
"\"OPTIONAL_\"",
"if",
"self",
".",
"optional",
"else",
"\"\"",
",",
"self",
".",
"type",
"[",
":",
"-",
"1",
"]",
",",
"self",
".",
"name",
")",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/gpu/command_buffer/build_gles2_cmd_buffer.py#L5837-L5845 |
||
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/logger-rate-limiter.py | python | Logger.shouldPrintMessage | (self, timestamp, message) | return True | Returns true if the message should be printed in the given timestamp, otherwise returns false. The timestamp is in seconds granularity.
:type timestamp: int
:type message: str
:rtype: bool | Returns true if the message should be printed in the given timestamp, otherwise returns false. The timestamp is in seconds granularity.
:type timestamp: int
:type message: str
:rtype: bool | [
"Returns",
"true",
"if",
"the",
"message",
"should",
"be",
"printed",
"in",
"the",
"given",
"timestamp",
"otherwise",
"returns",
"false",
".",
"The",
"timestamp",
"is",
"in",
"seconds",
"granularity",
".",
":",
"type",
"timestamp",
":",
"int",
":",
"type",
"message",
":",
"str",
":",
"rtype",
":",
"bool"
] | def shouldPrintMessage(self, timestamp, message):
"""
Returns true if the message should be printed in the given timestamp, otherwise returns false. The timestamp is in seconds granularity.
:type timestamp: int
:type message: str
:rtype: bool
"""
while self.__dq and self.__dq[0][0] <= timestamp - 10:
self.__printed.remove(self.__dq.popleft()[1])
if message in self.__printed:
return False
self.__dq.append((timestamp, message))
self.__printed.add(message)
return True | [
"def",
"shouldPrintMessage",
"(",
"self",
",",
"timestamp",
",",
"message",
")",
":",
"while",
"self",
".",
"__dq",
"and",
"self",
".",
"__dq",
"[",
"0",
"]",
"[",
"0",
"]",
"<=",
"timestamp",
"-",
"10",
":",
"self",
".",
"__printed",
".",
"remove",
"(",
"self",
".",
"__dq",
".",
"popleft",
"(",
")",
"[",
"1",
"]",
")",
"if",
"message",
"in",
"self",
".",
"__printed",
":",
"return",
"False",
"self",
".",
"__dq",
".",
"append",
"(",
"(",
"timestamp",
",",
"message",
")",
")",
"self",
".",
"__printed",
".",
"add",
"(",
"message",
")",
"return",
"True"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/logger-rate-limiter.py#L16-L29 |
|
KDE/krita | 10ea63984e00366865769c193ab298de73a59c5c | plugins/extensions/pykrita/plugin/krita/attic/mikro.py | python | PyQtClass.__members__ | (self) | return names | This method is for introspection.
Using dir(thispyqtclass_object) returns a list of
all children, methods, properties and dynamic properties. | This method is for introspection.
Using dir(thispyqtclass_object) returns a list of
all children, methods, properties and dynamic properties. | [
"This",
"method",
"is",
"for",
"introspection",
".",
"Using",
"dir",
"(",
"thispyqtclass_object",
")",
"returns",
"a",
"list",
"of",
"all",
"children",
"methods",
"properties",
"and",
"dynamic",
"properties",
"."
] | def __members__(self):
"""
This method is for introspection.
Using dir(thispyqtclass_object) returns a list of
all children, methods, properties and dynamic properties.
"""
names = list(self.__dict__.keys())
for c in self._instance.children():
child_name = str(c.objectName())
if child_name:
names.append(child_name)
for pn in self._instance.dynamicPropertyNames():
names.append(str(pn))
return names | [
"def",
"__members__",
"(",
"self",
")",
":",
"names",
"=",
"list",
"(",
"self",
".",
"__dict__",
".",
"keys",
"(",
")",
")",
"for",
"c",
"in",
"self",
".",
"_instance",
".",
"children",
"(",
")",
":",
"child_name",
"=",
"str",
"(",
"c",
".",
"objectName",
"(",
")",
")",
"if",
"child_name",
":",
"names",
".",
"append",
"(",
"child_name",
")",
"for",
"pn",
"in",
"self",
".",
"_instance",
".",
"dynamicPropertyNames",
"(",
")",
":",
"names",
".",
"append",
"(",
"str",
"(",
"pn",
")",
")",
"return",
"names"
] | https://github.com/KDE/krita/blob/10ea63984e00366865769c193ab298de73a59c5c/plugins/extensions/pykrita/plugin/krita/attic/mikro.py#L263-L276 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/core/defchararray.py | python | istitle | (a) | return _vec_string(a, bool_, 'istitle') | Returns true for each element if the element is a titlecased
string and there is at least one character, false otherwise.
Call `str.istitle` element-wise.
For 8-bit strings, this method is locale-dependent.
Parameters
----------
a : array_like of str or unicode
Returns
-------
out : ndarray
Output array of bools
See Also
--------
str.istitle | Returns true for each element if the element is a titlecased
string and there is at least one character, false otherwise. | [
"Returns",
"true",
"for",
"each",
"element",
"if",
"the",
"element",
"is",
"a",
"titlecased",
"string",
"and",
"there",
"is",
"at",
"least",
"one",
"character",
"false",
"otherwise",
"."
] | def istitle(a):
"""
Returns true for each element if the element is a titlecased
string and there is at least one character, false otherwise.
Call `str.istitle` element-wise.
For 8-bit strings, this method is locale-dependent.
Parameters
----------
a : array_like of str or unicode
Returns
-------
out : ndarray
Output array of bools
See Also
--------
str.istitle
"""
return _vec_string(a, bool_, 'istitle') | [
"def",
"istitle",
"(",
"a",
")",
":",
"return",
"_vec_string",
"(",
"a",
",",
"bool_",
",",
"'istitle'",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/core/defchararray.py#L882-L904 |
|
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/build/fuchsia/binary_sizes.py | python | ReadPackageBlobsJson | (json_path) | return package_blobs | Reads package blob info from json file.
Opens json file of blob info written by WritePackageBlobsJson,
and converts back into package blobs used in this script. | Reads package blob info from json file. | [
"Reads",
"package",
"blob",
"info",
"from",
"json",
"file",
"."
] | def ReadPackageBlobsJson(json_path):
"""Reads package blob info from json file.
Opens json file of blob info written by WritePackageBlobsJson,
and converts back into package blobs used in this script.
"""
with open(json_path, 'rt') as json_file:
formatted_blob_info = json.load(json_file)
package_blobs = {}
for package in formatted_blob_info:
package_blobs[package] = {}
for blob_info in formatted_blob_info[package]:
blob = Blob(name=blob_info['path'],
hash=blob_info['merkle'],
uncompressed=blob_info['bytes'],
compressed=blob_info['size'],
is_counted=blob_info['is_counted'])
package_blobs[package][blob.name] = blob
return package_blobs | [
"def",
"ReadPackageBlobsJson",
"(",
"json_path",
")",
":",
"with",
"open",
"(",
"json_path",
",",
"'rt'",
")",
"as",
"json_file",
":",
"formatted_blob_info",
"=",
"json",
".",
"load",
"(",
"json_file",
")",
"package_blobs",
"=",
"{",
"}",
"for",
"package",
"in",
"formatted_blob_info",
":",
"package_blobs",
"[",
"package",
"]",
"=",
"{",
"}",
"for",
"blob_info",
"in",
"formatted_blob_info",
"[",
"package",
"]",
":",
"blob",
"=",
"Blob",
"(",
"name",
"=",
"blob_info",
"[",
"'path'",
"]",
",",
"hash",
"=",
"blob_info",
"[",
"'merkle'",
"]",
",",
"uncompressed",
"=",
"blob_info",
"[",
"'bytes'",
"]",
",",
"compressed",
"=",
"blob_info",
"[",
"'size'",
"]",
",",
"is_counted",
"=",
"blob_info",
"[",
"'is_counted'",
"]",
")",
"package_blobs",
"[",
"package",
"]",
"[",
"blob",
".",
"name",
"]",
"=",
"blob",
"return",
"package_blobs"
] | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/fuchsia/binary_sizes.py#L187-L207 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_controls.py | python | ToolBarToolBase.GetNormalBitmap | (*args, **kwargs) | return _controls_.ToolBarToolBase_GetNormalBitmap(*args, **kwargs) | GetNormalBitmap(self) -> Bitmap | GetNormalBitmap(self) -> Bitmap | [
"GetNormalBitmap",
"(",
"self",
")",
"-",
">",
"Bitmap"
] | def GetNormalBitmap(*args, **kwargs):
"""GetNormalBitmap(self) -> Bitmap"""
return _controls_.ToolBarToolBase_GetNormalBitmap(*args, **kwargs) | [
"def",
"GetNormalBitmap",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"ToolBarToolBase_GetNormalBitmap",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L3497-L3499 |
|
infinit/elle | a8154593c42743f45b9df09daf62b44630c24a02 | drake/src/drake/__init__.py | python | Path.prefix_of | (self, rhs) | return len(path) == 0 | Whether self is a prefix of rhs.
>>> p = Path('foo/bar')
>>> p.prefix_of('foo/bar/baz/quux')
True
>>> p.prefix_of('foo/baz/bar/quux')
False
>>> p.prefix_of('nope')
False | Whether self is a prefix of rhs. | [
"Whether",
"self",
"is",
"a",
"prefix",
"of",
"rhs",
"."
] | def prefix_of(self, rhs):
"""Whether self is a prefix of rhs.
>>> p = Path('foo/bar')
>>> p.prefix_of('foo/bar/baz/quux')
True
>>> p.prefix_of('foo/baz/bar/quux')
False
>>> p.prefix_of('nope')
False
"""
rhs = drake.Path(rhs).canonize().__path
path = self.__path
while len(rhs) and len(path) and path[0] == rhs[0]:
rhs = rhs[1:]
path = path[1:]
return len(path) == 0 | [
"def",
"prefix_of",
"(",
"self",
",",
"rhs",
")",
":",
"rhs",
"=",
"drake",
".",
"Path",
"(",
"rhs",
")",
".",
"canonize",
"(",
")",
".",
"__path",
"path",
"=",
"self",
".",
"__path",
"while",
"len",
"(",
"rhs",
")",
"and",
"len",
"(",
"path",
")",
"and",
"path",
"[",
"0",
"]",
"==",
"rhs",
"[",
"0",
"]",
":",
"rhs",
"=",
"rhs",
"[",
"1",
":",
"]",
"path",
"=",
"path",
"[",
"1",
":",
"]",
"return",
"len",
"(",
"path",
")",
"==",
"0"
] | https://github.com/infinit/elle/blob/a8154593c42743f45b9df09daf62b44630c24a02/drake/src/drake/__init__.py#L989-L1005 |
|
kripken/BananaBread | 455191d2e289f6d67f22c9ec44477ff0814d9aa3 | tools/websockify/websockify/websocket.py | python | WebSocketServer.gen_md5 | (keys) | return b2s(md5(pack('>II8s',
int(num1), int(num2), key3)).digest()) | Generate hash value for WebSockets hixie-76. | Generate hash value for WebSockets hixie-76. | [
"Generate",
"hash",
"value",
"for",
"WebSockets",
"hixie",
"-",
"76",
"."
] | def gen_md5(keys):
""" Generate hash value for WebSockets hixie-76. """
key1 = keys['Sec-WebSocket-Key1']
key2 = keys['Sec-WebSocket-Key2']
key3 = keys['key3']
spaces1 = key1.count(" ")
spaces2 = key2.count(" ")
num1 = int("".join([c for c in key1 if c.isdigit()])) / spaces1
num2 = int("".join([c for c in key2 if c.isdigit()])) / spaces2
return b2s(md5(pack('>II8s',
int(num1), int(num2), key3)).digest()) | [
"def",
"gen_md5",
"(",
"keys",
")",
":",
"key1",
"=",
"keys",
"[",
"'Sec-WebSocket-Key1'",
"]",
"key2",
"=",
"keys",
"[",
"'Sec-WebSocket-Key2'",
"]",
"key3",
"=",
"keys",
"[",
"'key3'",
"]",
"spaces1",
"=",
"key1",
".",
"count",
"(",
"\" \"",
")",
"spaces2",
"=",
"key2",
".",
"count",
"(",
"\" \"",
")",
"num1",
"=",
"int",
"(",
"\"\"",
".",
"join",
"(",
"[",
"c",
"for",
"c",
"in",
"key1",
"if",
"c",
".",
"isdigit",
"(",
")",
"]",
")",
")",
"/",
"spaces1",
"num2",
"=",
"int",
"(",
"\"\"",
".",
"join",
"(",
"[",
"c",
"for",
"c",
"in",
"key2",
"if",
"c",
".",
"isdigit",
"(",
")",
"]",
")",
")",
"/",
"spaces2",
"return",
"b2s",
"(",
"md5",
"(",
"pack",
"(",
"'>II8s'",
",",
"int",
"(",
"num1",
")",
",",
"int",
"(",
"num2",
")",
",",
"key3",
")",
")",
".",
"digest",
"(",
")",
")"
] | https://github.com/kripken/BananaBread/blob/455191d2e289f6d67f22c9ec44477ff0814d9aa3/tools/websockify/websockify/websocket.py#L399-L410 |
|
rdkit/rdkit | ede860ae316d12d8568daf5ee800921c3389c84e | rdkit/Dbase/DbConnection.py | python | DbConnect.GetColumnNamesAndTypes | (self, table='', join='', what='*', where='', **kwargs) | return DbInfo.GetColumnNamesAndTypes(self.dbName, table, self.user, self.password, join=join,
what=what, cn=self.cn) | gets a list of columns available in the current table along with their types
**Returns**
a list of 2-tuples containing:
1) column name
2) column type
**Notes**
- this uses _DbInfo.GetColumnNamesAndTypes_ | gets a list of columns available in the current table along with their types | [
"gets",
"a",
"list",
"of",
"columns",
"available",
"in",
"the",
"current",
"table",
"along",
"with",
"their",
"types"
] | def GetColumnNamesAndTypes(self, table='', join='', what='*', where='', **kwargs):
""" gets a list of columns available in the current table along with their types
**Returns**
a list of 2-tuples containing:
1) column name
2) column type
**Notes**
- this uses _DbInfo.GetColumnNamesAndTypes_
"""
table = table or self.tableName
return DbInfo.GetColumnNamesAndTypes(self.dbName, table, self.user, self.password, join=join,
what=what, cn=self.cn) | [
"def",
"GetColumnNamesAndTypes",
"(",
"self",
",",
"table",
"=",
"''",
",",
"join",
"=",
"''",
",",
"what",
"=",
"'*'",
",",
"where",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"table",
"=",
"table",
"or",
"self",
".",
"tableName",
"return",
"DbInfo",
".",
"GetColumnNamesAndTypes",
"(",
"self",
".",
"dbName",
",",
"table",
",",
"self",
".",
"user",
",",
"self",
".",
"password",
",",
"join",
"=",
"join",
",",
"what",
"=",
"what",
",",
"cn",
"=",
"self",
".",
"cn",
")"
] | https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/Dbase/DbConnection.py#L88-L106 |
|
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | example/ssd/dataset/pascal_voc.py | python | PascalVoc.do_python_eval | (self) | python evaluation wrapper
Returns:
----------
None | python evaluation wrapper | [
"python",
"evaluation",
"wrapper"
] | def do_python_eval(self):
"""
python evaluation wrapper
Returns:
----------
None
"""
annopath = os.path.join(self.data_path, 'Annotations', '{:s}.xml')
imageset_file = os.path.join(self.data_path, 'ImageSets', 'Main', self.image_set + '.txt')
cache_dir = os.path.join(self.cache_path, self.name)
aps = []
# The PASCAL VOC metric changed in 2010
use_07_metric = True if int(self.year) < 2010 else False
print('VOC07 metric? ' + ('Y' if use_07_metric else 'No'))
for cls_ind, cls in enumerate(self.classes):
filename = self.get_result_file_template().format(cls)
rec, prec, ap = voc_eval(filename, annopath, imageset_file, cls, cache_dir,
ovthresh=0.5, use_07_metric=use_07_metric)
aps += [ap]
print('AP for {} = {:.4f}'.format(cls, ap))
print('Mean AP = {:.4f}'.format(np.mean(aps))) | [
"def",
"do_python_eval",
"(",
"self",
")",
":",
"annopath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"data_path",
",",
"'Annotations'",
",",
"'{:s}.xml'",
")",
"imageset_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"data_path",
",",
"'ImageSets'",
",",
"'Main'",
",",
"self",
".",
"image_set",
"+",
"'.txt'",
")",
"cache_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"cache_path",
",",
"self",
".",
"name",
")",
"aps",
"=",
"[",
"]",
"# The PASCAL VOC metric changed in 2010",
"use_07_metric",
"=",
"True",
"if",
"int",
"(",
"self",
".",
"year",
")",
"<",
"2010",
"else",
"False",
"print",
"(",
"'VOC07 metric? '",
"+",
"(",
"'Y'",
"if",
"use_07_metric",
"else",
"'No'",
")",
")",
"for",
"cls_ind",
",",
"cls",
"in",
"enumerate",
"(",
"self",
".",
"classes",
")",
":",
"filename",
"=",
"self",
".",
"get_result_file_template",
"(",
")",
".",
"format",
"(",
"cls",
")",
"rec",
",",
"prec",
",",
"ap",
"=",
"voc_eval",
"(",
"filename",
",",
"annopath",
",",
"imageset_file",
",",
"cls",
",",
"cache_dir",
",",
"ovthresh",
"=",
"0.5",
",",
"use_07_metric",
"=",
"use_07_metric",
")",
"aps",
"+=",
"[",
"ap",
"]",
"print",
"(",
"'AP for {} = {:.4f}'",
".",
"format",
"(",
"cls",
",",
"ap",
")",
")",
"print",
"(",
"'Mean AP = {:.4f}'",
".",
"format",
"(",
"np",
".",
"mean",
"(",
"aps",
")",
")",
")"
] | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/example/ssd/dataset/pascal_voc.py#L255-L276 |
||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/ipaddress.py | python | IPv6Address.__init__ | (self, address) | Instantiate a new IPv6 address object.
Args:
address: A string or integer representing the IP
Additionally, an integer can be passed, so
IPv6Address('2001:db8::') ==
IPv6Address(42540766411282592856903984951653826560)
or, more generally
IPv6Address(int(IPv6Address('2001:db8::'))) ==
IPv6Address('2001:db8::')
Raises:
AddressValueError: If address isn't a valid IPv6 address. | Instantiate a new IPv6 address object. | [
"Instantiate",
"a",
"new",
"IPv6",
"address",
"object",
"."
] | def __init__(self, address):
"""Instantiate a new IPv6 address object.
Args:
address: A string or integer representing the IP
Additionally, an integer can be passed, so
IPv6Address('2001:db8::') ==
IPv6Address(42540766411282592856903984951653826560)
or, more generally
IPv6Address(int(IPv6Address('2001:db8::'))) ==
IPv6Address('2001:db8::')
Raises:
AddressValueError: If address isn't a valid IPv6 address.
"""
# Efficient constructor from integer.
if isinstance(address, _compat_int_types):
self._check_int_address(address)
self._ip = address
return
# Constructing from a packed address
if isinstance(address, bytes):
self._check_packed_address(address, 16)
bvs = _compat_bytes_to_byte_vals(address)
self._ip = _compat_int_from_byte_vals(bvs, 'big')
return
# Assume input argument to be string or any object representation
# which converts into a formatted IP string.
addr_str = _compat_str(address)
if '/' in addr_str:
raise AddressValueError("Unexpected '/' in %r" % address)
self._ip = self._ip_int_from_string(addr_str) | [
"def",
"__init__",
"(",
"self",
",",
"address",
")",
":",
"# Efficient constructor from integer.",
"if",
"isinstance",
"(",
"address",
",",
"_compat_int_types",
")",
":",
"self",
".",
"_check_int_address",
"(",
"address",
")",
"self",
".",
"_ip",
"=",
"address",
"return",
"# Constructing from a packed address",
"if",
"isinstance",
"(",
"address",
",",
"bytes",
")",
":",
"self",
".",
"_check_packed_address",
"(",
"address",
",",
"16",
")",
"bvs",
"=",
"_compat_bytes_to_byte_vals",
"(",
"address",
")",
"self",
".",
"_ip",
"=",
"_compat_int_from_byte_vals",
"(",
"bvs",
",",
"'big'",
")",
"return",
"# Assume input argument to be string or any object representation",
"# which converts into a formatted IP string.",
"addr_str",
"=",
"_compat_str",
"(",
"address",
")",
"if",
"'/'",
"in",
"addr_str",
":",
"raise",
"AddressValueError",
"(",
"\"Unexpected '/' in %r\"",
"%",
"address",
")",
"self",
".",
"_ip",
"=",
"self",
".",
"_ip_int_from_string",
"(",
"addr_str",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/ipaddress.py#L2003-L2038 |
||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/control/blocks/robotcontroller.py | python | RobotControllerIO.commandedConfiguration | (self) | Returns the commanded joint configuration or None if it is not
sensed. | Returns the commanded joint configuration or None if it is not
sensed. | [
"Returns",
"the",
"commanded",
"joint",
"configuration",
"or",
"None",
"if",
"it",
"is",
"not",
"sensed",
"."
] | def commandedConfiguration(self):
"""Returns the commanded joint configuration or None if it is not
sensed."""
try: return self.inputs['qcmd']
except KeyError: return None | [
"def",
"commandedConfiguration",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"inputs",
"[",
"'qcmd'",
"]",
"except",
"KeyError",
":",
"return",
"None"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/control/blocks/robotcontroller.py#L146-L150 |
||
TGAC/KAT | e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216 | deps/boost/tools/build/src/build/toolset.py | python | requirements | () | return __requirements | Return the list of global 'toolset requirements'.
Those requirements will be automatically added to the requirements of any main target. | Return the list of global 'toolset requirements'.
Those requirements will be automatically added to the requirements of any main target. | [
"Return",
"the",
"list",
"of",
"global",
"toolset",
"requirements",
".",
"Those",
"requirements",
"will",
"be",
"automatically",
"added",
"to",
"the",
"requirements",
"of",
"any",
"main",
"target",
"."
] | def requirements():
"""Return the list of global 'toolset requirements'.
Those requirements will be automatically added to the requirements of any main target."""
return __requirements | [
"def",
"requirements",
"(",
")",
":",
"return",
"__requirements"
] | https://github.com/TGAC/KAT/blob/e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216/deps/boost/tools/build/src/build/toolset.py#L386-L389 |
|
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/model/robotinfo.py | python | GripperInfo.visualize | (self) | Visually debugs the gripper | Visually debugs the gripper | [
"Visually",
"debugs",
"the",
"gripper"
] | def visualize(self) -> None:
"""Visually debugs the gripper"""
from klampt import vis
vis.loop(lambda: self.addToVis()) | [
"def",
"visualize",
"(",
"self",
")",
"->",
"None",
":",
"from",
"klampt",
"import",
"vis",
"vis",
".",
"loop",
"(",
"lambda",
":",
"self",
".",
"addToVis",
"(",
")",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/model/robotinfo.py#L864-L867 |
||
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | config/configobj.py | python | InterpolationEngine._fetch | (self, key) | return val, current_section | Helper function to fetch values from owning section.
Returns a 2-tuple: the value, and the section where it was found. | Helper function to fetch values from owning section. | [
"Helper",
"function",
"to",
"fetch",
"values",
"from",
"owning",
"section",
"."
] | def _fetch(self, key):
"""Helper function to fetch values from owning section.
Returns a 2-tuple: the value, and the section where it was found.
"""
# switch off interpolation before we try and fetch anything !
save_interp = self.section.main.interpolation
self.section.main.interpolation = False
# Start at section that "owns" this InterpolationEngine
current_section = self.section
while True:
# try the current section first
val = current_section.get(key)
if val is not None:
break
# try "DEFAULT" next
val = current_section.get('DEFAULT', {}).get(key)
if val is not None:
break
# move up to parent and try again
# top-level's parent is itself
if current_section.parent is current_section:
# reached top level, time to give up
break
current_section = current_section.parent
# restore interpolation to previous value before returning
self.section.main.interpolation = save_interp
if val is None:
raise MissingInterpolationOption(key)
return val, current_section | [
"def",
"_fetch",
"(",
"self",
",",
"key",
")",
":",
"# switch off interpolation before we try and fetch anything !",
"save_interp",
"=",
"self",
".",
"section",
".",
"main",
".",
"interpolation",
"self",
".",
"section",
".",
"main",
".",
"interpolation",
"=",
"False",
"# Start at section that \"owns\" this InterpolationEngine",
"current_section",
"=",
"self",
".",
"section",
"while",
"True",
":",
"# try the current section first",
"val",
"=",
"current_section",
".",
"get",
"(",
"key",
")",
"if",
"val",
"is",
"not",
"None",
":",
"break",
"# try \"DEFAULT\" next",
"val",
"=",
"current_section",
".",
"get",
"(",
"'DEFAULT'",
",",
"{",
"}",
")",
".",
"get",
"(",
"key",
")",
"if",
"val",
"is",
"not",
"None",
":",
"break",
"# move up to parent and try again",
"# top-level's parent is itself",
"if",
"current_section",
".",
"parent",
"is",
"current_section",
":",
"# reached top level, time to give up",
"break",
"current_section",
"=",
"current_section",
".",
"parent",
"# restore interpolation to previous value before returning",
"self",
".",
"section",
".",
"main",
".",
"interpolation",
"=",
"save_interp",
"if",
"val",
"is",
"None",
":",
"raise",
"MissingInterpolationOption",
"(",
"key",
")",
"return",
"val",
",",
"current_section"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/config/configobj.py#L359-L390 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/urllib/robotparser.py | python | RobotFileParser.set_url | (self, url) | Sets the URL referring to a robots.txt file. | Sets the URL referring to a robots.txt file. | [
"Sets",
"the",
"URL",
"referring",
"to",
"a",
"robots",
".",
"txt",
"file",
"."
] | def set_url(self, url):
"""Sets the URL referring to a robots.txt file."""
self.url = url
self.host, self.path = urllib.parse.urlparse(url)[1:3] | [
"def",
"set_url",
"(",
"self",
",",
"url",
")",
":",
"self",
".",
"url",
"=",
"url",
"self",
".",
"host",
",",
"self",
".",
"path",
"=",
"urllib",
".",
"parse",
".",
"urlparse",
"(",
"url",
")",
"[",
"1",
":",
"3",
"]"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/urllib/robotparser.py#L54-L57 |
||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/dataview.py | python | PyDataViewIndexListModel.__init__ | (self, *args, **kwargs) | __init__(self, unsigned int initial_size=0) -> PyDataViewIndexListModel | __init__(self, unsigned int initial_size=0) -> PyDataViewIndexListModel | [
"__init__",
"(",
"self",
"unsigned",
"int",
"initial_size",
"=",
"0",
")",
"-",
">",
"PyDataViewIndexListModel"
] | def __init__(self, *args, **kwargs):
"""__init__(self, unsigned int initial_size=0) -> PyDataViewIndexListModel"""
_dataview.PyDataViewIndexListModel_swiginit(self,_dataview.new_PyDataViewIndexListModel(*args, **kwargs))
PyDataViewIndexListModel._setCallbackInfo(self, self, PyDataViewIndexListModel) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_dataview",
".",
"PyDataViewIndexListModel_swiginit",
"(",
"self",
",",
"_dataview",
".",
"new_PyDataViewIndexListModel",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"PyDataViewIndexListModel",
".",
"_setCallbackInfo",
"(",
"self",
",",
"self",
",",
"PyDataViewIndexListModel",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/dataview.py#L927-L930 |
||
infinit/memo | 3a8394d0f647efe03ccb8bfe885a7279cb8be8a6 | elle/drake/src/drake/__init__.py | python | Node.clone | (self, path) | return Node(path) | Clone of this node, with an other path. | Clone of this node, with an other path. | [
"Clone",
"of",
"this",
"node",
"with",
"an",
"other",
"path",
"."
] | def clone(self, path):
"""Clone of this node, with an other path."""
return Node(path) | [
"def",
"clone",
"(",
"self",
",",
"path",
")",
":",
"return",
"Node",
"(",
"path",
")"
] | https://github.com/infinit/memo/blob/3a8394d0f647efe03ccb8bfe885a7279cb8be8a6/elle/drake/src/drake/__init__.py#L1620-L1622 |
|
microsoft/ELL | a1d6bacc37a14879cc025d9be2ba40b1a0632315 | tools/importers/common/converters.py | python | ConvertReorder.convert_node | (self, conversion_parameters: typing.Mapping[str, typing.Any]) | Derived classes override to convert the importer node to appropriate ELL node(s)
and insert into the model | Derived classes override to convert the importer node to appropriate ELL node(s)
and insert into the model | [
"Derived",
"classes",
"override",
"to",
"convert",
"the",
"importer",
"node",
"to",
"appropriate",
"ELL",
"node",
"(",
"s",
")",
"and",
"insert",
"into",
"the",
"model"
] | def convert_node(self, conversion_parameters: typing.Mapping[str, typing.Any]):
"""
Derived classes override to convert the importer node to appropriate ELL node(s)
and insert into the model
"""
model = conversion_parameters["model"]
builder = conversion_parameters["builder"]
lookup_table = conversion_parameters["lookup_table"]
input_port_elements = lookup_table.get_port_elements_for_input(self.importer_node)
order = list(np.array(self.importer_node.attributes["order"]).astype(np.int))
# Create the reorder node
reorder_node = builder.AddReorderDataNode(model, input_port_elements, order)
# Register the mapping
lookup_table.add_imported_ell_node(self.importer_node, reorder_node)
input_port_elements = lookup_table.get_output_port_elements_for_node(reorder_node) | [
"def",
"convert_node",
"(",
"self",
",",
"conversion_parameters",
":",
"typing",
".",
"Mapping",
"[",
"str",
",",
"typing",
".",
"Any",
"]",
")",
":",
"model",
"=",
"conversion_parameters",
"[",
"\"model\"",
"]",
"builder",
"=",
"conversion_parameters",
"[",
"\"builder\"",
"]",
"lookup_table",
"=",
"conversion_parameters",
"[",
"\"lookup_table\"",
"]",
"input_port_elements",
"=",
"lookup_table",
".",
"get_port_elements_for_input",
"(",
"self",
".",
"importer_node",
")",
"order",
"=",
"list",
"(",
"np",
".",
"array",
"(",
"self",
".",
"importer_node",
".",
"attributes",
"[",
"\"order\"",
"]",
")",
".",
"astype",
"(",
"np",
".",
"int",
")",
")",
"# Create the reorder node",
"reorder_node",
"=",
"builder",
".",
"AddReorderDataNode",
"(",
"model",
",",
"input_port_elements",
",",
"order",
")",
"# Register the mapping",
"lookup_table",
".",
"add_imported_ell_node",
"(",
"self",
".",
"importer_node",
",",
"reorder_node",
")",
"input_port_elements",
"=",
"lookup_table",
".",
"get_output_port_elements_for_node",
"(",
"reorder_node",
")"
] | https://github.com/microsoft/ELL/blob/a1d6bacc37a14879cc025d9be2ba40b1a0632315/tools/importers/common/converters.py#L1864-L1880 |
||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/importlib/abc.py | python | ExecutionLoader.get_filename | (self, fullname) | Abstract method which should return the value that __file__ is to be
set to.
Raises ImportError if the module cannot be found. | Abstract method which should return the value that __file__ is to be
set to. | [
"Abstract",
"method",
"which",
"should",
"return",
"the",
"value",
"that",
"__file__",
"is",
"to",
"be",
"set",
"to",
"."
] | def get_filename(self, fullname):
"""Abstract method which should return the value that __file__ is to be
set to.
Raises ImportError if the module cannot be found.
"""
raise ImportError | [
"def",
"get_filename",
"(",
"self",
",",
"fullname",
")",
":",
"raise",
"ImportError"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/importlib/abc.py#L262-L268 |
||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/utils/saved_model_export_utils.py | python | _default_compare_fn | (curr_best_eval_result, cand_eval_result) | return curr_best_eval_result[default_key] > cand_eval_result[default_key] | Compares two evaluation results and returns true if the 2nd one is better.
Both evaluation results should have the values for MetricKey.LOSS, which are
used for comparison.
Args:
curr_best_eval_result: current best eval metrics.
cand_eval_result: candidate eval metrics.
Returns:
True if cand_eval_result is better.
Raises:
ValueError: If input eval result is None or no loss is available. | Compares two evaluation results and returns true if the 2nd one is better. | [
"Compares",
"two",
"evaluation",
"results",
"and",
"returns",
"true",
"if",
"the",
"2nd",
"one",
"is",
"better",
"."
] | def _default_compare_fn(curr_best_eval_result, cand_eval_result):
"""Compares two evaluation results and returns true if the 2nd one is better.
Both evaluation results should have the values for MetricKey.LOSS, which are
used for comparison.
Args:
curr_best_eval_result: current best eval metrics.
cand_eval_result: candidate eval metrics.
Returns:
True if cand_eval_result is better.
Raises:
ValueError: If input eval result is None or no loss is available.
"""
default_key = metric_key.MetricKey.LOSS
if not curr_best_eval_result or default_key not in curr_best_eval_result:
raise ValueError(
'curr_best_eval_result cannot be empty or no loss is found in it.')
if not cand_eval_result or default_key not in cand_eval_result:
raise ValueError(
'cand_eval_result cannot be empty or no loss is found in it.')
return curr_best_eval_result[default_key] > cand_eval_result[default_key] | [
"def",
"_default_compare_fn",
"(",
"curr_best_eval_result",
",",
"cand_eval_result",
")",
":",
"default_key",
"=",
"metric_key",
".",
"MetricKey",
".",
"LOSS",
"if",
"not",
"curr_best_eval_result",
"or",
"default_key",
"not",
"in",
"curr_best_eval_result",
":",
"raise",
"ValueError",
"(",
"'curr_best_eval_result cannot be empty or no loss is found in it.'",
")",
"if",
"not",
"cand_eval_result",
"or",
"default_key",
"not",
"in",
"cand_eval_result",
":",
"raise",
"ValueError",
"(",
"'cand_eval_result cannot be empty or no loss is found in it.'",
")",
"return",
"curr_best_eval_result",
"[",
"default_key",
"]",
">",
"cand_eval_result",
"[",
"default_key",
"]"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/utils/saved_model_export_utils.py#L546-L571 |
|
vslavik/poedit | f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a | deps/boost/tools/build/src/build/type.py | python | set_scanner | (type, scanner) | Sets a scanner class that will be used for this 'type'. | Sets a scanner class that will be used for this 'type'. | [
"Sets",
"a",
"scanner",
"class",
"that",
"will",
"be",
"used",
"for",
"this",
"type",
"."
] | def set_scanner (type, scanner):
""" Sets a scanner class that will be used for this 'type'.
"""
if __debug__:
from .scanner import Scanner
assert isinstance(type, basestring)
assert issubclass(scanner, Scanner)
validate (type)
__types [type]['scanner'] = scanner | [
"def",
"set_scanner",
"(",
"type",
",",
"scanner",
")",
":",
"if",
"__debug__",
":",
"from",
".",
"scanner",
"import",
"Scanner",
"assert",
"isinstance",
"(",
"type",
",",
"basestring",
")",
"assert",
"issubclass",
"(",
"scanner",
",",
"Scanner",
")",
"validate",
"(",
"type",
")",
"__types",
"[",
"type",
"]",
"[",
"'scanner'",
"]",
"=",
"scanner"
] | https://github.com/vslavik/poedit/blob/f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a/deps/boost/tools/build/src/build/type.py#L150-L158 |
||
deepmind/streetlearn | ccf1d60b9c45154894d45a897748aee85d7eb69b | streetlearn/python/agents/city_nav_agent.py | python | CityNavAgent._core | (self, core_input, core_state) | return core_output, core_state | Assemble the recurrent core network components. | Assemble the recurrent core network components. | [
"Assemble",
"the",
"recurrent",
"core",
"network",
"components",
"."
] | def _core(self, core_input, core_state):
"""Assemble the recurrent core network components."""
(conv_output, action_reward, goal) = core_input
# Get the states
policy_state, locale_state = core_state
# Locale-specific pathway
locale_input = conv_output
locale_output, locale_state = self._locale_pathway((locale_input, goal),
locale_state)
(lstm_output, heading_output, xy_output, target_xy_output) = locale_output
# Policy LSTM
policy_input = self._locale_bottleneck(lstm_output)
if self._skip_connection:
policy_input = tf.concat([policy_input, conv_output], axis=1)
if self._feed_action_and_reward:
policy_input = tf.concat([policy_input, action_reward], axis=1)
policy_input = tf.identity(policy_input, name="policy_input")
policy_output, policy_state = self._policy_lstm(policy_input, policy_state)
core_output = (policy_output, heading_output, xy_output, target_xy_output)
core_state_list = []
core_state_list.append(policy_state)
core_state_list.append(locale_state)
core_state = tuple(core_state_list)
return core_output, core_state | [
"def",
"_core",
"(",
"self",
",",
"core_input",
",",
"core_state",
")",
":",
"(",
"conv_output",
",",
"action_reward",
",",
"goal",
")",
"=",
"core_input",
"# Get the states",
"policy_state",
",",
"locale_state",
"=",
"core_state",
"# Locale-specific pathway",
"locale_input",
"=",
"conv_output",
"locale_output",
",",
"locale_state",
"=",
"self",
".",
"_locale_pathway",
"(",
"(",
"locale_input",
",",
"goal",
")",
",",
"locale_state",
")",
"(",
"lstm_output",
",",
"heading_output",
",",
"xy_output",
",",
"target_xy_output",
")",
"=",
"locale_output",
"# Policy LSTM",
"policy_input",
"=",
"self",
".",
"_locale_bottleneck",
"(",
"lstm_output",
")",
"if",
"self",
".",
"_skip_connection",
":",
"policy_input",
"=",
"tf",
".",
"concat",
"(",
"[",
"policy_input",
",",
"conv_output",
"]",
",",
"axis",
"=",
"1",
")",
"if",
"self",
".",
"_feed_action_and_reward",
":",
"policy_input",
"=",
"tf",
".",
"concat",
"(",
"[",
"policy_input",
",",
"action_reward",
"]",
",",
"axis",
"=",
"1",
")",
"policy_input",
"=",
"tf",
".",
"identity",
"(",
"policy_input",
",",
"name",
"=",
"\"policy_input\"",
")",
"policy_output",
",",
"policy_state",
"=",
"self",
".",
"_policy_lstm",
"(",
"policy_input",
",",
"policy_state",
")",
"core_output",
"=",
"(",
"policy_output",
",",
"heading_output",
",",
"xy_output",
",",
"target_xy_output",
")",
"core_state_list",
"=",
"[",
"]",
"core_state_list",
".",
"append",
"(",
"policy_state",
")",
"core_state_list",
".",
"append",
"(",
"locale_state",
")",
"core_state",
"=",
"tuple",
"(",
"core_state_list",
")",
"return",
"core_output",
",",
"core_state"
] | https://github.com/deepmind/streetlearn/blob/ccf1d60b9c45154894d45a897748aee85d7eb69b/streetlearn/python/agents/city_nav_agent.py#L141-L169 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexes/range.py | python | RangeIndex.nbytes | (self) | return getsizeof(rng) + sum(
getsizeof(getattr(rng, attr_name))
for attr_name in ["start", "stop", "step"]
) | Return the number of bytes in the underlying data. | Return the number of bytes in the underlying data. | [
"Return",
"the",
"number",
"of",
"bytes",
"in",
"the",
"underlying",
"data",
"."
] | def nbytes(self) -> int:
"""
Return the number of bytes in the underlying data.
"""
rng = self._range
return getsizeof(rng) + sum(
getsizeof(getattr(rng, attr_name))
for attr_name in ["start", "stop", "step"]
) | [
"def",
"nbytes",
"(",
"self",
")",
"->",
"int",
":",
"rng",
"=",
"self",
".",
"_range",
"return",
"getsizeof",
"(",
"rng",
")",
"+",
"sum",
"(",
"getsizeof",
"(",
"getattr",
"(",
"rng",
",",
"attr_name",
")",
")",
"for",
"attr_name",
"in",
"[",
"\"start\"",
",",
"\"stop\"",
",",
"\"step\"",
"]",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexes/range.py#L281-L289 |
|
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | cmake/developer_package/cpplint/cpplint.py | python | CleansedLines._CollapseStrings | (elided) | return collapsed | Collapses strings and chars on a line to simple "" or '' blocks.
We nix strings first so we're not fooled by text like '"http://"'
Args:
elided: The line being processed.
Returns:
The line with collapsed strings. | Collapses strings and chars on a line to simple "" or '' blocks. | [
"Collapses",
"strings",
"and",
"chars",
"on",
"a",
"line",
"to",
"simple",
"or",
"blocks",
"."
] | def _CollapseStrings(elided):
"""Collapses strings and chars on a line to simple "" or '' blocks.
We nix strings first so we're not fooled by text like '"http://"'
Args:
elided: The line being processed.
Returns:
The line with collapsed strings.
"""
if _RE_PATTERN_INCLUDE.match(elided):
return elided
# Remove escaped characters first to make quote/single quote collapsing
# basic. Things that look like escaped characters shouldn't occur
# outside of strings and chars.
elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided)
# Replace quoted strings and digit separators. Both single quotes
# and double quotes are processed in the same loop, otherwise
# nested quotes wouldn't work.
collapsed = ''
while True:
# Find the first quote character
match = Match(r'^([^\'"]*)([\'"])(.*)$', elided)
if not match:
collapsed += elided
break
head, quote, tail = match.groups()
if quote == '"':
# Collapse double quoted strings
second_quote = tail.find('"')
if second_quote >= 0:
collapsed += head + '""'
elided = tail[second_quote + 1:]
else:
# Unmatched double quote, don't bother processing the rest
# of the line since this is probably a multiline string.
collapsed += elided
break
else:
# Found single quote, check nearby text to eliminate digit separators.
#
# There is no special handling for floating point here, because
# the integer/fractional/exponent parts would all be parsed
# correctly as long as there are digits on both sides of the
# separator. So we are fine as long as we don't see something
# like "0.'3" (gcc 4.9.0 will not allow this literal).
if Search(r'\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$', head):
match_literal = Match(r'^((?:\'?[0-9a-zA-Z_])*)(.*)$', "'" + tail)
collapsed += head + match_literal.group(1).replace("'", '')
elided = match_literal.group(2)
else:
second_quote = tail.find('\'')
if second_quote >= 0:
collapsed += head + "''"
elided = tail[second_quote + 1:]
else:
# Unmatched single quote
collapsed += elided
break
return collapsed | [
"def",
"_CollapseStrings",
"(",
"elided",
")",
":",
"if",
"_RE_PATTERN_INCLUDE",
".",
"match",
"(",
"elided",
")",
":",
"return",
"elided",
"# Remove escaped characters first to make quote/single quote collapsing",
"# basic. Things that look like escaped characters shouldn't occur",
"# outside of strings and chars.",
"elided",
"=",
"_RE_PATTERN_CLEANSE_LINE_ESCAPES",
".",
"sub",
"(",
"''",
",",
"elided",
")",
"# Replace quoted strings and digit separators. Both single quotes",
"# and double quotes are processed in the same loop, otherwise",
"# nested quotes wouldn't work.",
"collapsed",
"=",
"''",
"while",
"True",
":",
"# Find the first quote character",
"match",
"=",
"Match",
"(",
"r'^([^\\'\"]*)([\\'\"])(.*)$'",
",",
"elided",
")",
"if",
"not",
"match",
":",
"collapsed",
"+=",
"elided",
"break",
"head",
",",
"quote",
",",
"tail",
"=",
"match",
".",
"groups",
"(",
")",
"if",
"quote",
"==",
"'\"'",
":",
"# Collapse double quoted strings",
"second_quote",
"=",
"tail",
".",
"find",
"(",
"'\"'",
")",
"if",
"second_quote",
">=",
"0",
":",
"collapsed",
"+=",
"head",
"+",
"'\"\"'",
"elided",
"=",
"tail",
"[",
"second_quote",
"+",
"1",
":",
"]",
"else",
":",
"# Unmatched double quote, don't bother processing the rest",
"# of the line since this is probably a multiline string.",
"collapsed",
"+=",
"elided",
"break",
"else",
":",
"# Found single quote, check nearby text to eliminate digit separators.",
"#",
"# There is no special handling for floating point here, because",
"# the integer/fractional/exponent parts would all be parsed",
"# correctly as long as there are digits on both sides of the",
"# separator. So we are fine as long as we don't see something",
"# like \"0.'3\" (gcc 4.9.0 will not allow this literal).",
"if",
"Search",
"(",
"r'\\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$'",
",",
"head",
")",
":",
"match_literal",
"=",
"Match",
"(",
"r'^((?:\\'?[0-9a-zA-Z_])*)(.*)$'",
",",
"\"'\"",
"+",
"tail",
")",
"collapsed",
"+=",
"head",
"+",
"match_literal",
".",
"group",
"(",
"1",
")",
".",
"replace",
"(",
"\"'\"",
",",
"''",
")",
"elided",
"=",
"match_literal",
".",
"group",
"(",
"2",
")",
"else",
":",
"second_quote",
"=",
"tail",
".",
"find",
"(",
"'\\''",
")",
"if",
"second_quote",
">=",
"0",
":",
"collapsed",
"+=",
"head",
"+",
"\"''\"",
"elided",
"=",
"tail",
"[",
"second_quote",
"+",
"1",
":",
"]",
"else",
":",
"# Unmatched single quote",
"collapsed",
"+=",
"elided",
"break",
"return",
"collapsed"
] | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/cmake/developer_package/cpplint/cpplint.py#L1677-L1741 |
|
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/training/proximal_adagrad.py | python | ProximalAdagradOptimizer.__init__ | (self, learning_rate, initial_accumulator_value=0.1,
l1_regularization_strength=0.0, l2_regularization_strength=0.0,
use_locking=False, name="ProximalAdagrad") | Construct a new ProximalAdagrad optimizer.
Args:
learning_rate: A `Tensor` or a floating point value. The learning rate.
initial_accumulator_value: A floating point value.
Starting value for the accumulators, must be positive.
l1_regularization_strength: A float value, must be greater than or
equal to zero.
l2_regularization_strength: A float value, must be greater than or
equal to zero.
use_locking: If `True` use locks for update operations.
name: Optional name prefix for the operations created when applying
gradients. Defaults to "Adagrad".
Raises:
ValueError: If the `initial_accumulator_value` is invalid. | Construct a new ProximalAdagrad optimizer. | [
"Construct",
"a",
"new",
"ProximalAdagrad",
"optimizer",
"."
] | def __init__(self, learning_rate, initial_accumulator_value=0.1,
l1_regularization_strength=0.0, l2_regularization_strength=0.0,
use_locking=False, name="ProximalAdagrad"):
"""Construct a new ProximalAdagrad optimizer.
Args:
learning_rate: A `Tensor` or a floating point value. The learning rate.
initial_accumulator_value: A floating point value.
Starting value for the accumulators, must be positive.
l1_regularization_strength: A float value, must be greater than or
equal to zero.
l2_regularization_strength: A float value, must be greater than or
equal to zero.
use_locking: If `True` use locks for update operations.
name: Optional name prefix for the operations created when applying
gradients. Defaults to "Adagrad".
Raises:
ValueError: If the `initial_accumulator_value` is invalid.
"""
if initial_accumulator_value <= 0.0:
raise ValueError("initial_accumulator_value must be positive: %s" %
initial_accumulator_value)
super(ProximalAdagradOptimizer, self).__init__(use_locking, name)
self._learning_rate = learning_rate
self._initial_accumulator_value = initial_accumulator_value
self._l1_regularization_strength = l1_regularization_strength
self._l2_regularization_strength = l2_regularization_strength
# Created in Initialize.
self._l1_regularization_strength_tensor = None
self._l2_regularization_strength_tensor = None
self._learning_rate_tensor = None | [
"def",
"__init__",
"(",
"self",
",",
"learning_rate",
",",
"initial_accumulator_value",
"=",
"0.1",
",",
"l1_regularization_strength",
"=",
"0.0",
",",
"l2_regularization_strength",
"=",
"0.0",
",",
"use_locking",
"=",
"False",
",",
"name",
"=",
"\"ProximalAdagrad\"",
")",
":",
"if",
"initial_accumulator_value",
"<=",
"0.0",
":",
"raise",
"ValueError",
"(",
"\"initial_accumulator_value must be positive: %s\"",
"%",
"initial_accumulator_value",
")",
"super",
"(",
"ProximalAdagradOptimizer",
",",
"self",
")",
".",
"__init__",
"(",
"use_locking",
",",
"name",
")",
"self",
".",
"_learning_rate",
"=",
"learning_rate",
"self",
".",
"_initial_accumulator_value",
"=",
"initial_accumulator_value",
"self",
".",
"_l1_regularization_strength",
"=",
"l1_regularization_strength",
"self",
".",
"_l2_regularization_strength",
"=",
"l2_regularization_strength",
"# Created in Initialize.",
"self",
".",
"_l1_regularization_strength_tensor",
"=",
"None",
"self",
".",
"_l2_regularization_strength_tensor",
"=",
"None",
"self",
".",
"_learning_rate_tensor",
"=",
"None"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/training/proximal_adagrad.py#L36-L67 |
||
moderngl/moderngl | 32fe79927e02b0fa893b3603d677bdae39771e14 | moderngl/texture_3d.py | python | Texture3D.components | (self) | return self._components | int: The number of components of the texture. | int: The number of components of the texture. | [
"int",
":",
"The",
"number",
"of",
"components",
"of",
"the",
"texture",
"."
] | def components(self) -> int:
'''
int: The number of components of the texture.
'''
return self._components | [
"def",
"components",
"(",
"self",
")",
"->",
"int",
":",
"return",
"self",
".",
"_components"
] | https://github.com/moderngl/moderngl/blob/32fe79927e02b0fa893b3603d677bdae39771e14/moderngl/texture_3d.py#L192-L197 |
|
rapidsai/cudf | d5b2448fc69f17509304d594f029d0df56984962 | python/cudf/cudf/utils/applyutils.py | python | apply_chunks | (
df,
func,
incols,
outcols,
kwargs,
pessimistic_nulls,
chunks,
blkct=None,
tpb=None,
) | return applychunks.run(df, chunks=chunks, tpb=tpb) | Chunk-wise transformation
Parameters
----------
{params}
{params_chunks} | Chunk-wise transformation | [
"Chunk",
"-",
"wise",
"transformation"
] | def apply_chunks(
df,
func,
incols,
outcols,
kwargs,
pessimistic_nulls,
chunks,
blkct=None,
tpb=None,
):
"""Chunk-wise transformation
Parameters
----------
{params}
{params_chunks}
"""
applychunks = ApplyChunksCompiler(
func, incols, outcols, kwargs, pessimistic_nulls, cache_key=None
)
return applychunks.run(df, chunks=chunks, tpb=tpb) | [
"def",
"apply_chunks",
"(",
"df",
",",
"func",
",",
"incols",
",",
"outcols",
",",
"kwargs",
",",
"pessimistic_nulls",
",",
"chunks",
",",
"blkct",
"=",
"None",
",",
"tpb",
"=",
"None",
",",
")",
":",
"applychunks",
"=",
"ApplyChunksCompiler",
"(",
"func",
",",
"incols",
",",
"outcols",
",",
"kwargs",
",",
"pessimistic_nulls",
",",
"cache_key",
"=",
"None",
")",
"return",
"applychunks",
".",
"run",
"(",
"df",
",",
"chunks",
"=",
"chunks",
",",
"tpb",
"=",
"tpb",
")"
] | https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/utils/applyutils.py#L82-L103 |
|
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/layers/detection.py | python | target_assign | (input,
matched_indices,
negative_indices=None,
mismatch_value=None,
name=None) | return out, out_weight | This operator can be, for given the target bounding boxes or labels,
to assign classification and regression targets to each prediction as well as
weights to prediction. The weights is used to specify which prediction would
not contribute to training loss.
For each instance, the output `out` and`out_weight` are assigned based on
`match_indices` and `negative_indices`.
Assumed that the row offset for each instance in `input` is called lod,
this operator assigns classification/regression targets by performing the
following steps:
1. Assigning all outputs based on `match_indices`:
.. code-block:: text
If id = match_indices[i][j] > 0,
out[i][j][0 : K] = X[lod[i] + id][j % P][0 : K]
out_weight[i][j] = 1.
Otherwise,
out[j][j][0 : K] = {mismatch_value, mismatch_value, ...}
out_weight[i][j] = 0.
2. Assigning outputs based on `neg_indices` if `neg_indices` is provided:
Assumed that i-th instance in `neg_indices` is called `neg_indice`,
for i-th instance:
.. code-block:: text
for id in neg_indice:
out[i][id][0 : K] = {mismatch_value, mismatch_value, ...}
out_weight[i][id] = 1.0
Args:
input (Variable): This input is a 3D LoDTensor with shape [M, P, K].
Data type should be int32 or float32.
matched_indices (Variable): The input matched indices
is 2D Tenosr<int32> with shape [N, P], If MatchIndices[i][j] is -1,
the j-th entity of column is not matched to any entity of row in
i-th instance.
negative_indices (Variable, optional): The input negative example indices
are an optional input with shape [Neg, 1] and int32 type, where Neg is
the total number of negative example indices.
mismatch_value (float32, optional): Fill this value to the mismatched
location.
name (string): The default value is None. Normally there is no need for
user to set this property. For more information, please refer
to :ref:`api_guide_Name`.
Returns:
tuple: A tuple(out, out_weight) is returned.
out (Variable): a 3D Tensor with shape [N, P, K] and same data type
with `input`, N and P is the same as they are in `matched_indices`,
K is the same as it in input of X.
out_weight (Variable): the weight for output with the shape of [N, P, 1].
Data type is float32.
Examples:
.. code-block:: python
import paddle.fluid as fluid
import paddle
paddle.enable_static()
x = fluid.data(
name='x',
shape=[4, 20, 4],
dtype='float',
lod_level=1)
matched_id = fluid.data(
name='indices',
shape=[8, 20],
dtype='int32')
trg, trg_weight = fluid.layers.target_assign(
x,
matched_id,
mismatch_value=0) | [] | def target_assign(input,
matched_indices,
negative_indices=None,
mismatch_value=None,
name=None):
"""
This operator can be, for given the target bounding boxes or labels,
to assign classification and regression targets to each prediction as well as
weights to prediction. The weights is used to specify which prediction would
not contribute to training loss.
For each instance, the output `out` and`out_weight` are assigned based on
`match_indices` and `negative_indices`.
Assumed that the row offset for each instance in `input` is called lod,
this operator assigns classification/regression targets by performing the
following steps:
1. Assigning all outputs based on `match_indices`:
.. code-block:: text
If id = match_indices[i][j] > 0,
out[i][j][0 : K] = X[lod[i] + id][j % P][0 : K]
out_weight[i][j] = 1.
Otherwise,
out[j][j][0 : K] = {mismatch_value, mismatch_value, ...}
out_weight[i][j] = 0.
2. Assigning outputs based on `neg_indices` if `neg_indices` is provided:
Assumed that i-th instance in `neg_indices` is called `neg_indice`,
for i-th instance:
.. code-block:: text
for id in neg_indice:
out[i][id][0 : K] = {mismatch_value, mismatch_value, ...}
out_weight[i][id] = 1.0
Args:
input (Variable): This input is a 3D LoDTensor with shape [M, P, K].
Data type should be int32 or float32.
matched_indices (Variable): The input matched indices
is 2D Tenosr<int32> with shape [N, P], If MatchIndices[i][j] is -1,
the j-th entity of column is not matched to any entity of row in
i-th instance.
negative_indices (Variable, optional): The input negative example indices
are an optional input with shape [Neg, 1] and int32 type, where Neg is
the total number of negative example indices.
mismatch_value (float32, optional): Fill this value to the mismatched
location.
name (string): The default value is None. Normally there is no need for
user to set this property. For more information, please refer
to :ref:`api_guide_Name`.
Returns:
tuple: A tuple(out, out_weight) is returned.
out (Variable): a 3D Tensor with shape [N, P, K] and same data type
with `input`, N and P is the same as they are in `matched_indices`,
K is the same as it in input of X.
out_weight (Variable): the weight for output with the shape of [N, P, 1].
Data type is float32.
Examples:
.. code-block:: python
import paddle.fluid as fluid
import paddle
paddle.enable_static()
x = fluid.data(
name='x',
shape=[4, 20, 4],
dtype='float',
lod_level=1)
matched_id = fluid.data(
name='indices',
shape=[8, 20],
dtype='int32')
trg, trg_weight = fluid.layers.target_assign(
x,
matched_id,
mismatch_value=0)
"""
helper = LayerHelper('target_assign', **locals())
out = helper.create_variable_for_type_inference(dtype=input.dtype)
out_weight = helper.create_variable_for_type_inference(dtype='float32')
helper.append_op(
type='target_assign',
inputs={
'X': input,
'MatchIndices': matched_indices,
'NegIndices': negative_indices
},
outputs={'Out': out,
'OutWeight': out_weight},
attrs={'mismatch_value': mismatch_value})
return out, out_weight | [
"def",
"target_assign",
"(",
"input",
",",
"matched_indices",
",",
"negative_indices",
"=",
"None",
",",
"mismatch_value",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"helper",
"=",
"LayerHelper",
"(",
"'target_assign'",
",",
"*",
"*",
"locals",
"(",
")",
")",
"out",
"=",
"helper",
".",
"create_variable_for_type_inference",
"(",
"dtype",
"=",
"input",
".",
"dtype",
")",
"out_weight",
"=",
"helper",
".",
"create_variable_for_type_inference",
"(",
"dtype",
"=",
"'float32'",
")",
"helper",
".",
"append_op",
"(",
"type",
"=",
"'target_assign'",
",",
"inputs",
"=",
"{",
"'X'",
":",
"input",
",",
"'MatchIndices'",
":",
"matched_indices",
",",
"'NegIndices'",
":",
"negative_indices",
"}",
",",
"outputs",
"=",
"{",
"'Out'",
":",
"out",
",",
"'OutWeight'",
":",
"out_weight",
"}",
",",
"attrs",
"=",
"{",
"'mismatch_value'",
":",
"mismatch_value",
"}",
")",
"return",
"out",
",",
"out_weight"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/layers/detection.py#L1414-L1517 |
||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/logging/__init__.py | python | Handler.emit | (self, record) | Do whatever it takes to actually log the specified logging record.
This version is intended to be implemented by subclasses and so
raises a NotImplementedError. | Do whatever it takes to actually log the specified logging record. | [
"Do",
"whatever",
"it",
"takes",
"to",
"actually",
"log",
"the",
"specified",
"logging",
"record",
"."
] | def emit(self, record):
"""
Do whatever it takes to actually log the specified logging record.
This version is intended to be implemented by subclasses and so
raises a NotImplementedError.
"""
raise NotImplementedError('emit must be implemented '
'by Handler subclasses') | [
"def",
"emit",
"(",
"self",
",",
"record",
")",
":",
"raise",
"NotImplementedError",
"(",
"'emit must be implemented '",
"'by Handler subclasses'",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/logging/__init__.py#L726-L734 |
||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/requests/models.py | python | Response.text | (self) | return content | Content of the response, in unicode.
If Response.encoding is None, encoding will be guessed using
``chardet``.
The encoding of the response content is determined based solely on HTTP
headers, following RFC 2616 to the letter. If you can take advantage of
non-HTTP knowledge to make a better guess at the encoding, you should
set ``r.encoding`` appropriately before accessing this property. | Content of the response, in unicode. | [
"Content",
"of",
"the",
"response",
"in",
"unicode",
"."
] | def text(self):
"""Content of the response, in unicode.
If Response.encoding is None, encoding will be guessed using
``chardet``.
The encoding of the response content is determined based solely on HTTP
headers, following RFC 2616 to the letter. If you can take advantage of
non-HTTP knowledge to make a better guess at the encoding, you should
set ``r.encoding`` appropriately before accessing this property.
"""
# Try charset from content-type
content = None
encoding = self.encoding
if not self.content:
return str('')
# Fallback to auto-detected encoding.
if self.encoding is None:
encoding = self.apparent_encoding
# Decode unicode from given encoding.
try:
content = str(self.content, encoding, errors='replace')
except (LookupError, TypeError):
# A LookupError is raised if the encoding was not found which could
# indicate a misspelling or similar mistake.
#
# A TypeError can be raised if encoding is None
#
# So we try blindly encoding.
content = str(self.content, errors='replace')
return content | [
"def",
"text",
"(",
"self",
")",
":",
"# Try charset from content-type",
"content",
"=",
"None",
"encoding",
"=",
"self",
".",
"encoding",
"if",
"not",
"self",
".",
"content",
":",
"return",
"str",
"(",
"''",
")",
"# Fallback to auto-detected encoding.",
"if",
"self",
".",
"encoding",
"is",
"None",
":",
"encoding",
"=",
"self",
".",
"apparent_encoding",
"# Decode unicode from given encoding.",
"try",
":",
"content",
"=",
"str",
"(",
"self",
".",
"content",
",",
"encoding",
",",
"errors",
"=",
"'replace'",
")",
"except",
"(",
"LookupError",
",",
"TypeError",
")",
":",
"# A LookupError is raised if the encoding was not found which could",
"# indicate a misspelling or similar mistake.",
"#",
"# A TypeError can be raised if encoding is None",
"#",
"# So we try blindly encoding.",
"content",
"=",
"str",
"(",
"self",
".",
"content",
",",
"errors",
"=",
"'replace'",
")",
"return",
"content"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/requests/models.py#L839-L874 |
|
rdkit/rdkit | ede860ae316d12d8568daf5ee800921c3389c84e | rdkit/Chem/MolStandardize/standardize.py | python | Standardizer.isotope_parent | (self, mol, skip_standardize=False) | return mol | Return the isotope parent of a given molecule.
The isotope parent has all atoms replaced with the most abundant isotope for that element.
:param mol: The input molecule.
:type mol: :rdkit:`Mol <Chem.rdchem.Mol-class.html>`
:param bool skip_standardize: Set to True if mol has already been standardized.
:returns: The isotope parent molecule.
:rtype: :rdkit:`Mol <Chem.rdchem.Mol-class.html>` | Return the isotope parent of a given molecule. | [
"Return",
"the",
"isotope",
"parent",
"of",
"a",
"given",
"molecule",
"."
] | def isotope_parent(self, mol, skip_standardize=False):
"""Return the isotope parent of a given molecule.
The isotope parent has all atoms replaced with the most abundant isotope for that element.
:param mol: The input molecule.
:type mol: :rdkit:`Mol <Chem.rdchem.Mol-class.html>`
:param bool skip_standardize: Set to True if mol has already been standardized.
:returns: The isotope parent molecule.
:rtype: :rdkit:`Mol <Chem.rdchem.Mol-class.html>`
"""
if not skip_standardize:
mol = self.standardize(mol)
else:
mol = copy.deepcopy(mol)
# Replace isotopes with common weight
for atom in mol.GetAtoms():
atom.SetIsotope(0)
return mol | [
"def",
"isotope_parent",
"(",
"self",
",",
"mol",
",",
"skip_standardize",
"=",
"False",
")",
":",
"if",
"not",
"skip_standardize",
":",
"mol",
"=",
"self",
".",
"standardize",
"(",
"mol",
")",
"else",
":",
"mol",
"=",
"copy",
".",
"deepcopy",
"(",
"mol",
")",
"# Replace isotopes with common weight",
"for",
"atom",
"in",
"mol",
".",
"GetAtoms",
"(",
")",
":",
"atom",
".",
"SetIsotope",
"(",
"0",
")",
"return",
"mol"
] | https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/Chem/MolStandardize/standardize.py#L155-L173 |
|
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Canvas.type | (self, tagOrId) | return self.tk.call(self._w, 'type', tagOrId) or None | Return the type of the item TAGORID. | Return the type of the item TAGORID. | [
"Return",
"the",
"type",
"of",
"the",
"item",
"TAGORID",
"."
] | def type(self, tagOrId):
"""Return the type of the item TAGORID."""
return self.tk.call(self._w, 'type', tagOrId) or None | [
"def",
"type",
"(",
"self",
",",
"tagOrId",
")",
":",
"return",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"'type'",
",",
"tagOrId",
")",
"or",
"None"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py#L2401-L2403 |
|
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Job.py | python | Jobs.were_interrupted | (self) | return self.job.interrupted() | Returns whether the jobs were interrupted by a signal. | Returns whether the jobs were interrupted by a signal. | [
"Returns",
"whether",
"the",
"jobs",
"were",
"interrupted",
"by",
"a",
"signal",
"."
] | def were_interrupted(self):
"""Returns whether the jobs were interrupted by a signal."""
return self.job.interrupted() | [
"def",
"were_interrupted",
"(",
"self",
")",
":",
"return",
"self",
".",
"job",
".",
"interrupted",
"(",
")"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Job.py#L116-L118 |
|
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/cr/cr/commands/init.py | python | InitCommand.Run | (self, context) | Overridden from cr.Command. | Overridden from cr.Command. | [
"Overridden",
"from",
"cr",
".",
"Command",
"."
] | def Run(self, context):
"""Overridden from cr.Command."""
src_path = context.Get('CR_SRC')
if not os.path.isdir(src_path):
print context.Substitute('Path {CR_SRC} is not a valid client')
exit(1)
# Ensure we have an output directory override ready to fill in
# This will only be missing if we are creating a brand new output
# directory
build_package = cr.auto.build
# Collect the old version (and float convert)
old_version = context.Find('CR_VERSION')
try:
old_version = float(old_version)
except (ValueError, TypeError):
old_version = 0.0
is_new = not hasattr(build_package, 'config')
if is_new:
class FakeModule(object):
OVERRIDES = cr.Config('OVERRIDES')
def __init__(self):
self.__name__ = 'config'
old_version = None
config = FakeModule()
setattr(build_package, 'config', config)
cr.plugin.ChainModuleConfigs(config)
# Force override the version
build_package.config.OVERRIDES.Set(CR_VERSION=cr.base.client.VERSION)
# Add all the variables that we always want to have
for name in OUT_CONFIG_VARS:
value = context.Find(name)
build_package.config.OVERRIDES[name] = value
# Apply the settings from the command line
for setting in self._settings:
name, separator, value = setting.partition('=')
name = name.strip()
if not separator:
value = True
else:
value = cr.Config.ParseValue(value.strip())
build_package.config.OVERRIDES[name] = value
# Run all the output directory init hooks
for hook in InitHook.Plugins():
hook.Run(context, old_version, build_package.config)
# Redo activations, they might have changed
cr.plugin.Activate(context)
# Write out the new configuration, and select it as the default
cr.base.client.WriteConfig(context, context.Get('CR_BUILD_DIR'),
build_package.config.OVERRIDES.exported)
# Prepare the platform in here, using the updated config
cr.Platform.Prepare(context)
cr.SelectCommand.Select(context) | [
"def",
"Run",
"(",
"self",
",",
"context",
")",
":",
"src_path",
"=",
"context",
".",
"Get",
"(",
"'CR_SRC'",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"src_path",
")",
":",
"print",
"context",
".",
"Substitute",
"(",
"'Path {CR_SRC} is not a valid client'",
")",
"exit",
"(",
"1",
")",
"# Ensure we have an output directory override ready to fill in",
"# This will only be missing if we are creating a brand new output",
"# directory",
"build_package",
"=",
"cr",
".",
"auto",
".",
"build",
"# Collect the old version (and float convert)",
"old_version",
"=",
"context",
".",
"Find",
"(",
"'CR_VERSION'",
")",
"try",
":",
"old_version",
"=",
"float",
"(",
"old_version",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"old_version",
"=",
"0.0",
"is_new",
"=",
"not",
"hasattr",
"(",
"build_package",
",",
"'config'",
")",
"if",
"is_new",
":",
"class",
"FakeModule",
"(",
"object",
")",
":",
"OVERRIDES",
"=",
"cr",
".",
"Config",
"(",
"'OVERRIDES'",
")",
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"__name__",
"=",
"'config'",
"old_version",
"=",
"None",
"config",
"=",
"FakeModule",
"(",
")",
"setattr",
"(",
"build_package",
",",
"'config'",
",",
"config",
")",
"cr",
".",
"plugin",
".",
"ChainModuleConfigs",
"(",
"config",
")",
"# Force override the version",
"build_package",
".",
"config",
".",
"OVERRIDES",
".",
"Set",
"(",
"CR_VERSION",
"=",
"cr",
".",
"base",
".",
"client",
".",
"VERSION",
")",
"# Add all the variables that we always want to have",
"for",
"name",
"in",
"OUT_CONFIG_VARS",
":",
"value",
"=",
"context",
".",
"Find",
"(",
"name",
")",
"build_package",
".",
"config",
".",
"OVERRIDES",
"[",
"name",
"]",
"=",
"value",
"# Apply the settings from the command line",
"for",
"setting",
"in",
"self",
".",
"_settings",
":",
"name",
",",
"separator",
",",
"value",
"=",
"setting",
".",
"partition",
"(",
"'='",
")",
"name",
"=",
"name",
".",
"strip",
"(",
")",
"if",
"not",
"separator",
":",
"value",
"=",
"True",
"else",
":",
"value",
"=",
"cr",
".",
"Config",
".",
"ParseValue",
"(",
"value",
".",
"strip",
"(",
")",
")",
"build_package",
".",
"config",
".",
"OVERRIDES",
"[",
"name",
"]",
"=",
"value",
"# Run all the output directory init hooks",
"for",
"hook",
"in",
"InitHook",
".",
"Plugins",
"(",
")",
":",
"hook",
".",
"Run",
"(",
"context",
",",
"old_version",
",",
"build_package",
".",
"config",
")",
"# Redo activations, they might have changed",
"cr",
".",
"plugin",
".",
"Activate",
"(",
"context",
")",
"# Write out the new configuration, and select it as the default",
"cr",
".",
"base",
".",
"client",
".",
"WriteConfig",
"(",
"context",
",",
"context",
".",
"Get",
"(",
"'CR_BUILD_DIR'",
")",
",",
"build_package",
".",
"config",
".",
"OVERRIDES",
".",
"exported",
")",
"# Prepare the platform in here, using the updated config",
"cr",
".",
"Platform",
".",
"Prepare",
"(",
"context",
")",
"cr",
".",
"SelectCommand",
".",
"Select",
"(",
"context",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/cr/cr/commands/init.py#L99-L158 |
||
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/tools/cpplint.py | python | _BlockInfo.CheckBegin | (self, filename, clean_lines, linenum, error) | Run checks that applies to text up to the opening brace.
This is mostly for checking the text after the class identifier
and the "{", usually where the base class is specified. For other
blocks, there isn't much to check, so we always pass.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Run checks that applies to text up to the opening brace. | [
"Run",
"checks",
"that",
"applies",
"to",
"text",
"up",
"to",
"the",
"opening",
"brace",
"."
] | def CheckBegin(self, filename, clean_lines, linenum, error):
"""Run checks that applies to text up to the opening brace.
This is mostly for checking the text after the class identifier
and the "{", usually where the base class is specified. For other
blocks, there isn't much to check, so we always pass.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
pass | [
"def",
"CheckBegin",
"(",
"self",
",",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"pass"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/cpplint.py#L2317-L2330 |
||
lhmRyan/deep-supervised-hashing-DSH | 631901f82e2ab031fbac33f914a5b08ef8e21d57 | scripts/cpp_lint.py | python | CheckCaffeAlternatives | (filename, clean_lines, linenum, error) | Checks for C(++) functions for which a Caffe substitute should be used.
For certain native C functions (memset, memcpy), there is a Caffe alternative
which should be used instead.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Checks for C(++) functions for which a Caffe substitute should be used. | [
"Checks",
"for",
"C",
"(",
"++",
")",
"functions",
"for",
"which",
"a",
"Caffe",
"substitute",
"should",
"be",
"used",
"."
] | def CheckCaffeAlternatives(filename, clean_lines, linenum, error):
"""Checks for C(++) functions for which a Caffe substitute should be used.
For certain native C functions (memset, memcpy), there is a Caffe alternative
which should be used instead.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
for function, alts in caffe_alt_function_list:
ix = line.find(function + '(')
if ix >= 0 and (ix == 0 or (not line[ix - 1].isalnum() and
line[ix - 1] not in ('_', '.', '>'))):
disp_alts = ['%s(...)' % alt for alt in alts]
error(filename, linenum, 'caffe/alt_fn', 2,
'Use Caffe function %s instead of %s(...).' %
(' or '.join(disp_alts), function)) | [
"def",
"CheckCaffeAlternatives",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"for",
"function",
",",
"alts",
"in",
"caffe_alt_function_list",
":",
"ix",
"=",
"line",
".",
"find",
"(",
"function",
"+",
"'('",
")",
"if",
"ix",
">=",
"0",
"and",
"(",
"ix",
"==",
"0",
"or",
"(",
"not",
"line",
"[",
"ix",
"-",
"1",
"]",
".",
"isalnum",
"(",
")",
"and",
"line",
"[",
"ix",
"-",
"1",
"]",
"not",
"in",
"(",
"'_'",
",",
"'.'",
",",
"'>'",
")",
")",
")",
":",
"disp_alts",
"=",
"[",
"'%s(...)'",
"%",
"alt",
"for",
"alt",
"in",
"alts",
"]",
"error",
"(",
"filename",
",",
"linenum",
",",
"'caffe/alt_fn'",
",",
"2",
",",
"'Use Caffe function %s instead of %s(...).'",
"%",
"(",
"' or '",
".",
"join",
"(",
"disp_alts",
")",
",",
"function",
")",
")"
] | https://github.com/lhmRyan/deep-supervised-hashing-DSH/blob/631901f82e2ab031fbac33f914a5b08ef8e21d57/scripts/cpp_lint.py#L1572-L1592 |
||
Tencent/CMONGO | c40380caa14e05509f46993aa8b8da966b09b0b5 | src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Environment.py | python | OverrideEnvironment.Dictionary | (self) | return d | Emulates the items() method of dictionaries. | Emulates the items() method of dictionaries. | [
"Emulates",
"the",
"items",
"()",
"method",
"of",
"dictionaries",
"."
] | def Dictionary(self):
"""Emulates the items() method of dictionaries."""
d = self.__dict__['__subject'].Dictionary().copy()
d.update(self.__dict__['overrides'])
return d | [
"def",
"Dictionary",
"(",
"self",
")",
":",
"d",
"=",
"self",
".",
"__dict__",
"[",
"'__subject'",
"]",
".",
"Dictionary",
"(",
")",
".",
"copy",
"(",
")",
"d",
".",
"update",
"(",
"self",
".",
"__dict__",
"[",
"'overrides'",
"]",
")",
"return",
"d"
] | https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Environment.py#L2334-L2338 |
|
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/utilities/workspace_data_utils.py | python | x_limits_of_workspace | (workspace_name: str, default_limits: tuple = (DEFAULT_X_LOWER, DEFAULT_X_UPPER)) | return default_limits | Returns the x data limits of a provided workspace. | Returns the x data limits of a provided workspace. | [
"Returns",
"the",
"x",
"data",
"limits",
"of",
"a",
"provided",
"workspace",
"."
] | def x_limits_of_workspace(workspace_name: str, default_limits: tuple = (DEFAULT_X_LOWER, DEFAULT_X_UPPER)) -> tuple:
"""Returns the x data limits of a provided workspace."""
if workspace_name is not None and check_if_workspace_exist(workspace_name):
x_data = retrieve_ws(workspace_name).dataX(0)
if len(x_data) > 0:
x_data.sort()
x_lower, x_higher = x_data[0], x_data[-1]
# An offset is applied because if the x_lower is rounded up due to the precision of the Muon GUI, then some
# data points could be missed out unintentionally. A similar issue could happen if the x_higher were rounded
# down due to the GUI precision.
return x_lower - X_OFFSET, x_higher + X_OFFSET
return default_limits | [
"def",
"x_limits_of_workspace",
"(",
"workspace_name",
":",
"str",
",",
"default_limits",
":",
"tuple",
"=",
"(",
"DEFAULT_X_LOWER",
",",
"DEFAULT_X_UPPER",
")",
")",
"->",
"tuple",
":",
"if",
"workspace_name",
"is",
"not",
"None",
"and",
"check_if_workspace_exist",
"(",
"workspace_name",
")",
":",
"x_data",
"=",
"retrieve_ws",
"(",
"workspace_name",
")",
".",
"dataX",
"(",
"0",
")",
"if",
"len",
"(",
"x_data",
")",
">",
"0",
":",
"x_data",
".",
"sort",
"(",
")",
"x_lower",
",",
"x_higher",
"=",
"x_data",
"[",
"0",
"]",
",",
"x_data",
"[",
"-",
"1",
"]",
"# An offset is applied because if the x_lower is rounded up due to the precision of the Muon GUI, then some",
"# data points could be missed out unintentionally. A similar issue could happen if the x_higher were rounded",
"# down due to the GUI precision.",
"return",
"x_lower",
"-",
"X_OFFSET",
",",
"x_higher",
"+",
"X_OFFSET",
"return",
"default_limits"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/utilities/workspace_data_utils.py#L14-L25 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/attrs/attr/_make.py | python | _setattr_with_converter | (attr_name, value_var, has_on_setattr) | return "_setattr('%s', %s(%s))" % (
attr_name,
_init_converter_pat % (attr_name,),
value_var,
) | Use the cached object.setattr to set *attr_name* to *value_var*, but run
its converter first. | Use the cached object.setattr to set *attr_name* to *value_var*, but run
its converter first. | [
"Use",
"the",
"cached",
"object",
".",
"setattr",
"to",
"set",
"*",
"attr_name",
"*",
"to",
"*",
"value_var",
"*",
"but",
"run",
"its",
"converter",
"first",
"."
] | def _setattr_with_converter(attr_name, value_var, has_on_setattr):
"""
Use the cached object.setattr to set *attr_name* to *value_var*, but run
its converter first.
"""
return "_setattr('%s', %s(%s))" % (
attr_name,
_init_converter_pat % (attr_name,),
value_var,
) | [
"def",
"_setattr_with_converter",
"(",
"attr_name",
",",
"value_var",
",",
"has_on_setattr",
")",
":",
"return",
"\"_setattr('%s', %s(%s))\"",
"%",
"(",
"attr_name",
",",
"_init_converter_pat",
"%",
"(",
"attr_name",
",",
")",
",",
"value_var",
",",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/attrs/attr/_make.py#L2081-L2090 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/perspective.py | python | PerspectiveManager.GetFrameManager | (self) | return self._mgr | Returns the manager for this frame
@return: Reference to the AuiMgr of this window | Returns the manager for this frame
@return: Reference to the AuiMgr of this window | [
"Returns",
"the",
"manager",
"for",
"this",
"frame",
"@return",
":",
"Reference",
"to",
"the",
"AuiMgr",
"of",
"this",
"window"
] | def GetFrameManager(self):
"""Returns the manager for this frame
@return: Reference to the AuiMgr of this window
"""
return self._mgr | [
"def",
"GetFrameManager",
"(",
"self",
")",
":",
"return",
"self",
".",
"_mgr"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/perspective.py#L150-L155 |
|
ApolloAuto/apollo | 463fb82f9e979d02dcb25044e60931293ab2dba0 | modules/tools/record_analyzer/module_planning_analyzer.py | python | PlannigAnalyzer.print_sim_results | (self) | dreamland metrics for planning v2 | dreamland metrics for planning v2 | [
"dreamland",
"metrics",
"for",
"planning",
"v2"
] | def print_sim_results(self):
"""
dreamland metrics for planning v2
"""
v2_results = {}
# acceleration
v2_results["accel"] = self.lon_acceleration_analyzer.get_acceleration()
# deceleration
v2_results["decel"] = self.lon_acceleration_analyzer.get_deceleration()
# jerk
v2_results["acc_jerk"] = self.lon_acceleration_analyzer.get_acc_jerk()
v2_results["dec_jerk"] = self.lon_acceleration_analyzer.get_dec_jerk()
# centripetal_jerk
v2_results["lat_jerk"] = self.lat_acceleration_analyzer.get_jerk()
# centripetal_accel
v2_results["lat_accel"] = self.lat_acceleration_analyzer.get_acceleration()
# frame_count
v2_results["frame_count"] = self.frame_count_analyzer.get()
# latency
v2_results["planning_latency"] = self.latency_analyzer.get()
# reference line
v2_results["reference_line"] = self.reference_line.get()
# output final reuslts
print(json.dumps(v2_results)) | [
"def",
"print_sim_results",
"(",
"self",
")",
":",
"v2_results",
"=",
"{",
"}",
"# acceleration",
"v2_results",
"[",
"\"accel\"",
"]",
"=",
"self",
".",
"lon_acceleration_analyzer",
".",
"get_acceleration",
"(",
")",
"# deceleration",
"v2_results",
"[",
"\"decel\"",
"]",
"=",
"self",
".",
"lon_acceleration_analyzer",
".",
"get_deceleration",
"(",
")",
"# jerk",
"v2_results",
"[",
"\"acc_jerk\"",
"]",
"=",
"self",
".",
"lon_acceleration_analyzer",
".",
"get_acc_jerk",
"(",
")",
"v2_results",
"[",
"\"dec_jerk\"",
"]",
"=",
"self",
".",
"lon_acceleration_analyzer",
".",
"get_dec_jerk",
"(",
")",
"# centripetal_jerk",
"v2_results",
"[",
"\"lat_jerk\"",
"]",
"=",
"self",
".",
"lat_acceleration_analyzer",
".",
"get_jerk",
"(",
")",
"# centripetal_accel",
"v2_results",
"[",
"\"lat_accel\"",
"]",
"=",
"self",
".",
"lat_acceleration_analyzer",
".",
"get_acceleration",
"(",
")",
"# frame_count",
"v2_results",
"[",
"\"frame_count\"",
"]",
"=",
"self",
".",
"frame_count_analyzer",
".",
"get",
"(",
")",
"# latency",
"v2_results",
"[",
"\"planning_latency\"",
"]",
"=",
"self",
".",
"latency_analyzer",
".",
"get",
"(",
")",
"# reference line",
"v2_results",
"[",
"\"reference_line\"",
"]",
"=",
"self",
".",
"reference_line",
".",
"get",
"(",
")",
"# output final reuslts",
"print",
"(",
"json",
".",
"dumps",
"(",
"v2_results",
")",
")"
] | https://github.com/ApolloAuto/apollo/blob/463fb82f9e979d02dcb25044e60931293ab2dba0/modules/tools/record_analyzer/module_planning_analyzer.py#L173-L205 |
||
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPM2_HierarchyChangeAuth_REQUEST.__init__ | (self, authHandle = TPM_HANDLE(), newAuth = None) | This command allows the authorization secret for a hierarchy or
lockout to be changed using the current authorization value as the
command authorization.
Attributes:
authHandle (TPM_HANDLE): TPM_RH_LOCKOUT, TPM_RH_ENDORSEMENT,
TPM_RH_OWNER or TPM_RH_PLATFORM+{PP}
Auth Index: 1
Auth Role: USER
newAuth (bytes): New authorization value | This command allows the authorization secret for a hierarchy or
lockout to be changed using the current authorization value as the
command authorization. | [
"This",
"command",
"allows",
"the",
"authorization",
"secret",
"for",
"a",
"hierarchy",
"or",
"lockout",
"to",
"be",
"changed",
"using",
"the",
"current",
"authorization",
"value",
"as",
"the",
"command",
"authorization",
"."
] | def __init__(self, authHandle = TPM_HANDLE(), newAuth = None):
""" This command allows the authorization secret for a hierarchy or
lockout to be changed using the current authorization value as the
command authorization.
Attributes:
authHandle (TPM_HANDLE): TPM_RH_LOCKOUT, TPM_RH_ENDORSEMENT,
TPM_RH_OWNER or TPM_RH_PLATFORM+{PP}
Auth Index: 1
Auth Role: USER
newAuth (bytes): New authorization value
"""
self.authHandle = authHandle
self.newAuth = newAuth | [
"def",
"__init__",
"(",
"self",
",",
"authHandle",
"=",
"TPM_HANDLE",
"(",
")",
",",
"newAuth",
"=",
"None",
")",
":",
"self",
".",
"authHandle",
"=",
"authHandle",
"self",
".",
"newAuth",
"=",
"newAuth"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L15619-L15632 |
||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/sipconfig.py | python | SIPModuleMakefile.__init__ | (self, configuration, build_file, install_dir=None, static=0,
console=0, qt=0, opengl=0, threaded=0, warnings=1, debug=0,
dir=None, makefile="Makefile", installs=None, strip=1,
export_all=0, universal=None, arch=None, prot_is_public=0,
deployment_target=None) | Initialise an instance of a SIP generated module Makefile.
prot_is_public is set if "protected" is to be redefined as "public".
If the platform's C++ ABI allows it this can significantly reduce the
size of the generated code.
For all other arguments see ModuleMakefile. | Initialise an instance of a SIP generated module Makefile. | [
"Initialise",
"an",
"instance",
"of",
"a",
"SIP",
"generated",
"module",
"Makefile",
"."
] | def __init__(self, configuration, build_file, install_dir=None, static=0,
console=0, qt=0, opengl=0, threaded=0, warnings=1, debug=0,
dir=None, makefile="Makefile", installs=None, strip=1,
export_all=0, universal=None, arch=None, prot_is_public=0,
deployment_target=None):
"""Initialise an instance of a SIP generated module Makefile.
prot_is_public is set if "protected" is to be redefined as "public".
If the platform's C++ ABI allows it this can significantly reduce the
size of the generated code.
For all other arguments see ModuleMakefile.
"""
ModuleMakefile.__init__(self, configuration, build_file, install_dir,
static, console, qt, opengl, threaded, warnings, debug, dir,
makefile, installs, strip, export_all, universal, arch,
deployment_target)
self._prot_is_public = prot_is_public | [
"def",
"__init__",
"(",
"self",
",",
"configuration",
",",
"build_file",
",",
"install_dir",
"=",
"None",
",",
"static",
"=",
"0",
",",
"console",
"=",
"0",
",",
"qt",
"=",
"0",
",",
"opengl",
"=",
"0",
",",
"threaded",
"=",
"0",
",",
"warnings",
"=",
"1",
",",
"debug",
"=",
"0",
",",
"dir",
"=",
"None",
",",
"makefile",
"=",
"\"Makefile\"",
",",
"installs",
"=",
"None",
",",
"strip",
"=",
"1",
",",
"export_all",
"=",
"0",
",",
"universal",
"=",
"None",
",",
"arch",
"=",
"None",
",",
"prot_is_public",
"=",
"0",
",",
"deployment_target",
"=",
"None",
")",
":",
"ModuleMakefile",
".",
"__init__",
"(",
"self",
",",
"configuration",
",",
"build_file",
",",
"install_dir",
",",
"static",
",",
"console",
",",
"qt",
",",
"opengl",
",",
"threaded",
",",
"warnings",
",",
"debug",
",",
"dir",
",",
"makefile",
",",
"installs",
",",
"strip",
",",
"export_all",
",",
"universal",
",",
"arch",
",",
"deployment_target",
")",
"self",
".",
"_prot_is_public",
"=",
"prot_is_public"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/sipconfig.py#L1839-L1857 |
||
microsoft/EdgeML | ef9f8a77f096acbdeb941014791f8eda1c1bc35b | tools/SeeDot/seedot/compiler/converter/util.py | python | readXandYasCSV | (trainingDataset) | return X, Y | In CSV format, the input is a folder containing two files "X.csv" and "Y.csv".
Each file contains comma seperated values.
X contains feature vector and Y contains the class ID of each data point. | In CSV format, the input is a folder containing two files "X.csv" and "Y.csv".
Each file contains comma seperated values.
X contains feature vector and Y contains the class ID of each data point. | [
"In",
"CSV",
"format",
"the",
"input",
"is",
"a",
"folder",
"containing",
"two",
"files",
"X",
".",
"csv",
"and",
"Y",
".",
"csv",
".",
"Each",
"file",
"contains",
"comma",
"seperated",
"values",
".",
"X",
"contains",
"feature",
"vector",
"and",
"Y",
"contains",
"the",
"class",
"ID",
"of",
"each",
"data",
"point",
"."
] | def readXandYasCSV(trainingDataset):
'''
In CSV format, the input is a folder containing two files "X.csv" and "Y.csv".
Each file contains comma seperated values.
X contains feature vector and Y contains the class ID of each data point.
'''
if trainingDataset == True or usingTrainingDataset() == True:
X = readFileAsMat(os.path.join(
Config.trainingFile, "X.csv"), ", ", float)
Y = readFileAsMat(os.path.join(
Config.trainingFile, "Y.csv"), ", ", int)
else:
X = readFileAsMat(os.path.join(
Config.testingFile, "X.csv"), ", ", float)
Y = readFileAsMat(os.path.join(Config.testingFile, "Y.csv"), ", ", int)
Y = zeroIndexLabels(Y)
return X, Y | [
"def",
"readXandYasCSV",
"(",
"trainingDataset",
")",
":",
"if",
"trainingDataset",
"==",
"True",
"or",
"usingTrainingDataset",
"(",
")",
"==",
"True",
":",
"X",
"=",
"readFileAsMat",
"(",
"os",
".",
"path",
".",
"join",
"(",
"Config",
".",
"trainingFile",
",",
"\"X.csv\"",
")",
",",
"\", \"",
",",
"float",
")",
"Y",
"=",
"readFileAsMat",
"(",
"os",
".",
"path",
".",
"join",
"(",
"Config",
".",
"trainingFile",
",",
"\"Y.csv\"",
")",
",",
"\", \"",
",",
"int",
")",
"else",
":",
"X",
"=",
"readFileAsMat",
"(",
"os",
".",
"path",
".",
"join",
"(",
"Config",
".",
"testingFile",
",",
"\"X.csv\"",
")",
",",
"\", \"",
",",
"float",
")",
"Y",
"=",
"readFileAsMat",
"(",
"os",
".",
"path",
".",
"join",
"(",
"Config",
".",
"testingFile",
",",
"\"Y.csv\"",
")",
",",
"\", \"",
",",
"int",
")",
"Y",
"=",
"zeroIndexLabels",
"(",
"Y",
")",
"return",
"X",
",",
"Y"
] | https://github.com/microsoft/EdgeML/blob/ef9f8a77f096acbdeb941014791f8eda1c1bc35b/tools/SeeDot/seedot/compiler/converter/util.py#L236-L254 |
|
msitt/blpapi-python | bebcf43668c9e5f5467b1f685f9baebbfc45bc87 | src/blpapi/schema.py | python | SchemaTypeDefinition.numElementDefinitions | (self) | return internals.blpapi_SchemaTypeDefinition_numElementDefinitions(
self.__handle) | Returns:
int: The number of :class:`SchemaElementDefinition` objects.
If this :class:`SchemaTypeDefinition` is neither a choice nor a
sequence this will return ``0``. | Returns:
int: The number of :class:`SchemaElementDefinition` objects. | [
"Returns",
":",
"int",
":",
"The",
"number",
"of",
":",
"class",
":",
"SchemaElementDefinition",
"objects",
"."
] | def numElementDefinitions(self):
"""
Returns:
int: The number of :class:`SchemaElementDefinition` objects.
If this :class:`SchemaTypeDefinition` is neither a choice nor a
sequence this will return ``0``.
"""
return internals.blpapi_SchemaTypeDefinition_numElementDefinitions(
self.__handle) | [
"def",
"numElementDefinitions",
"(",
"self",
")",
":",
"return",
"internals",
".",
"blpapi_SchemaTypeDefinition_numElementDefinitions",
"(",
"self",
".",
"__handle",
")"
] | https://github.com/msitt/blpapi-python/blob/bebcf43668c9e5f5467b1f685f9baebbfc45bc87/src/blpapi/schema.py#L281-L291 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_controls.py | python | PreGauge | (*args, **kwargs) | return val | PreGauge() -> Gauge | PreGauge() -> Gauge | [
"PreGauge",
"()",
"-",
">",
"Gauge"
] | def PreGauge(*args, **kwargs):
"""PreGauge() -> Gauge"""
val = _controls_.new_PreGauge(*args, **kwargs)
return val | [
"def",
"PreGauge",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"val",
"=",
"_controls_",
".",
"new_PreGauge",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"val"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L812-L815 |
|
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/tools/gyp/pylib/gyp/MSVSVersion.py | python | _RegistryGetValueUsingWinReg | (key, value) | Use the _winreg module to obtain the value of a registry key.
Args:
key: The registry key.
value: The particular registry value to read.
Return:
contents of the registry key's value, or None on failure. Throws
ImportError if winreg is unavailable. | Use the _winreg module to obtain the value of a registry key. | [
"Use",
"the",
"_winreg",
"module",
"to",
"obtain",
"the",
"value",
"of",
"a",
"registry",
"key",
"."
] | def _RegistryGetValueUsingWinReg(key, value):
"""Use the _winreg module to obtain the value of a registry key.
Args:
key: The registry key.
value: The particular registry value to read.
Return:
contents of the registry key's value, or None on failure. Throws
ImportError if winreg is unavailable.
"""
from winreg import HKEY_LOCAL_MACHINE, OpenKey, QueryValueEx
try:
root, subkey = key.split("\\", 1)
assert root == "HKLM" # Only need HKLM for now.
with OpenKey(HKEY_LOCAL_MACHINE, subkey) as hkey:
return QueryValueEx(hkey, value)[0]
except OSError:
return None | [
"def",
"_RegistryGetValueUsingWinReg",
"(",
"key",
",",
"value",
")",
":",
"from",
"winreg",
"import",
"HKEY_LOCAL_MACHINE",
",",
"OpenKey",
",",
"QueryValueEx",
"try",
":",
"root",
",",
"subkey",
"=",
"key",
".",
"split",
"(",
"\"\\\\\"",
",",
"1",
")",
"assert",
"root",
"==",
"\"HKLM\"",
"# Only need HKLM for now.",
"with",
"OpenKey",
"(",
"HKEY_LOCAL_MACHINE",
",",
"subkey",
")",
"as",
"hkey",
":",
"return",
"QueryValueEx",
"(",
"hkey",
",",
"value",
")",
"[",
"0",
"]",
"except",
"OSError",
":",
"return",
"None"
] | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/gyp/pylib/gyp/MSVSVersion.py#L212-L229 |
||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_controls.py | python | Gauge.SetRange | (*args, **kwargs) | return _controls_.Gauge_SetRange(*args, **kwargs) | SetRange(self, int range) | SetRange(self, int range) | [
"SetRange",
"(",
"self",
"int",
"range",
")"
] | def SetRange(*args, **kwargs):
"""SetRange(self, int range)"""
return _controls_.Gauge_SetRange(*args, **kwargs) | [
"def",
"SetRange",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"Gauge_SetRange",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L747-L749 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_controls.py | python | ToolBarBase.AddStretchableSpace | (*args, **kwargs) | return _controls_.ToolBarBase_AddStretchableSpace(*args, **kwargs) | AddStretchableSpace(self) -> ToolBarToolBase | AddStretchableSpace(self) -> ToolBarToolBase | [
"AddStretchableSpace",
"(",
"self",
")",
"-",
">",
"ToolBarToolBase"
] | def AddStretchableSpace(*args, **kwargs):
"""AddStretchableSpace(self) -> ToolBarToolBase"""
return _controls_.ToolBarBase_AddStretchableSpace(*args, **kwargs) | [
"def",
"AddStretchableSpace",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"ToolBarBase_AddStretchableSpace",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L3771-L3773 |
|
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/vis/visualization.py | python | setDrawFunc | (name : ItemPath, func : Callable) | Sets a custom OpenGL drawing function for an item.
Args:
name (str): the name of the item
func (function or None): a one-argument function draw(data) that takes the item data
as input. Set func to None to revert to default drawing. | Sets a custom OpenGL drawing function for an item. | [
"Sets",
"a",
"custom",
"OpenGL",
"drawing",
"function",
"for",
"an",
"item",
"."
] | def setDrawFunc(name : ItemPath, func : Callable) -> None:
"""Sets a custom OpenGL drawing function for an item.
Args:
name (str): the name of the item
func (function or None): a one-argument function draw(data) that takes the item data
as input. Set func to None to revert to default drawing.
"""
scene().setDrawFunc(name,func) | [
"def",
"setDrawFunc",
"(",
"name",
":",
"ItemPath",
",",
"func",
":",
"Callable",
")",
"->",
"None",
":",
"scene",
"(",
")",
".",
"setDrawFunc",
"(",
"name",
",",
"func",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/vis/visualization.py#L1419-L1427 |
||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/perf/metrics/smoothness.py | python | SmoothnessMetric.SetStats | (self, stats) | Pass in a RenderingStats object directly. For unittests that don't call
Start/Stop. | Pass in a RenderingStats object directly. For unittests that don't call
Start/Stop. | [
"Pass",
"in",
"a",
"RenderingStats",
"object",
"directly",
".",
"For",
"unittests",
"that",
"don",
"t",
"call",
"Start",
"/",
"Stop",
"."
] | def SetStats(self, stats):
""" Pass in a RenderingStats object directly. For unittests that don't call
Start/Stop.
"""
self._stats = stats | [
"def",
"SetStats",
"(",
"self",
",",
"stats",
")",
":",
"self",
".",
"_stats",
"=",
"stats"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/perf/metrics/smoothness.py#L74-L78 |
||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/logging/__init__.py | python | Handler.createLock | (self) | Acquire a thread lock for serializing access to the underlying I/O. | Acquire a thread lock for serializing access to the underlying I/O. | [
"Acquire",
"a",
"thread",
"lock",
"for",
"serializing",
"access",
"to",
"the",
"underlying",
"I",
"/",
"O",
"."
] | def createLock(self):
"""
Acquire a thread lock for serializing access to the underlying I/O.
"""
self.lock = threading.RLock()
_register_at_fork_reinit_lock(self) | [
"def",
"createLock",
"(",
"self",
")",
":",
"self",
".",
"lock",
"=",
"threading",
".",
"RLock",
"(",
")",
"_register_at_fork_reinit_lock",
"(",
"self",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/logging/__init__.py#L831-L836 |
||
nnrg/opennero | 43e12a1bcba6e228639db3886fec1dc47ddc24cb | mods/Roomba/module.py | python | SandboxMod.distribute_bots | (self, num_bots, bot_type) | distribute bots so that they don't overlap | distribute bots so that they don't overlap | [
"distribute",
"bots",
"so",
"that",
"they",
"don",
"t",
"overlap"
] | def distribute_bots(self, num_bots, bot_type):
"""distribute bots so that they don't overlap"""
# make a number of tiles to stick bots in
N_TILES = 10
tiles = [ (r,c) for r in range(N_TILES) for c in range(N_TILES)]
random.shuffle(tiles)
bots_to_add = num_bots
while bots_to_add > 0:
(r,c) = tiles.pop() # random tile
x, y = r * constants.XDIM / float(N_TILES), c * constants.YDIM / float(N_TILES) # position within tile
x, y = x + random.random() * constants.XDIM * 0.5 / N_TILES, y + random.random() * constants.YDIM * 0.5 / N_TILES # random offset
if in_bounds(x,y):
agent_id = common.addObject(bot_type, OpenNero.Vector3f(x, y, 0), scale=OpenNero.Vector3f(1, 1, 1), type = constants.OBJECT_TYPE_ROOMBA, collision = constants.OBJECT_TYPE_ROOMBA)
self.agent_ids.append(agent_id)
bots_to_add -= 1
else:
pass | [
"def",
"distribute_bots",
"(",
"self",
",",
"num_bots",
",",
"bot_type",
")",
":",
"# make a number of tiles to stick bots in",
"N_TILES",
"=",
"10",
"tiles",
"=",
"[",
"(",
"r",
",",
"c",
")",
"for",
"r",
"in",
"range",
"(",
"N_TILES",
")",
"for",
"c",
"in",
"range",
"(",
"N_TILES",
")",
"]",
"random",
".",
"shuffle",
"(",
"tiles",
")",
"bots_to_add",
"=",
"num_bots",
"while",
"bots_to_add",
">",
"0",
":",
"(",
"r",
",",
"c",
")",
"=",
"tiles",
".",
"pop",
"(",
")",
"# random tile",
"x",
",",
"y",
"=",
"r",
"*",
"constants",
".",
"XDIM",
"/",
"float",
"(",
"N_TILES",
")",
",",
"c",
"*",
"constants",
".",
"YDIM",
"/",
"float",
"(",
"N_TILES",
")",
"# position within tile",
"x",
",",
"y",
"=",
"x",
"+",
"random",
".",
"random",
"(",
")",
"*",
"constants",
".",
"XDIM",
"*",
"0.5",
"/",
"N_TILES",
",",
"y",
"+",
"random",
".",
"random",
"(",
")",
"*",
"constants",
".",
"YDIM",
"*",
"0.5",
"/",
"N_TILES",
"# random offset",
"if",
"in_bounds",
"(",
"x",
",",
"y",
")",
":",
"agent_id",
"=",
"common",
".",
"addObject",
"(",
"bot_type",
",",
"OpenNero",
".",
"Vector3f",
"(",
"x",
",",
"y",
",",
"0",
")",
",",
"scale",
"=",
"OpenNero",
".",
"Vector3f",
"(",
"1",
",",
"1",
",",
"1",
")",
",",
"type",
"=",
"constants",
".",
"OBJECT_TYPE_ROOMBA",
",",
"collision",
"=",
"constants",
".",
"OBJECT_TYPE_ROOMBA",
")",
"self",
".",
"agent_ids",
".",
"append",
"(",
"agent_id",
")",
"bots_to_add",
"-=",
"1",
"else",
":",
"pass"
] | https://github.com/nnrg/opennero/blob/43e12a1bcba6e228639db3886fec1dc47ddc24cb/mods/Roomba/module.py#L86-L102 |
||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/ogl/_basic.py | python | Shape.AncestorSelected | (self) | return self.GetParent().AncestorSelected() | TRUE if the shape's ancestor is currently selected. | TRUE if the shape's ancestor is currently selected. | [
"TRUE",
"if",
"the",
"shape",
"s",
"ancestor",
"is",
"currently",
"selected",
"."
] | def AncestorSelected(self):
"""TRUE if the shape's ancestor is currently selected."""
if self._selected:
return True
if not self.GetParent():
return False
return self.GetParent().AncestorSelected() | [
"def",
"AncestorSelected",
"(",
"self",
")",
":",
"if",
"self",
".",
"_selected",
":",
"return",
"True",
"if",
"not",
"self",
".",
"GetParent",
"(",
")",
":",
"return",
"False",
"return",
"self",
".",
"GetParent",
"(",
")",
".",
"AncestorSelected",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/ogl/_basic.py#L1455-L1461 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py3/IPython/core/interactiveshell.py | python | InteractiveShell.reset_selective | (self, regex=None) | Clear selective variables from internal namespaces based on a
specified regular expression.
Parameters
----------
regex : string or compiled pattern, optional
A regular expression pattern that will be used in searching
variable names in the users namespaces. | Clear selective variables from internal namespaces based on a
specified regular expression. | [
"Clear",
"selective",
"variables",
"from",
"internal",
"namespaces",
"based",
"on",
"a",
"specified",
"regular",
"expression",
"."
] | def reset_selective(self, regex=None):
"""Clear selective variables from internal namespaces based on a
specified regular expression.
Parameters
----------
regex : string or compiled pattern, optional
A regular expression pattern that will be used in searching
variable names in the users namespaces.
"""
if regex is not None:
try:
m = re.compile(regex)
except TypeError:
raise TypeError('regex must be a string or compiled pattern')
# Search for keys in each namespace that match the given regex
# If a match is found, delete the key/value pair.
for ns in self.all_ns_refs:
for var in ns:
if m.search(var):
del ns[var] | [
"def",
"reset_selective",
"(",
"self",
",",
"regex",
"=",
"None",
")",
":",
"if",
"regex",
"is",
"not",
"None",
":",
"try",
":",
"m",
"=",
"re",
".",
"compile",
"(",
"regex",
")",
"except",
"TypeError",
":",
"raise",
"TypeError",
"(",
"'regex must be a string or compiled pattern'",
")",
"# Search for keys in each namespace that match the given regex",
"# If a match is found, delete the key/value pair.",
"for",
"ns",
"in",
"self",
".",
"all_ns_refs",
":",
"for",
"var",
"in",
"ns",
":",
"if",
"m",
".",
"search",
"(",
"var",
")",
":",
"del",
"ns",
"[",
"var",
"]"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/core/interactiveshell.py#L1530-L1550 |
||
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/maximum-number-of-darts-inside-of-a-circular-dartboard.py | python | Solution.numPoints | (self, points, r) | return max(count_points(points, r, i) for i in xrange(len(points))) | :type points: List[List[int]]
:type r: int
:rtype: int | :type points: List[List[int]]
:type r: int
:rtype: int | [
":",
"type",
"points",
":",
"List",
"[",
"List",
"[",
"int",
"]]",
":",
"type",
"r",
":",
"int",
":",
"rtype",
":",
"int"
] | def numPoints(self, points, r):
"""
:type points: List[List[int]]
:type r: int
:rtype: int
"""
def count_points(points, r, i):
angles = []
for j in xrange(len(points)):
if i == j:
continue
dx, dy = points[i][0]-points[j][0], points[i][1]-points[j][1]
d = math.sqrt(dx**2 + dy**2)
if d > 2*r:
continue
delta, angle = math.acos(d/(2*r)), math.atan2(dy, dx)
angles.append((angle-delta, 0)), angles.append((angle+delta, 1))
angles.sort()
result, count = 1, 1
for _, is_closed in angles: # angle sweep
if not is_closed:
count += 1
else:
count -= 1
result = max(result, count)
return result
return max(count_points(points, r, i) for i in xrange(len(points))) | [
"def",
"numPoints",
"(",
"self",
",",
"points",
",",
"r",
")",
":",
"def",
"count_points",
"(",
"points",
",",
"r",
",",
"i",
")",
":",
"angles",
"=",
"[",
"]",
"for",
"j",
"in",
"xrange",
"(",
"len",
"(",
"points",
")",
")",
":",
"if",
"i",
"==",
"j",
":",
"continue",
"dx",
",",
"dy",
"=",
"points",
"[",
"i",
"]",
"[",
"0",
"]",
"-",
"points",
"[",
"j",
"]",
"[",
"0",
"]",
",",
"points",
"[",
"i",
"]",
"[",
"1",
"]",
"-",
"points",
"[",
"j",
"]",
"[",
"1",
"]",
"d",
"=",
"math",
".",
"sqrt",
"(",
"dx",
"**",
"2",
"+",
"dy",
"**",
"2",
")",
"if",
"d",
">",
"2",
"*",
"r",
":",
"continue",
"delta",
",",
"angle",
"=",
"math",
".",
"acos",
"(",
"d",
"/",
"(",
"2",
"*",
"r",
")",
")",
",",
"math",
".",
"atan2",
"(",
"dy",
",",
"dx",
")",
"angles",
".",
"append",
"(",
"(",
"angle",
"-",
"delta",
",",
"0",
")",
")",
",",
"angles",
".",
"append",
"(",
"(",
"angle",
"+",
"delta",
",",
"1",
")",
")",
"angles",
".",
"sort",
"(",
")",
"result",
",",
"count",
"=",
"1",
",",
"1",
"for",
"_",
",",
"is_closed",
"in",
"angles",
":",
"# angle sweep",
"if",
"not",
"is_closed",
":",
"count",
"+=",
"1",
"else",
":",
"count",
"-=",
"1",
"result",
"=",
"max",
"(",
"result",
",",
"count",
")",
"return",
"result",
"return",
"max",
"(",
"count_points",
"(",
"points",
",",
"r",
",",
"i",
")",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"points",
")",
")",
")"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/maximum-number-of-darts-inside-of-a-circular-dartboard.py#L11-L38 |
|
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/Tpm.py | python | Tpm.LoadExternal | (self, inPrivate, inPublic, hierarchy) | return res.handle if res else None | This command is used to load an object that is not a Protected
Object into the TPM. The command allows loading of a public area or both
a public and sensitive area.
Args:
inPrivate (TPMT_SENSITIVE): The sensitive portion of the object (optional)
inPublic (TPMT_PUBLIC): The public portion of the object
hierarchy (TPM_HANDLE): Hierarchy with which the object area is associated
Returns:
handle - Handle of type TPM_HT_TRANSIENT for the loaded object | This command is used to load an object that is not a Protected
Object into the TPM. The command allows loading of a public area or both
a public and sensitive area. | [
"This",
"command",
"is",
"used",
"to",
"load",
"an",
"object",
"that",
"is",
"not",
"a",
"Protected",
"Object",
"into",
"the",
"TPM",
".",
"The",
"command",
"allows",
"loading",
"of",
"a",
"public",
"area",
"or",
"both",
"a",
"public",
"and",
"sensitive",
"area",
"."
] | def LoadExternal(self, inPrivate, inPublic, hierarchy):
""" This command is used to load an object that is not a Protected
Object into the TPM. The command allows loading of a public area or both
a public and sensitive area.
Args:
inPrivate (TPMT_SENSITIVE): The sensitive portion of the object (optional)
inPublic (TPMT_PUBLIC): The public portion of the object
hierarchy (TPM_HANDLE): Hierarchy with which the object area is associated
Returns:
handle - Handle of type TPM_HT_TRANSIENT for the loaded object
"""
req = TPM2_LoadExternal_REQUEST(inPrivate, inPublic, hierarchy)
respBuf = self.dispatchCommand(TPM_CC.LoadExternal, req)
res = self.processResponse(respBuf, LoadExternalResponse)
return res.handle if res else None | [
"def",
"LoadExternal",
"(",
"self",
",",
"inPrivate",
",",
"inPublic",
",",
"hierarchy",
")",
":",
"req",
"=",
"TPM2_LoadExternal_REQUEST",
"(",
"inPrivate",
",",
"inPublic",
",",
"hierarchy",
")",
"respBuf",
"=",
"self",
".",
"dispatchCommand",
"(",
"TPM_CC",
".",
"LoadExternal",
",",
"req",
")",
"res",
"=",
"self",
".",
"processResponse",
"(",
"respBuf",
",",
"LoadExternalResponse",
")",
"return",
"res",
".",
"handle",
"if",
"res",
"else",
"None"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/Tpm.py#L200-L216 |
|
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | js/src/builtin/make_intl_data.py | python | writeMappingsVar | (intlData, dict, name, description, fileDate, url) | Writes a variable definition with a mapping table to file intlData.
Writes the contents of dictionary dict to file intlData with the given
variable name and a comment with description, fileDate, and URL. | Writes a variable definition with a mapping table to file intlData. | [
"Writes",
"a",
"variable",
"definition",
"with",
"a",
"mapping",
"table",
"to",
"file",
"intlData",
"."
] | def writeMappingsVar(intlData, dict, name, description, fileDate, url):
""" Writes a variable definition with a mapping table to file intlData.
Writes the contents of dictionary dict to file intlData with the given
variable name and a comment with description, fileDate, and URL.
"""
intlData.write("\n")
intlData.write("// {0}.\n".format(description))
intlData.write("// Derived from IANA Language Subtag Registry, file date {0}.\n".format(fileDate))
intlData.write("// {0}\n".format(url))
intlData.write("var {0} = {{\n".format(name))
keys = sorted(dict)
for key in keys:
if isinstance(dict[key], basestring):
value = '"{0}"'.format(dict[key])
else:
preferred = dict[key]["preferred"]
prefix = dict[key]["prefix"]
value = '{{preferred: "{0}", prefix: "{1}"}}'.format(preferred, prefix)
intlData.write(' "{0}": {1},\n'.format(key, value))
intlData.write("};\n") | [
"def",
"writeMappingsVar",
"(",
"intlData",
",",
"dict",
",",
"name",
",",
"description",
",",
"fileDate",
",",
"url",
")",
":",
"intlData",
".",
"write",
"(",
"\"\\n\"",
")",
"intlData",
".",
"write",
"(",
"\"// {0}.\\n\"",
".",
"format",
"(",
"description",
")",
")",
"intlData",
".",
"write",
"(",
"\"// Derived from IANA Language Subtag Registry, file date {0}.\\n\"",
".",
"format",
"(",
"fileDate",
")",
")",
"intlData",
".",
"write",
"(",
"\"// {0}\\n\"",
".",
"format",
"(",
"url",
")",
")",
"intlData",
".",
"write",
"(",
"\"var {0} = {{\\n\"",
".",
"format",
"(",
"name",
")",
")",
"keys",
"=",
"sorted",
"(",
"dict",
")",
"for",
"key",
"in",
"keys",
":",
"if",
"isinstance",
"(",
"dict",
"[",
"key",
"]",
",",
"basestring",
")",
":",
"value",
"=",
"'\"{0}\"'",
".",
"format",
"(",
"dict",
"[",
"key",
"]",
")",
"else",
":",
"preferred",
"=",
"dict",
"[",
"key",
"]",
"[",
"\"preferred\"",
"]",
"prefix",
"=",
"dict",
"[",
"key",
"]",
"[",
"\"prefix\"",
"]",
"value",
"=",
"'{{preferred: \"{0}\", prefix: \"{1}\"}}'",
".",
"format",
"(",
"preferred",
",",
"prefix",
")",
"intlData",
".",
"write",
"(",
"' \"{0}\": {1},\\n'",
".",
"format",
"(",
"key",
",",
"value",
")",
")",
"intlData",
".",
"write",
"(",
"\"};\\n\"",
")"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/js/src/builtin/make_intl_data.py#L136-L156 |
||
facebookincubator/profilo | d3a275d0e7897cc4e3507d543459f3227e85c67f | python/profilo/symbols/apk_symbols.py | python | parse_dex_id | (signature) | return struct.unpack("<I", signature[0:4])[0] | Take first 4 bytes of the Dex signature as Dex Id | Take first 4 bytes of the Dex signature as Dex Id | [
"Take",
"first",
"4",
"bytes",
"of",
"the",
"Dex",
"signature",
"as",
"Dex",
"Id"
] | def parse_dex_id(signature):
"""Take first 4 bytes of the Dex signature as Dex Id"""
return struct.unpack("<I", signature[0:4])[0] | [
"def",
"parse_dex_id",
"(",
"signature",
")",
":",
"return",
"struct",
".",
"unpack",
"(",
"\"<I\"",
",",
"signature",
"[",
"0",
":",
"4",
"]",
")",
"[",
"0",
"]"
] | https://github.com/facebookincubator/profilo/blob/d3a275d0e7897cc4e3507d543459f3227e85c67f/python/profilo/symbols/apk_symbols.py#L27-L29 |
Subsets and Splits