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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
google/shaka-packager | e1b0c7c45431327fd3ce193514a5407d07b39b22 | packager/third_party/protobuf/third_party/six/six.py | python | _SixMetaPathImporter.get_code | (self, fullname) | return None | Return None
Required, if is_package is implemented | Return None | [
"Return",
"None"
] | def get_code(self, fullname):
"""Return None
Required, if is_package is implemented"""
self.__get_module(fullname) # eventually raises ImportError
return None | [
"def",
"get_code",
"(",
"self",
",",
"fullname",
")",
":",
"self",
".",
"__get_module",
"(",
"fullname",
")",
"# eventually raises ImportError",
"return",
"None"
] | https://github.com/google/shaka-packager/blob/e1b0c7c45431327fd3ce193514a5407d07b39b22/packager/third_party/protobuf/third_party/six/six.py#L218-L223 | |
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPM2B_DIGEST.__init__ | (self, buffer = None) | This structure is used for a sized buffer that cannot be larger than
the largest digest produced by any hash algorithm implemented on the TPM.
Attributes:
buffer (bytes): The buffer area that can be no larger than a digest | This structure is used for a sized buffer that cannot be larger than
the largest digest produced by any hash algorithm implemented on the TPM. | [
"This",
"structure",
"is",
"used",
"for",
"a",
"sized",
"buffer",
"that",
"cannot",
"be",
"larger",
"than",
"the",
"largest",
"digest",
"produced",
"by",
"any",
"hash",
"algorithm",
"implemented",
"on",
"the",
"TPM",
"."
] | def __init__(self, buffer = None):
""" This structure is used for a sized buffer that cannot be larger than
the largest digest produced by any hash algorithm implemented on the TPM.
Attributes:
buffer (bytes): The buffer area that can be no larger than a digest
"""
self.buffer = buffer | [
"def",
"__init__",
"(",
"self",
",",
"buffer",
"=",
"None",
")",
":",
"self",
".",
"buffer",
"=",
"buffer"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L3669-L3676 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/stc.py | python | StyledTextCtrl.VCHomeRectExtend | (*args, **kwargs) | return _stc.StyledTextCtrl_VCHomeRectExtend(*args, **kwargs) | VCHomeRectExtend(self)
Move caret to before first visible character on line.
If already there move to first character on line.
In either case, extend rectangular selection to new caret position. | VCHomeRectExtend(self) | [
"VCHomeRectExtend",
"(",
"self",
")"
] | def VCHomeRectExtend(*args, **kwargs):
"""
VCHomeRectExtend(self)
Move caret to before first visible character on line.
If already there move to first character on line.
In either case, extend rectangular selection to new caret position.
"""
return _stc.StyledTextCtrl_VCHomeRectExtend(*args, **kwargs) | [
"def",
"VCHomeRectExtend",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_VCHomeRectExtend",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/stc.py#L5407-L5415 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros_comm/rosbag/src/rosbag/bag.py | python | Bag._get_entry | (self, t, connections=None) | return first_entry | Return the first index entry on/before the given time on the given connections | Return the first index entry on/before the given time on the given connections | [
"Return",
"the",
"first",
"index",
"entry",
"on",
"/",
"before",
"the",
"given",
"time",
"on",
"the",
"given",
"connections"
] | def _get_entry(self, t, connections=None):
"""
Return the first index entry on/before the given time on the given connections
"""
indexes = self._get_indexes(connections)
entry = _IndexEntry(t)
first_entry = None
for index in indexes:
i = bisect.bisect_right(index, entry) - 1
if i >= 0:
index_entry = index[i]
if first_entry is None or index_entry > first_entry:
first_entry = index_entry
return first_entry | [
"def",
"_get_entry",
"(",
"self",
",",
"t",
",",
"connections",
"=",
"None",
")",
":",
"indexes",
"=",
"self",
".",
"_get_indexes",
"(",
"connections",
")",
"entry",
"=",
"_IndexEntry",
"(",
"t",
")",
"first_entry",
"=",
"None",
"for",
"index",
"in",
"indexes",
":",
"i",
"=",
"bisect",
".",
"bisect_right",
"(",
"index",
",",
"entry",
")",
"-",
"1",
"if",
"i",
">=",
"0",
":",
"index_entry",
"=",
"index",
"[",
"i",
"]",
"if",
"first_entry",
"is",
"None",
"or",
"index_entry",
">",
"first_entry",
":",
"first_entry",
"=",
"index_entry",
"return",
"first_entry"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rosbag/src/rosbag/bag.py#L1029-L1046 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/contrib/factorization/python/ops/gmm.py | python | GMM.covariances | (self) | return tf.contrib.framework.load_variable(
self.model_dir,
gmm_ops.GmmAlgorithm.CLUSTERS_COVS_VARIABLE) | Returns the covariances. | Returns the covariances. | [
"Returns",
"the",
"covariances",
"."
] | def covariances(self):
"""Returns the covariances."""
return tf.contrib.framework.load_variable(
self.model_dir,
gmm_ops.GmmAlgorithm.CLUSTERS_COVS_VARIABLE) | [
"def",
"covariances",
"(",
"self",
")",
":",
"return",
"tf",
".",
"contrib",
".",
"framework",
".",
"load_variable",
"(",
"self",
".",
"model_dir",
",",
"gmm_ops",
".",
"GmmAlgorithm",
".",
"CLUSTERS_COVS_VARIABLE",
")"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/factorization/python/ops/gmm.py#L164-L168 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/utils/_pprint.py | python | _changed_params | (estimator) | return filtered_params | Return dict (param_name: value) of parameters that were given to
estimator with non-default values. | Return dict (param_name: value) of parameters that were given to
estimator with non-default values. | [
"Return",
"dict",
"(",
"param_name",
":",
"value",
")",
"of",
"parameters",
"that",
"were",
"given",
"to",
"estimator",
"with",
"non",
"-",
"default",
"values",
"."
] | def _changed_params(estimator):
"""Return dict (param_name: value) of parameters that were given to
estimator with non-default values."""
params = estimator.get_params(deep=False)
filtered_params = {}
init_func = getattr(estimator.__init__, 'deprecated_original',
estimator.__init__)
init_params = signature(init_func).parameters
init_params = {name: param.default for name, param in init_params.items()}
for k, v in params.items():
if (repr(v) != repr(init_params[k]) and
not (is_scalar_nan(init_params[k]) and is_scalar_nan(v))):
filtered_params[k] = v
return filtered_params | [
"def",
"_changed_params",
"(",
"estimator",
")",
":",
"params",
"=",
"estimator",
".",
"get_params",
"(",
"deep",
"=",
"False",
")",
"filtered_params",
"=",
"{",
"}",
"init_func",
"=",
"getattr",
"(",
"estimator",
".",
"__init__",
",",
"'deprecated_original'",
",",
"estimator",
".",
"__init__",
")",
"init_params",
"=",
"signature",
"(",
"init_func",
")",
".",
"parameters",
"init_params",
"=",
"{",
"name",
":",
"param",
".",
"default",
"for",
"name",
",",
"param",
"in",
"init_params",
".",
"items",
"(",
")",
"}",
"for",
"k",
",",
"v",
"in",
"params",
".",
"items",
"(",
")",
":",
"if",
"(",
"repr",
"(",
"v",
")",
"!=",
"repr",
"(",
"init_params",
"[",
"k",
"]",
")",
"and",
"not",
"(",
"is_scalar_nan",
"(",
"init_params",
"[",
"k",
"]",
")",
"and",
"is_scalar_nan",
"(",
"v",
")",
")",
")",
":",
"filtered_params",
"[",
"k",
"]",
"=",
"v",
"return",
"filtered_params"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/utils/_pprint.py#L87-L101 | |
BitMEX/api-connectors | 37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812 | auto-generated/python/swagger_client/models/position.py | python | Position.prev_close_price | (self, prev_close_price) | Sets the prev_close_price of this Position.
:param prev_close_price: The prev_close_price of this Position. # noqa: E501
:type: float | Sets the prev_close_price of this Position. | [
"Sets",
"the",
"prev_close_price",
"of",
"this",
"Position",
"."
] | def prev_close_price(self, prev_close_price):
"""Sets the prev_close_price of this Position.
:param prev_close_price: The prev_close_price of this Position. # noqa: E501
:type: float
"""
self._prev_close_price = prev_close_price | [
"def",
"prev_close_price",
"(",
"self",
",",
"prev_close_price",
")",
":",
"self",
".",
"_prev_close_price",
"=",
"prev_close_price"
] | https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/position.py#L829-L837 | ||
simsong/bulk_extractor | 738911df22b7066ca9e1662f4131fb44090a4196 | python/dfxml.py | python | extentdb.add | (self,extent) | Adds an EXTENT (start,length) to the database.
Raises ValueError if there is an intersection. | Adds an EXTENT (start,length) to the database.
Raises ValueError if there is an intersection. | [
"Adds",
"an",
"EXTENT",
"(",
"start",
"length",
")",
"to",
"the",
"database",
".",
"Raises",
"ValueError",
"if",
"there",
"is",
"an",
"intersection",
"."
] | def add(self,extent):
"""Adds an EXTENT (start,length) to the database.
Raises ValueError if there is an intersection."""
v = self.intersects(extent)
if v:
raise ValueError("Cannot add "+str(extent)+": it intersects "+str(v))
self.db.append(extent) | [
"def",
"add",
"(",
"self",
",",
"extent",
")",
":",
"v",
"=",
"self",
".",
"intersects",
"(",
"extent",
")",
"if",
"v",
":",
"raise",
"ValueError",
"(",
"\"Cannot add \"",
"+",
"str",
"(",
"extent",
")",
"+",
"\": it intersects \"",
"+",
"str",
"(",
"v",
")",
")",
"self",
".",
"db",
".",
"append",
"(",
"extent",
")"
] | https://github.com/simsong/bulk_extractor/blob/738911df22b7066ca9e1662f4131fb44090a4196/python/dfxml.py#L1449-L1455 | ||
udacity/CarND-MPC-Project | 5d5d9c55b1b11cfdcf73b0c74b97211fc3566531 | src/Eigen-3.3/debug/gdb/printers.py | python | EigenMatrixPrinter.__init__ | (self, variety, val) | Extract all the necessary information | Extract all the necessary information | [
"Extract",
"all",
"the",
"necessary",
"information"
] | def __init__(self, variety, val):
"Extract all the necessary information"
# Save the variety (presumably "Matrix" or "Array") for later usage
self.variety = variety
# The gdb extension does not support value template arguments - need to extract them by hand
type = val.type
if type.code == gdb.TYPE_CODE_REF:
type = type.target()
self.type = type.unqualified().strip_typedefs()
tag = self.type.tag
regex = re.compile('\<.*\>')
m = regex.findall(tag)[0][1:-1]
template_params = m.split(',')
template_params = [x.replace(" ", "") for x in template_params]
if template_params[1] == '-0x00000000000000001' or template_params[1] == '-0x000000001' or template_params[1] == '-1':
self.rows = val['m_storage']['m_rows']
else:
self.rows = int(template_params[1])
if template_params[2] == '-0x00000000000000001' or template_params[2] == '-0x000000001' or template_params[2] == '-1':
self.cols = val['m_storage']['m_cols']
else:
self.cols = int(template_params[2])
self.options = 0 # default value
if len(template_params) > 3:
self.options = template_params[3];
self.rowMajor = (int(self.options) & 0x1)
self.innerType = self.type.template_argument(0)
self.val = val
# Fixed size matrices have a struct as their storage, so we need to walk through this
self.data = self.val['m_storage']['m_data']
if self.data.type.code == gdb.TYPE_CODE_STRUCT:
self.data = self.data['array']
self.data = self.data.cast(self.innerType.pointer()) | [
"def",
"__init__",
"(",
"self",
",",
"variety",
",",
"val",
")",
":",
"# Save the variety (presumably \"Matrix\" or \"Array\") for later usage",
"self",
".",
"variety",
"=",
"variety",
"# The gdb extension does not support value template arguments - need to extract them by hand",
"type",
"=",
"val",
".",
"type",
"if",
"type",
".",
"code",
"==",
"gdb",
".",
"TYPE_CODE_REF",
":",
"type",
"=",
"type",
".",
"target",
"(",
")",
"self",
".",
"type",
"=",
"type",
".",
"unqualified",
"(",
")",
".",
"strip_typedefs",
"(",
")",
"tag",
"=",
"self",
".",
"type",
".",
"tag",
"regex",
"=",
"re",
".",
"compile",
"(",
"'\\<.*\\>'",
")",
"m",
"=",
"regex",
".",
"findall",
"(",
"tag",
")",
"[",
"0",
"]",
"[",
"1",
":",
"-",
"1",
"]",
"template_params",
"=",
"m",
".",
"split",
"(",
"','",
")",
"template_params",
"=",
"[",
"x",
".",
"replace",
"(",
"\" \"",
",",
"\"\"",
")",
"for",
"x",
"in",
"template_params",
"]",
"if",
"template_params",
"[",
"1",
"]",
"==",
"'-0x00000000000000001'",
"or",
"template_params",
"[",
"1",
"]",
"==",
"'-0x000000001'",
"or",
"template_params",
"[",
"1",
"]",
"==",
"'-1'",
":",
"self",
".",
"rows",
"=",
"val",
"[",
"'m_storage'",
"]",
"[",
"'m_rows'",
"]",
"else",
":",
"self",
".",
"rows",
"=",
"int",
"(",
"template_params",
"[",
"1",
"]",
")",
"if",
"template_params",
"[",
"2",
"]",
"==",
"'-0x00000000000000001'",
"or",
"template_params",
"[",
"2",
"]",
"==",
"'-0x000000001'",
"or",
"template_params",
"[",
"2",
"]",
"==",
"'-1'",
":",
"self",
".",
"cols",
"=",
"val",
"[",
"'m_storage'",
"]",
"[",
"'m_cols'",
"]",
"else",
":",
"self",
".",
"cols",
"=",
"int",
"(",
"template_params",
"[",
"2",
"]",
")",
"self",
".",
"options",
"=",
"0",
"# default value",
"if",
"len",
"(",
"template_params",
")",
">",
"3",
":",
"self",
".",
"options",
"=",
"template_params",
"[",
"3",
"]",
"self",
".",
"rowMajor",
"=",
"(",
"int",
"(",
"self",
".",
"options",
")",
"&",
"0x1",
")",
"self",
".",
"innerType",
"=",
"self",
".",
"type",
".",
"template_argument",
"(",
"0",
")",
"self",
".",
"val",
"=",
"val",
"# Fixed size matrices have a struct as their storage, so we need to walk through this",
"self",
".",
"data",
"=",
"self",
".",
"val",
"[",
"'m_storage'",
"]",
"[",
"'m_data'",
"]",
"if",
"self",
".",
"data",
".",
"type",
".",
"code",
"==",
"gdb",
".",
"TYPE_CODE_STRUCT",
":",
"self",
".",
"data",
"=",
"self",
".",
"data",
"[",
"'array'",
"]",
"self",
".",
"data",
"=",
"self",
".",
"data",
".",
"cast",
"(",
"self",
".",
"innerType",
".",
"pointer",
"(",
")",
")"
] | https://github.com/udacity/CarND-MPC-Project/blob/5d5d9c55b1b11cfdcf73b0c74b97211fc3566531/src/Eigen-3.3/debug/gdb/printers.py#L37-L78 | ||
facebookresearch/habitat-sim | 63b6c71d9ca8adaefb140b198196f5d0ca1f1e34 | examples/motion_viewer.py | python | FairmotionSimInteractiveViewer.navmesh_config_and_recompute | (self) | Overwrite the NavMesh function to compute more restricted bounds for character. | Overwrite the NavMesh function to compute more restricted bounds for character. | [
"Overwrite",
"the",
"NavMesh",
"function",
"to",
"compute",
"more",
"restricted",
"bounds",
"for",
"character",
"."
] | def navmesh_config_and_recompute(self) -> None:
"""
Overwrite the NavMesh function to compute more restricted bounds for character.
"""
art_obj_mgr, art_cache = self.sim.get_articulated_object_manager(), {}
rgd_obj_mgr, rgd_cache = self.sim.get_rigid_object_manager(), {}
# Setting all articulated objects to static
for obj_handle in art_obj_mgr.get_object_handles():
# save original motion type
art_cache[obj_handle] = art_obj_mgr.get_object_by_handle(
obj_handle
).motion_type
# setting object motion_type to static
art_obj_mgr.get_object_by_handle(
obj_handle
).motion_type = phy.MotionType.STATIC
# Setting all rigid objects to static
for obj_handle in rgd_obj_mgr.get_object_handles():
# save original motion type
rgd_cache[obj_handle] = rgd_obj_mgr.get_object_by_handle(
obj_handle
).motion_type
# setting object motion_type to static
rgd_obj_mgr.get_object_by_handle(
obj_handle
).motion_type = phy.MotionType.STATIC
# compute NavMesh to be wary of Scene Objects
self.navmesh_settings = habitat_sim.NavMeshSettings()
self.navmesh_settings.set_defaults()
self.navmesh_settings.agent_radius = 0.30
self.sim.recompute_navmesh(
self.sim.pathfinder,
self.navmesh_settings,
include_static_objects=True,
)
# Set all articulated objects back to original motion_type
for obj_handle in art_obj_mgr.get_object_handles():
art_obj_mgr.get_object_by_handle(obj_handle).motion_type = art_cache[
obj_handle
]
# Set all rigid objects back to original motion_type
for obj_handle in rgd_obj_mgr.get_object_handles():
rgd_obj_mgr.get_object_by_handle(obj_handle).motion_type = rgd_cache[
obj_handle
] | [
"def",
"navmesh_config_and_recompute",
"(",
"self",
")",
"->",
"None",
":",
"art_obj_mgr",
",",
"art_cache",
"=",
"self",
".",
"sim",
".",
"get_articulated_object_manager",
"(",
")",
",",
"{",
"}",
"rgd_obj_mgr",
",",
"rgd_cache",
"=",
"self",
".",
"sim",
".",
"get_rigid_object_manager",
"(",
")",
",",
"{",
"}",
"# Setting all articulated objects to static",
"for",
"obj_handle",
"in",
"art_obj_mgr",
".",
"get_object_handles",
"(",
")",
":",
"# save original motion type",
"art_cache",
"[",
"obj_handle",
"]",
"=",
"art_obj_mgr",
".",
"get_object_by_handle",
"(",
"obj_handle",
")",
".",
"motion_type",
"# setting object motion_type to static",
"art_obj_mgr",
".",
"get_object_by_handle",
"(",
"obj_handle",
")",
".",
"motion_type",
"=",
"phy",
".",
"MotionType",
".",
"STATIC",
"# Setting all rigid objects to static",
"for",
"obj_handle",
"in",
"rgd_obj_mgr",
".",
"get_object_handles",
"(",
")",
":",
"# save original motion type",
"rgd_cache",
"[",
"obj_handle",
"]",
"=",
"rgd_obj_mgr",
".",
"get_object_by_handle",
"(",
"obj_handle",
")",
".",
"motion_type",
"# setting object motion_type to static",
"rgd_obj_mgr",
".",
"get_object_by_handle",
"(",
"obj_handle",
")",
".",
"motion_type",
"=",
"phy",
".",
"MotionType",
".",
"STATIC",
"# compute NavMesh to be wary of Scene Objects",
"self",
".",
"navmesh_settings",
"=",
"habitat_sim",
".",
"NavMeshSettings",
"(",
")",
"self",
".",
"navmesh_settings",
".",
"set_defaults",
"(",
")",
"self",
".",
"navmesh_settings",
".",
"agent_radius",
"=",
"0.30",
"self",
".",
"sim",
".",
"recompute_navmesh",
"(",
"self",
".",
"sim",
".",
"pathfinder",
",",
"self",
".",
"navmesh_settings",
",",
"include_static_objects",
"=",
"True",
",",
")",
"# Set all articulated objects back to original motion_type",
"for",
"obj_handle",
"in",
"art_obj_mgr",
".",
"get_object_handles",
"(",
")",
":",
"art_obj_mgr",
".",
"get_object_by_handle",
"(",
"obj_handle",
")",
".",
"motion_type",
"=",
"art_cache",
"[",
"obj_handle",
"]",
"# Set all rigid objects back to original motion_type",
"for",
"obj_handle",
"in",
"rgd_obj_mgr",
".",
"get_object_handles",
"(",
")",
":",
"rgd_obj_mgr",
".",
"get_object_by_handle",
"(",
"obj_handle",
")",
".",
"motion_type",
"=",
"rgd_cache",
"[",
"obj_handle",
"]"
] | https://github.com/facebookresearch/habitat-sim/blob/63b6c71d9ca8adaefb140b198196f5d0ca1f1e34/examples/motion_viewer.py#L552-L603 | ||
Ewenwan/MVision | 97b394dfa48cb21c82cd003b1a952745e413a17f | deepLearning/03_cnn.py | python | ConvLayer.__init__ | (self, inpt, filter_shape, strides=(1, 1, 1, 1),
padding="SAME", activation=tf.nn.relu, bias_setting=True) | inpt: tf.Tensor, shape [n_examples, witdth, height, channels]
filter_shape: list or tuple, [witdth, height. channels, filter_nums]
strides: list or tuple, the step of filter
padding:
activation:
bias_setting: | inpt: tf.Tensor, shape [n_examples, witdth, height, channels]
filter_shape: list or tuple, [witdth, height. channels, filter_nums]
strides: list or tuple, the step of filter
padding:
activation:
bias_setting: | [
"inpt",
":",
"tf",
".",
"Tensor",
"shape",
"[",
"n_examples",
"witdth",
"height",
"channels",
"]",
"filter_shape",
":",
"list",
"or",
"tuple",
"[",
"witdth",
"height",
".",
"channels",
"filter_nums",
"]",
"strides",
":",
"list",
"or",
"tuple",
"the",
"step",
"of",
"filter",
"padding",
":",
"activation",
":",
"bias_setting",
":"
] | def __init__(self, inpt, filter_shape, strides=(1, 1, 1, 1),
padding="SAME", activation=tf.nn.relu, bias_setting=True):
"""
inpt: tf.Tensor, shape [n_examples, witdth, height, channels]
filter_shape: list or tuple, [witdth, height. channels, filter_nums]
strides: list or tuple, the step of filter
padding:
activation:
bias_setting:
"""
self.input = inpt
# initializes the filter
self.W = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), dtype=tf.float32)
if bias_setting:
self.b = tf.Variable(tf.truncated_normal(filter_shape[-1:], stddev=0.1),
dtype=tf.float32)
else:
self.b = None
conv_output = tf.nn.conv2d(self.input, filter=self.W, strides=strides,
padding=padding)
conv_output = conv_output + self.b if self.b is not None else conv_output
# the output
self.output = conv_output if activation is None else activation(conv_output)
# the params
self.params = [self.W, self.b] if self.b is not None else [self.W, ] | [
"def",
"__init__",
"(",
"self",
",",
"inpt",
",",
"filter_shape",
",",
"strides",
"=",
"(",
"1",
",",
"1",
",",
"1",
",",
"1",
")",
",",
"padding",
"=",
"\"SAME\"",
",",
"activation",
"=",
"tf",
".",
"nn",
".",
"relu",
",",
"bias_setting",
"=",
"True",
")",
":",
"self",
".",
"input",
"=",
"inpt",
"# initializes the filter",
"self",
".",
"W",
"=",
"tf",
".",
"Variable",
"(",
"tf",
".",
"truncated_normal",
"(",
"filter_shape",
",",
"stddev",
"=",
"0.1",
")",
",",
"dtype",
"=",
"tf",
".",
"float32",
")",
"if",
"bias_setting",
":",
"self",
".",
"b",
"=",
"tf",
".",
"Variable",
"(",
"tf",
".",
"truncated_normal",
"(",
"filter_shape",
"[",
"-",
"1",
":",
"]",
",",
"stddev",
"=",
"0.1",
")",
",",
"dtype",
"=",
"tf",
".",
"float32",
")",
"else",
":",
"self",
".",
"b",
"=",
"None",
"conv_output",
"=",
"tf",
".",
"nn",
".",
"conv2d",
"(",
"self",
".",
"input",
",",
"filter",
"=",
"self",
".",
"W",
",",
"strides",
"=",
"strides",
",",
"padding",
"=",
"padding",
")",
"conv_output",
"=",
"conv_output",
"+",
"self",
".",
"b",
"if",
"self",
".",
"b",
"is",
"not",
"None",
"else",
"conv_output",
"# the output",
"self",
".",
"output",
"=",
"conv_output",
"if",
"activation",
"is",
"None",
"else",
"activation",
"(",
"conv_output",
")",
"# the params",
"self",
".",
"params",
"=",
"[",
"self",
".",
"W",
",",
"self",
".",
"b",
"]",
"if",
"self",
".",
"b",
"is",
"not",
"None",
"else",
"[",
"self",
".",
"W",
",",
"]"
] | https://github.com/Ewenwan/MVision/blob/97b394dfa48cb21c82cd003b1a952745e413a17f/deepLearning/03_cnn.py#L17-L41 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/learn/python/learn/dataframe/dataframe.py | python | DataFrame.assign | (self, **kwargs) | Adds columns to DataFrame.
Args:
**kwargs: assignments of the form key=value where key is a string
and value is an `inflow.Series`, a `pandas.Series` or a numpy array.
Raises:
TypeError: keys are not strings.
TypeError: values are not `inflow.Series`, `pandas.Series` or
`numpy.ndarray`.
TODO(jamieas): pandas assign method returns a new DataFrame. Consider
switching to this behavior, changing the name or adding in_place as an
argument. | Adds columns to DataFrame. | [
"Adds",
"columns",
"to",
"DataFrame",
"."
] | def assign(self, **kwargs):
"""Adds columns to DataFrame.
Args:
**kwargs: assignments of the form key=value where key is a string
and value is an `inflow.Series`, a `pandas.Series` or a numpy array.
Raises:
TypeError: keys are not strings.
TypeError: values are not `inflow.Series`, `pandas.Series` or
`numpy.ndarray`.
TODO(jamieas): pandas assign method returns a new DataFrame. Consider
switching to this behavior, changing the name or adding in_place as an
argument.
"""
for k, v in kwargs.items():
if not isinstance(k, str):
raise TypeError("The only supported type for keys is string; got %s" %
type(k))
if isinstance(v, Series):
s = v
elif isinstance(v, Transform) and v.input_valency() == 0:
s = v()
# TODO(jamieas): hook up these special cases again
# TODO(soergel): can these special cases be generalized?
# elif isinstance(v, pd.Series):
# s = series.NumpySeries(v.values)
# elif isinstance(v, np.ndarray):
# s = series.NumpySeries(v)
else:
raise TypeError(
"Column in assignment must be an inflow.Series, pandas.Series or a"
" numpy array; got type '%s'." % type(v).__name__)
self._columns[k] = s | [
"def",
"assign",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"k",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"The only supported type for keys is string; got %s\"",
"%",
"type",
"(",
"k",
")",
")",
"if",
"isinstance",
"(",
"v",
",",
"Series",
")",
":",
"s",
"=",
"v",
"elif",
"isinstance",
"(",
"v",
",",
"Transform",
")",
"and",
"v",
".",
"input_valency",
"(",
")",
"==",
"0",
":",
"s",
"=",
"v",
"(",
")",
"# TODO(jamieas): hook up these special cases again",
"# TODO(soergel): can these special cases be generalized?",
"# elif isinstance(v, pd.Series):",
"# s = series.NumpySeries(v.values)",
"# elif isinstance(v, np.ndarray):",
"# s = series.NumpySeries(v)",
"else",
":",
"raise",
"TypeError",
"(",
"\"Column in assignment must be an inflow.Series, pandas.Series or a\"",
"\" numpy array; got type '%s'.\"",
"%",
"type",
"(",
"v",
")",
".",
"__name__",
")",
"self",
".",
"_columns",
"[",
"k",
"]",
"=",
"s"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/learn/python/learn/dataframe/dataframe.py#L42-L76 | ||
geemaple/leetcode | 68bc5032e1ee52c22ef2f2e608053484c487af54 | leetcode/426.convert-binary-search-tree-to-sorted-doubly-linked-list.py | python | Solution.treeToDoublyList | (self, root) | return self.head.right | :type root: Node
:rtype: Node | :type root: Node
:rtype: Node | [
":",
"type",
"root",
":",
"Node",
":",
"rtype",
":",
"Node"
] | def treeToDoublyList(self, root):
"""
:type root: Node
:rtype: Node
"""
if root is None:
return root
self.helper(root)
self.head.right.left.right = self.head.right
return self.head.right | [
"def",
"treeToDoublyList",
"(",
"self",
",",
"root",
")",
":",
"if",
"root",
"is",
"None",
":",
"return",
"root",
"self",
".",
"helper",
"(",
"root",
")",
"self",
".",
"head",
".",
"right",
".",
"left",
".",
"right",
"=",
"self",
".",
"head",
".",
"right",
"return",
"self",
".",
"head",
".",
"right"
] | https://github.com/geemaple/leetcode/blob/68bc5032e1ee52c22ef2f2e608053484c487af54/leetcode/426.convert-binary-search-tree-to-sorted-doubly-linked-list.py#L29-L41 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/SANS/SANSUtility.py | python | ConvertToSpecList | (maskstring, firstspec, dimension, orientation) | return speclist | Compile spectra ID list | Compile spectra ID list | [
"Compile",
"spectra",
"ID",
"list"
] | def ConvertToSpecList(maskstring, firstspec, dimension, orientation):
'''Compile spectra ID list'''
if maskstring == '':
return ''
masklist = maskstring.split(',')
speclist = ''
for x in masklist:
x = x.lower()
if '+' in x:
bigPieces = x.split('+')
if '>' in bigPieces[0]:
pieces = bigPieces[0].split('>')
low = int(pieces[0].lstrip('hv'))
upp = int(pieces[1].lstrip('hv'))
else:
low = int(bigPieces[0].lstrip('hv'))
upp = low
if '>' in bigPieces[1]:
pieces = bigPieces[1].split('>')
low2 = int(pieces[0].lstrip('hv'))
upp2 = int(pieces[1].lstrip('hv'))
else:
low2 = int(bigPieces[1].lstrip('hv'))
upp2 = low2
if 'h' in bigPieces[0] and 'v' in bigPieces[1]:
ydim=abs(upp-low)+1
xdim=abs(upp2-low2)+1
speclist += spectrumBlock(firstspec,low, low2,ydim, xdim, dimension,orientation) + ','
elif 'v' in bigPieces[0] and 'h' in bigPieces[1]:
xdim=abs(upp-low)+1
ydim=abs(upp2-low2)+1
speclist += spectrumBlock(firstspec,low2, low,nstrips, dimension, dimension,orientation)+ ','
else:
print("error in mask, ignored: " + x)
elif '>' in x:
pieces = x.split('>')
low = int(pieces[0].lstrip('hvs'))
upp = int(pieces[1].lstrip('hvs'))
if 'h' in pieces[0]:
nstrips = abs(upp - low) + 1
speclist += spectrumBlock(firstspec,low, 0,nstrips, dimension, dimension,orientation) + ','
elif 'v' in pieces[0]:
nstrips = abs(upp - low) + 1
speclist += spectrumBlock(firstspec,0,low, dimension, nstrips, dimension,orientation) + ','
else:
for i in range(low, upp + 1):
speclist += str(i) + ','
elif 'h' in x:
speclist += spectrumBlock(firstspec,int(x.lstrip('h')), 0,1, dimension, dimension,orientation) + ','
elif 'v' in x:
speclist += spectrumBlock(firstspec,0,int(x.lstrip('v')), dimension, 1, dimension,orientation) + ','
else:
speclist += x.lstrip('s') + ','
return speclist | [
"def",
"ConvertToSpecList",
"(",
"maskstring",
",",
"firstspec",
",",
"dimension",
",",
"orientation",
")",
":",
"if",
"maskstring",
"==",
"''",
":",
"return",
"''",
"masklist",
"=",
"maskstring",
".",
"split",
"(",
"','",
")",
"speclist",
"=",
"''",
"for",
"x",
"in",
"masklist",
":",
"x",
"=",
"x",
".",
"lower",
"(",
")",
"if",
"'+'",
"in",
"x",
":",
"bigPieces",
"=",
"x",
".",
"split",
"(",
"'+'",
")",
"if",
"'>'",
"in",
"bigPieces",
"[",
"0",
"]",
":",
"pieces",
"=",
"bigPieces",
"[",
"0",
"]",
".",
"split",
"(",
"'>'",
")",
"low",
"=",
"int",
"(",
"pieces",
"[",
"0",
"]",
".",
"lstrip",
"(",
"'hv'",
")",
")",
"upp",
"=",
"int",
"(",
"pieces",
"[",
"1",
"]",
".",
"lstrip",
"(",
"'hv'",
")",
")",
"else",
":",
"low",
"=",
"int",
"(",
"bigPieces",
"[",
"0",
"]",
".",
"lstrip",
"(",
"'hv'",
")",
")",
"upp",
"=",
"low",
"if",
"'>'",
"in",
"bigPieces",
"[",
"1",
"]",
":",
"pieces",
"=",
"bigPieces",
"[",
"1",
"]",
".",
"split",
"(",
"'>'",
")",
"low2",
"=",
"int",
"(",
"pieces",
"[",
"0",
"]",
".",
"lstrip",
"(",
"'hv'",
")",
")",
"upp2",
"=",
"int",
"(",
"pieces",
"[",
"1",
"]",
".",
"lstrip",
"(",
"'hv'",
")",
")",
"else",
":",
"low2",
"=",
"int",
"(",
"bigPieces",
"[",
"1",
"]",
".",
"lstrip",
"(",
"'hv'",
")",
")",
"upp2",
"=",
"low2",
"if",
"'h'",
"in",
"bigPieces",
"[",
"0",
"]",
"and",
"'v'",
"in",
"bigPieces",
"[",
"1",
"]",
":",
"ydim",
"=",
"abs",
"(",
"upp",
"-",
"low",
")",
"+",
"1",
"xdim",
"=",
"abs",
"(",
"upp2",
"-",
"low2",
")",
"+",
"1",
"speclist",
"+=",
"spectrumBlock",
"(",
"firstspec",
",",
"low",
",",
"low2",
",",
"ydim",
",",
"xdim",
",",
"dimension",
",",
"orientation",
")",
"+",
"','",
"elif",
"'v'",
"in",
"bigPieces",
"[",
"0",
"]",
"and",
"'h'",
"in",
"bigPieces",
"[",
"1",
"]",
":",
"xdim",
"=",
"abs",
"(",
"upp",
"-",
"low",
")",
"+",
"1",
"ydim",
"=",
"abs",
"(",
"upp2",
"-",
"low2",
")",
"+",
"1",
"speclist",
"+=",
"spectrumBlock",
"(",
"firstspec",
",",
"low2",
",",
"low",
",",
"nstrips",
",",
"dimension",
",",
"dimension",
",",
"orientation",
")",
"+",
"','",
"else",
":",
"print",
"(",
"\"error in mask, ignored: \"",
"+",
"x",
")",
"elif",
"'>'",
"in",
"x",
":",
"pieces",
"=",
"x",
".",
"split",
"(",
"'>'",
")",
"low",
"=",
"int",
"(",
"pieces",
"[",
"0",
"]",
".",
"lstrip",
"(",
"'hvs'",
")",
")",
"upp",
"=",
"int",
"(",
"pieces",
"[",
"1",
"]",
".",
"lstrip",
"(",
"'hvs'",
")",
")",
"if",
"'h'",
"in",
"pieces",
"[",
"0",
"]",
":",
"nstrips",
"=",
"abs",
"(",
"upp",
"-",
"low",
")",
"+",
"1",
"speclist",
"+=",
"spectrumBlock",
"(",
"firstspec",
",",
"low",
",",
"0",
",",
"nstrips",
",",
"dimension",
",",
"dimension",
",",
"orientation",
")",
"+",
"','",
"elif",
"'v'",
"in",
"pieces",
"[",
"0",
"]",
":",
"nstrips",
"=",
"abs",
"(",
"upp",
"-",
"low",
")",
"+",
"1",
"speclist",
"+=",
"spectrumBlock",
"(",
"firstspec",
",",
"0",
",",
"low",
",",
"dimension",
",",
"nstrips",
",",
"dimension",
",",
"orientation",
")",
"+",
"','",
"else",
":",
"for",
"i",
"in",
"range",
"(",
"low",
",",
"upp",
"+",
"1",
")",
":",
"speclist",
"+=",
"str",
"(",
"i",
")",
"+",
"','",
"elif",
"'h'",
"in",
"x",
":",
"speclist",
"+=",
"spectrumBlock",
"(",
"firstspec",
",",
"int",
"(",
"x",
".",
"lstrip",
"(",
"'h'",
")",
")",
",",
"0",
",",
"1",
",",
"dimension",
",",
"dimension",
",",
"orientation",
")",
"+",
"','",
"elif",
"'v'",
"in",
"x",
":",
"speclist",
"+=",
"spectrumBlock",
"(",
"firstspec",
",",
"0",
",",
"int",
"(",
"x",
".",
"lstrip",
"(",
"'v'",
")",
")",
",",
"dimension",
",",
"1",
",",
"dimension",
",",
"orientation",
")",
"+",
"','",
"else",
":",
"speclist",
"+=",
"x",
".",
"lstrip",
"(",
"'s'",
")",
"+",
"','",
"return",
"speclist"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/SANSUtility.py#L2214-L2268 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/syntax/syntax.py | python | SynExtensionDelegate.GetXmlObject | (self) | return self._xml | Get the xml object
@return: EditraXml instance | Get the xml object
@return: EditraXml instance | [
"Get",
"the",
"xml",
"object",
"@return",
":",
"EditraXml",
"instance"
] | def GetXmlObject(self):
"""Get the xml object
@return: EditraXml instance
"""
return self._xml | [
"def",
"GetXmlObject",
"(",
"self",
")",
":",
"return",
"self",
".",
"_xml"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/syntax/syntax.py#L291-L296 | |
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBBlock.GetSibling | (self) | return _lldb.SBBlock_GetSibling(self) | GetSibling(SBBlock self) -> SBBlock
Get the sibling block for this block. | GetSibling(SBBlock self) -> SBBlock | [
"GetSibling",
"(",
"SBBlock",
"self",
")",
"-",
">",
"SBBlock"
] | def GetSibling(self):
"""
GetSibling(SBBlock self) -> SBBlock
Get the sibling block for this block.
"""
return _lldb.SBBlock_GetSibling(self) | [
"def",
"GetSibling",
"(",
"self",
")",
":",
"return",
"_lldb",
".",
"SBBlock_GetSibling",
"(",
"self",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L1315-L1321 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | FileSystem.ChangePathTo | (*args, **kwargs) | return _core_.FileSystem_ChangePathTo(*args, **kwargs) | ChangePathTo(self, String location, bool is_dir=False) | ChangePathTo(self, String location, bool is_dir=False) | [
"ChangePathTo",
"(",
"self",
"String",
"location",
"bool",
"is_dir",
"=",
"False",
")"
] | def ChangePathTo(*args, **kwargs):
"""ChangePathTo(self, String location, bool is_dir=False)"""
return _core_.FileSystem_ChangePathTo(*args, **kwargs) | [
"def",
"ChangePathTo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"FileSystem_ChangePathTo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L2416-L2418 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/base.py | python | SelectionMixin._gotitem | (self, key, ndim, subset=None) | sub-classes to define
return a sliced object
Parameters
----------
key : string / list of selections
ndim : 1,2
requested ndim of result
subset : object, default None
subset to act on | sub-classes to define
return a sliced object | [
"sub",
"-",
"classes",
"to",
"define",
"return",
"a",
"sliced",
"object"
] | def _gotitem(self, key, ndim, subset=None):
"""
sub-classes to define
return a sliced object
Parameters
----------
key : string / list of selections
ndim : 1,2
requested ndim of result
subset : object, default None
subset to act on
"""
raise AbstractMethodError(self) | [
"def",
"_gotitem",
"(",
"self",
",",
"key",
",",
"ndim",
",",
"subset",
"=",
"None",
")",
":",
"raise",
"AbstractMethodError",
"(",
"self",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/base.py#L233-L247 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/web-page-replay/third_party/dns/message.py | python | Message.find_rrset | (self, section, name, rdclass, rdtype,
covers=dns.rdatatype.NONE, deleting=None, create=False,
force_unique=False) | return rrset | Find the RRset with the given attributes in the specified section.
@param section: the section of the message to look in, e.g.
self.answer.
@type section: list of dns.rrset.RRset objects
@param name: the name of the RRset
@type name: dns.name.Name object
@param rdclass: the class of the RRset
@type rdclass: int
@param rdtype: the type of the RRset
@type rdtype: int
@param covers: the covers value of the RRset
@type covers: int
@param deleting: the deleting value of the RRset
@type deleting: int
@param create: If True, create the RRset if it is not found.
The created RRset is appended to I{section}.
@type create: bool
@param force_unique: If True and create is also True, create a
new RRset regardless of whether a matching RRset exists already.
@type force_unique: bool
@raises KeyError: the RRset was not found and create was False
@rtype: dns.rrset.RRset object | Find the RRset with the given attributes in the specified section. | [
"Find",
"the",
"RRset",
"with",
"the",
"given",
"attributes",
"in",
"the",
"specified",
"section",
"."
] | def find_rrset(self, section, name, rdclass, rdtype,
covers=dns.rdatatype.NONE, deleting=None, create=False,
force_unique=False):
"""Find the RRset with the given attributes in the specified section.
@param section: the section of the message to look in, e.g.
self.answer.
@type section: list of dns.rrset.RRset objects
@param name: the name of the RRset
@type name: dns.name.Name object
@param rdclass: the class of the RRset
@type rdclass: int
@param rdtype: the type of the RRset
@type rdtype: int
@param covers: the covers value of the RRset
@type covers: int
@param deleting: the deleting value of the RRset
@type deleting: int
@param create: If True, create the RRset if it is not found.
The created RRset is appended to I{section}.
@type create: bool
@param force_unique: If True and create is also True, create a
new RRset regardless of whether a matching RRset exists already.
@type force_unique: bool
@raises KeyError: the RRset was not found and create was False
@rtype: dns.rrset.RRset object"""
key = (self.section_number(section),
name, rdclass, rdtype, covers, deleting)
if not force_unique:
if not self.index is None:
rrset = self.index.get(key)
if not rrset is None:
return rrset
else:
for rrset in section:
if rrset.match(name, rdclass, rdtype, covers, deleting):
return rrset
if not create:
raise KeyError
rrset = dns.rrset.RRset(name, rdclass, rdtype, covers, deleting)
section.append(rrset)
if not self.index is None:
self.index[key] = rrset
return rrset | [
"def",
"find_rrset",
"(",
"self",
",",
"section",
",",
"name",
",",
"rdclass",
",",
"rdtype",
",",
"covers",
"=",
"dns",
".",
"rdatatype",
".",
"NONE",
",",
"deleting",
"=",
"None",
",",
"create",
"=",
"False",
",",
"force_unique",
"=",
"False",
")",
":",
"key",
"=",
"(",
"self",
".",
"section_number",
"(",
"section",
")",
",",
"name",
",",
"rdclass",
",",
"rdtype",
",",
"covers",
",",
"deleting",
")",
"if",
"not",
"force_unique",
":",
"if",
"not",
"self",
".",
"index",
"is",
"None",
":",
"rrset",
"=",
"self",
".",
"index",
".",
"get",
"(",
"key",
")",
"if",
"not",
"rrset",
"is",
"None",
":",
"return",
"rrset",
"else",
":",
"for",
"rrset",
"in",
"section",
":",
"if",
"rrset",
".",
"match",
"(",
"name",
",",
"rdclass",
",",
"rdtype",
",",
"covers",
",",
"deleting",
")",
":",
"return",
"rrset",
"if",
"not",
"create",
":",
"raise",
"KeyError",
"rrset",
"=",
"dns",
".",
"rrset",
".",
"RRset",
"(",
"name",
",",
"rdclass",
",",
"rdtype",
",",
"covers",
",",
"deleting",
")",
"section",
".",
"append",
"(",
"rrset",
")",
"if",
"not",
"self",
".",
"index",
"is",
"None",
":",
"self",
".",
"index",
"[",
"key",
"]",
"=",
"rrset",
"return",
"rrset"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/web-page-replay/third_party/dns/message.py#L295-L339 | |
LARG/HFO | b8b2a1d462823c6732f4d5581aa7fe2e371d55cb | hfo/hfo.py | python | HFOEnvironment.step | (self) | return hfo_lib.step(self.obj) | Advances the state of the environment | Advances the state of the environment | [
"Advances",
"the",
"state",
"of",
"the",
"environment"
] | def step(self):
""" Advances the state of the environment """
return hfo_lib.step(self.obj) | [
"def",
"step",
"(",
"self",
")",
":",
"return",
"hfo_lib",
".",
"step",
"(",
"self",
".",
"obj",
")"
] | https://github.com/LARG/HFO/blob/b8b2a1d462823c6732f4d5581aa7fe2e371d55cb/hfo/hfo.py#L177-L179 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/mailbox.py | python | MaildirMessage.get_flags | (self) | Return as a string the flags that are set. | Return as a string the flags that are set. | [
"Return",
"as",
"a",
"string",
"the",
"flags",
"that",
"are",
"set",
"."
] | def get_flags(self):
"""Return as a string the flags that are set."""
if self._info.startswith('2,'):
return self._info[2:]
else:
return '' | [
"def",
"get_flags",
"(",
"self",
")",
":",
"if",
"self",
".",
"_info",
".",
"startswith",
"(",
"'2,'",
")",
":",
"return",
"self",
".",
"_info",
"[",
"2",
":",
"]",
"else",
":",
"return",
"''"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/mailbox.py#L1492-L1497 | ||
microsoft/ELL | a1d6bacc37a14879cc025d9be2ba40b1a0632315 | tools/utilities/pythonlibs/audio/view_audio.py | python | AudioDemo.on_play_button_click | (self) | called when user clicks the record button, same button is used to "stop" playback | called when user clicks the record button, same button is used to "stop" playback | [
"called",
"when",
"user",
"clicks",
"the",
"record",
"button",
"same",
"button",
"is",
"used",
"to",
"stop",
"playback"
] | def on_play_button_click(self):
""" called when user clicks the record button, same button is used to "stop" playback """
if self.play_button["text"] == "Play":
self.play_button["text"] = "Stop"
self.rec_button["text"] = "Rec"
self.on_play()
else:
self.play_button["text"] = "Play"
self.on_stop() | [
"def",
"on_play_button_click",
"(",
"self",
")",
":",
"if",
"self",
".",
"play_button",
"[",
"\"text\"",
"]",
"==",
"\"Play\"",
":",
"self",
".",
"play_button",
"[",
"\"text\"",
"]",
"=",
"\"Stop\"",
"self",
".",
"rec_button",
"[",
"\"text\"",
"]",
"=",
"\"Rec\"",
"self",
".",
"on_play",
"(",
")",
"else",
":",
"self",
".",
"play_button",
"[",
"\"text\"",
"]",
"=",
"\"Play\"",
"self",
".",
"on_stop",
"(",
")"
] | https://github.com/microsoft/ELL/blob/a1d6bacc37a14879cc025d9be2ba40b1a0632315/tools/utilities/pythonlibs/audio/view_audio.py#L530-L538 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/llvmlite/binding/passmanagers.py | python | PassManager.add_dead_code_elimination_pass | (self) | See http://llvm.org/docs/Passes.html#dce-dead-code-elimination. | See http://llvm.org/docs/Passes.html#dce-dead-code-elimination. | [
"See",
"http",
":",
"//",
"llvm",
".",
"org",
"/",
"docs",
"/",
"Passes",
".",
"html#dce",
"-",
"dead",
"-",
"code",
"-",
"elimination",
"."
] | def add_dead_code_elimination_pass(self):
"""See http://llvm.org/docs/Passes.html#dce-dead-code-elimination."""
ffi.lib.LLVMPY_AddDeadCodeEliminationPass(self) | [
"def",
"add_dead_code_elimination_pass",
"(",
"self",
")",
":",
"ffi",
".",
"lib",
".",
"LLVMPY_AddDeadCodeEliminationPass",
"(",
"self",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/llvmlite/binding/passmanagers.py#L49-L51 | ||
llvm/llvm-project | ffa6262cb4e2a335d26416fad39a581b4f98c5f4 | lldb/utils/lui/lldbutil.py | python | ChildVisitingFormatter.__init__ | (self, indent_child=2) | Default indentation of 2 SPC's for the children. | Default indentation of 2 SPC's for the children. | [
"Default",
"indentation",
"of",
"2",
"SPC",
"s",
"for",
"the",
"children",
"."
] | def __init__(self, indent_child=2):
"""Default indentation of 2 SPC's for the children."""
self.cindent = indent_child | [
"def",
"__init__",
"(",
"self",
",",
"indent_child",
"=",
"2",
")",
":",
"self",
".",
"cindent",
"=",
"indent_child"
] | https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/lldb/utils/lui/lldbutil.py#L989-L991 | ||
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSNew.py | python | MSVSSolution.__init__ | (self, path, version, entries=None, variants=None,
websiteProperties=True) | Initializes the solution.
Args:
path: Path to solution file.
version: Format version to emit.
entries: List of entries in solution. May contain Folder or Project
objects. May be None, if the folder is empty.
variants: List of build variant strings. If none, a default list will
be used.
websiteProperties: Flag to decide if the website properties section
is generated. | Initializes the solution. | [
"Initializes",
"the",
"solution",
"."
] | def __init__(self, path, version, entries=None, variants=None,
websiteProperties=True):
"""Initializes the solution.
Args:
path: Path to solution file.
version: Format version to emit.
entries: List of entries in solution. May contain Folder or Project
objects. May be None, if the folder is empty.
variants: List of build variant strings. If none, a default list will
be used.
websiteProperties: Flag to decide if the website properties section
is generated.
"""
self.path = path
self.websiteProperties = websiteProperties
self.version = version
# Copy passed lists (or set to empty lists)
self.entries = list(entries or [])
if variants:
# Copy passed list
self.variants = variants[:]
else:
# Use default
self.variants = ['Debug|Win32', 'Release|Win32']
# TODO(rspangler): Need to be able to handle a mapping of solution config
# to project config. Should we be able to handle variants being a dict,
# or add a separate variant_map variable? If it's a dict, we can't
# guarantee the order of variants since dict keys aren't ordered.
# TODO(rspangler): Automatically write to disk for now; should delay until
# node-evaluation time.
self.Write() | [
"def",
"__init__",
"(",
"self",
",",
"path",
",",
"version",
",",
"entries",
"=",
"None",
",",
"variants",
"=",
"None",
",",
"websiteProperties",
"=",
"True",
")",
":",
"self",
".",
"path",
"=",
"path",
"self",
".",
"websiteProperties",
"=",
"websiteProperties",
"self",
".",
"version",
"=",
"version",
"# Copy passed lists (or set to empty lists)",
"self",
".",
"entries",
"=",
"list",
"(",
"entries",
"or",
"[",
"]",
")",
"if",
"variants",
":",
"# Copy passed list",
"self",
".",
"variants",
"=",
"variants",
"[",
":",
"]",
"else",
":",
"# Use default",
"self",
".",
"variants",
"=",
"[",
"'Debug|Win32'",
",",
"'Release|Win32'",
"]",
"# TODO(rspangler): Need to be able to handle a mapping of solution config",
"# to project config. Should we be able to handle variants being a dict,",
"# or add a separate variant_map variable? If it's a dict, we can't",
"# guarantee the order of variants since dict keys aren't ordered.",
"# TODO(rspangler): Automatically write to disk for now; should delay until",
"# node-evaluation time.",
"self",
".",
"Write",
"(",
")"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSNew.py#L178-L213 | ||
google-ar/WebARonTango | e86965d2cbc652156b480e0fcf77c716745578cd | chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py | python | Int64Argument.WriteArgAccessor | (self, f) | Writes specialized accessor for compound members. | Writes specialized accessor for compound members. | [
"Writes",
"specialized",
"accessor",
"for",
"compound",
"members",
"."
] | def WriteArgAccessor(self, f):
"""Writes specialized accessor for compound members."""
f.write(" %s %s() const volatile {\n" % (self.type, self.name))
f.write(" return static_cast<%s>(\n" % self.type)
f.write(" GLES2Util::MapTwoUint32ToUint64(\n")
f.write(" %s_0,\n" % self.name)
f.write(" %s_1));\n" % self.name)
f.write(" }\n")
f.write("\n") | [
"def",
"WriteArgAccessor",
"(",
"self",
",",
"f",
")",
":",
"f",
".",
"write",
"(",
"\" %s %s() const volatile {\\n\"",
"%",
"(",
"self",
".",
"type",
",",
"self",
".",
"name",
")",
")",
"f",
".",
"write",
"(",
"\" return static_cast<%s>(\\n\"",
"%",
"self",
".",
"type",
")",
"f",
".",
"write",
"(",
"\" GLES2Util::MapTwoUint32ToUint64(\\n\"",
")",
"f",
".",
"write",
"(",
"\" %s_0,\\n\"",
"%",
"self",
".",
"name",
")",
"f",
".",
"write",
"(",
"\" %s_1));\\n\"",
"%",
"self",
".",
"name",
")",
"f",
".",
"write",
"(",
"\" }\\n\"",
")",
"f",
".",
"write",
"(",
"\"\\n\"",
")"
] | https://github.com/google-ar/WebARonTango/blob/e86965d2cbc652156b480e0fcf77c716745578cd/chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py#L9177-L9185 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/learn/python/learn/learn_runner.py | python | _execute_schedule | (experiment, schedule) | return task() | Execute the method named `schedule` of `experiment`. | Execute the method named `schedule` of `experiment`. | [
"Execute",
"the",
"method",
"named",
"schedule",
"of",
"experiment",
"."
] | def _execute_schedule(experiment, schedule):
"""Execute the method named `schedule` of `experiment`."""
if not hasattr(experiment, schedule):
logging.error('Schedule references non-existent task %s', schedule)
valid_tasks = [x for x in dir(experiment)
if not x.startswith('_')
and callable(getattr(experiment, x))]
logging.error('Allowed values for this experiment are: %s', valid_tasks)
raise ValueError('Schedule references non-existent task %s' % schedule)
task = getattr(experiment, schedule)
if not callable(task):
logging.error('Schedule references non-callable member %s', schedule)
valid_tasks = [x for x in dir(experiment)
if not x.startswith('_')
and callable(getattr(experiment, x))]
logging.error('Allowed values for this experiment are: %s', valid_tasks)
raise TypeError('Schedule references non-callable member %s' % schedule)
return task() | [
"def",
"_execute_schedule",
"(",
"experiment",
",",
"schedule",
")",
":",
"if",
"not",
"hasattr",
"(",
"experiment",
",",
"schedule",
")",
":",
"logging",
".",
"error",
"(",
"'Schedule references non-existent task %s'",
",",
"schedule",
")",
"valid_tasks",
"=",
"[",
"x",
"for",
"x",
"in",
"dir",
"(",
"experiment",
")",
"if",
"not",
"x",
".",
"startswith",
"(",
"'_'",
")",
"and",
"callable",
"(",
"getattr",
"(",
"experiment",
",",
"x",
")",
")",
"]",
"logging",
".",
"error",
"(",
"'Allowed values for this experiment are: %s'",
",",
"valid_tasks",
")",
"raise",
"ValueError",
"(",
"'Schedule references non-existent task %s'",
"%",
"schedule",
")",
"task",
"=",
"getattr",
"(",
"experiment",
",",
"schedule",
")",
"if",
"not",
"callable",
"(",
"task",
")",
":",
"logging",
".",
"error",
"(",
"'Schedule references non-callable member %s'",
",",
"schedule",
")",
"valid_tasks",
"=",
"[",
"x",
"for",
"x",
"in",
"dir",
"(",
"experiment",
")",
"if",
"not",
"x",
".",
"startswith",
"(",
"'_'",
")",
"and",
"callable",
"(",
"getattr",
"(",
"experiment",
",",
"x",
")",
")",
"]",
"logging",
".",
"error",
"(",
"'Allowed values for this experiment are: %s'",
",",
"valid_tasks",
")",
"raise",
"TypeError",
"(",
"'Schedule references non-callable member %s'",
"%",
"schedule",
")",
"return",
"task",
"(",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/learn/python/learn/learn_runner.py#L28-L46 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBTypeMember.IsBitfield | (self) | return _lldb.SBTypeMember_IsBitfield(self) | IsBitfield(self) -> bool | IsBitfield(self) -> bool | [
"IsBitfield",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsBitfield(self):
"""IsBitfield(self) -> bool"""
return _lldb.SBTypeMember_IsBitfield(self) | [
"def",
"IsBitfield",
"(",
"self",
")",
":",
"return",
"_lldb",
".",
"SBTypeMember_IsBitfield",
"(",
"self",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L10156-L10158 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/setuptools/package_index.py | python | PackageIndex.process_index | (self,url,page) | Process the contents of a PyPI page | Process the contents of a PyPI page | [
"Process",
"the",
"contents",
"of",
"a",
"PyPI",
"page"
] | def process_index(self,url,page):
"""Process the contents of a PyPI page"""
def scan(link):
# Process a URL to see if it's for a package page
if link.startswith(self.index_url):
parts = list(map(
unquote, link[len(self.index_url):].split('/')
))
if len(parts)==2 and '#' not in parts[1]:
# it's a package page, sanitize and index it
pkg = safe_name(parts[0])
ver = safe_version(parts[1])
self.package_pages.setdefault(pkg.lower(),{})[link] = True
return to_filename(pkg), to_filename(ver)
return None, None
# process an index page into the package-page index
for match in HREF.finditer(page):
try:
scan(urljoin(url, htmldecode(match.group(1))))
except ValueError:
pass
pkg, ver = scan(url) # ensure this page is in the page index
if pkg:
# process individual package page
for new_url in find_external_links(url, page):
# Process the found URL
base, frag = egg_info_for_url(new_url)
if base.endswith('.py') and not frag:
if ver:
new_url+='#egg=%s-%s' % (pkg,ver)
else:
self.need_version_info(url)
self.scan_url(new_url)
return PYPI_MD5.sub(
lambda m: '<a href="%s#md5=%s">%s</a>' % m.group(1,3,2), page
)
else:
return "" | [
"def",
"process_index",
"(",
"self",
",",
"url",
",",
"page",
")",
":",
"def",
"scan",
"(",
"link",
")",
":",
"# Process a URL to see if it's for a package page",
"if",
"link",
".",
"startswith",
"(",
"self",
".",
"index_url",
")",
":",
"parts",
"=",
"list",
"(",
"map",
"(",
"unquote",
",",
"link",
"[",
"len",
"(",
"self",
".",
"index_url",
")",
":",
"]",
".",
"split",
"(",
"'/'",
")",
")",
")",
"if",
"len",
"(",
"parts",
")",
"==",
"2",
"and",
"'#'",
"not",
"in",
"parts",
"[",
"1",
"]",
":",
"# it's a package page, sanitize and index it",
"pkg",
"=",
"safe_name",
"(",
"parts",
"[",
"0",
"]",
")",
"ver",
"=",
"safe_version",
"(",
"parts",
"[",
"1",
"]",
")",
"self",
".",
"package_pages",
".",
"setdefault",
"(",
"pkg",
".",
"lower",
"(",
")",
",",
"{",
"}",
")",
"[",
"link",
"]",
"=",
"True",
"return",
"to_filename",
"(",
"pkg",
")",
",",
"to_filename",
"(",
"ver",
")",
"return",
"None",
",",
"None",
"# process an index page into the package-page index",
"for",
"match",
"in",
"HREF",
".",
"finditer",
"(",
"page",
")",
":",
"try",
":",
"scan",
"(",
"urljoin",
"(",
"url",
",",
"htmldecode",
"(",
"match",
".",
"group",
"(",
"1",
")",
")",
")",
")",
"except",
"ValueError",
":",
"pass",
"pkg",
",",
"ver",
"=",
"scan",
"(",
"url",
")",
"# ensure this page is in the page index",
"if",
"pkg",
":",
"# process individual package page",
"for",
"new_url",
"in",
"find_external_links",
"(",
"url",
",",
"page",
")",
":",
"# Process the found URL",
"base",
",",
"frag",
"=",
"egg_info_for_url",
"(",
"new_url",
")",
"if",
"base",
".",
"endswith",
"(",
"'.py'",
")",
"and",
"not",
"frag",
":",
"if",
"ver",
":",
"new_url",
"+=",
"'#egg=%s-%s'",
"%",
"(",
"pkg",
",",
"ver",
")",
"else",
":",
"self",
".",
"need_version_info",
"(",
"url",
")",
"self",
".",
"scan_url",
"(",
"new_url",
")",
"return",
"PYPI_MD5",
".",
"sub",
"(",
"lambda",
"m",
":",
"'<a href=\"%s#md5=%s\">%s</a>'",
"%",
"m",
".",
"group",
"(",
"1",
",",
"3",
",",
"2",
")",
",",
"page",
")",
"else",
":",
"return",
"\"\""
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/setuptools/package_index.py#L368-L408 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/protobuf/python/google/protobuf/descriptor_pool.py | python | DescriptorPool.FindFileContainingSymbol | (self, symbol) | return self._ConvertFileProtoToFileDescriptor(file_proto) | Gets the FileDescriptor for the file containing the specified symbol.
Args:
symbol: The name of the symbol to search for.
Returns:
A FileDescriptor that contains the specified symbol.
Raises:
KeyError: if the file can not be found in the pool. | Gets the FileDescriptor for the file containing the specified symbol. | [
"Gets",
"the",
"FileDescriptor",
"for",
"the",
"file",
"containing",
"the",
"specified",
"symbol",
"."
] | def FindFileContainingSymbol(self, symbol):
"""Gets the FileDescriptor for the file containing the specified symbol.
Args:
symbol: The name of the symbol to search for.
Returns:
A FileDescriptor that contains the specified symbol.
Raises:
KeyError: if the file can not be found in the pool.
"""
symbol = _NormalizeFullyQualifiedName(symbol)
try:
return self._descriptors[symbol].file
except KeyError:
pass
try:
return self._enum_descriptors[symbol].file
except KeyError:
pass
try:
file_proto = self._internal_db.FindFileContainingSymbol(symbol)
except KeyError as error:
if self._descriptor_db:
file_proto = self._descriptor_db.FindFileContainingSymbol(symbol)
else:
raise error
if not file_proto:
raise KeyError('Cannot find a file containing %s' % symbol)
return self._ConvertFileProtoToFileDescriptor(file_proto) | [
"def",
"FindFileContainingSymbol",
"(",
"self",
",",
"symbol",
")",
":",
"symbol",
"=",
"_NormalizeFullyQualifiedName",
"(",
"symbol",
")",
"try",
":",
"return",
"self",
".",
"_descriptors",
"[",
"symbol",
"]",
".",
"file",
"except",
"KeyError",
":",
"pass",
"try",
":",
"return",
"self",
".",
"_enum_descriptors",
"[",
"symbol",
"]",
".",
"file",
"except",
"KeyError",
":",
"pass",
"try",
":",
"file_proto",
"=",
"self",
".",
"_internal_db",
".",
"FindFileContainingSymbol",
"(",
"symbol",
")",
"except",
"KeyError",
"as",
"error",
":",
"if",
"self",
".",
"_descriptor_db",
":",
"file_proto",
"=",
"self",
".",
"_descriptor_db",
".",
"FindFileContainingSymbol",
"(",
"symbol",
")",
"else",
":",
"raise",
"error",
"if",
"not",
"file_proto",
":",
"raise",
"KeyError",
"(",
"'Cannot find a file containing %s'",
"%",
"symbol",
")",
"return",
"self",
".",
"_ConvertFileProtoToFileDescriptor",
"(",
"file_proto",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/protobuf/python/google/protobuf/descriptor_pool.py#L208-L241 | |
deepmind/streetlearn | ccf1d60b9c45154894d45a897748aee85d7eb69b | streetlearn/python/environment/streetlearn.py | python | StreetLearn.reward | (self) | return self._reward | Returns the reward for the last time step. | Returns the reward for the last time step. | [
"Returns",
"the",
"reward",
"for",
"the",
"last",
"time",
"step",
"."
] | def reward(self):
"""Returns the reward for the last time step."""
return self._reward | [
"def",
"reward",
"(",
"self",
")",
":",
"return",
"self",
".",
"_reward"
] | https://github.com/deepmind/streetlearn/blob/ccf1d60b9c45154894d45a897748aee85d7eb69b/streetlearn/python/environment/streetlearn.py#L383-L385 | |
Slicer/SlicerGitSVNArchive | 65e92bb16c2b32ea47a1a66bee71f238891ee1ca | Base/Python/slicer/util.py | python | importModuleObjects | (from_module_name, dest_module_name, type_info) | Import object of type 'type_info' (str or type) from module identified
by 'from_module_name' into the module identified by 'dest_module_name'. | Import object of type 'type_info' (str or type) from module identified
by 'from_module_name' into the module identified by 'dest_module_name'. | [
"Import",
"object",
"of",
"type",
"type_info",
"(",
"str",
"or",
"type",
")",
"from",
"module",
"identified",
"by",
"from_module_name",
"into",
"the",
"module",
"identified",
"by",
"dest_module_name",
"."
] | def importModuleObjects(from_module_name, dest_module_name, type_info):
"""Import object of type 'type_info' (str or type) from module identified
by 'from_module_name' into the module identified by 'dest_module_name'."""
# Obtain a reference to the module identifed by 'dest_module_name'
import sys
dest_module = sys.modules[dest_module_name]
# Skip if module has already been loaded
if from_module_name in sys.modules:
return
# Obtain a reference to the module identified by 'from_module_name'
import imp
fp, pathname, description = imp.find_module(from_module_name)
module = imp.load_module(from_module_name, fp, pathname, description)
# Loop over content of the python module associated with the given python library
for item_name in dir(module):
# Obtain a reference associated with the current object
item = getattr(module, item_name)
# Check type match by type or type name
match = False
if isinstance(type_info, type):
try:
match = issubclass(item, type_info)
except TypeError as e:
pass
else:
match = type(item).__name__ == type_info
if match:
setattr(dest_module, item_name, item) | [
"def",
"importModuleObjects",
"(",
"from_module_name",
",",
"dest_module_name",
",",
"type_info",
")",
":",
"# Obtain a reference to the module identifed by 'dest_module_name'",
"import",
"sys",
"dest_module",
"=",
"sys",
".",
"modules",
"[",
"dest_module_name",
"]",
"# Skip if module has already been loaded",
"if",
"from_module_name",
"in",
"sys",
".",
"modules",
":",
"return",
"# Obtain a reference to the module identified by 'from_module_name'",
"import",
"imp",
"fp",
",",
"pathname",
",",
"description",
"=",
"imp",
".",
"find_module",
"(",
"from_module_name",
")",
"module",
"=",
"imp",
".",
"load_module",
"(",
"from_module_name",
",",
"fp",
",",
"pathname",
",",
"description",
")",
"# Loop over content of the python module associated with the given python library",
"for",
"item_name",
"in",
"dir",
"(",
"module",
")",
":",
"# Obtain a reference associated with the current object",
"item",
"=",
"getattr",
"(",
"module",
",",
"item_name",
")",
"# Check type match by type or type name",
"match",
"=",
"False",
"if",
"isinstance",
"(",
"type_info",
",",
"type",
")",
":",
"try",
":",
"match",
"=",
"issubclass",
"(",
"item",
",",
"type_info",
")",
"except",
"TypeError",
"as",
"e",
":",
"pass",
"else",
":",
"match",
"=",
"type",
"(",
"item",
")",
".",
"__name__",
"==",
"type_info",
"if",
"match",
":",
"setattr",
"(",
"dest_module",
",",
"item_name",
",",
"item",
")"
] | https://github.com/Slicer/SlicerGitSVNArchive/blob/65e92bb16c2b32ea47a1a66bee71f238891ee1ca/Base/Python/slicer/util.py#L135-L169 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/flatmenu.py | python | FlatMenu._DestroyById | (self, id) | Used internally. | Used internally. | [
"Used",
"internally",
"."
] | def _DestroyById(self, id):
""" Used internally. """
item = None
item = self.Remove(id)
if item:
del item | [
"def",
"_DestroyById",
"(",
"self",
",",
"id",
")",
":",
"item",
"=",
"None",
"item",
"=",
"self",
".",
"Remove",
"(",
"id",
")",
"if",
"item",
":",
"del",
"item"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatmenu.py#L6640-L6647 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/llvmlite/binding/initfini.py | python | initialize_native_asmparser | () | Initialize the native ASM parser. | Initialize the native ASM parser. | [
"Initialize",
"the",
"native",
"ASM",
"parser",
"."
] | def initialize_native_asmparser():
"""
Initialize the native ASM parser.
"""
ffi.lib.LLVMPY_InitializeNativeAsmParser() | [
"def",
"initialize_native_asmparser",
"(",
")",
":",
"ffi",
".",
"lib",
".",
"LLVMPY_InitializeNativeAsmParser",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/llvmlite/binding/initfini.py#L46-L50 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/devil/devil/android/decorators.py | python | WithTimeoutAndRetriesFromInstance | (
default_timeout_name=DEFAULT_TIMEOUT_ATTR,
default_retries_name=DEFAULT_RETRIES_ATTR,
min_default_timeout=None) | return decorator | Returns a decorator that handles timeouts and retries.
The provided |default_timeout_name| and |default_retries_name| are used to
get the default timeout value and the default retries value from the object
instance if timeout and retries values are not provided.
Note that this should only be used to decorate methods, not functions.
Args:
default_timeout_name: The name of the default timeout attribute of the
instance.
default_retries_name: The name of the default retries attribute of the
instance.
min_timeout: Miniumum timeout to be used when using instance timeout.
Returns:
The actual decorator. | Returns a decorator that handles timeouts and retries. | [
"Returns",
"a",
"decorator",
"that",
"handles",
"timeouts",
"and",
"retries",
"."
] | def WithTimeoutAndRetriesFromInstance(
default_timeout_name=DEFAULT_TIMEOUT_ATTR,
default_retries_name=DEFAULT_RETRIES_ATTR,
min_default_timeout=None):
"""Returns a decorator that handles timeouts and retries.
The provided |default_timeout_name| and |default_retries_name| are used to
get the default timeout value and the default retries value from the object
instance if timeout and retries values are not provided.
Note that this should only be used to decorate methods, not functions.
Args:
default_timeout_name: The name of the default timeout attribute of the
instance.
default_retries_name: The name of the default retries attribute of the
instance.
min_timeout: Miniumum timeout to be used when using instance timeout.
Returns:
The actual decorator.
"""
def decorator(f):
def get_timeout(inst, *_args, **kwargs):
ret = getattr(inst, default_timeout_name)
if min_default_timeout is not None:
ret = max(min_default_timeout, ret)
return kwargs.get('timeout', ret)
def get_retries(inst, *_args, **kwargs):
return kwargs.get('retries', getattr(inst, default_retries_name))
return _TimeoutRetryWrapper(f, get_timeout, get_retries, pass_values=True)
return decorator | [
"def",
"WithTimeoutAndRetriesFromInstance",
"(",
"default_timeout_name",
"=",
"DEFAULT_TIMEOUT_ATTR",
",",
"default_retries_name",
"=",
"DEFAULT_RETRIES_ATTR",
",",
"min_default_timeout",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"def",
"get_timeout",
"(",
"inst",
",",
"*",
"_args",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"getattr",
"(",
"inst",
",",
"default_timeout_name",
")",
"if",
"min_default_timeout",
"is",
"not",
"None",
":",
"ret",
"=",
"max",
"(",
"min_default_timeout",
",",
"ret",
")",
"return",
"kwargs",
".",
"get",
"(",
"'timeout'",
",",
"ret",
")",
"def",
"get_retries",
"(",
"inst",
",",
"*",
"_args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"kwargs",
".",
"get",
"(",
"'retries'",
",",
"getattr",
"(",
"inst",
",",
"default_retries_name",
")",
")",
"return",
"_TimeoutRetryWrapper",
"(",
"f",
",",
"get_timeout",
",",
"get_retries",
",",
"pass_values",
"=",
"True",
")",
"return",
"decorator"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/devil/devil/android/decorators.py#L144-L175 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/ma/extras.py | python | masked_all | (shape, dtype=float) | return a | Empty masked array with all elements masked.
Return an empty masked array of the given shape and dtype, where all the
data are masked.
Parameters
----------
shape : tuple
Shape of the required MaskedArray.
dtype : dtype, optional
Data type of the output.
Returns
-------
a : MaskedArray
A masked array with all data masked.
See Also
--------
masked_all_like : Empty masked array modelled on an existing array.
Examples
--------
>>> import numpy.ma as ma
>>> ma.masked_all((3, 3))
masked_array(data =
[[-- -- --]
[-- -- --]
[-- -- --]],
mask =
[[ True True True]
[ True True True]
[ True True True]],
fill_value=1e+20)
The `dtype` parameter defines the underlying data type.
>>> a = ma.masked_all((3, 3))
>>> a.dtype
dtype('float64')
>>> a = ma.masked_all((3, 3), dtype=np.int32)
>>> a.dtype
dtype('int32') | Empty masked array with all elements masked. | [
"Empty",
"masked",
"array",
"with",
"all",
"elements",
"masked",
"."
] | def masked_all(shape, dtype=float):
"""
Empty masked array with all elements masked.
Return an empty masked array of the given shape and dtype, where all the
data are masked.
Parameters
----------
shape : tuple
Shape of the required MaskedArray.
dtype : dtype, optional
Data type of the output.
Returns
-------
a : MaskedArray
A masked array with all data masked.
See Also
--------
masked_all_like : Empty masked array modelled on an existing array.
Examples
--------
>>> import numpy.ma as ma
>>> ma.masked_all((3, 3))
masked_array(data =
[[-- -- --]
[-- -- --]
[-- -- --]],
mask =
[[ True True True]
[ True True True]
[ True True True]],
fill_value=1e+20)
The `dtype` parameter defines the underlying data type.
>>> a = ma.masked_all((3, 3))
>>> a.dtype
dtype('float64')
>>> a = ma.masked_all((3, 3), dtype=np.int32)
>>> a.dtype
dtype('int32')
"""
a = masked_array(np.empty(shape, dtype),
mask=np.ones(shape, make_mask_descr(dtype)))
return a | [
"def",
"masked_all",
"(",
"shape",
",",
"dtype",
"=",
"float",
")",
":",
"a",
"=",
"masked_array",
"(",
"np",
".",
"empty",
"(",
"shape",
",",
"dtype",
")",
",",
"mask",
"=",
"np",
".",
"ones",
"(",
"shape",
",",
"make_mask_descr",
"(",
"dtype",
")",
")",
")",
"return",
"a"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/ma/extras.py#L115-L164 | |
jiangxiluning/FOTS.PyTorch | b1851c170b4f1ad18406766352cb5171648ce603 | FOTS/utils/eval_tools/icdar2015/rrc_evaluation_funcs_1_1.py | python | validate_lines_in_file | (fileName,file_contents,CRLF=True,LTRB=True,withTranscription=False,withConfidence=False,imWidth=0,imHeight=0) | This function validates that all lines of the file calling the Line validation function for each line | This function validates that all lines of the file calling the Line validation function for each line | [
"This",
"function",
"validates",
"that",
"all",
"lines",
"of",
"the",
"file",
"calling",
"the",
"Line",
"validation",
"function",
"for",
"each",
"line"
] | def validate_lines_in_file(fileName,file_contents,CRLF=True,LTRB=True,withTranscription=False,withConfidence=False,imWidth=0,imHeight=0):
"""
This function validates that all lines of the file calling the Line validation function for each line
"""
utf8File = decode_utf8(file_contents)
if (utf8File is None) :
raise Exception("The file %s is not UTF-8" %fileName)
lines = utf8File.split( "\r\n" if CRLF else "\n" )
for line in lines:
line = line.replace("\r","").replace("\n","")
if(line != ""):
try:
validate_tl_line(line,LTRB,withTranscription,withConfidence,imWidth,imHeight)
except Exception as e:
raise Exception(("Line in sample not valid. Sample: %s Line: %s Error: %s" %(fileName,line,str(e))).encode('utf-8', 'replace')) | [
"def",
"validate_lines_in_file",
"(",
"fileName",
",",
"file_contents",
",",
"CRLF",
"=",
"True",
",",
"LTRB",
"=",
"True",
",",
"withTranscription",
"=",
"False",
",",
"withConfidence",
"=",
"False",
",",
"imWidth",
"=",
"0",
",",
"imHeight",
"=",
"0",
")",
":",
"utf8File",
"=",
"decode_utf8",
"(",
"file_contents",
")",
"if",
"(",
"utf8File",
"is",
"None",
")",
":",
"raise",
"Exception",
"(",
"\"The file %s is not UTF-8\"",
"%",
"fileName",
")",
"lines",
"=",
"utf8File",
".",
"split",
"(",
"\"\\r\\n\"",
"if",
"CRLF",
"else",
"\"\\n\"",
")",
"for",
"line",
"in",
"lines",
":",
"line",
"=",
"line",
".",
"replace",
"(",
"\"\\r\"",
",",
"\"\"",
")",
".",
"replace",
"(",
"\"\\n\"",
",",
"\"\"",
")",
"if",
"(",
"line",
"!=",
"\"\"",
")",
":",
"try",
":",
"validate_tl_line",
"(",
"line",
",",
"LTRB",
",",
"withTranscription",
",",
"withConfidence",
",",
"imWidth",
",",
"imHeight",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"Exception",
"(",
"(",
"\"Line in sample not valid. Sample: %s Line: %s Error: %s\"",
"%",
"(",
"fileName",
",",
"line",
",",
"str",
"(",
"e",
")",
")",
")",
".",
"encode",
"(",
"'utf-8'",
",",
"'replace'",
")",
")"
] | https://github.com/jiangxiluning/FOTS.PyTorch/blob/b1851c170b4f1ad18406766352cb5171648ce603/FOTS/utils/eval_tools/icdar2015/rrc_evaluation_funcs_1_1.py#L92-L107 | ||
githubharald/CTCWordBeamSearch | 43567e5b06dd43bdcbec452f5099171c81f5e737 | extras/prototype/PrefixTree.py | python | PrefixTree.getNode | (self, text) | return node | get node representing given text | get node representing given text | [
"get",
"node",
"representing",
"given",
"text"
] | def getNode(self, text):
"get node representing given text"
node = self.root
for c in text:
if c in node.children:
node = node.children[c]
else:
return None
return node | [
"def",
"getNode",
"(",
"self",
",",
"text",
")",
":",
"node",
"=",
"self",
".",
"root",
"for",
"c",
"in",
"text",
":",
"if",
"c",
"in",
"node",
".",
"children",
":",
"node",
"=",
"node",
".",
"children",
"[",
"c",
"]",
"else",
":",
"return",
"None",
"return",
"node"
] | https://github.com/githubharald/CTCWordBeamSearch/blob/43567e5b06dd43bdcbec452f5099171c81f5e737/extras/prototype/PrefixTree.py#L37-L45 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/keras/python/keras/engine/topology.py | python | Container.set_weights | (self, weights) | Sets the weights of the model.
Arguments:
weights: A list of Numpy arrays with shapes and types matching
the output of `model.get_weights()`. | Sets the weights of the model. | [
"Sets",
"the",
"weights",
"of",
"the",
"model",
"."
] | def set_weights(self, weights):
"""Sets the weights of the model.
Arguments:
weights: A list of Numpy arrays with shapes and types matching
the output of `model.get_weights()`.
"""
tuples = []
for layer in self.layers:
num_param = len(layer.weights)
layer_weights = weights[:num_param]
for sw, w in zip(layer.weights, layer_weights):
tuples.append((sw, w))
weights = weights[num_param:]
K.batch_set_value(tuples) | [
"def",
"set_weights",
"(",
"self",
",",
"weights",
")",
":",
"tuples",
"=",
"[",
"]",
"for",
"layer",
"in",
"self",
".",
"layers",
":",
"num_param",
"=",
"len",
"(",
"layer",
".",
"weights",
")",
"layer_weights",
"=",
"weights",
"[",
":",
"num_param",
"]",
"for",
"sw",
",",
"w",
"in",
"zip",
"(",
"layer",
".",
"weights",
",",
"layer_weights",
")",
":",
"tuples",
".",
"append",
"(",
"(",
"sw",
",",
"w",
")",
")",
"weights",
"=",
"weights",
"[",
"num_param",
":",
"]",
"K",
".",
"batch_set_value",
"(",
"tuples",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/keras/python/keras/engine/topology.py#L1675-L1689 | ||
etodd/lasercrabs | 91484d9ac3a47ac38b8f40ec3ff35194714dad8e | assets/script/etodd_blender_fbx/export_fbx_bin.py | python | fbx_header_elements | (root, scene_data, time=None) | Write boiling code of FBX root.
time is expected to be a datetime.datetime object, or None (using now() in this case). | Write boiling code of FBX root.
time is expected to be a datetime.datetime object, or None (using now() in this case). | [
"Write",
"boiling",
"code",
"of",
"FBX",
"root",
".",
"time",
"is",
"expected",
"to",
"be",
"a",
"datetime",
".",
"datetime",
"object",
"or",
"None",
"(",
"using",
"now",
"()",
"in",
"this",
"case",
")",
"."
] | def fbx_header_elements(root, scene_data, time=None):
"""
Write boiling code of FBX root.
time is expected to be a datetime.datetime object, or None (using now() in this case).
"""
app_vendor = "Blender Foundation"
app_name = "Blender (stable FBX IO)"
app_ver = bpy.app.version_string
import addon_utils
import sys
addon_ver = (1, 0, 0) # etodd version hack
# ##### Start of FBXHeaderExtension element.
header_ext = elem_empty(root, b"FBXHeaderExtension")
elem_data_single_int32(header_ext, b"FBXHeaderVersion", FBX_HEADER_VERSION)
elem_data_single_int32(header_ext, b"FBXVersion", FBX_VERSION)
# No encryption!
elem_data_single_int32(header_ext, b"EncryptionType", 0)
if time is None:
time = datetime.datetime.now()
elem = elem_empty(header_ext, b"CreationTimeStamp")
elem_data_single_int32(elem, b"Version", 1000)
elem_data_single_int32(elem, b"Year", time.year)
elem_data_single_int32(elem, b"Month", time.month)
elem_data_single_int32(elem, b"Day", time.day)
elem_data_single_int32(elem, b"Hour", time.hour)
elem_data_single_int32(elem, b"Minute", time.minute)
elem_data_single_int32(elem, b"Second", time.second)
elem_data_single_int32(elem, b"Millisecond", time.microsecond // 1000)
elem_data_single_string_unicode(header_ext, b"Creator", "%s - %s - %d.%d.%d"
% (app_name, app_ver, addon_ver[0], addon_ver[1], addon_ver[2]))
# 'SceneInfo' seems mandatory to get a valid FBX file...
# TODO use real values!
# XXX Should we use scene.name.encode() here?
scene_info = elem_data_single_string(header_ext, b"SceneInfo", fbx_name_class(b"GlobalInfo", b"SceneInfo"))
scene_info.add_string(b"UserData")
elem_data_single_string(scene_info, b"Type", b"UserData")
elem_data_single_int32(scene_info, b"Version", FBX_SCENEINFO_VERSION)
meta_data = elem_empty(scene_info, b"MetaData")
elem_data_single_int32(meta_data, b"Version", FBX_SCENEINFO_VERSION)
elem_data_single_string(meta_data, b"Title", b"")
elem_data_single_string(meta_data, b"Subject", b"")
elem_data_single_string(meta_data, b"Author", b"")
elem_data_single_string(meta_data, b"Keywords", b"")
elem_data_single_string(meta_data, b"Revision", b"")
elem_data_single_string(meta_data, b"Comment", b"")
props = elem_properties(scene_info)
elem_props_set(props, "p_string_url", b"DocumentUrl", "/foobar.fbx")
elem_props_set(props, "p_string_url", b"SrcDocumentUrl", "/foobar.fbx")
original = elem_props_compound(props, b"Original")
original("p_string", b"ApplicationVendor", app_vendor)
original("p_string", b"ApplicationName", app_name)
original("p_string", b"ApplicationVersion", app_ver)
original("p_datetime", b"DateTime_GMT", "01/01/1970 00:00:00.000")
original("p_string", b"FileName", "/foobar.fbx")
lastsaved = elem_props_compound(props, b"LastSaved")
lastsaved("p_string", b"ApplicationVendor", app_vendor)
lastsaved("p_string", b"ApplicationName", app_name)
lastsaved("p_string", b"ApplicationVersion", app_ver)
lastsaved("p_datetime", b"DateTime_GMT", "01/01/1970 00:00:00.000")
# ##### End of FBXHeaderExtension element.
# FileID is replaced by dummy value currently...
elem_data_single_bytes(root, b"FileId", b"FooBar")
# CreationTime is replaced by dummy value currently, but anyway...
elem_data_single_string_unicode(root, b"CreationTime",
"{:04}-{:02}-{:02} {:02}:{:02}:{:02}:{:03}"
"".format(time.year, time.month, time.day, time.hour, time.minute, time.second,
time.microsecond * 1000))
elem_data_single_string_unicode(root, b"Creator", "%s - %s - %d.%d.%d"
% (app_name, app_ver, addon_ver[0], addon_ver[1], addon_ver[2]))
# ##### Start of GlobalSettings element.
global_settings = elem_empty(root, b"GlobalSettings")
scene = scene_data.scene
elem_data_single_int32(global_settings, b"Version", 1000)
props = elem_properties(global_settings)
up_axis, front_axis, coord_axis = RIGHT_HAND_AXES[scene_data.settings.to_axes]
#~ # DO NOT take into account global scale here! That setting is applied to object transformations during export
#~ # (in other words, this is pure blender-exporter feature, and has nothing to do with FBX data).
#~ if scene_data.settings.apply_unit_scale:
#~ # Unit scaling is applied to objects' scale, so our unit is effectively FBX one (centimeter).
#~ scale_factor_org = 1.0
#~ scale_factor = 1.0 / units_blender_to_fbx_factor(scene)
#~ else:
#~ scale_factor_org = units_blender_to_fbx_factor(scene)
#~ scale_factor = scale_factor_org
scale_factor = scale_factor_org = scene_data.settings.unit_scale
elem_props_set(props, "p_integer", b"UpAxis", up_axis[0])
elem_props_set(props, "p_integer", b"UpAxisSign", up_axis[1])
elem_props_set(props, "p_integer", b"FrontAxis", front_axis[0])
elem_props_set(props, "p_integer", b"FrontAxisSign", front_axis[1])
elem_props_set(props, "p_integer", b"CoordAxis", coord_axis[0])
elem_props_set(props, "p_integer", b"CoordAxisSign", coord_axis[1])
elem_props_set(props, "p_integer", b"OriginalUpAxis", -1)
elem_props_set(props, "p_integer", b"OriginalUpAxisSign", 1)
elem_props_set(props, "p_double", b"UnitScaleFactor", scale_factor)
elem_props_set(props, "p_double", b"OriginalUnitScaleFactor", scale_factor_org)
elem_props_set(props, "p_color_rgb", b"AmbientColor", (0.0, 0.0, 0.0))
elem_props_set(props, "p_string", b"DefaultCamera", "Producer Perspective")
# Global timing data.
r = scene.render
_, fbx_fps_mode = FBX_FRAMERATES[0] # Custom framerate.
fbx_fps = fps = r.fps / r.fps_base
for ref_fps, fps_mode in FBX_FRAMERATES:
if similar_values(fps, ref_fps):
fbx_fps = ref_fps
fbx_fps_mode = fps_mode
elem_props_set(props, "p_enum", b"TimeMode", fbx_fps_mode)
elem_props_set(props, "p_timestamp", b"TimeSpanStart", 0)
elem_props_set(props, "p_timestamp", b"TimeSpanStop", FBX_KTIME)
elem_props_set(props, "p_double", b"CustomFrameRate", fbx_fps) | [
"def",
"fbx_header_elements",
"(",
"root",
",",
"scene_data",
",",
"time",
"=",
"None",
")",
":",
"app_vendor",
"=",
"\"Blender Foundation\"",
"app_name",
"=",
"\"Blender (stable FBX IO)\"",
"app_ver",
"=",
"bpy",
".",
"app",
".",
"version_string",
"import",
"addon_utils",
"import",
"sys",
"addon_ver",
"=",
"(",
"1",
",",
"0",
",",
"0",
")",
"# etodd version hack",
"# ##### Start of FBXHeaderExtension element.",
"header_ext",
"=",
"elem_empty",
"(",
"root",
",",
"b\"FBXHeaderExtension\"",
")",
"elem_data_single_int32",
"(",
"header_ext",
",",
"b\"FBXHeaderVersion\"",
",",
"FBX_HEADER_VERSION",
")",
"elem_data_single_int32",
"(",
"header_ext",
",",
"b\"FBXVersion\"",
",",
"FBX_VERSION",
")",
"# No encryption!",
"elem_data_single_int32",
"(",
"header_ext",
",",
"b\"EncryptionType\"",
",",
"0",
")",
"if",
"time",
"is",
"None",
":",
"time",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"elem",
"=",
"elem_empty",
"(",
"header_ext",
",",
"b\"CreationTimeStamp\"",
")",
"elem_data_single_int32",
"(",
"elem",
",",
"b\"Version\"",
",",
"1000",
")",
"elem_data_single_int32",
"(",
"elem",
",",
"b\"Year\"",
",",
"time",
".",
"year",
")",
"elem_data_single_int32",
"(",
"elem",
",",
"b\"Month\"",
",",
"time",
".",
"month",
")",
"elem_data_single_int32",
"(",
"elem",
",",
"b\"Day\"",
",",
"time",
".",
"day",
")",
"elem_data_single_int32",
"(",
"elem",
",",
"b\"Hour\"",
",",
"time",
".",
"hour",
")",
"elem_data_single_int32",
"(",
"elem",
",",
"b\"Minute\"",
",",
"time",
".",
"minute",
")",
"elem_data_single_int32",
"(",
"elem",
",",
"b\"Second\"",
",",
"time",
".",
"second",
")",
"elem_data_single_int32",
"(",
"elem",
",",
"b\"Millisecond\"",
",",
"time",
".",
"microsecond",
"//",
"1000",
")",
"elem_data_single_string_unicode",
"(",
"header_ext",
",",
"b\"Creator\"",
",",
"\"%s - %s - %d.%d.%d\"",
"%",
"(",
"app_name",
",",
"app_ver",
",",
"addon_ver",
"[",
"0",
"]",
",",
"addon_ver",
"[",
"1",
"]",
",",
"addon_ver",
"[",
"2",
"]",
")",
")",
"# 'SceneInfo' seems mandatory to get a valid FBX file...",
"# TODO use real values!",
"# XXX Should we use scene.name.encode() here?",
"scene_info",
"=",
"elem_data_single_string",
"(",
"header_ext",
",",
"b\"SceneInfo\"",
",",
"fbx_name_class",
"(",
"b\"GlobalInfo\"",
",",
"b\"SceneInfo\"",
")",
")",
"scene_info",
".",
"add_string",
"(",
"b\"UserData\"",
")",
"elem_data_single_string",
"(",
"scene_info",
",",
"b\"Type\"",
",",
"b\"UserData\"",
")",
"elem_data_single_int32",
"(",
"scene_info",
",",
"b\"Version\"",
",",
"FBX_SCENEINFO_VERSION",
")",
"meta_data",
"=",
"elem_empty",
"(",
"scene_info",
",",
"b\"MetaData\"",
")",
"elem_data_single_int32",
"(",
"meta_data",
",",
"b\"Version\"",
",",
"FBX_SCENEINFO_VERSION",
")",
"elem_data_single_string",
"(",
"meta_data",
",",
"b\"Title\"",
",",
"b\"\"",
")",
"elem_data_single_string",
"(",
"meta_data",
",",
"b\"Subject\"",
",",
"b\"\"",
")",
"elem_data_single_string",
"(",
"meta_data",
",",
"b\"Author\"",
",",
"b\"\"",
")",
"elem_data_single_string",
"(",
"meta_data",
",",
"b\"Keywords\"",
",",
"b\"\"",
")",
"elem_data_single_string",
"(",
"meta_data",
",",
"b\"Revision\"",
",",
"b\"\"",
")",
"elem_data_single_string",
"(",
"meta_data",
",",
"b\"Comment\"",
",",
"b\"\"",
")",
"props",
"=",
"elem_properties",
"(",
"scene_info",
")",
"elem_props_set",
"(",
"props",
",",
"\"p_string_url\"",
",",
"b\"DocumentUrl\"",
",",
"\"/foobar.fbx\"",
")",
"elem_props_set",
"(",
"props",
",",
"\"p_string_url\"",
",",
"b\"SrcDocumentUrl\"",
",",
"\"/foobar.fbx\"",
")",
"original",
"=",
"elem_props_compound",
"(",
"props",
",",
"b\"Original\"",
")",
"original",
"(",
"\"p_string\"",
",",
"b\"ApplicationVendor\"",
",",
"app_vendor",
")",
"original",
"(",
"\"p_string\"",
",",
"b\"ApplicationName\"",
",",
"app_name",
")",
"original",
"(",
"\"p_string\"",
",",
"b\"ApplicationVersion\"",
",",
"app_ver",
")",
"original",
"(",
"\"p_datetime\"",
",",
"b\"DateTime_GMT\"",
",",
"\"01/01/1970 00:00:00.000\"",
")",
"original",
"(",
"\"p_string\"",
",",
"b\"FileName\"",
",",
"\"/foobar.fbx\"",
")",
"lastsaved",
"=",
"elem_props_compound",
"(",
"props",
",",
"b\"LastSaved\"",
")",
"lastsaved",
"(",
"\"p_string\"",
",",
"b\"ApplicationVendor\"",
",",
"app_vendor",
")",
"lastsaved",
"(",
"\"p_string\"",
",",
"b\"ApplicationName\"",
",",
"app_name",
")",
"lastsaved",
"(",
"\"p_string\"",
",",
"b\"ApplicationVersion\"",
",",
"app_ver",
")",
"lastsaved",
"(",
"\"p_datetime\"",
",",
"b\"DateTime_GMT\"",
",",
"\"01/01/1970 00:00:00.000\"",
")",
"# ##### End of FBXHeaderExtension element.",
"# FileID is replaced by dummy value currently...",
"elem_data_single_bytes",
"(",
"root",
",",
"b\"FileId\"",
",",
"b\"FooBar\"",
")",
"# CreationTime is replaced by dummy value currently, but anyway...",
"elem_data_single_string_unicode",
"(",
"root",
",",
"b\"CreationTime\"",
",",
"\"{:04}-{:02}-{:02} {:02}:{:02}:{:02}:{:03}\"",
"\"\"",
".",
"format",
"(",
"time",
".",
"year",
",",
"time",
".",
"month",
",",
"time",
".",
"day",
",",
"time",
".",
"hour",
",",
"time",
".",
"minute",
",",
"time",
".",
"second",
",",
"time",
".",
"microsecond",
"*",
"1000",
")",
")",
"elem_data_single_string_unicode",
"(",
"root",
",",
"b\"Creator\"",
",",
"\"%s - %s - %d.%d.%d\"",
"%",
"(",
"app_name",
",",
"app_ver",
",",
"addon_ver",
"[",
"0",
"]",
",",
"addon_ver",
"[",
"1",
"]",
",",
"addon_ver",
"[",
"2",
"]",
")",
")",
"# ##### Start of GlobalSettings element.",
"global_settings",
"=",
"elem_empty",
"(",
"root",
",",
"b\"GlobalSettings\"",
")",
"scene",
"=",
"scene_data",
".",
"scene",
"elem_data_single_int32",
"(",
"global_settings",
",",
"b\"Version\"",
",",
"1000",
")",
"props",
"=",
"elem_properties",
"(",
"global_settings",
")",
"up_axis",
",",
"front_axis",
",",
"coord_axis",
"=",
"RIGHT_HAND_AXES",
"[",
"scene_data",
".",
"settings",
".",
"to_axes",
"]",
"#~ # DO NOT take into account global scale here! That setting is applied to object transformations during export",
"#~ # (in other words, this is pure blender-exporter feature, and has nothing to do with FBX data).",
"#~ if scene_data.settings.apply_unit_scale:",
"#~ # Unit scaling is applied to objects' scale, so our unit is effectively FBX one (centimeter).",
"#~ scale_factor_org = 1.0",
"#~ scale_factor = 1.0 / units_blender_to_fbx_factor(scene)",
"#~ else:",
"#~ scale_factor_org = units_blender_to_fbx_factor(scene)",
"#~ scale_factor = scale_factor_org",
"scale_factor",
"=",
"scale_factor_org",
"=",
"scene_data",
".",
"settings",
".",
"unit_scale",
"elem_props_set",
"(",
"props",
",",
"\"p_integer\"",
",",
"b\"UpAxis\"",
",",
"up_axis",
"[",
"0",
"]",
")",
"elem_props_set",
"(",
"props",
",",
"\"p_integer\"",
",",
"b\"UpAxisSign\"",
",",
"up_axis",
"[",
"1",
"]",
")",
"elem_props_set",
"(",
"props",
",",
"\"p_integer\"",
",",
"b\"FrontAxis\"",
",",
"front_axis",
"[",
"0",
"]",
")",
"elem_props_set",
"(",
"props",
",",
"\"p_integer\"",
",",
"b\"FrontAxisSign\"",
",",
"front_axis",
"[",
"1",
"]",
")",
"elem_props_set",
"(",
"props",
",",
"\"p_integer\"",
",",
"b\"CoordAxis\"",
",",
"coord_axis",
"[",
"0",
"]",
")",
"elem_props_set",
"(",
"props",
",",
"\"p_integer\"",
",",
"b\"CoordAxisSign\"",
",",
"coord_axis",
"[",
"1",
"]",
")",
"elem_props_set",
"(",
"props",
",",
"\"p_integer\"",
",",
"b\"OriginalUpAxis\"",
",",
"-",
"1",
")",
"elem_props_set",
"(",
"props",
",",
"\"p_integer\"",
",",
"b\"OriginalUpAxisSign\"",
",",
"1",
")",
"elem_props_set",
"(",
"props",
",",
"\"p_double\"",
",",
"b\"UnitScaleFactor\"",
",",
"scale_factor",
")",
"elem_props_set",
"(",
"props",
",",
"\"p_double\"",
",",
"b\"OriginalUnitScaleFactor\"",
",",
"scale_factor_org",
")",
"elem_props_set",
"(",
"props",
",",
"\"p_color_rgb\"",
",",
"b\"AmbientColor\"",
",",
"(",
"0.0",
",",
"0.0",
",",
"0.0",
")",
")",
"elem_props_set",
"(",
"props",
",",
"\"p_string\"",
",",
"b\"DefaultCamera\"",
",",
"\"Producer Perspective\"",
")",
"# Global timing data.",
"r",
"=",
"scene",
".",
"render",
"_",
",",
"fbx_fps_mode",
"=",
"FBX_FRAMERATES",
"[",
"0",
"]",
"# Custom framerate.",
"fbx_fps",
"=",
"fps",
"=",
"r",
".",
"fps",
"/",
"r",
".",
"fps_base",
"for",
"ref_fps",
",",
"fps_mode",
"in",
"FBX_FRAMERATES",
":",
"if",
"similar_values",
"(",
"fps",
",",
"ref_fps",
")",
":",
"fbx_fps",
"=",
"ref_fps",
"fbx_fps_mode",
"=",
"fps_mode",
"elem_props_set",
"(",
"props",
",",
"\"p_enum\"",
",",
"b\"TimeMode\"",
",",
"fbx_fps_mode",
")",
"elem_props_set",
"(",
"props",
",",
"\"p_timestamp\"",
",",
"b\"TimeSpanStart\"",
",",
"0",
")",
"elem_props_set",
"(",
"props",
",",
"\"p_timestamp\"",
",",
"b\"TimeSpanStop\"",
",",
"FBX_KTIME",
")",
"elem_props_set",
"(",
"props",
",",
"\"p_double\"",
",",
"b\"CustomFrameRate\"",
",",
"fbx_fps",
")"
] | https://github.com/etodd/lasercrabs/blob/91484d9ac3a47ac38b8f40ec3ff35194714dad8e/assets/script/etodd_blender_fbx/export_fbx_bin.py#L2661-L2786 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/utils/__init__.py | python | tosequence | (x) | Cast iterable x to a Sequence, avoiding a copy if possible.
Parameters
----------
x : iterable | Cast iterable x to a Sequence, avoiding a copy if possible. | [
"Cast",
"iterable",
"x",
"to",
"a",
"Sequence",
"avoiding",
"a",
"copy",
"if",
"possible",
"."
] | def tosequence(x):
"""Cast iterable x to a Sequence, avoiding a copy if possible.
Parameters
----------
x : iterable
"""
if isinstance(x, np.ndarray):
return np.asarray(x)
elif isinstance(x, Sequence):
return x
else:
return list(x) | [
"def",
"tosequence",
"(",
"x",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"np",
".",
"ndarray",
")",
":",
"return",
"np",
".",
"asarray",
"(",
"x",
")",
"elif",
"isinstance",
"(",
"x",
",",
"Sequence",
")",
":",
"return",
"x",
"else",
":",
"return",
"list",
"(",
"x",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/utils/__init__.py#L831-L843 | ||
grpc/grpc | 27bc6fe7797e43298dc931b96dc57322d0852a9f | src/python/grpcio/grpc/aio/_server.py | python | server | (migration_thread_pool: Optional[Executor] = None,
handlers: Optional[Sequence[grpc.GenericRpcHandler]] = None,
interceptors: Optional[Sequence[Any]] = None,
options: Optional[ChannelArgumentType] = None,
maximum_concurrent_rpcs: Optional[int] = None,
compression: Optional[grpc.Compression] = None) | return Server(migration_thread_pool, () if handlers is None else handlers,
() if interceptors is None else interceptors,
() if options is None else options, maximum_concurrent_rpcs,
compression) | Creates a Server with which RPCs can be serviced.
Args:
migration_thread_pool: A futures.ThreadPoolExecutor to be used by the
Server to execute non-AsyncIO RPC handlers for migration purpose.
handlers: An optional list of GenericRpcHandlers used for executing RPCs.
More handlers may be added by calling add_generic_rpc_handlers any time
before the server is started.
interceptors: An optional list of ServerInterceptor objects that observe
and optionally manipulate the incoming RPCs before handing them over to
handlers. The interceptors are given control in the order they are
specified. This is an EXPERIMENTAL API.
options: An optional list of key-value pairs (:term:`channel_arguments` in gRPC runtime)
to configure the channel.
maximum_concurrent_rpcs: The maximum number of concurrent RPCs this server
will service before returning RESOURCE_EXHAUSTED status, or None to
indicate no limit.
compression: An element of grpc.compression, e.g.
grpc.compression.Gzip. This compression algorithm will be used for the
lifetime of the server unless overridden by set_compression. This is an
EXPERIMENTAL option.
Returns:
A Server object. | Creates a Server with which RPCs can be serviced. | [
"Creates",
"a",
"Server",
"with",
"which",
"RPCs",
"can",
"be",
"serviced",
"."
] | def server(migration_thread_pool: Optional[Executor] = None,
handlers: Optional[Sequence[grpc.GenericRpcHandler]] = None,
interceptors: Optional[Sequence[Any]] = None,
options: Optional[ChannelArgumentType] = None,
maximum_concurrent_rpcs: Optional[int] = None,
compression: Optional[grpc.Compression] = None):
"""Creates a Server with which RPCs can be serviced.
Args:
migration_thread_pool: A futures.ThreadPoolExecutor to be used by the
Server to execute non-AsyncIO RPC handlers for migration purpose.
handlers: An optional list of GenericRpcHandlers used for executing RPCs.
More handlers may be added by calling add_generic_rpc_handlers any time
before the server is started.
interceptors: An optional list of ServerInterceptor objects that observe
and optionally manipulate the incoming RPCs before handing them over to
handlers. The interceptors are given control in the order they are
specified. This is an EXPERIMENTAL API.
options: An optional list of key-value pairs (:term:`channel_arguments` in gRPC runtime)
to configure the channel.
maximum_concurrent_rpcs: The maximum number of concurrent RPCs this server
will service before returning RESOURCE_EXHAUSTED status, or None to
indicate no limit.
compression: An element of grpc.compression, e.g.
grpc.compression.Gzip. This compression algorithm will be used for the
lifetime of the server unless overridden by set_compression. This is an
EXPERIMENTAL option.
Returns:
A Server object.
"""
return Server(migration_thread_pool, () if handlers is None else handlers,
() if interceptors is None else interceptors,
() if options is None else options, maximum_concurrent_rpcs,
compression) | [
"def",
"server",
"(",
"migration_thread_pool",
":",
"Optional",
"[",
"Executor",
"]",
"=",
"None",
",",
"handlers",
":",
"Optional",
"[",
"Sequence",
"[",
"grpc",
".",
"GenericRpcHandler",
"]",
"]",
"=",
"None",
",",
"interceptors",
":",
"Optional",
"[",
"Sequence",
"[",
"Any",
"]",
"]",
"=",
"None",
",",
"options",
":",
"Optional",
"[",
"ChannelArgumentType",
"]",
"=",
"None",
",",
"maximum_concurrent_rpcs",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"compression",
":",
"Optional",
"[",
"grpc",
".",
"Compression",
"]",
"=",
"None",
")",
":",
"return",
"Server",
"(",
"migration_thread_pool",
",",
"(",
")",
"if",
"handlers",
"is",
"None",
"else",
"handlers",
",",
"(",
")",
"if",
"interceptors",
"is",
"None",
"else",
"interceptors",
",",
"(",
")",
"if",
"options",
"is",
"None",
"else",
"options",
",",
"maximum_concurrent_rpcs",
",",
"compression",
")"
] | https://github.com/grpc/grpc/blob/27bc6fe7797e43298dc931b96dc57322d0852a9f/src/python/grpcio/grpc/aio/_server.py#L176-L210 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cuda/cudadrv/devices.py | python | _DeviceList.__getitem__ | (self, devnum) | return self.lst[devnum] | Returns the context manager for device *devnum*. | Returns the context manager for device *devnum*. | [
"Returns",
"the",
"context",
"manager",
"for",
"device",
"*",
"devnum",
"*",
"."
] | def __getitem__(self, devnum):
'''
Returns the context manager for device *devnum*.
'''
return self.lst[devnum] | [
"def",
"__getitem__",
"(",
"self",
",",
"devnum",
")",
":",
"return",
"self",
".",
"lst",
"[",
"devnum",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cuda/cudadrv/devices.py#L37-L41 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/setuptools/glibc.py | python | libc_ver | () | Try to determine the glibc version
Returns a tuple of strings (lib, version) which default to empty strings
in case the lookup fails. | Try to determine the glibc version | [
"Try",
"to",
"determine",
"the",
"glibc",
"version"
] | def libc_ver():
"""Try to determine the glibc version
Returns a tuple of strings (lib, version) which default to empty strings
in case the lookup fails.
"""
glibc_version = glibc_version_string()
if glibc_version is None:
return ("", "")
else:
return ("glibc", glibc_version) | [
"def",
"libc_ver",
"(",
")",
":",
"glibc_version",
"=",
"glibc_version_string",
"(",
")",
"if",
"glibc_version",
"is",
"None",
":",
"return",
"(",
"\"\"",
",",
"\"\"",
")",
"else",
":",
"return",
"(",
"\"glibc\"",
",",
"glibc_version",
")"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/setuptools/glibc.py#L76-L86 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/rsa/rsa/varblock.py | python | yield_varblocks | (infile) | Generator, yields each block in the input file.
@param infile: file to read, is expected to have the VARBLOCK format as
described in the module's docstring.
@yields the contents of each block. | Generator, yields each block in the input file. | [
"Generator",
"yields",
"each",
"block",
"in",
"the",
"input",
"file",
"."
] | def yield_varblocks(infile):
'''Generator, yields each block in the input file.
@param infile: file to read, is expected to have the VARBLOCK format as
described in the module's docstring.
@yields the contents of each block.
'''
# Check the version number
first_char = infile.read(1)
if len(first_char) == 0:
raise EOFError('Unable to read VARBLOCK version number')
version = ord(first_char)
if version != VARBLOCK_VERSION:
raise ValueError('VARBLOCK version %i not supported' % version)
while True:
(block_size, read_bytes) = read_varint(infile)
# EOF at block boundary, that's fine.
if read_bytes == 0 and block_size == 0:
break
block = infile.read(block_size)
read_size = len(block)
if read_size != block_size:
raise EOFError('Block size is %i, but could read only %i bytes' %
(block_size, read_size))
yield block | [
"def",
"yield_varblocks",
"(",
"infile",
")",
":",
"# Check the version number",
"first_char",
"=",
"infile",
".",
"read",
"(",
"1",
")",
"if",
"len",
"(",
"first_char",
")",
"==",
"0",
":",
"raise",
"EOFError",
"(",
"'Unable to read VARBLOCK version number'",
")",
"version",
"=",
"ord",
"(",
"first_char",
")",
"if",
"version",
"!=",
"VARBLOCK_VERSION",
":",
"raise",
"ValueError",
"(",
"'VARBLOCK version %i not supported'",
"%",
"version",
")",
"while",
"True",
":",
"(",
"block_size",
",",
"read_bytes",
")",
"=",
"read_varint",
"(",
"infile",
")",
"# EOF at block boundary, that's fine.",
"if",
"read_bytes",
"==",
"0",
"and",
"block_size",
"==",
"0",
":",
"break",
"block",
"=",
"infile",
".",
"read",
"(",
"block_size",
")",
"read_size",
"=",
"len",
"(",
"block",
")",
"if",
"read_size",
"!=",
"block_size",
":",
"raise",
"EOFError",
"(",
"'Block size is %i, but could read only %i bytes'",
"%",
"(",
"block_size",
",",
"read_size",
")",
")",
"yield",
"block"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/rsa/rsa/varblock.py#L103-L134 | ||
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/lib2to3/pytree.py | python | Base.remove | (self) | Remove the node from the tree. Returns the position of the node in its
parent's children before it was removed. | Remove the node from the tree. Returns the position of the node in its
parent's children before it was removed. | [
"Remove",
"the",
"node",
"from",
"the",
"tree",
".",
"Returns",
"the",
"position",
"of",
"the",
"node",
"in",
"its",
"parent",
"s",
"children",
"before",
"it",
"was",
"removed",
"."
] | def remove(self):
"""
Remove the node from the tree. Returns the position of the node in its
parent's children before it was removed.
"""
if self.parent:
for i, node in enumerate(self.parent.children):
if node is self:
self.parent.changed()
del self.parent.children[i]
self.parent = None
return i | [
"def",
"remove",
"(",
"self",
")",
":",
"if",
"self",
".",
"parent",
":",
"for",
"i",
",",
"node",
"in",
"enumerate",
"(",
"self",
".",
"parent",
".",
"children",
")",
":",
"if",
"node",
"is",
"self",
":",
"self",
".",
"parent",
".",
"changed",
"(",
")",
"del",
"self",
".",
"parent",
".",
"children",
"[",
"i",
"]",
"self",
".",
"parent",
"=",
"None",
"return",
"i"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/lib2to3/pytree.py#L170-L181 | ||
apache/qpid-proton | 6bcdfebb55ea3554bc29b1901422532db331a591 | python/proton/_reactor.py | python | Container.create_sender | (
self,
context: Union[str, Url, Connection],
target: Optional[str] = None,
source: Optional[str] = None,
name: Optional[str] = None,
handler: Optional[Handler] = None,
tags: Optional[Callable[[], bytes]] = None,
options: Optional[Union['SenderOption', List['SenderOption'], 'LinkOption', List['LinkOption']]] = None
) | return snd | Initiates the establishment of a link over which messages can
be sent.
There are two patterns of use:
1. A connection can be passed as the first argument, in which
case the link is established on that connection. In this case
the target address can be specified as the second argument (or
as a keyword argument). The source address can also be specified
if desired.
2. Alternatively a URL can be passed as the first argument. In
this case a new connection will be established on which the link
will be attached. If a path is specified and the target is not,
then the path of the URL is used as the target address.
The name of the link may be specified if desired, otherwise a
unique name will be generated.
Various :class:`LinkOption` s can be specified to further control the
attachment.
:param context: A connection object or a URL.
:param target: Address of target node.
:param source: Address of source node.
:param name: Sender name.
:param handler: Event handler for this sender.
:param tags: Function to generate tags for this sender of the form ``def simple_tags():`` and returns a ``bytes`` type
:param options: A single option, or a list of sender options
:return: New sender instance. | Initiates the establishment of a link over which messages can
be sent. | [
"Initiates",
"the",
"establishment",
"of",
"a",
"link",
"over",
"which",
"messages",
"can",
"be",
"sent",
"."
] | def create_sender(
self,
context: Union[str, Url, Connection],
target: Optional[str] = None,
source: Optional[str] = None,
name: Optional[str] = None,
handler: Optional[Handler] = None,
tags: Optional[Callable[[], bytes]] = None,
options: Optional[Union['SenderOption', List['SenderOption'], 'LinkOption', List['LinkOption']]] = None
) -> 'Sender':
"""
Initiates the establishment of a link over which messages can
be sent.
There are two patterns of use:
1. A connection can be passed as the first argument, in which
case the link is established on that connection. In this case
the target address can be specified as the second argument (or
as a keyword argument). The source address can also be specified
if desired.
2. Alternatively a URL can be passed as the first argument. In
this case a new connection will be established on which the link
will be attached. If a path is specified and the target is not,
then the path of the URL is used as the target address.
The name of the link may be specified if desired, otherwise a
unique name will be generated.
Various :class:`LinkOption` s can be specified to further control the
attachment.
:param context: A connection object or a URL.
:param target: Address of target node.
:param source: Address of source node.
:param name: Sender name.
:param handler: Event handler for this sender.
:param tags: Function to generate tags for this sender of the form ``def simple_tags():`` and returns a ``bytes`` type
:param options: A single option, or a list of sender options
:return: New sender instance.
"""
if isstring(context):
context = Url(context)
if isinstance(context, Url) and not target:
target = context.path
session = self._get_session(context)
snd = session.sender(name or self._get_id(session.connection.container, target, source))
if source:
snd.source.address = source
if target:
snd.target.address = target
if handler is not None:
snd.handler = handler
if tags:
snd.tag_generator = tags
_apply_link_options(options, snd)
snd.open()
return snd | [
"def",
"create_sender",
"(",
"self",
",",
"context",
":",
"Union",
"[",
"str",
",",
"Url",
",",
"Connection",
"]",
",",
"target",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"source",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"handler",
":",
"Optional",
"[",
"Handler",
"]",
"=",
"None",
",",
"tags",
":",
"Optional",
"[",
"Callable",
"[",
"[",
"]",
",",
"bytes",
"]",
"]",
"=",
"None",
",",
"options",
":",
"Optional",
"[",
"Union",
"[",
"'SenderOption'",
",",
"List",
"[",
"'SenderOption'",
"]",
",",
"'LinkOption'",
",",
"List",
"[",
"'LinkOption'",
"]",
"]",
"]",
"=",
"None",
")",
"->",
"'Sender'",
":",
"if",
"isstring",
"(",
"context",
")",
":",
"context",
"=",
"Url",
"(",
"context",
")",
"if",
"isinstance",
"(",
"context",
",",
"Url",
")",
"and",
"not",
"target",
":",
"target",
"=",
"context",
".",
"path",
"session",
"=",
"self",
".",
"_get_session",
"(",
"context",
")",
"snd",
"=",
"session",
".",
"sender",
"(",
"name",
"or",
"self",
".",
"_get_id",
"(",
"session",
".",
"connection",
".",
"container",
",",
"target",
",",
"source",
")",
")",
"if",
"source",
":",
"snd",
".",
"source",
".",
"address",
"=",
"source",
"if",
"target",
":",
"snd",
".",
"target",
".",
"address",
"=",
"target",
"if",
"handler",
"is",
"not",
"None",
":",
"snd",
".",
"handler",
"=",
"handler",
"if",
"tags",
":",
"snd",
".",
"tag_generator",
"=",
"tags",
"_apply_link_options",
"(",
"options",
",",
"snd",
")",
"snd",
".",
"open",
"(",
")",
"return",
"snd"
] | https://github.com/apache/qpid-proton/blob/6bcdfebb55ea3554bc29b1901422532db331a591/python/proton/_reactor.py#L1424-L1483 | |
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/build/fuchsia/common.py | python | EnsurePathExists | (path) | return path | Checks that the file |path| exists on the filesystem and returns the path
if it does, raising an exception otherwise. | Checks that the file |path| exists on the filesystem and returns the path
if it does, raising an exception otherwise. | [
"Checks",
"that",
"the",
"file",
"|path|",
"exists",
"on",
"the",
"filesystem",
"and",
"returns",
"the",
"path",
"if",
"it",
"does",
"raising",
"an",
"exception",
"otherwise",
"."
] | def EnsurePathExists(path):
"""Checks that the file |path| exists on the filesystem and returns the path
if it does, raising an exception otherwise."""
if not os.path.exists(path):
raise IOError('Missing file: ' + path)
return path | [
"def",
"EnsurePathExists",
"(",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"raise",
"IOError",
"(",
"'Missing file: '",
"+",
"path",
")",
"return",
"path"
] | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/fuchsia/common.py#L21-L28 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/collections/__init__.py | python | OrderedDict.keys | (self) | return _OrderedDictKeysView(self) | D.keys() -> a set-like object providing a view on D's keys | D.keys() -> a set-like object providing a view on D's keys | [
"D",
".",
"keys",
"()",
"-",
">",
"a",
"set",
"-",
"like",
"object",
"providing",
"a",
"view",
"on",
"D",
"s",
"keys"
] | def keys(self):
"D.keys() -> a set-like object providing a view on D's keys"
return _OrderedDictKeysView(self) | [
"def",
"keys",
"(",
"self",
")",
":",
"return",
"_OrderedDictKeysView",
"(",
"self",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/collections/__init__.py#L226-L228 | |
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/ipaddress.py | python | _BaseNetwork.is_private | (self) | return (self.network_address.is_private and
self.broadcast_address.is_private) | Test if this address is allocated for private networks.
Returns:
A boolean, True if the address is reserved per
iana-ipv4-special-registry or iana-ipv6-special-registry. | Test if this address is allocated for private networks. | [
"Test",
"if",
"this",
"address",
"is",
"allocated",
"for",
"private",
"networks",
"."
] | def is_private(self):
"""Test if this address is allocated for private networks.
Returns:
A boolean, True if the address is reserved per
iana-ipv4-special-registry or iana-ipv6-special-registry.
"""
return (self.network_address.is_private and
self.broadcast_address.is_private) | [
"def",
"is_private",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"network_address",
".",
"is_private",
"and",
"self",
".",
"broadcast_address",
".",
"is_private",
")"
] | https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/ipaddress.py#L1145-L1154 | |
seqan/seqan | f5f658343c366c9c3d44ba358ffc9317e78a09ed | util/py_lib/pyratemp.py | python | Template.__init__ | (self, string=None,filename=None,parsetree=None, encoding='utf-8', data=None, escape=HTML,
loader_class=LoaderFile,
parser_class=Parser,
renderer_class=Renderer,
eval_class=EvalPseudoSandbox,
escape_func=escape) | Load (+parse) a template.
:Parameters:
- `string,filename,parsetree`: a template-string,
filename of a template to load,
or a template-parsetree.
(only one of these 3 is allowed)
- `encoding`: encoding of the template-files (only used for "filename")
- `data`: data to fill into the template by default (dictionary).
This data may later be overridden when rendering the template.
- `escape`: default-escaping for the template, may be overwritten by the template!
- `loader_class`
- `parser_class`
- `renderer_class`
- `eval_class`
- `escapefunc` | Load (+parse) a template. | [
"Load",
"(",
"+",
"parse",
")",
"a",
"template",
"."
] | def __init__(self, string=None,filename=None,parsetree=None, encoding='utf-8', data=None, escape=HTML,
loader_class=LoaderFile,
parser_class=Parser,
renderer_class=Renderer,
eval_class=EvalPseudoSandbox,
escape_func=escape):
"""Load (+parse) a template.
:Parameters:
- `string,filename,parsetree`: a template-string,
filename of a template to load,
or a template-parsetree.
(only one of these 3 is allowed)
- `encoding`: encoding of the template-files (only used for "filename")
- `data`: data to fill into the template by default (dictionary).
This data may later be overridden when rendering the template.
- `escape`: default-escaping for the template, may be overwritten by the template!
- `loader_class`
- `parser_class`
- `renderer_class`
- `eval_class`
- `escapefunc`
"""
if [string, filename, parsetree].count(None) != 2:
raise ValueError('Exactly 1 of string,filename,parsetree is necessary.')
tmpl = None
# load template
if filename is not None:
incl_load = loader_class(os.path.dirname(filename), encoding).load
tmpl = incl_load(os.path.basename(filename))
if string is not None:
incl_load = dummy_raise(NotImplementedError, "'include' not supported for template-strings.")
tmpl = LoaderString(encoding).load(string)
# eval (incl. compile-cache)
templateeval = eval_class()
# parse
if tmpl is not None:
p = parser_class(loadfunc=incl_load, testexpr=templateeval.compile, escape=escape)
parsetree = p.parse(tmpl)
del p
# renderer
renderfunc = renderer_class(templateeval.eval, escape_func).render
#create template
TemplateBase.__init__(self, parsetree, renderfunc, data) | [
"def",
"__init__",
"(",
"self",
",",
"string",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"parsetree",
"=",
"None",
",",
"encoding",
"=",
"'utf-8'",
",",
"data",
"=",
"None",
",",
"escape",
"=",
"HTML",
",",
"loader_class",
"=",
"LoaderFile",
",",
"parser_class",
"=",
"Parser",
",",
"renderer_class",
"=",
"Renderer",
",",
"eval_class",
"=",
"EvalPseudoSandbox",
",",
"escape_func",
"=",
"escape",
")",
":",
"if",
"[",
"string",
",",
"filename",
",",
"parsetree",
"]",
".",
"count",
"(",
"None",
")",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"'Exactly 1 of string,filename,parsetree is necessary.'",
")",
"tmpl",
"=",
"None",
"# load template",
"if",
"filename",
"is",
"not",
"None",
":",
"incl_load",
"=",
"loader_class",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
",",
"encoding",
")",
".",
"load",
"tmpl",
"=",
"incl_load",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
")",
"if",
"string",
"is",
"not",
"None",
":",
"incl_load",
"=",
"dummy_raise",
"(",
"NotImplementedError",
",",
"\"'include' not supported for template-strings.\"",
")",
"tmpl",
"=",
"LoaderString",
"(",
"encoding",
")",
".",
"load",
"(",
"string",
")",
"# eval (incl. compile-cache)",
"templateeval",
"=",
"eval_class",
"(",
")",
"# parse",
"if",
"tmpl",
"is",
"not",
"None",
":",
"p",
"=",
"parser_class",
"(",
"loadfunc",
"=",
"incl_load",
",",
"testexpr",
"=",
"templateeval",
".",
"compile",
",",
"escape",
"=",
"escape",
")",
"parsetree",
"=",
"p",
".",
"parse",
"(",
"tmpl",
")",
"del",
"p",
"# renderer",
"renderfunc",
"=",
"renderer_class",
"(",
"templateeval",
".",
"eval",
",",
"escape_func",
")",
".",
"render",
"#create template",
"TemplateBase",
".",
"__init__",
"(",
"self",
",",
"parsetree",
",",
"renderfunc",
",",
"data",
")"
] | https://github.com/seqan/seqan/blob/f5f658343c366c9c3d44ba358ffc9317e78a09ed/util/py_lib/pyratemp.py#L1129-L1177 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/lib2to3/pytree.py | python | Base.__ne__ | (self, other) | return not self._eq(other) | Compare two nodes for inequality.
This calls the method _eq(). | Compare two nodes for inequality. | [
"Compare",
"two",
"nodes",
"for",
"inequality",
"."
] | def __ne__(self, other):
"""
Compare two nodes for inequality.
This calls the method _eq().
"""
if self.__class__ is not other.__class__:
return NotImplemented
return not self._eq(other) | [
"def",
"__ne__",
"(",
"self",
",",
"other",
")",
":",
"if",
"self",
".",
"__class__",
"is",
"not",
"other",
".",
"__class__",
":",
"return",
"NotImplemented",
"return",
"not",
"self",
".",
"_eq",
"(",
"other",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib2to3/pytree.py#L67-L75 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/docutils/nodes.py | python | Element.update_all_atts_coercion | (self, dict_, replace = True,
and_source = False) | Updates all attributes from node or dictionary `dict_`.
Appends the basic attributes ('ids', 'names', 'classes',
'dupnames', but not 'source') and then, for all other attributes in
dict_, updates the same attribute in self. When attributes with the
same identifier appear in both self and dict_ whose values are both
not lists and replace is True, the values in self are replaced with
the values in dict_; if either of the values from self and dict_ for
the given identifier are of list type, then first any non-lists are
converted to 1-element lists and then the two lists are concatenated
and the result stored in self; otherwise, the values in self are
preserved. When and_source is True, the 'source' attribute is
included in the copy.
NOTE: When replace is False, and self contains a 'source' attribute,
'source' is not replaced even when dict_ has a 'source'
attribute, though it may still be merged into a list depending
on the value of update_fun. | Updates all attributes from node or dictionary `dict_`. | [
"Updates",
"all",
"attributes",
"from",
"node",
"or",
"dictionary",
"dict_",
"."
] | def update_all_atts_coercion(self, dict_, replace = True,
and_source = False):
"""
Updates all attributes from node or dictionary `dict_`.
Appends the basic attributes ('ids', 'names', 'classes',
'dupnames', but not 'source') and then, for all other attributes in
dict_, updates the same attribute in self. When attributes with the
same identifier appear in both self and dict_ whose values are both
not lists and replace is True, the values in self are replaced with
the values in dict_; if either of the values from self and dict_ for
the given identifier are of list type, then first any non-lists are
converted to 1-element lists and then the two lists are concatenated
and the result stored in self; otherwise, the values in self are
preserved. When and_source is True, the 'source' attribute is
included in the copy.
NOTE: When replace is False, and self contains a 'source' attribute,
'source' is not replaced even when dict_ has a 'source'
attribute, though it may still be merged into a list depending
on the value of update_fun.
"""
self.update_all_atts(dict_, Element.copy_attr_coerce, replace,
and_source) | [
"def",
"update_all_atts_coercion",
"(",
"self",
",",
"dict_",
",",
"replace",
"=",
"True",
",",
"and_source",
"=",
"False",
")",
":",
"self",
".",
"update_all_atts",
"(",
"dict_",
",",
"Element",
".",
"copy_attr_coerce",
",",
"replace",
",",
"and_source",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/nodes.py#L877-L900 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/turtle.py | python | TurtleScreenBase._ondrag | (self, item, fun, num=1, add=None) | Bind fun to mouse-move-event (with pressed mouse button) on turtle.
fun must be a function with two arguments, the coordinates of the
actual mouse position on the canvas.
num, the number of the mouse-button defaults to 1
Every sequence of mouse-move-events on a turtle is preceded by a
mouse-click event on that turtle. | Bind fun to mouse-move-event (with pressed mouse button) on turtle.
fun must be a function with two arguments, the coordinates of the
actual mouse position on the canvas.
num, the number of the mouse-button defaults to 1 | [
"Bind",
"fun",
"to",
"mouse",
"-",
"move",
"-",
"event",
"(",
"with",
"pressed",
"mouse",
"button",
")",
"on",
"turtle",
".",
"fun",
"must",
"be",
"a",
"function",
"with",
"two",
"arguments",
"the",
"coordinates",
"of",
"the",
"actual",
"mouse",
"position",
"on",
"the",
"canvas",
".",
"num",
"the",
"number",
"of",
"the",
"mouse",
"-",
"button",
"defaults",
"to",
"1"
] | def _ondrag(self, item, fun, num=1, add=None):
"""Bind fun to mouse-move-event (with pressed mouse button) on turtle.
fun must be a function with two arguments, the coordinates of the
actual mouse position on the canvas.
num, the number of the mouse-button defaults to 1
Every sequence of mouse-move-events on a turtle is preceded by a
mouse-click event on that turtle.
"""
if fun is None:
self.cv.tag_unbind(item, "<Button%s-Motion>" % num)
else:
def eventfun(event):
try:
x, y = (self.cv.canvasx(event.x)/self.xscale,
-self.cv.canvasy(event.y)/self.yscale)
fun(x, y)
except Exception:
pass
self.cv.tag_bind(item, "<Button%s-Motion>" % num, eventfun, add) | [
"def",
"_ondrag",
"(",
"self",
",",
"item",
",",
"fun",
",",
"num",
"=",
"1",
",",
"add",
"=",
"None",
")",
":",
"if",
"fun",
"is",
"None",
":",
"self",
".",
"cv",
".",
"tag_unbind",
"(",
"item",
",",
"\"<Button%s-Motion>\"",
"%",
"num",
")",
"else",
":",
"def",
"eventfun",
"(",
"event",
")",
":",
"try",
":",
"x",
",",
"y",
"=",
"(",
"self",
".",
"cv",
".",
"canvasx",
"(",
"event",
".",
"x",
")",
"/",
"self",
".",
"xscale",
",",
"-",
"self",
".",
"cv",
".",
"canvasy",
"(",
"event",
".",
"y",
")",
"/",
"self",
".",
"yscale",
")",
"fun",
"(",
"x",
",",
"y",
")",
"except",
"Exception",
":",
"pass",
"self",
".",
"cv",
".",
"tag_bind",
"(",
"item",
",",
"\"<Button%s-Motion>\"",
"%",
"num",
",",
"eventfun",
",",
"add",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/turtle.py#L639-L658 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/distutils/cygwinccompiler.py | python | is_cygwingcc | () | return out_string.strip().endswith(b'cygwin') | Try to determine if the gcc that would be used is from cygwin. | Try to determine if the gcc that would be used is from cygwin. | [
"Try",
"to",
"determine",
"if",
"the",
"gcc",
"that",
"would",
"be",
"used",
"is",
"from",
"cygwin",
"."
] | def is_cygwingcc():
'''Try to determine if the gcc that would be used is from cygwin.'''
out_string = check_output(['gcc', '-dumpmachine'])
return out_string.strip().endswith(b'cygwin') | [
"def",
"is_cygwingcc",
"(",
")",
":",
"out_string",
"=",
"check_output",
"(",
"[",
"'gcc'",
",",
"'-dumpmachine'",
"]",
")",
"return",
"out_string",
".",
"strip",
"(",
")",
".",
"endswith",
"(",
"b'cygwin'",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/distutils/cygwinccompiler.py#L400-L403 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Path/PathScripts/PathPocket.py | python | ObjectPocket.groupConnectedEdges | (self, holding) | return (low, high) | groupConnectedEdges(self, holding)
Take edges and determine which are connected.
Group connected chains/loops into: low and high | groupConnectedEdges(self, holding)
Take edges and determine which are connected.
Group connected chains/loops into: low and high | [
"groupConnectedEdges",
"(",
"self",
"holding",
")",
"Take",
"edges",
"and",
"determine",
"which",
"are",
"connected",
".",
"Group",
"connected",
"chains",
"/",
"loops",
"into",
":",
"low",
"and",
"high"
] | def groupConnectedEdges(self, holding):
"""groupConnectedEdges(self, holding)
Take edges and determine which are connected.
Group connected chains/loops into: low and high"""
holds = []
grps = []
searched = []
stop = False
attachments = []
loops = 1
def updateAttachments(grps):
atchmnts = []
lenGrps = len(grps)
if lenGrps > 0:
lenG0 = len(grps[0])
if lenG0 < 2:
atchmnts.append((0, 0))
else:
atchmnts.append((0, 0))
atchmnts.append((0, lenG0 - 1))
if lenGrps == 2:
lenG1 = len(grps[1])
if lenG1 < 2:
atchmnts.append((1, 0))
else:
atchmnts.append((1, 0))
atchmnts.append((1, lenG1 - 1))
return atchmnts
def isSameVertex(o, t):
if o.X == t.X:
if o.Y == t.Y:
if o.Z == t.Z:
return True
return False
for hi in range(0, len(holding)):
holds.append(hi)
# Place initial edge in first group and update attachments
h0 = holds.pop()
grps.append([h0])
attachments = updateAttachments(grps)
while len(holds) > 0:
if loops > 500:
PathLog.error("BREAK --- LOOPS LIMIT of 500 ---")
break
save = False
h2 = holds.pop()
(sub2, face2, ei2) = holding[h2]
# Cycle through attachments for connection to existing
for (g, t) in attachments:
h1 = grps[g][t]
(sub1, face1, ei1) = holding[h1]
edg1 = face1.Edges[ei1]
edg2 = face2.Edges[ei2]
# CV = self.hasCommonVertex(edg1, edg2, show=False)
# Check attachment based on attachments order
if t == 0:
# is last vertex of h2 == first vertex of h1
e2lv = len(edg2.Vertexes) - 1
one = edg2.Vertexes[e2lv]
two = edg1.Vertexes[0]
if isSameVertex(one, two) is True:
# Connected, insert h1 in front of h2
grps[g].insert(0, h2)
stop = True
else:
# is last vertex of h1 == first vertex of h2
e1lv = len(edg1.Vertexes) - 1
one = edg1.Vertexes[e1lv]
two = edg2.Vertexes[0]
if isSameVertex(one, two) is True:
# Connected, append h1 after h2
grps[g].append(h2)
stop = True
if stop is True:
# attachment was found
attachments = updateAttachments(grps)
holds.extend(searched)
stop = False
break
else:
# no attachment found
save = True
# Efor
if save is True:
searched.append(h2)
if len(holds) == 0:
if len(grps) == 1:
h0 = searched.pop(0)
grps.append([h0])
attachments = updateAttachments(grps)
holds.extend(searched)
# Eif
loops += 1
# Ewhile
low = []
high = []
if len(grps) == 1:
grps.append([])
grp0 = []
grp1 = []
com0 = FreeCAD.Vector(0, 0, 0)
com1 = FreeCAD.Vector(0, 0, 0)
if len(grps[0]) > 0:
for g in grps[0]:
grp0.append(holding[g])
(sub, face, ei) = holding[g]
com0 = com0.add(face.Edges[ei].CenterOfMass)
com0z = com0.z / len(grps[0])
if len(grps[1]) > 0:
for g in grps[1]:
grp1.append(holding[g])
(sub, face, ei) = holding[g]
com1 = com1.add(face.Edges[ei].CenterOfMass)
com1z = com1.z / len(grps[1])
if len(grps[1]) > 0:
if com0z > com1z:
low = grp1
high = grp0
else:
low = grp0
high = grp1
else:
low = grp0
high = grp0
return (low, high) | [
"def",
"groupConnectedEdges",
"(",
"self",
",",
"holding",
")",
":",
"holds",
"=",
"[",
"]",
"grps",
"=",
"[",
"]",
"searched",
"=",
"[",
"]",
"stop",
"=",
"False",
"attachments",
"=",
"[",
"]",
"loops",
"=",
"1",
"def",
"updateAttachments",
"(",
"grps",
")",
":",
"atchmnts",
"=",
"[",
"]",
"lenGrps",
"=",
"len",
"(",
"grps",
")",
"if",
"lenGrps",
">",
"0",
":",
"lenG0",
"=",
"len",
"(",
"grps",
"[",
"0",
"]",
")",
"if",
"lenG0",
"<",
"2",
":",
"atchmnts",
".",
"append",
"(",
"(",
"0",
",",
"0",
")",
")",
"else",
":",
"atchmnts",
".",
"append",
"(",
"(",
"0",
",",
"0",
")",
")",
"atchmnts",
".",
"append",
"(",
"(",
"0",
",",
"lenG0",
"-",
"1",
")",
")",
"if",
"lenGrps",
"==",
"2",
":",
"lenG1",
"=",
"len",
"(",
"grps",
"[",
"1",
"]",
")",
"if",
"lenG1",
"<",
"2",
":",
"atchmnts",
".",
"append",
"(",
"(",
"1",
",",
"0",
")",
")",
"else",
":",
"atchmnts",
".",
"append",
"(",
"(",
"1",
",",
"0",
")",
")",
"atchmnts",
".",
"append",
"(",
"(",
"1",
",",
"lenG1",
"-",
"1",
")",
")",
"return",
"atchmnts",
"def",
"isSameVertex",
"(",
"o",
",",
"t",
")",
":",
"if",
"o",
".",
"X",
"==",
"t",
".",
"X",
":",
"if",
"o",
".",
"Y",
"==",
"t",
".",
"Y",
":",
"if",
"o",
".",
"Z",
"==",
"t",
".",
"Z",
":",
"return",
"True",
"return",
"False",
"for",
"hi",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"holding",
")",
")",
":",
"holds",
".",
"append",
"(",
"hi",
")",
"# Place initial edge in first group and update attachments",
"h0",
"=",
"holds",
".",
"pop",
"(",
")",
"grps",
".",
"append",
"(",
"[",
"h0",
"]",
")",
"attachments",
"=",
"updateAttachments",
"(",
"grps",
")",
"while",
"len",
"(",
"holds",
")",
">",
"0",
":",
"if",
"loops",
">",
"500",
":",
"PathLog",
".",
"error",
"(",
"\"BREAK --- LOOPS LIMIT of 500 ---\"",
")",
"break",
"save",
"=",
"False",
"h2",
"=",
"holds",
".",
"pop",
"(",
")",
"(",
"sub2",
",",
"face2",
",",
"ei2",
")",
"=",
"holding",
"[",
"h2",
"]",
"# Cycle through attachments for connection to existing",
"for",
"(",
"g",
",",
"t",
")",
"in",
"attachments",
":",
"h1",
"=",
"grps",
"[",
"g",
"]",
"[",
"t",
"]",
"(",
"sub1",
",",
"face1",
",",
"ei1",
")",
"=",
"holding",
"[",
"h1",
"]",
"edg1",
"=",
"face1",
".",
"Edges",
"[",
"ei1",
"]",
"edg2",
"=",
"face2",
".",
"Edges",
"[",
"ei2",
"]",
"# CV = self.hasCommonVertex(edg1, edg2, show=False)",
"# Check attachment based on attachments order",
"if",
"t",
"==",
"0",
":",
"# is last vertex of h2 == first vertex of h1",
"e2lv",
"=",
"len",
"(",
"edg2",
".",
"Vertexes",
")",
"-",
"1",
"one",
"=",
"edg2",
".",
"Vertexes",
"[",
"e2lv",
"]",
"two",
"=",
"edg1",
".",
"Vertexes",
"[",
"0",
"]",
"if",
"isSameVertex",
"(",
"one",
",",
"two",
")",
"is",
"True",
":",
"# Connected, insert h1 in front of h2",
"grps",
"[",
"g",
"]",
".",
"insert",
"(",
"0",
",",
"h2",
")",
"stop",
"=",
"True",
"else",
":",
"# is last vertex of h1 == first vertex of h2",
"e1lv",
"=",
"len",
"(",
"edg1",
".",
"Vertexes",
")",
"-",
"1",
"one",
"=",
"edg1",
".",
"Vertexes",
"[",
"e1lv",
"]",
"two",
"=",
"edg2",
".",
"Vertexes",
"[",
"0",
"]",
"if",
"isSameVertex",
"(",
"one",
",",
"two",
")",
"is",
"True",
":",
"# Connected, append h1 after h2",
"grps",
"[",
"g",
"]",
".",
"append",
"(",
"h2",
")",
"stop",
"=",
"True",
"if",
"stop",
"is",
"True",
":",
"# attachment was found",
"attachments",
"=",
"updateAttachments",
"(",
"grps",
")",
"holds",
".",
"extend",
"(",
"searched",
")",
"stop",
"=",
"False",
"break",
"else",
":",
"# no attachment found",
"save",
"=",
"True",
"# Efor",
"if",
"save",
"is",
"True",
":",
"searched",
".",
"append",
"(",
"h2",
")",
"if",
"len",
"(",
"holds",
")",
"==",
"0",
":",
"if",
"len",
"(",
"grps",
")",
"==",
"1",
":",
"h0",
"=",
"searched",
".",
"pop",
"(",
"0",
")",
"grps",
".",
"append",
"(",
"[",
"h0",
"]",
")",
"attachments",
"=",
"updateAttachments",
"(",
"grps",
")",
"holds",
".",
"extend",
"(",
"searched",
")",
"# Eif",
"loops",
"+=",
"1",
"# Ewhile",
"low",
"=",
"[",
"]",
"high",
"=",
"[",
"]",
"if",
"len",
"(",
"grps",
")",
"==",
"1",
":",
"grps",
".",
"append",
"(",
"[",
"]",
")",
"grp0",
"=",
"[",
"]",
"grp1",
"=",
"[",
"]",
"com0",
"=",
"FreeCAD",
".",
"Vector",
"(",
"0",
",",
"0",
",",
"0",
")",
"com1",
"=",
"FreeCAD",
".",
"Vector",
"(",
"0",
",",
"0",
",",
"0",
")",
"if",
"len",
"(",
"grps",
"[",
"0",
"]",
")",
">",
"0",
":",
"for",
"g",
"in",
"grps",
"[",
"0",
"]",
":",
"grp0",
".",
"append",
"(",
"holding",
"[",
"g",
"]",
")",
"(",
"sub",
",",
"face",
",",
"ei",
")",
"=",
"holding",
"[",
"g",
"]",
"com0",
"=",
"com0",
".",
"add",
"(",
"face",
".",
"Edges",
"[",
"ei",
"]",
".",
"CenterOfMass",
")",
"com0z",
"=",
"com0",
".",
"z",
"/",
"len",
"(",
"grps",
"[",
"0",
"]",
")",
"if",
"len",
"(",
"grps",
"[",
"1",
"]",
")",
">",
"0",
":",
"for",
"g",
"in",
"grps",
"[",
"1",
"]",
":",
"grp1",
".",
"append",
"(",
"holding",
"[",
"g",
"]",
")",
"(",
"sub",
",",
"face",
",",
"ei",
")",
"=",
"holding",
"[",
"g",
"]",
"com1",
"=",
"com1",
".",
"add",
"(",
"face",
".",
"Edges",
"[",
"ei",
"]",
".",
"CenterOfMass",
")",
"com1z",
"=",
"com1",
".",
"z",
"/",
"len",
"(",
"grps",
"[",
"1",
"]",
")",
"if",
"len",
"(",
"grps",
"[",
"1",
"]",
")",
">",
"0",
":",
"if",
"com0z",
">",
"com1z",
":",
"low",
"=",
"grp1",
"high",
"=",
"grp0",
"else",
":",
"low",
"=",
"grp0",
"high",
"=",
"grp1",
"else",
":",
"low",
"=",
"grp0",
"high",
"=",
"grp0",
"return",
"(",
"low",
",",
"high",
")"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathPocket.py#L681-L819 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/implement-magic-dictionary.py | python | MagicDictionary.search | (self, word) | return find(word, self.trie, 0, True) | Returns if there is any word in the trie that equals to the given word after modifying exactly one character
:type word: str
:rtype: bool | Returns if there is any word in the trie that equals to the given word after modifying exactly one character
:type word: str
:rtype: bool | [
"Returns",
"if",
"there",
"is",
"any",
"word",
"in",
"the",
"trie",
"that",
"equals",
"to",
"the",
"given",
"word",
"after",
"modifying",
"exactly",
"one",
"character",
":",
"type",
"word",
":",
"str",
":",
"rtype",
":",
"bool"
] | def search(self, word):
"""
Returns if there is any word in the trie that equals to the given word after modifying exactly one character
:type word: str
:rtype: bool
"""
def find(word, curr, i, mistakeAllowed):
if i == len(word):
return "_end" in curr and not mistakeAllowed
if word[i] not in curr:
return any(find(word, curr[c], i+1, False) for c in curr if c != "_end") \
if mistakeAllowed else False
if mistakeAllowed:
return find(word, curr[word[i]], i+1, True) or \
any(find(word, curr[c], i+1, False) \
for c in curr if c not in ("_end", word[i]))
return find(word, curr[word[i]], i+1, False)
return find(word, self.trie, 0, True) | [
"def",
"search",
"(",
"self",
",",
"word",
")",
":",
"def",
"find",
"(",
"word",
",",
"curr",
",",
"i",
",",
"mistakeAllowed",
")",
":",
"if",
"i",
"==",
"len",
"(",
"word",
")",
":",
"return",
"\"_end\"",
"in",
"curr",
"and",
"not",
"mistakeAllowed",
"if",
"word",
"[",
"i",
"]",
"not",
"in",
"curr",
":",
"return",
"any",
"(",
"find",
"(",
"word",
",",
"curr",
"[",
"c",
"]",
",",
"i",
"+",
"1",
",",
"False",
")",
"for",
"c",
"in",
"curr",
"if",
"c",
"!=",
"\"_end\"",
")",
"if",
"mistakeAllowed",
"else",
"False",
"if",
"mistakeAllowed",
":",
"return",
"find",
"(",
"word",
",",
"curr",
"[",
"word",
"[",
"i",
"]",
"]",
",",
"i",
"+",
"1",
",",
"True",
")",
"or",
"any",
"(",
"find",
"(",
"word",
",",
"curr",
"[",
"c",
"]",
",",
"i",
"+",
"1",
",",
"False",
")",
"for",
"c",
"in",
"curr",
"if",
"c",
"not",
"in",
"(",
"\"_end\"",
",",
"word",
"[",
"i",
"]",
")",
")",
"return",
"find",
"(",
"word",
",",
"curr",
"[",
"word",
"[",
"i",
"]",
"]",
",",
"i",
"+",
"1",
",",
"False",
")",
"return",
"find",
"(",
"word",
",",
"self",
".",
"trie",
",",
"0",
",",
"True",
")"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/implement-magic-dictionary.py#L27-L47 | |
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | thirdparty/parser/sm/js/src/build/win32/pgomerge.py | python | MergePGOFiles | (basename, pgddir, pgcdir) | Merge pgc files produced from an instrumented binary
into the pgd file for the second pass of profile-guided optimization
with MSVC. |basename| is the name of the DLL or EXE without the
extension. |pgddir| is the path that contains <basename>.pgd
(should be the objdir it was built in). |pgcdir| is the path
containing basename!N.pgc files, which is probably dist/bin.
Calls pgomgr to merge each pgc file into the pgd, then deletes
the pgc files. | Merge pgc files produced from an instrumented binary
into the pgd file for the second pass of profile-guided optimization
with MSVC. |basename| is the name of the DLL or EXE without the
extension. |pgddir| is the path that contains <basename>.pgd
(should be the objdir it was built in). |pgcdir| is the path
containing basename!N.pgc files, which is probably dist/bin.
Calls pgomgr to merge each pgc file into the pgd, then deletes
the pgc files. | [
"Merge",
"pgc",
"files",
"produced",
"from",
"an",
"instrumented",
"binary",
"into",
"the",
"pgd",
"file",
"for",
"the",
"second",
"pass",
"of",
"profile",
"-",
"guided",
"optimization",
"with",
"MSVC",
".",
"|basename|",
"is",
"the",
"name",
"of",
"the",
"DLL",
"or",
"EXE",
"without",
"the",
"extension",
".",
"|pgddir|",
"is",
"the",
"path",
"that",
"contains",
"<basename",
">",
".",
"pgd",
"(",
"should",
"be",
"the",
"objdir",
"it",
"was",
"built",
"in",
")",
".",
"|pgcdir|",
"is",
"the",
"path",
"containing",
"basename!N",
".",
"pgc",
"files",
"which",
"is",
"probably",
"dist",
"/",
"bin",
".",
"Calls",
"pgomgr",
"to",
"merge",
"each",
"pgc",
"file",
"into",
"the",
"pgd",
"then",
"deletes",
"the",
"pgc",
"files",
"."
] | def MergePGOFiles(basename, pgddir, pgcdir):
"""Merge pgc files produced from an instrumented binary
into the pgd file for the second pass of profile-guided optimization
with MSVC. |basename| is the name of the DLL or EXE without the
extension. |pgddir| is the path that contains <basename>.pgd
(should be the objdir it was built in). |pgcdir| is the path
containing basename!N.pgc files, which is probably dist/bin.
Calls pgomgr to merge each pgc file into the pgd, then deletes
the pgc files."""
if not os.path.isdir(pgddir) or not os.path.isdir(pgcdir):
return
pgdfile = os.path.abspath(os.path.join(pgddir, basename + ".pgd"))
if not os.path.isfile(pgdfile):
return
for file in os.listdir(pgcdir):
if file.startswith(basename+"!") and file.endswith(".pgc"):
try:
pgcfile = os.path.normpath(os.path.join(pgcdir, file))
subprocess.call(['pgomgr', '-merge',
pgcfile,
pgdfile])
os.remove(pgcfile)
except OSError:
pass | [
"def",
"MergePGOFiles",
"(",
"basename",
",",
"pgddir",
",",
"pgcdir",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"pgddir",
")",
"or",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"pgcdir",
")",
":",
"return",
"pgdfile",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"pgddir",
",",
"basename",
"+",
"\".pgd\"",
")",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"pgdfile",
")",
":",
"return",
"for",
"file",
"in",
"os",
".",
"listdir",
"(",
"pgcdir",
")",
":",
"if",
"file",
".",
"startswith",
"(",
"basename",
"+",
"\"!\"",
")",
"and",
"file",
".",
"endswith",
"(",
"\".pgc\"",
")",
":",
"try",
":",
"pgcfile",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"pgcdir",
",",
"file",
")",
")",
"subprocess",
".",
"call",
"(",
"[",
"'pgomgr'",
",",
"'-merge'",
",",
"pgcfile",
",",
"pgdfile",
"]",
")",
"os",
".",
"remove",
"(",
"pgcfile",
")",
"except",
"OSError",
":",
"pass"
] | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/thirdparty/parser/sm/js/src/build/win32/pgomerge.py#L11-L34 | ||
gnuradio/gnuradio | 09c3c4fa4bfb1a02caac74cb5334dfe065391e3b | grc/core/FlowGraph.py | python | FlowGraph.rewrite | (self) | Flag the namespace to be renewed. | Flag the namespace to be renewed. | [
"Flag",
"the",
"namespace",
"to",
"be",
"renewed",
"."
] | def rewrite(self):
"""
Flag the namespace to be renewed.
"""
self.renew_namespace()
Element.rewrite(self) | [
"def",
"rewrite",
"(",
"self",
")",
":",
"self",
".",
"renew_namespace",
"(",
")",
"Element",
".",
"rewrite",
"(",
"self",
")"
] | https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/grc/core/FlowGraph.py#L225-L230 | ||
sdhash/sdhash | b9eff63e4e5867e910f41fd69032bbb1c94a2a5e | sdhash-ui/thrift/transport/TZlibTransport.py | python | TZlibTransport.write | (self, buf) | Write some bytes, putting them into the internal write
buffer for eventual compression. | Write some bytes, putting them into the internal write
buffer for eventual compression. | [
"Write",
"some",
"bytes",
"putting",
"them",
"into",
"the",
"internal",
"write",
"buffer",
"for",
"eventual",
"compression",
"."
] | def write(self, buf):
'''
Write some bytes, putting them into the internal write
buffer for eventual compression.
'''
self.__wbuf.write(buf) | [
"def",
"write",
"(",
"self",
",",
"buf",
")",
":",
"self",
".",
"__wbuf",
".",
"write",
"(",
"buf",
")"
] | https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/thrift/transport/TZlibTransport.py#L222-L227 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/cluster/_kmeans.py | python | _labels_inertia | (X, sample_weight, x_squared_norms, centers,
precompute_distances=True, distances=None) | return labels, inertia | E step of the K-means EM algorithm.
Compute the labels and the inertia of the given samples and centers.
This will compute the distances in-place.
Parameters
----------
X : float64 array-like or CSR sparse matrix, shape (n_samples, n_features)
The input samples to assign to the labels.
sample_weight : array-like, shape (n_samples,)
The weights for each observation in X.
x_squared_norms : array, shape (n_samples,)
Precomputed squared euclidean norm of each data point, to speed up
computations.
centers : float array, shape (k, n_features)
The cluster centers.
precompute_distances : boolean, default: True
Precompute distances (faster but takes more memory).
distances : float array, shape (n_samples,)
Pre-allocated array to be filled in with each sample's distance
to the closest center.
Returns
-------
labels : int array of shape(n)
The resulting assignment
inertia : float
Sum of squared distances of samples to their closest cluster center. | E step of the K-means EM algorithm. | [
"E",
"step",
"of",
"the",
"K",
"-",
"means",
"EM",
"algorithm",
"."
] | def _labels_inertia(X, sample_weight, x_squared_norms, centers,
precompute_distances=True, distances=None):
"""E step of the K-means EM algorithm.
Compute the labels and the inertia of the given samples and centers.
This will compute the distances in-place.
Parameters
----------
X : float64 array-like or CSR sparse matrix, shape (n_samples, n_features)
The input samples to assign to the labels.
sample_weight : array-like, shape (n_samples,)
The weights for each observation in X.
x_squared_norms : array, shape (n_samples,)
Precomputed squared euclidean norm of each data point, to speed up
computations.
centers : float array, shape (k, n_features)
The cluster centers.
precompute_distances : boolean, default: True
Precompute distances (faster but takes more memory).
distances : float array, shape (n_samples,)
Pre-allocated array to be filled in with each sample's distance
to the closest center.
Returns
-------
labels : int array of shape(n)
The resulting assignment
inertia : float
Sum of squared distances of samples to their closest cluster center.
"""
n_samples = X.shape[0]
sample_weight = _check_normalize_sample_weight(sample_weight, X)
# set the default value of centers to -1 to be able to detect any anomaly
# easily
labels = np.full(n_samples, -1, np.int32)
if distances is None:
distances = np.zeros(shape=(0,), dtype=X.dtype)
# distances will be changed in-place
if sp.issparse(X):
inertia = _k_means._assign_labels_csr(
X, sample_weight, x_squared_norms, centers, labels,
distances=distances)
else:
if precompute_distances:
return _labels_inertia_precompute_dense(X, sample_weight,
x_squared_norms, centers,
distances)
inertia = _k_means._assign_labels_array(
X, sample_weight, x_squared_norms, centers, labels,
distances=distances)
return labels, inertia | [
"def",
"_labels_inertia",
"(",
"X",
",",
"sample_weight",
",",
"x_squared_norms",
",",
"centers",
",",
"precompute_distances",
"=",
"True",
",",
"distances",
"=",
"None",
")",
":",
"n_samples",
"=",
"X",
".",
"shape",
"[",
"0",
"]",
"sample_weight",
"=",
"_check_normalize_sample_weight",
"(",
"sample_weight",
",",
"X",
")",
"# set the default value of centers to -1 to be able to detect any anomaly",
"# easily",
"labels",
"=",
"np",
".",
"full",
"(",
"n_samples",
",",
"-",
"1",
",",
"np",
".",
"int32",
")",
"if",
"distances",
"is",
"None",
":",
"distances",
"=",
"np",
".",
"zeros",
"(",
"shape",
"=",
"(",
"0",
",",
")",
",",
"dtype",
"=",
"X",
".",
"dtype",
")",
"# distances will be changed in-place",
"if",
"sp",
".",
"issparse",
"(",
"X",
")",
":",
"inertia",
"=",
"_k_means",
".",
"_assign_labels_csr",
"(",
"X",
",",
"sample_weight",
",",
"x_squared_norms",
",",
"centers",
",",
"labels",
",",
"distances",
"=",
"distances",
")",
"else",
":",
"if",
"precompute_distances",
":",
"return",
"_labels_inertia_precompute_dense",
"(",
"X",
",",
"sample_weight",
",",
"x_squared_norms",
",",
"centers",
",",
"distances",
")",
"inertia",
"=",
"_k_means",
".",
"_assign_labels_array",
"(",
"X",
",",
"sample_weight",
",",
"x_squared_norms",
",",
"centers",
",",
"labels",
",",
"distances",
"=",
"distances",
")",
"return",
"labels",
",",
"inertia"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/cluster/_kmeans.py#L509-L566 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/urllib.py | python | splitquery | (url) | return url, None | splitquery('/path?query') --> '/path', 'query'. | splitquery('/path?query') --> '/path', 'query'. | [
"splitquery",
"(",
"/",
"path?query",
")",
"--",
">",
"/",
"path",
"query",
"."
] | def splitquery(url):
"""splitquery('/path?query') --> '/path', 'query'."""
global _queryprog
if _queryprog is None:
import re
_queryprog = re.compile('^(.*)\?([^?]*)$')
match = _queryprog.match(url)
if match: return match.group(1, 2)
return url, None | [
"def",
"splitquery",
"(",
"url",
")",
":",
"global",
"_queryprog",
"if",
"_queryprog",
"is",
"None",
":",
"import",
"re",
"_queryprog",
"=",
"re",
".",
"compile",
"(",
"'^(.*)\\?([^?]*)$'",
")",
"match",
"=",
"_queryprog",
".",
"match",
"(",
"url",
")",
"if",
"match",
":",
"return",
"match",
".",
"group",
"(",
"1",
",",
"2",
")",
"return",
"url",
",",
"None"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/urllib.py#L1154-L1163 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/html.py | python | HtmlWindow.OnLinkClicked | (*args, **kwargs) | return _html.HtmlWindow_OnLinkClicked(*args, **kwargs) | OnLinkClicked(self, HtmlLinkInfo link) | OnLinkClicked(self, HtmlLinkInfo link) | [
"OnLinkClicked",
"(",
"self",
"HtmlLinkInfo",
"link",
")"
] | def OnLinkClicked(*args, **kwargs):
"""OnLinkClicked(self, HtmlLinkInfo link)"""
return _html.HtmlWindow_OnLinkClicked(*args, **kwargs) | [
"def",
"OnLinkClicked",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_html",
".",
"HtmlWindow_OnLinkClicked",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/html.py#L1114-L1116 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_misc.py | python | Log.Suspend | (*args, **kwargs) | return _misc_.Log_Suspend(*args, **kwargs) | Suspend() | Suspend() | [
"Suspend",
"()"
] | def Suspend(*args, **kwargs):
"""Suspend()"""
return _misc_.Log_Suspend(*args, **kwargs) | [
"def",
"Suspend",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"Log_Suspend",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L1525-L1527 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/framework/framework.py | python | set_default_dtype | (d) | Set default dtype. The default dtype is initially float32
Args:
d(string|np.dtype): the dtype to make the default. It only
supports float16, float32 and float64.
Returns:
None.
Examples:
.. code-block:: python
import paddle
paddle.set_default_dtype("float32") | Set default dtype. The default dtype is initially float32 | [
"Set",
"default",
"dtype",
".",
"The",
"default",
"dtype",
"is",
"initially",
"float32"
] | def set_default_dtype(d):
"""
Set default dtype. The default dtype is initially float32
Args:
d(string|np.dtype): the dtype to make the default. It only
supports float16, float32 and float64.
Returns:
None.
Examples:
.. code-block:: python
import paddle
paddle.set_default_dtype("float32")
"""
if isinstance(d, type):
if d in [np.float16, np.float32, np.float64]:
d = d.__name__
else:
raise TypeError(
"set_default_dtype only supports [float16, float32, float64] "
", but received %s" % d.__name__)
else:
if d in [
'float16', 'float32', 'float64', u'float16', u'float32',
u'float64'
]:
# this code is a little bit dangerous, since error could happen
# when casting no-ascii code to str in python2.
# but since the set itself is limited, so currently, it is good.
# however, jointly supporting python2 and python3, (as well as python4 maybe)
# may still be a long-lasting problem.
d = str(d)
else:
raise TypeError(
"set_default_dtype only supports [float16, float32, float64] "
", but received %s" % str(d))
LayerHelperBase.set_default_dtype(d) | [
"def",
"set_default_dtype",
"(",
"d",
")",
":",
"if",
"isinstance",
"(",
"d",
",",
"type",
")",
":",
"if",
"d",
"in",
"[",
"np",
".",
"float16",
",",
"np",
".",
"float32",
",",
"np",
".",
"float64",
"]",
":",
"d",
"=",
"d",
".",
"__name__",
"else",
":",
"raise",
"TypeError",
"(",
"\"set_default_dtype only supports [float16, float32, float64] \"",
"\", but received %s\"",
"%",
"d",
".",
"__name__",
")",
"else",
":",
"if",
"d",
"in",
"[",
"'float16'",
",",
"'float32'",
",",
"'float64'",
",",
"u'float16'",
",",
"u'float32'",
",",
"u'float64'",
"]",
":",
"# this code is a little bit dangerous, since error could happen",
"# when casting no-ascii code to str in python2.",
"# but since the set itself is limited, so currently, it is good.",
"# however, jointly supporting python2 and python3, (as well as python4 maybe)",
"# may still be a long-lasting problem.",
"d",
"=",
"str",
"(",
"d",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"set_default_dtype only supports [float16, float32, float64] \"",
"\", but received %s\"",
"%",
"str",
"(",
"d",
")",
")",
"LayerHelperBase",
".",
"set_default_dtype",
"(",
"d",
")"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/framework/framework.py#L25-L66 | ||
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBSection.GetLoadAddress | (self, target) | return _lldb.SBSection_GetLoadAddress(self, target) | GetLoadAddress(SBSection self, SBTarget target) -> lldb::addr_t | GetLoadAddress(SBSection self, SBTarget target) -> lldb::addr_t | [
"GetLoadAddress",
"(",
"SBSection",
"self",
"SBTarget",
"target",
")",
"-",
">",
"lldb",
"::",
"addr_t"
] | def GetLoadAddress(self, target):
"""GetLoadAddress(SBSection self, SBTarget target) -> lldb::addr_t"""
return _lldb.SBSection_GetLoadAddress(self, target) | [
"def",
"GetLoadAddress",
"(",
"self",
",",
"target",
")",
":",
"return",
"_lldb",
".",
"SBSection_GetLoadAddress",
"(",
"self",
",",
"target",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L9292-L9294 | |
GJDuck/LowFat | ecf6a0f0fa1b73a27a626cf493cc39e477b6faea | llvm-4.0.0.src/bindings/python/llvm/core.py | python | MemoryBuffer.__init__ | (self, filename=None) | Create a new memory buffer.
Currently, we support creating from the contents of a file at the
specified filename. | Create a new memory buffer. | [
"Create",
"a",
"new",
"memory",
"buffer",
"."
] | def __init__(self, filename=None):
"""Create a new memory buffer.
Currently, we support creating from the contents of a file at the
specified filename.
"""
if filename is None:
raise Exception("filename argument must be defined")
memory = c_object_p()
out = c_char_p(None)
result = lib.LLVMCreateMemoryBufferWithContentsOfFile(filename,
byref(memory), byref(out))
if result:
raise Exception("Could not create memory buffer: %s" % out.value)
LLVMObject.__init__(self, memory, disposer=lib.LLVMDisposeMemoryBuffer) | [
"def",
"__init__",
"(",
"self",
",",
"filename",
"=",
"None",
")",
":",
"if",
"filename",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"filename argument must be defined\"",
")",
"memory",
"=",
"c_object_p",
"(",
")",
"out",
"=",
"c_char_p",
"(",
"None",
")",
"result",
"=",
"lib",
".",
"LLVMCreateMemoryBufferWithContentsOfFile",
"(",
"filename",
",",
"byref",
"(",
"memory",
")",
",",
"byref",
"(",
"out",
")",
")",
"if",
"result",
":",
"raise",
"Exception",
"(",
"\"Could not create memory buffer: %s\"",
"%",
"out",
".",
"value",
")",
"LLVMObject",
".",
"__init__",
"(",
"self",
",",
"memory",
",",
"disposer",
"=",
"lib",
".",
"LLVMDisposeMemoryBuffer",
")"
] | https://github.com/GJDuck/LowFat/blob/ecf6a0f0fa1b73a27a626cf493cc39e477b6faea/llvm-4.0.0.src/bindings/python/llvm/core.py#L149-L167 | ||
Lavender105/DFF | 152397cec4a3dac2aa86e92a65cc27e6c8016ab9 | pytorch-encoding/encoding/models/model_store.py | python | purge | (root='./pretrain_models') | r"""Purge all pretrained model files in local file store.
Parameters
----------
root : str, default './pretrain_models'
Location for keeping the model parameters. | r"""Purge all pretrained model files in local file store. | [
"r",
"Purge",
"all",
"pretrained",
"model",
"files",
"in",
"local",
"file",
"store",
"."
] | def purge(root='./pretrain_models'):
r"""Purge all pretrained model files in local file store.
Parameters
----------
root : str, default './pretrain_models'
Location for keeping the model parameters.
"""
root = os.path.expanduser(root)
files = os.listdir(root)
for f in files:
if f.endswith(".pth"):
os.remove(os.path.join(root, f)) | [
"def",
"purge",
"(",
"root",
"=",
"'./pretrain_models'",
")",
":",
"root",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"root",
")",
"files",
"=",
"os",
".",
"listdir",
"(",
"root",
")",
"for",
"f",
"in",
"files",
":",
"if",
"f",
".",
"endswith",
"(",
"\".pth\"",
")",
":",
"os",
".",
"remove",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"f",
")",
")"
] | https://github.com/Lavender105/DFF/blob/152397cec4a3dac2aa86e92a65cc27e6c8016ab9/pytorch-encoding/encoding/models/model_store.py#L79-L91 | ||
google/or-tools | 2cb85b4eead4c38e1c54b48044f92087cf165bce | ortools/sat/python/cp_model.py | python | LinearExpr.Sum | (cls, expressions) | return _SumArray(expressions) | Creates the expression sum(expressions). | Creates the expression sum(expressions). | [
"Creates",
"the",
"expression",
"sum",
"(",
"expressions",
")",
"."
] | def Sum(cls, expressions):
"""Creates the expression sum(expressions)."""
if len(expressions) == 1:
return expressions[0]
return _SumArray(expressions) | [
"def",
"Sum",
"(",
"cls",
",",
"expressions",
")",
":",
"if",
"len",
"(",
"expressions",
")",
"==",
"1",
":",
"return",
"expressions",
"[",
"0",
"]",
"return",
"_SumArray",
"(",
"expressions",
")"
] | https://github.com/google/or-tools/blob/2cb85b4eead4c38e1c54b48044f92087cf165bce/ortools/sat/python/cp_model.py#L180-L184 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/propgrid.py | python | PropertyGridInterface.EditorValidate | (*args, **kwargs) | return _propgrid.PropertyGridInterface_EditorValidate(*args, **kwargs) | EditorValidate(self) -> bool | EditorValidate(self) -> bool | [
"EditorValidate",
"(",
"self",
")",
"-",
">",
"bool"
] | def EditorValidate(*args, **kwargs):
"""EditorValidate(self) -> bool"""
return _propgrid.PropertyGridInterface_EditorValidate(*args, **kwargs) | [
"def",
"EditorValidate",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PropertyGridInterface_EditorValidate",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/propgrid.py#L1142-L1144 | |
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/traci/_polygon.py | python | PolygonDomain.setFilled | (self, polygonID, filled) | setFilled(string, bool) -> None
Sets the filled status of the polygon | setFilled(string, bool) -> None
Sets the filled status of the polygon | [
"setFilled",
"(",
"string",
"bool",
")",
"-",
">",
"None",
"Sets",
"the",
"filled",
"status",
"of",
"the",
"polygon"
] | def setFilled(self, polygonID, filled):
"""setFilled(string, bool) -> None
Sets the filled status of the polygon
"""
self._setCmd(tc.VAR_FILL, polygonID, "i", filled) | [
"def",
"setFilled",
"(",
"self",
",",
"polygonID",
",",
"filled",
")",
":",
"self",
".",
"_setCmd",
"(",
"tc",
".",
"VAR_FILL",
",",
"polygonID",
",",
"\"i\"",
",",
"filled",
")"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_polygon.py#L88-L92 | ||
pskun/finance_news_analysis | 6ac13e32deede37a4cf57bba8b2897941ae3d80d | crawler/crawler/spiders/EastMoneyGubaListSpider.py | python | EastmoneyGubaListSpider.parse_index_page | (self, response) | 解析股吧列表第一页的信息 | 解析股吧列表第一页的信息 | [
"解析股吧列表第一页的信息"
] | def parse_index_page(self, response):
''' 解析股吧列表第一页的信息 '''
list_url = response.url
ticker_id = list_url.split(',')[1][0:6]
# 获得分页信息
pager_info = response.xpath(
'//span[@class="pagernums"]/@data-pager').extract()
pager_info = "".join(pager_info).split("|")
total_count = util_func.atoi(pager_info[1])
num_per_page = util_func.atoi(pager_info[2])
page_count = int(
math.ceil(float(total_count) / float(num_per_page)))
self.parse_list_item(response)
base_url = 'http://guba.eastmoney.com/list,%s_%d.html'
for i in range(2, page_count + 1):
url = base_url % (ticker_id, i)
yield Request(url, self.parse_list_item)
pass | [
"def",
"parse_index_page",
"(",
"self",
",",
"response",
")",
":",
"list_url",
"=",
"response",
".",
"url",
"ticker_id",
"=",
"list_url",
".",
"split",
"(",
"','",
")",
"[",
"1",
"]",
"[",
"0",
":",
"6",
"]",
"# 获得分页信息",
"pager_info",
"=",
"response",
".",
"xpath",
"(",
"'//span[@class=\"pagernums\"]/@data-pager'",
")",
".",
"extract",
"(",
")",
"pager_info",
"=",
"\"\"",
".",
"join",
"(",
"pager_info",
")",
".",
"split",
"(",
"\"|\"",
")",
"total_count",
"=",
"util_func",
".",
"atoi",
"(",
"pager_info",
"[",
"1",
"]",
")",
"num_per_page",
"=",
"util_func",
".",
"atoi",
"(",
"pager_info",
"[",
"2",
"]",
")",
"page_count",
"=",
"int",
"(",
"math",
".",
"ceil",
"(",
"float",
"(",
"total_count",
")",
"/",
"float",
"(",
"num_per_page",
")",
")",
")",
"self",
".",
"parse_list_item",
"(",
"response",
")",
"base_url",
"=",
"'http://guba.eastmoney.com/list,%s_%d.html'",
"for",
"i",
"in",
"range",
"(",
"2",
",",
"page_count",
"+",
"1",
")",
":",
"url",
"=",
"base_url",
"%",
"(",
"ticker_id",
",",
"i",
")",
"yield",
"Request",
"(",
"url",
",",
"self",
".",
"parse_list_item",
")",
"pass"
] | https://github.com/pskun/finance_news_analysis/blob/6ac13e32deede37a4cf57bba8b2897941ae3d80d/crawler/crawler/spiders/EastMoneyGubaListSpider.py#L50-L67 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/richtext.py | python | RichTextCtrl.Create | (*args, **kwargs) | return _richtext.RichTextCtrl_Create(*args, **kwargs) | Create(self, Window parent, int id=-1, String value=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=RE_MULTILINE, Validator validator=DefaultValidator,
String name=RichTextCtrlNameStr) -> bool | Create(self, Window parent, int id=-1, String value=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=RE_MULTILINE, Validator validator=DefaultValidator,
String name=RichTextCtrlNameStr) -> bool | [
"Create",
"(",
"self",
"Window",
"parent",
"int",
"id",
"=",
"-",
"1",
"String",
"value",
"=",
"EmptyString",
"Point",
"pos",
"=",
"DefaultPosition",
"Size",
"size",
"=",
"DefaultSize",
"long",
"style",
"=",
"RE_MULTILINE",
"Validator",
"validator",
"=",
"DefaultValidator",
"String",
"name",
"=",
"RichTextCtrlNameStr",
")",
"-",
">",
"bool"
] | def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, String value=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=RE_MULTILINE, Validator validator=DefaultValidator,
String name=RichTextCtrlNameStr) -> bool
"""
return _richtext.RichTextCtrl_Create(*args, **kwargs) | [
"def",
"Create",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextCtrl_Create",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L2914-L2921 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_windows.py | python | VListBox.SetItemCount | (*args, **kwargs) | return _windows_.VListBox_SetItemCount(*args, **kwargs) | SetItemCount(self, size_t count) | SetItemCount(self, size_t count) | [
"SetItemCount",
"(",
"self",
"size_t",
"count",
")"
] | def SetItemCount(*args, **kwargs):
"""SetItemCount(self, size_t count)"""
return _windows_.VListBox_SetItemCount(*args, **kwargs) | [
"def",
"SetItemCount",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"VListBox_SetItemCount",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L2648-L2650 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/signal/windows.py | python | blackman | (M, sym=True) | return _truncate(w, needs_trunc) | r"""
Return a Blackman window.
The Blackman window is a taper formed by using the first three terms of
a summation of cosines. It was designed to have close to the minimal
leakage possible. It is close to optimal, only slightly worse than a
Kaiser window.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an empty
array is returned.
sym : bool, optional
When True (default), generates a symmetric window, for use in filter
design.
When False, generates a periodic window, for use in spectral analysis.
Returns
-------
w : ndarray
The window, with the maximum value normalized to 1 (though the value 1
does not appear if `M` is even and `sym` is True).
Notes
-----
The Blackman window is defined as
.. math:: w(n) = 0.42 - 0.5 \cos(2\pi n/M) + 0.08 \cos(4\pi n/M)
The "exact Blackman" window was designed to null out the third and fourth
sidelobes, but has discontinuities at the boundaries, resulting in a
6 dB/oct fall-off. This window is an approximation of the "exact" window,
which does not null the sidelobes as well, but is smooth at the edges,
improving the fall-off rate to 18 dB/oct. [3]_
Most references to the Blackman 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. It is known as a
"near optimal" tapering function, almost as good (by some measures)
as the Kaiser window.
References
----------
.. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power
spectra, Dover Publications, New York.
.. [2] Oppenheim, A.V., and R.W. Schafer. Discrete-Time Signal Processing.
Upper Saddle River, NJ: Prentice-Hall, 1999, pp. 468-471.
.. [3] Harris, Fredric J. (Jan 1978). "On the use of Windows for Harmonic
Analysis with the Discrete Fourier Transform". Proceedings of the
IEEE 66 (1): 51-83. doi:10.1109/PROC.1978.10837
Examples
--------
Plot the window and its frequency response:
>>> from scipy import signal
>>> from scipy.fftpack import fft, fftshift
>>> import matplotlib.pyplot as plt
>>> window = signal.blackman(51)
>>> plt.plot(window)
>>> plt.title("Blackman window")
>>> plt.ylabel("Amplitude")
>>> plt.xlabel("Sample")
>>> plt.figure()
>>> A = fft(window, 2048) / (len(window)/2.0)
>>> freq = np.linspace(-0.5, 0.5, len(A))
>>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
>>> plt.plot(freq, response)
>>> plt.axis([-0.5, 0.5, -120, 0])
>>> plt.title("Frequency response of the Blackman window")
>>> plt.ylabel("Normalized magnitude [dB]")
>>> plt.xlabel("Normalized frequency [cycles per sample]") | r"""
Return a Blackman window. | [
"r",
"Return",
"a",
"Blackman",
"window",
"."
] | def blackman(M, sym=True):
r"""
Return a Blackman window.
The Blackman window is a taper formed by using the first three terms of
a summation of cosines. It was designed to have close to the minimal
leakage possible. It is close to optimal, only slightly worse than a
Kaiser window.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an empty
array is returned.
sym : bool, optional
When True (default), generates a symmetric window, for use in filter
design.
When False, generates a periodic window, for use in spectral analysis.
Returns
-------
w : ndarray
The window, with the maximum value normalized to 1 (though the value 1
does not appear if `M` is even and `sym` is True).
Notes
-----
The Blackman window is defined as
.. math:: w(n) = 0.42 - 0.5 \cos(2\pi n/M) + 0.08 \cos(4\pi n/M)
The "exact Blackman" window was designed to null out the third and fourth
sidelobes, but has discontinuities at the boundaries, resulting in a
6 dB/oct fall-off. This window is an approximation of the "exact" window,
which does not null the sidelobes as well, but is smooth at the edges,
improving the fall-off rate to 18 dB/oct. [3]_
Most references to the Blackman 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. It is known as a
"near optimal" tapering function, almost as good (by some measures)
as the Kaiser window.
References
----------
.. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power
spectra, Dover Publications, New York.
.. [2] Oppenheim, A.V., and R.W. Schafer. Discrete-Time Signal Processing.
Upper Saddle River, NJ: Prentice-Hall, 1999, pp. 468-471.
.. [3] Harris, Fredric J. (Jan 1978). "On the use of Windows for Harmonic
Analysis with the Discrete Fourier Transform". Proceedings of the
IEEE 66 (1): 51-83. doi:10.1109/PROC.1978.10837
Examples
--------
Plot the window and its frequency response:
>>> from scipy import signal
>>> from scipy.fftpack import fft, fftshift
>>> import matplotlib.pyplot as plt
>>> window = signal.blackman(51)
>>> plt.plot(window)
>>> plt.title("Blackman window")
>>> plt.ylabel("Amplitude")
>>> plt.xlabel("Sample")
>>> plt.figure()
>>> A = fft(window, 2048) / (len(window)/2.0)
>>> freq = np.linspace(-0.5, 0.5, len(A))
>>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
>>> plt.plot(freq, response)
>>> plt.axis([-0.5, 0.5, -120, 0])
>>> plt.title("Frequency response of the Blackman window")
>>> plt.ylabel("Normalized magnitude [dB]")
>>> plt.xlabel("Normalized frequency [cycles per sample]")
"""
# Docstring adapted from NumPy's blackman function
if _len_guards(M):
return np.ones(M)
M, needs_trunc = _extend(M, sym)
w = _cos_win(M, [0.42, 0.50, 0.08])
return _truncate(w, needs_trunc) | [
"def",
"blackman",
"(",
"M",
",",
"sym",
"=",
"True",
")",
":",
"# Docstring adapted from NumPy's blackman function",
"if",
"_len_guards",
"(",
"M",
")",
":",
"return",
"np",
".",
"ones",
"(",
"M",
")",
"M",
",",
"needs_trunc",
"=",
"_extend",
"(",
"M",
",",
"sym",
")",
"w",
"=",
"_cos_win",
"(",
"M",
",",
"[",
"0.42",
",",
"0.50",
",",
"0.08",
"]",
")",
"return",
"_truncate",
"(",
"w",
",",
"needs_trunc",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/signal/windows.py#L356-L443 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/idlelib/WidgetRedirector.py | python | WidgetRedirector.close | (self) | Unregister operations and revert redirection created by .__init__. | Unregister operations and revert redirection created by .__init__. | [
"Unregister",
"operations",
"and",
"revert",
"redirection",
"created",
"by",
".",
"__init__",
"."
] | def close(self):
"Unregister operations and revert redirection created by .__init__."
for operation in list(self._operations):
self.unregister(operation)
widget = self.widget
tk = widget.tk
w = widget._w
# Restore the original widget Tcl command.
tk.deletecommand(w)
tk.call("rename", self.orig, w)
del self.widget, self.tk | [
"def",
"close",
"(",
"self",
")",
":",
"for",
"operation",
"in",
"list",
"(",
"self",
".",
"_operations",
")",
":",
"self",
".",
"unregister",
"(",
"operation",
")",
"widget",
"=",
"self",
".",
"widget",
"tk",
"=",
"widget",
".",
"tk",
"w",
"=",
"widget",
".",
"_w",
"# Restore the original widget Tcl command.",
"tk",
".",
"deletecommand",
"(",
"w",
")",
"tk",
".",
"call",
"(",
"\"rename\"",
",",
"self",
".",
"orig",
",",
"w",
")",
"del",
"self",
".",
"widget",
",",
"self",
".",
"tk"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/idlelib/WidgetRedirector.py#L54-L64 | ||
naver/sling | 5671cd445a2caae0b4dd0332299e4cfede05062c | webkit/Tools/Scripts/webkitpy/style/checkers/cpp.py | python | _convert_to_lower_with_underscores | (text) | return text.lower() | Converts all text strings in camelCase or PascalCase to lowers with underscores. | Converts all text strings in camelCase or PascalCase to lowers with underscores. | [
"Converts",
"all",
"text",
"strings",
"in",
"camelCase",
"or",
"PascalCase",
"to",
"lowers",
"with",
"underscores",
"."
] | def _convert_to_lower_with_underscores(text):
"""Converts all text strings in camelCase or PascalCase to lowers with underscores."""
# First add underscores before any capital letter followed by a lower case letter
# as long as it is in a word.
# (This put an underscore before Password but not P and A in WPAPassword).
text = sub(r'(?<=[A-Za-z0-9])([A-Z])(?=[a-z])', r'_\1', text)
# Next add underscores before capitals at the end of words if it was
# preceeded by lower case letter or number.
# (This puts an underscore before A in isA but not A in CBA).
text = sub(r'(?<=[a-z0-9])([A-Z])(?=\b)', r'_\1', text)
# Next add underscores when you have a captial letter which is followed by a capital letter
# but is not proceeded by one. (This puts an underscore before A in 'WordADay').
text = sub(r'(?<=[a-z0-9])([A-Z][A-Z_])', r'_\1', text)
return text.lower() | [
"def",
"_convert_to_lower_with_underscores",
"(",
"text",
")",
":",
"# First add underscores before any capital letter followed by a lower case letter",
"# as long as it is in a word.",
"# (This put an underscore before Password but not P and A in WPAPassword).",
"text",
"=",
"sub",
"(",
"r'(?<=[A-Za-z0-9])([A-Z])(?=[a-z])'",
",",
"r'_\\1'",
",",
"text",
")",
"# Next add underscores before capitals at the end of words if it was",
"# preceeded by lower case letter or number.",
"# (This puts an underscore before A in isA but not A in CBA).",
"text",
"=",
"sub",
"(",
"r'(?<=[a-z0-9])([A-Z])(?=\\b)'",
",",
"r'_\\1'",
",",
"text",
")",
"# Next add underscores when you have a captial letter which is followed by a capital letter",
"# but is not proceeded by one. (This puts an underscore before A in 'WordADay').",
"text",
"=",
"sub",
"(",
"r'(?<=[a-z0-9])([A-Z][A-Z_])'",
",",
"r'_\\1'",
",",
"text",
")",
"return",
"text",
".",
"lower",
"(",
")"
] | https://github.com/naver/sling/blob/5671cd445a2caae0b4dd0332299e4cfede05062c/webkit/Tools/Scripts/webkitpy/style/checkers/cpp.py#L188-L205 | |
SpenceKonde/megaTinyCore | 1c4a70b18a149fe6bcb551dfa6db11ca50b8997b | megaavr/tools/libs/serial/serialposix.py | python | VTIMESerial._reconfigure_port | (self, force_update=True) | Set communication parameters on opened port. | Set communication parameters on opened port. | [
"Set",
"communication",
"parameters",
"on",
"opened",
"port",
"."
] | def _reconfigure_port(self, force_update=True):
"""Set communication parameters on opened port."""
super(VTIMESerial, self)._reconfigure_port()
fcntl.fcntl(self.fd, fcntl.F_SETFL, 0) # clear O_NONBLOCK
if self._inter_byte_timeout is not None:
vmin = 1
vtime = int(self._inter_byte_timeout * 10)
elif self._timeout is None:
vmin = 1
vtime = 0
else:
vmin = 0
vtime = int(self._timeout * 10)
try:
orig_attr = termios.tcgetattr(self.fd)
iflag, oflag, cflag, lflag, ispeed, ospeed, cc = orig_attr
except termios.error as msg: # if a port is nonexistent but has a /dev file, it'll fail here
raise serial.SerialException("Could not configure port: {}".format(msg))
if vtime < 0 or vtime > 255:
raise ValueError('Invalid vtime: {!r}'.format(vtime))
cc[termios.VTIME] = vtime
cc[termios.VMIN] = vmin
termios.tcsetattr(
self.fd,
termios.TCSANOW,
[iflag, oflag, cflag, lflag, ispeed, ospeed, cc]) | [
"def",
"_reconfigure_port",
"(",
"self",
",",
"force_update",
"=",
"True",
")",
":",
"super",
"(",
"VTIMESerial",
",",
"self",
")",
".",
"_reconfigure_port",
"(",
")",
"fcntl",
".",
"fcntl",
"(",
"self",
".",
"fd",
",",
"fcntl",
".",
"F_SETFL",
",",
"0",
")",
"# clear O_NONBLOCK",
"if",
"self",
".",
"_inter_byte_timeout",
"is",
"not",
"None",
":",
"vmin",
"=",
"1",
"vtime",
"=",
"int",
"(",
"self",
".",
"_inter_byte_timeout",
"*",
"10",
")",
"elif",
"self",
".",
"_timeout",
"is",
"None",
":",
"vmin",
"=",
"1",
"vtime",
"=",
"0",
"else",
":",
"vmin",
"=",
"0",
"vtime",
"=",
"int",
"(",
"self",
".",
"_timeout",
"*",
"10",
")",
"try",
":",
"orig_attr",
"=",
"termios",
".",
"tcgetattr",
"(",
"self",
".",
"fd",
")",
"iflag",
",",
"oflag",
",",
"cflag",
",",
"lflag",
",",
"ispeed",
",",
"ospeed",
",",
"cc",
"=",
"orig_attr",
"except",
"termios",
".",
"error",
"as",
"msg",
":",
"# if a port is nonexistent but has a /dev file, it'll fail here",
"raise",
"serial",
".",
"SerialException",
"(",
"\"Could not configure port: {}\"",
".",
"format",
"(",
"msg",
")",
")",
"if",
"vtime",
"<",
"0",
"or",
"vtime",
">",
"255",
":",
"raise",
"ValueError",
"(",
"'Invalid vtime: {!r}'",
".",
"format",
"(",
"vtime",
")",
")",
"cc",
"[",
"termios",
".",
"VTIME",
"]",
"=",
"vtime",
"cc",
"[",
"termios",
".",
"VMIN",
"]",
"=",
"vmin",
"termios",
".",
"tcsetattr",
"(",
"self",
".",
"fd",
",",
"termios",
".",
"TCSANOW",
",",
"[",
"iflag",
",",
"oflag",
",",
"cflag",
",",
"lflag",
",",
"ispeed",
",",
"ospeed",
",",
"cc",
"]",
")"
] | https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/serial/serialposix.py#L764-L792 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/keras/_impl/keras/backend.py | python | one_hot | (indices, num_classes) | return array_ops.one_hot(indices, depth=num_classes, axis=-1) | Computes the one-hot representation of an integer tensor.
Arguments:
indices: nD integer tensor of shape
`(batch_size, dim1, dim2, ... dim(n-1))`
num_classes: Integer, number of classes to consider.
Returns:
(n + 1)D one hot representation of the input
with shape `(batch_size, dim1, dim2, ... dim(n-1), num_classes)`
Returns:
The one-hot tensor. | Computes the one-hot representation of an integer tensor. | [
"Computes",
"the",
"one",
"-",
"hot",
"representation",
"of",
"an",
"integer",
"tensor",
"."
] | def one_hot(indices, num_classes):
"""Computes the one-hot representation of an integer tensor.
Arguments:
indices: nD integer tensor of shape
`(batch_size, dim1, dim2, ... dim(n-1))`
num_classes: Integer, number of classes to consider.
Returns:
(n + 1)D one hot representation of the input
with shape `(batch_size, dim1, dim2, ... dim(n-1), num_classes)`
Returns:
The one-hot tensor.
"""
return array_ops.one_hot(indices, depth=num_classes, axis=-1) | [
"def",
"one_hot",
"(",
"indices",
",",
"num_classes",
")",
":",
"return",
"array_ops",
".",
"one_hot",
"(",
"indices",
",",
"depth",
"=",
"num_classes",
",",
"axis",
"=",
"-",
"1",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/keras/_impl/keras/backend.py#L2298-L2313 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/core/defchararray.py | python | isupper | (a) | return _vec_string(a, bool_, 'isupper') | Returns true for each element if all cased characters in the
string are uppercase and there is at least one character, false
otherwise.
Call `str.isupper` element-wise.
For 8-bit strings, this method is locale-dependent.
Parameters
----------
a : array_like of str or unicode
Returns
-------
out : ndarray
Output array of bools
See also
--------
str.isupper | Returns true for each element if all cased characters in the
string are uppercase and there is at least one character, false
otherwise. | [
"Returns",
"true",
"for",
"each",
"element",
"if",
"all",
"cased",
"characters",
"in",
"the",
"string",
"are",
"uppercase",
"and",
"there",
"is",
"at",
"least",
"one",
"character",
"false",
"otherwise",
"."
] | def isupper(a):
"""
Returns true for each element if all cased characters in the
string are uppercase and there is at least one character, false
otherwise.
Call `str.isupper` element-wise.
For 8-bit strings, this method is locale-dependent.
Parameters
----------
a : array_like of str or unicode
Returns
-------
out : ndarray
Output array of bools
See also
--------
str.isupper
"""
return _vec_string(a, bool_, 'isupper') | [
"def",
"isupper",
"(",
"a",
")",
":",
"return",
"_vec_string",
"(",
"a",
",",
"bool_",
",",
"'isupper'",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/core/defchararray.py#L913-L936 | |
mhammond/pywin32 | 44afd86ba8485194df93234639243252deeb40d5 | com/win32comext/authorization/demos/EditServiceSecurity.py | python | ServiceSecurity.GetObjectInformation | (self) | return flags, hinstance, servername, objectname, pagetitle, objecttype | Identifies object whose security will be modified, and determines options available
to the end user | Identifies object whose security will be modified, and determines options available
to the end user | [
"Identifies",
"object",
"whose",
"security",
"will",
"be",
"modified",
"and",
"determines",
"options",
"available",
"to",
"the",
"end",
"user"
] | def GetObjectInformation(self):
"""Identifies object whose security will be modified, and determines options available
to the end user"""
flags = SI_ADVANCED | SI_EDIT_ALL | SI_PAGE_TITLE | SI_RESET
hinstance = 0 ## handle to module containing string resources
servername = "" ## name of authenticating server if not local machine
## service name can contain remote machine name of the form \\Server\ServiceName
objectname = os.path.split(self.ServiceName)[1]
pagetitle = "Service Permissions for " + self.ServiceName
objecttype = IID_NULL
return flags, hinstance, servername, objectname, pagetitle, objecttype | [
"def",
"GetObjectInformation",
"(",
"self",
")",
":",
"flags",
"=",
"SI_ADVANCED",
"|",
"SI_EDIT_ALL",
"|",
"SI_PAGE_TITLE",
"|",
"SI_RESET",
"hinstance",
"=",
"0",
"## handle to module containing string resources",
"servername",
"=",
"\"\"",
"## name of authenticating server if not local machine",
"## service name can contain remote machine name of the form \\\\Server\\ServiceName",
"objectname",
"=",
"os",
".",
"path",
".",
"split",
"(",
"self",
".",
"ServiceName",
")",
"[",
"1",
"]",
"pagetitle",
"=",
"\"Service Permissions for \"",
"+",
"self",
".",
"ServiceName",
"objecttype",
"=",
"IID_NULL",
"return",
"flags",
",",
"hinstance",
",",
"servername",
",",
"objectname",
",",
"pagetitle",
",",
"objecttype"
] | https://github.com/mhammond/pywin32/blob/44afd86ba8485194df93234639243252deeb40d5/com/win32comext/authorization/demos/EditServiceSecurity.py#L78-L89 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/layers/tensor.py | python | zeros | (shape, dtype, force_cpu=False, name=None) | return fill_constant(value=0.0, **locals()) | The OP creates a tensor of specified :attr:`shape` and :attr:`dtype`, and fills it with 0.
Its :attr:`stop_gradient` will be set to True to stop gradient computation.
Parameters:
shape(tuple|list|Tensor): Shape of output Tensor, the data type of ``shape`` is int32 or int64.
dtype (np.dtype|str): Data type of output Tensor, it supports
bool, float16, float32, float64, int32 and int64.
force_cpu (bool, optional): Whether force to store the output Tensor in CPU memory.
If :attr:`force_cpu` is False, the output Tensor will be stored in running device memory.
Default: False.
name(str, optional): The default value is None. Normally there is no need for user to set this
property. For more information, please refer to :ref:`api_guide_Name`.
Returns:
Tensor: A tensor of data type :attr:`dtype` with shape :attr:`shape` and all elements set to 0.
Examples:
.. code-block:: python
import paddle.fluid as fluid
data = fluid.layers.zeros(shape=[3, 2], dtype='float32') # [[0., 0.], [0., 0.], [0., 0.]]
# shape is a Tensor
shape = fluid.layers.fill_constant(shape=[2], dtype='int32', value=2)
data1 = fluid.layers.zeros(shape=shape, dtype='int32') #[[0, 0], [0, 0]] | The OP creates a tensor of specified :attr:`shape` and :attr:`dtype`, and fills it with 0.
Its :attr:`stop_gradient` will be set to True to stop gradient computation. | [
"The",
"OP",
"creates",
"a",
"tensor",
"of",
"specified",
":",
"attr",
":",
"shape",
"and",
":",
"attr",
":",
"dtype",
"and",
"fills",
"it",
"with",
"0",
".",
"Its",
":",
"attr",
":",
"stop_gradient",
"will",
"be",
"set",
"to",
"True",
"to",
"stop",
"gradient",
"computation",
"."
] | def zeros(shape, dtype, force_cpu=False, name=None):
"""
The OP creates a tensor of specified :attr:`shape` and :attr:`dtype`, and fills it with 0.
Its :attr:`stop_gradient` will be set to True to stop gradient computation.
Parameters:
shape(tuple|list|Tensor): Shape of output Tensor, the data type of ``shape`` is int32 or int64.
dtype (np.dtype|str): Data type of output Tensor, it supports
bool, float16, float32, float64, int32 and int64.
force_cpu (bool, optional): Whether force to store the output Tensor in CPU memory.
If :attr:`force_cpu` is False, the output Tensor will be stored in running device memory.
Default: False.
name(str, optional): The default value is None. Normally there is no need for user to set this
property. For more information, please refer to :ref:`api_guide_Name`.
Returns:
Tensor: A tensor of data type :attr:`dtype` with shape :attr:`shape` and all elements set to 0.
Examples:
.. code-block:: python
import paddle.fluid as fluid
data = fluid.layers.zeros(shape=[3, 2], dtype='float32') # [[0., 0.], [0., 0.], [0., 0.]]
# shape is a Tensor
shape = fluid.layers.fill_constant(shape=[2], dtype='int32', value=2)
data1 = fluid.layers.zeros(shape=shape, dtype='int32') #[[0, 0], [0, 0]]
"""
return fill_constant(value=0.0, **locals()) | [
"def",
"zeros",
"(",
"shape",
",",
"dtype",
",",
"force_cpu",
"=",
"False",
",",
"name",
"=",
"None",
")",
":",
"return",
"fill_constant",
"(",
"value",
"=",
"0.0",
",",
"*",
"*",
"locals",
"(",
")",
")"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/layers/tensor.py#L1099-L1127 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/richtext.py | python | RichTextPrinting.SetShowOnFirstPage | (*args, **kwargs) | return _richtext.RichTextPrinting_SetShowOnFirstPage(*args, **kwargs) | SetShowOnFirstPage(self, bool show) | SetShowOnFirstPage(self, bool show) | [
"SetShowOnFirstPage",
"(",
"self",
"bool",
"show",
")"
] | def SetShowOnFirstPage(*args, **kwargs):
"""SetShowOnFirstPage(self, bool show)"""
return _richtext.RichTextPrinting_SetShowOnFirstPage(*args, **kwargs) | [
"def",
"SetShowOnFirstPage",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextPrinting_SetShowOnFirstPage",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L4540-L4542 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/corrections_tab_widget/dead_time_corrections_view.py | python | DeadTimeCorrectionsView.set_slot_for_dead_time_from_selector_changed | (self, slot) | Connect the slot for the Dead Time Selector Combobox. | Connect the slot for the Dead Time Selector Combobox. | [
"Connect",
"the",
"slot",
"for",
"the",
"Dead",
"Time",
"Selector",
"Combobox",
"."
] | def set_slot_for_dead_time_from_selector_changed(self, slot) -> None:
"""Connect the slot for the Dead Time Selector Combobox."""
self.dead_time_from_selector.currentIndexChanged.connect(slot) | [
"def",
"set_slot_for_dead_time_from_selector_changed",
"(",
"self",
",",
"slot",
")",
"->",
"None",
":",
"self",
".",
"dead_time_from_selector",
".",
"currentIndexChanged",
".",
"connect",
"(",
"slot",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/corrections_tab_widget/dead_time_corrections_view.py#L32-L34 | ||
metashell/metashell | f4177e4854ea00c8dbc722cadab26ef413d798ea | 3rd/templight/clang/tools/scan-build-py/libscanbuild/intercept.py | python | setup_environment | (args, destination) | return environment | Sets up the environment for the build command.
It sets the required environment variables and execute the given command.
The exec calls will be logged by the 'libear' preloaded library or by the
'wrapper' programs. | Sets up the environment for the build command. | [
"Sets",
"up",
"the",
"environment",
"for",
"the",
"build",
"command",
"."
] | def setup_environment(args, destination):
""" Sets up the environment for the build command.
It sets the required environment variables and execute the given command.
The exec calls will be logged by the 'libear' preloaded library or by the
'wrapper' programs. """
c_compiler = args.cc if 'cc' in args else 'cc'
cxx_compiler = args.cxx if 'cxx' in args else 'c++'
libear_path = None if args.override_compiler or is_preload_disabled(
sys.platform) else build_libear(c_compiler, destination)
environment = dict(os.environ)
environment.update({'INTERCEPT_BUILD_TARGET_DIR': destination})
if not libear_path:
logging.debug('intercept gonna use compiler wrappers')
environment.update(wrapper_environment(args))
environment.update({
'CC': COMPILER_WRAPPER_CC,
'CXX': COMPILER_WRAPPER_CXX
})
elif sys.platform == 'darwin':
logging.debug('intercept gonna preload libear on OSX')
environment.update({
'DYLD_INSERT_LIBRARIES': libear_path,
'DYLD_FORCE_FLAT_NAMESPACE': '1'
})
else:
logging.debug('intercept gonna preload libear on UNIX')
environment.update({'LD_PRELOAD': libear_path})
return environment | [
"def",
"setup_environment",
"(",
"args",
",",
"destination",
")",
":",
"c_compiler",
"=",
"args",
".",
"cc",
"if",
"'cc'",
"in",
"args",
"else",
"'cc'",
"cxx_compiler",
"=",
"args",
".",
"cxx",
"if",
"'cxx'",
"in",
"args",
"else",
"'c++'",
"libear_path",
"=",
"None",
"if",
"args",
".",
"override_compiler",
"or",
"is_preload_disabled",
"(",
"sys",
".",
"platform",
")",
"else",
"build_libear",
"(",
"c_compiler",
",",
"destination",
")",
"environment",
"=",
"dict",
"(",
"os",
".",
"environ",
")",
"environment",
".",
"update",
"(",
"{",
"'INTERCEPT_BUILD_TARGET_DIR'",
":",
"destination",
"}",
")",
"if",
"not",
"libear_path",
":",
"logging",
".",
"debug",
"(",
"'intercept gonna use compiler wrappers'",
")",
"environment",
".",
"update",
"(",
"wrapper_environment",
"(",
"args",
")",
")",
"environment",
".",
"update",
"(",
"{",
"'CC'",
":",
"COMPILER_WRAPPER_CC",
",",
"'CXX'",
":",
"COMPILER_WRAPPER_CXX",
"}",
")",
"elif",
"sys",
".",
"platform",
"==",
"'darwin'",
":",
"logging",
".",
"debug",
"(",
"'intercept gonna preload libear on OSX'",
")",
"environment",
".",
"update",
"(",
"{",
"'DYLD_INSERT_LIBRARIES'",
":",
"libear_path",
",",
"'DYLD_FORCE_FLAT_NAMESPACE'",
":",
"'1'",
"}",
")",
"else",
":",
"logging",
".",
"debug",
"(",
"'intercept gonna preload libear on UNIX'",
")",
"environment",
".",
"update",
"(",
"{",
"'LD_PRELOAD'",
":",
"libear_path",
"}",
")",
"return",
"environment"
] | https://github.com/metashell/metashell/blob/f4177e4854ea00c8dbc722cadab26ef413d798ea/3rd/templight/clang/tools/scan-build-py/libscanbuild/intercept.py#L102-L135 | |
htcondor/htcondor | 4829724575176d1d6c936e4693dfd78a728569b0 | src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/conversion.py | python | IConversion.CallFailureReasonToText | (self, Reason) | return self._ToText('cfr', Reason) | Returns failure reason as text.
@param Reason: Call failure reason.
@type Reason: L{Call failure reason<enums.cfrUnknown>}
@return: Text describing the call failure reason.
@rtype: unicode | Returns failure reason as text. | [
"Returns",
"failure",
"reason",
"as",
"text",
"."
] | def CallFailureReasonToText(self, Reason):
'''Returns failure reason as text.
@param Reason: Call failure reason.
@type Reason: L{Call failure reason<enums.cfrUnknown>}
@return: Text describing the call failure reason.
@rtype: unicode
'''
return self._ToText('cfr', Reason) | [
"def",
"CallFailureReasonToText",
"(",
"self",
",",
"Reason",
")",
":",
"return",
"self",
".",
"_ToText",
"(",
"'cfr'",
",",
"Reason",
")"
] | https://github.com/htcondor/htcondor/blob/4829724575176d1d6c936e4693dfd78a728569b0/src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/conversion.py#L68-L76 | |
lhmRyan/deep-supervised-hashing-DSH | 631901f82e2ab031fbac33f914a5b08ef8e21d57 | scripts/cpp_lint.py | python | FileInfo.IsSource | (self) | return self.Extension()[1:] in ('c', 'cc', 'cpp', 'cxx') | File has a source file extension. | File has a source file extension. | [
"File",
"has",
"a",
"source",
"file",
"extension",
"."
] | def IsSource(self):
"""File has a source file extension."""
return self.Extension()[1:] in ('c', 'cc', 'cpp', 'cxx') | [
"def",
"IsSource",
"(",
"self",
")",
":",
"return",
"self",
".",
"Extension",
"(",
")",
"[",
"1",
":",
"]",
"in",
"(",
"'c'",
",",
"'cc'",
",",
"'cpp'",
",",
"'cxx'",
")"
] | https://github.com/lhmRyan/deep-supervised-hashing-DSH/blob/631901f82e2ab031fbac33f914a5b08ef8e21d57/scripts/cpp_lint.py#L956-L958 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/idl/idl/struct_types.py | python | StructTypeInfoBase.get_to_bson_method | (self) | Get the to_bson method for a struct. | Get the to_bson method for a struct. | [
"Get",
"the",
"to_bson",
"method",
"for",
"a",
"struct",
"."
] | def get_to_bson_method(self):
# type: () -> MethodInfo
"""Get the to_bson method for a struct."""
pass | [
"def",
"get_to_bson_method",
"(",
"self",
")",
":",
"# type: () -> MethodInfo",
"pass"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl/struct_types.py#L175-L178 | ||
dmlc/nnvm | dab5ce8ab6adbf4edd8bd2fa89f1a99f343b6e38 | python/nnvm/frontend/darknet.py | python | _darknet_route | (inputs, attrs) | return _darknet_get_nnvm_op(op_name)(*inputs, **new_attrs), None | Process the route operation, which is equivalent to concat. | Process the route operation, which is equivalent to concat. | [
"Process",
"the",
"route",
"operation",
"which",
"is",
"equivalent",
"to",
"concat",
"."
] | def _darknet_route(inputs, attrs):
"""Process the route operation, which is equivalent to concat."""
op_name = 'concatenate'
new_attrs = {'axis': attrs.get('dim', 1)}
return _darknet_get_nnvm_op(op_name)(*inputs, **new_attrs), None | [
"def",
"_darknet_route",
"(",
"inputs",
",",
"attrs",
")",
":",
"op_name",
"=",
"'concatenate'",
"new_attrs",
"=",
"{",
"'axis'",
":",
"attrs",
".",
"get",
"(",
"'dim'",
",",
"1",
")",
"}",
"return",
"_darknet_get_nnvm_op",
"(",
"op_name",
")",
"(",
"*",
"inputs",
",",
"*",
"*",
"new_attrs",
")",
",",
"None"
] | https://github.com/dmlc/nnvm/blob/dab5ce8ab6adbf4edd8bd2fa89f1a99f343b6e38/python/nnvm/frontend/darknet.py#L266-L270 | |
opengauss-mirror/openGauss-server | e383f1b77720a00ddbe4c0655bc85914d9b02a2b | src/gausskernel/dbmind/tools/xtuner/tuner/benchmark/tpcc.py | python | run | (remote_server, local_host) | return float(tpmC) - 10 * nb_err | Because TPC-C would insert many tuples into database, we suggest that
backup the raw data directory and restore it when run TPC-C benchmark some times.
e.g.
```
remote_server.exec_command_sync('mv ~/backup ~/gsdata')
```
The passed two parameters are both Executor instance.
:param remote_server: SSH object for remote database server.
:param local_host: LocalExec object for local client host where run our tuning tool.
:return: benchmark score, higher one must be better, be sure to keep in mind. | Because TPC-C would insert many tuples into database, we suggest that
backup the raw data directory and restore it when run TPC-C benchmark some times.
e.g.
```
remote_server.exec_command_sync('mv ~/backup ~/gsdata')
``` | [
"Because",
"TPC",
"-",
"C",
"would",
"insert",
"many",
"tuples",
"into",
"database",
"we",
"suggest",
"that",
"backup",
"the",
"raw",
"data",
"directory",
"and",
"restore",
"it",
"when",
"run",
"TPC",
"-",
"C",
"benchmark",
"some",
"times",
".",
"e",
".",
"g",
".",
"remote_server",
".",
"exec_command_sync",
"(",
"mv",
"~",
"/",
"backup",
"~",
"/",
"gsdata",
")"
] | def run(remote_server, local_host):
"""
Because TPC-C would insert many tuples into database, we suggest that
backup the raw data directory and restore it when run TPC-C benchmark some times.
e.g.
```
remote_server.exec_command_sync('mv ~/backup ~/gsdata')
```
The passed two parameters are both Executor instance.
:param remote_server: SSH object for remote database server.
:param local_host: LocalExec object for local client host where run our tuning tool.
:return: benchmark score, higher one must be better, be sure to keep in mind.
"""
# Benchmark can be deployed on a remote server or a local server.
# Here we set the terminal as a remote server.
terminal = remote_server
err_logfile = os.path.join(path, 'benchmarksql-error.log')
cmd_files = shlex.split(cmd)
if len(cmd_files) != 2:
print('Invalid configuration parameter `benchmark_cmd`. '
'You should check the item in the configuration file.', file=sys.stderr)
exit(-1)
# Check whether these files exist.
shell_file, conf_file = cmd_files
shell_file = os.path.join(path, shell_file)
conf_file = os.path.join(path, conf_file)
_, stderr1 = terminal.exec_command_sync('ls %s' % shell_file)
_, stderr2 = terminal.exec_command_sync('ls %s' % conf_file)
if len(stderr1) > 0 or len(stderr2) > 0:
print('You should correct the parameter `benchmark_path` that the path contains several executable SQL files '
'in the configuration file.')
exit(-1)
# Clean log file
terminal.exec_command_sync('rm -rf %s' % err_logfile)
# Run benchmark
stdout, stderr = terminal.exec_command_sync('cd %s; %s %s' % (path, shell_file, conf_file))
if len(stderr) > 0:
raise ExecutionError(stderr)
# Find the tpmC result.
tpmC = None
split_string = stdout.split()
for i, st in enumerate(split_string):
if "(NewOrders)" in st:
tpmC = split_string[i + 2]
break
stdout, stderr = terminal.exec_command_sync(
"cat %s/benchmarksql-error.log" % path)
nb_err = stdout.count("ERROR:") # Penalty term.
return float(tpmC) - 10 * nb_err | [
"def",
"run",
"(",
"remote_server",
",",
"local_host",
")",
":",
"# Benchmark can be deployed on a remote server or a local server.",
"# Here we set the terminal as a remote server.",
"terminal",
"=",
"remote_server",
"err_logfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'benchmarksql-error.log'",
")",
"cmd_files",
"=",
"shlex",
".",
"split",
"(",
"cmd",
")",
"if",
"len",
"(",
"cmd_files",
")",
"!=",
"2",
":",
"print",
"(",
"'Invalid configuration parameter `benchmark_cmd`. '",
"'You should check the item in the configuration file.'",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"exit",
"(",
"-",
"1",
")",
"# Check whether these files exist.",
"shell_file",
",",
"conf_file",
"=",
"cmd_files",
"shell_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"shell_file",
")",
"conf_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"conf_file",
")",
"_",
",",
"stderr1",
"=",
"terminal",
".",
"exec_command_sync",
"(",
"'ls %s'",
"%",
"shell_file",
")",
"_",
",",
"stderr2",
"=",
"terminal",
".",
"exec_command_sync",
"(",
"'ls %s'",
"%",
"conf_file",
")",
"if",
"len",
"(",
"stderr1",
")",
">",
"0",
"or",
"len",
"(",
"stderr2",
")",
">",
"0",
":",
"print",
"(",
"'You should correct the parameter `benchmark_path` that the path contains several executable SQL files '",
"'in the configuration file.'",
")",
"exit",
"(",
"-",
"1",
")",
"# Clean log file",
"terminal",
".",
"exec_command_sync",
"(",
"'rm -rf %s'",
"%",
"err_logfile",
")",
"# Run benchmark",
"stdout",
",",
"stderr",
"=",
"terminal",
".",
"exec_command_sync",
"(",
"'cd %s; %s %s'",
"%",
"(",
"path",
",",
"shell_file",
",",
"conf_file",
")",
")",
"if",
"len",
"(",
"stderr",
")",
">",
"0",
":",
"raise",
"ExecutionError",
"(",
"stderr",
")",
"# Find the tpmC result.",
"tpmC",
"=",
"None",
"split_string",
"=",
"stdout",
".",
"split",
"(",
")",
"for",
"i",
",",
"st",
"in",
"enumerate",
"(",
"split_string",
")",
":",
"if",
"\"(NewOrders)\"",
"in",
"st",
":",
"tpmC",
"=",
"split_string",
"[",
"i",
"+",
"2",
"]",
"break",
"stdout",
",",
"stderr",
"=",
"terminal",
".",
"exec_command_sync",
"(",
"\"cat %s/benchmarksql-error.log\"",
"%",
"path",
")",
"nb_err",
"=",
"stdout",
".",
"count",
"(",
"\"ERROR:\"",
")",
"# Penalty term.",
"return",
"float",
"(",
"tpmC",
")",
"-",
"10",
"*",
"nb_err"
] | https://github.com/opengauss-mirror/openGauss-server/blob/e383f1b77720a00ddbe4c0655bc85914d9b02a2b/src/gausskernel/dbmind/tools/xtuner/tuner/benchmark/tpcc.py#L30-L80 | |
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/mfg/games/linear_quadratic.py | python | MFGLinearQuadraticState.returns | (self) | return [self._returns()] | Returns for all players. | Returns for all players. | [
"Returns",
"for",
"all",
"players",
"."
] | def returns(self) -> List[float]:
"""Returns for all players."""
# For now, only single-population (single-player) mean field games
# are supported.
return [self._returns()] | [
"def",
"returns",
"(",
"self",
")",
"->",
"List",
"[",
"float",
"]",
":",
"# For now, only single-population (single-player) mean field games",
"# are supported.",
"return",
"[",
"self",
".",
"_returns",
"(",
")",
"]"
] | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/mfg/games/linear_quadratic.py#L341-L345 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | Size.IncBy | (*args, **kwargs) | return _core_.Size_IncBy(*args, **kwargs) | IncBy(self, int dx, int dy) | IncBy(self, int dx, int dy) | [
"IncBy",
"(",
"self",
"int",
"dx",
"int",
"dy",
")"
] | def IncBy(*args, **kwargs):
"""IncBy(self, int dx, int dy)"""
return _core_.Size_IncBy(*args, **kwargs) | [
"def",
"IncBy",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Size_IncBy",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L994-L996 | |
flexflow/FlexFlow | 581fad8ba8d10a16a3102ee2b406b0319586df24 | python/flexflow/core/flexflow_cffi.py | python | FFModel.subtract | (self, x, y, inplace_a=False, name=None) | return Tensor(handle, owner_op_type=OpType.SUBTRACT) | Layer that subtracts two input Tensors, :attr:`output = x * y`.
:param x: the first input Tensor.
:type x: Tensor
:param y: the second input Tensor.
:type y: Tensor
:param name: the name of the layer. Default is None.
:type name: string
:returns: Tensor -- the output tensor. | Layer that subtracts two input Tensors, :attr:`output = x * y`.
:param x: the first input Tensor.
:type x: Tensor
:param y: the second input Tensor.
:type y: Tensor
:param name: the name of the layer. Default is None.
:type name: string | [
"Layer",
"that",
"subtracts",
"two",
"input",
"Tensors",
":",
"attr",
":",
"output",
"=",
"x",
"*",
"y",
".",
":",
"param",
"x",
":",
"the",
"first",
"input",
"Tensor",
".",
":",
"type",
"x",
":",
"Tensor",
":",
"param",
"y",
":",
"the",
"second",
"input",
"Tensor",
".",
":",
"type",
"y",
":",
"Tensor",
":",
"param",
"name",
":",
"the",
"name",
"of",
"the",
"layer",
".",
"Default",
"is",
"None",
".",
":",
"type",
"name",
":",
"string"
] | def subtract(self, x, y, inplace_a=False, name=None):
"""Layer that subtracts two input Tensors, :attr:`output = x * y`.
:param x: the first input Tensor.
:type x: Tensor
:param y: the second input Tensor.
:type y: Tensor
:param name: the name of the layer. Default is None.
:type name: string
:returns: Tensor -- the output tensor.
"""
c_name = get_c_name(name)
handle = ffc.flexflow_model_add_subtract(self.handle, x.handle, y.handle, inplace_a, c_name)
self.add_layer(OpType.SUBTRACT, name)
return Tensor(handle, owner_op_type=OpType.SUBTRACT) | [
"def",
"subtract",
"(",
"self",
",",
"x",
",",
"y",
",",
"inplace_a",
"=",
"False",
",",
"name",
"=",
"None",
")",
":",
"c_name",
"=",
"get_c_name",
"(",
"name",
")",
"handle",
"=",
"ffc",
".",
"flexflow_model_add_subtract",
"(",
"self",
".",
"handle",
",",
"x",
".",
"handle",
",",
"y",
".",
"handle",
",",
"inplace_a",
",",
"c_name",
")",
"self",
".",
"add_layer",
"(",
"OpType",
".",
"SUBTRACT",
",",
"name",
")",
"return",
"Tensor",
"(",
"handle",
",",
"owner_op_type",
"=",
"OpType",
".",
"SUBTRACT",
")"
] | https://github.com/flexflow/FlexFlow/blob/581fad8ba8d10a16a3102ee2b406b0319586df24/python/flexflow/core/flexflow_cffi.py#L832-L849 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/html.py | python | HtmlWinTagHandler.__init__ | (self, *args, **kwargs) | __init__(self) -> HtmlWinTagHandler | __init__(self) -> HtmlWinTagHandler | [
"__init__",
"(",
"self",
")",
"-",
">",
"HtmlWinTagHandler"
] | def __init__(self, *args, **kwargs):
"""__init__(self) -> HtmlWinTagHandler"""
_html.HtmlWinTagHandler_swiginit(self,_html.new_HtmlWinTagHandler(*args, **kwargs))
HtmlWinTagHandler._setCallbackInfo(self, self, HtmlWinTagHandler) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_html",
".",
"HtmlWinTagHandler_swiginit",
"(",
"self",
",",
"_html",
".",
"new_HtmlWinTagHandler",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"HtmlWinTagHandler",
".",
"_setCallbackInfo",
"(",
"self",
",",
"self",
",",
"HtmlWinTagHandler",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/html.py#L424-L427 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/_pydecimal.py | python | Context.copy_negate | (self, a) | return a.copy_negate() | Returns a copy of the operand with the sign inverted.
>>> ExtendedContext.copy_negate(Decimal('101.5'))
Decimal('-101.5')
>>> ExtendedContext.copy_negate(Decimal('-101.5'))
Decimal('101.5')
>>> ExtendedContext.copy_negate(1)
Decimal('-1') | Returns a copy of the operand with the sign inverted. | [
"Returns",
"a",
"copy",
"of",
"the",
"operand",
"with",
"the",
"sign",
"inverted",
"."
] | def copy_negate(self, a):
"""Returns a copy of the operand with the sign inverted.
>>> ExtendedContext.copy_negate(Decimal('101.5'))
Decimal('-101.5')
>>> ExtendedContext.copy_negate(Decimal('-101.5'))
Decimal('101.5')
>>> ExtendedContext.copy_negate(1)
Decimal('-1')
"""
a = _convert_other(a, raiseit=True)
return a.copy_negate() | [
"def",
"copy_negate",
"(",
"self",
",",
"a",
")",
":",
"a",
"=",
"_convert_other",
"(",
"a",
",",
"raiseit",
"=",
"True",
")",
"return",
"a",
".",
"copy_negate",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/_pydecimal.py#L4321-L4332 | |
eldar/deepcut-cnn | 928bf2f224fce132f6e4404b4c95fb017297a5e0 | scripts/cpp_lint.py | python | _NestingState.UpdatePreprocessor | (self, line) | Update preprocessor stack.
We need to handle preprocessors due to classes like this:
#ifdef SWIG
struct ResultDetailsPageElementExtensionPoint {
#else
struct ResultDetailsPageElementExtensionPoint : public Extension {
#endif
We make the following assumptions (good enough for most files):
- Preprocessor condition evaluates to true from #if up to first
#else/#elif/#endif.
- Preprocessor condition evaluates to false from #else/#elif up
to #endif. We still perform lint checks on these lines, but
these do not affect nesting stack.
Args:
line: current line to check. | Update preprocessor stack. | [
"Update",
"preprocessor",
"stack",
"."
] | def UpdatePreprocessor(self, line):
"""Update preprocessor stack.
We need to handle preprocessors due to classes like this:
#ifdef SWIG
struct ResultDetailsPageElementExtensionPoint {
#else
struct ResultDetailsPageElementExtensionPoint : public Extension {
#endif
We make the following assumptions (good enough for most files):
- Preprocessor condition evaluates to true from #if up to first
#else/#elif/#endif.
- Preprocessor condition evaluates to false from #else/#elif up
to #endif. We still perform lint checks on these lines, but
these do not affect nesting stack.
Args:
line: current line to check.
"""
if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line):
# Beginning of #if block, save the nesting stack here. The saved
# stack will allow us to restore the parsing state in the #else case.
self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack)))
elif Match(r'^\s*#\s*(else|elif)\b', line):
# Beginning of #else block
if self.pp_stack:
if not self.pp_stack[-1].seen_else:
# This is the first #else or #elif block. Remember the
# whole nesting stack up to this point. This is what we
# keep after the #endif.
self.pp_stack[-1].seen_else = True
self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack)
# Restore the stack to how it was before the #if
self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if)
else:
# TODO(unknown): unexpected #else, issue warning?
pass
elif Match(r'^\s*#\s*endif\b', line):
# End of #if or #else blocks.
if self.pp_stack:
# If we saw an #else, we will need to restore the nesting
# stack to its former state before the #else, otherwise we
# will just continue from where we left off.
if self.pp_stack[-1].seen_else:
# Here we can just use a shallow copy since we are the last
# reference to it.
self.stack = self.pp_stack[-1].stack_before_else
# Drop the corresponding #if
self.pp_stack.pop()
else:
# TODO(unknown): unexpected #endif, issue warning?
pass | [
"def",
"UpdatePreprocessor",
"(",
"self",
",",
"line",
")",
":",
"if",
"Match",
"(",
"r'^\\s*#\\s*(if|ifdef|ifndef)\\b'",
",",
"line",
")",
":",
"# Beginning of #if block, save the nesting stack here. The saved",
"# stack will allow us to restore the parsing state in the #else case.",
"self",
".",
"pp_stack",
".",
"append",
"(",
"_PreprocessorInfo",
"(",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"stack",
")",
")",
")",
"elif",
"Match",
"(",
"r'^\\s*#\\s*(else|elif)\\b'",
",",
"line",
")",
":",
"# Beginning of #else block",
"if",
"self",
".",
"pp_stack",
":",
"if",
"not",
"self",
".",
"pp_stack",
"[",
"-",
"1",
"]",
".",
"seen_else",
":",
"# This is the first #else or #elif block. Remember the",
"# whole nesting stack up to this point. This is what we",
"# keep after the #endif.",
"self",
".",
"pp_stack",
"[",
"-",
"1",
"]",
".",
"seen_else",
"=",
"True",
"self",
".",
"pp_stack",
"[",
"-",
"1",
"]",
".",
"stack_before_else",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"stack",
")",
"# Restore the stack to how it was before the #if",
"self",
".",
"stack",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"pp_stack",
"[",
"-",
"1",
"]",
".",
"stack_before_if",
")",
"else",
":",
"# TODO(unknown): unexpected #else, issue warning?",
"pass",
"elif",
"Match",
"(",
"r'^\\s*#\\s*endif\\b'",
",",
"line",
")",
":",
"# End of #if or #else blocks.",
"if",
"self",
".",
"pp_stack",
":",
"# If we saw an #else, we will need to restore the nesting",
"# stack to its former state before the #else, otherwise we",
"# will just continue from where we left off.",
"if",
"self",
".",
"pp_stack",
"[",
"-",
"1",
"]",
".",
"seen_else",
":",
"# Here we can just use a shallow copy since we are the last",
"# reference to it.",
"self",
".",
"stack",
"=",
"self",
".",
"pp_stack",
"[",
"-",
"1",
"]",
".",
"stack_before_else",
"# Drop the corresponding #if",
"self",
".",
"pp_stack",
".",
"pop",
"(",
")",
"else",
":",
"# TODO(unknown): unexpected #endif, issue warning?",
"pass"
] | https://github.com/eldar/deepcut-cnn/blob/928bf2f224fce132f6e4404b4c95fb017297a5e0/scripts/cpp_lint.py#L1948-L2002 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/joblib/joblib/parallel.py | python | _register_dask | () | Register Dask Backend if called with parallel_backend("dask") | Register Dask Backend if called with parallel_backend("dask") | [
"Register",
"Dask",
"Backend",
"if",
"called",
"with",
"parallel_backend",
"(",
"dask",
")"
] | def _register_dask():
""" Register Dask Backend if called with parallel_backend("dask") """
try:
from ._dask import DaskDistributedBackend
register_parallel_backend('dask', DaskDistributedBackend)
except ImportError as e:
msg = ("To use the dask.distributed backend you must install both "
"the `dask` and distributed modules.\n\n"
"See https://dask.pydata.org/en/latest/install.html for more "
"information.")
raise ImportError(msg) from e | [
"def",
"_register_dask",
"(",
")",
":",
"try",
":",
"from",
".",
"_dask",
"import",
"DaskDistributedBackend",
"register_parallel_backend",
"(",
"'dask'",
",",
"DaskDistributedBackend",
")",
"except",
"ImportError",
"as",
"e",
":",
"msg",
"=",
"(",
"\"To use the dask.distributed backend you must install both \"",
"\"the `dask` and distributed modules.\\n\\n\"",
"\"See https://dask.pydata.org/en/latest/install.html for more \"",
"\"information.\"",
")",
"raise",
"ImportError",
"(",
"msg",
")",
"from",
"e"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/joblib/joblib/parallel.py#L58-L68 | ||
apple/swift | 469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893 | utils/build_swift/build_swift/wrappers/xcrun.py | python | XcrunWrapper.sdk_version | (self, sdk=None, toolchain=None) | return Version(output.rstrip()) | Returns the SDK version. Returns None if the SDK cannot be found. | Returns the SDK version. Returns None if the SDK cannot be found. | [
"Returns",
"the",
"SDK",
"version",
".",
"Returns",
"None",
"if",
"the",
"SDK",
"cannot",
"be",
"found",
"."
] | def sdk_version(self, sdk=None, toolchain=None):
"""Returns the SDK version. Returns None if the SDK cannot be found.
"""
output = self.check_output(
'--show-sdk-version',
sdk=sdk,
toolchain=toolchain,
stderr=shell.DEVNULL)
return Version(output.rstrip()) | [
"def",
"sdk_version",
"(",
"self",
",",
"sdk",
"=",
"None",
",",
"toolchain",
"=",
"None",
")",
":",
"output",
"=",
"self",
".",
"check_output",
"(",
"'--show-sdk-version'",
",",
"sdk",
"=",
"sdk",
",",
"toolchain",
"=",
"toolchain",
",",
"stderr",
"=",
"shell",
".",
"DEVNULL",
")",
"return",
"Version",
"(",
"output",
".",
"rstrip",
"(",
")",
")"
] | https://github.com/apple/swift/blob/469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893/utils/build_swift/build_swift/wrappers/xcrun.py#L147-L157 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/Reflectometry/isis_reflectometry/combineMulti.py | python | combineDataMulti | (wksp_list, output_wksp, beg_overlap, end_overlap, Qmin, Qmax, binning, scale_high=1,
scale_factor=-1.0, which_period=1, keep=0, scale_right=True) | return mtd[output_wksp] | Function stitches multiple workspaces together. Workspaces should have an X-axis in mod Q, and the Spectrum axis as I/I0
wksp_list: A list of workspaces to stitch together
ouput_wksp: output workspace name
beg_overlap: The beginning of the overlap region. List argument, each entry matches the entry in the wksp_list
end_overlap: The end of the overlap region. List argument, each entry matches the entry in the wksp_list
Qmin: Q minimum of the final output workspace
Qmax: Q maximum of the input workspace
which_period: Which period to use if multiperiod workspaces are provided.
keep=1: keep individual workspaces in Mantid, otherwise delete wksp_list
scale_right: Scales the rhs workspace as part of stitching, if False scales the lhs workspace. | Function stitches multiple workspaces together. Workspaces should have an X-axis in mod Q, and the Spectrum axis as I/I0 | [
"Function",
"stitches",
"multiple",
"workspaces",
"together",
".",
"Workspaces",
"should",
"have",
"an",
"X",
"-",
"axis",
"in",
"mod",
"Q",
"and",
"the",
"Spectrum",
"axis",
"as",
"I",
"/",
"I0"
] | def combineDataMulti(wksp_list, output_wksp, beg_overlap, end_overlap, Qmin, Qmax, binning, scale_high=1,
scale_factor=-1.0, which_period=1, keep=0, scale_right=True):
"""
Function stitches multiple workspaces together. Workspaces should have an X-axis in mod Q, and the Spectrum axis as I/I0
wksp_list: A list of workspaces to stitch together
ouput_wksp: output workspace name
beg_overlap: The beginning of the overlap region. List argument, each entry matches the entry in the wksp_list
end_overlap: The end of the overlap region. List argument, each entry matches the entry in the wksp_list
Qmin: Q minimum of the final output workspace
Qmax: Q maximum of the input workspace
which_period: Which period to use if multiperiod workspaces are provided.
keep=1: keep individual workspaces in Mantid, otherwise delete wksp_list
scale_right: Scales the rhs workspace as part of stitching, if False scales the lhs workspace.
"""
# check if overlaps have correct number of entries
defaultoverlaps = False
if not isinstance(beg_overlap, list):
beg_overlap = [beg_overlap]
if not isinstance(end_overlap, list):
end_overlap = [end_overlap]
if len(wksp_list) != len(beg_overlap):
print("Using default values!")
defaultoverlaps = True
# copy first workspace into temporary wksp 'currentSum'
currentSum = CloneWorkspace(InputWorkspace=wksp_list[0])
print("Length: ", len(wksp_list), wksp_list)
for i in range(0, len(wksp_list) - 1):
w1 = currentSum
w2 = getWorkspace(wksp_list[i + 1])
# TODO: distinguishing between a group and a individual workspace is unnecessary for an algorithm.
# But custom group behavior WILL be required.
if defaultoverlaps:
overlapLow = w2.readX(0)[0]
overlapHigh = 0.5 * max(w1.readX(0))
else:
overlapLow = beg_overlap[i + 1]
overlapHigh = end_overlap[i]
print("Iteration", i)
currentSum, scale_factor = stitch2(currentSum, mtd[wksp_list[i + 1]], currentSum.name(), overlapLow,
overlapHigh, Qmin, Qmax, binning, scale_high, scale_right=scale_right)
RenameWorkspace(InputWorkspace=currentSum.name(), OutputWorkspace=output_wksp)
# Remove any existing workspaces from the workspace list.
if not keep:
names = mtd.getObjectNames()
for ws in wksp_list:
candidate = ws
if candidate in names:
DeleteWorkspace(candidate)
return mtd[output_wksp] | [
"def",
"combineDataMulti",
"(",
"wksp_list",
",",
"output_wksp",
",",
"beg_overlap",
",",
"end_overlap",
",",
"Qmin",
",",
"Qmax",
",",
"binning",
",",
"scale_high",
"=",
"1",
",",
"scale_factor",
"=",
"-",
"1.0",
",",
"which_period",
"=",
"1",
",",
"keep",
"=",
"0",
",",
"scale_right",
"=",
"True",
")",
":",
"# check if overlaps have correct number of entries",
"defaultoverlaps",
"=",
"False",
"if",
"not",
"isinstance",
"(",
"beg_overlap",
",",
"list",
")",
":",
"beg_overlap",
"=",
"[",
"beg_overlap",
"]",
"if",
"not",
"isinstance",
"(",
"end_overlap",
",",
"list",
")",
":",
"end_overlap",
"=",
"[",
"end_overlap",
"]",
"if",
"len",
"(",
"wksp_list",
")",
"!=",
"len",
"(",
"beg_overlap",
")",
":",
"print",
"(",
"\"Using default values!\"",
")",
"defaultoverlaps",
"=",
"True",
"# copy first workspace into temporary wksp 'currentSum'",
"currentSum",
"=",
"CloneWorkspace",
"(",
"InputWorkspace",
"=",
"wksp_list",
"[",
"0",
"]",
")",
"print",
"(",
"\"Length: \"",
",",
"len",
"(",
"wksp_list",
")",
",",
"wksp_list",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"wksp_list",
")",
"-",
"1",
")",
":",
"w1",
"=",
"currentSum",
"w2",
"=",
"getWorkspace",
"(",
"wksp_list",
"[",
"i",
"+",
"1",
"]",
")",
"# TODO: distinguishing between a group and a individual workspace is unnecessary for an algorithm.",
"# But custom group behavior WILL be required.",
"if",
"defaultoverlaps",
":",
"overlapLow",
"=",
"w2",
".",
"readX",
"(",
"0",
")",
"[",
"0",
"]",
"overlapHigh",
"=",
"0.5",
"*",
"max",
"(",
"w1",
".",
"readX",
"(",
"0",
")",
")",
"else",
":",
"overlapLow",
"=",
"beg_overlap",
"[",
"i",
"+",
"1",
"]",
"overlapHigh",
"=",
"end_overlap",
"[",
"i",
"]",
"print",
"(",
"\"Iteration\"",
",",
"i",
")",
"currentSum",
",",
"scale_factor",
"=",
"stitch2",
"(",
"currentSum",
",",
"mtd",
"[",
"wksp_list",
"[",
"i",
"+",
"1",
"]",
"]",
",",
"currentSum",
".",
"name",
"(",
")",
",",
"overlapLow",
",",
"overlapHigh",
",",
"Qmin",
",",
"Qmax",
",",
"binning",
",",
"scale_high",
",",
"scale_right",
"=",
"scale_right",
")",
"RenameWorkspace",
"(",
"InputWorkspace",
"=",
"currentSum",
".",
"name",
"(",
")",
",",
"OutputWorkspace",
"=",
"output_wksp",
")",
"# Remove any existing workspaces from the workspace list.",
"if",
"not",
"keep",
":",
"names",
"=",
"mtd",
".",
"getObjectNames",
"(",
")",
"for",
"ws",
"in",
"wksp_list",
":",
"candidate",
"=",
"ws",
"if",
"candidate",
"in",
"names",
":",
"DeleteWorkspace",
"(",
"candidate",
")",
"return",
"mtd",
"[",
"output_wksp",
"]"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Reflectometry/isis_reflectometry/combineMulti.py#L13-L67 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/multi_threads_helpers.py | python | AddPeaksThread.__init__ | (self, main_window, exp_number, scan_number_list) | return | Initialization
:param main_window:
:param exp_number:
:param scan_number_list: | Initialization
:param main_window:
:param exp_number:
:param scan_number_list: | [
"Initialization",
":",
"param",
"main_window",
":",
":",
"param",
"exp_number",
":",
":",
"param",
"scan_number_list",
":"
] | def __init__(self, main_window, exp_number, scan_number_list):
"""
Initialization
:param main_window:
:param exp_number:
:param scan_number_list:
"""
# check
assert main_window is not None, 'Main window cannot be None'
assert isinstance(exp_number, int), 'Experiment number must be an integer.'
assert isinstance(scan_number_list, list), 'Scan number list must be a list but not %s.' \
'' % str(type(scan_number_list))
# init thread
super(AddPeaksThread, self).__init__()
# set values
self._mainWindow = main_window
self._expNumber = exp_number
self._scanNumberList = scan_number_list
# connect to the updateTextEdit slot defined in app1.py
self.peakAddedSignal.connect(self._mainWindow.update_peak_added_info)
self.peakStatusSignal.connect(self._mainWindow.update_adding_peaks_status)
self.peakAddedErrorSignal.connect(self._mainWindow.report_peak_addition)
return | [
"def",
"__init__",
"(",
"self",
",",
"main_window",
",",
"exp_number",
",",
"scan_number_list",
")",
":",
"# check",
"assert",
"main_window",
"is",
"not",
"None",
",",
"'Main window cannot be None'",
"assert",
"isinstance",
"(",
"exp_number",
",",
"int",
")",
",",
"'Experiment number must be an integer.'",
"assert",
"isinstance",
"(",
"scan_number_list",
",",
"list",
")",
",",
"'Scan number list must be a list but not %s.'",
"''",
"%",
"str",
"(",
"type",
"(",
"scan_number_list",
")",
")",
"# init thread",
"super",
"(",
"AddPeaksThread",
",",
"self",
")",
".",
"__init__",
"(",
")",
"# set values",
"self",
".",
"_mainWindow",
"=",
"main_window",
"self",
".",
"_expNumber",
"=",
"exp_number",
"self",
".",
"_scanNumberList",
"=",
"scan_number_list",
"# connect to the updateTextEdit slot defined in app1.py",
"self",
".",
"peakAddedSignal",
".",
"connect",
"(",
"self",
".",
"_mainWindow",
".",
"update_peak_added_info",
")",
"self",
".",
"peakStatusSignal",
".",
"connect",
"(",
"self",
".",
"_mainWindow",
".",
"update_adding_peaks_status",
")",
"self",
".",
"peakAddedErrorSignal",
".",
"connect",
"(",
"self",
".",
"_mainWindow",
".",
"report_peak_addition",
")",
"return"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/multi_threads_helpers.py#L26-L52 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.