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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/collections.py | python | OrderedDict.__delitem__ | (self, key, dict_delitem=dict.__delitem__) | od.__delitem__(y) <==> del od[y] | od.__delitem__(y) <==> del od[y] | [
"od",
".",
"__delitem__",
"(",
"y",
")",
"<",
"==",
">",
"del",
"od",
"[",
"y",
"]"
] | def __delitem__(self, key, dict_delitem=dict.__delitem__):
'od.__delitem__(y) <==> del od[y]'
# Deleting an existing item uses self.__map to find the link which gets
# removed by updating the links in the predecessor and successor nodes.
dict_delitem(self, key)
link_prev, link_next, _ = self.__map.pop(key)
link_prev[1] = link_next # update link_prev[NEXT]
link_next[0] = link_prev | [
"def",
"__delitem__",
"(",
"self",
",",
"key",
",",
"dict_delitem",
"=",
"dict",
".",
"__delitem__",
")",
":",
"# Deleting an existing item uses self.__map to find the link which gets",
"# removed by updating the links in the predecessor and successor nodes.",
"dict_delitem",
"(",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/collections.py#L81-L88 | ||
openthread/openthread | 9fcdbed9c526c70f1556d1ed84099c1535c7cd32 | tools/otci/otci/otci.py | python | OTCI.get_child_list | (self) | return [ChildId(id) for id in line.strip().split()] | Get attached Child IDs. | Get attached Child IDs. | [
"Get",
"attached",
"Child",
"IDs",
"."
] | def get_child_list(self) -> List[ChildId]:
"""Get attached Child IDs."""
line = self.__parse_str(self.execute_command(f'child list'))
return [ChildId(id) for id in line.strip().split()] | [
"def",
"get_child_list",
"(",
"self",
")",
"->",
"List",
"[",
"ChildId",
"]",
":",
"line",
"=",
"self",
".",
"__parse_str",
"(",
"self",
".",
"execute_command",
"(",
"f'child list'",
")",
")",
"return",
"[",
"ChildId",
"(",
"id",
")",
"for",
"id",
"in"... | https://github.com/openthread/openthread/blob/9fcdbed9c526c70f1556d1ed84099c1535c7cd32/tools/otci/otci/otci.py#L1188-L1191 | |
OAID/Tengine | 66b2c22ad129d25e2fc6de3b22a608bb54dd90db | tools/optimize/convert_model_batch.py | python | convert_model_onnx | (convert_tool_path, onnx_model_path) | convert single model
:param convert_tool_path:
:param onnx_model_path:
:return: | convert single model
:param convert_tool_path:
:param onnx_model_path:
:return: | [
"convert",
"single",
"model",
":",
"param",
"convert_tool_path",
":",
":",
"param",
"onnx_model_path",
":",
":",
"return",
":"
] | def convert_model_onnx(convert_tool_path, onnx_model_path):
"""
convert single model
:param convert_tool_path:
:param onnx_model_path:
:return:
"""
folder_dir, file_name = os.path.split(onnx_model_path)
shell_commad = './' if './' not in convert_tool_path else ''
shell_commad += f"{convert_tool_path} -f onnx -m {onnx_model_path} -o {folder_dir}/onnx.tmfile"
# print(shell_commad)
(status, output) = subprocess.getstatusoutput(shell_commad)
if status != 0:
if os.path.exists(f"{folder_dir}/onnx.tmfile"):
shell_commad = f"rm {folder_dir}/onnx.tmfile"
os.system(shell_commad)
return False, output
else:
return True, output | [
"def",
"convert_model_onnx",
"(",
"convert_tool_path",
",",
"onnx_model_path",
")",
":",
"folder_dir",
",",
"file_name",
"=",
"os",
".",
"path",
".",
"split",
"(",
"onnx_model_path",
")",
"shell_commad",
"=",
"'./'",
"if",
"'./'",
"not",
"in",
"convert_tool_path... | https://github.com/OAID/Tengine/blob/66b2c22ad129d25e2fc6de3b22a608bb54dd90db/tools/optimize/convert_model_batch.py#L70-L90 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/traitlets/py2/traitlets/traitlets.py | python | TraitType.init_default_value | (self, obj) | return value | DEPRECATED: Set the static default value for the trait type. | DEPRECATED: Set the static default value for the trait type. | [
"DEPRECATED",
":",
"Set",
"the",
"static",
"default",
"value",
"for",
"the",
"trait",
"type",
"."
] | def init_default_value(self, obj):
"""DEPRECATED: Set the static default value for the trait type.
"""
warn("init_default_value is deprecated in traitlets 4.0, and may be removed in the future", DeprecationWarning,
stacklevel=2)
value = self._validate(obj, self.default_value)
obj._trait_values[self.name] = value
return value | [
"def",
"init_default_value",
"(",
"self",
",",
"obj",
")",
":",
"warn",
"(",
"\"init_default_value is deprecated in traitlets 4.0, and may be removed in the future\"",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
")",
"value",
"=",
"self",
".",
"_validate",
"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/traitlets/py2/traitlets/traitlets.py#L477-L484 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | build/android/pylib/device/adb_wrapper.py | python | AdbWrapper.WaitForDevice | (self, timeout=60*5, retries=_DEFAULT_RETRIES) | Block until the device is online.
Args:
timeout: (optional) Timeout per try in seconds.
retries: (optional) Number of retries to attempt. | Block until the device is online. | [
"Block",
"until",
"the",
"device",
"is",
"online",
"."
] | def WaitForDevice(self, timeout=60*5, retries=_DEFAULT_RETRIES):
"""Block until the device is online.
Args:
timeout: (optional) Timeout per try in seconds.
retries: (optional) Number of retries to attempt.
"""
self._DeviceAdbCmd(['wait-for-device'], timeout, retries) | [
"def",
"WaitForDevice",
"(",
"self",
",",
"timeout",
"=",
"60",
"*",
"5",
",",
"retries",
"=",
"_DEFAULT_RETRIES",
")",
":",
"self",
".",
"_DeviceAdbCmd",
"(",
"[",
"'wait-for-device'",
"]",
",",
"timeout",
",",
"retries",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/build/android/pylib/device/adb_wrapper.py#L361-L368 | ||
Tencent/CMONGO | c40380caa14e05509f46993aa8b8da966b09b0b5 | site_scons/libdeps.py | python | sorted_by_str | (iterable) | return sorted(iterable, cmp=lambda lhs, rhs: cmp(str(lhs), str(rhs))) | Shorthand for sorting an iterable according to its string representation.
We use this instead of sorted(), below, because SCons.Node objects are
compared on object identity, rather than value, so sorts aren't stable
across invocations of SCons. Since dependency order changes force rebuilds,
we use this sort to create stable dependency orders. | Shorthand for sorting an iterable according to its string representation. | [
"Shorthand",
"for",
"sorting",
"an",
"iterable",
"according",
"to",
"its",
"string",
"representation",
"."
] | def sorted_by_str(iterable):
"""Shorthand for sorting an iterable according to its string representation.
We use this instead of sorted(), below, because SCons.Node objects are
compared on object identity, rather than value, so sorts aren't stable
across invocations of SCons. Since dependency order changes force rebuilds,
we use this sort to create stable dependency orders.
"""
return sorted(iterable, cmp=lambda lhs, rhs: cmp(str(lhs), str(rhs))) | [
"def",
"sorted_by_str",
"(",
"iterable",
")",
":",
"return",
"sorted",
"(",
"iterable",
",",
"cmp",
"=",
"lambda",
"lhs",
",",
"rhs",
":",
"cmp",
"(",
"str",
"(",
"lhs",
")",
",",
"str",
"(",
"rhs",
")",
")",
")"
] | https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/site_scons/libdeps.py#L63-L71 | |
cocos2d/cocos2d-x | 90f6542cf7fb081335f04e474b880d7ce8c445a1 | tools/tolua/genbindings.py | python | _check_ndk_root_env | () | return NDK_ROOT | Checking the environment NDK_ROOT, which will be used for building | Checking the environment NDK_ROOT, which will be used for building | [
"Checking",
"the",
"environment",
"NDK_ROOT",
"which",
"will",
"be",
"used",
"for",
"building"
] | def _check_ndk_root_env():
''' Checking the environment NDK_ROOT, which will be used for building
'''
try:
NDK_ROOT = os.environ['NDK_ROOT']
except Exception:
print "NDK_ROOT not defined. Please define NDK_ROOT in your environment."
sys.exit(1)
return NDK_ROOT | [
"def",
"_check_ndk_root_env",
"(",
")",
":",
"try",
":",
"NDK_ROOT",
"=",
"os",
".",
"environ",
"[",
"'NDK_ROOT'",
"]",
"except",
"Exception",
":",
"print",
"\"NDK_ROOT not defined. Please define NDK_ROOT in your environment.\"",
"sys",
".",
"exit",
"(",
"1",
")",
... | https://github.com/cocos2d/cocos2d-x/blob/90f6542cf7fb081335f04e474b880d7ce8c445a1/tools/tolua/genbindings.py#L16-L26 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/keras/backend.py | python | deprecated_internal_set_learning_phase | (value) | A deprecated internal implementation of set_learning_phase.
This method is an internal-only version of `set_learning_phase` that
does not raise a deprecation error. It is required because
saved_model needs to keep working with user code that uses the deprecated
learning phase methods until those APIs are fully removed from the public API.
Specifically SavedModel saving needs to make sure the learning phase is 0
during tracing even if users overwrote it to a different value.
But, we don't want to raise deprecation warnings for users when savedmodel
sets learning phase just for compatibility with code that relied on
explicitly setting the learning phase for other values.
Args:
value: Learning phase value, either 0 or 1 (integers). 0 = test, 1 = train
Raises:
ValueError: if `value` is neither `0` nor `1`. | A deprecated internal implementation of set_learning_phase. | [
"A",
"deprecated",
"internal",
"implementation",
"of",
"set_learning_phase",
"."
] | def deprecated_internal_set_learning_phase(value):
"""A deprecated internal implementation of set_learning_phase.
This method is an internal-only version of `set_learning_phase` that
does not raise a deprecation error. It is required because
saved_model needs to keep working with user code that uses the deprecated
learning phase methods until those APIs are fully removed from the public API.
Specifically SavedModel saving needs to make sure the learning phase is 0
during tracing even if users overwrote it to a different value.
But, we don't want to raise deprecation warnings for users when savedmodel
sets learning phase just for compatibility with code that relied on
explicitly setting the learning phase for other values.
Args:
value: Learning phase value, either 0 or 1 (integers). 0 = test, 1 = train
Raises:
ValueError: if `value` is neither `0` nor `1`.
"""
global _GRAPH_LEARNING_PHASES # pylint: disable=global-variable-not-assigned
if value not in {0, 1}:
raise ValueError('Expected learning phase to be 0 or 1.')
with ops.init_scope():
if context.executing_eagerly():
# In an eager context, the learning phase values applies to both the eager
# context and the internal Keras graph.
_DUMMY_EAGER_GRAPH.learning_phase_is_set = True
_GRAPH_LEARNING_PHASES[_DUMMY_EAGER_GRAPH.key] = value
_GRAPH_LEARNING_PHASES[get_graph()] = value | [
"def",
"deprecated_internal_set_learning_phase",
"(",
"value",
")",
":",
"global",
"_GRAPH_LEARNING_PHASES",
"# pylint: disable=global-variable-not-assigned",
"if",
"value",
"not",
"in",
"{",
"0",
",",
"1",
"}",
":",
"raise",
"ValueError",
"(",
"'Expected learning phase t... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/backend.py#L444-L474 | ||
NERSC/timemory | 431912b360ff50d1a160d7826e2eea04fbd1037f | timemory/analyze/analyze.py | python | search | (data, pattern, field="name") | return ret | Find the graphframes with substring that matches regular expression | Find the graphframes with substring that matches regular expression | [
"Find",
"the",
"graphframes",
"with",
"substring",
"that",
"matches",
"regular",
"expression"
] | def search(data, pattern, field="name"):
"""Find the graphframes with substring that matches regular expression"""
prog = re.compile(pattern)
if not isinstance(data, list):
return data.filter(
lambda x: (prog.search(x[field]) is not None),
num_procs=filter_num_procs,
)
ret = []
for itr in data:
ret.append(
itr.filter(
lambda x: (prog.search(x[field]) is not None),
num_procs=filter_num_procs,
)
)
return ret | [
"def",
"search",
"(",
"data",
",",
"pattern",
",",
"field",
"=",
"\"name\"",
")",
":",
"prog",
"=",
"re",
".",
"compile",
"(",
"pattern",
")",
"if",
"not",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"return",
"data",
".",
"filter",
"(",
"lam... | https://github.com/NERSC/timemory/blob/431912b360ff50d1a160d7826e2eea04fbd1037f/timemory/analyze/analyze.py#L177-L196 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/compression/export/quant_export.py | python | ExportToQuantInferNetwork._get_quant_block | (self, cell_core, activation, fake_quant_a_out) | return block | convert network's quant subcell to deploy subcell | convert network's quant subcell to deploy subcell | [
"convert",
"network",
"s",
"quant",
"subcell",
"to",
"deploy",
"subcell"
] | def _get_quant_block(self, cell_core, activation, fake_quant_a_out):
"""convert network's quant subcell to deploy subcell"""
scale_a_in, zp_a_in, scale_w, zp_w, param_dict = self.__get_quant_param(cell_core, fake_quant_a_out)
# Build the `Quant` `Dequant` op.
# Quant only support perlayer version. Need check here.
quant_op = inner.Quant(1 / float(scale_a_in), float(zp_a_in))
scale_deq = self.__get_dequant_scale(scale_a_in, scale_w)
dequant_op = inner.Dequant()
if isinstance(activation, _AddFakeQuantAfterSubCell):
activation = activation.subcell
elif hasattr(activation, "get_origin"):
activation = activation.get_origin()
# get op
if isinstance(cell_core, quant.DenseQuant):
op_core = P.MatMul()
else:
op_core = cell_core.conv
# get the `weight` and `bias`
weight, bias, weight_b, bias_b = self.__get_weight_bias(cell_core, scale_a_in, scale_w, zp_w)
if self.is_mindir:
block = QuantMindirBlock(op_core, weight_b, bias_b, activation, param_dict)
else:
block = QuantBlock(op_core, weight, quant_op, dequant_op, scale_deq, bias, activation)
return block | [
"def",
"_get_quant_block",
"(",
"self",
",",
"cell_core",
",",
"activation",
",",
"fake_quant_a_out",
")",
":",
"scale_a_in",
",",
"zp_a_in",
",",
"scale_w",
",",
"zp_w",
",",
"param_dict",
"=",
"self",
".",
"__get_quant_param",
"(",
"cell_core",
",",
"fake_qu... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/compression/export/quant_export.py#L228-L256 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/layers/python/layers/feature_column.py | python | _SparseColumnKeys.insert_transformed_feature | (self, columns_to_tensors) | Handles sparse column to id conversion. | Handles sparse column to id conversion. | [
"Handles",
"sparse",
"column",
"to",
"id",
"conversion",
"."
] | def insert_transformed_feature(self, columns_to_tensors):
"""Handles sparse column to id conversion."""
columns_to_tensors[self] = contrib_lookup_ops.string_to_index(
tensor=columns_to_tensors[self.name],
mapping=list(self.lookup_config.keys),
default_value=self.lookup_config.default_value,
name=self.name + "_lookup") | [
"def",
"insert_transformed_feature",
"(",
"self",
",",
"columns_to_tensors",
")",
":",
"columns_to_tensors",
"[",
"self",
"]",
"=",
"contrib_lookup_ops",
".",
"string_to_index",
"(",
"tensor",
"=",
"columns_to_tensors",
"[",
"self",
".",
"name",
"]",
",",
"mapping... | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/layers/python/layers/feature_column.py#L419-L425 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/floatcanvas/FloatCanvas.py | python | DrawObject.__init__ | (self, InForeground = False, IsVisible = True) | :param InForeground=False: whether you want the object in the foreground
:param param IsVisible = True: whther the object is visible | :param InForeground=False: whether you want the object in the foreground
:param param IsVisible = True: whther the object is visible | [
":",
"param",
"InForeground",
"=",
"False",
":",
"whether",
"you",
"want",
"the",
"object",
"in",
"the",
"foreground",
":",
"param",
"param",
"IsVisible",
"=",
"True",
":",
"whther",
"the",
"object",
"is",
"visible"
] | def __init__(self, InForeground = False, IsVisible = True):
"""
:param InForeground=False: whether you want the object in the foreground
:param param IsVisible = True: whther the object is visible
"""
self.InForeground = InForeground
self._Canvas = None
#self._Actual_Canvas = None
self.HitColor = None
self.CallBackFuncs = {}
## these are the defaults
self.HitAble = False
self.HitLine = True
self.HitFill = True
self.MinHitLineWidth = 3
self.HitLineWidth = 3 ## this gets re-set by the subclasses if necessary
self.Brush = None
self.Pen = None
self.FillStyle = "Solid"
self.Visible = IsVisible | [
"def",
"__init__",
"(",
"self",
",",
"InForeground",
"=",
"False",
",",
"IsVisible",
"=",
"True",
")",
":",
"self",
".",
"InForeground",
"=",
"InForeground",
"self",
".",
"_Canvas",
"=",
"None",
"#self._Actual_Canvas = None",
"self",
".",
"HitColor",
"=",
"N... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/floatcanvas/FloatCanvas.py#L164-L189 | ||
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/boost_1_66_0/tools/build/src/build/type.py | python | reset | () | Clear the module state. This is mainly for testing purposes.
Note that this must be called _after_ resetting the module 'feature'. | Clear the module state. This is mainly for testing purposes.
Note that this must be called _after_ resetting the module 'feature'. | [
"Clear",
"the",
"module",
"state",
".",
"This",
"is",
"mainly",
"for",
"testing",
"purposes",
".",
"Note",
"that",
"this",
"must",
"be",
"called",
"_after_",
"resetting",
"the",
"module",
"feature",
"."
] | def reset ():
""" Clear the module state. This is mainly for testing purposes.
Note that this must be called _after_ resetting the module 'feature'.
"""
global __prefixes_suffixes, __suffixes_to_types, __types, __rule_names_to_types, __target_suffixes_cache
__register_features ()
# Stores suffixes for generated targets.
__prefixes_suffixes = [property.PropertyMap(), property.PropertyMap()]
# Maps suffixes to types
__suffixes_to_types = {}
# A map with all the registered types, indexed by the type name
# Each entry is a dictionary with following values:
# 'base': the name of base type or None if type has no base
# 'derived': a list of names of type which derive from this one
# 'scanner': the scanner class registered for this type, if any
__types = {}
# Caches suffixes for targets with certain properties.
__target_suffixes_cache = {} | [
"def",
"reset",
"(",
")",
":",
"global",
"__prefixes_suffixes",
",",
"__suffixes_to_types",
",",
"__types",
",",
"__rule_names_to_types",
",",
"__target_suffixes_cache",
"__register_features",
"(",
")",
"# Stores suffixes for generated targets.",
"__prefixes_suffixes",
"=",
... | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/boost_1_66_0/tools/build/src/build/type.py#L32-L54 | ||
wyrover/book-code | 7f4883d9030d553bc6bcfa3da685e34789839900 | 3rdparty/protobuf/python/google/protobuf/internal/well_known_types.py | python | Struct.get_or_create_list | (self, key) | return self.fields[key].list_value | Returns a list for this key, creating if it didn't exist already. | Returns a list for this key, creating if it didn't exist already. | [
"Returns",
"a",
"list",
"for",
"this",
"key",
"creating",
"if",
"it",
"didn",
"t",
"exist",
"already",
"."
] | def get_or_create_list(self, key):
"""Returns a list for this key, creating if it didn't exist already."""
return self.fields[key].list_value | [
"def",
"get_or_create_list",
"(",
"self",
",",
"key",
")",
":",
"return",
"self",
".",
"fields",
"[",
"key",
"]",
".",
"list_value"
] | https://github.com/wyrover/book-code/blob/7f4883d9030d553bc6bcfa3da685e34789839900/3rdparty/protobuf/python/google/protobuf/internal/well_known_types.py#L673-L675 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/tools/jinja2/compiler.py | python | CodeGenerator.position | (self, node) | return rv | Return a human readable position for the node. | Return a human readable position for the node. | [
"Return",
"a",
"human",
"readable",
"position",
"for",
"the",
"node",
"."
] | def position(self, node):
"""Return a human readable position for the node."""
rv = 'line %d' % node.lineno
if self.name is not None:
rv += ' in ' + repr(self.name)
return rv | [
"def",
"position",
"(",
"self",
",",
"node",
")",
":",
"rv",
"=",
"'line %d'",
"%",
"node",
".",
"lineno",
"if",
"self",
".",
"name",
"is",
"not",
"None",
":",
"rv",
"+=",
"' in '",
"+",
"repr",
"(",
"self",
".",
"name",
")",
"return",
"rv"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/jinja2/compiler.py#L593-L598 | |
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | build/pymake/pymake/data.py | python | BaseExpansion.variable_references | (self, descend=False) | Obtain all variable references in this expansion.
This is a generator for pymake.functionsVariableRef instances.
To retrieve the names of variables, simply query the `vname` field on
the returned instances. Most of the time these will be StringExpansion
instances. | Obtain all variable references in this expansion. | [
"Obtain",
"all",
"variable",
"references",
"in",
"this",
"expansion",
"."
] | def variable_references(self, descend=False):
"""Obtain all variable references in this expansion.
This is a generator for pymake.functionsVariableRef instances.
To retrieve the names of variables, simply query the `vname` field on
the returned instances. Most of the time these will be StringExpansion
instances.
"""
for f in self.functions(descend=descend):
if not isinstance(f, functions.VariableRef):
continue
yield f | [
"def",
"variable_references",
"(",
"self",
",",
"descend",
"=",
"False",
")",
":",
"for",
"f",
"in",
"self",
".",
"functions",
"(",
"descend",
"=",
"descend",
")",
":",
"if",
"not",
"isinstance",
"(",
"f",
",",
"functions",
".",
"VariableRef",
")",
":"... | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/build/pymake/pymake/data.py#L101-L114 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/command/sdist.py | python | sdist.make_distribution | (self) | Workaround for #516 | Workaround for #516 | [
"Workaround",
"for",
"#516"
] | def make_distribution(self):
"""
Workaround for #516
"""
with self._remove_os_link():
orig.sdist.make_distribution(self) | [
"def",
"make_distribution",
"(",
"self",
")",
":",
"with",
"self",
".",
"_remove_os_link",
"(",
")",
":",
"orig",
".",
"sdist",
".",
"make_distribution",
"(",
"self",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/command/sdist.py#L73-L78 | ||
h2oai/datatable | 753197c3f76041dd6468e0f6a9708af92d80f6aa | docs/_ext/xfunction.py | python | XobjectDirective._parse_docstring | (self) | Split the docstring into two parts: the signature and the
body (the parts should be separated with a "--" line). After
that, defers parsing of each part to :meth:`_parse_parameters`
and :meth:`_parse_body` respectively. | Split the docstring into two parts: the signature and the
body (the parts should be separated with a "--" line). After
that, defers parsing of each part to :meth:`_parse_parameters`
and :meth:`_parse_body` respectively. | [
"Split",
"the",
"docstring",
"into",
"two",
"parts",
":",
"the",
"signature",
"and",
"the",
"body",
"(",
"the",
"parts",
"should",
"be",
"separated",
"with",
"a",
"--",
"line",
")",
".",
"After",
"that",
"defers",
"parsing",
"of",
"each",
"part",
"to",
... | def _parse_docstring(self):
"""
Split the docstring into two parts: the signature and the
body (the parts should be separated with a "--" line). After
that, defers parsing of each part to :meth:`_parse_parameters`
and :meth:`_parse_body` respectively.
"""
if self.signature:
signature = self.signature
body = self.content
else:
if (self.name in ["xdata", "xattr", "xclass", "xexc"] or
"--" not in self.doc_lines):
self.parsed_params = []
self._parse_body(self.doc_lines)
return
iddash = self.doc_lines.index("--")
signature = "\n".join(self.doc_lines.data[:iddash])
body = self.doc_lines[iddash + 1:]
if not (signature.startswith(self.obj_name + "(") and
signature.endswith(")")):
raise self.error("Unexpected docstring: should have started with "
"`%s(` and ended with `)`, instead found %r"
% (self.obj_name, signature))
# strip objname and the parentheses
signature = signature[(len(self.obj_name) + 1):-1]
self._parse_parameters(signature)
self._parse_body(body) | [
"def",
"_parse_docstring",
"(",
"self",
")",
":",
"if",
"self",
".",
"signature",
":",
"signature",
"=",
"self",
".",
"signature",
"body",
"=",
"self",
".",
"content",
"else",
":",
"if",
"(",
"self",
".",
"name",
"in",
"[",
"\"xdata\"",
",",
"\"xattr\"... | https://github.com/h2oai/datatable/blob/753197c3f76041dd6468e0f6a9708af92d80f6aa/docs/_ext/xfunction.py#L626-L656 | ||
kevinlin311tw/cvpr16-deepbit | c60fb3233d7d534cfcee9d3ed47d77af437ee32a | scripts/cpp_lint.py | python | CleanseRawStrings | (raw_lines) | return lines_without_raw_strings | Removes C++11 raw strings from lines.
Before:
static const char kData[] = R"(
multi-line string
)";
After:
static const char kData[] = ""
(replaced by blank line)
"";
Args:
raw_lines: list of raw lines.
Returns:
list of lines with C++11 raw strings replaced by empty strings. | Removes C++11 raw strings from lines. | [
"Removes",
"C",
"++",
"11",
"raw",
"strings",
"from",
"lines",
"."
] | def CleanseRawStrings(raw_lines):
"""Removes C++11 raw strings from lines.
Before:
static const char kData[] = R"(
multi-line string
)";
After:
static const char kData[] = ""
(replaced by blank line)
"";
Args:
raw_lines: list of raw lines.
Returns:
list of lines with C++11 raw strings replaced by empty strings.
"""
delimiter = None
lines_without_raw_strings = []
for line in raw_lines:
if delimiter:
# Inside a raw string, look for the end
end = line.find(delimiter)
if end >= 0:
# Found the end of the string, match leading space for this
# line and resume copying the original lines, and also insert
# a "" on the last line.
leading_space = Match(r'^(\s*)\S', line)
line = leading_space.group(1) + '""' + line[end + len(delimiter):]
delimiter = None
else:
# Haven't found the end yet, append a blank line.
line = ''
else:
# Look for beginning of a raw string.
# See 2.14.15 [lex.string] for syntax.
matched = Match(r'^(.*)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line)
if matched:
delimiter = ')' + matched.group(2) + '"'
end = matched.group(3).find(delimiter)
if end >= 0:
# Raw string ended on same line
line = (matched.group(1) + '""' +
matched.group(3)[end + len(delimiter):])
delimiter = None
else:
# Start of a multi-line raw string
line = matched.group(1) + '""'
lines_without_raw_strings.append(line)
# TODO(unknown): if delimiter is not None here, we might want to
# emit a warning for unterminated string.
return lines_without_raw_strings | [
"def",
"CleanseRawStrings",
"(",
"raw_lines",
")",
":",
"delimiter",
"=",
"None",
"lines_without_raw_strings",
"=",
"[",
"]",
"for",
"line",
"in",
"raw_lines",
":",
"if",
"delimiter",
":",
"# Inside a raw string, look for the end",
"end",
"=",
"line",
".",
"find",... | https://github.com/kevinlin311tw/cvpr16-deepbit/blob/c60fb3233d7d534cfcee9d3ed47d77af437ee32a/scripts/cpp_lint.py#L1062-L1120 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | third_party/python_gflags/gflags.py | python | DEFINE | (parser, name, default, help, flag_values=FLAGS, serializer=None,
**args) | Registers a generic Flag object.
NOTE: in the docstrings of all DEFINE* functions, "registers" is short
for "creates a new flag and registers it".
Auxiliary function: clients should use the specialized DEFINE_<type>
function instead.
Args:
parser: ArgumentParser that is used to parse the flag arguments.
name: A string, the flag name.
default: The default value of the flag.
help: A help string.
flag_values: FlagValues object the flag will be registered with.
serializer: ArgumentSerializer that serializes the flag value.
args: Dictionary with extra keyword args that are passes to the
Flag __init__. | Registers a generic Flag object. | [
"Registers",
"a",
"generic",
"Flag",
"object",
"."
] | def DEFINE(parser, name, default, help, flag_values=FLAGS, serializer=None,
**args):
"""Registers a generic Flag object.
NOTE: in the docstrings of all DEFINE* functions, "registers" is short
for "creates a new flag and registers it".
Auxiliary function: clients should use the specialized DEFINE_<type>
function instead.
Args:
parser: ArgumentParser that is used to parse the flag arguments.
name: A string, the flag name.
default: The default value of the flag.
help: A help string.
flag_values: FlagValues object the flag will be registered with.
serializer: ArgumentSerializer that serializes the flag value.
args: Dictionary with extra keyword args that are passes to the
Flag __init__.
"""
DEFINE_flag(Flag(parser, serializer, name, default, help, **args),
flag_values) | [
"def",
"DEFINE",
"(",
"parser",
",",
"name",
",",
"default",
",",
"help",
",",
"flag_values",
"=",
"FLAGS",
",",
"serializer",
"=",
"None",
",",
"*",
"*",
"args",
")",
":",
"DEFINE_flag",
"(",
"Flag",
"(",
"parser",
",",
"serializer",
",",
"name",
",... | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/python_gflags/gflags.py#L2154-L2175 | ||
CoolProp/CoolProp | 381c8535e5dec3eec27ad430ebbfff8bc9dfc008 | wrappers/Python/CoolProp/Plots/Plots.py | python | PropertyPlot.__init__ | (self, fluid_name, graph_type, **kwargs) | Create graph for the specified fluid properties
Parameters
----------
fluid_name : string or AbstractState
The name of the fluid to be plotted or a state instance
graph_type : string
The graph type to be plotted, like \"PH\" or \"TS\"
axis : :func:`matplotlib.pyplot.gca()`, Optional
The current axis system to be plotted to.
Default: create a new axis system
fig : :func:`matplotlib.pyplot.figure()`, Optional
The current figure to be plotted to.
Default: create a new figure
unit_system : string, ['EUR','KSI','SI']
Select the units used for the plotting. 'EUR' is bar, kJ, C; 'KSI' is kPa, kJ, K; 'SI' is Pa, J, K
tp_limits : string, ['NONE','DEF','ACHP','ORC']
Select the limits in T and p.
reciprocal_density : bool
NOT IMPLEMENTED: If True, 1/rho will be plotted instead of rho
Examples
--------
>>> from CoolProp.Plots import PropertyPlot
>>> plot = PropertyPlot('HEOS::Water', 'TS')
>>> plot.calc_isolines()
>>> plot.show()
>>> import CoolProp
>>> from CoolProp.Plots import PropertyPlot
>>> plot = PropertyPlot('HEOS::R134a', 'PH', unit_system='EUR', tp_limits='ACHP')
>>> plot.calc_isolines(CoolProp.iQ, num=11)
>>> plot.calc_isolines(CoolProp.iT, num=25)
>>> plot.calc_isolines(CoolProp.iSmass, num=15)
>>> plot.show()
>>> import CoolProp
>>> from CoolProp.Plots import PropertyPlot
>>> plot = PropertyPlot('HEOS::R245fa', 'TS', unit_system='EUR', tp_limits='ORC')
>>> plot.calc_isolines(CoolProp.iQ, num=11)
>>> plot.calc_isolines(CoolProp.iP, iso_range=[1,50], num=10, rounding=True)
>>> plot.draw()
>>> plot.isolines.clear()
>>> plot.props[CoolProp.iP]['color'] = 'green'
>>> plot.props[CoolProp.iP]['lw'] = '0.5'
>>> plot.calc_isolines(CoolProp.iP, iso_range=[1,50], num=10, rounding=False)
>>> plot.show()
.. note::
See the online documentation for a list of the available fluids and
graph types | Create graph for the specified fluid properties | [
"Create",
"graph",
"for",
"the",
"specified",
"fluid",
"properties"
] | def __init__(self, fluid_name, graph_type, **kwargs):
"""
Create graph for the specified fluid properties
Parameters
----------
fluid_name : string or AbstractState
The name of the fluid to be plotted or a state instance
graph_type : string
The graph type to be plotted, like \"PH\" or \"TS\"
axis : :func:`matplotlib.pyplot.gca()`, Optional
The current axis system to be plotted to.
Default: create a new axis system
fig : :func:`matplotlib.pyplot.figure()`, Optional
The current figure to be plotted to.
Default: create a new figure
unit_system : string, ['EUR','KSI','SI']
Select the units used for the plotting. 'EUR' is bar, kJ, C; 'KSI' is kPa, kJ, K; 'SI' is Pa, J, K
tp_limits : string, ['NONE','DEF','ACHP','ORC']
Select the limits in T and p.
reciprocal_density : bool
NOT IMPLEMENTED: If True, 1/rho will be plotted instead of rho
Examples
--------
>>> from CoolProp.Plots import PropertyPlot
>>> plot = PropertyPlot('HEOS::Water', 'TS')
>>> plot.calc_isolines()
>>> plot.show()
>>> import CoolProp
>>> from CoolProp.Plots import PropertyPlot
>>> plot = PropertyPlot('HEOS::R134a', 'PH', unit_system='EUR', tp_limits='ACHP')
>>> plot.calc_isolines(CoolProp.iQ, num=11)
>>> plot.calc_isolines(CoolProp.iT, num=25)
>>> plot.calc_isolines(CoolProp.iSmass, num=15)
>>> plot.show()
>>> import CoolProp
>>> from CoolProp.Plots import PropertyPlot
>>> plot = PropertyPlot('HEOS::R245fa', 'TS', unit_system='EUR', tp_limits='ORC')
>>> plot.calc_isolines(CoolProp.iQ, num=11)
>>> plot.calc_isolines(CoolProp.iP, iso_range=[1,50], num=10, rounding=True)
>>> plot.draw()
>>> plot.isolines.clear()
>>> plot.props[CoolProp.iP]['color'] = 'green'
>>> plot.props[CoolProp.iP]['lw'] = '0.5'
>>> plot.calc_isolines(CoolProp.iP, iso_range=[1,50], num=10, rounding=False)
>>> plot.show()
.. note::
See the online documentation for a list of the available fluids and
graph types
"""
super(PropertyPlot, self).__init__(fluid_name, graph_type, **kwargs)
self._isolines = {}
#self._plines = {}
#self._ppoints = {}
self.get_axis_limits()
self._plot_default_annotations() | [
"def",
"__init__",
"(",
"self",
",",
"fluid_name",
",",
"graph_type",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"PropertyPlot",
",",
"self",
")",
".",
"__init__",
"(",
"fluid_name",
",",
"graph_type",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
... | https://github.com/CoolProp/CoolProp/blob/381c8535e5dec3eec27ad430ebbfff8bc9dfc008/wrappers/Python/CoolProp/Plots/Plots.py#L13-L73 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py | python | LstParser.extractlstset | (self, reader) | Extract the global lstset parameters. | Extract the global lstset parameters. | [
"Extract",
"the",
"global",
"lstset",
"parameters",
"."
] | def extractlstset(self, reader):
"Extract the global lstset parameters."
paramtext = ''
while not reader.finished():
paramtext += reader.currentline()
reader.nextline()
if paramtext.endswith('}'):
return paramtext
Trace.error('Could not find end of \\lstset settings; aborting') | [
"def",
"extractlstset",
"(",
"self",
",",
"reader",
")",
":",
"paramtext",
"=",
"''",
"while",
"not",
"reader",
".",
"finished",
"(",
")",
":",
"paramtext",
"+=",
"reader",
".",
"currentline",
"(",
")",
"reader",
".",
"nextline",
"(",
")",
"if",
"param... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py#L5148-L5156 | ||
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | tools/pot/openvino/tools/pot/algorithms/quantization/fake_quantize.py | python | fill_fake_quantize_node | (fq, min_level, max_level, output_low=None, output_high=None) | Fills fake quantize input nodes with min/max values
:param fq: fake quantize node to fill
:param min_level: low border of quantization range
:param max_level: high border of quantization range | Fills fake quantize input nodes with min/max values
:param fq: fake quantize node to fill
:param min_level: low border of quantization range
:param max_level: high border of quantization range | [
"Fills",
"fake",
"quantize",
"input",
"nodes",
"with",
"min",
"/",
"max",
"values",
":",
"param",
"fq",
":",
"fake",
"quantize",
"node",
"to",
"fill",
":",
"param",
"min_level",
":",
"low",
"border",
"of",
"quantization",
"range",
":",
"param",
"max_level"... | def fill_fake_quantize_node(fq, min_level, max_level, output_low=None, output_high=None):
""" Fills fake quantize input nodes with min/max values
:param fq: fake quantize node to fill
:param min_level: low border of quantization range
:param max_level: high border of quantization range
"""
if output_low is None:
output_low = min_level
if output_high is None:
output_high = max_level
def _update_node_val(port_idx, value):
_node = get_node_input(fq, port_idx)
set_node_value(_node, value)
_update_node_val(1, min_level)
_update_node_val(2, max_level)
_update_node_val(3, output_low)
_update_node_val(4, output_high) | [
"def",
"fill_fake_quantize_node",
"(",
"fq",
",",
"min_level",
",",
"max_level",
",",
"output_low",
"=",
"None",
",",
"output_high",
"=",
"None",
")",
":",
"if",
"output_low",
"is",
"None",
":",
"output_low",
"=",
"min_level",
"if",
"output_high",
"is",
"Non... | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/pot/openvino/tools/pot/algorithms/quantization/fake_quantize.py#L87-L105 | ||
randyrossi/bmc64 | 862d2c6cc4b4e71b3a442f5d93f6a45f0ea48b00 | third_party/vice-3.3/src/lib/libx264/tools/digress/scm/dummy.py | python | checkout | (revision) | Checkout a revision. | Checkout a revision. | [
"Checkout",
"a",
"revision",
"."
] | def checkout(revision):
"""
Checkout a revision.
"""
pass | [
"def",
"checkout",
"(",
"revision",
")",
":",
"pass"
] | https://github.com/randyrossi/bmc64/blob/862d2c6cc4b4e71b3a442f5d93f6a45f0ea48b00/third_party/vice-3.3/src/lib/libx264/tools/digress/scm/dummy.py#L7-L11 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py | python | WhileContext.loop_exits | (self) | return self._loop_exits | The list of exit tensors for loop variables. | The list of exit tensors for loop variables. | [
"The",
"list",
"of",
"exit",
"tensors",
"for",
"loop",
"variables",
"."
] | def loop_exits(self):
"""The list of exit tensors for loop variables."""
return self._loop_exits | [
"def",
"loop_exits",
"(",
"self",
")",
":",
"return",
"self",
".",
"_loop_exits"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py#L1420-L1422 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/robotsim.py | python | RobotModel.loadFile | (self, fn) | return _robotsim.RobotModel_loadFile(self, fn) | loadFile(RobotModel self, char const * fn) -> bool
Loads the robot from the file fn. | loadFile(RobotModel self, char const * fn) -> bool | [
"loadFile",
"(",
"RobotModel",
"self",
"char",
"const",
"*",
"fn",
")",
"-",
">",
"bool"
] | def loadFile(self, fn):
"""
loadFile(RobotModel self, char const * fn) -> bool
Loads the robot from the file fn.
"""
return _robotsim.RobotModel_loadFile(self, fn) | [
"def",
"loadFile",
"(",
"self",
",",
"fn",
")",
":",
"return",
"_robotsim",
".",
"RobotModel_loadFile",
"(",
"self",
",",
"fn",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/robotsim.py#L4502-L4511 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/email/message.py | python | Message.items | (self) | return [(k, self.policy.header_fetch_parse(k, v))
for k, v in self._headers] | Get all the message's header fields and values.
These will be sorted in the order they appeared in the original
message, or were added to the message, and may contain duplicates.
Any fields deleted and re-inserted are always appended to the header
list. | Get all the message's header fields and values. | [
"Get",
"all",
"the",
"message",
"s",
"header",
"fields",
"and",
"values",
"."
] | def items(self):
"""Get all the message's header fields and values.
These will be sorted in the order they appeared in the original
message, or were added to the message, and may contain duplicates.
Any fields deleted and re-inserted are always appended to the header
list.
"""
return [(k, self.policy.header_fetch_parse(k, v))
for k, v in self._headers] | [
"def",
"items",
"(",
"self",
")",
":",
"return",
"[",
"(",
"k",
",",
"self",
".",
"policy",
".",
"header_fetch_parse",
"(",
"k",
",",
"v",
")",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_headers",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/email/message.py#L451-L460 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/src/robotsim.py | python | TerrainModel.geometry | (self) | return _robotsim.TerrainModel_geometry(self) | geometry(TerrainModel self) -> Geometry3D
Returns a reference to the geometry associated with this object. | geometry(TerrainModel self) -> Geometry3D | [
"geometry",
"(",
"TerrainModel",
"self",
")",
"-",
">",
"Geometry3D"
] | def geometry(self):
"""
geometry(TerrainModel self) -> Geometry3D
Returns a reference to the geometry associated with this object.
"""
return _robotsim.TerrainModel_geometry(self) | [
"def",
"geometry",
"(",
"self",
")",
":",
"return",
"_robotsim",
".",
"TerrainModel_geometry",
"(",
"self",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/src/robotsim.py#L5638-L5647 | |
chatopera/clause | dee31153d5ffdef33deedb6bff03e7806c296968 | var/assets/clients/gen-py/clause/Serving.py | python | Client.getIntents | (self, request) | return self.recv_getIntents() | Parameters:
- request | Parameters:
- request | [
"Parameters",
":",
"-",
"request"
] | def getIntents(self, request):
"""
Parameters:
- request
"""
self.send_getIntents(request)
return self.recv_getIntents() | [
"def",
"getIntents",
"(",
"self",
",",
"request",
")",
":",
"self",
".",
"send_getIntents",
"(",
"request",
")",
"return",
"self",
".",
"recv_getIntents",
"(",
")"
] | https://github.com/chatopera/clause/blob/dee31153d5ffdef33deedb6bff03e7806c296968/var/assets/clients/gen-py/clause/Serving.py#L992-L999 | |
vnpy/vnpy | f50f2535ed39dd33272e0985ed40c7078e4c19f6 | vnpy/trader/utility.py | python | BarGenerator.update_tick | (self, tick: TickData) | Update new tick data into generator. | Update new tick data into generator. | [
"Update",
"new",
"tick",
"data",
"into",
"generator",
"."
] | def update_tick(self, tick: TickData) -> None:
"""
Update new tick data into generator.
"""
new_minute = False
# Filter tick data with 0 last price
if not tick.last_price:
return
# Filter tick data with older timestamp
if self.last_tick and tick.datetime < self.last_tick.datetime:
return
if not self.bar:
new_minute = True
elif (
(self.bar.datetime.minute != tick.datetime.minute)
or (self.bar.datetime.hour != tick.datetime.hour)
):
self.bar.datetime = self.bar.datetime.replace(
second=0, microsecond=0
)
self.on_bar(self.bar)
new_minute = True
if new_minute:
self.bar = BarData(
symbol=tick.symbol,
exchange=tick.exchange,
interval=Interval.MINUTE,
datetime=tick.datetime,
gateway_name=tick.gateway_name,
open_price=tick.last_price,
high_price=tick.last_price,
low_price=tick.last_price,
close_price=tick.last_price,
open_interest=tick.open_interest
)
else:
self.bar.high_price = max(self.bar.high_price, tick.last_price)
if tick.high_price > self.last_tick.high_price:
self.bar.high_price = max(self.bar.high_price, tick.high_price)
self.bar.low_price = min(self.bar.low_price, tick.last_price)
if tick.low_price < self.last_tick.low_price:
self.bar.low_price = min(self.bar.low_price, tick.low_price)
self.bar.close_price = tick.last_price
self.bar.open_interest = tick.open_interest
self.bar.datetime = tick.datetime
if self.last_tick:
volume_change = tick.volume - self.last_tick.volume
self.bar.volume += max(volume_change, 0)
turnover_change = tick.turnover - self.last_tick.turnover
self.bar.turnover += max(turnover_change, 0)
self.last_tick = tick | [
"def",
"update_tick",
"(",
"self",
",",
"tick",
":",
"TickData",
")",
"->",
"None",
":",
"new_minute",
"=",
"False",
"# Filter tick data with 0 last price",
"if",
"not",
"tick",
".",
"last_price",
":",
"return",
"# Filter tick data with older timestamp",
"if",
"self... | https://github.com/vnpy/vnpy/blob/f50f2535ed39dd33272e0985ed40c7078e4c19f6/vnpy/trader/utility.py#L199-L259 | ||
root-project/root | fcd3583bb14852bf2e8cd2415717cbaac0e75896 | interpreter/llvm/src/tools/clang/tools/scan-build-py/libscanbuild/arguments.py | python | create_analyze_parser | (from_build_command) | return parser | Creates a parser for command-line arguments to 'analyze'. | Creates a parser for command-line arguments to 'analyze'. | [
"Creates",
"a",
"parser",
"for",
"command",
"-",
"line",
"arguments",
"to",
"analyze",
"."
] | def create_analyze_parser(from_build_command):
""" Creates a parser for command-line arguments to 'analyze'. """
parser = create_default_parser()
if from_build_command:
parser_add_prefer_wrapper(parser)
parser_add_compilers(parser)
parser.add_argument(
'--intercept-first',
action='store_true',
help="""Run the build commands first, intercept compiler
calls and then run the static analyzer afterwards.
Generally speaking it has better coverage on build commands.
With '--override-compiler' it use compiler wrapper, but does
not run the analyzer till the build is finished.""")
else:
parser_add_cdb(parser)
parser.add_argument(
'--status-bugs',
action='store_true',
help="""The exit status of '%(prog)s' is the same as the executed
build command. This option ignores the build exit status and sets to
be non zero if it found potential bugs or zero otherwise.""")
parser.add_argument(
'--exclude',
metavar='<directory>',
dest='excludes',
action='append',
default=[],
help="""Do not run static analyzer against files found in this
directory. (You can specify this option multiple times.)
Could be useful when project contains 3rd party libraries.""")
output = parser.add_argument_group('output control options')
output.add_argument(
'--output',
'-o',
metavar='<path>',
default=tempfile.gettempdir(),
help="""Specifies the output directory for analyzer reports.
Subdirectory will be created if default directory is targeted.""")
output.add_argument(
'--keep-empty',
action='store_true',
help="""Don't remove the build results directory even if no issues
were reported.""")
output.add_argument(
'--html-title',
metavar='<title>',
help="""Specify the title used on generated HTML pages.
If not specified, a default title will be used.""")
format_group = output.add_mutually_exclusive_group()
format_group.add_argument(
'--plist',
'-plist',
dest='output_format',
const='plist',
default='html',
action='store_const',
help="""Cause the results as a set of .plist files.""")
format_group.add_argument(
'--plist-html',
'-plist-html',
dest='output_format',
const='plist-html',
default='html',
action='store_const',
help="""Cause the results as a set of .html and .plist files.""")
format_group.add_argument(
'--plist-multi-file',
'-plist-multi-file',
dest='output_format',
const='plist-multi-file',
default='html',
action='store_const',
help="""Cause the results as a set of .plist files with extra
information on related files.""")
advanced = parser.add_argument_group('advanced options')
advanced.add_argument(
'--use-analyzer',
metavar='<path>',
dest='clang',
default='clang',
help="""'%(prog)s' uses the 'clang' executable relative to itself for
static analysis. One can override this behavior with this option by
using the 'clang' packaged with Xcode (on OS X) or from the PATH.""")
advanced.add_argument(
'--no-failure-reports',
'-no-failure-reports',
dest='output_failures',
action='store_false',
help="""Do not create a 'failures' subdirectory that includes analyzer
crash reports and preprocessed source files.""")
parser.add_argument(
'--analyze-headers',
action='store_true',
help="""Also analyze functions in #included files. By default, such
functions are skipped unless they are called by functions within the
main source file.""")
advanced.add_argument(
'--stats',
'-stats',
action='store_true',
help="""Generates visitation statistics for the project.""")
advanced.add_argument(
'--internal-stats',
action='store_true',
help="""Generate internal analyzer statistics.""")
advanced.add_argument(
'--maxloop',
'-maxloop',
metavar='<loop count>',
type=int,
help="""Specify the number of times a block can be visited before
giving up. Increase for more comprehensive coverage at a cost of
speed.""")
advanced.add_argument(
'--store',
'-store',
metavar='<model>',
dest='store_model',
choices=['region', 'basic'],
help="""Specify the store model used by the analyzer. 'region'
specifies a field- sensitive store model. 'basic' which is far less
precise but can more quickly analyze code. 'basic' was the default
store model for checker-0.221 and earlier.""")
advanced.add_argument(
'--constraints',
'-constraints',
metavar='<model>',
dest='constraints_model',
choices=['range', 'basic'],
help="""Specify the constraint engine used by the analyzer. Specifying
'basic' uses a simpler, less powerful constraint model used by
checker-0.160 and earlier.""")
advanced.add_argument(
'--analyzer-config',
'-analyzer-config',
metavar='<options>',
help="""Provide options to pass through to the analyzer's
-analyzer-config flag. Several options are separated with comma:
'key1=val1,key2=val2'
Available options:
stable-report-filename=true or false (default)
Switch the page naming to:
report-<filename>-<function/method name>-<id>.html
instead of report-XXXXXX.html""")
advanced.add_argument(
'--force-analyze-debug-code',
dest='force_debug',
action='store_true',
help="""Tells analyzer to enable assertions in code even if they were
disabled during compilation, enabling more precise results.""")
plugins = parser.add_argument_group('checker options')
plugins.add_argument(
'--load-plugin',
'-load-plugin',
metavar='<plugin library>',
dest='plugins',
action='append',
help="""Loading external checkers using the clang plugin interface.""")
plugins.add_argument(
'--enable-checker',
'-enable-checker',
metavar='<checker name>',
action=AppendCommaSeparated,
help="""Enable specific checker.""")
plugins.add_argument(
'--disable-checker',
'-disable-checker',
metavar='<checker name>',
action=AppendCommaSeparated,
help="""Disable specific checker.""")
plugins.add_argument(
'--help-checkers',
action='store_true',
help="""A default group of checkers is run unless explicitly disabled.
Exactly which checkers constitute the default group is a function of
the operating system in use. These can be printed with this flag.""")
plugins.add_argument(
'--help-checkers-verbose',
action='store_true',
help="""Print all available checkers and mark the enabled ones.""")
if from_build_command:
parser.add_argument(
dest='build', nargs=argparse.REMAINDER, help="""Command to run.""")
else:
ctu = parser.add_argument_group('cross translation unit analysis')
ctu_mutex_group = ctu.add_mutually_exclusive_group()
ctu_mutex_group.add_argument(
'--ctu',
action='store_const',
const=CtuConfig(collect=True, analyze=True,
dir='', extdef_map_cmd=''),
dest='ctu_phases',
help="""Perform cross translation unit (ctu) analysis (both collect
and analyze phases) using default <ctu-dir> for temporary output.
At the end of the analysis, the temporary directory is removed.""")
ctu.add_argument(
'--ctu-dir',
metavar='<ctu-dir>',
dest='ctu_dir',
default='ctu-dir',
help="""Defines the temporary directory used between ctu
phases.""")
ctu_mutex_group.add_argument(
'--ctu-collect-only',
action='store_const',
const=CtuConfig(collect=True, analyze=False,
dir='', extdef_map_cmd=''),
dest='ctu_phases',
help="""Perform only the collect phase of ctu.
Keep <ctu-dir> for further use.""")
ctu_mutex_group.add_argument(
'--ctu-analyze-only',
action='store_const',
const=CtuConfig(collect=False, analyze=True,
dir='', extdef_map_cmd=''),
dest='ctu_phases',
help="""Perform only the analyze phase of ctu. <ctu-dir> should be
present and will not be removed after analysis.""")
ctu.add_argument(
'--use-extdef-map-cmd',
metavar='<path>',
dest='extdef_map_cmd',
default='clang-extdef-mapping',
help="""'%(prog)s' uses the 'clang-extdef-mapping' executable
relative to itself for generating external definition maps for
static analysis. One can override this behavior with this option
by using the 'clang-extdef-mapping' packaged with Xcode (on OS X)
or from the PATH.""")
return parser | [
"def",
"create_analyze_parser",
"(",
"from_build_command",
")",
":",
"parser",
"=",
"create_default_parser",
"(",
")",
"if",
"from_build_command",
":",
"parser_add_prefer_wrapper",
"(",
"parser",
")",
"parser_add_compilers",
"(",
"parser",
")",
"parser",
".",
"add_arg... | https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/interpreter/llvm/src/tools/clang/tools/scan-build-py/libscanbuild/arguments.py#L167-L406 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/calendar.py | python | CalendarDateAttr.__init__ | (self, *args, **kwargs) | __init__(self, Colour colText=wxNullColour, Colour colBack=wxNullColour,
Colour colBorder=wxNullColour, Font font=wxNullFont,
int border=CAL_BORDER_NONE) -> CalendarDateAttr
Create a CalendarDateAttr. | __init__(self, Colour colText=wxNullColour, Colour colBack=wxNullColour,
Colour colBorder=wxNullColour, Font font=wxNullFont,
int border=CAL_BORDER_NONE) -> CalendarDateAttr | [
"__init__",
"(",
"self",
"Colour",
"colText",
"=",
"wxNullColour",
"Colour",
"colBack",
"=",
"wxNullColour",
"Colour",
"colBorder",
"=",
"wxNullColour",
"Font",
"font",
"=",
"wxNullFont",
"int",
"border",
"=",
"CAL_BORDER_NONE",
")",
"-",
">",
"CalendarDateAttr"
] | def __init__(self, *args, **kwargs):
"""
__init__(self, Colour colText=wxNullColour, Colour colBack=wxNullColour,
Colour colBorder=wxNullColour, Font font=wxNullFont,
int border=CAL_BORDER_NONE) -> CalendarDateAttr
Create a CalendarDateAttr.
"""
_calendar.CalendarDateAttr_swiginit(self,_calendar.new_CalendarDateAttr(*args, **kwargs)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_calendar",
".",
"CalendarDateAttr_swiginit",
"(",
"self",
",",
"_calendar",
".",
"new_CalendarDateAttr",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/calendar.py#L87-L95 | ||
dmlc/xgboost | 2775c2a1abd4b5b759ff517617434c8b9aeb4cc0 | python-package/xgboost/core.py | python | DMatrix.get_uint_info | (self, field: str) | return ctypes2numpy(ret, length.value, np.uint32) | Get unsigned integer property from the DMatrix.
Parameters
----------
field: str
The field name of the information
Returns
-------
info : array
a numpy array of unsigned integer information of the data | Get unsigned integer property from the DMatrix. | [
"Get",
"unsigned",
"integer",
"property",
"from",
"the",
"DMatrix",
"."
] | def get_uint_info(self, field: str) -> np.ndarray:
"""Get unsigned integer property from the DMatrix.
Parameters
----------
field: str
The field name of the information
Returns
-------
info : array
a numpy array of unsigned integer information of the data
"""
length = c_bst_ulong()
ret = ctypes.POINTER(ctypes.c_uint)()
_check_call(_LIB.XGDMatrixGetUIntInfo(self.handle,
c_str(field),
ctypes.byref(length),
ctypes.byref(ret)))
return ctypes2numpy(ret, length.value, np.uint32) | [
"def",
"get_uint_info",
"(",
"self",
",",
"field",
":",
"str",
")",
"->",
"np",
".",
"ndarray",
":",
"length",
"=",
"c_bst_ulong",
"(",
")",
"ret",
"=",
"ctypes",
".",
"POINTER",
"(",
"ctypes",
".",
"c_uint",
")",
"(",
")",
"_check_call",
"(",
"_LIB"... | https://github.com/dmlc/xgboost/blob/2775c2a1abd4b5b759ff517617434c8b9aeb4cc0/python-package/xgboost/core.py#L729-L748 | |
Kitware/ParaView | f760af9124ff4634b23ebbeab95a4f56e0261955 | Plugins/pvblot/tplot.py | python | TPlot.get_curves_with_variable_type | (self, var_type) | return [c for c in self._curves if c.var.type == var_type] | Given a variable type (NODE_VARIABLE, ELEMENT_VARIABLE, GLOBAL_VARIABLE)
return all the curves for variables of the given type. | Given a variable type (NODE_VARIABLE, ELEMENT_VARIABLE, GLOBAL_VARIABLE)
return all the curves for variables of the given type. | [
"Given",
"a",
"variable",
"type",
"(",
"NODE_VARIABLE",
"ELEMENT_VARIABLE",
"GLOBAL_VARIABLE",
")",
"return",
"all",
"the",
"curves",
"for",
"variables",
"of",
"the",
"given",
"type",
"."
] | def get_curves_with_variable_type(self, var_type):
"""Given a variable type (NODE_VARIABLE, ELEMENT_VARIABLE, GLOBAL_VARIABLE)
return all the curves for variables of the given type."""
return [c for c in self._curves if c.var.type == var_type] | [
"def",
"get_curves_with_variable_type",
"(",
"self",
",",
"var_type",
")",
":",
"return",
"[",
"c",
"for",
"c",
"in",
"self",
".",
"_curves",
"if",
"c",
".",
"var",
".",
"type",
"==",
"var_type",
"]"
] | https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/Plugins/pvblot/tplot.py#L267-L270 | |
Slicer/Slicer | ba9fadf332cb0303515b68d8d06a344c82e3e3e5 | Modules/Scripted/DICOMPlugins/DICOMScalarVolumePlugin.py | python | DICOMScalarVolumePluginClass.loadFilesWithSeriesReader | (self,imageIOName,files,name,grayscale=True) | return(volumeNode) | Explicitly use the named imageIO to perform the loading | Explicitly use the named imageIO to perform the loading | [
"Explicitly",
"use",
"the",
"named",
"imageIO",
"to",
"perform",
"the",
"loading"
] | def loadFilesWithSeriesReader(self,imageIOName,files,name,grayscale=True):
""" Explicitly use the named imageIO to perform the loading
"""
if grayscale:
reader = vtkITK.vtkITKArchetypeImageSeriesScalarReader()
else:
reader = vtkITK.vtkITKArchetypeImageSeriesVectorReaderFile()
reader.SetArchetype(files[0])
for f in files:
reader.AddFileName(f)
reader.SetSingleFile(0)
reader.SetOutputScalarTypeToNative()
reader.SetDesiredCoordinateOrientationToNative()
reader.SetUseNativeOriginOn()
if imageIOName == "GDCM":
reader.SetDICOMImageIOApproachToGDCM()
elif imageIOName == "DCMTK":
reader.SetDICOMImageIOApproachToDCMTK()
else:
raise Exception("Invalid imageIOName of %s" % imageIOName)
logging.info("Loading with imageIOName: %s" % imageIOName)
reader.Update()
slicer.modules.reader = reader
if reader.GetErrorCode() != vtk.vtkErrorCode.NoError:
errorStrings = (imageIOName, vtk.vtkErrorCode.GetStringFromErrorCode(reader.GetErrorCode()))
logging.error("Could not read scalar volume using %s approach. Error is: %s" % errorStrings)
return
imageChangeInformation = vtk.vtkImageChangeInformation()
imageChangeInformation.SetInputConnection(reader.GetOutputPort())
imageChangeInformation.SetOutputSpacing( 1, 1, 1 )
imageChangeInformation.SetOutputOrigin( 0, 0, 0 )
imageChangeInformation.Update()
name = slicer.mrmlScene.GenerateUniqueName(name)
if grayscale:
volumeNode = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLScalarVolumeNode", name)
else:
volumeNode = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLVectorVolumeNode", name)
volumeNode.SetAndObserveImageData(imageChangeInformation.GetOutputDataObject(0))
slicer.vtkMRMLVolumeArchetypeStorageNode.SetMetaDataDictionaryFromReader(volumeNode, reader)
volumeNode.SetRASToIJKMatrix(reader.GetRasToIjkMatrix())
volumeNode.CreateDefaultDisplayNodes()
slicer.modules.DICOMInstance.reader = reader
slicer.modules.DICOMInstance.imageChangeInformation = imageChangeInformation
return(volumeNode) | [
"def",
"loadFilesWithSeriesReader",
"(",
"self",
",",
"imageIOName",
",",
"files",
",",
"name",
",",
"grayscale",
"=",
"True",
")",
":",
"if",
"grayscale",
":",
"reader",
"=",
"vtkITK",
".",
"vtkITKArchetypeImageSeriesScalarReader",
"(",
")",
"else",
":",
"rea... | https://github.com/Slicer/Slicer/blob/ba9fadf332cb0303515b68d8d06a344c82e3e3e5/Modules/Scripted/DICOMPlugins/DICOMScalarVolumePlugin.py#L363-L412 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBLaunchInfo.SetDetachOnError | (self, *args) | return _lldb.SBLaunchInfo_SetDetachOnError(self, *args) | SetDetachOnError(self, bool enable) | SetDetachOnError(self, bool enable) | [
"SetDetachOnError",
"(",
"self",
"bool",
"enable",
")"
] | def SetDetachOnError(self, *args):
"""SetDetachOnError(self, bool enable)"""
return _lldb.SBLaunchInfo_SetDetachOnError(self, *args) | [
"def",
"SetDetachOnError",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_lldb",
".",
"SBLaunchInfo_SetDetachOnError",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L5569-L5571 | |
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/tools/inspector_protocol/jinja2/filters.py | python | do_groupby | (environment, value, attribute) | return [_GroupTuple(key, list(values)) for key, values
in groupby(sorted(value, key=expr), expr)] | Group a sequence of objects by a common attribute.
If you for example have a list of dicts or objects that represent persons
with `gender`, `first_name` and `last_name` attributes and you want to
group all users by genders you can do something like the following
snippet:
.. sourcecode:: html+jinja
<ul>
{% for group in persons|groupby('gender') %}
<li>{{ group.grouper }}<ul>
{% for person in group.list %}
<li>{{ person.first_name }} {{ person.last_name }}</li>
{% endfor %}</ul></li>
{% endfor %}
</ul>
Additionally it's possible to use tuple unpacking for the grouper and
list:
.. sourcecode:: html+jinja
<ul>
{% for grouper, list in persons|groupby('gender') %}
...
{% endfor %}
</ul>
As you can see the item we're grouping by is stored in the `grouper`
attribute and the `list` contains all the objects that have this grouper
in common.
.. versionchanged:: 2.6
It's now possible to use dotted notation to group by the child
attribute of another attribute. | Group a sequence of objects by a common attribute. | [
"Group",
"a",
"sequence",
"of",
"objects",
"by",
"a",
"common",
"attribute",
"."
] | def do_groupby(environment, value, attribute):
"""Group a sequence of objects by a common attribute.
If you for example have a list of dicts or objects that represent persons
with `gender`, `first_name` and `last_name` attributes and you want to
group all users by genders you can do something like the following
snippet:
.. sourcecode:: html+jinja
<ul>
{% for group in persons|groupby('gender') %}
<li>{{ group.grouper }}<ul>
{% for person in group.list %}
<li>{{ person.first_name }} {{ person.last_name }}</li>
{% endfor %}</ul></li>
{% endfor %}
</ul>
Additionally it's possible to use tuple unpacking for the grouper and
list:
.. sourcecode:: html+jinja
<ul>
{% for grouper, list in persons|groupby('gender') %}
...
{% endfor %}
</ul>
As you can see the item we're grouping by is stored in the `grouper`
attribute and the `list` contains all the objects that have this grouper
in common.
.. versionchanged:: 2.6
It's now possible to use dotted notation to group by the child
attribute of another attribute.
"""
expr = make_attrgetter(environment, attribute)
return [_GroupTuple(key, list(values)) for key, values
in groupby(sorted(value, key=expr), expr)] | [
"def",
"do_groupby",
"(",
"environment",
",",
"value",
",",
"attribute",
")",
":",
"expr",
"=",
"make_attrgetter",
"(",
"environment",
",",
"attribute",
")",
"return",
"[",
"_GroupTuple",
"(",
"key",
",",
"list",
"(",
"values",
")",
")",
"for",
"key",
",... | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/inspector_protocol/jinja2/filters.py#L812-L852 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/idlelib/replace.py | python | ReplaceDialog.create_command_buttons | (self) | Create base and additional command buttons.
The additional buttons are for Find, Replace,
Replace+Find, and Replace All. | Create base and additional command buttons. | [
"Create",
"base",
"and",
"additional",
"command",
"buttons",
"."
] | def create_command_buttons(self):
"""Create base and additional command buttons.
The additional buttons are for Find, Replace,
Replace+Find, and Replace All.
"""
SearchDialogBase.create_command_buttons(self)
self.make_button("Find", self.find_it)
self.make_button("Replace", self.replace_it)
self.make_button("Replace+Find", self.default_command, isdef=True)
self.make_button("Replace All", self.replace_all) | [
"def",
"create_command_buttons",
"(",
"self",
")",
":",
"SearchDialogBase",
".",
"create_command_buttons",
"(",
"self",
")",
"self",
".",
"make_button",
"(",
"\"Find\"",
",",
"self",
".",
"find_it",
")",
"self",
".",
"make_button",
"(",
"\"Replace\"",
",",
"se... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/idlelib/replace.py#L81-L91 | ||
omnisci/omniscidb | b9c95f1bd602b4ffc8b0edf18bfad61031e08d86 | python/omnisci/thrift/OmniSci.py | python | Client.interrupt | (self, query_session, interrupt_session) | Parameters:
- query_session
- interrupt_session | Parameters:
- query_session
- interrupt_session | [
"Parameters",
":",
"-",
"query_session",
"-",
"interrupt_session"
] | def interrupt(self, query_session, interrupt_session):
"""
Parameters:
- query_session
- interrupt_session
"""
self.send_interrupt(query_session, interrupt_session)
self.recv_interrupt() | [
"def",
"interrupt",
"(",
"self",
",",
"query_session",
",",
"interrupt_session",
")",
":",
"self",
".",
"send_interrupt",
"(",
"query_session",
",",
"interrupt_session",
")",
"self",
".",
"recv_interrupt",
"(",
")"
] | https://github.com/omnisci/omniscidb/blob/b9c95f1bd602b4ffc8b0edf18bfad61031e08d86/python/omnisci/thrift/OmniSci.py#L2333-L2341 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/distutils/archive_util.py | python | _get_gid | (name) | return None | Returns a gid, given a group name. | Returns a gid, given a group name. | [
"Returns",
"a",
"gid",
"given",
"a",
"group",
"name",
"."
] | def _get_gid(name):
"""Returns a gid, given a group name."""
if getgrnam is None or name is None:
return None
try:
result = getgrnam(name)
except KeyError:
result = None
if result is not None:
return result[2]
return None | [
"def",
"_get_gid",
"(",
"name",
")",
":",
"if",
"getgrnam",
"is",
"None",
"or",
"name",
"is",
"None",
":",
"return",
"None",
"try",
":",
"result",
"=",
"getgrnam",
"(",
"name",
")",
"except",
"KeyError",
":",
"result",
"=",
"None",
"if",
"result",
"i... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/distutils/archive_util.py#L27-L37 | |
vmware/concord-bft | ec036a384b4c81be0423d4b429bd37900b13b864 | util/pyclient/bft_client.py | python | TcpTlsClient.__exit__ | (self, *args) | Context manager method for 'with' statements | Context manager method for 'with' statements | [
"Context",
"manager",
"method",
"for",
"with",
"statements"
] | def __exit__(self, *args):
""" Context manager method for 'with' statements """
self.exit_flag = True
for lot in self.establish_ssl_stream_parklot.values():
lot.unpark() | [
"def",
"__exit__",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"exit_flag",
"=",
"True",
"for",
"lot",
"in",
"self",
".",
"establish_ssl_stream_parklot",
".",
"values",
"(",
")",
":",
"lot",
".",
"unpark",
"(",
")"
] | https://github.com/vmware/concord-bft/blob/ec036a384b4c81be0423d4b429bd37900b13b864/util/pyclient/bft_client.py#L621-L625 | ||
Samsung/veles | 95ed733c2e49bc011ad98ccf2416ecec23fbf352 | veles/external/daemon/daemon.py | python | is_detach_process_context_required | () | return result | Determine whether detaching process context is required.
Return ``True`` if the process environment indicates the
process is already detached:
* Process was started by `init`; or
* Process was started by `inetd`. | Determine whether detaching process context is required. | [
"Determine",
"whether",
"detaching",
"process",
"context",
"is",
"required",
"."
] | def is_detach_process_context_required():
""" Determine whether detaching process context is required.
Return ``True`` if the process environment indicates the
process is already detached:
* Process was started by `init`; or
* Process was started by `inetd`.
"""
result = True
if is_process_started_by_init() or is_process_started_by_superserver():
result = False
return result | [
"def",
"is_detach_process_context_required",
"(",
")",
":",
"result",
"=",
"True",
"if",
"is_process_started_by_init",
"(",
")",
"or",
"is_process_started_by_superserver",
"(",
")",
":",
"result",
"=",
"False",
"return",
"result"
] | https://github.com/Samsung/veles/blob/95ed733c2e49bc011ad98ccf2416ecec23fbf352/veles/external/daemon/daemon.py#L678-L693 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/richtext.py | python | TextBoxAttr.RemoveStyle | (*args, **kwargs) | return _richtext.TextBoxAttr_RemoveStyle(*args, **kwargs) | RemoveStyle(self, TextBoxAttr attr) -> bool | RemoveStyle(self, TextBoxAttr attr) -> bool | [
"RemoveStyle",
"(",
"self",
"TextBoxAttr",
"attr",
")",
"-",
">",
"bool"
] | def RemoveStyle(*args, **kwargs):
"""RemoveStyle(self, TextBoxAttr attr) -> bool"""
return _richtext.TextBoxAttr_RemoveStyle(*args, **kwargs) | [
"def",
"RemoveStyle",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"TextBoxAttr_RemoveStyle",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/richtext.py#L552-L554 | |
junhyukoh/caffe-lstm | 598d45456fa2a1b127a644f4aa38daa8fb9fc722 | scripts/cpp_lint.py | python | _CppLintState.ResetErrorCounts | (self) | Sets the module's error statistic back to zero. | Sets the module's error statistic back to zero. | [
"Sets",
"the",
"module",
"s",
"error",
"statistic",
"back",
"to",
"zero",
"."
] | def ResetErrorCounts(self):
"""Sets the module's error statistic back to zero."""
self.error_count = 0
self.errors_by_category = {} | [
"def",
"ResetErrorCounts",
"(",
"self",
")",
":",
"self",
".",
"error_count",
"=",
"0",
"self",
".",
"errors_by_category",
"=",
"{",
"}"
] | https://github.com/junhyukoh/caffe-lstm/blob/598d45456fa2a1b127a644f4aa38daa8fb9fc722/scripts/cpp_lint.py#L742-L745 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/ftplib.py | python | FTP.makeport | (self) | return sock | Create a new socket and send a PORT command for it. | Create a new socket and send a PORT command for it. | [
"Create",
"a",
"new",
"socket",
"and",
"send",
"a",
"PORT",
"command",
"for",
"it",
"."
] | def makeport(self):
'''Create a new socket and send a PORT command for it.'''
err = None
sock = None
for res in socket.getaddrinfo(None, 0, self.af, socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
af, socktype, proto, canonname, sa = res
try:
sock = socket.socket(af, socktype, proto)
sock.bind(sa)
except OSError as _:
err = _
if sock:
sock.close()
sock = None
continue
break
if sock is None:
if err is not None:
raise err
else:
raise OSError("getaddrinfo returns an empty list")
sock.listen(1)
port = sock.getsockname()[1] # Get proper port
host = self.sock.getsockname()[0] # Get proper host
if self.af == socket.AF_INET:
resp = self.sendport(host, port)
else:
resp = self.sendeprt(host, port)
if self.timeout is not _GLOBAL_DEFAULT_TIMEOUT:
sock.settimeout(self.timeout)
return sock | [
"def",
"makeport",
"(",
"self",
")",
":",
"err",
"=",
"None",
"sock",
"=",
"None",
"for",
"res",
"in",
"socket",
".",
"getaddrinfo",
"(",
"None",
",",
"0",
",",
"self",
".",
"af",
",",
"socket",
".",
"SOCK_STREAM",
",",
"0",
",",
"socket",
".",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/ftplib.py#L303-L333 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/_op_impl/aicpu/gather.py | python | _gather_aicpu | () | return | GatherD AiCPU register | GatherD AiCPU register | [
"GatherD",
"AiCPU",
"register"
] | def _gather_aicpu():
"""GatherD AiCPU register"""
return | [
"def",
"_gather_aicpu",
"(",
")",
":",
"return"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/aicpu/gather.py#L76-L78 | |
xiaolonw/caffe-video_triplet | c39ea1ad6e937ccf7deba4510b7e555165abf05f | scripts/cpp_lint.py | python | CheckCaffeDataLayerSetUp | (filename, clean_lines, linenum, error) | Except the base classes, Caffe DataLayer should define DataLayerSetUp
instead of LayerSetUp.
The base DataLayers define common SetUp steps, the subclasses should
not override them.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Except the base classes, Caffe DataLayer should define DataLayerSetUp
instead of LayerSetUp.
The base DataLayers define common SetUp steps, the subclasses should
not override them.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | [
"Except",
"the",
"base",
"classes",
"Caffe",
"DataLayer",
"should",
"define",
"DataLayerSetUp",
"instead",
"of",
"LayerSetUp",
".",
"The",
"base",
"DataLayers",
"define",
"common",
"SetUp",
"steps",
"the",
"subclasses",
"should",
"not",
"override",
"them",
".",
... | def CheckCaffeDataLayerSetUp(filename, clean_lines, linenum, error):
"""Except the base classes, Caffe DataLayer should define DataLayerSetUp
instead of LayerSetUp.
The base DataLayers define common SetUp steps, the subclasses should
not override them.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
ix = line.find('DataLayer<Dtype>::LayerSetUp')
if ix >= 0 and (
line.find('void DataLayer<Dtype>::LayerSetUp') != -1 or
line.find('void ImageDataLayer<Dtype>::LayerSetUp') != -1 or
line.find('void MemoryDataLayer<Dtype>::LayerSetUp') != -1 or
line.find('void WindowDataLayer<Dtype>::LayerSetUp') != -1):
error(filename, linenum, 'caffe/data_layer_setup', 2,
'Except the base classes, Caffe DataLayer should define'
+ ' DataLayerSetUp instead of LayerSetUp. The base DataLayers'
+ ' define common SetUp steps, the subclasses should'
+ ' not override them.')
ix = line.find('DataLayer<Dtype>::DataLayerSetUp')
if ix >= 0 and (
line.find('void Base') == -1 and
line.find('void DataLayer<Dtype>::DataLayerSetUp') == -1 and
line.find('void ImageDataLayer<Dtype>::DataLayerSetUp') == -1 and
line.find('void MemoryDataLayer<Dtype>::DataLayerSetUp') == -1 and
line.find('void WindowDataLayer<Dtype>::DataLayerSetUp') == -1):
error(filename, linenum, 'caffe/data_layer_setup', 2,
'Except the base classes, Caffe DataLayer should define'
+ ' DataLayerSetUp instead of LayerSetUp. The base DataLayers'
+ ' define common SetUp steps, the subclasses should'
+ ' not override them.') | [
"def",
"CheckCaffeDataLayerSetUp",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"ix",
"=",
"line",
".",
"find",
"(",
"'DataLayer<Dtype>::LayerSetUp'",
")",
"if",
... | https://github.com/xiaolonw/caffe-video_triplet/blob/c39ea1ad6e937ccf7deba4510b7e555165abf05f/scripts/cpp_lint.py#L1595-L1631 | ||
BitMEX/api-connectors | 37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812 | auto-generated/python/swagger_client/api/order_api.py | python | OrderApi.order_close_position | (self, symbol, **kwargs) | Close a position. [Deprecated, use POST /order with execInst: 'Close'] # noqa: E501
If no `price` is specified, a market order will be submitted to close the whole of your position. This will also close all other open orders in this symbol. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.order_close_position(symbol, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str symbol: Symbol of position to close. (required)
:param float price: Optional limit price.
:return: Order
If the method is called asynchronously,
returns the request thread. | Close a position. [Deprecated, use POST /order with execInst: 'Close'] # noqa: E501 | [
"Close",
"a",
"position",
".",
"[",
"Deprecated",
"use",
"POST",
"/",
"order",
"with",
"execInst",
":",
"Close",
"]",
"#",
"noqa",
":",
"E501"
] | def order_close_position(self, symbol, **kwargs): # noqa: E501
"""Close a position. [Deprecated, use POST /order with execInst: 'Close'] # noqa: E501
If no `price` is specified, a market order will be submitted to close the whole of your position. This will also close all other open orders in this symbol. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.order_close_position(symbol, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str symbol: Symbol of position to close. (required)
:param float price: Optional limit price.
:return: Order
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.order_close_position_with_http_info(symbol, **kwargs) # noqa: E501
else:
(data) = self.order_close_position_with_http_info(symbol, **kwargs) # noqa: E501
return data | [
"def",
"order_close_position",
"(",
"self",
",",
"symbol",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"ord... | https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/api/order_api.py#L474-L495 | ||
facebook/hhvm | cd8d20db628e93583fffa0194aaca937af9b2692 | hphp/tools/gdb/hhbc.py | python | as_idx | (op) | Cast an HPHP::Op to an integer. | Cast an HPHP::Op to an integer. | [
"Cast",
"an",
"HPHP",
"::",
"Op",
"to",
"an",
"integer",
"."
] | def as_idx(op):
"""Cast an HPHP::Op to an integer."""
if V('HPHP::Op_count') > 256:
return op.cast(T('uint16_t'))
else:
# This is necessary to avoid unwanted sign extension.
return op.cast(T('uint8_t')) | [
"def",
"as_idx",
"(",
"op",
")",
":",
"if",
"V",
"(",
"'HPHP::Op_count'",
")",
">",
"256",
":",
"return",
"op",
".",
"cast",
"(",
"T",
"(",
"'uint16_t'",
")",
")",
"else",
":",
"# This is necessary to avoid unwanted sign extension.",
"return",
"op",
".",
"... | https://github.com/facebook/hhvm/blob/cd8d20db628e93583fffa0194aaca937af9b2692/hphp/tools/gdb/hhbc.py#L18-L24 | ||
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | packages/seacas/scripts/exomerge2.py | python | ExodusModel._format_element_block_id_list | (self, id_list, *args, **kwargs) | return self._format_id_list(id_list,
sorted(object.keys()),
entity=entity,
*args,
translator=dict(tuples),
**kwargs) | Return a validated list of element block IDs. | Return a validated list of element block IDs. | [
"Return",
"a",
"validated",
"list",
"of",
"element",
"block",
"IDs",
"."
] | def _format_element_block_id_list(self, id_list, *args, **kwargs):
"""Return a validated list of element block IDs."""
object = self.element_blocks
entity = 'element block'
# get element block translations
tuples = [(value[0], key)
for key, value in object.items()
if value[0]]
# ensure element block names are unique
if len(set(x[0] for x in tuples)) != len(tuples):
self._warning('Duplicate %s names' % entity,
'At least two %s have the same name. '
'This may cause problems.' % self._plural(entity))
return self._format_id_list(id_list,
sorted(object.keys()),
entity=entity,
*args,
translator=dict(tuples),
**kwargs) | [
"def",
"_format_element_block_id_list",
"(",
"self",
",",
"id_list",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"object",
"=",
"self",
".",
"element_blocks",
"entity",
"=",
"'element block'",
"# get element block translations",
"tuples",
"=",
"[",
"(",... | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exomerge2.py#L1084-L1102 | |
SFTtech/openage | d6a08c53c48dc1e157807471df92197f6ca9e04d | openage/util/fslike/path.py | python | Path.__getitem__ | (self, subpath) | return self.joinpath(subpath) | Like joinpath. | Like joinpath. | [
"Like",
"joinpath",
"."
] | def __getitem__(self, subpath):
""" Like joinpath. """
return self.joinpath(subpath) | [
"def",
"__getitem__",
"(",
"self",
",",
"subpath",
")",
":",
"return",
"self",
".",
"joinpath",
"(",
"subpath",
")"
] | https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/util/fslike/path.py#L301-L303 | |
mitmedialab/Junkyard-Jumbotron | 7e32ecc8a01ea5a578fea6ea54f1f44c7f8f546e | python/calibrate.py | python | _debug | (**kwargs) | Log a list of keyword/value pairs | Log a list of keyword/value pairs | [
"Log",
"a",
"list",
"of",
"keyword",
"/",
"value",
"pairs"
] | def _debug(**kwargs):
"""Log a list of keyword/value pairs"""
for key, value in kwargs.items():
logging.debug("%s\t: %s", key, str(value)) | [
"def",
"_debug",
"(",
"*",
"*",
"kwargs",
")",
":",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"logging",
".",
"debug",
"(",
"\"%s\\t: %s\"",
",",
"key",
",",
"str",
"(",
"value",
")",
")"
] | https://github.com/mitmedialab/Junkyard-Jumbotron/blob/7e32ecc8a01ea5a578fea6ea54f1f44c7f8f546e/python/calibrate.py#L130-L133 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/cr/cr/config.py | python | Config.ParseValue | (value) | return value | Converts a string to a value.
Takes a string from something like an environment variable, and tries to
build an internal typed value. Recognizes Null, booleans, and numbers as
special.
Args:
value: The the string value to interpret.
Returns:
the parsed form of the value. | Converts a string to a value. | [
"Converts",
"a",
"string",
"to",
"a",
"value",
"."
] | def ParseValue(value):
"""Converts a string to a value.
Takes a string from something like an environment variable, and tries to
build an internal typed value. Recognizes Null, booleans, and numbers as
special.
Args:
value: The the string value to interpret.
Returns:
the parsed form of the value.
"""
if value in _PARSE_CONSTANTS:
return _PARSE_CONSTANTS[value]
try:
return int(value)
except ValueError:
pass
try:
return float(value)
except ValueError:
pass
return value | [
"def",
"ParseValue",
"(",
"value",
")",
":",
"if",
"value",
"in",
"_PARSE_CONSTANTS",
":",
"return",
"_PARSE_CONSTANTS",
"[",
"value",
"]",
"try",
":",
"return",
"int",
"(",
"value",
")",
"except",
"ValueError",
":",
"pass",
"try",
":",
"return",
"float",
... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/cr/cr/config.py#L174-L195 | |
Tencent/TNN | 7acca99f54c55747b415a4c57677403eebc7b706 | third_party/flatbuffers/python/flatbuffers/flexbuffers.py | python | Ref.MutateFloat | (self, value) | Mutates underlying floating point value bytes in place.
Args:
value: New float value. It must fit to the byte size of the existing
encoded value.
Returns:
Whether the value was mutated or not. | Mutates underlying floating point value bytes in place. | [
"Mutates",
"underlying",
"floating",
"point",
"value",
"bytes",
"in",
"place",
"."
] | def MutateFloat(self, value):
"""Mutates underlying floating point value bytes in place.
Args:
value: New float value. It must fit to the byte size of the existing
encoded value.
Returns:
Whether the value was mutated or not.
"""
if self._type is Type.FLOAT:
return _Mutate(F, self._buf, value, self._parent_width,
BitWidth.B(self._parent_width))
elif self._type is Type.INDIRECT_FLOAT:
return _Mutate(F, self._Indirect(), value, self._byte_width,
BitWidth.B(self._byte_width))
else:
return False | [
"def",
"MutateFloat",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"_type",
"is",
"Type",
".",
"FLOAT",
":",
"return",
"_Mutate",
"(",
"F",
",",
"self",
".",
"_buf",
",",
"value",
",",
"self",
".",
"_parent_width",
",",
"BitWidth",
".",
... | https://github.com/Tencent/TNN/blob/7acca99f54c55747b415a4c57677403eebc7b706/third_party/flatbuffers/python/flatbuffers/flexbuffers.py#L689-L706 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/xml/dom/pulldom.py | python | PullDOM.clear | (self) | clear(): Explicitly release parsing structures | clear(): Explicitly release parsing structures | [
"clear",
"()",
":",
"Explicitly",
"release",
"parsing",
"structures"
] | def clear(self):
"clear(): Explicitly release parsing structures"
self.document = None | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"document",
"=",
"None"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/xml/dom/pulldom.py#L192-L194 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/html.py | python | HtmlPrintout.SetMargins | (*args, **kwargs) | return _html.HtmlPrintout_SetMargins(*args, **kwargs) | SetMargins(self, float top=25.2, float bottom=25.2, float left=25.2,
float right=25.2, float spaces=5) | SetMargins(self, float top=25.2, float bottom=25.2, float left=25.2,
float right=25.2, float spaces=5) | [
"SetMargins",
"(",
"self",
"float",
"top",
"=",
"25",
".",
"2",
"float",
"bottom",
"=",
"25",
".",
"2",
"float",
"left",
"=",
"25",
".",
"2",
"float",
"right",
"=",
"25",
".",
"2",
"float",
"spaces",
"=",
"5",
")"
] | def SetMargins(*args, **kwargs):
"""
SetMargins(self, float top=25.2, float bottom=25.2, float left=25.2,
float right=25.2, float spaces=5)
"""
return _html.HtmlPrintout_SetMargins(*args, **kwargs) | [
"def",
"SetMargins",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_html",
".",
"HtmlPrintout_SetMargins",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/html.py#L1300-L1305 | |
google/asylo | a3b09ebff6c0e3b10e25d40f14991e16bb75d883 | asylo/platform/system_call/preprocess.py | python | SystemCallTable.parse_defines | (self) | Parse each 'SYSCALL_DEFINE' directive in the input stream. | Parse each 'SYSCALL_DEFINE' directive in the input stream. | [
"Parse",
"each",
"SYSCALL_DEFINE",
"directive",
"in",
"the",
"input",
"stream",
"."
] | def parse_defines(self):
"""Parse each 'SYSCALL_DEFINE' directive in the input stream."""
pattern = re.compile(r'SYSCALL_DEFINE(\d)\s*\(([^)]*)\)', re.MULTILINE)
for definition in re.findall(pattern, self.declarations):
arity, rest = definition
split = rest.split(',')
# 'split' is expected to begin with a system call name followed by a
# zero or more parameter name, parameter type values at consecutive
# offsets into the list. Check here that its length is odd as a sanity
# check.
if len(split) % 2 != 1:
raise ParseError('Could not parse definition: ' + definition)
name = split[0]
self.parameter_count[name] = arity
self.parameter_list[name] = [item.strip() for item in split[1:]] | [
"def",
"parse_defines",
"(",
"self",
")",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"r'SYSCALL_DEFINE(\\d)\\s*\\(([^)]*)\\)'",
",",
"re",
".",
"MULTILINE",
")",
"for",
"definition",
"in",
"re",
".",
"findall",
"(",
"pattern",
",",
"self",
".",
"declara... | https://github.com/google/asylo/blob/a3b09ebff6c0e3b10e25d40f14991e16bb75d883/asylo/platform/system_call/preprocess.py#L110-L127 | ||
protocolbuffers/protobuf | b5ab0b7a18b7336c60130f4ddb2d97c51792f896 | python/google/protobuf/internal/containers.py | python | RepeatedScalarFieldContainer.__eq__ | (self, other) | return other == self._values | Compares the current instance with another one. | Compares the current instance with another one. | [
"Compares",
"the",
"current",
"instance",
"with",
"another",
"one",
"."
] | def __eq__(self, other):
"""Compares the current instance with another one."""
if self is other:
return True
# Special case for the same type which should be common and fast.
if isinstance(other, self.__class__):
return other._values == self._values
# We are presumably comparing against some other sequence type.
return other == self._values | [
"def",
"__eq__",
"(",
"self",
",",
"other",
")",
":",
"if",
"self",
"is",
"other",
":",
"return",
"True",
"# Special case for the same type which should be common and fast.",
"if",
"isinstance",
"(",
"other",
",",
"self",
".",
"__class__",
")",
":",
"return",
"o... | https://github.com/protocolbuffers/protobuf/blob/b5ab0b7a18b7336c60130f4ddb2d97c51792f896/python/google/protobuf/internal/containers.py#L198-L206 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/lib2to3/patcomp.py | python | PatternCompiler.__init__ | (self, grammar_file=None) | Initializer.
Takes an optional alternative filename for the pattern grammar. | Initializer. | [
"Initializer",
"."
] | def __init__(self, grammar_file=None):
"""Initializer.
Takes an optional alternative filename for the pattern grammar.
"""
if grammar_file is None:
self.grammar = pygram.pattern_grammar
self.syms = pygram.pattern_symbols
else:
self.grammar = driver.load_grammar(grammar_file)
self.syms = pygram.Symbols(self.grammar)
self.pygrammar = pygram.python_grammar
self.pysyms = pygram.python_symbols
self.driver = driver.Driver(self.grammar, convert=pattern_convert) | [
"def",
"__init__",
"(",
"self",
",",
"grammar_file",
"=",
"None",
")",
":",
"if",
"grammar_file",
"is",
"None",
":",
"self",
".",
"grammar",
"=",
"pygram",
".",
"pattern_grammar",
"self",
".",
"syms",
"=",
"pygram",
".",
"pattern_symbols",
"else",
":",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/lib2to3/patcomp.py#L40-L53 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/aui/auibar.py | python | AuiToolBar.SetToolShortHelp | (self, tool_id, help_string) | Sets the short help for the given tool.
:param integer `tool_id`: the tool identifier;
:param string `help_string`: the string for the short help. | Sets the short help for the given tool. | [
"Sets",
"the",
"short",
"help",
"for",
"the",
"given",
"tool",
"."
] | def SetToolShortHelp(self, tool_id, help_string):
"""
Sets the short help for the given tool.
:param integer `tool_id`: the tool identifier;
:param string `help_string`: the string for the short help.
"""
tool = self.FindTool(tool_id)
if tool:
tool.short_help = help_string | [
"def",
"SetToolShortHelp",
"(",
"self",
",",
"tool_id",
",",
"help_string",
")",
":",
"tool",
"=",
"self",
".",
"FindTool",
"(",
"tool_id",
")",
"if",
"tool",
":",
"tool",
".",
"short_help",
"=",
"help_string"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/auibar.py#L2805-L2815 | ||
gnuradio/gnuradio | 09c3c4fa4bfb1a02caac74cb5334dfe065391e3b | grc/gui/canvas/connection.py | python | Connection.draw | (self, cr) | Draw the connection. | Draw the connection. | [
"Draw",
"the",
"connection",
"."
] | def draw(self, cr):
"""
Draw the connection.
"""
self._current_cr = cr
sink = self.sink_port
source = self.source_port
# check for changes
port_rotations = (source.rotation, sink.rotation)
if self._current_port_rotations != port_rotations:
self.create_shapes() # triggers _make_path() call below
self._current_port_rotations = port_rotations
new_coordinates = (source.parent_block.coordinate,
sink.parent_block.coordinate)
if self._current_coordinates != new_coordinates:
self._make_path(cr)
self._current_coordinates = new_coordinates
color1, color2 = (
None if color is None else
colors.HIGHLIGHT_COLOR if self.highlighted else
colors.CONNECTION_DISABLED_COLOR if not self.enabled else
colors.CONNECTION_ERROR_COLOR if not self.is_valid() else
color
for color in (self._color1, self._color2)
)
cr.translate(*self.coordinate)
cr.set_line_width(self._line_width_factor * cr.get_line_width())
cr.new_path()
cr.append_path(self._line_path)
arrow_pos = cr.get_current_point()
if color1: # not a message connection
cr.set_source_rgba(*color1)
cr.stroke_preserve()
if color1 != color2:
cr.save()
cr.set_dash([5.0, 5.0], 5.0 if color1 else 0.0)
cr.set_source_rgba(*color2)
cr.stroke()
cr.restore()
else:
cr.new_path()
cr.move_to(*arrow_pos)
cr.set_source_rgba(*color2)
cr.rotate(self._arrow_rotation)
cr.rel_move_to(CONNECTOR_ARROW_HEIGHT, 0)
cr.rel_line_to(-CONNECTOR_ARROW_HEIGHT, -CONNECTOR_ARROW_BASE / 2)
cr.rel_line_to(0, CONNECTOR_ARROW_BASE)
cr.close_path()
cr.fill() | [
"def",
"draw",
"(",
"self",
",",
"cr",
")",
":",
"self",
".",
"_current_cr",
"=",
"cr",
"sink",
"=",
"self",
".",
"sink_port",
"source",
"=",
"self",
".",
"source_port",
"# check for changes",
"port_rotations",
"=",
"(",
"source",
".",
"rotation",
",",
"... | https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/grc/gui/canvas/connection.py#L129-L185 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/turtle.py | python | TurtleScreen.delay | (self, delay=None) | Return or set the drawing delay in milliseconds.
Optional argument:
delay -- positive integer
Example (for a TurtleScreen instance named screen):
>>> screen.delay(15)
>>> screen.delay()
15 | Return or set the drawing delay in milliseconds. | [
"Return",
"or",
"set",
"the",
"drawing",
"delay",
"in",
"milliseconds",
"."
] | def delay(self, delay=None):
""" Return or set the drawing delay in milliseconds.
Optional argument:
delay -- positive integer
Example (for a TurtleScreen instance named screen):
>>> screen.delay(15)
>>> screen.delay()
15
"""
if delay is None:
return self._delayvalue
self._delayvalue = int(delay) | [
"def",
"delay",
"(",
"self",
",",
"delay",
"=",
"None",
")",
":",
"if",
"delay",
"is",
"None",
":",
"return",
"self",
".",
"_delayvalue",
"self",
".",
"_delayvalue",
"=",
"int",
"(",
"delay",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/turtle.py#L1220-L1233 | ||
llvm-mirror/lldb | d01083a850f577b85501a0902b52fd0930de72c7 | examples/python/gdbremote.py | python | RegisterInfo.__str__ | (self) | return s | Dump the register info key/value pairs | Dump the register info key/value pairs | [
"Dump",
"the",
"register",
"info",
"key",
"/",
"value",
"pairs"
] | def __str__(self):
'''Dump the register info key/value pairs'''
s = ''
for key in self.info.keys():
if s:
s += ', '
s += "%s=%s " % (key, self.info[key])
return s | [
"def",
"__str__",
"(",
"self",
")",
":",
"s",
"=",
"''",
"for",
"key",
"in",
"self",
".",
"info",
".",
"keys",
"(",
")",
":",
"if",
"s",
":",
"s",
"+=",
"', '",
"s",
"+=",
"\"%s=%s \"",
"%",
"(",
"key",
",",
"self",
".",
"info",
"[",
"key",
... | https://github.com/llvm-mirror/lldb/blob/d01083a850f577b85501a0902b52fd0930de72c7/examples/python/gdbremote.py#L392-L399 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/distributions/python/ops/beta.py | python | Beta.name | (self) | return self._name | Name to prepend to all ops. | Name to prepend to all ops. | [
"Name",
"to",
"prepend",
"to",
"all",
"ops",
"."
] | def name(self):
"""Name to prepend to all ops."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/beta.py#L164-L166 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/resolvelib/structs.py | python | DirectedGraph.add | (self, key) | Add a new vertex to the graph. | Add a new vertex to the graph. | [
"Add",
"a",
"new",
"vertex",
"to",
"the",
"graph",
"."
] | def add(self, key):
"""Add a new vertex to the graph."""
if key in self._vertices:
raise ValueError("vertex exists")
self._vertices.add(key)
self._forwards[key] = set()
self._backwards[key] = set() | [
"def",
"add",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"in",
"self",
".",
"_vertices",
":",
"raise",
"ValueError",
"(",
"\"vertex exists\"",
")",
"self",
".",
"_vertices",
".",
"add",
"(",
"key",
")",
"self",
".",
"_forwards",
"[",
"key",
"]",... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/resolvelib/structs.py#L29-L35 | ||
envoyproxy/envoy | 65541accdafe255e72310b4298d646e091da2d80 | tools/protodoc/protodoc.py | python | format_field_type | (type_context, field) | Format a FieldDescriptorProto type description.
Adds cross-refs for message types.
TODO(htuch): Add cross-refs for enums as well.
Args:
type_context: contextual information for message/enum/field.
field: FieldDescriptor proto.
Return: RST formatted field type. | Format a FieldDescriptorProto type description. | [
"Format",
"a",
"FieldDescriptorProto",
"type",
"description",
"."
] | def format_field_type(type_context, field):
"""Format a FieldDescriptorProto type description.
Adds cross-refs for message types.
TODO(htuch): Add cross-refs for enums as well.
Args:
type_context: contextual information for message/enum/field.
field: FieldDescriptor proto.
Return: RST formatted field type.
"""
if field.type_name.startswith(ENVOY_API_NAMESPACE_PREFIX) or field.type_name.startswith(
ENVOY_PREFIX):
type_name = normalize_field_type_name(field.type_name)
if field.type == field.TYPE_MESSAGE:
if type_context.map_typenames and type_name_from_fqn(
field.type_name) in type_context.map_typenames:
return 'map<%s, %s>' % tuple(
map(
functools.partial(format_field_type, type_context),
type_context.map_typenames[type_name_from_fqn(field.type_name)]))
return format_internal_link(type_name, message_cross_ref_label(type_name))
if field.type == field.TYPE_ENUM:
return format_internal_link(type_name, enum_cross_ref_label(type_name))
elif field.type_name.startswith(WKT_NAMESPACE_PREFIX):
wkt = field.type_name[len(WKT_NAMESPACE_PREFIX):]
return format_external_link(
wkt, 'https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#%s'
% wkt.lower())
elif field.type_name.startswith(RPC_NAMESPACE_PREFIX):
rpc = field.type_name[len(RPC_NAMESPACE_PREFIX):]
return format_external_link(
rpc, 'https://cloud.google.com/natural-language/docs/reference/rpc/google.rpc#%s'
% rpc.lower())
elif field.type_name:
return field.type_name
pretty_type_names = {
field.TYPE_DOUBLE: 'double',
field.TYPE_FLOAT: 'float',
field.TYPE_INT32: 'int32',
field.TYPE_SFIXED32: 'int32',
field.TYPE_SINT32: 'int32',
field.TYPE_FIXED32: 'uint32',
field.TYPE_UINT32: 'uint32',
field.TYPE_INT64: 'int64',
field.TYPE_SFIXED64: 'int64',
field.TYPE_SINT64: 'int64',
field.TYPE_FIXED64: 'uint64',
field.TYPE_UINT64: 'uint64',
field.TYPE_BOOL: 'bool',
field.TYPE_STRING: 'string',
field.TYPE_BYTES: 'bytes',
}
if field.type in pretty_type_names:
return format_external_link(
pretty_type_names[field.type],
'https://developers.google.com/protocol-buffers/docs/proto#scalar')
raise ProtodocError('Unknown field type ' + str(field.type)) | [
"def",
"format_field_type",
"(",
"type_context",
",",
"field",
")",
":",
"if",
"field",
".",
"type_name",
".",
"startswith",
"(",
"ENVOY_API_NAMESPACE_PREFIX",
")",
"or",
"field",
".",
"type_name",
".",
"startswith",
"(",
"ENVOY_PREFIX",
")",
":",
"type_name",
... | https://github.com/envoyproxy/envoy/blob/65541accdafe255e72310b4298d646e091da2d80/tools/protodoc/protodoc.py#L420-L478 | ||
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/contributed/sumopy/coremodules/demand/detectorflows_wxgui.py | python | AddDetectorflowTool.deactivate | (self) | This call by metacanvas signals that the tool has been
deactivated and can now interact with metacanvas. | This call by metacanvas signals that the tool has been
deactivated and can now interact with metacanvas. | [
"This",
"call",
"by",
"metacanvas",
"signals",
"that",
"the",
"tool",
"has",
"been",
"deactivated",
"and",
"can",
"now",
"interact",
"with",
"metacanvas",
"."
] | def deactivate(self):
"""
This call by metacanvas signals that the tool has been
deactivated and can now interact with metacanvas.
"""
self._is_active = False
# self.unhighlight()
# reset lane visibility
if self._is_lane_visible_before is not None:
lanedraws = self.get_drawobj_by_ident('lanedraws')
if lanedraws:
lanedraws.set_visible(self._is_lane_visible_before)
self._canvas.draw()
self.deactivate_select() | [
"def",
"deactivate",
"(",
"self",
")",
":",
"self",
".",
"_is_active",
"=",
"False",
"# self.unhighlight()",
"# reset lane visibility",
"if",
"self",
".",
"_is_lane_visible_before",
"is",
"not",
"None",
":",
"lanedraws",
"=",
"self",
".",
"get_drawobj_by_ident",
"... | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/coremodules/demand/detectorflows_wxgui.py#L308-L324 | ||
PX4/PX4-Autopilot | 0b9f60a0370be53d683352c63fd92db3d6586e18 | msg/tools/px_generate_uorb_topic_files.py | python | generate_uRTPS_general | (filename_send_msgs, filename_alias_send_msgs, filename_receive_msgs, filename_alias_receive_msgs,
msg_dir, outputdir, templatedir, package, includepath, msgs, fastrtps_version, ros2_distro, template_name) | return generate_by_template(output_file, template_file, merged_em_globals) | Generates source file by msg content | Generates source file by msg content | [
"Generates",
"source",
"file",
"by",
"msg",
"content"
] | def generate_uRTPS_general(filename_send_msgs, filename_alias_send_msgs, filename_receive_msgs, filename_alias_receive_msgs,
msg_dir, outputdir, templatedir, package, includepath, msgs, fastrtps_version, ros2_distro, template_name):
"""
Generates source file by msg content
"""
send_msgs = list(os.path.join(msg_dir, msg + ".msg")
for msg in filename_send_msgs)
receive_msgs = list(os.path.join(msg_dir, msg + ".msg")
for msg in filename_receive_msgs)
alias_send_msgs = list([os.path.join(
msg_dir, msg[1] + ".msg"), msg[0]] for msg in filename_alias_send_msgs)
alias_receive_msgs = list([os.path.join(
msg_dir, msg[1] + ".msg"), msg[0]] for msg in filename_alias_receive_msgs)
em_globals_list = []
if send_msgs:
em_globals_list.extend([get_em_globals(
f, "", package, includepath, msgs, fastrtps_version, ros2_distro, MsgScope.SEND) for f in send_msgs])
if alias_send_msgs:
em_globals_list.extend([get_em_globals(
f[0], f[1], package, includepath, msgs, fastrtps_version, ros2_distro, MsgScope.SEND) for f in alias_send_msgs])
if receive_msgs:
em_globals_list.extend([get_em_globals(
f, "", package, includepath, msgs, fastrtps_version, ros2_distro, MsgScope.RECEIVE) for f in receive_msgs])
if alias_receive_msgs:
em_globals_list.extend([get_em_globals(
f[0], f[1], package, includepath, msgs, fastrtps_version, ros2_distro, MsgScope.RECEIVE) for f in alias_receive_msgs])
merged_em_globals = merge_em_globals_list(em_globals_list)
# Make sure output directory exists:
if not os.path.isdir(outputdir):
os.makedirs(outputdir)
template_file = os.path.join(templatedir, template_name)
output_file = os.path.join(
outputdir, template_name.replace(".em", ""))
return generate_by_template(output_file, template_file, merged_em_globals) | [
"def",
"generate_uRTPS_general",
"(",
"filename_send_msgs",
",",
"filename_alias_send_msgs",
",",
"filename_receive_msgs",
",",
"filename_alias_receive_msgs",
",",
"msg_dir",
",",
"outputdir",
",",
"templatedir",
",",
"package",
",",
"includepath",
",",
"msgs",
",",
"fa... | https://github.com/PX4/PX4-Autopilot/blob/0b9f60a0370be53d683352c63fd92db3d6586e18/msg/tools/px_generate_uorb_topic_files.py#L210-L253 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/keras/utils/layer_utils.py | python | cached_per_instance | (f) | return wrapped | Lightweight decorator for caching lazily constructed properties.
When to use:
This decorator provides simple caching with minimal overhead. It is designed
for properties which are expensive to compute and static over the life of a
class instance, and provides no mechanism for cache invalidation. Thus it is
best suited for lazily exposing derived properties of other static data.
For classes with custom getattr / setattr behavior (such as trackable
objects), storing cache results as object attributes is not performant.
Instead, a specialized cache can significantly reduce property lookup
overhead. (While still allowing the decorated property to be lazily computed.)
Consider the following class:
```
class MyClass(object):
def __setattr__(self, key, value):
# Some expensive class specific code
# ...
# ...
super(MyClass, self).__setattr__(key, value)
@property
def thing(self):
# `thing` is expensive to compute (and may not even be requested), so we
# want to lazily compute it and then cache it.
output = getattr(self, '_thing', None)
if output is None:
self._thing = output = compute_thing(self)
return output
```
It's also worth noting that ANY overriding of __setattr__, even something as
simple as:
```
def __setattr__(self, key, value):
super(MyClass, self).__setattr__(key, value)
```
Slows down attribute assignment by nearly 10x.
By contrast, replacing the definition of `thing` with the following sidesteps
the expensive __setattr__ altogether:
'''
@property
@tracking.cached_per_instance
def thing(self):
# `thing` is expensive to compute (and may not even be requested), so we
# want to lazily compute it and then cache it.
return compute_thing(self)
'''
Performance:
The overhead for this decorator is ~0.4 us / call. A much lower overhead
implementation (~0.085 us / call) can be achieved by using a custom dict type:
```
def dict_based_cache(f):
class Cache(dict):
__slots__ = ()
def __missing__(self, key):
self[key] = output = f(key)
return output
return property(Cache().__getitem__)
```
However, that implementation holds class instances as keys, and as a result
blocks garbage collection. (And modifying it to use weakref's as keys raises
the lookup overhead to ~0.4 us) As a result, the WeakKeyDictionary
implementation below turns out to be more prudent.
Args:
f: The function to cache.
Returns:
f decorated with simple caching behavior. | Lightweight decorator for caching lazily constructed properties. | [
"Lightweight",
"decorator",
"for",
"caching",
"lazily",
"constructed",
"properties",
"."
] | def cached_per_instance(f):
"""Lightweight decorator for caching lazily constructed properties.
When to use:
This decorator provides simple caching with minimal overhead. It is designed
for properties which are expensive to compute and static over the life of a
class instance, and provides no mechanism for cache invalidation. Thus it is
best suited for lazily exposing derived properties of other static data.
For classes with custom getattr / setattr behavior (such as trackable
objects), storing cache results as object attributes is not performant.
Instead, a specialized cache can significantly reduce property lookup
overhead. (While still allowing the decorated property to be lazily computed.)
Consider the following class:
```
class MyClass(object):
def __setattr__(self, key, value):
# Some expensive class specific code
# ...
# ...
super(MyClass, self).__setattr__(key, value)
@property
def thing(self):
# `thing` is expensive to compute (and may not even be requested), so we
# want to lazily compute it and then cache it.
output = getattr(self, '_thing', None)
if output is None:
self._thing = output = compute_thing(self)
return output
```
It's also worth noting that ANY overriding of __setattr__, even something as
simple as:
```
def __setattr__(self, key, value):
super(MyClass, self).__setattr__(key, value)
```
Slows down attribute assignment by nearly 10x.
By contrast, replacing the definition of `thing` with the following sidesteps
the expensive __setattr__ altogether:
'''
@property
@tracking.cached_per_instance
def thing(self):
# `thing` is expensive to compute (and may not even be requested), so we
# want to lazily compute it and then cache it.
return compute_thing(self)
'''
Performance:
The overhead for this decorator is ~0.4 us / call. A much lower overhead
implementation (~0.085 us / call) can be achieved by using a custom dict type:
```
def dict_based_cache(f):
class Cache(dict):
__slots__ = ()
def __missing__(self, key):
self[key] = output = f(key)
return output
return property(Cache().__getitem__)
```
However, that implementation holds class instances as keys, and as a result
blocks garbage collection. (And modifying it to use weakref's as keys raises
the lookup overhead to ~0.4 us) As a result, the WeakKeyDictionary
implementation below turns out to be more prudent.
Args:
f: The function to cache.
Returns:
f decorated with simple caching behavior.
"""
cache = weakref.WeakKeyDictionary()
@functools.wraps(f)
def wrapped(item):
output = cache.get(item)
if output is None:
cache[item] = output = f(item)
return output
wrapped.cache = cache
return wrapped | [
"def",
"cached_per_instance",
"(",
"f",
")",
":",
"cache",
"=",
"weakref",
".",
"WeakKeyDictionary",
"(",
")",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapped",
"(",
"item",
")",
":",
"output",
"=",
"cache",
".",
"get",
"(",
"item",
")... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/utils/layer_utils.py#L322-L414 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | chrome/common/extensions/docs/server2/future.py | python | Future.Get | (self) | Gets the stored value, error, or delegate contents. | Gets the stored value, error, or delegate contents. | [
"Gets",
"the",
"stored",
"value",
"error",
"or",
"delegate",
"contents",
"."
] | def Get(self):
'''Gets the stored value, error, or delegate contents.
'''
if self._value is not _no_value:
return self._value
if self._exc_info is not None:
self._Raise()
try:
self._value = self._delegate.Get()
return self._value
except:
self._exc_info = sys.exc_info()
self._Raise() | [
"def",
"Get",
"(",
"self",
")",
":",
"if",
"self",
".",
"_value",
"is",
"not",
"_no_value",
":",
"return",
"self",
".",
"_value",
"if",
"self",
".",
"_exc_info",
"is",
"not",
"None",
":",
"self",
".",
"_Raise",
"(",
")",
"try",
":",
"self",
".",
... | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/chrome/common/extensions/docs/server2/future.py#L39-L51 | ||
nucleic/atom | 9f0cb2a8101dd63c354a98ebc7489b2c616dc82a | atom/atom.py | python | observe | (*names: str) | return ObserveHandler(pairs) | A decorator which can be used to observe members on a class.
Parameters
----------
*names
The str names of the attributes to observe on the object.
These must be of the form 'foo' or 'foo.bar'. | A decorator which can be used to observe members on a class. | [
"A",
"decorator",
"which",
"can",
"be",
"used",
"to",
"observe",
"members",
"on",
"a",
"class",
"."
] | def observe(*names: str):
"""A decorator which can be used to observe members on a class.
Parameters
----------
*names
The str names of the attributes to observe on the object.
These must be of the form 'foo' or 'foo.bar'.
"""
# backwards compatibility for a single tuple or list argument
if len(names) == 1 and isinstance(names[0], (tuple, list)):
names = names[0]
pairs: List[Tuple[str, Optional[str]]] = []
for name in names:
if not isinstance(name, str):
msg = "observe attribute name must be a string, got '%s' instead"
raise TypeError(msg % type(name).__name__)
ndots = name.count(".")
if ndots > 1:
msg = "cannot observe '%s', only a single extension is allowed"
raise TypeError(msg % name)
if ndots == 1:
name, attr = name.split(".")
pairs.append((name, attr))
else:
pairs.append((name, None))
return ObserveHandler(pairs) | [
"def",
"observe",
"(",
"*",
"names",
":",
"str",
")",
":",
"# backwards compatibility for a single tuple or list argument",
"if",
"len",
"(",
"names",
")",
"==",
"1",
"and",
"isinstance",
"(",
"names",
"[",
"0",
"]",
",",
"(",
"tuple",
",",
"list",
")",
")... | https://github.com/nucleic/atom/blob/9f0cb2a8101dd63c354a98ebc7489b2c616dc82a/atom/atom.py#L42-L69 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/sparse/linalg/interface.py | python | LinearOperator._matmat | (self, X) | return np.hstack([self.matvec(col.reshape(-1,1)) for col in X.T]) | Default matrix-matrix multiplication handler.
Falls back on the user-defined _matvec method, so defining that will
define matrix multiplication (though in a very suboptimal way). | Default matrix-matrix multiplication handler. | [
"Default",
"matrix",
"-",
"matrix",
"multiplication",
"handler",
"."
] | def _matmat(self, X):
"""Default matrix-matrix multiplication handler.
Falls back on the user-defined _matvec method, so defining that will
define matrix multiplication (though in a very suboptimal way).
"""
return np.hstack([self.matvec(col.reshape(-1,1)) for col in X.T]) | [
"def",
"_matmat",
"(",
"self",
",",
"X",
")",
":",
"return",
"np",
".",
"hstack",
"(",
"[",
"self",
".",
"matvec",
"(",
"col",
".",
"reshape",
"(",
"-",
"1",
",",
"1",
")",
")",
"for",
"col",
"in",
"X",
".",
"T",
"]",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/sparse/linalg/interface.py#L167-L174 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/flatnotebook.py | python | FlatNotebookEvent.SetOldSelection | (self, nOldSel) | Sets old event selection. | Sets old event selection. | [
"Sets",
"old",
"event",
"selection",
"."
] | def SetOldSelection(self, nOldSel):
""" Sets old event selection. """
self._oldselection = nOldSel | [
"def",
"SetOldSelection",
"(",
"self",
",",
"nOldSel",
")",
":",
"self",
".",
"_oldselection",
"=",
"nOldSel"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/flatnotebook.py#L1071-L1074 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/android/loading/request_track.py | python | Request.GetResponseTransportLength | (self) | return encoded_data_length + self.response_headers_length | Get the total amount of encoded data no matter whether load has finished
or not. | Get the total amount of encoded data no matter whether load has finished
or not. | [
"Get",
"the",
"total",
"amount",
"of",
"encoded",
"data",
"no",
"matter",
"whether",
"load",
"has",
"finished",
"or",
"not",
"."
] | def GetResponseTransportLength(self):
"""Get the total amount of encoded data no matter whether load has finished
or not.
"""
assert self.HasReceivedResponse()
assert not self.from_disk_cache and not self.served_from_cache
assert self.protocol not in {'about', 'blob', 'data'}
if self.timing.loading_finished != Timing.UNVAILABLE:
encoded_data_length = self.encoded_data_length
else:
encoded_data_length = sum(
[chunk_size for _, chunk_size in self.data_chunks])
assert encoded_data_length > 0 or len(self.data_chunks) == 0
return encoded_data_length + self.response_headers_length | [
"def",
"GetResponseTransportLength",
"(",
"self",
")",
":",
"assert",
"self",
".",
"HasReceivedResponse",
"(",
")",
"assert",
"not",
"self",
".",
"from_disk_cache",
"and",
"not",
"self",
".",
"served_from_cache",
"assert",
"self",
".",
"protocol",
"not",
"in",
... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/android/loading/request_track.py#L257-L270 | |
kushview/Element | 1cc16380caa2ab79461246ba758b9de1f46db2a5 | waflib/Build.py | python | CleanContext.execute | (self) | See :py:func:`waflib.Build.BuildContext.execute`. | See :py:func:`waflib.Build.BuildContext.execute`. | [
"See",
":",
"py",
":",
"func",
":",
"waflib",
".",
"Build",
".",
"BuildContext",
".",
"execute",
"."
] | def execute(self):
"""
See :py:func:`waflib.Build.BuildContext.execute`.
"""
self.restore()
if not self.all_envs:
self.load_envs()
self.recurse([self.run_dir])
try:
self.clean()
finally:
self.store() | [
"def",
"execute",
"(",
"self",
")",
":",
"self",
".",
"restore",
"(",
")",
"if",
"not",
"self",
".",
"all_envs",
":",
"self",
".",
"load_envs",
"(",
")",
"self",
".",
"recurse",
"(",
"[",
"self",
".",
"run_dir",
"]",
")",
"try",
":",
"self",
".",... | https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/Build.py#L1303-L1315 | ||
geemaple/leetcode | 68bc5032e1ee52c22ef2f2e608053484c487af54 | leetcode/338.counting-bits.py | python | Solution.countBits | (self, num) | return res | :type num: int
:rtype: List[int] | :type num: int
:rtype: List[int] | [
":",
"type",
"num",
":",
"int",
":",
"rtype",
":",
"List",
"[",
"int",
"]"
] | def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
res = [0 for i in range(num + 1)]
for i in range(1, num + 1):
res[i] = res[i & (i - 1)] + 1
return res | [
"def",
"countBits",
"(",
"self",
",",
"num",
")",
":",
"res",
"=",
"[",
"0",
"for",
"i",
"in",
"range",
"(",
"num",
"+",
"1",
")",
"]",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"num",
"+",
"1",
")",
":",
"res",
"[",
"i",
"]",
"=",
"res",... | https://github.com/geemaple/leetcode/blob/68bc5032e1ee52c22ef2f2e608053484c487af54/leetcode/338.counting-bits.py#L43-L54 | |
Slicer/Slicer | ba9fadf332cb0303515b68d8d06a344c82e3e3e5 | Base/Python/slicer/util.py | python | confirmOkCancelDisplay | (text, windowTitle=None, parent=None, **kwargs) | return result == qt.QMessageBox.Ok | Display a confirmation popup. Return if confirmed with OK.
When the application is running in testing mode (``slicer.app.testingEnabled() == True``),
the popup is skipped and True ("Ok") is returned, with a message being logged to indicate this. | Display a confirmation popup. Return if confirmed with OK. | [
"Display",
"a",
"confirmation",
"popup",
".",
"Return",
"if",
"confirmed",
"with",
"OK",
"."
] | def confirmOkCancelDisplay(text, windowTitle=None, parent=None, **kwargs):
"""Display a confirmation popup. Return if confirmed with OK.
When the application is running in testing mode (``slicer.app.testingEnabled() == True``),
the popup is skipped and True ("Ok") is returned, with a message being logged to indicate this.
"""
import qt, slicer, logging
if not windowTitle:
windowTitle = slicer.app.applicationName + " confirmation"
result = _messageDisplay(logging.INFO, text, True, parent=parent, windowTitle=windowTitle, icon=qt.QMessageBox.Question,
standardButtons=qt.QMessageBox.Ok | qt.QMessageBox.Cancel, **kwargs)
return result == qt.QMessageBox.Ok | [
"def",
"confirmOkCancelDisplay",
"(",
"text",
",",
"windowTitle",
"=",
"None",
",",
"parent",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"qt",
",",
"slicer",
",",
"logging",
"if",
"not",
"windowTitle",
":",
"windowTitle",
"=",
"slicer",
".... | https://github.com/Slicer/Slicer/blob/ba9fadf332cb0303515b68d8d06a344c82e3e3e5/Base/Python/slicer/util.py#L2339-L2350 | |
doyubkim/fluid-engine-dev | 45b4bdbdb4c6d8c0beebc682180469198203b0ef | scripts/utils.py | python | guess_os | () | Returns the name of the operating system.
This will return 'linux' for Linux compatible system, 'macos' for Macs,
'win32' for Windows, and 'freebsd' for FreeBSD. | Returns the name of the operating system.
This will return 'linux' for Linux compatible system, 'macos' for Macs,
'win32' for Windows, and 'freebsd' for FreeBSD. | [
"Returns",
"the",
"name",
"of",
"the",
"operating",
"system",
".",
"This",
"will",
"return",
"linux",
"for",
"Linux",
"compatible",
"system",
"macos",
"for",
"Macs",
"win32",
"for",
"Windows",
"and",
"freebsd",
"for",
"FreeBSD",
"."
] | def guess_os():
"""
Returns the name of the operating system.
This will return 'linux' for Linux compatible system, 'macos' for Macs,
'win32' for Windows, and 'freebsd' for FreeBSD.
"""
id = platform.system()
if id == 'Linux':
return 'linux'
elif id == 'Darwin':
return 'macosx'
elif id == 'Windows' or id == 'Microsoft':
return 'win32'
else:
return None | [
"def",
"guess_os",
"(",
")",
":",
"id",
"=",
"platform",
".",
"system",
"(",
")",
"if",
"id",
"==",
"'Linux'",
":",
"return",
"'linux'",
"elif",
"id",
"==",
"'Darwin'",
":",
"return",
"'macosx'",
"elif",
"id",
"==",
"'Windows'",
"or",
"id",
"==",
"'M... | https://github.com/doyubkim/fluid-engine-dev/blob/45b4bdbdb4c6d8c0beebc682180469198203b0ef/scripts/utils.py#L45-L59 | ||
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros_comm/roslaunch/src/roslaunch/pmon.py | python | Process.stop | (self, errors=None) | Stop the process. Record any significant error messages in the errors parameter
@param errors: error messages. stop() will record messages into this list.
@type errors: [str] | Stop the process. Record any significant error messages in the errors parameter | [
"Stop",
"the",
"process",
".",
"Record",
"any",
"significant",
"error",
"messages",
"in",
"the",
"errors",
"parameter"
] | def stop(self, errors=None):
"""
Stop the process. Record any significant error messages in the errors parameter
@param errors: error messages. stop() will record messages into this list.
@type errors: [str]
"""
pass | [
"def",
"stop",
"(",
"self",
",",
"errors",
"=",
"None",
")",
":",
"pass"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/roslaunch/src/roslaunch/pmon.py#L251-L258 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py | python | _join | (value) | return ' '.join(map(_stringify, value)) | Internal function. | Internal function. | [
"Internal",
"function",
"."
] | def _join(value):
"""Internal function."""
return ' '.join(map(_stringify, value)) | [
"def",
"_join",
"(",
"value",
")",
":",
"return",
"' '",
".",
"join",
"(",
"map",
"(",
"_stringify",
",",
"value",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py#L55-L57 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/array_ops.py | python | _autopacking_helper | (list_or_tuple, dtype, name) | Converts the given list or tuple to a tensor by packing.
Args:
list_or_tuple: A (possibly nested) list or tuple containing a tensor.
dtype: The element type of the returned tensor.
name: A name for the returned tensor.
Returns:
A `tf.Tensor` with value equivalent to `list_or_tuple`. | Converts the given list or tuple to a tensor by packing. | [
"Converts",
"the",
"given",
"list",
"or",
"tuple",
"to",
"a",
"tensor",
"by",
"packing",
"."
] | def _autopacking_helper(list_or_tuple, dtype, name):
"""Converts the given list or tuple to a tensor by packing.
Args:
list_or_tuple: A (possibly nested) list or tuple containing a tensor.
dtype: The element type of the returned tensor.
name: A name for the returned tensor.
Returns:
A `tf.Tensor` with value equivalent to `list_or_tuple`.
"""
if context.executing_eagerly():
# NOTE: Fast path when all the items are tensors, this doesn't do any type
# checking.
if all(ops.is_dense_tensor_like(elem) for elem in list_or_tuple):
return gen_array_ops.pack(list_or_tuple, name=name)
must_pack = False
converted_elems = []
with ops.name_scope(name) as scope:
for i, elem in enumerate(list_or_tuple):
if ops.is_dense_tensor_like(elem):
if dtype is not None and elem.dtype.base_dtype != dtype:
raise TypeError("Cannot convert a list containing a tensor of dtype "
"%s to %s (Tensor is: %r)" %
(elem.dtype, dtype, elem))
converted_elems.append(elem)
must_pack = True
elif isinstance(elem, (list, tuple)):
converted_elem = _autopacking_helper(elem, dtype, str(i))
if ops.is_dense_tensor_like(converted_elem):
must_pack = True
converted_elems.append(converted_elem)
else:
converted_elems.append(elem)
if must_pack:
elems_as_tensors = []
for i, elem in enumerate(converted_elems):
if ops.is_dense_tensor_like(elem):
elems_as_tensors.append(elem)
else:
# NOTE(mrry): This is inefficient, but it enables us to
# handle the case where the list arguments are other
# convertible-to-tensor types, such as numpy arrays.
elems_as_tensors.append(
constant_op.constant(elem, dtype=dtype, name=str(i)))
return gen_array_ops.pack(elems_as_tensors, name=scope)
else:
return converted_elems | [
"def",
"_autopacking_helper",
"(",
"list_or_tuple",
",",
"dtype",
",",
"name",
")",
":",
"if",
"context",
".",
"executing_eagerly",
"(",
")",
":",
"# NOTE: Fast path when all the items are tensors, this doesn't do any type",
"# checking.",
"if",
"all",
"(",
"ops",
".",
... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/array_ops.py#L1158-L1205 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | UpdateUIEvent.GetUpdateInterval | (*args, **kwargs) | return _core_.UpdateUIEvent_GetUpdateInterval(*args, **kwargs) | GetUpdateInterval() -> long
Returns the current interval between updates in milliseconds. -1
disables updates, 0 updates as frequently as possible. | GetUpdateInterval() -> long | [
"GetUpdateInterval",
"()",
"-",
">",
"long"
] | def GetUpdateInterval(*args, **kwargs):
"""
GetUpdateInterval() -> long
Returns the current interval between updates in milliseconds. -1
disables updates, 0 updates as frequently as possible.
"""
return _core_.UpdateUIEvent_GetUpdateInterval(*args, **kwargs) | [
"def",
"GetUpdateInterval",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"UpdateUIEvent_GetUpdateInterval",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L6866-L6873 | |
bigartm/bigartm | 47e37f982de87aa67bfd475ff1f39da696b181b3 | 3rdparty/protobuf-3.0.0/python/google/protobuf/internal/enum_type_wrapper.py | python | EnumTypeWrapper.items | (self) | return [(value_descriptor.name, value_descriptor.number)
for value_descriptor in self._enum_type.values] | Return a list of the (name, value) pairs of the enum.
These are returned in the order they were defined in the .proto file. | Return a list of the (name, value) pairs of the enum. | [
"Return",
"a",
"list",
"of",
"the",
"(",
"name",
"value",
")",
"pairs",
"of",
"the",
"enum",
"."
] | def items(self):
"""Return a list of the (name, value) pairs of the enum.
These are returned in the order they were defined in the .proto file.
"""
return [(value_descriptor.name, value_descriptor.number)
for value_descriptor in self._enum_type.values] | [
"def",
"items",
"(",
"self",
")",
":",
"return",
"[",
"(",
"value_descriptor",
".",
"name",
",",
"value_descriptor",
".",
"number",
")",
"for",
"value_descriptor",
"in",
"self",
".",
"_enum_type",
".",
"values",
"]"
] | https://github.com/bigartm/bigartm/blob/47e37f982de87aa67bfd475ff1f39da696b181b3/3rdparty/protobuf-3.0.0/python/google/protobuf/internal/enum_type_wrapper.py#L83-L89 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/smtplib.py | python | SMTP.close | (self) | Close the connection to the SMTP server. | Close the connection to the SMTP server. | [
"Close",
"the",
"connection",
"to",
"the",
"SMTP",
"server",
"."
] | def close(self):
"""Close the connection to the SMTP server."""
try:
file = self.file
self.file = None
if file:
file.close()
finally:
sock = self.sock
self.sock = None
if sock:
sock.close() | [
"def",
"close",
"(",
"self",
")",
":",
"try",
":",
"file",
"=",
"self",
".",
"file",
"self",
".",
"file",
"=",
"None",
"if",
"file",
":",
"file",
".",
"close",
"(",
")",
"finally",
":",
"sock",
"=",
"self",
".",
"sock",
"self",
".",
"sock",
"="... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/smtplib.py#L969-L980 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | KeyEvent.GetUnicodeKey | (*args, **kwargs) | return _core_.KeyEvent_GetUnicodeKey(*args, **kwargs) | GetUnicodeKey(self) -> int
Returns the Unicode character corresponding to this key event. This
function is only meaningful in a Unicode build of wxPython. | GetUnicodeKey(self) -> int | [
"GetUnicodeKey",
"(",
"self",
")",
"-",
">",
"int"
] | def GetUnicodeKey(*args, **kwargs):
"""
GetUnicodeKey(self) -> int
Returns the Unicode character corresponding to this key event. This
function is only meaningful in a Unicode build of wxPython.
"""
return _core_.KeyEvent_GetUnicodeKey(*args, **kwargs) | [
"def",
"GetUnicodeKey",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"KeyEvent_GetUnicodeKey",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L6021-L6028 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/stringold.py | python | rjust | (s, width) | return ' '*n + s | rjust(s, width) -> string
Return a right-justified version of s, in a field of the
specified width, padded with spaces as needed. The string is
never truncated. | rjust(s, width) -> string | [
"rjust",
"(",
"s",
"width",
")",
"-",
">",
"string"
] | def rjust(s, width):
"""rjust(s, width) -> string
Return a right-justified version of s, in a field of the
specified width, padded with spaces as needed. The string is
never truncated.
"""
n = width - len(s)
if n <= 0: return s
return ' '*n + s | [
"def",
"rjust",
"(",
"s",
",",
"width",
")",
":",
"n",
"=",
"width",
"-",
"len",
"(",
"s",
")",
"if",
"n",
"<=",
"0",
":",
"return",
"s",
"return",
"' '",
"*",
"n",
"+",
"s"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/stringold.py#L278-L288 | |
pyne/pyne | 0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3 | pyne/dbgen/kaeri.py | python | parse_for_all_isotopes | (htmlfile) | return isos | Parses an elemental html file, returning a set of all occuring isotopes. | Parses an elemental html file, returning a set of all occuring isotopes. | [
"Parses",
"an",
"elemental",
"html",
"file",
"returning",
"a",
"set",
"of",
"all",
"occuring",
"isotopes",
"."
] | def parse_for_all_isotopes(htmlfile):
"""Parses an elemental html file, returning a set of all occuring isotopes."""
isos = set()
with open(htmlfile, 'r') as f:
for line in f:
m = all_iso_regex.search(line)
if m is not None:
isos.add(nucname.id(m.group(1)))
return isos | [
"def",
"parse_for_all_isotopes",
"(",
"htmlfile",
")",
":",
"isos",
"=",
"set",
"(",
")",
"with",
"open",
"(",
"htmlfile",
",",
"'r'",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"m",
"=",
"all_iso_regex",
".",
"search",
"(",
"line",
")",
"... | https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/pyne/dbgen/kaeri.py#L82-L90 | |
Salensoft/thu-cst-cracker | f7f6b4de460aaac6da3d776ab28d9175e8b32ae2 | 大三上/软件工程/hw/2015/Homework/作业2 - 代码风格/01_code_style/my_posixpath.py | python | expanduser | (path) | return (userhome + path[i:]) or '/' | Expand ~ and ~user constructions. If user or $HOME is unknown,
do nothing. | Expand ~ and ~user constructions. If user or $HOME is unknown,
do nothing. | [
"Expand",
"~",
"and",
"~user",
"constructions",
".",
"If",
"user",
"or",
"$HOME",
"is",
"unknown",
"do",
"nothing",
"."
] | def expanduser(path):
"""Expand ~ and ~user constructions. If user or $HOME is unknown,
do nothing."""
if not path.startswith('~'):
return path
i = path.find('/', 1)
if i < 0:
i = len(path)
if i == 1:
if 'HOME' not in os.environ:
import pwd
userhome = pwd.getpwuid(os.getuid()).pw_dir
else:
userhome = os.environ['HOME']
else:
import pwd
try:
pwent = pwd.getpwnam(path[1:i])
except KeyError:
return path
userhome = pwent.pw_dir
userhome = userhome.rstrip('/')
return (userhome + path[i:]) or '/' | [
"def",
"expanduser",
"(",
"path",
")",
":",
"if",
"not",
"path",
".",
"startswith",
"(",
"'~'",
")",
":",
"return",
"path",
"i",
"=",
"path",
".",
"find",
"(",
"'/'",
",",
"1",
")",
"if",
"i",
"<",
"0",
":",
"i",
"=",
"len",
"(",
"path",
")",... | https://github.com/Salensoft/thu-cst-cracker/blob/f7f6b4de460aaac6da3d776ab28d9175e8b32ae2/大三上/软件工程/hw/2015/Homework/作业2 - 代码风格/01_code_style/my_posixpath.py#L264-L286 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/learn/python/learn/learn_runner.py | python | _get_default_schedule | (config) | Returns the default schedule for the provided RunConfig. | Returns the default schedule for the provided RunConfig. | [
"Returns",
"the",
"default",
"schedule",
"for",
"the",
"provided",
"RunConfig",
"."
] | def _get_default_schedule(config):
"""Returns the default schedule for the provided RunConfig."""
if not config or not _is_distributed(config):
return 'train_and_evaluate'
if not config.task_type:
raise ValueError('Must specify a schedule')
if config.task_type == run_config_lib.TaskType.MASTER:
# TODO(rhaertel): handle the case where there is more than one master
# or explicitly disallow such a case.
return 'train_and_evaluate'
elif config.task_type == run_config_lib.TaskType.PS:
return 'run_std_server'
elif config.task_type == run_config_lib.TaskType.WORKER:
return 'train'
raise ValueError('No default schedule for task type: %s' % (config.task_type)) | [
"def",
"_get_default_schedule",
"(",
"config",
")",
":",
"if",
"not",
"config",
"or",
"not",
"_is_distributed",
"(",
"config",
")",
":",
"return",
"'train_and_evaluate'",
"if",
"not",
"config",
".",
"task_type",
":",
"raise",
"ValueError",
"(",
"'Must specify a ... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/learn/python/learn/learn_runner.py#L263-L280 | ||
apiaryio/drafter | 4634ebd07f6c6f257cc656598ccd535492fdfb55 | tools/gyp/pylib/gyp/MSVSUserFile.py | python | Writer.__init__ | (self, user_file_path, version, name) | Initializes the user file.
Args:
user_file_path: Path to the user file.
version: Version info.
name: Name of the user file. | Initializes the user file. | [
"Initializes",
"the",
"user",
"file",
"."
] | def __init__(self, user_file_path, version, name):
"""Initializes the user file.
Args:
user_file_path: Path to the user file.
version: Version info.
name: Name of the user file.
"""
self.user_file_path = user_file_path
self.version = version
self.name = name
self.configurations = {} | [
"def",
"__init__",
"(",
"self",
",",
"user_file_path",
",",
"version",
",",
"name",
")",
":",
"self",
".",
"user_file_path",
"=",
"user_file_path",
"self",
".",
"version",
"=",
"version",
"self",
".",
"name",
"=",
"name",
"self",
".",
"configurations",
"="... | https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/pylib/gyp/MSVSUserFile.py#L57-L68 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pkg_resources/__init__.py | python | Environment.remove | (self, dist) | Remove `dist` from the environment | Remove `dist` from the environment | [
"Remove",
"dist",
"from",
"the",
"environment"
] | def remove(self, dist):
"""Remove `dist` from the environment"""
self._distmap[dist.key].remove(dist) | [
"def",
"remove",
"(",
"self",
",",
"dist",
")",
":",
"self",
".",
"_distmap",
"[",
"dist",
".",
"key",
"]",
".",
"remove",
"(",
"dist",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pkg_resources/__init__.py#L1001-L1003 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/pipeline/pipeline/pipeline.py | python | Pipeline.finalized_test | (self, *args, **kwargs) | Finalized this Pipeline in test mode. | Finalized this Pipeline in test mode. | [
"Finalized",
"this",
"Pipeline",
"in",
"test",
"mode",
"."
] | def finalized_test(self, *args, **kwargs):
"""Finalized this Pipeline in test mode."""
raise NotImplementedError(
'Must implement "finalized_test" in Pipeline sub-class.') | [
"def",
"finalized_test",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"raise",
"NotImplementedError",
"(",
"'Must implement \"finalized_test\" in Pipeline sub-class.'",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/pipeline/pipeline/pipeline.py#L1009-L1012 | ||
neoml-lib/neoml | a0d370fba05269a1b2258cef126f77bbd2054a3e | NeoML/samples/python/regressor.py | python | cv_iterator | (X, y, n_folds) | Returns X_train, y_train, X_test, y_test for each of the folds | Returns X_train, y_train, X_test, y_test for each of the folds | [
"Returns",
"X_train",
"y_train",
"X_test",
"y_test",
"for",
"each",
"of",
"the",
"folds"
] | def cv_iterator(X, y, n_folds):
"""Returns X_train, y_train, X_test, y_test for each of the folds"""
data_size = len(y)
test_size = data_size // n_folds
for i in range(n_folds):
train = list(itertools.chain(range(i*test_size),
range((i+1)*test_size, data_size)))
test = range(i*test_size, (i+1)*test_size)
yield X[train], y[train], X[test], y[test] | [
"def",
"cv_iterator",
"(",
"X",
",",
"y",
",",
"n_folds",
")",
":",
"data_size",
"=",
"len",
"(",
"y",
")",
"test_size",
"=",
"data_size",
"//",
"n_folds",
"for",
"i",
"in",
"range",
"(",
"n_folds",
")",
":",
"train",
"=",
"list",
"(",
"itertools",
... | https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/samples/python/regressor.py#L29-L37 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/idlelib/Debugger.py | python | StackViewer.fill_menu | (self) | override base method | override base method | [
"override",
"base",
"method"
] | def fill_menu(self):
"override base method"
menu = self.menu
menu.add_command(label="Go to source line",
command=self.goto_source_line)
menu.add_command(label="Show stack frame",
command=self.show_stack_frame) | [
"def",
"fill_menu",
"(",
"self",
")",
":",
"menu",
"=",
"self",
".",
"menu",
"menu",
".",
"add_command",
"(",
"label",
"=",
"\"Go to source line\"",
",",
"command",
"=",
"self",
".",
"goto_source_line",
")",
"menu",
".",
"add_command",
"(",
"label",
"=",
... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/idlelib/Debugger.py#L369-L375 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/cond_v2.py | python | _set_read_only_resource_inputs_attr | (op, branch_graphs) | Sets the list of resource inputs which are read-only.
This is used by AutomaticControlDependencies.
Args:
op: If or Case Operation.
branch_graphs: List of branch FuncGraphs. | Sets the list of resource inputs which are read-only. | [
"Sets",
"the",
"list",
"of",
"resource",
"inputs",
"which",
"are",
"read",
"-",
"only",
"."
] | def _set_read_only_resource_inputs_attr(op, branch_graphs):
"""Sets the list of resource inputs which are read-only.
This is used by AutomaticControlDependencies.
Args:
op: If or Case Operation.
branch_graphs: List of branch FuncGraphs.
"""
# The first entry in `op.inputs` is the predicate which is not passed to
# branch graphs so len(branch_graph[i].inputs) == len(op.inputs) - 1.
read_only_indices = set(range(len(op.inputs) - 1))
for branch_graph in branch_graphs:
assert len(branch_graph.inputs) == len(op.inputs) - 1, "should never happen"
if not read_only_indices:
break
branch_read_only_indices = acd.get_read_only_resource_input_indices_graph(
branch_graph)
read_only_indices = read_only_indices.intersection(branch_read_only_indices)
# Convert indices in `branch_graphs[i].inputs` to `op.inputs`.
read_only_indices = [i + 1 for i in read_only_indices]
ops.set_int_list_attr(op, acd.READ_ONLY_RESOURCE_INPUTS_ATTR,
sorted(read_only_indices)) | [
"def",
"_set_read_only_resource_inputs_attr",
"(",
"op",
",",
"branch_graphs",
")",
":",
"# The first entry in `op.inputs` is the predicate which is not passed to",
"# branch graphs so len(branch_graph[i].inputs) == len(op.inputs) - 1.",
"read_only_indices",
"=",
"set",
"(",
"range",
"... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/cond_v2.py#L1239-L1261 | ||
apache/impala | 8ddac48f3428c86f2cbd037ced89cfb903298b12 | bin/diagnostics/collect_diagnostics.py | python | ImpalaDiagnosticsHandler.copy_minidumps | (self, target, start_ts) | Copies mindumps with create time >= start_ts to 'target' directory. | Copies mindumps with create time >= start_ts to 'target' directory. | [
"Copies",
"mindumps",
"with",
"create",
"time",
">",
"=",
"start_ts",
"to",
"target",
"directory",
"."
] | def copy_minidumps(self, target, start_ts):
"""Copies mindumps with create time >= start_ts to 'target' directory."""
logging.info("Copying minidumps from %s to %s with ctime >= %s"
% (self.minidump_search_path, target, start_ts))
for filename in glob.glob(os.path.join(self.minidump_search_path, "*.dmp")):
try:
minidump_ctime = self.get_minidump_create_timestamp(filename)
if minidump_ctime >= math.floor(start_ts):
shutil.copy2(filename, target)
else:
logging.info("Ignored mindump: %s ctime: %s" % (filename, minidump_ctime))
except Exception:
logging.exception("Error processing minidump at path: %s. Skipping it." % filename) | [
"def",
"copy_minidumps",
"(",
"self",
",",
"target",
",",
"start_ts",
")",
":",
"logging",
".",
"info",
"(",
"\"Copying minidumps from %s to %s with ctime >= %s\"",
"%",
"(",
"self",
".",
"minidump_search_path",
",",
"target",
",",
"start_ts",
")",
")",
"for",
"... | https://github.com/apache/impala/blob/8ddac48f3428c86f2cbd037ced89cfb903298b12/bin/diagnostics/collect_diagnostics.py#L351-L363 | ||
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2class.py | python | xmlDoc.docCompressMode | (self) | return ret | get the compression ratio for a document, ZLIB based | get the compression ratio for a document, ZLIB based | [
"get",
"the",
"compression",
"ratio",
"for",
"a",
"document",
"ZLIB",
"based"
] | def docCompressMode(self):
"""get the compression ratio for a document, ZLIB based """
ret = libxml2mod.xmlGetDocCompressMode(self._o)
return ret | [
"def",
"docCompressMode",
"(",
"self",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlGetDocCompressMode",
"(",
"self",
".",
"_o",
")",
"return",
"ret"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L3471-L3474 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/win32/scripts/regsetup.py | python | FindPythonExe | (exeAlias, possibleRealNames, searchPaths) | return found, registered_ok | Find an exe.
Returns the full path to the .exe, and a boolean indicating if the current
registered entry is OK. We don't trust the already registered version even
if it exists - it may be wrong (ie, for a different Python version) | Find an exe. | [
"Find",
"an",
"exe",
"."
] | def FindPythonExe(exeAlias, possibleRealNames, searchPaths):
"""Find an exe.
Returns the full path to the .exe, and a boolean indicating if the current
registered entry is OK. We don't trust the already registered version even
if it exists - it may be wrong (ie, for a different Python version)
"""
import win32api, regutil, string, os, sys
if possibleRealNames is None:
possibleRealNames = exeAlias
# Look first in Python's home.
found = os.path.join(sys.prefix, possibleRealNames)
if not FileExists(found): # for developers
if "64 bit" in sys.version:
found = os.path.join(sys.prefix, "PCBuild", "amd64", possibleRealNames)
else:
found = os.path.join(sys.prefix, "PCBuild", possibleRealNames)
if not FileExists(found):
found = LocateFileName(possibleRealNames, searchPaths)
registered_ok = 0
try:
registered = win32api.RegQueryValue(regutil.GetRootKey(), regutil.GetAppPathsKey() + "\\" + exeAlias)
registered_ok = found==registered
except win32api.error:
pass
return found, registered_ok | [
"def",
"FindPythonExe",
"(",
"exeAlias",
",",
"possibleRealNames",
",",
"searchPaths",
")",
":",
"import",
"win32api",
",",
"regutil",
",",
"string",
",",
"os",
",",
"sys",
"if",
"possibleRealNames",
"is",
"None",
":",
"possibleRealNames",
"=",
"exeAlias",
"# ... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/win32/scripts/regsetup.py#L102-L128 | |
Tencent/Pebble | 68315f176d9e328a233ace29b7579a829f89879f | tools/blade/src/blade/cc_targets.py | python | cc_benchmark | (name, deps=[], **kwargs) | cc_benchmark target. | cc_benchmark target. | [
"cc_benchmark",
"target",
"."
] | def cc_benchmark(name, deps=[], **kwargs):
"""cc_benchmark target. """
cc_config = configparse.blade_config.get_config('cc_config')
benchmark_libs = cc_config['benchmark_libs']
benchmark_main_libs = cc_config['benchmark_main_libs']
deps = var_to_list(deps) + benchmark_libs + benchmark_main_libs
cc_binary(name=name, deps=deps, **kwargs) | [
"def",
"cc_benchmark",
"(",
"name",
",",
"deps",
"=",
"[",
"]",
",",
"*",
"*",
"kwargs",
")",
":",
"cc_config",
"=",
"configparse",
".",
"blade_config",
".",
"get_config",
"(",
"'cc_config'",
")",
"benchmark_libs",
"=",
"cc_config",
"[",
"'benchmark_libs'",
... | https://github.com/Tencent/Pebble/blob/68315f176d9e328a233ace29b7579a829f89879f/tools/blade/src/blade/cc_targets.py#L893-L899 | ||
monero-project/monero | 9aab19f349433687c7aaf2c1cbc5751e5912c0aa | src/device_trezor/trezor/tools/py2backports/weakref.py | python | finalize.__call__ | (self, _=None) | If alive then mark as dead and return func(*args, **kwargs);
otherwise return None | If alive then mark as dead and return func(*args, **kwargs);
otherwise return None | [
"If",
"alive",
"then",
"mark",
"as",
"dead",
"and",
"return",
"func",
"(",
"*",
"args",
"**",
"kwargs",
")",
";",
"otherwise",
"return",
"None"
] | def __call__(self, _=None):
"""If alive then mark as dead and return func(*args, **kwargs);
otherwise return None"""
info = self._registry.pop(self, None)
if info and not self._shutdown:
return info.func(*info.args, **(info.kwargs or {})) | [
"def",
"__call__",
"(",
"self",
",",
"_",
"=",
"None",
")",
":",
"info",
"=",
"self",
".",
"_registry",
".",
"pop",
"(",
"self",
",",
"None",
")",
"if",
"info",
"and",
"not",
"self",
".",
"_shutdown",
":",
"return",
"info",
".",
"func",
"(",
"*",... | https://github.com/monero-project/monero/blob/9aab19f349433687c7aaf2c1cbc5751e5912c0aa/src/device_trezor/trezor/tools/py2backports/weakref.py#L59-L64 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.