nwo stringlengths 5 86 | sha stringlengths 40 40 | path stringlengths 4 189 | language stringclasses 1 value | identifier stringlengths 1 94 | parameters stringlengths 2 4.03k | argument_list stringclasses 1 value | return_statement stringlengths 0 11.5k | docstring stringlengths 1 33.2k | docstring_summary stringlengths 0 5.15k | docstring_tokens list | function stringlengths 34 151k | function_tokens list | url stringlengths 90 278 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_controls.py | python | SpinButton.GetValue | (*args, **kwargs) | return _controls_.SpinButton_GetValue(*args, **kwargs) | GetValue(self) -> int | GetValue(self) -> int | [
"GetValue",
"(",
"self",
")",
"-",
">",
"int"
] | def GetValue(*args, **kwargs):
"""GetValue(self) -> int"""
return _controls_.SpinButton_GetValue(*args, **kwargs) | [
"def",
"GetValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"SpinButton_GetValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L2254-L2256 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py | python | FormulaSymbol.addsymbol | (self, symbol, pos) | Add a symbol | Add a symbol | [
"Add",
"a",
"symbol"
] | def addsymbol(self, symbol, pos):
"Add a symbol"
self.skiporiginal(pos.current(), pos)
self.contents.append(FormulaConstant(symbol)) | [
"def",
"addsymbol",
"(",
"self",
",",
"symbol",
",",
"pos",
")",
":",
"self",
".",
"skiporiginal",
"(",
"pos",
".",
"current",
"(",
")",
",",
"pos",
")",
"self",
".",
"contents",
".",
"append",
"(",
"FormulaConstant",
"(",
"symbol",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py#L2708-L2711 | ||
opencv/opencv | 76aff8478883858f0e46746044348ebb16dc3c67 | apps/opencv_stitching_tool/opencv_stitching/exposure_error_compensator.py | python | ExposureErrorCompensator.apply | (self, *args) | return self.compensator.apply(*args) | https://docs.opencv.org/4.x/d2/d37/classcv_1_1detail_1_1ExposureCompensator.html#a473eaf1e585804c08d77c91e004f93aa | https://docs.opencv.org/4.x/d2/d37/classcv_1_1detail_1_1ExposureCompensator.html#a473eaf1e585804c08d77c91e004f93aa | [
"https",
":",
"//",
"docs",
".",
"opencv",
".",
"org",
"/",
"4",
".",
"x",
"/",
"d2",
"/",
"d37",
"/",
"classcv_1_1detail_1_1ExposureCompensator",
".",
"html#a473eaf1e585804c08d77c91e004f93aa"
] | def apply(self, *args):
"""https://docs.opencv.org/4.x/d2/d37/classcv_1_1detail_1_1ExposureCompensator.html#a473eaf1e585804c08d77c91e004f93aa""" # noqa
return self.compensator.apply(*args) | [
"def",
"apply",
"(",
"self",
",",
"*",
"args",
")",
":",
"# noqa",
"return",
"self",
".",
"compensator",
".",
"apply",
"(",
"*",
"args",
")"
] | https://github.com/opencv/opencv/blob/76aff8478883858f0e46746044348ebb16dc3c67/apps/opencv_stitching_tool/opencv_stitching/exposure_error_compensator.py#L38-L40 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pkg_resources/__init__.py | python | Environment.__iadd__ | (self, other) | return self | In-place addition of a distribution or environment | In-place addition of a distribution or environment | [
"In",
"-",
"place",
"addition",
"of",
"a",
"distribution",
"or",
"environment"
] | def __iadd__(self, other):
"""In-place addition of a distribution or environment"""
if isinstance(other, Distribution):
self.add(other)
elif isinstance(other, Environment):
for project in other:
for dist in other[project]:
self.add(dist)
else:
raise TypeError("Can't add %r to environment" % (other,))
return self | [
"def",
"__iadd__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"Distribution",
")",
":",
"self",
".",
"add",
"(",
"other",
")",
"elif",
"isinstance",
"(",
"other",
",",
"Environment",
")",
":",
"for",
"project",
"in",
... | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pkg_resources/__init__.py#L1085-L1095 | |
Tencent/CMONGO | c40380caa14e05509f46993aa8b8da966b09b0b5 | src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Action.py | python | _function_contents | (func) | return ''.join(contents) | Return the signature contents of a function. | Return the signature contents of a function. | [
"Return",
"the",
"signature",
"contents",
"of",
"a",
"function",
"."
] | def _function_contents(func):
"""Return the signature contents of a function."""
contents = [_code_contents(func.func_code)]
# The function contents depends on the value of defaults arguments
if func.func_defaults:
contents.append(',(' + ','.join(map(_object_contents,func.func_defaults)) + ')')
else:
contents.append(',()')
# The function contents depends on the closure captured cell values.
closure = func.func_closure or []
#xxx = [_object_contents(x.cell_contents) for x in closure]
try:
xxx = [_object_contents(x.cell_contents) for x in closure]
except AttributeError:
xxx = []
contents.append(',(' + ','.join(xxx) + ')')
return ''.join(contents) | [
"def",
"_function_contents",
"(",
"func",
")",
":",
"contents",
"=",
"[",
"_code_contents",
"(",
"func",
".",
"func_code",
")",
"]",
"# The function contents depends on the value of defaults arguments",
"if",
"func",
".",
"func_defaults",
":",
"contents",
".",
"append... | https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Action.py#L263-L284 | |
opengauss-mirror/openGauss-server | e383f1b77720a00ddbe4c0655bc85914d9b02a2b | src/gausskernel/dbmind/tools/ai_manager/module/index_advisor/install.py | python | Installer._clean_remote_module_dir | (self) | Clean install path before unpack. | Clean install path before unpack. | [
"Clean",
"install",
"path",
"before",
"unpack",
"."
] | def _clean_remote_module_dir(self):
"""
Clean install path before unpack.
"""
for node in self.install_nodes:
ip = node.get(Constant.NODE_IP)
uname = node.get(Constant.NODE_USER)
pwd = node.get(Constant.NODE_PWD)
_, output = CommonTools.retry_remote_clean_dir(self.module_path, ip, uname, pwd)
g.logger.info('Result of clean module path on node:[%s], output:%s' % (ip, output)) | [
"def",
"_clean_remote_module_dir",
"(",
"self",
")",
":",
"for",
"node",
"in",
"self",
".",
"install_nodes",
":",
"ip",
"=",
"node",
".",
"get",
"(",
"Constant",
".",
"NODE_IP",
")",
"uname",
"=",
"node",
".",
"get",
"(",
"Constant",
".",
"NODE_USER",
... | https://github.com/opengauss-mirror/openGauss-server/blob/e383f1b77720a00ddbe4c0655bc85914d9b02a2b/src/gausskernel/dbmind/tools/ai_manager/module/index_advisor/install.py#L60-L69 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/ops/random_ops.py | python | random_normal | (shape,
mean=0.0,
stddev=1.0,
dtype=dtypes.float32,
seed=None,
name=None) | Outputs random values from a normal distribution.
Args:
shape: A 1-D integer Tensor or Python array. The shape of the output tensor.
mean: A 0-D Tensor or Python value of type `dtype`. The mean of the normal
distribution.
stddev: A 0-D Tensor or Python value of type `dtype`. The standard deviation
of the normal distribution.
dtype: The type of the output.
seed: A Python integer. Used to create a random seed for the distribution.
See
[`set_random_seed`](../../api_docs/python/constant_op.md#set_random_seed)
for behavior.
name: A name for the operation (optional).
Returns:
A tensor of the specified shape filled with random normal values. | Outputs random values from a normal distribution. | [
"Outputs",
"random",
"values",
"from",
"a",
"normal",
"distribution",
"."
] | def random_normal(shape,
mean=0.0,
stddev=1.0,
dtype=dtypes.float32,
seed=None,
name=None):
"""Outputs random values from a normal distribution.
Args:
shape: A 1-D integer Tensor or Python array. The shape of the output tensor.
mean: A 0-D Tensor or Python value of type `dtype`. The mean of the normal
distribution.
stddev: A 0-D Tensor or Python value of type `dtype`. The standard deviation
of the normal distribution.
dtype: The type of the output.
seed: A Python integer. Used to create a random seed for the distribution.
See
[`set_random_seed`](../../api_docs/python/constant_op.md#set_random_seed)
for behavior.
name: A name for the operation (optional).
Returns:
A tensor of the specified shape filled with random normal values.
"""
with ops.op_scope([shape, mean, stddev], name, "random_normal") as name:
shape_tensor = _ShapeTensor(shape)
mean_tensor = ops.convert_to_tensor(mean, dtype=dtype, name="mean")
stddev_tensor = ops.convert_to_tensor(stddev, dtype=dtype, name="stddev")
seed1, seed2 = random_seed.get_seed(seed)
rnd = gen_random_ops._random_standard_normal(shape_tensor,
dtype,
seed=seed1,
seed2=seed2)
mul = rnd * stddev_tensor
value = math_ops.add(mul, mean_tensor, name=name)
return value | [
"def",
"random_normal",
"(",
"shape",
",",
"mean",
"=",
"0.0",
",",
"stddev",
"=",
"1.0",
",",
"dtype",
"=",
"dtypes",
".",
"float32",
",",
"seed",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"op_scope",
"(",
"[",
"shape",
... | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/random_ops.py#L49-L84 | ||
pytorch/FBGEMM | 501dfa78e149d25fc3ca3e9cc3d71d28a3b58aeb | fbgemm_gpu/fbgemm_gpu/split_table_batched_embeddings_ops.py | python | SplitTableBatchedEmbeddingBagsCodegen.set_learning_rate | (self, lr: float) | Sets the learning rate. | Sets the learning rate. | [
"Sets",
"the",
"learning",
"rate",
"."
] | def set_learning_rate(self, lr: float) -> None:
"""
Sets the learning rate.
"""
self._set_learning_rate(lr) | [
"def",
"set_learning_rate",
"(",
"self",
",",
"lr",
":",
"float",
")",
"->",
"None",
":",
"self",
".",
"_set_learning_rate",
"(",
"lr",
")"
] | https://github.com/pytorch/FBGEMM/blob/501dfa78e149d25fc3ca3e9cc3d71d28a3b58aeb/fbgemm_gpu/fbgemm_gpu/split_table_batched_embeddings_ops.py#L1025-L1029 | ||
priyankchheda/algorithms | c361aa9071573fa9966d5b02d05e524815abcf2b | deque/deque.py | python | Deque.peek_front | (self) | return None | Returns the value found at the 0th index of the list, which
represents the front of the Deque.
The runtime is constant because all we're doing is indexing into
a list. | Returns the value found at the 0th index of the list, which
represents the front of the Deque. | [
"Returns",
"the",
"value",
"found",
"at",
"the",
"0th",
"index",
"of",
"the",
"list",
"which",
"represents",
"the",
"front",
"of",
"the",
"Deque",
"."
] | def peek_front(self):
""" Returns the value found at the 0th index of the list, which
represents the front of the Deque.
The runtime is constant because all we're doing is indexing into
a list.
"""
if self.items:
return self.items[0]
return None | [
"def",
"peek_front",
"(",
"self",
")",
":",
"if",
"self",
".",
"items",
":",
"return",
"self",
".",
"items",
"[",
"0",
"]",
"return",
"None"
] | https://github.com/priyankchheda/algorithms/blob/c361aa9071573fa9966d5b02d05e524815abcf2b/deque/deque.py#L55-L64 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/logging/config.py | python | _clearExistingHandlers | () | Clear and close existing handlers | Clear and close existing handlers | [
"Clear",
"and",
"close",
"existing",
"handlers"
] | def _clearExistingHandlers():
"""Clear and close existing handlers"""
logging._handlers.clear()
logging.shutdown(logging._handlerList[:])
del logging._handlerList[:] | [
"def",
"_clearExistingHandlers",
"(",
")",
":",
"logging",
".",
"_handlers",
".",
"clear",
"(",
")",
"logging",
".",
"shutdown",
"(",
"logging",
".",
"_handlerList",
"[",
":",
"]",
")",
"del",
"logging",
".",
"_handlerList",
"[",
":",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/logging/config.py#L270-L274 | ||
GoSSIP-SJTU/Armariris | ad5d868482956b2194a77b39c8d543c7c2318200 | bindings/python/llvm/core.py | python | LLVMEnumeration.register | (cls, name, value) | Registers a new enumeration.
This is called by this module for each enumeration defined in
enumerations. You should not need to call this outside this module. | Registers a new enumeration. | [
"Registers",
"a",
"new",
"enumeration",
"."
] | def register(cls, name, value):
"""Registers a new enumeration.
This is called by this module for each enumeration defined in
enumerations. You should not need to call this outside this module.
"""
if value in cls._value_map:
raise ValueError('%s value already registered: %d' % (cls.__name__,
value))
enum = cls(name, value)
cls._value_map[value] = enum
setattr(cls, name, enum) | [
"def",
"register",
"(",
"cls",
",",
"name",
",",
"value",
")",
":",
"if",
"value",
"in",
"cls",
".",
"_value_map",
":",
"raise",
"ValueError",
"(",
"'%s value already registered: %d'",
"%",
"(",
"cls",
".",
"__name__",
",",
"value",
")",
")",
"enum",
"="... | https://github.com/GoSSIP-SJTU/Armariris/blob/ad5d868482956b2194a77b39c8d543c7c2318200/bindings/python/llvm/core.py#L61-L72 | ||
snyball/Hawck | 625d840a9ac6f15d067d8307e2bd1a6930693a8b | hawck-ui/hawck_ui/privesc.py | python | SudoMethod.__init__ | (self, base_cmd: str, options: Dict[str, str], *base_flags) | Checks whether the sudo method exists. | Checks whether the sudo method exists. | [
"Checks",
"whether",
"the",
"sudo",
"method",
"exists",
"."
] | def __init__(self, base_cmd: str, options: Dict[str, str], *base_flags):
"""
Checks whether the sudo method exists.
"""
p = Popen(["which", base_cmd], stdout=PIPE)
ret = p.wait()
if ret != 0:
raise SudoException(f"No such method: {base_cmd}")
path = p.stdout.read().decode("utf-8").strip()
self.cmd = path
self.options = options
self.base_flags = base_flags | [
"def",
"__init__",
"(",
"self",
",",
"base_cmd",
":",
"str",
",",
"options",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
",",
"*",
"base_flags",
")",
":",
"p",
"=",
"Popen",
"(",
"[",
"\"which\"",
",",
"base_cmd",
"]",
",",
"stdout",
"=",
"PIPE",
"... | https://github.com/snyball/Hawck/blob/625d840a9ac6f15d067d8307e2bd1a6930693a8b/hawck-ui/hawck_ui/privesc.py#L60-L71 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/named_commands.py | python | backward_char | (event) | Move back a character. | Move back a character. | [
"Move",
"back",
"a",
"character",
"."
] | def backward_char(event):
" Move back a character. "
buff = event.current_buffer
buff.cursor_position += buff.document.get_cursor_left_position(count=event.arg) | [
"def",
"backward_char",
"(",
"event",
")",
":",
"buff",
"=",
"event",
".",
"current_buffer",
"buff",
".",
"cursor_position",
"+=",
"buff",
".",
"document",
".",
"get_cursor_left_position",
"(",
"count",
"=",
"event",
".",
"arg",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/named_commands.py#L75-L78 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/richtext.py | python | RichTextCtrl.ExtendSelection | (*args, **kwargs) | return _richtext.RichTextCtrl_ExtendSelection(*args, **kwargs) | ExtendSelection(self, long oldPosition, long newPosition, int flags) -> bool | ExtendSelection(self, long oldPosition, long newPosition, int flags) -> bool | [
"ExtendSelection",
"(",
"self",
"long",
"oldPosition",
"long",
"newPosition",
"int",
"flags",
")",
"-",
">",
"bool"
] | def ExtendSelection(*args, **kwargs):
"""ExtendSelection(self, long oldPosition, long newPosition, int flags) -> bool"""
return _richtext.RichTextCtrl_ExtendSelection(*args, **kwargs) | [
"def",
"ExtendSelection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextCtrl_ExtendSelection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L4060-L4062 | |
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | Validation/RecoTrack/python/plotting/ntupleDataFormat.py | python | TrackingParticle.nMatchedSeeds | (self) | return self._nMatchedSeeds() | Returns the number of matched seeds. | Returns the number of matched seeds. | [
"Returns",
"the",
"number",
"of",
"matched",
"seeds",
"."
] | def nMatchedSeeds(self):
"""Returns the number of matched seeds."""
self._checkIsValid()
return self._nMatchedSeeds() | [
"def",
"nMatchedSeeds",
"(",
"self",
")",
":",
"self",
".",
"_checkIsValid",
"(",
")",
"return",
"self",
".",
"_nMatchedSeeds",
"(",
")"
] | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Validation/RecoTrack/python/plotting/ntupleDataFormat.py#L1033-L1036 | |
omnisci/omniscidb | b9c95f1bd602b4ffc8b0edf18bfad61031e08d86 | python/omnisci/thrift/OmniSci.py | python | Client.has_object_privilege | (self, session, granteeName, ObjectName, objectType, permissions) | return self.recv_has_object_privilege() | Parameters:
- session
- granteeName
- ObjectName
- objectType
- permissions | Parameters:
- session
- granteeName
- ObjectName
- objectType
- permissions | [
"Parameters",
":",
"-",
"session",
"-",
"granteeName",
"-",
"ObjectName",
"-",
"objectType",
"-",
"permissions"
] | def has_object_privilege(self, session, granteeName, ObjectName, objectType, permissions):
"""
Parameters:
- session
- granteeName
- ObjectName
- objectType
- permissions
"""
self.send_has_object_privilege(session, granteeName, ObjectName, objectType, permissions)
return self.recv_has_object_privilege() | [
"def",
"has_object_privilege",
"(",
"self",
",",
"session",
",",
"granteeName",
",",
"ObjectName",
",",
"objectType",
",",
"permissions",
")",
":",
"self",
".",
"send_has_object_privilege",
"(",
"session",
",",
"granteeName",
",",
"ObjectName",
",",
"objectType",
... | https://github.com/omnisci/omniscidb/blob/b9c95f1bd602b4ffc8b0edf18bfad61031e08d86/python/omnisci/thrift/OmniSci.py#L4217-L4228 | |
oxen-io/lokinet | 257f48a1662bf37da1e9c77a4d07fa05fd7e613f | contrib/py/ffi-example/lokinet.py | python | LokiNET.inform_fail | (self) | inform lokinet crashed | inform lokinet crashed | [
"inform",
"lokinet",
"crashed"
] | def inform_fail(self):
"""
inform lokinet crashed
""" | [
"def",
"inform_fail",
"(",
"self",
")",
":"
] | https://github.com/oxen-io/lokinet/blob/257f48a1662bf37da1e9c77a4d07fa05fd7e613f/contrib/py/ffi-example/lokinet.py#L23-L26 | ||
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/ao/ns/_numeric_suite_dbr.py | python | add_loggers | (
name_a: str,
model_a: torch.nn.Module,
name_b: str,
model_b: torch.nn.Module,
) | return model_a, model_b | Enables intermediate activation logging on model_a and model_b. | Enables intermediate activation logging on model_a and model_b. | [
"Enables",
"intermediate",
"activation",
"logging",
"on",
"model_a",
"and",
"model_b",
"."
] | def add_loggers(
name_a: str,
model_a: torch.nn.Module,
name_b: str,
model_b: torch.nn.Module,
) -> Tuple[torch.nn.Module, torch.nn.Module]:
"""
Enables intermediate activation logging on model_a and model_b.
"""
_turn_on_loggers(name_a, model_a)
_turn_on_loggers(name_b, model_b)
return model_a, model_b | [
"def",
"add_loggers",
"(",
"name_a",
":",
"str",
",",
"model_a",
":",
"torch",
".",
"nn",
".",
"Module",
",",
"name_b",
":",
"str",
",",
"model_b",
":",
"torch",
".",
"nn",
".",
"Module",
",",
")",
"->",
"Tuple",
"[",
"torch",
".",
"nn",
".",
"Mo... | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/ao/ns/_numeric_suite_dbr.py#L22-L33 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_controls.py | python | TextAttr.GetFontAttributes | (*args, **kwargs) | return _controls_.TextAttr_GetFontAttributes(*args, **kwargs) | GetFontAttributes(self, Font font, int flags=TEXT_ATTR_FONT) -> bool | GetFontAttributes(self, Font font, int flags=TEXT_ATTR_FONT) -> bool | [
"GetFontAttributes",
"(",
"self",
"Font",
"font",
"int",
"flags",
"=",
"TEXT_ATTR_FONT",
")",
"-",
">",
"bool"
] | def GetFontAttributes(*args, **kwargs):
"""GetFontAttributes(self, Font font, int flags=TEXT_ATTR_FONT) -> bool"""
return _controls_.TextAttr_GetFontAttributes(*args, **kwargs) | [
"def",
"GetFontAttributes",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"TextAttr_GetFontAttributes",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L1507-L1509 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/aui/framemanager.py | python | AuiManager.SetArtProvider | (self, art_provider) | Instructs :class:`AuiManager` to use art provider specified by the parameter
`art_provider` for all drawing calls. This allows plugable look-and-feel
features.
:param `art_provider`: a AUI dock art provider.
:note: The previous art provider object, if any, will be deleted by :class:`AuiManager`. | Instructs :class:`AuiManager` to use art provider specified by the parameter
`art_provider` for all drawing calls. This allows plugable look-and-feel
features. | [
"Instructs",
":",
"class",
":",
"AuiManager",
"to",
"use",
"art",
"provider",
"specified",
"by",
"the",
"parameter",
"art_provider",
"for",
"all",
"drawing",
"calls",
".",
"This",
"allows",
"plugable",
"look",
"-",
"and",
"-",
"feel",
"features",
"."
] | def SetArtProvider(self, art_provider):
"""
Instructs :class:`AuiManager` to use art provider specified by the parameter
`art_provider` for all drawing calls. This allows plugable look-and-feel
features.
:param `art_provider`: a AUI dock art provider.
:note: The previous art provider object, if any, will be deleted by :class:`AuiManager`.
"""
# delete the last art provider, if any
del self._art
# assign the new art provider
self._art = art_provider
for pane in self.GetAllPanes():
if pane.IsFloating() and pane.frame:
pane.frame._mgr.SetArtProvider(art_provider)
pane.frame._mgr.Update() | [
"def",
"SetArtProvider",
"(",
"self",
",",
"art_provider",
")",
":",
"# delete the last art provider, if any",
"del",
"self",
".",
"_art",
"# assign the new art provider",
"self",
".",
"_art",
"=",
"art_provider",
"for",
"pane",
"in",
"self",
".",
"GetAllPanes",
"("... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/framemanager.py#L4660-L4680 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/io/pytables.py | python | WORMTable.read | (
self,
where=None,
columns=None,
start: int | None = None,
stop: int | None = None,
) | read the indices and the indexing array, calculate offset rows and return | read the indices and the indexing array, calculate offset rows and return | [
"read",
"the",
"indices",
"and",
"the",
"indexing",
"array",
"calculate",
"offset",
"rows",
"and",
"return"
] | def read(
self,
where=None,
columns=None,
start: int | None = None,
stop: int | None = None,
):
"""
read the indices and the indexing array, calculate offset rows and return
"""
raise NotImplementedError("WORMTable needs to implement read") | [
"def",
"read",
"(",
"self",
",",
"where",
"=",
"None",
",",
"columns",
"=",
"None",
",",
"start",
":",
"int",
"|",
"None",
"=",
"None",
",",
"stop",
":",
"int",
"|",
"None",
"=",
"None",
",",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"WORMTa... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/io/pytables.py#L4247-L4257 | ||
rapidsai/cudf | d5b2448fc69f17509304d594f029d0df56984962 | python/cudf/cudf/core/index.py | python | _extended_gcd | (a: int, b: int) | return old_r, old_s, old_t | Extended Euclidean algorithms to solve Bezout's identity:
a*x + b*y = gcd(x, y)
Finds one particular solution for x, y: s, t
Returns: gcd, s, t | Extended Euclidean algorithms to solve Bezout's identity:
a*x + b*y = gcd(x, y)
Finds one particular solution for x, y: s, t
Returns: gcd, s, t | [
"Extended",
"Euclidean",
"algorithms",
"to",
"solve",
"Bezout",
"s",
"identity",
":",
"a",
"*",
"x",
"+",
"b",
"*",
"y",
"=",
"gcd",
"(",
"x",
"y",
")",
"Finds",
"one",
"particular",
"solution",
"for",
"x",
"y",
":",
"s",
"t",
"Returns",
":",
"gcd"... | def _extended_gcd(a: int, b: int) -> Tuple[int, int, int]:
"""
Extended Euclidean algorithms to solve Bezout's identity:
a*x + b*y = gcd(x, y)
Finds one particular solution for x, y: s, t
Returns: gcd, s, t
"""
s, old_s = 0, 1
t, old_t = 1, 0
r, old_r = b, a
while r:
quotient = old_r // r
old_r, r = r, old_r - quotient * r
old_s, s = s, old_s - quotient * s
old_t, t = t, old_t - quotient * t
return old_r, old_s, old_t | [
"def",
"_extended_gcd",
"(",
"a",
":",
"int",
",",
"b",
":",
"int",
")",
"->",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
":",
"s",
",",
"old_s",
"=",
"0",
",",
"1",
"t",
",",
"old_t",
"=",
"1",
",",
"0",
"r",
",",
"old_r",
"=",
"b... | https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/index.py#L2734-L2749 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/plan/contactcspace.py | python | StanceCSpace.testSupportPolygon | (self,q) | return True | Returns True if the robot's COM is in the support polygon at
configuration q. | Returns True if the robot's COM is in the support polygon at
configuration q. | [
"Returns",
"True",
"if",
"the",
"robot",
"s",
"COM",
"is",
"in",
"the",
"support",
"polygon",
"at",
"configuration",
"q",
"."
] | def testSupportPolygon(self,q):
"""Returns True if the robot's COM is in the support polygon at
configuration q.
"""
self.robot.setConfig(q)
x = self.robot.getCom()
for plane in self.sp:
if vectorops.dot(plane[:2],(x[0],x[1])) > plane[2] - self.equilibriumMargin:
#print("COM",x[:2],"out of support polygon size",len(sp))
#for plane in sp:
# print(" ",vectorops.dot(plane[:2],(x[0],x[1])) - plane[2])
return False
return True | [
"def",
"testSupportPolygon",
"(",
"self",
",",
"q",
")",
":",
"self",
".",
"robot",
".",
"setConfig",
"(",
"q",
")",
"x",
"=",
"self",
".",
"robot",
".",
"getCom",
"(",
")",
"for",
"plane",
"in",
"self",
".",
"sp",
":",
"if",
"vectorops",
".",
"d... | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/plan/contactcspace.py#L45-L57 | |
blackberry/Boost | fc90c3fde129c62565c023f091eddc4a7ed9902b | tools/build/v2/build/generators.py | python | register_standard | (id, source_types, target_types, requirements = []) | return g | Creates new instance of the 'generator' class and registers it.
Returns the creates instance.
Rationale: the instance is returned so that it's possible to first register
a generator and then call 'run' method on that generator, bypassing all
generator selection. | Creates new instance of the 'generator' class and registers it.
Returns the creates instance.
Rationale: the instance is returned so that it's possible to first register
a generator and then call 'run' method on that generator, bypassing all
generator selection. | [
"Creates",
"new",
"instance",
"of",
"the",
"generator",
"class",
"and",
"registers",
"it",
".",
"Returns",
"the",
"creates",
"instance",
".",
"Rationale",
":",
"the",
"instance",
"is",
"returned",
"so",
"that",
"it",
"s",
"possible",
"to",
"first",
"register... | def register_standard (id, source_types, target_types, requirements = []):
""" Creates new instance of the 'generator' class and registers it.
Returns the creates instance.
Rationale: the instance is returned so that it's possible to first register
a generator and then call 'run' method on that generator, bypassing all
generator selection.
"""
g = Generator (id, False, source_types, target_types, requirements)
register (g)
return g | [
"def",
"register_standard",
"(",
"id",
",",
"source_types",
",",
"target_types",
",",
"requirements",
"=",
"[",
"]",
")",
":",
"g",
"=",
"Generator",
"(",
"id",
",",
"False",
",",
"source_types",
",",
"target_types",
",",
"requirements",
")",
"register",
"... | https://github.com/blackberry/Boost/blob/fc90c3fde129c62565c023f091eddc4a7ed9902b/tools/build/v2/build/generators.py#L663-L672 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/rfc822.py | python | Message.getdate | (self, name) | return parsedate(data) | Retrieve a date field from a header.
Retrieves a date field from the named header, returning a tuple
compatible with time.mktime(). | Retrieve a date field from a header. | [
"Retrieve",
"a",
"date",
"field",
"from",
"a",
"header",
"."
] | def getdate(self, name):
"""Retrieve a date field from a header.
Retrieves a date field from the named header, returning a tuple
compatible with time.mktime().
"""
try:
data = self[name]
except KeyError:
return None
return parsedate(data) | [
"def",
"getdate",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"data",
"=",
"self",
"[",
"name",
"]",
"except",
"KeyError",
":",
"return",
"None",
"return",
"parsedate",
"(",
"data",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/rfc822.py#L355-L365 | |
include-what-you-use/include-what-you-use | 208fbfffa5d69364b9f78e427caa443441279283 | fix_includes.py | python | IWYUOutputParser.ParseOneRecord | (self, iwyu_output, flags) | return retval | Given a file object with output from an iwyu run, return per file info.
For each source file that iwyu_output mentions (because iwyu was run on
it), we return a structure holding the information in IWYUOutputRecord:
1) What file these changes apply to
2) What line numbers hold includes/fwd-declares to remove
3) What includes/fwd-declares to add
4) Ordering information for includes and fwd-declares
Arguments:
iwyu_output: a File object returning lines from an iwyu run
flags: commandline flags, as parsed by optparse. We use
flags.comments, which controls whether we output comments
generated by iwyu.
Returns:
An IWYUOutputRecord object, or None at EOF.
Raises:
FixIncludesError: for malformed-looking lines in the iwyu output. | Given a file object with output from an iwyu run, return per file info. | [
"Given",
"a",
"file",
"object",
"with",
"output",
"from",
"an",
"iwyu",
"run",
"return",
"per",
"file",
"info",
"."
] | def ParseOneRecord(self, iwyu_output, flags):
"""Given a file object with output from an iwyu run, return per file info.
For each source file that iwyu_output mentions (because iwyu was run on
it), we return a structure holding the information in IWYUOutputRecord:
1) What file these changes apply to
2) What line numbers hold includes/fwd-declares to remove
3) What includes/fwd-declares to add
4) Ordering information for includes and fwd-declares
Arguments:
iwyu_output: a File object returning lines from an iwyu run
flags: commandline flags, as parsed by optparse. We use
flags.comments, which controls whether we output comments
generated by iwyu.
Returns:
An IWYUOutputRecord object, or None at EOF.
Raises:
FixIncludesError: for malformed-looking lines in the iwyu output.
"""
for line in iwyu_output:
if not self._ProcessOneLine(line, flags.basedir):
# returns False at end-of-record
break
else: # for/else
return None # at EOF
# Now set up all the fields in an IWYUOutputRecord.
# IWYUOutputRecord.filename
retval = IWYUOutputRecord(self.filename)
# IWYUOutputRecord.lines_to_delete
for line in self.lines_by_section.get(self._REMOVE_SECTION_RE, []):
m = self._LINE_NUMBERS_COMMENT_RE.search(line)
if not m:
raise FixIncludesError('line "%s" (for %s) has no line number'
% (line, self.filename))
# The RE is of the form [start_line, end_line], inclusive.
for line_number in range(int(m.group(1)), int(m.group(2)) + 1):
retval.lines_to_delete.add(line_number)
# IWYUOutputRecord.some_include_lines
for line in (self.lines_by_section.get(self._REMOVE_SECTION_RE, []) +
self.lines_by_section.get(self._TOTAL_SECTION_RE, [])):
if not _INCLUDE_RE.match(line):
continue
m = self._LINE_NUMBERS_COMMENT_RE.search(line)
if not m:
continue # not all #include lines have line numbers, but some do
for line_number in range(int(m.group(1)), int(m.group(2)) + 1):
retval.some_include_lines.add(line_number)
# IWYUOutputRecord.seen_forward_declare_lines
for line in (self.lines_by_section.get(self._REMOVE_SECTION_RE, []) +
self.lines_by_section.get(self._TOTAL_SECTION_RE, [])):
# Everything that's not an #include is a forward-declare.
if line.startswith('- '): # the 'remove' lines all start with '- '.
line = line[len('- '):]
if _INCLUDE_RE.match(line):
continue
m = self._LINE_NUMBERS_COMMENT_RE.search(line)
if m:
line_range = (int(m.group(1)), int(m.group(2))+1)
retval.seen_forward_declare_lines.add(line_range)
if '::' in line:
retval.nested_forward_declare_lines.add(line_range)
# IWYUOutputRecord.includes_and_forward_declares_to_add
for line in self.lines_by_section.get(self._ADD_SECTION_RE, []):
line = _COMMENT_RE.sub('', line)
retval.includes_and_forward_declares_to_add.add(line)
# IWYUOutputRecord.full_include_lines
for line in self.lines_by_section.get(self._TOTAL_SECTION_RE, []):
m = _INCLUDE_RE.match(line)
if m:
if not flags.comments:
line = _COMMENT_RE.sub('', line) # pretend there were no comments
else:
# Just remove '// line XX': that's iwyu metadata, not a real comment
line = self._LINE_NUMBERS_COMMENT_RE.sub('', line)
retval.full_include_lines[m.group(1)] = line
return retval | [
"def",
"ParseOneRecord",
"(",
"self",
",",
"iwyu_output",
",",
"flags",
")",
":",
"for",
"line",
"in",
"iwyu_output",
":",
"if",
"not",
"self",
".",
"_ProcessOneLine",
"(",
"line",
",",
"flags",
".",
"basedir",
")",
":",
"# returns False at end-of-record",
"... | https://github.com/include-what-you-use/include-what-you-use/blob/208fbfffa5d69364b9f78e427caa443441279283/fix_includes.py#L388-L472 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/logging/__init__.py | python | LoggerAdapter.info | (self, msg, *args, **kwargs) | Delegate an info call to the underlying logger. | Delegate an info call to the underlying logger. | [
"Delegate",
"an",
"info",
"call",
"to",
"the",
"underlying",
"logger",
"."
] | def info(self, msg, *args, **kwargs):
"""
Delegate an info call to the underlying logger.
"""
self.log(INFO, msg, *args, **kwargs) | [
"def",
"info",
"(",
"self",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"log",
"(",
"INFO",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/logging/__init__.py#L1724-L1728 | ||
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/msvs_emulation.py | python | MsvsSettings._TargetConfig | (self, config) | return config | Returns the target-specific configuration. | Returns the target-specific configuration. | [
"Returns",
"the",
"target",
"-",
"specific",
"configuration",
"."
] | def _TargetConfig(self, config):
"""Returns the target-specific configuration."""
# There's two levels of architecture/platform specification in VS. The
# first level is globally for the configuration (this is what we consider
# "the" config at the gyp level, which will be something like 'Debug' or
# 'Release_x64'), and a second target-specific configuration, which is an
# override for the global one. |config| is remapped here to take into
# account the local target-specific overrides to the global configuration.
arch = self.GetArch(config)
if arch == 'x64' and not config.endswith('_x64'):
config += '_x64'
if arch == 'x86' and config.endswith('_x64'):
config = config.rsplit('_', 1)[0]
return config | [
"def",
"_TargetConfig",
"(",
"self",
",",
"config",
")",
":",
"# There's two levels of architecture/platform specification in VS. The",
"# first level is globally for the configuration (this is what we consider",
"# \"the\" config at the gyp level, which will be something like 'Debug' or",
"# ... | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/msvs_emulation.py#L304-L317 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/drill/view/DrillSettingsDialog.py | python | MouseScrollEventFilter.eventFilter | (self, obj, event) | return event.type() == QEvent.Wheel | Override QObject::eventFilter
Args:
obj (QObject): object on which the event is called
event (QEvent): event received | Override QObject::eventFilter | [
"Override",
"QObject",
"::",
"eventFilter"
] | def eventFilter(self, obj, event):
"""
Override QObject::eventFilter
Args:
obj (QObject): object on which the event is called
event (QEvent): event received
"""
return event.type() == QEvent.Wheel | [
"def",
"eventFilter",
"(",
"self",
",",
"obj",
",",
"event",
")",
":",
"return",
"event",
".",
"type",
"(",
")",
"==",
"QEvent",
".",
"Wheel"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/drill/view/DrillSettingsDialog.py#L28-L36 | |
alibaba/weex_js_engine | 2bdf4b6f020c1fc99c63f649718f6faf7e27fdde | jni/v8core/v8/build/gyp/pylib/gyp/input.py | python | ValidateActionsInTarget | (target, target_dict, build_file) | Validates the inputs to the actions in a target. | Validates the inputs to the actions in a target. | [
"Validates",
"the",
"inputs",
"to",
"the",
"actions",
"in",
"a",
"target",
"."
] | def ValidateActionsInTarget(target, target_dict, build_file):
'''Validates the inputs to the actions in a target.'''
target_name = target_dict.get('target_name')
actions = target_dict.get('actions', [])
for action in actions:
action_name = action.get('action_name')
if not action_name:
raise GypError("Anonymous action in target %s. "
"An action must have an 'action_name' field." %
target_name)
inputs = action.get('inputs', None)
if inputs is None:
raise GypError('Action in target %s has no inputs.' % target_name)
action_command = action.get('action')
if action_command and not action_command[0]:
raise GypError("Empty action as command in target %s." % target_name) | [
"def",
"ValidateActionsInTarget",
"(",
"target",
",",
"target_dict",
",",
"build_file",
")",
":",
"target_name",
"=",
"target_dict",
".",
"get",
"(",
"'target_name'",
")",
"actions",
"=",
"target_dict",
".",
"get",
"(",
"'actions'",
",",
"[",
"]",
")",
"for"... | https://github.com/alibaba/weex_js_engine/blob/2bdf4b6f020c1fc99c63f649718f6faf7e27fdde/jni/v8core/v8/build/gyp/pylib/gyp/input.py#L2260-L2275 | ||
llvm/llvm-project | ffa6262cb4e2a335d26416fad39a581b4f98c5f4 | lldb/third_party/Python/module/pexpect-4.6/pexpect/screen.py | python | screen.__init__ | (self, r=24, c=80, encoding='latin-1', encoding_errors='replace') | This initializes a blank screen of the given dimensions. | This initializes a blank screen of the given dimensions. | [
"This",
"initializes",
"a",
"blank",
"screen",
"of",
"the",
"given",
"dimensions",
"."
] | def __init__(self, r=24, c=80, encoding='latin-1', encoding_errors='replace'):
'''This initializes a blank screen of the given dimensions.'''
self.rows = r
self.cols = c
self.encoding = encoding
self.encoding_errors = encoding_errors
if encoding is not None:
self.decoder = codecs.getincrementaldecoder(encoding)(encoding_errors)
else:
self.decoder = None
self.cur_r = 1
self.cur_c = 1
self.cur_saved_r = 1
self.cur_saved_c = 1
self.scroll_row_start = 1
self.scroll_row_end = self.rows
self.w = [ [SPACE] * self.cols for _ in range(self.rows)] | [
"def",
"__init__",
"(",
"self",
",",
"r",
"=",
"24",
",",
"c",
"=",
"80",
",",
"encoding",
"=",
"'latin-1'",
",",
"encoding_errors",
"=",
"'replace'",
")",
":",
"self",
".",
"rows",
"=",
"r",
"self",
".",
"cols",
"=",
"c",
"self",
".",
"encoding",
... | https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/lldb/third_party/Python/module/pexpect-4.6/pexpect/screen.py#L85-L102 | ||
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/ndarray/numpy/_op.py | python | hanning | (M, dtype=None, device=None) | return _api_internal.hanning(M, dtype, device) | r"""Return the Hanning window.
The Hanning window is a taper formed by using a weighted cosine.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an
empty array is returned.
device : Device, optional
Device context on which the memory is allocated. Default is
`mxnet.device.current_device()`.
Returns
-------
out : ndarray, shape(M,)
The window, with the maximum value normalized to one (the value
one appears only if `M` is odd).
When npx.is_np_default_dtype() returns False, default dtype is float32;
When npx.is_np_default_dtype() returns True, default dtype is float64.
Note that you need select numpy.float32 or float64 in this operator.
See Also
--------
blackman, hamming
Notes
-----
The Hanning window is defined as
.. math:: w(n) = 0.5 - 0.5cos\left(\frac{2\pi{n}}{M-1}\right)
\qquad 0 \leq n \leq M-1
The Hanning was named for Julius von Hann, an Austrian meteorologist.
It is also known as the Cosine Bell. Some authors prefer that it be
called a Hann window, to help avoid confusion with the very similar
Hamming window.
Most references to the Hanning window come from the signal processing
literature, where it is used as one of many windowing functions for
smoothing values. It is also known as an apodization (which means
"removing the foot", i.e. smoothing discontinuities at the beginning
and end of the sampled signal) or tapering function.
References
----------
.. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power
spectra, Dover Publications, New York.
.. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics",
The University of Alberta Press, 1975, pp. 106-108.
.. [3] Wikipedia, "Window function",
http://en.wikipedia.org/wiki/Window_function
.. [4] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling,
"Numerical Recipes", Cambridge University Press, 1986, page 425.
Examples
--------
>>> np.hanning(12)
array([0. , 0.07937324, 0.29229254, 0.5711574 , 0.8274304 ,
0.9797465 , 0.97974646, 0.82743025, 0.5711573 , 0.29229245,
0.07937312, 0. ])
Plot the window and its frequency response:
>>> import matplotlib.pyplot as plt
>>> window = np.hanning(51)
>>> plt.plot(window.asnumpy())
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("Hann window")
Text(0.5, 1.0, 'Hann window')
>>> plt.ylabel("Amplitude")
Text(0, 0.5, 'Amplitude')
>>> plt.xlabel("Sample")
Text(0.5, 0, 'Sample')
>>> plt.show() | r"""Return the Hanning window. | [
"r",
"Return",
"the",
"Hanning",
"window",
"."
] | def hanning(M, dtype=None, device=None):
r"""Return the Hanning window.
The Hanning window is a taper formed by using a weighted cosine.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an
empty array is returned.
device : Device, optional
Device context on which the memory is allocated. Default is
`mxnet.device.current_device()`.
Returns
-------
out : ndarray, shape(M,)
The window, with the maximum value normalized to one (the value
one appears only if `M` is odd).
When npx.is_np_default_dtype() returns False, default dtype is float32;
When npx.is_np_default_dtype() returns True, default dtype is float64.
Note that you need select numpy.float32 or float64 in this operator.
See Also
--------
blackman, hamming
Notes
-----
The Hanning window is defined as
.. math:: w(n) = 0.5 - 0.5cos\left(\frac{2\pi{n}}{M-1}\right)
\qquad 0 \leq n \leq M-1
The Hanning was named for Julius von Hann, an Austrian meteorologist.
It is also known as the Cosine Bell. Some authors prefer that it be
called a Hann window, to help avoid confusion with the very similar
Hamming window.
Most references to the Hanning window come from the signal processing
literature, where it is used as one of many windowing functions for
smoothing values. It is also known as an apodization (which means
"removing the foot", i.e. smoothing discontinuities at the beginning
and end of the sampled signal) or tapering function.
References
----------
.. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power
spectra, Dover Publications, New York.
.. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics",
The University of Alberta Press, 1975, pp. 106-108.
.. [3] Wikipedia, "Window function",
http://en.wikipedia.org/wiki/Window_function
.. [4] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling,
"Numerical Recipes", Cambridge University Press, 1986, page 425.
Examples
--------
>>> np.hanning(12)
array([0. , 0.07937324, 0.29229254, 0.5711574 , 0.8274304 ,
0.9797465 , 0.97974646, 0.82743025, 0.5711573 , 0.29229245,
0.07937312, 0. ])
Plot the window and its frequency response:
>>> import matplotlib.pyplot as plt
>>> window = np.hanning(51)
>>> plt.plot(window.asnumpy())
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("Hann window")
Text(0.5, 1.0, 'Hann window')
>>> plt.ylabel("Amplitude")
Text(0, 0.5, 'Amplitude')
>>> plt.xlabel("Sample")
Text(0.5, 0, 'Sample')
>>> plt.show()
"""
if device is None:
device = str(current_device())
else:
device = str(device)
if dtype is not None and not isinstance(dtype, str):
dtype = _np.dtype(dtype).name
return _api_internal.hanning(M, dtype, device) | [
"def",
"hanning",
"(",
"M",
",",
"dtype",
"=",
"None",
",",
"device",
"=",
"None",
")",
":",
"if",
"device",
"is",
"None",
":",
"device",
"=",
"str",
"(",
"current_device",
"(",
")",
")",
"else",
":",
"device",
"=",
"str",
"(",
"device",
")",
"if... | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/ndarray/numpy/_op.py#L6192-L6275 | |
nasa/fprime | 595cf3682d8365943d86c1a6fe7c78f0a116acf0 | Autocoders/Python/src/fprime_ac/generators/visitors/InstanceTopologyCmdHTMLVisitor.py | python | InstanceTopologyCmdHTMLVisitor._writeTmpl | (self, instance, c, visit_str) | Wrapper to write tmpl to files desc. | Wrapper to write tmpl to files desc. | [
"Wrapper",
"to",
"write",
"tmpl",
"to",
"files",
"desc",
"."
] | def _writeTmpl(self, instance, c, visit_str):
"""
Wrapper to write tmpl to files desc.
"""
DEBUG.debug("InstanceTopologyCmdHTMLVisitor:%s" % visit_str)
DEBUG.debug("===================================")
DEBUG.debug(c)
self.__fp_dict[instance].writelines(c.__str__())
DEBUG.debug("===================================") | [
"def",
"_writeTmpl",
"(",
"self",
",",
"instance",
",",
"c",
",",
"visit_str",
")",
":",
"DEBUG",
".",
"debug",
"(",
"\"InstanceTopologyCmdHTMLVisitor:%s\"",
"%",
"visit_str",
")",
"DEBUG",
".",
"debug",
"(",
"\"===================================\"",
")",
"DEBUG"... | https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/generators/visitors/InstanceTopologyCmdHTMLVisitor.py#L83-L91 | ||
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/simpla/_utils.py | python | GapController._accel | (self, speedDiff, gap) | return self._gapGain * gapError + self._speedGain * speedDiff | Returns the acceleration computed by a linear controller | Returns the acceleration computed by a linear controller | [
"Returns",
"the",
"acceleration",
"computed",
"by",
"a",
"linear",
"controller"
] | def _accel(self, speedDiff, gap):
'''
Returns the acceleration computed by a linear controller
'''
gapError = gap - self._desiredGap
return self._gapGain * gapError + self._speedGain * speedDiff | [
"def",
"_accel",
"(",
"self",
",",
"speedDiff",
",",
"gap",
")",
":",
"gapError",
"=",
"gap",
"-",
"self",
".",
"_desiredGap",
"return",
"self",
".",
"_gapGain",
"*",
"gapError",
"+",
"self",
".",
"_speedGain",
"*",
"speedDiff"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/simpla/_utils.py#L134-L139 | |
Cisco-Talos/moflow | ed71dfb0540d9e0d7a4c72f0881b58958d573728 | BAP-0.7-moflow/libtracewrap/libtrace/protobuf/python/google/protobuf/text_format.py | python | _Tokenizer.ConsumeUint64 | (self) | return result | Consumes an unsigned 64bit integer number.
Returns:
The integer parsed.
Raises:
ParseError: If an unsigned 64bit integer couldn't be consumed. | Consumes an unsigned 64bit integer number. | [
"Consumes",
"an",
"unsigned",
"64bit",
"integer",
"number",
"."
] | def ConsumeUint64(self):
"""Consumes an unsigned 64bit integer number.
Returns:
The integer parsed.
Raises:
ParseError: If an unsigned 64bit integer couldn't be consumed.
"""
try:
result = self._ParseInteger(self.token, is_signed=False, is_long=True)
except ValueError, e:
raise self._IntegerParseError(e)
self.NextToken()
return result | [
"def",
"ConsumeUint64",
"(",
"self",
")",
":",
"try",
":",
"result",
"=",
"self",
".",
"_ParseInteger",
"(",
"self",
".",
"token",
",",
"is_signed",
"=",
"False",
",",
"is_long",
"=",
"True",
")",
"except",
"ValueError",
",",
"e",
":",
"raise",
"self",... | https://github.com/Cisco-Talos/moflow/blob/ed71dfb0540d9e0d7a4c72f0881b58958d573728/BAP-0.7-moflow/libtracewrap/libtrace/protobuf/python/google/protobuf/text_format.py#L471-L485 | |
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | qa/tasks/ec_inconsistent_hinfo.py | python | task | (ctx, config) | Test handling of objects with inconsistent hash info during backfill and deep-scrub.
A pretty rigid cluster is brought up and tested by this task | Test handling of objects with inconsistent hash info during backfill and deep-scrub. | [
"Test",
"handling",
"of",
"objects",
"with",
"inconsistent",
"hash",
"info",
"during",
"backfill",
"and",
"deep",
"-",
"scrub",
"."
] | def task(ctx, config):
"""
Test handling of objects with inconsistent hash info during backfill and deep-scrub.
A pretty rigid cluster is brought up and tested by this task
"""
if config is None:
config = {}
assert isinstance(config, dict), \
'ec_inconsistent_hinfo task only accepts a dict for configuration'
first_mon = teuthology.get_first_mon(ctx, config)
(mon,) = ctx.cluster.only(first_mon).remotes.keys()
manager = ceph_manager.CephManager(
mon,
ctx=ctx,
logger=log.getChild('ceph_manager'),
)
profile = config.get('erasure_code_profile', {
'k': '2',
'm': '1',
'crush-failure-domain': 'osd'
})
profile_name = profile.get('name', 'backfill_unfound')
manager.create_erasure_code_profile(profile_name, profile)
pool = manager.create_pool_with_unique_name(
pg_num=1,
erasure_code_profile_name=profile_name,
min_size=2)
manager.raw_cluster_cmd('osd', 'pool', 'set', pool,
'pg_autoscale_mode', 'off')
manager.flush_pg_stats([0, 1, 2, 3])
manager.wait_for_clean()
pool_id = manager.get_pool_num(pool)
pgid = '%d.0' % pool_id
pgs = manager.get_pg_stats()
acting = next((pg['acting'] for pg in pgs if pg['pgid'] == pgid), None)
log.info("acting=%s" % acting)
assert acting
primary = acting[0]
# something that is always there, readable and never empty
dummyfile = '/etc/group'
# kludge to make sure they get a map
rados(ctx, mon, ['-p', pool, 'put', 'dummy', dummyfile])
manager.flush_pg_stats([0, 1])
manager.wait_for_recovery()
log.debug("create test object")
obj = 'test'
rados(ctx, mon, ['-p', pool, 'put', obj, dummyfile])
victim = acting[1]
log.info("remove test object hash info from osd.%s shard and test deep-scrub and repair"
% victim)
manager.objectstore_tool(pool, options='', args='rm-attr hinfo_key',
object_name=obj, osd=victim)
check_time_now = time.strftime('%s')
manager.raw_cluster_cmd('pg', 'deep-scrub', pgid)
wait_for_deep_scrub_complete(manager, pgid, check_time_now, True)
check_time_now = time.strftime('%s')
manager.raw_cluster_cmd('pg', 'repair', pgid)
wait_for_deep_scrub_complete(manager, pgid, check_time_now, False)
log.info("remove test object hash info from primary osd.%s shard and test backfill"
% primary)
log.debug("write some data")
rados(ctx, mon, ['-p', pool, 'bench', '30', 'write', '-b', '4096',
'--no-cleanup'])
manager.objectstore_tool(pool, options='', args='rm-attr hinfo_key',
object_name=obj, osd=primary)
# mark the osd out to trigger a rebalance/backfill
source = acting[1]
target = [x for x in [0, 1, 2, 3] if x not in acting][0]
manager.mark_out_osd(source)
# wait for everything to peer, backfill and recover
wait_for_backfilling_complete(manager, pgid, source, target)
manager.wait_for_clean()
manager.flush_pg_stats([0, 1, 2, 3])
pgs = manager.get_pg_stats()
pg = next((pg for pg in pgs if pg['pgid'] == pgid), None)
log.debug('pg=%s' % pg)
assert pg
assert 'clean' in pg['state'].split('+')
assert 'inconsistent' not in pg['state'].split('+')
unfound = manager.get_num_unfound_objects()
log.debug("there are %d unfound objects" % unfound)
assert unfound == 0
source, target = target, source
log.info("remove test object hash info from non-primary osd.%s shard and test backfill"
% source)
manager.objectstore_tool(pool, options='', args='rm-attr hinfo_key',
object_name=obj, osd=source)
# mark the osd in to trigger a rebalance/backfill
manager.mark_in_osd(target)
# wait for everything to peer, backfill and recover
wait_for_backfilling_complete(manager, pgid, source, target)
manager.wait_for_clean()
manager.flush_pg_stats([0, 1, 2, 3])
pgs = manager.get_pg_stats()
pg = next((pg for pg in pgs if pg['pgid'] == pgid), None)
log.debug('pg=%s' % pg)
assert pg
assert 'clean' in pg['state'].split('+')
assert 'inconsistent' not in pg['state'].split('+')
unfound = manager.get_num_unfound_objects()
log.debug("there are %d unfound objects" % unfound)
assert unfound == 0
log.info("remove hash info from two shards and test backfill")
source = acting[2]
target = [x for x in [0, 1, 2, 3] if x not in acting][0]
manager.objectstore_tool(pool, options='', args='rm-attr hinfo_key',
object_name=obj, osd=primary)
manager.objectstore_tool(pool, options='', args='rm-attr hinfo_key',
object_name=obj, osd=source)
# mark the osd out to trigger a rebalance/backfill
manager.mark_out_osd(source)
# wait for everything to peer, backfill and detect unfound object
wait_for_backfilling_complete(manager, pgid, source, target)
# verify that there is unfound object
manager.flush_pg_stats([0, 1, 2, 3])
pgs = manager.get_pg_stats()
pg = next((pg for pg in pgs if pg['pgid'] == pgid), None)
log.debug('pg=%s' % pg)
assert pg
assert 'backfill_unfound' in pg['state'].split('+')
unfound = manager.get_num_unfound_objects()
log.debug("there are %d unfound objects" % unfound)
assert unfound == 1
m = manager.list_pg_unfound(pgid)
log.debug('list_pg_unfound=%s' % m)
assert m['num_unfound'] == pg['stat_sum']['num_objects_unfound']
# mark stuff lost
pgs = manager.get_pg_stats()
manager.raw_cluster_cmd('pg', pgid, 'mark_unfound_lost', 'delete')
# wait for everything to peer and be happy...
manager.flush_pg_stats([0, 1, 2, 3])
manager.wait_for_recovery() | [
"def",
"task",
"(",
"ctx",
",",
"config",
")",
":",
"if",
"config",
"is",
"None",
":",
"config",
"=",
"{",
"}",
"assert",
"isinstance",
"(",
"config",
",",
"dict",
")",
",",
"'ec_inconsistent_hinfo task only accepts a dict for configuration'",
"first_mon",
"=",
... | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/qa/tasks/ec_inconsistent_hinfo.py#L63-L225 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/tools/inspector_protocol/jinja2/compiler.py | python | CodeGenerator.macro_def | (self, macro_ref, frame) | Dump the macro definition for the def created by macro_body. | Dump the macro definition for the def created by macro_body. | [
"Dump",
"the",
"macro",
"definition",
"for",
"the",
"def",
"created",
"by",
"macro_body",
"."
] | def macro_def(self, macro_ref, frame):
"""Dump the macro definition for the def created by macro_body."""
arg_tuple = ', '.join(repr(x.name) for x in macro_ref.node.args)
name = getattr(macro_ref.node, 'name', None)
if len(macro_ref.node.args) == 1:
arg_tuple += ','
self.write('Macro(environment, macro, %r, (%s), %r, %r, %r, '
'context.eval_ctx.autoescape)' %
(name, arg_tuple, macro_ref.accesses_kwargs,
macro_ref.accesses_varargs, macro_ref.accesses_caller)) | [
"def",
"macro_def",
"(",
"self",
",",
"macro_ref",
",",
"frame",
")",
":",
"arg_tuple",
"=",
"', '",
".",
"join",
"(",
"repr",
"(",
"x",
".",
"name",
")",
"for",
"x",
"in",
"macro_ref",
".",
"node",
".",
"args",
")",
"name",
"=",
"getattr",
"(",
... | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/inspector_protocol/jinja2/compiler.py#L582-L591 | ||
bitconch/bitconch-core | 5537f3215b3e3b76f6720d6f908676a6c34bc5db | deploy-morgan.py | python | rmtree_onerror | (self, func, file_path, exc_info) | Error handler for ``shutil.rmtree``.
If the error is due to an access error (read only file)
it attempts to add write permission and then retries.
If the error is for another reason it re-raises the error.
Usage : ``shutil.rmtree(path, onerror=onerror)`` | Error handler for ``shutil.rmtree``.
If the error is due to an access error (read only file)
it attempts to add write permission and then retries.
If the error is for another reason it re-raises the error.
Usage : ``shutil.rmtree(path, onerror=onerror)`` | [
"Error",
"handler",
"for",
"shutil",
".",
"rmtree",
".",
"If",
"the",
"error",
"is",
"due",
"to",
"an",
"access",
"error",
"(",
"read",
"only",
"file",
")",
"it",
"attempts",
"to",
"add",
"write",
"permission",
"and",
"then",
"retries",
".",
"If",
"the... | def rmtree_onerror(self, func, file_path, exc_info):
"""
Error handler for ``shutil.rmtree``.
If the error is due to an access error (read only file)
it attempts to add write permission and then retries.
If the error is for another reason it re-raises the error.
Usage : ``shutil.rmtree(path, onerror=onerror)``
"""
logging.warning(str(exc_info))
logging.warning("rmtree error,check the file exists or try to chmod the file,then retry rmtree action.")
os.chmod(file_path, stat.S_IWRITE) #chmod to writeable
if os.path.isdir(file_path):
#file exists
func(file_path)
else:
#handle whatever
raise | [
"def",
"rmtree_onerror",
"(",
"self",
",",
"func",
",",
"file_path",
",",
"exc_info",
")",
":",
"logging",
".",
"warning",
"(",
"str",
"(",
"exc_info",
")",
")",
"logging",
".",
"warning",
"(",
"\"rmtree error,check the file exists or try to chmod the file,then retr... | https://github.com/bitconch/bitconch-core/blob/5537f3215b3e3b76f6720d6f908676a6c34bc5db/deploy-morgan.py#L18-L34 | ||
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/distutils/fancy_getopt.py | python | FancyGetopt.generate_help | (self, header=None) | return lines | Generate help text (a list of strings, one per suggested line of
output) from the option table for this FancyGetopt object. | Generate help text (a list of strings, one per suggested line of
output) from the option table for this FancyGetopt object. | [
"Generate",
"help",
"text",
"(",
"a",
"list",
"of",
"strings",
"one",
"per",
"suggested",
"line",
"of",
"output",
")",
"from",
"the",
"option",
"table",
"for",
"this",
"FancyGetopt",
"object",
"."
] | def generate_help (self, header=None):
"""Generate help text (a list of strings, one per suggested line of
output) from the option table for this FancyGetopt object.
"""
# Blithely assume the option table is good: probably wouldn't call
# 'generate_help()' unless you've already called 'getopt()'.
# First pass: determine maximum length of long option names
max_opt = 0
for option in self.option_table:
long = option[0]
short = option[1]
l = len(long)
if long[-1] == '=':
l = l - 1
if short is not None:
l = l + 5 # " (-x)" where short == 'x'
if l > max_opt:
max_opt = l
opt_width = max_opt + 2 + 2 + 2 # room for indent + dashes + gutter
# Typical help block looks like this:
# --foo controls foonabulation
# Help block for longest option looks like this:
# --flimflam set the flim-flam level
# and with wrapped text:
# --flimflam set the flim-flam level (must be between
# 0 and 100, except on Tuesdays)
# Options with short names will have the short name shown (but
# it doesn't contribute to max_opt):
# --foo (-f) controls foonabulation
# If adding the short option would make the left column too wide,
# we push the explanation off to the next line
# --flimflam (-l)
# set the flim-flam level
# Important parameters:
# - 2 spaces before option block start lines
# - 2 dashes for each long option name
# - min. 2 spaces between option and explanation (gutter)
# - 5 characters (incl. space) for short option name
# Now generate lines of help text. (If 80 columns were good enough
# for Jesus, then 78 columns are good enough for me!)
line_width = 78
text_width = line_width - opt_width
big_indent = ' ' * opt_width
if header:
lines = [header]
else:
lines = ['Option summary:']
for option in self.option_table:
long, short, help = option[:3]
text = wrap_text(help, text_width)
if long[-1] == '=':
long = long[0:-1]
# Case 1: no short option at all (makes life easy)
if short is None:
if text:
lines.append(" --%-*s %s" % (max_opt, long, text[0]))
else:
lines.append(" --%-*s " % (max_opt, long))
# Case 2: we have a short option, so we have to include it
# just after the long option
else:
opt_names = "%s (-%s)" % (long, short)
if text:
lines.append(" --%-*s %s" %
(max_opt, opt_names, text[0]))
else:
lines.append(" --%-*s" % opt_names)
for l in text[1:]:
lines.append(big_indent + l)
# for self.option_table
return lines | [
"def",
"generate_help",
"(",
"self",
",",
"header",
"=",
"None",
")",
":",
"# Blithely assume the option table is good: probably wouldn't call",
"# 'generate_help()' unless you've already called 'getopt()'.",
"# First pass: determine maximum length of long option names",
"max_opt",
"=",
... | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/distutils/fancy_getopt.py#L310-L390 | |
yrnkrn/zapcc | c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50 | tools/clang/utils/check_cfc/obj_diff.py | python | compare_debug_info | (objfilea, objfileb) | return first_diff(dbga, dbgb, objfilea, objfileb) | Compare debug info of two different files.
Allowing unavoidable differences, such as filenames.
Return the first difference if the debug info differs, or None.
If there are differences in the code, there will almost certainly be differences in the debug info too. | Compare debug info of two different files.
Allowing unavoidable differences, such as filenames.
Return the first difference if the debug info differs, or None.
If there are differences in the code, there will almost certainly be differences in the debug info too. | [
"Compare",
"debug",
"info",
"of",
"two",
"different",
"files",
".",
"Allowing",
"unavoidable",
"differences",
"such",
"as",
"filenames",
".",
"Return",
"the",
"first",
"difference",
"if",
"the",
"debug",
"info",
"differs",
"or",
"None",
".",
"If",
"there",
"... | def compare_debug_info(objfilea, objfileb):
"""Compare debug info of two different files.
Allowing unavoidable differences, such as filenames.
Return the first difference if the debug info differs, or None.
If there are differences in the code, there will almost certainly be differences in the debug info too.
"""
dbga = dump_debug(objfilea)
dbgb = dump_debug(objfileb)
return first_diff(dbga, dbgb, objfilea, objfileb) | [
"def",
"compare_debug_info",
"(",
"objfilea",
",",
"objfileb",
")",
":",
"dbga",
"=",
"dump_debug",
"(",
"objfilea",
")",
"dbgb",
"=",
"dump_debug",
"(",
"objfileb",
")",
"return",
"first_diff",
"(",
"dbga",
",",
"dbgb",
",",
"objfilea",
",",
"objfileb",
"... | https://github.com/yrnkrn/zapcc/blob/c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50/tools/clang/utils/check_cfc/obj_diff.py#L76-L84 | |
yrnkrn/zapcc | c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50 | utils/llvm-build/llvmbuild/componentinfo.py | python | ComponentInfo.get_component_references | (self) | get_component_references() -> iter
Return an iterator over the named references to other components from
this object. Items are of the form (reference-type, component-name). | get_component_references() -> iter | [
"get_component_references",
"()",
"-",
">",
"iter"
] | def get_component_references(self):
"""get_component_references() -> iter
Return an iterator over the named references to other components from
this object. Items are of the form (reference-type, component-name).
"""
# Parent references are handled specially.
for r in self.dependencies:
yield ('dependency', r) | [
"def",
"get_component_references",
"(",
"self",
")",
":",
"# Parent references are handled specially.",
"for",
"r",
"in",
"self",
".",
"dependencies",
":",
"yield",
"(",
"'dependency'",
",",
"r",
")"
] | https://github.com/yrnkrn/zapcc/blob/c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50/utils/llvm-build/llvmbuild/componentinfo.py#L60-L69 | ||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Code/Tools/waf-1.7.13/waflib/Tools/ruby.py | python | check_ruby_module | (self, module_name) | Check if the selected ruby interpreter can require the given ruby module::
def configure(conf):
conf.check_ruby_module('libxml')
:param module_name: module
:type module_name: string | Check if the selected ruby interpreter can require the given ruby module:: | [
"Check",
"if",
"the",
"selected",
"ruby",
"interpreter",
"can",
"require",
"the",
"given",
"ruby",
"module",
"::"
] | def check_ruby_module(self, module_name):
"""
Check if the selected ruby interpreter can require the given ruby module::
def configure(conf):
conf.check_ruby_module('libxml')
:param module_name: module
:type module_name: string
"""
self.start_msg('Ruby module %s' % module_name)
try:
self.cmd_and_log([self.env['RUBY'], '-e', 'require \'%s\';puts 1' % module_name])
except Exception:
self.end_msg(False)
self.fatal('Could not find the ruby module %r' % module_name)
self.end_msg(True) | [
"def",
"check_ruby_module",
"(",
"self",
",",
"module_name",
")",
":",
"self",
".",
"start_msg",
"(",
"'Ruby module %s'",
"%",
"module_name",
")",
"try",
":",
"self",
".",
"cmd_and_log",
"(",
"[",
"self",
".",
"env",
"[",
"'RUBY'",
"]",
",",
"'-e'",
",",... | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/Tools/ruby.py#L148-L164 | ||
forkineye/ESPixelStick | 22926f1c0d1131f1369fc7cad405689a095ae3cb | dist/bin/pyserial/examples/wxTerminal.py | python | TerminalFrame.OnSaveAs | (self, event) | Save contents of output window. | Save contents of output window. | [
"Save",
"contents",
"of",
"output",
"window",
"."
] | def OnSaveAs(self, event): # wxGlade: TerminalFrame.<event_handler>
"""Save contents of output window."""
with wx.FileDialog(
None,
"Save Text As...",
".",
"",
"Text File|*.txt|All Files|*",
wx.SAVE) as dlg:
if dlg.ShowModal() == wx.ID_OK:
filename = dlg.GetPath()
with codecs.open(filename, 'w', encoding='utf-8') as f:
text = self.text_ctrl_output.GetValue().encode("utf-8")
f.write(text) | [
"def",
"OnSaveAs",
"(",
"self",
",",
"event",
")",
":",
"# wxGlade: TerminalFrame.<event_handler>",
"with",
"wx",
".",
"FileDialog",
"(",
"None",
",",
"\"Save Text As...\"",
",",
"\".\"",
",",
"\"\"",
",",
"\"Text File|*.txt|All Files|*\"",
",",
"wx",
".",
"SAVE",... | https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/pyserial/examples/wxTerminal.py#L231-L244 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/importlib/_bootstrap_external.py | python | WindowsRegistryFinder.find_module | (cls, fullname, path=None) | Find module named in the registry.
This method is deprecated. Use exec_module() instead. | Find module named in the registry. | [
"Find",
"module",
"named",
"in",
"the",
"registry",
"."
] | def find_module(cls, fullname, path=None):
"""Find module named in the registry.
This method is deprecated. Use exec_module() instead.
"""
spec = cls.find_spec(fullname, path)
if spec is not None:
return spec.loader
else:
return None | [
"def",
"find_module",
"(",
"cls",
",",
"fullname",
",",
"path",
"=",
"None",
")",
":",
"spec",
"=",
"cls",
".",
"find_spec",
"(",
"fullname",
",",
"path",
")",
"if",
"spec",
"is",
"not",
"None",
":",
"return",
"spec",
".",
"loader",
"else",
":",
"r... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/importlib/_bootstrap_external.py#L693-L703 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/arrays/datetimelike.py | python | DatetimeLikeArrayMixin._format_native_types | (self, na_rep="NaT", date_format=None) | Helper method for astype when converting to strings.
Returns
-------
ndarray[str] | Helper method for astype when converting to strings. | [
"Helper",
"method",
"for",
"astype",
"when",
"converting",
"to",
"strings",
"."
] | def _format_native_types(self, na_rep="NaT", date_format=None):
"""
Helper method for astype when converting to strings.
Returns
-------
ndarray[str]
"""
raise AbstractMethodError(self) | [
"def",
"_format_native_types",
"(",
"self",
",",
"na_rep",
"=",
"\"NaT\"",
",",
"date_format",
"=",
"None",
")",
":",
"raise",
"AbstractMethodError",
"(",
"self",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/arrays/datetimelike.py#L292-L300 | ||
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/polynomial/laguerre.py | python | lagder | (c, m=1, scl=1, axis=0) | return c | Differentiate a Laguerre series.
Returns the Laguerre series coefficients `c` differentiated `m` times
along `axis`. At each iteration the result is multiplied by `scl` (the
scaling factor is for use in a linear change of variable). The argument
`c` is an array of coefficients from low to high degree along each
axis, e.g., [1,2,3] represents the series ``1*L_0 + 2*L_1 + 3*L_2``
while [[1,2],[1,2]] represents ``1*L_0(x)*L_0(y) + 1*L_1(x)*L_0(y) +
2*L_0(x)*L_1(y) + 2*L_1(x)*L_1(y)`` if axis=0 is ``x`` and axis=1 is
``y``.
Parameters
----------
c : array_like
Array of Laguerre series coefficients. If `c` is multidimensional
the different axis correspond to different variables with the
degree in each axis given by the corresponding index.
m : int, optional
Number of derivatives taken, must be non-negative. (Default: 1)
scl : scalar, optional
Each differentiation is multiplied by `scl`. The end result is
multiplication by ``scl**m``. This is for use in a linear change of
variable. (Default: 1)
axis : int, optional
Axis over which the derivative is taken. (Default: 0).
.. versionadded:: 1.7.0
Returns
-------
der : ndarray
Laguerre series of the derivative.
See Also
--------
lagint
Notes
-----
In general, the result of differentiating a Laguerre series does not
resemble the same operation on a power series. Thus the result of this
function may be "unintuitive," albeit correct; see Examples section
below.
Examples
--------
>>> from numpy.polynomial.laguerre import lagder
>>> lagder([ 1., 1., 1., -3.])
array([ 1., 2., 3.])
>>> lagder([ 1., 0., 0., -4., 3.], m=2)
array([ 1., 2., 3.]) | Differentiate a Laguerre series. | [
"Differentiate",
"a",
"Laguerre",
"series",
"."
] | def lagder(c, m=1, scl=1, axis=0) :
"""
Differentiate a Laguerre series.
Returns the Laguerre series coefficients `c` differentiated `m` times
along `axis`. At each iteration the result is multiplied by `scl` (the
scaling factor is for use in a linear change of variable). The argument
`c` is an array of coefficients from low to high degree along each
axis, e.g., [1,2,3] represents the series ``1*L_0 + 2*L_1 + 3*L_2``
while [[1,2],[1,2]] represents ``1*L_0(x)*L_0(y) + 1*L_1(x)*L_0(y) +
2*L_0(x)*L_1(y) + 2*L_1(x)*L_1(y)`` if axis=0 is ``x`` and axis=1 is
``y``.
Parameters
----------
c : array_like
Array of Laguerre series coefficients. If `c` is multidimensional
the different axis correspond to different variables with the
degree in each axis given by the corresponding index.
m : int, optional
Number of derivatives taken, must be non-negative. (Default: 1)
scl : scalar, optional
Each differentiation is multiplied by `scl`. The end result is
multiplication by ``scl**m``. This is for use in a linear change of
variable. (Default: 1)
axis : int, optional
Axis over which the derivative is taken. (Default: 0).
.. versionadded:: 1.7.0
Returns
-------
der : ndarray
Laguerre series of the derivative.
See Also
--------
lagint
Notes
-----
In general, the result of differentiating a Laguerre series does not
resemble the same operation on a power series. Thus the result of this
function may be "unintuitive," albeit correct; see Examples section
below.
Examples
--------
>>> from numpy.polynomial.laguerre import lagder
>>> lagder([ 1., 1., 1., -3.])
array([ 1., 2., 3.])
>>> lagder([ 1., 0., 0., -4., 3.], m=2)
array([ 1., 2., 3.])
"""
c = np.array(c, ndmin=1, copy=1)
if c.dtype.char in '?bBhHiIlLqQpP':
c = c.astype(np.double)
cnt, iaxis = [int(t) for t in [m, axis]]
if cnt != m:
raise ValueError("The order of derivation must be integer")
if cnt < 0:
raise ValueError("The order of derivation must be non-negative")
if iaxis != axis:
raise ValueError("The axis must be integer")
if not -c.ndim <= iaxis < c.ndim:
raise ValueError("The axis is out of range")
if iaxis < 0:
iaxis += c.ndim
if cnt == 0:
return c
c = np.rollaxis(c, iaxis)
n = len(c)
if cnt >= n:
c = c[:1]*0
else :
for i in range(cnt):
n = n - 1
c *= scl
der = np.empty((n,) + c.shape[1:], dtype=c.dtype)
for j in range(n, 1, -1):
der[j - 1] = -c[j]
c[j - 1] += c[j]
der[0] = -c[1]
c = der
c = np.rollaxis(c, 0, iaxis + 1)
return c | [
"def",
"lagder",
"(",
"c",
",",
"m",
"=",
"1",
",",
"scl",
"=",
"1",
",",
"axis",
"=",
"0",
")",
":",
"c",
"=",
"np",
".",
"array",
"(",
"c",
",",
"ndmin",
"=",
"1",
",",
"copy",
"=",
"1",
")",
"if",
"c",
".",
"dtype",
".",
"char",
"in"... | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/polynomial/laguerre.py#L632-L721 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | contrib/gizmos/osx_cocoa/gizmos.py | python | LEDNumberCtrl.SetAlignment | (*args, **kwargs) | return _gizmos.LEDNumberCtrl_SetAlignment(*args, **kwargs) | SetAlignment(self, int Alignment, bool Redraw=True) | SetAlignment(self, int Alignment, bool Redraw=True) | [
"SetAlignment",
"(",
"self",
"int",
"Alignment",
"bool",
"Redraw",
"=",
"True",
")"
] | def SetAlignment(*args, **kwargs):
"""SetAlignment(self, int Alignment, bool Redraw=True)"""
return _gizmos.LEDNumberCtrl_SetAlignment(*args, **kwargs) | [
"def",
"SetAlignment",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gizmos",
".",
"LEDNumberCtrl_SetAlignment",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/osx_cocoa/gizmos.py#L338-L340 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/core/fromnumeric.py | python | nonzero | (a) | return _wrapfunc(a, 'nonzero') | Return the indices of the elements that are non-zero.
Returns a tuple of arrays, one for each dimension of `a`,
containing the indices of the non-zero elements in that
dimension. The values in `a` are always tested and returned in
row-major, C-style order.
To group the indices by element, rather than dimension, use `argwhere`,
which returns a row for each non-zero element.
.. note::
When called on a zero-d array or scalar, ``nonzero(a)`` is treated
as ``nonzero(atleast1d(a))``.
.. deprecated:: 1.17.0
Use `atleast1d` explicitly if this behavior is deliberate.
Parameters
----------
a : array_like
Input array.
Returns
-------
tuple_of_arrays : tuple
Indices of elements that are non-zero.
See Also
--------
flatnonzero :
Return indices that are non-zero in the flattened version of the input
array.
ndarray.nonzero :
Equivalent ndarray method.
count_nonzero :
Counts the number of non-zero elements in the input array.
Notes
-----
While the nonzero values can be obtained with ``a[nonzero(a)]``, it is
recommended to use ``x[x.astype(bool)]`` or ``x[x != 0]`` instead, which
will correctly handle 0-d arrays.
Examples
--------
>>> x = np.array([[3, 0, 0], [0, 4, 0], [5, 6, 0]])
>>> x
array([[3, 0, 0],
[0, 4, 0],
[5, 6, 0]])
>>> np.nonzero(x)
(array([0, 1, 2, 2]), array([0, 1, 0, 1]))
>>> x[np.nonzero(x)]
array([3, 4, 5, 6])
>>> np.transpose(np.nonzero(x))
array([[0, 0],
[1, 1],
[2, 0],
[2, 1]])
A common use for ``nonzero`` is to find the indices of an array, where
a condition is True. Given an array `a`, the condition `a` > 3 is a
boolean array and since False is interpreted as 0, np.nonzero(a > 3)
yields the indices of the `a` where the condition is true.
>>> a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> a > 3
array([[False, False, False],
[ True, True, True],
[ True, True, True]])
>>> np.nonzero(a > 3)
(array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
Using this result to index `a` is equivalent to using the mask directly:
>>> a[np.nonzero(a > 3)]
array([4, 5, 6, 7, 8, 9])
>>> a[a > 3] # prefer this spelling
array([4, 5, 6, 7, 8, 9])
``nonzero`` can also be called as a method of the array.
>>> (a > 3).nonzero()
(array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2])) | Return the indices of the elements that are non-zero. | [
"Return",
"the",
"indices",
"of",
"the",
"elements",
"that",
"are",
"non",
"-",
"zero",
"."
] | def nonzero(a):
"""
Return the indices of the elements that are non-zero.
Returns a tuple of arrays, one for each dimension of `a`,
containing the indices of the non-zero elements in that
dimension. The values in `a` are always tested and returned in
row-major, C-style order.
To group the indices by element, rather than dimension, use `argwhere`,
which returns a row for each non-zero element.
.. note::
When called on a zero-d array or scalar, ``nonzero(a)`` is treated
as ``nonzero(atleast1d(a))``.
.. deprecated:: 1.17.0
Use `atleast1d` explicitly if this behavior is deliberate.
Parameters
----------
a : array_like
Input array.
Returns
-------
tuple_of_arrays : tuple
Indices of elements that are non-zero.
See Also
--------
flatnonzero :
Return indices that are non-zero in the flattened version of the input
array.
ndarray.nonzero :
Equivalent ndarray method.
count_nonzero :
Counts the number of non-zero elements in the input array.
Notes
-----
While the nonzero values can be obtained with ``a[nonzero(a)]``, it is
recommended to use ``x[x.astype(bool)]`` or ``x[x != 0]`` instead, which
will correctly handle 0-d arrays.
Examples
--------
>>> x = np.array([[3, 0, 0], [0, 4, 0], [5, 6, 0]])
>>> x
array([[3, 0, 0],
[0, 4, 0],
[5, 6, 0]])
>>> np.nonzero(x)
(array([0, 1, 2, 2]), array([0, 1, 0, 1]))
>>> x[np.nonzero(x)]
array([3, 4, 5, 6])
>>> np.transpose(np.nonzero(x))
array([[0, 0],
[1, 1],
[2, 0],
[2, 1]])
A common use for ``nonzero`` is to find the indices of an array, where
a condition is True. Given an array `a`, the condition `a` > 3 is a
boolean array and since False is interpreted as 0, np.nonzero(a > 3)
yields the indices of the `a` where the condition is true.
>>> a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> a > 3
array([[False, False, False],
[ True, True, True],
[ True, True, True]])
>>> np.nonzero(a > 3)
(array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
Using this result to index `a` is equivalent to using the mask directly:
>>> a[np.nonzero(a > 3)]
array([4, 5, 6, 7, 8, 9])
>>> a[a > 3] # prefer this spelling
array([4, 5, 6, 7, 8, 9])
``nonzero`` can also be called as a method of the array.
>>> (a > 3).nonzero()
(array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
"""
return _wrapfunc(a, 'nonzero') | [
"def",
"nonzero",
"(",
"a",
")",
":",
"return",
"_wrapfunc",
"(",
"a",
",",
"'nonzero'",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/core/fromnumeric.py#L1805-L1896 | |
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | python/mozbuild/mozbuild/controller/building.py | python | TierStatus.tiered_resource_usage | (self) | return o | Obtains an object containing resource usage for tiers.
The returned object is suitable for serialization. | Obtains an object containing resource usage for tiers. | [
"Obtains",
"an",
"object",
"containing",
"resource",
"usage",
"for",
"tiers",
"."
] | def tiered_resource_usage(self):
"""Obtains an object containing resource usage for tiers.
The returned object is suitable for serialization.
"""
o = []
for tier, state in self.tiers.items():
t_entry = dict(
name=tier,
start=state['begin_time'],
end=state['finish_time'],
duration=state['duration'],
)
self.add_resources_to_dict(t_entry, phase=tier)
o.append(t_entry)
return o | [
"def",
"tiered_resource_usage",
"(",
"self",
")",
":",
"o",
"=",
"[",
"]",
"for",
"tier",
",",
"state",
"in",
"self",
".",
"tiers",
".",
"items",
"(",
")",
":",
"t_entry",
"=",
"dict",
"(",
"name",
"=",
"tier",
",",
"start",
"=",
"state",
"[",
"'... | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/mozbuild/mozbuild/controller/building.py#L105-L124 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/platform/benchmark.py | python | _global_report_benchmark | (
name, iters=None, cpu_time=None, wall_time=None,
throughput=None, extras=None) | Method for recording a benchmark directly.
Args:
name: The BenchmarkEntry name.
iters: (optional) How many iterations were run
cpu_time: (optional) Total cpu time in seconds
wall_time: (optional) Total wall time in seconds
throughput: (optional) Throughput (in MB/s)
extras: (optional) Dict mapping string keys to additional benchmark info.
Raises:
TypeError: if extras is not a dict.
IOError: if the benchmark output file already exists. | Method for recording a benchmark directly. | [
"Method",
"for",
"recording",
"a",
"benchmark",
"directly",
"."
] | def _global_report_benchmark(
name, iters=None, cpu_time=None, wall_time=None,
throughput=None, extras=None):
"""Method for recording a benchmark directly.
Args:
name: The BenchmarkEntry name.
iters: (optional) How many iterations were run
cpu_time: (optional) Total cpu time in seconds
wall_time: (optional) Total wall time in seconds
throughput: (optional) Throughput (in MB/s)
extras: (optional) Dict mapping string keys to additional benchmark info.
Raises:
TypeError: if extras is not a dict.
IOError: if the benchmark output file already exists.
"""
if extras is not None:
if not isinstance(extras, dict):
raise TypeError("extras must be a dict")
logging.info("Benchmark [%s] iters: %d, wall_time: %g, cpu_time: %g,"
"throughput: %g %s", name, iters if iters is not None else -1,
wall_time if wall_time is not None else -1, cpu_time if
cpu_time is not None else -1, throughput if
throughput is not None else -1, str(extras) if extras else "")
entries = test_log_pb2.BenchmarkEntries()
entry = entries.entry.add()
entry.name = name
if iters is not None:
entry.iters = iters
if cpu_time is not None:
entry.cpu_time = cpu_time
if wall_time is not None:
entry.wall_time = wall_time
if throughput is not None:
entry.throughput = throughput
if extras is not None:
for (k, v) in extras.items():
if isinstance(v, numbers.Number):
entry.extras[k].double_value = v
else:
entry.extras[k].string_value = str(v)
test_env = os.environ.get(TEST_REPORTER_TEST_ENV, None)
if test_env is None:
# Reporting was not requested, just print the proto
print(str(entries))
return
serialized_entry = entries.SerializeToString()
mangled_name = name.replace("/", "__")
output_path = "%s%s" % (test_env, mangled_name)
if gfile.Exists(output_path):
raise IOError("File already exists: %s" % output_path)
with gfile.GFile(output_path, "wb") as out:
out.write(serialized_entry) | [
"def",
"_global_report_benchmark",
"(",
"name",
",",
"iters",
"=",
"None",
",",
"cpu_time",
"=",
"None",
",",
"wall_time",
"=",
"None",
",",
"throughput",
"=",
"None",
",",
"extras",
"=",
"None",
")",
":",
"if",
"extras",
"is",
"not",
"None",
":",
"if"... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/platform/benchmark.py#L49-L107 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py | python | Listbox.activate | (self, index) | Activate item identified by INDEX. | Activate item identified by INDEX. | [
"Activate",
"item",
"identified",
"by",
"INDEX",
"."
] | def activate(self, index):
"""Activate item identified by INDEX."""
self.tk.call(self._w, 'activate', index) | [
"def",
"activate",
"(",
"self",
",",
"index",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"'activate'",
",",
"index",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py#L2550-L2552 | ||
Slicer/Slicer | ba9fadf332cb0303515b68d8d06a344c82e3e3e5 | Utilities/Scripts/SlicerWizard/GithubHelper.py | python | logIn | (repo=None) | return session | Create github session.
:param repo:
If not ``None``, use the git client (i.e. configuration) from the specified
git repository; otherwise use a default client.
:type repo:
:class:`git.Repo <git:git.repo.base.Repo>` or ``None``.
:returns: A logged in github session.
:rtype: :class:`github.Github <github:github.MainClass.Github>`.
:raises:
:class:`github:github.GithubException.BadCredentialsException` if
authentication fails.
This obtains and returns a logged in github session using the user's
credentials, as managed by `git-credentials`_; login information is obtained
as necessary via the same. On success, the credentials are also saved to any
store that the user has configured.
If `GITHUB_TOKEN` environment variable is set, its value will be used
as password when invoking `git-credentials`_.
.. _git-credentials: http://git-scm.com/docs/gitcredentials.html | Create github session. | [
"Create",
"github",
"session",
"."
] | def logIn(repo=None):
"""Create github session.
:param repo:
If not ``None``, use the git client (i.e. configuration) from the specified
git repository; otherwise use a default client.
:type repo:
:class:`git.Repo <git:git.repo.base.Repo>` or ``None``.
:returns: A logged in github session.
:rtype: :class:`github.Github <github:github.MainClass.Github>`.
:raises:
:class:`github:github.GithubException.BadCredentialsException` if
authentication fails.
This obtains and returns a logged in github session using the user's
credentials, as managed by `git-credentials`_; login information is obtained
as necessary via the same. On success, the credentials are also saved to any
store that the user has configured.
If `GITHUB_TOKEN` environment variable is set, its value will be used
as password when invoking `git-credentials`_.
.. _git-credentials: http://git-scm.com/docs/gitcredentials.html
"""
# Get client; use generic client if no repository
client = repo.git if repo is not None else git.cmd.Git()
# Request login credentials
github_token = {}
if "GITHUB_TOKEN" in os.environ:
github_token = {"password": os.environ["GITHUB_TOKEN"]}
credRequest = _CredentialToken(protocol="https", host="github.com", **github_token)
cred = _credentials(client, credRequest)
# Log in
session = Github(cred.username, cred.password)
# Try to get the logged in user name; will raise an exception if
# authentication failed
if session.get_user().login:
# Save the credentials
_credentials(client, cred, action="approve")
# Return github session
return session | [
"def",
"logIn",
"(",
"repo",
"=",
"None",
")",
":",
"# Get client; use generic client if no repository",
"client",
"=",
"repo",
".",
"git",
"if",
"repo",
"is",
"not",
"None",
"else",
"git",
".",
"cmd",
".",
"Git",
"(",
")",
"# Request login credentials",
"gith... | https://github.com/Slicer/Slicer/blob/ba9fadf332cb0303515b68d8d06a344c82e3e3e5/Utilities/Scripts/SlicerWizard/GithubHelper.py#L58-L106 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py2/numpy/linalg/linalg.py | python | tensorsolve | (a, b, axes=None) | return res | Solve the tensor equation ``a x = b`` for x.
It is assumed that all indices of `x` are summed over in the product,
together with the rightmost indices of `a`, as is done in, for example,
``tensordot(a, x, axes=b.ndim)``.
Parameters
----------
a : array_like
Coefficient tensor, of shape ``b.shape + Q``. `Q`, a tuple, equals
the shape of that sub-tensor of `a` consisting of the appropriate
number of its rightmost indices, and must be such that
``prod(Q) == prod(b.shape)`` (in which sense `a` is said to be
'square').
b : array_like
Right-hand tensor, which can be of any shape.
axes : tuple of ints, optional
Axes in `a` to reorder to the right, before inversion.
If None (default), no reordering is done.
Returns
-------
x : ndarray, shape Q
Raises
------
LinAlgError
If `a` is singular or not 'square' (in the above sense).
See Also
--------
numpy.tensordot, tensorinv, numpy.einsum
Examples
--------
>>> a = np.eye(2*3*4)
>>> a.shape = (2*3, 4, 2, 3, 4)
>>> b = np.random.randn(2*3, 4)
>>> x = np.linalg.tensorsolve(a, b)
>>> x.shape
(2, 3, 4)
>>> np.allclose(np.tensordot(a, x, axes=3), b)
True | Solve the tensor equation ``a x = b`` for x. | [
"Solve",
"the",
"tensor",
"equation",
"a",
"x",
"=",
"b",
"for",
"x",
"."
] | def tensorsolve(a, b, axes=None):
"""
Solve the tensor equation ``a x = b`` for x.
It is assumed that all indices of `x` are summed over in the product,
together with the rightmost indices of `a`, as is done in, for example,
``tensordot(a, x, axes=b.ndim)``.
Parameters
----------
a : array_like
Coefficient tensor, of shape ``b.shape + Q``. `Q`, a tuple, equals
the shape of that sub-tensor of `a` consisting of the appropriate
number of its rightmost indices, and must be such that
``prod(Q) == prod(b.shape)`` (in which sense `a` is said to be
'square').
b : array_like
Right-hand tensor, which can be of any shape.
axes : tuple of ints, optional
Axes in `a` to reorder to the right, before inversion.
If None (default), no reordering is done.
Returns
-------
x : ndarray, shape Q
Raises
------
LinAlgError
If `a` is singular or not 'square' (in the above sense).
See Also
--------
numpy.tensordot, tensorinv, numpy.einsum
Examples
--------
>>> a = np.eye(2*3*4)
>>> a.shape = (2*3, 4, 2, 3, 4)
>>> b = np.random.randn(2*3, 4)
>>> x = np.linalg.tensorsolve(a, b)
>>> x.shape
(2, 3, 4)
>>> np.allclose(np.tensordot(a, x, axes=3), b)
True
"""
a, wrap = _makearray(a)
b = asarray(b)
an = a.ndim
if axes is not None:
allaxes = list(range(0, an))
for k in axes:
allaxes.remove(k)
allaxes.insert(an, k)
a = a.transpose(allaxes)
oldshape = a.shape[-(an-b.ndim):]
prod = 1
for k in oldshape:
prod *= k
a = a.reshape(-1, prod)
b = b.ravel()
res = wrap(solve(a, b))
res.shape = oldshape
return res | [
"def",
"tensorsolve",
"(",
"a",
",",
"b",
",",
"axes",
"=",
"None",
")",
":",
"a",
",",
"wrap",
"=",
"_makearray",
"(",
"a",
")",
"b",
"=",
"asarray",
"(",
"b",
")",
"an",
"=",
"a",
".",
"ndim",
"if",
"axes",
"is",
"not",
"None",
":",
"allaxe... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/linalg/linalg.py#L253-L320 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/requests/utils.py | python | get_auth_from_url | (url) | return auth | Given a url with authentication components, extract them into a tuple of
username,password.
:rtype: (str,str) | Given a url with authentication components, extract them into a tuple of | [
"Given",
"a",
"url",
"with",
"authentication",
"components",
"extract",
"them",
"into",
"a",
"tuple",
"of"
] | def get_auth_from_url(url):
"""Given a url with authentication components, extract them into a tuple of
username,password.
:rtype: (str,str)
"""
parsed = urlparse(url)
try:
auth = (unquote(parsed.username), unquote(parsed.password))
except (AttributeError, TypeError):
auth = ('', '')
return auth | [
"def",
"get_auth_from_url",
"(",
"url",
")",
":",
"parsed",
"=",
"urlparse",
"(",
"url",
")",
"try",
":",
"auth",
"=",
"(",
"unquote",
"(",
"parsed",
".",
"username",
")",
",",
"unquote",
"(",
"parsed",
".",
"password",
")",
")",
"except",
"(",
"Attr... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/requests/utils.py#L1841-L1867 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py | python | xpathParserContext.xpathStartsWithFunction | (self, nargs) | Implement the starts-with() XPath function boolean
starts-with(string, string) The starts-with function
returns true if the first argument string starts with the
second argument string, and otherwise returns false. | Implement the starts-with() XPath function boolean
starts-with(string, string) The starts-with function
returns true if the first argument string starts with the
second argument string, and otherwise returns false. | [
"Implement",
"the",
"starts",
"-",
"with",
"()",
"XPath",
"function",
"boolean",
"starts",
"-",
"with",
"(",
"string",
"string",
")",
"The",
"starts",
"-",
"with",
"function",
"returns",
"true",
"if",
"the",
"first",
"argument",
"string",
"starts",
"with",
... | def xpathStartsWithFunction(self, nargs):
"""Implement the starts-with() XPath function boolean
starts-with(string, string) The starts-with function
returns true if the first argument string starts with the
second argument string, and otherwise returns false. """
libxml2mod.xmlXPathStartsWithFunction(self._o, nargs) | [
"def",
"xpathStartsWithFunction",
"(",
"self",
",",
"nargs",
")",
":",
"libxml2mod",
".",
"xmlXPathStartsWithFunction",
"(",
"self",
".",
"_o",
",",
"nargs",
")"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L7050-L7055 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/propgrid.py | python | PropertyGridInterface.IsPropertyShown | (*args, **kwargs) | return _propgrid.PropertyGridInterface_IsPropertyShown(*args, **kwargs) | IsPropertyShown(self, PGPropArg id) -> bool | IsPropertyShown(self, PGPropArg id) -> bool | [
"IsPropertyShown",
"(",
"self",
"PGPropArg",
"id",
")",
"-",
">",
"bool"
] | def IsPropertyShown(*args, **kwargs):
"""IsPropertyShown(self, PGPropArg id) -> bool"""
return _propgrid.PropertyGridInterface_IsPropertyShown(*args, **kwargs) | [
"def",
"IsPropertyShown",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PropertyGridInterface_IsPropertyShown",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/propgrid.py#L1324-L1326 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/dataset/vision/py_transforms_util.py | python | random_color | (img, degrees) | return ImageEnhance.Color(img).enhance(v) | Adjust the color of the input PIL image by a random degree.
Args:
img (PIL image): Image to be color adjusted.
degrees (sequence): Range of random color adjustment degrees.
It should be in (min, max) format (default=(0.1,1.9)).
Returns:
img (PIL image), Color adjusted image. | Adjust the color of the input PIL image by a random degree. | [
"Adjust",
"the",
"color",
"of",
"the",
"input",
"PIL",
"image",
"by",
"a",
"random",
"degree",
"."
] | def random_color(img, degrees):
"""
Adjust the color of the input PIL image by a random degree.
Args:
img (PIL image): Image to be color adjusted.
degrees (sequence): Range of random color adjustment degrees.
It should be in (min, max) format (default=(0.1,1.9)).
Returns:
img (PIL image), Color adjusted image.
"""
if not is_pil(img):
raise TypeError(augment_error_message.format(type(img)))
v = (degrees[1] - degrees[0]) * random.random() + degrees[0]
return ImageEnhance.Color(img).enhance(v) | [
"def",
"random_color",
"(",
"img",
",",
"degrees",
")",
":",
"if",
"not",
"is_pil",
"(",
"img",
")",
":",
"raise",
"TypeError",
"(",
"augment_error_message",
".",
"format",
"(",
"type",
"(",
"img",
")",
")",
")",
"v",
"=",
"(",
"degrees",
"[",
"1",
... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/dataset/vision/py_transforms_util.py#L1468-L1485 | |
forkineye/ESPixelStick | 22926f1c0d1131f1369fc7cad405689a095ae3cb | dist/bin/pyserial/serial/threaded/__init__.py | python | Packetizer.connection_made | (self, transport) | Store transport | Store transport | [
"Store",
"transport"
] | def connection_made(self, transport):
"""Store transport"""
self.transport = transport | [
"def",
"connection_made",
"(",
"self",
",",
"transport",
")",
":",
"self",
".",
"transport",
"=",
"transport"
] | https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/pyserial/serial/threaded/__init__.py#L51-L53 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/perf_insights/third_party/cloudstorage/api_utils.py | python | _run_until_rpc | () | Eagerly evaluate tasklets until it is blocking on some RPC.
Usually ndb eventloop el isn't run until some code calls future.get_result().
When an async tasklet is called, the tasklet wrapper evaluates the tasklet
code into a generator, enqueues a callback _help_tasklet_along onto
the el.current queue, and returns a future.
_help_tasklet_along, when called by the el, will
get one yielded value from the generator. If the value if another future,
set up a callback _on_future_complete to invoke _help_tasklet_along
when the dependent future fulfills. If the value if a RPC, set up a
callback _on_rpc_complete to invoke _help_tasklet_along when the RPC fulfills.
Thus _help_tasklet_along drills down
the chain of futures until some future is blocked by RPC. El runs
all callbacks and constantly check pending RPC status. | Eagerly evaluate tasklets until it is blocking on some RPC. | [
"Eagerly",
"evaluate",
"tasklets",
"until",
"it",
"is",
"blocking",
"on",
"some",
"RPC",
"."
] | def _run_until_rpc():
"""Eagerly evaluate tasklets until it is blocking on some RPC.
Usually ndb eventloop el isn't run until some code calls future.get_result().
When an async tasklet is called, the tasklet wrapper evaluates the tasklet
code into a generator, enqueues a callback _help_tasklet_along onto
the el.current queue, and returns a future.
_help_tasklet_along, when called by the el, will
get one yielded value from the generator. If the value if another future,
set up a callback _on_future_complete to invoke _help_tasklet_along
when the dependent future fulfills. If the value if a RPC, set up a
callback _on_rpc_complete to invoke _help_tasklet_along when the RPC fulfills.
Thus _help_tasklet_along drills down
the chain of futures until some future is blocked by RPC. El runs
all callbacks and constantly check pending RPC status.
"""
el = eventloop.get_event_loop()
while el.current:
el.run0() | [
"def",
"_run_until_rpc",
"(",
")",
":",
"el",
"=",
"eventloop",
".",
"get_event_loop",
"(",
")",
"while",
"el",
".",
"current",
":",
"el",
".",
"run0",
"(",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/perf_insights/third_party/cloudstorage/api_utils.py#L321-L341 | ||
timi-liuliang/echo | 40a5a24d430eee4118314459ab7e03afcb3b8719 | thirdparty/protobuf/python/google/protobuf/message_factory.py | python | GetMessages | (file_protos) | return _FACTORY.GetMessages([file_proto.name for file_proto in file_protos]) | Builds a dictionary of all the messages available in a set of files.
Args:
file_protos: A sequence of file protos to build messages out of.
Returns:
A dictionary mapping proto names to the message classes. This will include
any dependent messages as well as any messages defined in the same file as
a specified message. | Builds a dictionary of all the messages available in a set of files. | [
"Builds",
"a",
"dictionary",
"of",
"all",
"the",
"messages",
"available",
"in",
"a",
"set",
"of",
"files",
"."
] | def GetMessages(file_protos):
"""Builds a dictionary of all the messages available in a set of files.
Args:
file_protos: A sequence of file protos to build messages out of.
Returns:
A dictionary mapping proto names to the message classes. This will include
any dependent messages as well as any messages defined in the same file as
a specified message.
"""
for file_proto in file_protos:
_FACTORY.pool.Add(file_proto)
return _FACTORY.GetMessages([file_proto.name for file_proto in file_protos]) | [
"def",
"GetMessages",
"(",
"file_protos",
")",
":",
"for",
"file_proto",
"in",
"file_protos",
":",
"_FACTORY",
".",
"pool",
".",
"Add",
"(",
"file_proto",
")",
"return",
"_FACTORY",
".",
"GetMessages",
"(",
"[",
"file_proto",
".",
"name",
"for",
"file_proto"... | https://github.com/timi-liuliang/echo/blob/40a5a24d430eee4118314459ab7e03afcb3b8719/thirdparty/protobuf/python/google/protobuf/message_factory.py#L142-L155 | |
polyworld/polyworld | eb7e6bbc82fe77ba79e3bc48c3da2ad8c8238c26 | scripts/agent/genome.py | python | Genome.genome | (self) | return g | Lazy loading of genome | Lazy loading of genome | [
"Lazy",
"loading",
"of",
"genome"
] | def genome(self):
""" Lazy loading of genome """
# Open genome, clean lines
f = open(self.filename)
g = array(map(int, f.readlines()), dtype='u1')
f.close()
# Sanity check on genome
assert 0 <= g.all() <= 255, "genes outside range [0,255]"
return g | [
"def",
"genome",
"(",
"self",
")",
":",
"# Open genome, clean lines",
"f",
"=",
"open",
"(",
"self",
".",
"filename",
")",
"g",
"=",
"array",
"(",
"map",
"(",
"int",
",",
"f",
".",
"readlines",
"(",
")",
")",
",",
"dtype",
"=",
"'u1'",
")",
"f",
... | https://github.com/polyworld/polyworld/blob/eb7e6bbc82fe77ba79e3bc48c3da2ad8c8238c26/scripts/agent/genome.py#L19-L30 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/propgrid.py | python | PGCell.GetBitmap | (*args, **kwargs) | return _propgrid.PGCell_GetBitmap(*args, **kwargs) | GetBitmap(self) -> Bitmap | GetBitmap(self) -> Bitmap | [
"GetBitmap",
"(",
"self",
")",
"-",
">",
"Bitmap"
] | def GetBitmap(*args, **kwargs):
"""GetBitmap(self) -> Bitmap"""
return _propgrid.PGCell_GetBitmap(*args, **kwargs) | [
"def",
"GetBitmap",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PGCell_GetBitmap",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L175-L177 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/xml/sax/xmlreader.py | python | XMLReader.setErrorHandler | (self, handler) | Register an object to receive error-message events. | Register an object to receive error-message events. | [
"Register",
"an",
"object",
"to",
"receive",
"error",
"-",
"message",
"events",
"."
] | def setErrorHandler(self, handler):
"Register an object to receive error-message events."
self._err_handler = handler | [
"def",
"setErrorHandler",
"(",
"self",
",",
"handler",
")",
":",
"self",
".",
"_err_handler",
"=",
"handler"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/xml/sax/xmlreader.py#L62-L64 | ||
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/peacock/Input/ParamsTable.py | python | ParamsTable.updateSizes | (self) | Update the sizes of the header. | Update the sizes of the header. | [
"Update",
"the",
"sizes",
"of",
"the",
"header",
"."
] | def updateSizes(self):
"""
Update the sizes of the header.
"""
header = self.horizontalHeader()
header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
header.setSectionResizeMode(3, QtWidgets.QHeaderView.Stretch) | [
"def",
"updateSizes",
"(",
"self",
")",
":",
"header",
"=",
"self",
".",
"horizontalHeader",
"(",
")",
"header",
".",
"setSectionResizeMode",
"(",
"0",
",",
"QtWidgets",
".",
"QHeaderView",
".",
"ResizeToContents",
")",
"header",
".",
"setSectionResizeMode",
"... | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/Input/ParamsTable.py#L248-L256 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/s3transfer/utils.py | python | invoke_progress_callbacks | (callbacks, bytes_transferred) | Calls all progress callbacks
:param callbacks: A list of progress callbacks to invoke
:param bytes_transferred: The number of bytes transferred. This is passed
to the callbacks. If no bytes were transferred the callbacks will not
be invoked because no progress was achieved. It is also possible
to receive a negative amount which comes from retrying a transfer
request. | Calls all progress callbacks | [
"Calls",
"all",
"progress",
"callbacks"
] | def invoke_progress_callbacks(callbacks, bytes_transferred):
"""Calls all progress callbacks
:param callbacks: A list of progress callbacks to invoke
:param bytes_transferred: The number of bytes transferred. This is passed
to the callbacks. If no bytes were transferred the callbacks will not
be invoked because no progress was achieved. It is also possible
to receive a negative amount which comes from retrying a transfer
request.
"""
# Only invoke the callbacks if bytes were actually transferred.
if bytes_transferred:
for callback in callbacks:
callback(bytes_transferred=bytes_transferred) | [
"def",
"invoke_progress_callbacks",
"(",
"callbacks",
",",
"bytes_transferred",
")",
":",
"# Only invoke the callbacks if bytes were actually transferred.",
"if",
"bytes_transferred",
":",
"for",
"callback",
"in",
"callbacks",
":",
"callback",
"(",
"bytes_transferred",
"=",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/s3transfer/utils.py#L128-L141 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/connection.py | python | EC2Connection.get_all_regions | (self, region_names=None, filters=None, dry_run=False) | return regions | Get all available regions for the EC2 service.
:type region_names: list of str
:param region_names: Names of regions to limit output
:type filters: dict
:param filters: Optional filters that can be used to limit
the results returned. Filters are provided
in the form of a dictionary consisting of
filter names as the key and filter values
as the value. The set of allowable filter
names/values is dependent on the request
being performed. Check the EC2 API guide
for details.
:type dry_run: bool
:param dry_run: Set to True if the operation should not actually run.
:rtype: list
:return: A list of :class:`boto.ec2.regioninfo.RegionInfo` | Get all available regions for the EC2 service. | [
"Get",
"all",
"available",
"regions",
"for",
"the",
"EC2",
"service",
"."
] | def get_all_regions(self, region_names=None, filters=None, dry_run=False):
"""
Get all available regions for the EC2 service.
:type region_names: list of str
:param region_names: Names of regions to limit output
:type filters: dict
:param filters: Optional filters that can be used to limit
the results returned. Filters are provided
in the form of a dictionary consisting of
filter names as the key and filter values
as the value. The set of allowable filter
names/values is dependent on the request
being performed. Check the EC2 API guide
for details.
:type dry_run: bool
:param dry_run: Set to True if the operation should not actually run.
:rtype: list
:return: A list of :class:`boto.ec2.regioninfo.RegionInfo`
"""
params = {}
if region_names:
self.build_list_params(params, region_names, 'RegionName')
if filters:
self.build_filter_params(params, filters)
if dry_run:
params['DryRun'] = 'true'
regions = self.get_list('DescribeRegions', params,
[('item', RegionInfo)], verb='POST')
for region in regions:
region.connection_cls = EC2Connection
return regions | [
"def",
"get_all_regions",
"(",
"self",
",",
"region_names",
"=",
"None",
",",
"filters",
"=",
"None",
",",
"dry_run",
"=",
"False",
")",
":",
"params",
"=",
"{",
"}",
"if",
"region_names",
":",
"self",
".",
"build_list_params",
"(",
"params",
",",
"regio... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/connection.py#L3446-L3480 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/exclusive-time-of-functions.py | python | Solution.exclusiveTime | (self, n, logs) | return result | :type n: int
:type logs: List[str]
:rtype: List[int] | :type n: int
:type logs: List[str]
:rtype: List[int] | [
":",
"type",
"n",
":",
"int",
":",
"type",
"logs",
":",
"List",
"[",
"str",
"]",
":",
"rtype",
":",
"List",
"[",
"int",
"]"
] | def exclusiveTime(self, n, logs):
"""
:type n: int
:type logs: List[str]
:rtype: List[int]
"""
result = [0] * n
stk, prev = [], 0
for log in logs:
tokens = log.split(":")
if tokens[1] == "start":
if stk:
result[stk[-1]] += int(tokens[2]) - prev
stk.append(int(tokens[0]))
prev = int(tokens[2])
else:
result[stk.pop()] += int(tokens[2]) - prev + 1
prev = int(tokens[2]) + 1
return result | [
"def",
"exclusiveTime",
"(",
"self",
",",
"n",
",",
"logs",
")",
":",
"result",
"=",
"[",
"0",
"]",
"*",
"n",
"stk",
",",
"prev",
"=",
"[",
"]",
",",
"0",
"for",
"log",
"in",
"logs",
":",
"tokens",
"=",
"log",
".",
"split",
"(",
"\":\"",
")",... | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/exclusive-time-of-functions.py#L5-L23 | |
cathywu/Sentiment-Analysis | eb501fd1375c0c3f3ab430f963255f1bb858e659 | PyML-0.7.9/PyML/utils/misc.py | python | count | (A) | return counts | count the number of occurrences of each element in a list | count the number of occurrences of each element in a list | [
"count",
"the",
"number",
"of",
"occurrences",
"of",
"each",
"element",
"in",
"a",
"list"
] | def count(A) :
'''count the number of occurrences of each element in a list'''
counts = {}
for a in A :
if a in counts :
counts[a] += 1
else :
counts[a] = 1
return counts | [
"def",
"count",
"(",
"A",
")",
":",
"counts",
"=",
"{",
"}",
"for",
"a",
"in",
"A",
":",
"if",
"a",
"in",
"counts",
":",
"counts",
"[",
"a",
"]",
"+=",
"1",
"else",
":",
"counts",
"[",
"a",
"]",
"=",
"1",
"return",
"counts"
] | https://github.com/cathywu/Sentiment-Analysis/blob/eb501fd1375c0c3f3ab430f963255f1bb858e659/PyML-0.7.9/PyML/utils/misc.py#L371-L382 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/email/quoprimime.py | python | header_decode | (s) | return re.sub(r'=[a-fA-F0-9]{2}', _unquote_match, s, flags=re.ASCII) | Decode a string encoded with RFC 2045 MIME header `Q' encoding.
This function does not parse a full MIME header value encoded with
quoted-printable (like =?iso-8859-1?q?Hello_World?=) -- please use
the high level email.header class for that functionality. | Decode a string encoded with RFC 2045 MIME header `Q' encoding. | [
"Decode",
"a",
"string",
"encoded",
"with",
"RFC",
"2045",
"MIME",
"header",
"Q",
"encoding",
"."
] | def header_decode(s):
"""Decode a string encoded with RFC 2045 MIME header `Q' encoding.
This function does not parse a full MIME header value encoded with
quoted-printable (like =?iso-8859-1?q?Hello_World?=) -- please use
the high level email.header class for that functionality.
"""
s = s.replace('_', ' ')
return re.sub(r'=[a-fA-F0-9]{2}', _unquote_match, s, flags=re.ASCII) | [
"def",
"header_decode",
"(",
"s",
")",
":",
"s",
"=",
"s",
".",
"replace",
"(",
"'_'",
",",
"' '",
")",
"return",
"re",
".",
"sub",
"(",
"r'=[a-fA-F0-9]{2}'",
",",
"_unquote_match",
",",
"s",
",",
"flags",
"=",
"re",
".",
"ASCII",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/email/quoprimime.py#L291-L299 | |
CalcProgrammer1/OpenRGB | 8156b0167a7590dd8ba561dfde524bfcacf46b5e | dependencies/mbedtls-2.24.0/scripts/assemble_changelog.py | python | TextChangelogFormat.split_categories | (cls, version_body) | return [CategoryContent(title_match.group(1), title_line,
body, body_line)
for title_match, title_line, body, body_line
in zip(title_matches, title_lines, bodies, body_lines)] | A category title is a line with the title in column 0. | A category title is a line with the title in column 0. | [
"A",
"category",
"title",
"is",
"a",
"line",
"with",
"the",
"title",
"in",
"column",
"0",
"."
] | def split_categories(cls, version_body):
"""A category title is a line with the title in column 0."""
if not version_body:
return []
title_matches = list(re.finditer(cls._category_title_re, version_body))
if not title_matches or title_matches[0].start() != 0:
# There is junk before the first category.
raise CategoryParseError(0, 'Junk found where category expected')
title_starts = [m.start(1) for m in title_matches]
body_starts = [m.end(0) for m in title_matches]
body_ends = title_starts[1:] + [len(version_body)]
bodies = [version_body[body_start:body_end].rstrip(b'\n') + b'\n'
for (body_start, body_end) in zip(body_starts, body_ends)]
title_lines = [version_body[:pos].count(b'\n') for pos in title_starts]
body_lines = [version_body[:pos].count(b'\n') for pos in body_starts]
return [CategoryContent(title_match.group(1), title_line,
body, body_line)
for title_match, title_line, body, body_line
in zip(title_matches, title_lines, bodies, body_lines)] | [
"def",
"split_categories",
"(",
"cls",
",",
"version_body",
")",
":",
"if",
"not",
"version_body",
":",
"return",
"[",
"]",
"title_matches",
"=",
"list",
"(",
"re",
".",
"finditer",
"(",
"cls",
".",
"_category_title_re",
",",
"version_body",
")",
")",
"if"... | https://github.com/CalcProgrammer1/OpenRGB/blob/8156b0167a7590dd8ba561dfde524bfcacf46b5e/dependencies/mbedtls-2.24.0/scripts/assemble_changelog.py#L152-L170 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/ultimatelistctrl.py | python | UltimateListItemData.SetKind | (self, kind) | Sets the item kind.
:param `kind`: may be one of the following integers:
=============== ==========================
Item Kind Description
=============== ==========================
0 A normal item
1 A checkbox-like item
2 A radiobutton-type item
=============== ========================== | Sets the item kind. | [
"Sets",
"the",
"item",
"kind",
"."
] | def SetKind(self, kind):
"""
Sets the item kind.
:param `kind`: may be one of the following integers:
=============== ==========================
Item Kind Description
=============== ==========================
0 A normal item
1 A checkbox-like item
2 A radiobutton-type item
=============== ==========================
"""
self._kind = kind | [
"def",
"SetKind",
"(",
"self",
",",
"kind",
")",
":",
"self",
".",
"_kind",
"=",
"kind"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L2713-L2729 | ||
koth/kcws | 88efbd36a7022de4e6e90f5a1fb880cf87cfae9f | third_party/setuptools/pkg_resources.py | python | Environment.can_add | (self, dist) | return (self.python is None or dist.py_version is None
or dist.py_version==self.python) \
and compatible_platforms(dist.platform, self.platform) | Is distribution `dist` acceptable for this environment?
The distribution must match the platform and python version
requirements specified when this environment was created, or False
is returned. | Is distribution `dist` acceptable for this environment? | [
"Is",
"distribution",
"dist",
"acceptable",
"for",
"this",
"environment?"
] | def can_add(self, dist):
"""Is distribution `dist` acceptable for this environment?
The distribution must match the platform and python version
requirements specified when this environment was created, or False
is returned.
"""
return (self.python is None or dist.py_version is None
or dist.py_version==self.python) \
and compatible_platforms(dist.platform, self.platform) | [
"def",
"can_add",
"(",
"self",
",",
"dist",
")",
":",
"return",
"(",
"self",
".",
"python",
"is",
"None",
"or",
"dist",
".",
"py_version",
"is",
"None",
"or",
"dist",
".",
"py_version",
"==",
"self",
".",
"python",
")",
"and",
"compatible_platforms",
"... | https://github.com/koth/kcws/blob/88efbd36a7022de4e6e90f5a1fb880cf87cfae9f/third_party/setuptools/pkg_resources.py#L801-L810 | |
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | qa/tasks/osd_backfill.py | python | task | (ctx, config) | Test backfill | Test backfill | [
"Test",
"backfill"
] | def task(ctx, config):
"""
Test backfill
"""
if config is None:
config = {}
assert isinstance(config, dict), \
'thrashosds task only accepts a dict for configuration'
first_mon = teuthology.get_first_mon(ctx, config)
(mon,) = ctx.cluster.only(first_mon).remotes.keys()
num_osds = teuthology.num_instances_of_type(ctx.cluster, 'osd')
log.info('num_osds is %s' % num_osds)
assert num_osds == 3
manager = ceph_manager.CephManager(
mon,
ctx=ctx,
logger=log.getChild('ceph_manager'),
)
while len(manager.get_osd_status()['up']) < 3:
time.sleep(10)
manager.flush_pg_stats([0, 1, 2])
manager.wait_for_clean()
# write some data
p = rados_start(ctx, mon, ['-p', 'rbd', 'bench', '15', 'write', '-b', '4096',
'--no-cleanup'])
err = p.wait()
log.info('err is %d' % err)
# mark osd.0 out to trigger a rebalance/backfill
manager.mark_out_osd(0)
# also mark it down to it won't be included in pg_temps
manager.kill_osd(0)
manager.mark_down_osd(0)
# wait for everything to peer and be happy...
manager.flush_pg_stats([1, 2])
manager.wait_for_recovery()
# write some new data
p = rados_start(ctx, mon, ['-p', 'rbd', 'bench', '30', 'write', '-b', '4096',
'--no-cleanup'])
time.sleep(15)
# blackhole + restart osd.1
# this triggers a divergent backfill target
manager.blackhole_kill_osd(1)
time.sleep(2)
manager.revive_osd(1)
# wait for our writes to complete + succeed
err = p.wait()
log.info('err is %d' % err)
# wait for osd.1 and osd.2 to be up
manager.wait_till_osd_is_up(1)
manager.wait_till_osd_is_up(2)
# cluster must recover
manager.flush_pg_stats([1, 2])
manager.wait_for_recovery()
# re-add osd.0
manager.revive_osd(0)
manager.flush_pg_stats([1, 2])
manager.wait_for_clean() | [
"def",
"task",
"(",
"ctx",
",",
"config",
")",
":",
"if",
"config",
"is",
"None",
":",
"config",
"=",
"{",
"}",
"assert",
"isinstance",
"(",
"config",
",",
"dict",
")",
",",
"'thrashosds task only accepts a dict for configuration'",
"first_mon",
"=",
"teutholo... | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/qa/tasks/osd_backfill.py#L32-L102 | ||
rbfx/rbfx | 68c45708fd26759d1186360044827aef0484c4ae | Source/ThirdParty/glslang/update_glslang_sources.py | python | GoodCommit.AddRemote | (self) | Add the remote 'known-good' if it does not exist. | Add the remote 'known-good' if it does not exist. | [
"Add",
"the",
"remote",
"known",
"-",
"good",
"if",
"it",
"does",
"not",
"exist",
"."
] | def AddRemote(self):
"""Add the remote 'known-good' if it does not exist."""
remotes = command_output(['git', 'remote'], self.subdir).splitlines()
if b'known-good' not in remotes:
command_output(['git', 'remote', 'add', 'known-good', self.GetUrl()], self.subdir) | [
"def",
"AddRemote",
"(",
"self",
")",
":",
"remotes",
"=",
"command_output",
"(",
"[",
"'git'",
",",
"'remote'",
"]",
",",
"self",
".",
"subdir",
")",
".",
"splitlines",
"(",
")",
"if",
"b'known-good'",
"not",
"in",
"remotes",
":",
"command_output",
"(",... | https://github.com/rbfx/rbfx/blob/68c45708fd26759d1186360044827aef0484c4ae/Source/ThirdParty/glslang/update_glslang_sources.py#L96-L100 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/decimal.py | python | Decimal.compare_total_mag | (self, other) | return s.compare_total(o) | Compares self to other using abstract repr., ignoring sign.
Like compare_total, but with operand's sign ignored and assumed to be 0. | Compares self to other using abstract repr., ignoring sign. | [
"Compares",
"self",
"to",
"other",
"using",
"abstract",
"repr",
".",
"ignoring",
"sign",
"."
] | def compare_total_mag(self, other):
"""Compares self to other using abstract repr., ignoring sign.
Like compare_total, but with operand's sign ignored and assumed to be 0.
"""
other = _convert_other(other, raiseit=True)
s = self.copy_abs()
o = other.copy_abs()
return s.compare_total(o) | [
"def",
"compare_total_mag",
"(",
"self",
",",
"other",
")",
":",
"other",
"=",
"_convert_other",
"(",
"other",
",",
"raiseit",
"=",
"True",
")",
"s",
"=",
"self",
".",
"copy_abs",
"(",
")",
"o",
"=",
"other",
".",
"copy_abs",
"(",
")",
"return",
"s",... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/decimal.py#L2904-L2913 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/neighbors/approximate.py | python | _find_longest_prefix_match | (tree, bin_X, hash_size,
left_masks, right_masks) | return res | Find the longest prefix match in tree for each query in bin_X
Most significant bits are considered as the prefix. | Find the longest prefix match in tree for each query in bin_X | [
"Find",
"the",
"longest",
"prefix",
"match",
"in",
"tree",
"for",
"each",
"query",
"in",
"bin_X"
] | def _find_longest_prefix_match(tree, bin_X, hash_size,
left_masks, right_masks):
"""Find the longest prefix match in tree for each query in bin_X
Most significant bits are considered as the prefix.
"""
hi = np.empty_like(bin_X, dtype=np.intp)
hi.fill(hash_size)
lo = np.zeros_like(bin_X, dtype=np.intp)
res = np.empty_like(bin_X, dtype=np.intp)
left_idx, right_idx = _find_matching_indices(tree, bin_X,
left_masks[hi],
right_masks[hi])
found = right_idx > left_idx
res[found] = lo[found] = hash_size
r = np.arange(bin_X.shape[0])
kept = r[lo < hi] # indices remaining in bin_X mask
while kept.shape[0]:
mid = (lo.take(kept) + hi.take(kept)) // 2
left_idx, right_idx = _find_matching_indices(tree,
bin_X.take(kept),
left_masks[mid],
right_masks[mid])
found = right_idx > left_idx
mid_found = mid[found]
lo[kept[found]] = mid_found + 1
res[kept[found]] = mid_found
hi[kept[~found]] = mid[~found]
kept = r[lo < hi]
return res | [
"def",
"_find_longest_prefix_match",
"(",
"tree",
",",
"bin_X",
",",
"hash_size",
",",
"left_masks",
",",
"right_masks",
")",
":",
"hi",
"=",
"np",
".",
"empty_like",
"(",
"bin_X",
",",
"dtype",
"=",
"np",
".",
"intp",
")",
"hi",
".",
"fill",
"(",
"has... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/neighbors/approximate.py#L36-L70 | |
twhui/LiteFlowNet | 00925aebf2db9ac50f4b1666f718688b10dd10d1 | python/caffe/draw.py | python | get_pydot_graph | (caffe_net, rankdir, label_edges=True) | return pydot_graph | Create a data structure which represents the `caffe_net`.
Parameters
----------
caffe_net : object
rankdir : {'LR', 'TB', 'BT'}
Direction of graph layout.
label_edges : boolean, optional
Label the edges (default is True).
Returns
-------
pydot graph object | Create a data structure which represents the `caffe_net`. | [
"Create",
"a",
"data",
"structure",
"which",
"represents",
"the",
"caffe_net",
"."
] | def get_pydot_graph(caffe_net, rankdir, label_edges=True):
"""Create a data structure which represents the `caffe_net`.
Parameters
----------
caffe_net : object
rankdir : {'LR', 'TB', 'BT'}
Direction of graph layout.
label_edges : boolean, optional
Label the edges (default is True).
Returns
-------
pydot graph object
"""
pydot_graph = pydot.Dot(caffe_net.name if caffe_net.name else 'Net',
graph_type='digraph',
rankdir=rankdir)
pydot_nodes = {}
pydot_edges = []
for layer in caffe_net.layer:
node_label = get_layer_label(layer, rankdir)
node_name = "%s_%s" % (layer.name, layer.type)
if (len(layer.bottom) == 1 and len(layer.top) == 1 and
layer.bottom[0] == layer.top[0]):
# We have an in-place neuron layer.
pydot_nodes[node_name] = pydot.Node(node_label,
**NEURON_LAYER_STYLE)
else:
layer_style = LAYER_STYLE_DEFAULT
layer_style['fillcolor'] = choose_color_by_layertype(layer.type)
pydot_nodes[node_name] = pydot.Node(node_label, **layer_style)
for bottom_blob in layer.bottom:
pydot_nodes[bottom_blob + '_blob'] = pydot.Node('%s' % bottom_blob,
**BLOB_STYLE)
edge_label = '""'
pydot_edges.append({'src': bottom_blob + '_blob',
'dst': node_name,
'label': edge_label})
for top_blob in layer.top:
pydot_nodes[top_blob + '_blob'] = pydot.Node('%s' % (top_blob))
if label_edges:
edge_label = get_edge_label(layer)
else:
edge_label = '""'
pydot_edges.append({'src': node_name,
'dst': top_blob + '_blob',
'label': edge_label})
# Now, add the nodes and edges to the graph.
for node in pydot_nodes.values():
pydot_graph.add_node(node)
for edge in pydot_edges:
pydot_graph.add_edge(
pydot.Edge(pydot_nodes[edge['src']],
pydot_nodes[edge['dst']],
label=edge['label']))
return pydot_graph | [
"def",
"get_pydot_graph",
"(",
"caffe_net",
",",
"rankdir",
",",
"label_edges",
"=",
"True",
")",
":",
"pydot_graph",
"=",
"pydot",
".",
"Dot",
"(",
"caffe_net",
".",
"name",
"if",
"caffe_net",
".",
"name",
"else",
"'Net'",
",",
"graph_type",
"=",
"'digrap... | https://github.com/twhui/LiteFlowNet/blob/00925aebf2db9ac50f4b1666f718688b10dd10d1/python/caffe/draw.py#L130-L186 | |
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/peacock/Input/ParamsTable.py | python | ParamsTable.createRow | (self, param, name_editable=False, value_editable=True, comments_editable=True, index=-1) | Create a row in the table for a param.
Input:
param: ParamNode
Return:
BaseRowItem derived object | Create a row in the table for a param.
Input:
param: ParamNode
Return:
BaseRowItem derived object | [
"Create",
"a",
"row",
"in",
"the",
"table",
"for",
"a",
"param",
".",
"Input",
":",
"param",
":",
"ParamNode",
"Return",
":",
"BaseRowItem",
"derived",
"object"
] | def createRow(self, param, name_editable=False, value_editable=True, comments_editable=True, index=-1):
"""
Create a row in the table for a param.
Input:
param: ParamNode
Return:
BaseRowItem derived object
"""
row = self.rowCount()
if index >= 0:
row = index
self.insertRow(row)
name_item = QtWidgets.QTableWidgetItem(param.name)
name_item.setData(Qt.UserRole, param)
if not name_editable:
name_item.setFlags(Qt.ItemIsEnabled)
if param.required:
color = QColor(255, 204, 153)
brush = QBrush(color)
name_item.setBackground(brush)
elif param.user_added:
color = QColor("cyan")
brush = QBrush(color)
name_item.setBackground(brush)
name_item.setText(param.name)
self.setItem(row, 0, name_item)
if param.cpp_type == "bool":
checkbox = QtWidgets.QCheckBox()
if param.value == "true":
checkbox.setCheckState(Qt.Checked)
else:
checkbox.setCheckState(Qt.Unchecked)
checkbox.pressed.connect(self.changed)
self.setCellWidget(row, 1, checkbox)
else:
value_item = QtWidgets.QTableWidgetItem(param.value)
if not value_editable or param.name == "type":
value_item.setFlags(Qt.ItemIsEnabled)
else:
name_item.setToolTip(param.toolTip())
self.setItem(row, 1, value_item)
comments_item = QtWidgets.QTableWidgetItem(param.comments)
if not comments_editable:
comments_item.setFlags(Qt.ItemIsEnabled)
self.setItem(row, 3, comments_item)
watch_blocks = self._getChildrenOfNodeOptions(param.cpp_type)
if param.cpp_type == "FileName" or param.cpp_type == "MeshFileName" or param.cpp_type == "FileNameNoExtension":
self._createFilenameOption(param)
elif watch_blocks:
self._createBlockWatcher(param, watch_blocks)
elif param.options:
self._createOptions(param)
elif param.user_added:
button = QtWidgets.QPushButton("Remove")
button.clicked.connect(lambda checked: self._removeButtonClicked(name_item))
self.setCellWidget(row, 2, button)
else:
option_item = QtWidgets.QTableWidgetItem()
option_item.setFlags(Qt.NoItemFlags)
self.setItem(row, 2, option_item) | [
"def",
"createRow",
"(",
"self",
",",
"param",
",",
"name_editable",
"=",
"False",
",",
"value_editable",
"=",
"True",
",",
"comments_editable",
"=",
"True",
",",
"index",
"=",
"-",
"1",
")",
":",
"row",
"=",
"self",
".",
"rowCount",
"(",
")",
"if",
... | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/Input/ParamsTable.py#L418-L484 | ||
facebook/wangle | 2e7e3fbb3a15c4986d6fe0e36c31daeeba614ce3 | build/fbcode_builder/getdeps/expr.py | python | parse_expr | (expr_text, valid_variables) | return p.parse() | parses the simple criteria expression syntax used in
dependency specifications.
Returns an ExprNode instance that can be evaluated like this:
```
expr = parse_expr("os=windows")
ok = expr.eval({
"os": "windows"
})
```
Whitespace is allowed between tokens. The following terms
are recognized:
KEY = VALUE # Evaluates to True if ctx[KEY] == VALUE
not(EXPR) # Evaluates to True if EXPR evaluates to False
# and vice versa
all(EXPR1, EXPR2, ...) # Evaluates True if all of the supplied
# EXPR's also evaluate True
any(EXPR1, EXPR2, ...) # Evaluates True if any of the supplied
# EXPR's also evaluate True, False if
# none of them evaluated true. | parses the simple criteria expression syntax used in
dependency specifications.
Returns an ExprNode instance that can be evaluated like this: | [
"parses",
"the",
"simple",
"criteria",
"expression",
"syntax",
"used",
"in",
"dependency",
"specifications",
".",
"Returns",
"an",
"ExprNode",
"instance",
"that",
"can",
"be",
"evaluated",
"like",
"this",
":"
] | def parse_expr(expr_text, valid_variables):
"""parses the simple criteria expression syntax used in
dependency specifications.
Returns an ExprNode instance that can be evaluated like this:
```
expr = parse_expr("os=windows")
ok = expr.eval({
"os": "windows"
})
```
Whitespace is allowed between tokens. The following terms
are recognized:
KEY = VALUE # Evaluates to True if ctx[KEY] == VALUE
not(EXPR) # Evaluates to True if EXPR evaluates to False
# and vice versa
all(EXPR1, EXPR2, ...) # Evaluates True if all of the supplied
# EXPR's also evaluate True
any(EXPR1, EXPR2, ...) # Evaluates True if any of the supplied
# EXPR's also evaluate True, False if
# none of them evaluated true.
"""
p = Parser(expr_text, valid_variables)
return p.parse() | [
"def",
"parse_expr",
"(",
"expr_text",
",",
"valid_variables",
")",
":",
"p",
"=",
"Parser",
"(",
"expr_text",
",",
"valid_variables",
")",
"return",
"p",
".",
"parse",
"(",
")"
] | https://github.com/facebook/wangle/blob/2e7e3fbb3a15c4986d6fe0e36c31daeeba614ce3/build/fbcode_builder/getdeps/expr.py#L10-L36 | |
Samsung/veles | 95ed733c2e49bc011ad98ccf2416ecec23fbf352 | veles/external/pydot.py | python | Node.get_port | (self) | return self.obj_dict['port'] | Get the node's port. | Get the node's port. | [
"Get",
"the",
"node",
"s",
"port",
"."
] | def get_port(self):
"""Get the node's port."""
return self.obj_dict['port'] | [
"def",
"get_port",
"(",
"self",
")",
":",
"return",
"self",
".",
"obj_dict",
"[",
"'port'",
"]"
] | https://github.com/Samsung/veles/blob/95ed733c2e49bc011ad98ccf2416ecec23fbf352/veles/external/pydot.py#L769-L772 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pyparsing/py2/pyparsing.py | python | ParserElement.transformString | (self, instring) | Extension to :class:`scanString`, to modify matching text with modified tokens that may
be returned from a parse action. To use ``transformString``, define a grammar and
attach a parse action to it that modifies the returned token list.
Invoking ``transformString()`` on a target string will then scan for matches,
and replace the matched text patterns according to the logic in the parse
action. ``transformString()`` returns the resulting transformed string.
Example::
wd = Word(alphas)
wd.setParseAction(lambda toks: toks[0].title())
print(wd.transformString("now is the winter of our discontent made glorious summer by this sun of york."))
prints::
Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York. | Extension to :class:`scanString`, to modify matching text with modified tokens that may
be returned from a parse action. To use ``transformString``, define a grammar and
attach a parse action to it that modifies the returned token list.
Invoking ``transformString()`` on a target string will then scan for matches,
and replace the matched text patterns according to the logic in the parse
action. ``transformString()`` returns the resulting transformed string. | [
"Extension",
"to",
":",
"class",
":",
"scanString",
"to",
"modify",
"matching",
"text",
"with",
"modified",
"tokens",
"that",
"may",
"be",
"returned",
"from",
"a",
"parse",
"action",
".",
"To",
"use",
"transformString",
"define",
"a",
"grammar",
"and",
"atta... | def transformString(self, instring):
"""
Extension to :class:`scanString`, to modify matching text with modified tokens that may
be returned from a parse action. To use ``transformString``, define a grammar and
attach a parse action to it that modifies the returned token list.
Invoking ``transformString()`` on a target string will then scan for matches,
and replace the matched text patterns according to the logic in the parse
action. ``transformString()`` returns the resulting transformed string.
Example::
wd = Word(alphas)
wd.setParseAction(lambda toks: toks[0].title())
print(wd.transformString("now is the winter of our discontent made glorious summer by this sun of york."))
prints::
Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York.
"""
out = []
lastE = 0
# force preservation of <TAB>s, to minimize unwanted transformation of string, and to
# keep string locs straight between transformString and scanString
self.keepTabs = True
try:
for t, s, e in self.scanString(instring):
out.append(instring[lastE:s])
if t:
if isinstance(t, ParseResults):
out += t.asList()
elif isinstance(t, list):
out += t
else:
out.append(t)
lastE = e
out.append(instring[lastE:])
out = [o for o in out if o]
return "".join(map(_ustr, _flatten(out)))
except ParseBaseException as exc:
if ParserElement.verbose_stacktrace:
raise
else:
# catch and re-raise exception from here, clearing out pyparsing internal stack trace
if getattr(exc, '__traceback__', None) is not None:
exc.__traceback__ = self._trim_traceback(exc.__traceback__)
raise exc | [
"def",
"transformString",
"(",
"self",
",",
"instring",
")",
":",
"out",
"=",
"[",
"]",
"lastE",
"=",
"0",
"# force preservation of <TAB>s, to minimize unwanted transformation of string, and to",
"# keep string locs straight between transformString and scanString",
"self",
".",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pyparsing/py2/pyparsing.py#L2033-L2079 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/stc.py | python | StyledTextCtrl.SetSelAlpha | (*args, **kwargs) | return _stc.StyledTextCtrl_SetSelAlpha(*args, **kwargs) | SetSelAlpha(self, int alpha)
Set the alpha of the selection. | SetSelAlpha(self, int alpha) | [
"SetSelAlpha",
"(",
"self",
"int",
"alpha",
")"
] | def SetSelAlpha(*args, **kwargs):
"""
SetSelAlpha(self, int alpha)
Set the alpha of the selection.
"""
return _stc.StyledTextCtrl_SetSelAlpha(*args, **kwargs) | [
"def",
"SetSelAlpha",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_SetSelAlpha",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/stc.py#L2747-L2753 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/vis/camera.py | python | orbit.set_orientation | (self,R,ori=None) | Sets the orientation of the camera to the so3 element R.
If ori is provided, it is an orientation list (e.g., ['x','y','z'])
that tells the function how to interpret the columns of R in terms of
the right, down, and fwd axes of the camera. Its default value is
None. | Sets the orientation of the camera to the so3 element R. | [
"Sets",
"the",
"orientation",
"of",
"the",
"camera",
"to",
"the",
"so3",
"element",
"R",
"."
] | def set_orientation(self,R,ori=None):
"""Sets the orientation of the camera to the so3 element R.
If ori is provided, it is an orientation list (e.g., ['x','y','z'])
that tells the function how to interpret the columns of R in terms of
the right, down, and fwd axes of the camera. Its default value is
None.
"""
import math
#Rdes*oR*[right,down,fwd] = R_euler(rot)*o*[right,down,fwd]
if ori is not None:
o = orientation_matrix(*self.ori)
oR = orientation_matrix(*ori)
R = so3.mul(R,so3.mul(so3.inv(oR),o))
#Ry = so3.rotation([0,1,0],self.rot[0])
#Rx = so3.rotation([1,0,0],self.rot[1])
#Rz = so3.rotation([0,0,1],self.rot[2])
#set self.rot to fulfill constraint R = Rz*Rx*Ry
# [cz -sz 0][1 0 0][cy 0 sy] [cz -szcx szsx][cy 0 sy]
# R = [sz cz 0][0 cx -sx][0 1 0] = [sz czcx -czsx][0 1 0 ]
# [0 0 1][0 sx cx][-sy 0 cy] [0 sx cx][-sy 0 cy]
# [czcy-szsxsy -szcx czsy+szsxcy ]
# = [szcy+czsxsy czcx szsy-czsxcy ]
# [-cxsy sx cxcy ]
m = so3.matrix(R)
cx = math.sqrt(m[0][1]**2 + m[1][1]**2)
#assume cx is positive (pitch in range [-pi/2,pi/2])
sx = m[2][1]
self.rot[1] = math.atan2(sx,cx)
if abs(cx) > 1e-5:
sz = -m[0][1]
cz = m[1][1]
sy = -m[2][0]
cy = m[2][2]
self.rot[2] = math.atan2(sz,cz)
self.rot[0] = math.atan2(sy,cy)
else:
#near vertical, have redundancy, have cx=0,sx = +/-1, set Ry=0 (so cy=1, sy=0)
self.rot[0] = 0
cz = m[0][0]
sz = m[1][0]
self.rot[2] = math.atan2(sz,cz) | [
"def",
"set_orientation",
"(",
"self",
",",
"R",
",",
"ori",
"=",
"None",
")",
":",
"import",
"math",
"#Rdes*oR*[right,down,fwd] = R_euler(rot)*o*[right,down,fwd]",
"if",
"ori",
"is",
"not",
"None",
":",
"o",
"=",
"orientation_matrix",
"(",
"*",
"self",
".",
"... | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/vis/camera.py#L113-L154 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/multiprocessing/managers.py | python | BaseProxy.__str__ | (self) | Return representation of the referent (or a fall-back if that fails) | Return representation of the referent (or a fall-back if that fails) | [
"Return",
"representation",
"of",
"the",
"referent",
"(",
"or",
"a",
"fall",
"-",
"back",
"if",
"that",
"fails",
")"
] | def __str__(self):
'''
Return representation of the referent (or a fall-back if that fails)
'''
try:
return self._callmethod('__repr__')
except Exception:
return repr(self)[:-1] + "; '__str__()' failed>" | [
"def",
"__str__",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_callmethod",
"(",
"'__repr__'",
")",
"except",
"Exception",
":",
"return",
"repr",
"(",
"self",
")",
"[",
":",
"-",
"1",
"]",
"+",
"\"; '__str__()' failed>\""
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/multiprocessing/managers.py#L851-L858 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib2to3/pytree.py | python | Node.clone | (self) | return Node(self.type, [ch.clone() for ch in self.children],
fixers_applied=self.fixers_applied) | Return a cloned (deep) copy of self. | Return a cloned (deep) copy of self. | [
"Return",
"a",
"cloned",
"(",
"deep",
")",
"copy",
"of",
"self",
"."
] | def clone(self):
"""Return a cloned (deep) copy of self."""
return Node(self.type, [ch.clone() for ch in self.children],
fixers_applied=self.fixers_applied) | [
"def",
"clone",
"(",
"self",
")",
":",
"return",
"Node",
"(",
"self",
".",
"type",
",",
"[",
"ch",
".",
"clone",
"(",
")",
"for",
"ch",
"in",
"self",
".",
"children",
"]",
",",
"fixers_applied",
"=",
"self",
".",
"fixers_applied",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib2to3/pytree.py#L289-L292 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/pkg_resources/__init__.py | python | yield_lines | (strs) | Yield non-empty/non-comment lines of a string or sequence | Yield non-empty/non-comment lines of a string or sequence | [
"Yield",
"non",
"-",
"empty",
"/",
"non",
"-",
"comment",
"lines",
"of",
"a",
"string",
"or",
"sequence"
] | def yield_lines(strs):
"""Yield non-empty/non-comment lines of a string or sequence"""
if isinstance(strs, six.string_types):
for s in strs.splitlines():
s = s.strip()
# skip blank lines/comments
if s and not s.startswith('#'):
yield s
else:
for ss in strs:
for s in yield_lines(ss):
yield s | [
"def",
"yield_lines",
"(",
"strs",
")",
":",
"if",
"isinstance",
"(",
"strs",
",",
"six",
".",
"string_types",
")",
":",
"for",
"s",
"in",
"strs",
".",
"splitlines",
"(",
")",
":",
"s",
"=",
"s",
".",
"strip",
"(",
")",
"# skip blank lines/comments",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/pkg_resources/__init__.py#L4755-L4777 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/dtypes/common.py | python | is_signed_integer_dtype | (arr_or_dtype) | return _is_dtype_type(
arr_or_dtype, classes_and_not_datetimelike(np.signedinteger)) | Check whether the provided array or dtype is of a signed integer dtype.
Unlike in `in_any_int_dtype`, timedelta64 instances will return False.
.. versionchanged:: 0.24.0
The nullable Integer dtypes (e.g. pandas.Int64Dtype) are also considered
as integer by this function.
Parameters
----------
arr_or_dtype : array-like
The array or dtype to check.
Returns
-------
boolean : Whether or not the array or dtype is of a signed integer dtype
and not an instance of timedelta64.
Examples
--------
>>> is_signed_integer_dtype(str)
False
>>> is_signed_integer_dtype(int)
True
>>> is_signed_integer_dtype(float)
False
>>> is_signed_integer_dtype(np.uint64) # unsigned
False
>>> is_signed_integer_dtype('int8')
True
>>> is_signed_integer_dtype('Int8')
True
>>> is_signed_dtype(pd.Int8Dtype)
True
>>> is_signed_integer_dtype(np.datetime64)
False
>>> is_signed_integer_dtype(np.timedelta64)
False
>>> is_signed_integer_dtype(np.array(['a', 'b']))
False
>>> is_signed_integer_dtype(pd.Series([1, 2]))
True
>>> is_signed_integer_dtype(np.array([], dtype=np.timedelta64))
False
>>> is_signed_integer_dtype(pd.Index([1, 2.])) # float
False
>>> is_signed_integer_dtype(np.array([1, 2], dtype=np.uint32)) # unsigned
False | Check whether the provided array or dtype is of a signed integer dtype. | [
"Check",
"whether",
"the",
"provided",
"array",
"or",
"dtype",
"is",
"of",
"a",
"signed",
"integer",
"dtype",
"."
] | def is_signed_integer_dtype(arr_or_dtype):
"""
Check whether the provided array or dtype is of a signed integer dtype.
Unlike in `in_any_int_dtype`, timedelta64 instances will return False.
.. versionchanged:: 0.24.0
The nullable Integer dtypes (e.g. pandas.Int64Dtype) are also considered
as integer by this function.
Parameters
----------
arr_or_dtype : array-like
The array or dtype to check.
Returns
-------
boolean : Whether or not the array or dtype is of a signed integer dtype
and not an instance of timedelta64.
Examples
--------
>>> is_signed_integer_dtype(str)
False
>>> is_signed_integer_dtype(int)
True
>>> is_signed_integer_dtype(float)
False
>>> is_signed_integer_dtype(np.uint64) # unsigned
False
>>> is_signed_integer_dtype('int8')
True
>>> is_signed_integer_dtype('Int8')
True
>>> is_signed_dtype(pd.Int8Dtype)
True
>>> is_signed_integer_dtype(np.datetime64)
False
>>> is_signed_integer_dtype(np.timedelta64)
False
>>> is_signed_integer_dtype(np.array(['a', 'b']))
False
>>> is_signed_integer_dtype(pd.Series([1, 2]))
True
>>> is_signed_integer_dtype(np.array([], dtype=np.timedelta64))
False
>>> is_signed_integer_dtype(pd.Index([1, 2.])) # float
False
>>> is_signed_integer_dtype(np.array([1, 2], dtype=np.uint32)) # unsigned
False
"""
return _is_dtype_type(
arr_or_dtype, classes_and_not_datetimelike(np.signedinteger)) | [
"def",
"is_signed_integer_dtype",
"(",
"arr_or_dtype",
")",
":",
"return",
"_is_dtype_type",
"(",
"arr_or_dtype",
",",
"classes_and_not_datetimelike",
"(",
"np",
".",
"signedinteger",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/dtypes/common.py#L923-L977 | |
livecode/livecode | 4606a10ea10b16d5071d0f9f263ccdd7ede8b31d | gyp/pylib/gyp/generator/msvs.py | python | _GetOutputTargetExt | (spec) | return None | Returns the extension for this target, including the dot
If product_extension is specified, set target_extension to this to avoid
MSB8012, returns None otherwise. Ignores any target_extension settings in
the input files.
Arguments:
spec: The target dictionary containing the properties of the target.
Returns:
A string with the extension, or None | Returns the extension for this target, including the dot | [
"Returns",
"the",
"extension",
"for",
"this",
"target",
"including",
"the",
"dot"
] | def _GetOutputTargetExt(spec):
"""Returns the extension for this target, including the dot
If product_extension is specified, set target_extension to this to avoid
MSB8012, returns None otherwise. Ignores any target_extension settings in
the input files.
Arguments:
spec: The target dictionary containing the properties of the target.
Returns:
A string with the extension, or None
"""
target_extension = spec.get('product_extension')
if target_extension:
return '.' + target_extension
return None | [
"def",
"_GetOutputTargetExt",
"(",
"spec",
")",
":",
"target_extension",
"=",
"spec",
".",
"get",
"(",
"'product_extension'",
")",
"if",
"target_extension",
":",
"return",
"'.'",
"+",
"target_extension",
"return",
"None"
] | https://github.com/livecode/livecode/blob/4606a10ea10b16d5071d0f9f263ccdd7ede8b31d/gyp/pylib/gyp/generator/msvs.py#L1287-L1302 | |
bundy-dns/bundy | 3d41934996b82b0cd2fe22dd74d2abc1daba835d | src/lib/python/bundy/config/config_data.py | python | MultiConfigData.set_value | (self, identifier, value) | Set the local value at the given identifier to value. If
there is a specification for the given identifier, the type
is checked. | Set the local value at the given identifier to value. If
there is a specification for the given identifier, the type
is checked. | [
"Set",
"the",
"local",
"value",
"at",
"the",
"given",
"identifier",
"to",
"value",
".",
"If",
"there",
"is",
"a",
"specification",
"for",
"the",
"given",
"identifier",
"the",
"type",
"is",
"checked",
"."
] | def set_value(self, identifier, value):
"""Set the local value at the given identifier to value. If
there is a specification for the given identifier, the type
is checked."""
spec_part = self.find_spec_part(identifier)
if spec_part is not None:
if value is not None:
id, list_indices = bundy.cc.data.split_identifier_list_indices(identifier)
if list_indices is not None \
and spec_part['item_type'] == 'list':
spec_part = spec_part['list_item_spec']
check_type(spec_part, value)
else:
raise bundy.cc.data.DataNotFoundError(identifier + " not found")
# Since we do not support list diffs (yet?), we need to
# copy the currently set list of items to _local_changes
# if we want to modify an element in there
# (for any list indices specified in the full identifier)
id_parts = bundy.cc.data.split_identifier(identifier)
cur_id_part = '/'
for id_part in id_parts:
id, list_indices = bundy.cc.data.split_identifier_list_indices(id_part)
cur_value, status = self.get_value(cur_id_part + id)
# Check if the value was there in the first place
# If we are at the final element, we do not care whether we found
# it, since if we have reached this point and it did not exist,
# it was apparently an optional value without a default.
if status == MultiConfigData.NONE and cur_id_part != "/" and\
cur_id_part + id != identifier:
raise bundy.cc.data.DataNotFoundError(id_part +
" not found in " +
cur_id_part)
if list_indices is not None:
# And check if we don't set something outside of any
# list
cur_list = cur_value
for list_index in list_indices:
if type(cur_list) != list:
raise bundy.cc.data.DataTypeError(id + " is not a list")
if list_index >= len(cur_list):
raise bundy.cc.data.DataNotFoundError("No item " +
str(list_index) + " in " + id_part)
else:
cur_list = cur_list[list_index]
if status != MultiConfigData.LOCAL:
bundy.cc.data.set(self._local_changes,
cur_id_part + id,
cur_value)
cur_id_part = cur_id_part + id_part + "/"
# We also need to copy to local if we are changing a named set,
# so that the other items in the set do not disappear
if spec_part_is_named_set(self.find_spec_part(cur_id_part)):
ns_value, ns_status = self.get_value(cur_id_part)
if ns_status != MultiConfigData.LOCAL:
bundy.cc.data.set(self._local_changes,
cur_id_part,
ns_value)
bundy.cc.data.set(self._local_changes, identifier, value) | [
"def",
"set_value",
"(",
"self",
",",
"identifier",
",",
"value",
")",
":",
"spec_part",
"=",
"self",
".",
"find_spec_part",
"(",
"identifier",
")",
"if",
"spec_part",
"is",
"not",
"None",
":",
"if",
"value",
"is",
"not",
"None",
":",
"id",
",",
"list_... | https://github.com/bundy-dns/bundy/blob/3d41934996b82b0cd2fe22dd74d2abc1daba835d/src/lib/python/bundy/config/config_data.py#L781-L840 | ||
freeorion/freeorion | c266a40eccd3a99a17de8fe57c36ef6ba3771665 | default/python/AI/MilitaryAI.py | python | cur_best_mil_ship_rating | (include_designs=False) | return max(best_rating, 0.001) | Find the best military ship we have available in this turn and return its rating.
:param include_designs: toggles if available designs are considered or only existing ships
:return: float: rating of the best ship | Find the best military ship we have available in this turn and return its rating. | [
"Find",
"the",
"best",
"military",
"ship",
"we",
"have",
"available",
"in",
"this",
"turn",
"and",
"return",
"its",
"rating",
"."
] | def cur_best_mil_ship_rating(include_designs=False):
"""Find the best military ship we have available in this turn and return its rating.
:param include_designs: toggles if available designs are considered or only existing ships
:return: float: rating of the best ship
"""
current_turn = fo.currentTurn()
if current_turn in _best_ship_rating_cache:
best_rating = _best_ship_rating_cache[current_turn]
if include_designs:
best_design_rating = cur_best_military_design_rating()
best_rating = max(best_rating, best_design_rating)
return best_rating
best_rating = 0.001
universe = fo.getUniverse()
aistate = get_aistate()
for fleet_id in FleetUtilsAI.get_empire_fleet_ids_by_role(MissionType.MILITARY):
fleet = universe.getFleet(fleet_id)
for ship_id in fleet.shipIDs:
ship_rating = get_ship_combat_stats(ship_id).get_rating(enemy_stats=aistate.get_standard_enemy())
best_rating = max(best_rating, ship_rating)
_best_ship_rating_cache[current_turn] = best_rating
if include_designs:
best_design_rating = cur_best_military_design_rating()
best_rating = max(best_rating, best_design_rating)
return max(best_rating, 0.001) | [
"def",
"cur_best_mil_ship_rating",
"(",
"include_designs",
"=",
"False",
")",
":",
"current_turn",
"=",
"fo",
".",
"currentTurn",
"(",
")",
"if",
"current_turn",
"in",
"_best_ship_rating_cache",
":",
"best_rating",
"=",
"_best_ship_rating_cache",
"[",
"current_turn",
... | https://github.com/freeorion/freeorion/blob/c266a40eccd3a99a17de8fe57c36ef6ba3771665/default/python/AI/MilitaryAI.py#L38-L63 | |
ArmageddonGames/ZeldaClassic | c244ae6c1d361d24a5529b1c0394e656f1f5d965 | allegro/misc/genexamp.py | python | replace_example_references | (documentation, ids_to_examples) | return new_lines | func([lines], {id: [words]}) -> [new_lines]
Goes through the documentation in memory searching for the
identifiers. When one is found, it looks it up in the provided
dictionary. If it's not found, nothing happens. Otherwise whatches
closely the following text lines for @erefs and updates them
accordingly. If no @erefs are found, they are created. Finally
a new list is returned with the updated documentation.
There is a special hardcoded case: if limit_example_erefs
is greater than 0, this value will be used as the limit of
example references generated per identifier. When the number
of example references is greater than this limit, a single
reference is generated to the value stored in the string
limit_example_reference, which should point to the correct
Allegro documentation chapter. | func([lines], {id: [words]}) -> [new_lines] | [
"func",
"(",
"[",
"lines",
"]",
"{",
"id",
":",
"[",
"words",
"]",
"}",
")",
"-",
">",
"[",
"new_lines",
"]"
] | def replace_example_references(documentation, ids_to_examples):
"""func([lines], {id: [words]}) -> [new_lines]
Goes through the documentation in memory searching for the
identifiers. When one is found, it looks it up in the provided
dictionary. If it's not found, nothing happens. Otherwise whatches
closely the following text lines for @erefs and updates them
accordingly. If no @erefs are found, they are created. Finally
a new list is returned with the updated documentation.
There is a special hardcoded case: if limit_example_erefs
is greater than 0, this value will be used as the limit of
example references generated per identifier. When the number
of example references is greater than this limit, a single
reference is generated to the value stored in the string
limit_example_reference, which should point to the correct
Allegro documentation chapter.
"""
new_lines = []
short_desc = []
found_id = ""
exp = re.compile(regular_expression_for_tx_identifiers)
for line in documentation:
if found_id:
if line[0] == '@':
# Don't append erefs, which will be regenerated.
if line[1:5] == "xref" or line[1] == "@" or line[1:3] == "\\ ":
new_lines.append(line)
# Append shortdesc, but after @erefs as a special case.
if line[1:10] == "shortdesc":
short_desc = [line]
else:
# create the eref block and append before normal text
eref_list = ids_to_examples[found_id]
eref_list.sort()
if len(eref_list) > limit_example_erefs:
new_lines.append("@eref %s\n" % limit_example_reference)
else:
new_lines.extend(build_xref_block(eref_list, "@eref"))
if short_desc:
new_lines.extend(short_desc)
short_desc = []
new_lines.append(line)
found_id = ""
else:
if short_desc:
new_lines.extend(short_desc)
short_desc = []
new_lines.append(line)
match = exp.match(line)
if match and ids_to_examples.has_key(match.group("name")):
found_id = match.group("name")
return new_lines | [
"def",
"replace_example_references",
"(",
"documentation",
",",
"ids_to_examples",
")",
":",
"new_lines",
"=",
"[",
"]",
"short_desc",
"=",
"[",
"]",
"found_id",
"=",
"\"\"",
"exp",
"=",
"re",
".",
"compile",
"(",
"regular_expression_for_tx_identifiers",
")",
"f... | https://github.com/ArmageddonGames/ZeldaClassic/blob/c244ae6c1d361d24a5529b1c0394e656f1f5d965/allegro/misc/genexamp.py#L346-L402 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/plotting/_matplotlib/tools.py | python | create_subplots | (
naxes: int,
sharex: bool = False,
sharey: bool = False,
squeeze: bool = True,
subplot_kw=None,
ax=None,
layout=None,
layout_type: str = "box",
**fig_kw,
) | return fig, axes | Create a figure with a set of subplots already made.
This utility wrapper makes it convenient to create common layouts of
subplots, including the enclosing figure object, in a single call.
Parameters
----------
naxes : int
Number of required axes. Exceeded axes are set invisible. Default is
nrows * ncols.
sharex : bool
If True, the X axis will be shared amongst all subplots.
sharey : bool
If True, the Y axis will be shared amongst all subplots.
squeeze : bool
If True, extra dimensions are squeezed out from the returned axis object:
- if only one subplot is constructed (nrows=ncols=1), the resulting
single Axis object is returned as a scalar.
- for Nx1 or 1xN subplots, the returned object is a 1-d numpy object
array of Axis objects are returned as numpy 1-d arrays.
- for NxM subplots with N>1 and M>1 are returned as a 2d array.
If False, no squeezing is done: the returned axis object is always
a 2-d array containing Axis instances, even if it ends up being 1x1.
subplot_kw : dict
Dict with keywords passed to the add_subplot() call used to create each
subplots.
ax : Matplotlib axis object, optional
layout : tuple
Number of rows and columns of the subplot grid.
If not specified, calculated from naxes and layout_type
layout_type : {'box', 'horizontal', 'vertical'}, default 'box'
Specify how to layout the subplot grid.
fig_kw : Other keyword arguments to be passed to the figure() call.
Note that all keywords not recognized above will be
automatically included here.
Returns
-------
fig, ax : tuple
- fig is the Matplotlib Figure object
- ax can be either a single axis object or an array of axis objects if
more than one subplot was created. The dimensions of the resulting array
can be controlled with the squeeze keyword, see above.
Examples
--------
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)
# Just a figure and one subplot
f, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')
# Two subplots, unpack the output array immediately
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)
# Four polar axes
plt.subplots(2, 2, subplot_kw=dict(polar=True)) | Create a figure with a set of subplots already made. | [
"Create",
"a",
"figure",
"with",
"a",
"set",
"of",
"subplots",
"already",
"made",
"."
] | def create_subplots(
naxes: int,
sharex: bool = False,
sharey: bool = False,
squeeze: bool = True,
subplot_kw=None,
ax=None,
layout=None,
layout_type: str = "box",
**fig_kw,
):
"""
Create a figure with a set of subplots already made.
This utility wrapper makes it convenient to create common layouts of
subplots, including the enclosing figure object, in a single call.
Parameters
----------
naxes : int
Number of required axes. Exceeded axes are set invisible. Default is
nrows * ncols.
sharex : bool
If True, the X axis will be shared amongst all subplots.
sharey : bool
If True, the Y axis will be shared amongst all subplots.
squeeze : bool
If True, extra dimensions are squeezed out from the returned axis object:
- if only one subplot is constructed (nrows=ncols=1), the resulting
single Axis object is returned as a scalar.
- for Nx1 or 1xN subplots, the returned object is a 1-d numpy object
array of Axis objects are returned as numpy 1-d arrays.
- for NxM subplots with N>1 and M>1 are returned as a 2d array.
If False, no squeezing is done: the returned axis object is always
a 2-d array containing Axis instances, even if it ends up being 1x1.
subplot_kw : dict
Dict with keywords passed to the add_subplot() call used to create each
subplots.
ax : Matplotlib axis object, optional
layout : tuple
Number of rows and columns of the subplot grid.
If not specified, calculated from naxes and layout_type
layout_type : {'box', 'horizontal', 'vertical'}, default 'box'
Specify how to layout the subplot grid.
fig_kw : Other keyword arguments to be passed to the figure() call.
Note that all keywords not recognized above will be
automatically included here.
Returns
-------
fig, ax : tuple
- fig is the Matplotlib Figure object
- ax can be either a single axis object or an array of axis objects if
more than one subplot was created. The dimensions of the resulting array
can be controlled with the squeeze keyword, see above.
Examples
--------
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)
# Just a figure and one subplot
f, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')
# Two subplots, unpack the output array immediately
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)
# Four polar axes
plt.subplots(2, 2, subplot_kw=dict(polar=True))
"""
import matplotlib.pyplot as plt
if subplot_kw is None:
subplot_kw = {}
if ax is None:
fig = plt.figure(**fig_kw)
else:
if is_list_like(ax):
if squeeze:
ax = flatten_axes(ax)
if layout is not None:
warnings.warn(
"When passing multiple axes, layout keyword is ignored", UserWarning
)
if sharex or sharey:
warnings.warn(
"When passing multiple axes, sharex and sharey "
"are ignored. These settings must be specified when creating axes",
UserWarning,
stacklevel=4,
)
if ax.size == naxes:
fig = ax.flat[0].get_figure()
return fig, ax
else:
raise ValueError(
f"The number of passed axes must be {naxes}, the "
"same as the output plot"
)
fig = ax.get_figure()
# if ax is passed and a number of subplots is 1, return ax as it is
if naxes == 1:
if squeeze:
return fig, ax
else:
return fig, flatten_axes(ax)
else:
warnings.warn(
"To output multiple subplots, the figure containing "
"the passed axes is being cleared",
UserWarning,
stacklevel=4,
)
fig.clear()
nrows, ncols = _get_layout(naxes, layout=layout, layout_type=layout_type)
nplots = nrows * ncols
# Create empty object array to hold all axes. It's easiest to make it 1-d
# so we can just append subplots upon creation, and then
axarr = np.empty(nplots, dtype=object)
# Create first subplot separately, so we can share it if requested
ax0 = fig.add_subplot(nrows, ncols, 1, **subplot_kw)
if sharex:
subplot_kw["sharex"] = ax0
if sharey:
subplot_kw["sharey"] = ax0
axarr[0] = ax0
# Note off-by-one counting because add_subplot uses the MATLAB 1-based
# convention.
for i in range(1, nplots):
kwds = subplot_kw.copy()
# Set sharex and sharey to None for blank/dummy axes, these can
# interfere with proper axis limits on the visible axes if
# they share axes e.g. issue #7528
if i >= naxes:
kwds["sharex"] = None
kwds["sharey"] = None
ax = fig.add_subplot(nrows, ncols, i + 1, **kwds)
axarr[i] = ax
if naxes != nplots:
for ax in axarr[naxes:]:
ax.set_visible(False)
handle_shared_axes(axarr, nplots, naxes, nrows, ncols, sharex, sharey)
if squeeze:
# Reshape the array to have the final desired dimension (nrow,ncol),
# though discarding unneeded dimensions that equal 1. If we only have
# one subplot, just return it instead of a 1-element array.
if nplots == 1:
axes = axarr[0]
else:
axes = axarr.reshape(nrows, ncols).squeeze()
else:
# returned axis array will be always 2-d, even if nrows=ncols=1
axes = axarr.reshape(nrows, ncols)
return fig, axes | [
"def",
"create_subplots",
"(",
"naxes",
":",
"int",
",",
"sharex",
":",
"bool",
"=",
"False",
",",
"sharey",
":",
"bool",
"=",
"False",
",",
"squeeze",
":",
"bool",
"=",
"True",
",",
"subplot_kw",
"=",
"None",
",",
"ax",
"=",
"None",
",",
"layout",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/plotting/_matplotlib/tools.py#L127-L306 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/email/charset.py | python | Charset.header_encode | (self, string) | return encoder_module.header_encode(header_bytes, codec) | Header-encode a string by converting it first to bytes.
The type of encoding (base64 or quoted-printable) will be based on
this charset's `header_encoding`.
:param string: A unicode string for the header. It must be possible
to encode this string to bytes using the character set's
output codec.
:return: The encoded string, with RFC 2047 chrome. | Header-encode a string by converting it first to bytes. | [
"Header",
"-",
"encode",
"a",
"string",
"by",
"converting",
"it",
"first",
"to",
"bytes",
"."
] | def header_encode(self, string):
"""Header-encode a string by converting it first to bytes.
The type of encoding (base64 or quoted-printable) will be based on
this charset's `header_encoding`.
:param string: A unicode string for the header. It must be possible
to encode this string to bytes using the character set's
output codec.
:return: The encoded string, with RFC 2047 chrome.
"""
codec = self.output_codec or 'us-ascii'
header_bytes = _encode(string, codec)
# 7bit/8bit encodings return the string unchanged (modulo conversions)
encoder_module = self._get_encoder(header_bytes)
if encoder_module is None:
return string
return encoder_module.header_encode(header_bytes, codec) | [
"def",
"header_encode",
"(",
"self",
",",
"string",
")",
":",
"codec",
"=",
"self",
".",
"output_codec",
"or",
"'us-ascii'",
"header_bytes",
"=",
"_encode",
"(",
"string",
",",
"codec",
")",
"# 7bit/8bit encodings return the string unchanged (modulo conversions)",
"en... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/email/charset.py#L281-L298 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/dygraph/dygraph_to_static/program_translator.py | python | _verify_init_in_dynamic_mode | (class_instance) | Verifies the instance is initialized in dynamic mode. | Verifies the instance is initialized in dynamic mode. | [
"Verifies",
"the",
"instance",
"is",
"initialized",
"in",
"dynamic",
"mode",
"."
] | def _verify_init_in_dynamic_mode(class_instance):
"""
Verifies the instance is initialized in dynamic mode.
"""
if isinstance(class_instance, layers.Layer):
if not class_instance._init_in_dynamic_mode:
raise RuntimeError(
" `paddle.jit.to_static` is only available in dynamic mode. Please call `paddle.disable_static()` before "
"initializing your Layer class `{}` . Because parameters of Layer class should be initialized firstly "
"in dynamic mode while applying transformation.".format(
class_instance)) | [
"def",
"_verify_init_in_dynamic_mode",
"(",
"class_instance",
")",
":",
"if",
"isinstance",
"(",
"class_instance",
",",
"layers",
".",
"Layer",
")",
":",
"if",
"not",
"class_instance",
".",
"_init_in_dynamic_mode",
":",
"raise",
"RuntimeError",
"(",
"\" `paddle.jit.... | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/dygraph/dygraph_to_static/program_translator.py#L578-L588 | ||
vtraag/leidenalg | b53366829360e10922a2dbf57eb405a516c23bc9 | setup.py | python | BuildConfiguration.replace_static_libraries | (self, only=None, exclusions=None) | Replaces references to libraries with full paths to their static
versions if the static version is to be found on the library path. | Replaces references to libraries with full paths to their static
versions if the static version is to be found on the library path. | [
"Replaces",
"references",
"to",
"libraries",
"with",
"full",
"paths",
"to",
"their",
"static",
"versions",
"if",
"the",
"static",
"version",
"is",
"to",
"be",
"found",
"on",
"the",
"library",
"path",
"."
] | def replace_static_libraries(self, only=None, exclusions=None):
"""Replaces references to libraries with full paths to their static
versions if the static version is to be found on the library path."""
building_on_windows = building_on_windows_msvc()
if not building_on_windows and "stdc++" not in self.libraries:
self.libraries.append("stdc++")
if exclusions is None:
exclusions = []
print(f"Libraries: {self.libraries}")
print(f"Exclusions: {exclusions}")
for library_name in set(self.libraries) - set(exclusions):
if only is not None and library_name not in only:
continue
static_lib = find_static_library(library_name, self.library_dirs)
if static_lib:
print(f"Found {library_name} as static library in {static_lib}.")
self.libraries.remove(library_name)
self.extra_objects.append(static_lib)
else:
print(f"Warning: could not find static library of {library_name}.") | [
"def",
"replace_static_libraries",
"(",
"self",
",",
"only",
"=",
"None",
",",
"exclusions",
"=",
"None",
")",
":",
"building_on_windows",
"=",
"building_on_windows_msvc",
"(",
")",
"if",
"not",
"building_on_windows",
"and",
"\"stdc++\"",
"not",
"in",
"self",
".... | https://github.com/vtraag/leidenalg/blob/b53366829360e10922a2dbf57eb405a516c23bc9/setup.py#L667-L690 | ||
CalcProgrammer1/OpenRGB | 8156b0167a7590dd8ba561dfde524bfcacf46b5e | dependencies/mbedtls-2.24.0/scripts/assemble_changelog.py | python | show_file_timestamps | (options) | List the files to merge and their timestamp.
This is only intended for debugging purposes. | List the files to merge and their timestamp. | [
"List",
"the",
"files",
"to",
"merge",
"and",
"their",
"timestamp",
"."
] | def show_file_timestamps(options):
"""List the files to merge and their timestamp.
This is only intended for debugging purposes.
"""
files = list_files_to_merge(options)
for filename in files:
ts = EntryFileSortKey(filename)
print(ts.category, ts.datetime, filename) | [
"def",
"show_file_timestamps",
"(",
"options",
")",
":",
"files",
"=",
"list_files_to_merge",
"(",
"options",
")",
"for",
"filename",
"in",
"files",
":",
"ts",
"=",
"EntryFileSortKey",
"(",
"filename",
")",
"print",
"(",
"ts",
".",
"category",
",",
"ts",
"... | https://github.com/CalcProgrammer1/OpenRGB/blob/8156b0167a7590dd8ba561dfde524bfcacf46b5e/dependencies/mbedtls-2.24.0/scripts/assemble_changelog.py#L451-L459 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/distribute/tpu_strategy.py | python | _set_last_step_outputs | (ctx, last_step_tensor_outputs) | Sets the last step outputs on the given context. | Sets the last step outputs on the given context. | [
"Sets",
"the",
"last",
"step",
"outputs",
"on",
"the",
"given",
"context",
"."
] | def _set_last_step_outputs(ctx, last_step_tensor_outputs):
"""Sets the last step outputs on the given context."""
# Convert replicate_outputs to the original dict structure of
# last_step_outputs.
last_step_tensor_outputs_dict = nest.pack_sequence_as(
ctx.last_step_outputs, last_step_tensor_outputs)
for name, reduce_op in ctx._last_step_outputs_reduce_ops.items(): # pylint: disable=protected-access
output = last_step_tensor_outputs_dict[name]
# For outputs that have already been reduced, take the first value
# from the list as each value should be the same. Else return the full
# list of values.
# TODO(josh11b): If reduce_op is NONE, we should return a PerReplica
# value.
if reduce_op is not None:
# TODO(priyag): Should this return the element or a list with 1 element
last_step_tensor_outputs_dict[name] = output[0]
ctx._set_last_step_outputs(last_step_tensor_outputs_dict) | [
"def",
"_set_last_step_outputs",
"(",
"ctx",
",",
"last_step_tensor_outputs",
")",
":",
"# Convert replicate_outputs to the original dict structure of",
"# last_step_outputs.",
"last_step_tensor_outputs_dict",
"=",
"nest",
".",
"pack_sequence_as",
"(",
"ctx",
".",
"last_step_outp... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/distribute/tpu_strategy.py#L727-L744 | ||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Code/Tools/waf-1.7.13/waflib/Tools/c_preproc.py | python | reduce_nums | (val_1, val_2, val_op) | return c | Apply arithmetic rules to compute a result
:param val1: input parameter
:type val1: int or string
:param val2: input parameter
:type val2: int or string
:param val_op: C operator in *+*, */*, *-*, etc
:type val_op: string
:rtype: int | Apply arithmetic rules to compute a result | [
"Apply",
"arithmetic",
"rules",
"to",
"compute",
"a",
"result"
] | def reduce_nums(val_1, val_2, val_op):
"""
Apply arithmetic rules to compute a result
:param val1: input parameter
:type val1: int or string
:param val2: input parameter
:type val2: int or string
:param val_op: C operator in *+*, */*, *-*, etc
:type val_op: string
:rtype: int
"""
#print val_1, val_2, val_op
# now perform the operation, make certain a and b are numeric
try: a = 0 + val_1
except TypeError: a = int(val_1)
try: b = 0 + val_2
except TypeError: b = int(val_2)
d = val_op
if d == '%': c = a%b
elif d=='+': c = a+b
elif d=='-': c = a-b
elif d=='*': c = a*b
elif d=='/': c = a/b
elif d=='^': c = a^b
elif d=='|': c = a|b
elif d=='||': c = int(a or b)
elif d=='&': c = a&b
elif d=='&&': c = int(a and b)
elif d=='==': c = int(a == b)
elif d=='!=': c = int(a != b)
elif d=='<=': c = int(a <= b)
elif d=='<': c = int(a < b)
elif d=='>': c = int(a > b)
elif d=='>=': c = int(a >= b)
elif d=='^': c = int(a^b)
elif d=='<<': c = a<<b
elif d=='>>': c = a>>b
else: c = 0
return c | [
"def",
"reduce_nums",
"(",
"val_1",
",",
"val_2",
",",
"val_op",
")",
":",
"#print val_1, val_2, val_op",
"# now perform the operation, make certain a and b are numeric",
"try",
":",
"a",
"=",
"0",
"+",
"val_1",
"except",
"TypeError",
":",
"a",
"=",
"int",
"(",
"v... | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/Tools/c_preproc.py#L187-L228 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/lib/format.py | python | write_array | (fp, array, version=None, allow_pickle=True, pickle_kwargs=None) | Write an array to an NPY file, including a header.
If the array is neither C-contiguous nor Fortran-contiguous AND the
file_like object is not a real file object, this function will have to
copy data in memory.
Parameters
----------
fp : file_like object
An open, writable file object, or similar object with a
``.write()`` method.
array : ndarray
The array to write to disk.
version : (int, int) or None, optional
The version number of the format. None means use the oldest
supported version that is able to store the data. Default: None
allow_pickle : bool, optional
Whether to allow writing pickled data. Default: True
pickle_kwargs : dict, optional
Additional keyword arguments to pass to pickle.dump, excluding
'protocol'. These are only useful when pickling objects in object
arrays on Python 3 to Python 2 compatible format.
Raises
------
ValueError
If the array cannot be persisted. This includes the case of
allow_pickle=False and array being an object array.
Various other errors
If the array contains Python objects as part of its dtype, the
process of pickling them may raise various errors if the objects
are not picklable. | Write an array to an NPY file, including a header. | [
"Write",
"an",
"array",
"to",
"an",
"NPY",
"file",
"including",
"a",
"header",
"."
] | def write_array(fp, array, version=None, allow_pickle=True, pickle_kwargs=None):
"""
Write an array to an NPY file, including a header.
If the array is neither C-contiguous nor Fortran-contiguous AND the
file_like object is not a real file object, this function will have to
copy data in memory.
Parameters
----------
fp : file_like object
An open, writable file object, or similar object with a
``.write()`` method.
array : ndarray
The array to write to disk.
version : (int, int) or None, optional
The version number of the format. None means use the oldest
supported version that is able to store the data. Default: None
allow_pickle : bool, optional
Whether to allow writing pickled data. Default: True
pickle_kwargs : dict, optional
Additional keyword arguments to pass to pickle.dump, excluding
'protocol'. These are only useful when pickling objects in object
arrays on Python 3 to Python 2 compatible format.
Raises
------
ValueError
If the array cannot be persisted. This includes the case of
allow_pickle=False and array being an object array.
Various other errors
If the array contains Python objects as part of its dtype, the
process of pickling them may raise various errors if the objects
are not picklable.
"""
_check_version(version)
_write_array_header(fp, header_data_from_array_1_0(array), version)
if array.itemsize == 0:
buffersize = 0
else:
# Set buffer size to 16 MiB to hide the Python loop overhead.
buffersize = max(16 * 1024 ** 2 // array.itemsize, 1)
if array.dtype.hasobject:
# We contain Python objects so we cannot write out the data
# directly. Instead, we will pickle it out
if not allow_pickle:
raise ValueError("Object arrays cannot be saved when "
"allow_pickle=False")
if pickle_kwargs is None:
pickle_kwargs = {}
pickle.dump(array, fp, protocol=3, **pickle_kwargs)
elif array.flags.f_contiguous and not array.flags.c_contiguous:
if isfileobj(fp):
array.T.tofile(fp)
else:
for chunk in numpy.nditer(
array, flags=['external_loop', 'buffered', 'zerosize_ok'],
buffersize=buffersize, order='F'):
fp.write(chunk.tobytes('C'))
else:
if isfileobj(fp):
array.tofile(fp)
else:
for chunk in numpy.nditer(
array, flags=['external_loop', 'buffered', 'zerosize_ok'],
buffersize=buffersize, order='C'):
fp.write(chunk.tobytes('C')) | [
"def",
"write_array",
"(",
"fp",
",",
"array",
",",
"version",
"=",
"None",
",",
"allow_pickle",
"=",
"True",
",",
"pickle_kwargs",
"=",
"None",
")",
":",
"_check_version",
"(",
"version",
")",
"_write_array_header",
"(",
"fp",
",",
"header_data_from_array_1_0... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/lib/format.py#L623-L692 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | DateSpan_Months | (*args, **kwargs) | return _misc_.DateSpan_Months(*args, **kwargs) | DateSpan_Months(int mon) -> DateSpan | DateSpan_Months(int mon) -> DateSpan | [
"DateSpan_Months",
"(",
"int",
"mon",
")",
"-",
">",
"DateSpan"
] | def DateSpan_Months(*args, **kwargs):
"""DateSpan_Months(int mon) -> DateSpan"""
return _misc_.DateSpan_Months(*args, **kwargs) | [
"def",
"DateSpan_Months",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DateSpan_Months",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L4768-L4770 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.