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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
sdhash/sdhash | b9eff63e4e5867e910f41fd69032bbb1c94a2a5e | sdhash-ui/jinja2/lexer.py | python | TokenStream.next_if | (self, expr) | Perform the token test and return the token if it matched.
Otherwise the return value is `None`. | Perform the token test and return the token if it matched.
Otherwise the return value is `None`. | [
"Perform",
"the",
"token",
"test",
"and",
"return",
"the",
"token",
"if",
"it",
"matched",
".",
"Otherwise",
"the",
"return",
"value",
"is",
"None",
"."
] | def next_if(self, expr):
"""Perform the token test and return the token if it matched.
Otherwise the return value is `None`.
"""
if self.current.test(expr):
return next(self) | [
"def",
"next_if",
"(",
"self",
",",
"expr",
")",
":",
"if",
"self",
".",
"current",
".",
"test",
"(",
"expr",
")",
":",
"return",
"next",
"(",
"self",
")"
] | https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/jinja2/lexer.py#L325-L330 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/ops/control_flow_ops.py | python | merge | (inputs, name=None) | Returns the value of an available element of `inputs`.
This op tests each of the tensors in `inputs` in turn to determine if any of
them is available. If it finds an available tensor, it returns it and its
index in `inputs`.
It is an error if more than one tensor in `inputs` is available. If no tensor
in `inputs` is available, the returned tensor and index are not set.
This op handles both `Tensor`s and `IndexedSlices`. If inputs has a mix of
`Tensor`s and `IndexedSlices`, all inputs are converted to IndexedSlices
before merging.
Args:
inputs: The input tensors, at most one of which is available.
name: A name for this operation (optional).
Returns:
A tuple containing the chosen input tensor and its index in `inputs`.
Raises:
ValueError: If any of the inputs is None, or inputs are IndexedSlices and
some but not all have a dense_shape property. | Returns the value of an available element of `inputs`. | [
"Returns",
"the",
"value",
"of",
"an",
"available",
"element",
"of",
"inputs",
"."
] | def merge(inputs, name=None):
"""Returns the value of an available element of `inputs`.
This op tests each of the tensors in `inputs` in turn to determine if any of
them is available. If it finds an available tensor, it returns it and its
index in `inputs`.
It is an error if more than one tensor in `inputs` is available. If no tensor
in `inputs` is available, the returned tensor and index are not set.
This op handles both `Tensor`s and `IndexedSlices`. If inputs has a mix of
`Tensor`s and `IndexedSlices`, all inputs are converted to IndexedSlices
before merging.
Args:
inputs: The input tensors, at most one of which is available.
name: A name for this operation (optional).
Returns:
A tuple containing the chosen input tensor and its index in `inputs`.
Raises:
ValueError: If any of the inputs is None, or inputs are IndexedSlices and
some but not all have a dense_shape property.
"""
if any([inp is None for inp in inputs]):
raise ValueError("At least one of the merge inputs is None: %s" % inputs)
with ops.name_scope(name, "Merge", inputs) as name:
inputs = [ops.internal_convert_to_tensor_or_indexed_slices(inp, as_ref=True)
for inp in inputs]
if all([isinstance(v, ops.Tensor) for v in inputs]):
if all([v.dtype._is_ref_dtype for v in inputs]): # pylint: disable=protected-access
return gen_control_flow_ops._ref_merge(inputs, name)
else:
return gen_control_flow_ops._merge(inputs, name)
elif all([isinstance(v, sparse_tensor.SparseTensor) for v in inputs]):
# Only handle the case when all inputs are SparseTensor.
values, _ = merge([inp.values for inp in inputs], name=name)
indices, chosen_index = gen_control_flow_ops._merge(
[inp.indices for inp in inputs], name="indices")
dense_shape, _ = gen_control_flow_ops._merge(
[inp.dense_shape for inp in inputs], name="dense_shape")
return (sparse_tensor.SparseTensor(indices, values, dense_shape),
chosen_index)
else:
# For now convert all the inputs as IndexedSlices.
inputs = math_ops._as_indexed_slices_list(inputs, optimize=False)
values, _ = merge([inp.values for inp in inputs], name=name)
indices, chosen_index = gen_control_flow_ops._merge(
[inp.indices for inp in inputs], name="indices")
if any(inp.dense_shape is not None for inp in inputs):
if any(inp.dense_shape is None for inp in inputs):
raise ValueError("Either all merged IndexedSlices must have a "
"dense_shape, or none must have a dense_shape.")
dense_shape, _ = gen_control_flow_ops._merge(
[inp.dense_shape for inp in inputs], name="dense_shape")
else:
dense_shape = None
return ops.IndexedSlices(values, indices, dense_shape), chosen_index | [
"def",
"merge",
"(",
"inputs",
",",
"name",
"=",
"None",
")",
":",
"if",
"any",
"(",
"[",
"inp",
"is",
"None",
"for",
"inp",
"in",
"inputs",
"]",
")",
":",
"raise",
"ValueError",
"(",
"\"At least one of the merge inputs is None: %s\"",
"%",
"inputs",
")",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"\"Merge\"",
",",
"inputs",
")",
"as",
"name",
":",
"inputs",
"=",
"[",
"ops",
".",
"internal_convert_to_tensor_or_indexed_slices",
"(",
"inp",
",",
"as_ref",
"=",
"True",
")",
"for",
"inp",
"in",
"inputs",
"]",
"if",
"all",
"(",
"[",
"isinstance",
"(",
"v",
",",
"ops",
".",
"Tensor",
")",
"for",
"v",
"in",
"inputs",
"]",
")",
":",
"if",
"all",
"(",
"[",
"v",
".",
"dtype",
".",
"_is_ref_dtype",
"for",
"v",
"in",
"inputs",
"]",
")",
":",
"# pylint: disable=protected-access",
"return",
"gen_control_flow_ops",
".",
"_ref_merge",
"(",
"inputs",
",",
"name",
")",
"else",
":",
"return",
"gen_control_flow_ops",
".",
"_merge",
"(",
"inputs",
",",
"name",
")",
"elif",
"all",
"(",
"[",
"isinstance",
"(",
"v",
",",
"sparse_tensor",
".",
"SparseTensor",
")",
"for",
"v",
"in",
"inputs",
"]",
")",
":",
"# Only handle the case when all inputs are SparseTensor.",
"values",
",",
"_",
"=",
"merge",
"(",
"[",
"inp",
".",
"values",
"for",
"inp",
"in",
"inputs",
"]",
",",
"name",
"=",
"name",
")",
"indices",
",",
"chosen_index",
"=",
"gen_control_flow_ops",
".",
"_merge",
"(",
"[",
"inp",
".",
"indices",
"for",
"inp",
"in",
"inputs",
"]",
",",
"name",
"=",
"\"indices\"",
")",
"dense_shape",
",",
"_",
"=",
"gen_control_flow_ops",
".",
"_merge",
"(",
"[",
"inp",
".",
"dense_shape",
"for",
"inp",
"in",
"inputs",
"]",
",",
"name",
"=",
"\"dense_shape\"",
")",
"return",
"(",
"sparse_tensor",
".",
"SparseTensor",
"(",
"indices",
",",
"values",
",",
"dense_shape",
")",
",",
"chosen_index",
")",
"else",
":",
"# For now convert all the inputs as IndexedSlices.",
"inputs",
"=",
"math_ops",
".",
"_as_indexed_slices_list",
"(",
"inputs",
",",
"optimize",
"=",
"False",
")",
"values",
",",
"_",
"=",
"merge",
"(",
"[",
"inp",
".",
"values",
"for",
"inp",
"in",
"inputs",
"]",
",",
"name",
"=",
"name",
")",
"indices",
",",
"chosen_index",
"=",
"gen_control_flow_ops",
".",
"_merge",
"(",
"[",
"inp",
".",
"indices",
"for",
"inp",
"in",
"inputs",
"]",
",",
"name",
"=",
"\"indices\"",
")",
"if",
"any",
"(",
"inp",
".",
"dense_shape",
"is",
"not",
"None",
"for",
"inp",
"in",
"inputs",
")",
":",
"if",
"any",
"(",
"inp",
".",
"dense_shape",
"is",
"None",
"for",
"inp",
"in",
"inputs",
")",
":",
"raise",
"ValueError",
"(",
"\"Either all merged IndexedSlices must have a \"",
"\"dense_shape, or none must have a dense_shape.\"",
")",
"dense_shape",
",",
"_",
"=",
"gen_control_flow_ops",
".",
"_merge",
"(",
"[",
"inp",
".",
"dense_shape",
"for",
"inp",
"in",
"inputs",
"]",
",",
"name",
"=",
"\"dense_shape\"",
")",
"else",
":",
"dense_shape",
"=",
"None",
"return",
"ops",
".",
"IndexedSlices",
"(",
"values",
",",
"indices",
",",
"dense_shape",
")",
",",
"chosen_index"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/control_flow_ops.py#L370-L428 | ||
epam/Indigo | 30e40b4b1eb9bae0207435a26cfcb81ddcc42be1 | api/python/indigo/__init__.py | python | Indigo.loadSmartsFromFile | (self, filename) | return self.IndigoObject(
self,
self._checkResult(
Indigo._lib.indigoLoadSmartsFromFile(
filename.encode(ENCODE_ENCODING)
)
),
) | Loads query molecule from file in SMARTS format
Args:
filename (str): full path to the file with smarts strings
Returns:
IndigoObject: loaded query molecular structure
Raises:
IndigoException: Exception if structure format is incorrect | Loads query molecule from file in SMARTS format | [
"Loads",
"query",
"molecule",
"from",
"file",
"in",
"SMARTS",
"format"
] | def loadSmartsFromFile(self, filename):
"""Loads query molecule from file in SMARTS format
Args:
filename (str): full path to the file with smarts strings
Returns:
IndigoObject: loaded query molecular structure
Raises:
IndigoException: Exception if structure format is incorrect
"""
self._setSessionId()
return self.IndigoObject(
self,
self._checkResult(
Indigo._lib.indigoLoadSmartsFromFile(
filename.encode(ENCODE_ENCODING)
)
),
) | [
"def",
"loadSmartsFromFile",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"_setSessionId",
"(",
")",
"return",
"self",
".",
"IndigoObject",
"(",
"self",
",",
"self",
".",
"_checkResult",
"(",
"Indigo",
".",
"_lib",
".",
"indigoLoadSmartsFromFile",
"(",
"filename",
".",
"encode",
"(",
"ENCODE_ENCODING",
")",
")",
")",
",",
")"
] | https://github.com/epam/Indigo/blob/30e40b4b1eb9bae0207435a26cfcb81ddcc42be1/api/python/indigo/__init__.py#L5634-L5654 | |
francinexue/xuefu | b6ff79747a42e020588c0c0a921048e08fe4680c | api/ctpx/ctptd.py | python | CtpTd.onRspUserLogin | (self, RspUserLoginField, RspInfoField, requestId, final) | 登录请求响应 | 登录请求响应 | [
"登录请求响应"
] | def onRspUserLogin(self, RspUserLoginField, RspInfoField, requestId, final):
"""登录请求响应"""
logger.debug("sessionID:{}".format(RspUserLoginField.sessionID))
if RspInfoField.errorID == 0:
self.frontID = RspUserLoginField.frontID
self.sessionID = RspUserLoginField.sessionID
logger.debug("orderRef: {}".format(RspUserLoginField.maxOrderRef))
self._orderRef = (int)(RspUserLoginField.maxOrderRef)
log = u'交易服务器登陆成功'
settlementInfoConfirmField = td.SettlementInfoConfirmField()
settlementInfoConfirmField.brokerID = self._brokerID
settlementInfoConfirmField.investorID = self._userID
self._requestId += 1
self.reqSettlementInfoConfirm(settlementInfoConfirmField, self._requestId)
for listener in self._barEventListeners:
listener.onRspUserLogin(RspUserLoginField)
else:
log = u'交易服务登陆失败,错误码:{0}, 错误信息:{1}'.format(
RspInfoField.errorID, RspInfoField.errorMsg.decode('gbk'))
logger.debug(log) | [
"def",
"onRspUserLogin",
"(",
"self",
",",
"RspUserLoginField",
",",
"RspInfoField",
",",
"requestId",
",",
"final",
")",
":",
"logger",
".",
"debug",
"(",
"\"sessionID:{}\"",
".",
"format",
"(",
"RspUserLoginField",
".",
"sessionID",
")",
")",
"if",
"RspInfoField",
".",
"errorID",
"==",
"0",
":",
"self",
".",
"frontID",
"=",
"RspUserLoginField",
".",
"frontID",
"self",
".",
"sessionID",
"=",
"RspUserLoginField",
".",
"sessionID",
"logger",
".",
"debug",
"(",
"\"orderRef: {}\"",
".",
"format",
"(",
"RspUserLoginField",
".",
"maxOrderRef",
")",
")",
"self",
".",
"_orderRef",
"=",
"(",
"int",
")",
"(",
"RspUserLoginField",
".",
"maxOrderRef",
")",
"log",
"=",
"u'交易服务器登陆成功'",
"settlementInfoConfirmField",
"=",
"td",
".",
"SettlementInfoConfirmField",
"(",
")",
"settlementInfoConfirmField",
".",
"brokerID",
"=",
"self",
".",
"_brokerID",
"settlementInfoConfirmField",
".",
"investorID",
"=",
"self",
".",
"_userID",
"self",
".",
"_requestId",
"+=",
"1",
"self",
".",
"reqSettlementInfoConfirm",
"(",
"settlementInfoConfirmField",
",",
"self",
".",
"_requestId",
")",
"for",
"listener",
"in",
"self",
".",
"_barEventListeners",
":",
"listener",
".",
"onRspUserLogin",
"(",
"RspUserLoginField",
")",
"else",
":",
"log",
"=",
"u'交易服务登陆失败,错误码:{0}, 错误信息:{1}'.format(",
"",
"",
"",
"RspInfoField",
".",
"errorID",
",",
"RspInfoField",
".",
"errorMsg",
".",
"decode",
"(",
"'gbk'",
")",
")",
"logger",
".",
"debug",
"(",
"log",
")"
] | https://github.com/francinexue/xuefu/blob/b6ff79747a42e020588c0c0a921048e08fe4680c/api/ctpx/ctptd.py#L55-L74 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ebmlib/fileutil.py | python | IsHidden | (path) | return bHidden | Is the path a hidden path
@param path: path to check
@return: bool | Is the path a hidden path
@param path: path to check
@return: bool | [
"Is",
"the",
"path",
"a",
"hidden",
"path",
"@param",
"path",
":",
"path",
"to",
"check",
"@return",
":",
"bool"
] | def IsHidden(path):
"""Is the path a hidden path
@param path: path to check
@return: bool
"""
bHidden = False
if PathExists(path):
if WIN:
try:
attrs = ctypes.windll.kernel32.GetFileAttributesW(path)
assert attrs != -1
bHidden = bool(attrs & 2)
except (AttributeError, AssertionError):
bHidden = False
else:
dname = GetFileName(path)
bHidden = dname.startswith('.')
return bHidden | [
"def",
"IsHidden",
"(",
"path",
")",
":",
"bHidden",
"=",
"False",
"if",
"PathExists",
"(",
"path",
")",
":",
"if",
"WIN",
":",
"try",
":",
"attrs",
"=",
"ctypes",
".",
"windll",
".",
"kernel32",
".",
"GetFileAttributesW",
"(",
"path",
")",
"assert",
"attrs",
"!=",
"-",
"1",
"bHidden",
"=",
"bool",
"(",
"attrs",
"&",
"2",
")",
"except",
"(",
"AttributeError",
",",
"AssertionError",
")",
":",
"bHidden",
"=",
"False",
"else",
":",
"dname",
"=",
"GetFileName",
"(",
"path",
")",
"bHidden",
"=",
"dname",
".",
"startswith",
"(",
"'.'",
")",
"return",
"bHidden"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ebmlib/fileutil.py#L218-L236 | |
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/build/android/gyp/extract_unwind_tables.py | python | _WriteCfiData | (cfi_data, out_file) | Writes the CFI data in defined format to out_file. | Writes the CFI data in defined format to out_file. | [
"Writes",
"the",
"CFI",
"data",
"in",
"defined",
"format",
"to",
"out_file",
"."
] | def _WriteCfiData(cfi_data, out_file):
"""Writes the CFI data in defined format to out_file."""
# Stores the final data that will be written to UNW_DATA table, in order
# with 2 byte items.
unw_data = []
# Represent all the CFI data of functions as set of numbers and map them to an
# index in the |unw_data|. This index is later written to the UNW_INDEX table
# for each function. This map is used to find index of the data for functions.
data_to_index = {}
# Store mapping between the functions to the index.
func_addr_to_index = {}
previous_func_end = 0
for addr, function in sorted(cfi_data.items()):
# Add an empty function entry when functions CFIs are missing between 2
# functions.
if previous_func_end != 0 and addr - previous_func_end > 4:
func_addr_to_index[previous_func_end + 2] = _CANT_UNWIND
previous_func_end = addr + cfi_data[addr][0][_LENGTH_ENTRY]
assert len(function) > 1
func_data_arr = []
func_data = 0
# The first row contains the function address and length. The rest of the
# rows have CFI data. Create function data array as given in the format.
for row in function[1:]:
addr_offset = row[_ADDR_ENTRY] - addr
cfa_offset = (row[_CFA_REG]) | (row[_RA_REG] // 4)
func_data_arr.append(addr_offset)
func_data_arr.append(cfa_offset)
# Consider all the rows in the data as one large integer and add it as a key
# to the |data_to_index|.
for data in func_data_arr:
func_data = (func_data << 16) | data
row_count = len(func_data_arr) // 2
if func_data not in data_to_index:
# When data is not found, create a new index = len(unw_data), and write
# the data to |unw_data|.
index = len(unw_data)
data_to_index[func_data] = index
unw_data.append(row_count)
for row in func_data_arr:
unw_data.append(row)
else:
# If the data was found, then use the same index for the function.
index = data_to_index[func_data]
assert row_count == unw_data[index]
func_addr_to_index[addr] = data_to_index[func_data]
# Mark the end end of last function entry.
func_addr_to_index[previous_func_end + 2] = _CANT_UNWIND
# Write the size of UNW_INDEX file in bytes.
_Write4Bytes(out_file, len(func_addr_to_index))
# Write the UNW_INDEX table. First list of addresses and then indices.
sorted_unw_index = sorted(func_addr_to_index.items())
for addr, index in sorted_unw_index:
_Write4Bytes(out_file, addr)
for addr, index in sorted_unw_index:
_Write2Bytes(out_file, index)
# Write the UNW_DATA table.
for data in unw_data:
_Write2Bytes(out_file, data) | [
"def",
"_WriteCfiData",
"(",
"cfi_data",
",",
"out_file",
")",
":",
"# Stores the final data that will be written to UNW_DATA table, in order",
"# with 2 byte items.",
"unw_data",
"=",
"[",
"]",
"# Represent all the CFI data of functions as set of numbers and map them to an",
"# index in the |unw_data|. This index is later written to the UNW_INDEX table",
"# for each function. This map is used to find index of the data for functions.",
"data_to_index",
"=",
"{",
"}",
"# Store mapping between the functions to the index.",
"func_addr_to_index",
"=",
"{",
"}",
"previous_func_end",
"=",
"0",
"for",
"addr",
",",
"function",
"in",
"sorted",
"(",
"cfi_data",
".",
"items",
"(",
")",
")",
":",
"# Add an empty function entry when functions CFIs are missing between 2",
"# functions.",
"if",
"previous_func_end",
"!=",
"0",
"and",
"addr",
"-",
"previous_func_end",
">",
"4",
":",
"func_addr_to_index",
"[",
"previous_func_end",
"+",
"2",
"]",
"=",
"_CANT_UNWIND",
"previous_func_end",
"=",
"addr",
"+",
"cfi_data",
"[",
"addr",
"]",
"[",
"0",
"]",
"[",
"_LENGTH_ENTRY",
"]",
"assert",
"len",
"(",
"function",
")",
">",
"1",
"func_data_arr",
"=",
"[",
"]",
"func_data",
"=",
"0",
"# The first row contains the function address and length. The rest of the",
"# rows have CFI data. Create function data array as given in the format.",
"for",
"row",
"in",
"function",
"[",
"1",
":",
"]",
":",
"addr_offset",
"=",
"row",
"[",
"_ADDR_ENTRY",
"]",
"-",
"addr",
"cfa_offset",
"=",
"(",
"row",
"[",
"_CFA_REG",
"]",
")",
"|",
"(",
"row",
"[",
"_RA_REG",
"]",
"//",
"4",
")",
"func_data_arr",
".",
"append",
"(",
"addr_offset",
")",
"func_data_arr",
".",
"append",
"(",
"cfa_offset",
")",
"# Consider all the rows in the data as one large integer and add it as a key",
"# to the |data_to_index|.",
"for",
"data",
"in",
"func_data_arr",
":",
"func_data",
"=",
"(",
"func_data",
"<<",
"16",
")",
"|",
"data",
"row_count",
"=",
"len",
"(",
"func_data_arr",
")",
"//",
"2",
"if",
"func_data",
"not",
"in",
"data_to_index",
":",
"# When data is not found, create a new index = len(unw_data), and write",
"# the data to |unw_data|.",
"index",
"=",
"len",
"(",
"unw_data",
")",
"data_to_index",
"[",
"func_data",
"]",
"=",
"index",
"unw_data",
".",
"append",
"(",
"row_count",
")",
"for",
"row",
"in",
"func_data_arr",
":",
"unw_data",
".",
"append",
"(",
"row",
")",
"else",
":",
"# If the data was found, then use the same index for the function.",
"index",
"=",
"data_to_index",
"[",
"func_data",
"]",
"assert",
"row_count",
"==",
"unw_data",
"[",
"index",
"]",
"func_addr_to_index",
"[",
"addr",
"]",
"=",
"data_to_index",
"[",
"func_data",
"]",
"# Mark the end end of last function entry.",
"func_addr_to_index",
"[",
"previous_func_end",
"+",
"2",
"]",
"=",
"_CANT_UNWIND",
"# Write the size of UNW_INDEX file in bytes.",
"_Write4Bytes",
"(",
"out_file",
",",
"len",
"(",
"func_addr_to_index",
")",
")",
"# Write the UNW_INDEX table. First list of addresses and then indices.",
"sorted_unw_index",
"=",
"sorted",
"(",
"func_addr_to_index",
".",
"items",
"(",
")",
")",
"for",
"addr",
",",
"index",
"in",
"sorted_unw_index",
":",
"_Write4Bytes",
"(",
"out_file",
",",
"addr",
")",
"for",
"addr",
",",
"index",
"in",
"sorted_unw_index",
":",
"_Write2Bytes",
"(",
"out_file",
",",
"index",
")",
"# Write the UNW_DATA table.",
"for",
"data",
"in",
"unw_data",
":",
"_Write2Bytes",
"(",
"out_file",
",",
"data",
")"
] | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/android/gyp/extract_unwind_tables.py#L188-L255 | ||
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/traci/_poi.py | python | PoiDomain.getImageFile | (self, poiID) | return self._getUniversal(tc.VAR_IMAGEFILE, poiID) | getImageFile(string) -> string
Returns the image file of the given poi. | getImageFile(string) -> string | [
"getImageFile",
"(",
"string",
")",
"-",
">",
"string"
] | def getImageFile(self, poiID):
"""getImageFile(string) -> string
Returns the image file of the given poi.
"""
return self._getUniversal(tc.VAR_IMAGEFILE, poiID) | [
"def",
"getImageFile",
"(",
"self",
",",
"poiID",
")",
":",
"return",
"self",
".",
"_getUniversal",
"(",
"tc",
".",
"VAR_IMAGEFILE",
",",
"poiID",
")"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_poi.py#L74-L79 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/random.py | python | Random.betavariate | (self, alpha, beta) | Beta distribution.
Conditions on the parameters are alpha > 0 and beta > 0.
Returned values range between 0 and 1. | Beta distribution. | [
"Beta",
"distribution",
"."
] | def betavariate(self, alpha, beta):
"""Beta distribution.
Conditions on the parameters are alpha > 0 and beta > 0.
Returned values range between 0 and 1.
"""
# This version due to Janne Sinkkonen, and matches all the std
# texts (e.g., Knuth Vol 2 Ed 3 pg 134 "the beta distribution").
y = self.gammavariate(alpha, 1.0)
if y == 0:
return 0.0
else:
return y / (y + self.gammavariate(beta, 1.0)) | [
"def",
"betavariate",
"(",
"self",
",",
"alpha",
",",
"beta",
")",
":",
"# This version due to Janne Sinkkonen, and matches all the std",
"# texts (e.g., Knuth Vol 2 Ed 3 pg 134 \"the beta distribution\").",
"y",
"=",
"self",
".",
"gammavariate",
"(",
"alpha",
",",
"1.0",
")",
"if",
"y",
"==",
"0",
":",
"return",
"0.0",
"else",
":",
"return",
"y",
"/",
"(",
"y",
"+",
"self",
".",
"gammavariate",
"(",
"beta",
",",
"1.0",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/random.py#L629-L643 | ||
metashell/metashell | f4177e4854ea00c8dbc722cadab26ef413d798ea | 3rd/templight/clang/bindings/python/clang/cindex.py | python | TranslationUnit.get_location | (self, filename, position) | return SourceLocation.from_position(self, f, position[0], position[1]) | Obtain a SourceLocation for a file in this translation unit.
The position can be specified by passing:
- Integer file offset. Initial file offset is 0.
- 2-tuple of (line number, column number). Initial file position is
(0, 0) | Obtain a SourceLocation for a file in this translation unit. | [
"Obtain",
"a",
"SourceLocation",
"for",
"a",
"file",
"in",
"this",
"translation",
"unit",
"."
] | def get_location(self, filename, position):
"""Obtain a SourceLocation for a file in this translation unit.
The position can be specified by passing:
- Integer file offset. Initial file offset is 0.
- 2-tuple of (line number, column number). Initial file position is
(0, 0)
"""
f = self.get_file(filename)
if isinstance(position, int):
return SourceLocation.from_offset(self, f, position)
return SourceLocation.from_position(self, f, position[0], position[1]) | [
"def",
"get_location",
"(",
"self",
",",
"filename",
",",
"position",
")",
":",
"f",
"=",
"self",
".",
"get_file",
"(",
"filename",
")",
"if",
"isinstance",
"(",
"position",
",",
"int",
")",
":",
"return",
"SourceLocation",
".",
"from_offset",
"(",
"self",
",",
"f",
",",
"position",
")",
"return",
"SourceLocation",
".",
"from_position",
"(",
"self",
",",
"f",
",",
"position",
"[",
"0",
"]",
",",
"position",
"[",
"1",
"]",
")"
] | https://github.com/metashell/metashell/blob/f4177e4854ea00c8dbc722cadab26ef413d798ea/3rd/templight/clang/bindings/python/clang/cindex.py#L2912-L2926 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/lambda-code/SanitizationLambda/sanitization_lambda.py | python | Sanitizer.__validate_mime_type | (self, key, content_type) | Validates mime type is of expected type. | Validates mime type is of expected type. | [
"Validates",
"mime",
"type",
"is",
"of",
"expected",
"type",
"."
] | def __validate_mime_type(self, key, content_type):
''' Validates mime type is of expected type. '''
if content_type in (constants.MIME_TYPE_IMAGE_JPEG, constants.MIME_TYPE_TEXT_PLAIN, constants.MIME_TYPE_IMAGE_PNG):
return True
else:
self.rejected_files.append(FileStatus(key, False, "Content-type not valid. (Mime)", ''))
return False | [
"def",
"__validate_mime_type",
"(",
"self",
",",
"key",
",",
"content_type",
")",
":",
"if",
"content_type",
"in",
"(",
"constants",
".",
"MIME_TYPE_IMAGE_JPEG",
",",
"constants",
".",
"MIME_TYPE_TEXT_PLAIN",
",",
"constants",
".",
"MIME_TYPE_IMAGE_PNG",
")",
":",
"return",
"True",
"else",
":",
"self",
".",
"rejected_files",
".",
"append",
"(",
"FileStatus",
"(",
"key",
",",
"False",
",",
"\"Content-type not valid. (Mime)\"",
",",
"''",
")",
")",
"return",
"False"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/lambda-code/SanitizationLambda/sanitization_lambda.py#L242-L249 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/tools/gyp/pylib/gyp/xcode_emulation.py | python | XcodeSettings.GetCflags | (self, configname, arch=None) | return cflags | Returns flags that need to be added to .c, .cc, .m, and .mm
compilations. | Returns flags that need to be added to .c, .cc, .m, and .mm
compilations. | [
"Returns",
"flags",
"that",
"need",
"to",
"be",
"added",
"to",
".",
"c",
".",
"cc",
".",
"m",
"and",
".",
"mm",
"compilations",
"."
] | def GetCflags(self, configname, arch=None):
"""Returns flags that need to be added to .c, .cc, .m, and .mm
compilations."""
# This functions (and the similar ones below) do not offer complete
# emulation of all xcode_settings keys. They're implemented on demand.
self.configname = configname
cflags = []
sdk_root = self._SdkPath()
if 'SDKROOT' in self._Settings() and sdk_root:
cflags.append('-isysroot %s' % sdk_root)
if self.header_map_path:
cflags.append('-I%s' % self.header_map_path)
if self._Test('CLANG_WARN_CONSTANT_CONVERSION', 'YES', default='NO'):
cflags.append('-Wconstant-conversion')
if self._Test('GCC_CHAR_IS_UNSIGNED_CHAR', 'YES', default='NO'):
cflags.append('-funsigned-char')
if self._Test('GCC_CW_ASM_SYNTAX', 'YES', default='YES'):
cflags.append('-fasm-blocks')
if 'GCC_DYNAMIC_NO_PIC' in self._Settings():
if self._Settings()['GCC_DYNAMIC_NO_PIC'] == 'YES':
cflags.append('-mdynamic-no-pic')
else:
pass
# TODO: In this case, it depends on the target. xcode passes
# mdynamic-no-pic by default for executable and possibly static lib
# according to mento
if self._Test('GCC_ENABLE_PASCAL_STRINGS', 'YES', default='YES'):
cflags.append('-mpascal-strings')
self._Appendf(cflags, 'GCC_OPTIMIZATION_LEVEL', '-O%s', default='s')
if self._Test('GCC_GENERATE_DEBUGGING_SYMBOLS', 'YES', default='YES'):
dbg_format = self._Settings().get('DEBUG_INFORMATION_FORMAT', 'dwarf')
if dbg_format == 'dwarf':
cflags.append('-gdwarf-2')
elif dbg_format == 'stabs':
raise NotImplementedError('stabs debug format is not supported yet.')
elif dbg_format == 'dwarf-with-dsym':
cflags.append('-gdwarf-2')
else:
raise NotImplementedError('Unknown debug format %s' % dbg_format)
if self._Settings().get('GCC_STRICT_ALIASING') == 'YES':
cflags.append('-fstrict-aliasing')
elif self._Settings().get('GCC_STRICT_ALIASING') == 'NO':
cflags.append('-fno-strict-aliasing')
if self._Test('GCC_SYMBOLS_PRIVATE_EXTERN', 'YES', default='NO'):
cflags.append('-fvisibility=hidden')
if self._Test('GCC_TREAT_WARNINGS_AS_ERRORS', 'YES', default='NO'):
cflags.append('-Werror')
if self._Test('GCC_WARN_ABOUT_MISSING_NEWLINE', 'YES', default='NO'):
cflags.append('-Wnewline-eof')
# In Xcode, this is only activated when GCC_COMPILER_VERSION is clang or
# llvm-gcc. It also requires a fairly recent libtool, and
# if the system clang isn't used, DYLD_LIBRARY_PATH needs to contain the
# path to the libLTO.dylib that matches the used clang.
if self._Test('LLVM_LTO', 'YES', default='NO'):
cflags.append('-flto')
self._AppendPlatformVersionMinFlags(cflags)
# TODO:
if self._Test('COPY_PHASE_STRIP', 'YES', default='NO'):
self._WarnUnimplemented('COPY_PHASE_STRIP')
self._WarnUnimplemented('GCC_DEBUGGING_SYMBOLS')
self._WarnUnimplemented('GCC_ENABLE_OBJC_EXCEPTIONS')
# TODO: This is exported correctly, but assigning to it is not supported.
self._WarnUnimplemented('MACH_O_TYPE')
self._WarnUnimplemented('PRODUCT_TYPE')
if arch is not None:
archs = [arch]
else:
assert self.configname
archs = self.GetActiveArchs(self.configname)
if len(archs) != 1:
# TODO: Supporting fat binaries will be annoying.
self._WarnUnimplemented('ARCHS')
archs = ['i386']
cflags.append('-arch ' + archs[0])
if archs[0] in ('i386', 'x86_64'):
if self._Test('GCC_ENABLE_SSE3_EXTENSIONS', 'YES', default='NO'):
cflags.append('-msse3')
if self._Test('GCC_ENABLE_SUPPLEMENTAL_SSE3_INSTRUCTIONS', 'YES',
default='NO'):
cflags.append('-mssse3') # Note 3rd 's'.
if self._Test('GCC_ENABLE_SSE41_EXTENSIONS', 'YES', default='NO'):
cflags.append('-msse4.1')
if self._Test('GCC_ENABLE_SSE42_EXTENSIONS', 'YES', default='NO'):
cflags.append('-msse4.2')
cflags += self._Settings().get('WARNING_CFLAGS', [])
if self._IsXCTest():
platform_root = self._XcodePlatformPath(configname)
if platform_root:
cflags.append('-F' + platform_root + '/Developer/Library/Frameworks/')
if sdk_root:
framework_root = sdk_root
else:
framework_root = ''
config = self.spec['configurations'][self.configname]
framework_dirs = config.get('mac_framework_dirs', [])
for directory in framework_dirs:
cflags.append('-F' + directory.replace('$(SDKROOT)', framework_root))
self.configname = None
return cflags | [
"def",
"GetCflags",
"(",
"self",
",",
"configname",
",",
"arch",
"=",
"None",
")",
":",
"# This functions (and the similar ones below) do not offer complete",
"# emulation of all xcode_settings keys. They're implemented on demand.",
"self",
".",
"configname",
"=",
"configname",
"cflags",
"=",
"[",
"]",
"sdk_root",
"=",
"self",
".",
"_SdkPath",
"(",
")",
"if",
"'SDKROOT'",
"in",
"self",
".",
"_Settings",
"(",
")",
"and",
"sdk_root",
":",
"cflags",
".",
"append",
"(",
"'-isysroot %s'",
"%",
"sdk_root",
")",
"if",
"self",
".",
"header_map_path",
":",
"cflags",
".",
"append",
"(",
"'-I%s'",
"%",
"self",
".",
"header_map_path",
")",
"if",
"self",
".",
"_Test",
"(",
"'CLANG_WARN_CONSTANT_CONVERSION'",
",",
"'YES'",
",",
"default",
"=",
"'NO'",
")",
":",
"cflags",
".",
"append",
"(",
"'-Wconstant-conversion'",
")",
"if",
"self",
".",
"_Test",
"(",
"'GCC_CHAR_IS_UNSIGNED_CHAR'",
",",
"'YES'",
",",
"default",
"=",
"'NO'",
")",
":",
"cflags",
".",
"append",
"(",
"'-funsigned-char'",
")",
"if",
"self",
".",
"_Test",
"(",
"'GCC_CW_ASM_SYNTAX'",
",",
"'YES'",
",",
"default",
"=",
"'YES'",
")",
":",
"cflags",
".",
"append",
"(",
"'-fasm-blocks'",
")",
"if",
"'GCC_DYNAMIC_NO_PIC'",
"in",
"self",
".",
"_Settings",
"(",
")",
":",
"if",
"self",
".",
"_Settings",
"(",
")",
"[",
"'GCC_DYNAMIC_NO_PIC'",
"]",
"==",
"'YES'",
":",
"cflags",
".",
"append",
"(",
"'-mdynamic-no-pic'",
")",
"else",
":",
"pass",
"# TODO: In this case, it depends on the target. xcode passes",
"# mdynamic-no-pic by default for executable and possibly static lib",
"# according to mento",
"if",
"self",
".",
"_Test",
"(",
"'GCC_ENABLE_PASCAL_STRINGS'",
",",
"'YES'",
",",
"default",
"=",
"'YES'",
")",
":",
"cflags",
".",
"append",
"(",
"'-mpascal-strings'",
")",
"self",
".",
"_Appendf",
"(",
"cflags",
",",
"'GCC_OPTIMIZATION_LEVEL'",
",",
"'-O%s'",
",",
"default",
"=",
"'s'",
")",
"if",
"self",
".",
"_Test",
"(",
"'GCC_GENERATE_DEBUGGING_SYMBOLS'",
",",
"'YES'",
",",
"default",
"=",
"'YES'",
")",
":",
"dbg_format",
"=",
"self",
".",
"_Settings",
"(",
")",
".",
"get",
"(",
"'DEBUG_INFORMATION_FORMAT'",
",",
"'dwarf'",
")",
"if",
"dbg_format",
"==",
"'dwarf'",
":",
"cflags",
".",
"append",
"(",
"'-gdwarf-2'",
")",
"elif",
"dbg_format",
"==",
"'stabs'",
":",
"raise",
"NotImplementedError",
"(",
"'stabs debug format is not supported yet.'",
")",
"elif",
"dbg_format",
"==",
"'dwarf-with-dsym'",
":",
"cflags",
".",
"append",
"(",
"'-gdwarf-2'",
")",
"else",
":",
"raise",
"NotImplementedError",
"(",
"'Unknown debug format %s'",
"%",
"dbg_format",
")",
"if",
"self",
".",
"_Settings",
"(",
")",
".",
"get",
"(",
"'GCC_STRICT_ALIASING'",
")",
"==",
"'YES'",
":",
"cflags",
".",
"append",
"(",
"'-fstrict-aliasing'",
")",
"elif",
"self",
".",
"_Settings",
"(",
")",
".",
"get",
"(",
"'GCC_STRICT_ALIASING'",
")",
"==",
"'NO'",
":",
"cflags",
".",
"append",
"(",
"'-fno-strict-aliasing'",
")",
"if",
"self",
".",
"_Test",
"(",
"'GCC_SYMBOLS_PRIVATE_EXTERN'",
",",
"'YES'",
",",
"default",
"=",
"'NO'",
")",
":",
"cflags",
".",
"append",
"(",
"'-fvisibility=hidden'",
")",
"if",
"self",
".",
"_Test",
"(",
"'GCC_TREAT_WARNINGS_AS_ERRORS'",
",",
"'YES'",
",",
"default",
"=",
"'NO'",
")",
":",
"cflags",
".",
"append",
"(",
"'-Werror'",
")",
"if",
"self",
".",
"_Test",
"(",
"'GCC_WARN_ABOUT_MISSING_NEWLINE'",
",",
"'YES'",
",",
"default",
"=",
"'NO'",
")",
":",
"cflags",
".",
"append",
"(",
"'-Wnewline-eof'",
")",
"# In Xcode, this is only activated when GCC_COMPILER_VERSION is clang or",
"# llvm-gcc. It also requires a fairly recent libtool, and",
"# if the system clang isn't used, DYLD_LIBRARY_PATH needs to contain the",
"# path to the libLTO.dylib that matches the used clang.",
"if",
"self",
".",
"_Test",
"(",
"'LLVM_LTO'",
",",
"'YES'",
",",
"default",
"=",
"'NO'",
")",
":",
"cflags",
".",
"append",
"(",
"'-flto'",
")",
"self",
".",
"_AppendPlatformVersionMinFlags",
"(",
"cflags",
")",
"# TODO:",
"if",
"self",
".",
"_Test",
"(",
"'COPY_PHASE_STRIP'",
",",
"'YES'",
",",
"default",
"=",
"'NO'",
")",
":",
"self",
".",
"_WarnUnimplemented",
"(",
"'COPY_PHASE_STRIP'",
")",
"self",
".",
"_WarnUnimplemented",
"(",
"'GCC_DEBUGGING_SYMBOLS'",
")",
"self",
".",
"_WarnUnimplemented",
"(",
"'GCC_ENABLE_OBJC_EXCEPTIONS'",
")",
"# TODO: This is exported correctly, but assigning to it is not supported.",
"self",
".",
"_WarnUnimplemented",
"(",
"'MACH_O_TYPE'",
")",
"self",
".",
"_WarnUnimplemented",
"(",
"'PRODUCT_TYPE'",
")",
"if",
"arch",
"is",
"not",
"None",
":",
"archs",
"=",
"[",
"arch",
"]",
"else",
":",
"assert",
"self",
".",
"configname",
"archs",
"=",
"self",
".",
"GetActiveArchs",
"(",
"self",
".",
"configname",
")",
"if",
"len",
"(",
"archs",
")",
"!=",
"1",
":",
"# TODO: Supporting fat binaries will be annoying.",
"self",
".",
"_WarnUnimplemented",
"(",
"'ARCHS'",
")",
"archs",
"=",
"[",
"'i386'",
"]",
"cflags",
".",
"append",
"(",
"'-arch '",
"+",
"archs",
"[",
"0",
"]",
")",
"if",
"archs",
"[",
"0",
"]",
"in",
"(",
"'i386'",
",",
"'x86_64'",
")",
":",
"if",
"self",
".",
"_Test",
"(",
"'GCC_ENABLE_SSE3_EXTENSIONS'",
",",
"'YES'",
",",
"default",
"=",
"'NO'",
")",
":",
"cflags",
".",
"append",
"(",
"'-msse3'",
")",
"if",
"self",
".",
"_Test",
"(",
"'GCC_ENABLE_SUPPLEMENTAL_SSE3_INSTRUCTIONS'",
",",
"'YES'",
",",
"default",
"=",
"'NO'",
")",
":",
"cflags",
".",
"append",
"(",
"'-mssse3'",
")",
"# Note 3rd 's'.",
"if",
"self",
".",
"_Test",
"(",
"'GCC_ENABLE_SSE41_EXTENSIONS'",
",",
"'YES'",
",",
"default",
"=",
"'NO'",
")",
":",
"cflags",
".",
"append",
"(",
"'-msse4.1'",
")",
"if",
"self",
".",
"_Test",
"(",
"'GCC_ENABLE_SSE42_EXTENSIONS'",
",",
"'YES'",
",",
"default",
"=",
"'NO'",
")",
":",
"cflags",
".",
"append",
"(",
"'-msse4.2'",
")",
"cflags",
"+=",
"self",
".",
"_Settings",
"(",
")",
".",
"get",
"(",
"'WARNING_CFLAGS'",
",",
"[",
"]",
")",
"if",
"self",
".",
"_IsXCTest",
"(",
")",
":",
"platform_root",
"=",
"self",
".",
"_XcodePlatformPath",
"(",
"configname",
")",
"if",
"platform_root",
":",
"cflags",
".",
"append",
"(",
"'-F'",
"+",
"platform_root",
"+",
"'/Developer/Library/Frameworks/'",
")",
"if",
"sdk_root",
":",
"framework_root",
"=",
"sdk_root",
"else",
":",
"framework_root",
"=",
"''",
"config",
"=",
"self",
".",
"spec",
"[",
"'configurations'",
"]",
"[",
"self",
".",
"configname",
"]",
"framework_dirs",
"=",
"config",
".",
"get",
"(",
"'mac_framework_dirs'",
",",
"[",
"]",
")",
"for",
"directory",
"in",
"framework_dirs",
":",
"cflags",
".",
"append",
"(",
"'-F'",
"+",
"directory",
".",
"replace",
"(",
"'$(SDKROOT)'",
",",
"framework_root",
")",
")",
"self",
".",
"configname",
"=",
"None",
"return",
"cflags"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/gyp/pylib/gyp/xcode_emulation.py#L545-L667 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/drill/model/DrillParameter.py | python | DrillParameter.getName | (self) | return self._name | Get the name of the parameter.
Args:
name (str): name of the parameter | Get the name of the parameter. | [
"Get",
"the",
"name",
"of",
"the",
"parameter",
"."
] | def getName(self):
"""
Get the name of the parameter.
Args:
name (str): name of the parameter
"""
return self._name | [
"def",
"getName",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/drill/model/DrillParameter.py#L139-L146 | |
larroy/clearskies_core | 3574ddf0edc8555454c7044126e786a6c29444dc | tools/gyp/pylib/gyp/xcodeproj_file.py | python | XCObject._XCKVPrint | (self, file, tabs, key, value) | Prints a key and value, members of an XCObject's _properties dictionary,
to file.
tabs is an int identifying the indentation level. If the class'
_should_print_single_line variable is True, tabs is ignored and the
key-value pair will be followed by a space insead of a newline. | Prints a key and value, members of an XCObject's _properties dictionary,
to file. | [
"Prints",
"a",
"key",
"and",
"value",
"members",
"of",
"an",
"XCObject",
"s",
"_properties",
"dictionary",
"to",
"file",
"."
] | def _XCKVPrint(self, file, tabs, key, value):
"""Prints a key and value, members of an XCObject's _properties dictionary,
to file.
tabs is an int identifying the indentation level. If the class'
_should_print_single_line variable is True, tabs is ignored and the
key-value pair will be followed by a space insead of a newline.
"""
if self._should_print_single_line:
printable = ''
after_kv = ' '
else:
printable = '\t' * tabs
after_kv = '\n'
# Xcode usually prints remoteGlobalIDString values in PBXContainerItemProxy
# objects without comments. Sometimes it prints them with comments, but
# the majority of the time, it doesn't. To avoid unnecessary changes to
# the project file after Xcode opens it, don't write comments for
# remoteGlobalIDString. This is a sucky hack and it would certainly be
# cleaner to extend the schema to indicate whether or not a comment should
# be printed, but since this is the only case where the problem occurs and
# Xcode itself can't seem to make up its mind, the hack will suffice.
#
# Also see PBXContainerItemProxy._schema['remoteGlobalIDString'].
if key == 'remoteGlobalIDString' and isinstance(self,
PBXContainerItemProxy):
value_to_print = value.id
else:
value_to_print = value
# PBXBuildFile's settings property is represented in the output as a dict,
# but a hack here has it represented as a string. Arrange to strip off the
# quotes so that it shows up in the output as expected.
if key == 'settings' and isinstance(self, PBXBuildFile):
strip_value_quotes = True
else:
strip_value_quotes = False
# In another one-off, let's set flatten_list on buildSettings properties
# of XCBuildConfiguration objects, because that's how Xcode treats them.
if key == 'buildSettings' and isinstance(self, XCBuildConfiguration):
flatten_list = True
else:
flatten_list = False
try:
printable_key = self._XCPrintableValue(tabs, key, flatten_list)
printable_value = self._XCPrintableValue(tabs, value_to_print,
flatten_list)
if strip_value_quotes and len(printable_value) > 1 and \
printable_value[0] == '"' and printable_value[-1] == '"':
printable_value = printable_value[1:-1]
printable += printable_key + ' = ' + printable_value + ';' + after_kv
except TypeError, e:
gyp.common.ExceptionAppend(e,
'while printing key "%s"' % key)
raise
self._XCPrint(file, 0, printable) | [
"def",
"_XCKVPrint",
"(",
"self",
",",
"file",
",",
"tabs",
",",
"key",
",",
"value",
")",
":",
"if",
"self",
".",
"_should_print_single_line",
":",
"printable",
"=",
"''",
"after_kv",
"=",
"' '",
"else",
":",
"printable",
"=",
"'\\t'",
"*",
"tabs",
"after_kv",
"=",
"'\\n'",
"# Xcode usually prints remoteGlobalIDString values in PBXContainerItemProxy",
"# objects without comments. Sometimes it prints them with comments, but",
"# the majority of the time, it doesn't. To avoid unnecessary changes to",
"# the project file after Xcode opens it, don't write comments for",
"# remoteGlobalIDString. This is a sucky hack and it would certainly be",
"# cleaner to extend the schema to indicate whether or not a comment should",
"# be printed, but since this is the only case where the problem occurs and",
"# Xcode itself can't seem to make up its mind, the hack will suffice.",
"#",
"# Also see PBXContainerItemProxy._schema['remoteGlobalIDString'].",
"if",
"key",
"==",
"'remoteGlobalIDString'",
"and",
"isinstance",
"(",
"self",
",",
"PBXContainerItemProxy",
")",
":",
"value_to_print",
"=",
"value",
".",
"id",
"else",
":",
"value_to_print",
"=",
"value",
"# PBXBuildFile's settings property is represented in the output as a dict,",
"# but a hack here has it represented as a string. Arrange to strip off the",
"# quotes so that it shows up in the output as expected.",
"if",
"key",
"==",
"'settings'",
"and",
"isinstance",
"(",
"self",
",",
"PBXBuildFile",
")",
":",
"strip_value_quotes",
"=",
"True",
"else",
":",
"strip_value_quotes",
"=",
"False",
"# In another one-off, let's set flatten_list on buildSettings properties",
"# of XCBuildConfiguration objects, because that's how Xcode treats them.",
"if",
"key",
"==",
"'buildSettings'",
"and",
"isinstance",
"(",
"self",
",",
"XCBuildConfiguration",
")",
":",
"flatten_list",
"=",
"True",
"else",
":",
"flatten_list",
"=",
"False",
"try",
":",
"printable_key",
"=",
"self",
".",
"_XCPrintableValue",
"(",
"tabs",
",",
"key",
",",
"flatten_list",
")",
"printable_value",
"=",
"self",
".",
"_XCPrintableValue",
"(",
"tabs",
",",
"value_to_print",
",",
"flatten_list",
")",
"if",
"strip_value_quotes",
"and",
"len",
"(",
"printable_value",
")",
">",
"1",
"and",
"printable_value",
"[",
"0",
"]",
"==",
"'\"'",
"and",
"printable_value",
"[",
"-",
"1",
"]",
"==",
"'\"'",
":",
"printable_value",
"=",
"printable_value",
"[",
"1",
":",
"-",
"1",
"]",
"printable",
"+=",
"printable_key",
"+",
"' = '",
"+",
"printable_value",
"+",
"';'",
"+",
"after_kv",
"except",
"TypeError",
",",
"e",
":",
"gyp",
".",
"common",
".",
"ExceptionAppend",
"(",
"e",
",",
"'while printing key \"%s\"'",
"%",
"key",
")",
"raise",
"self",
".",
"_XCPrint",
"(",
"file",
",",
"0",
",",
"printable",
")"
] | https://github.com/larroy/clearskies_core/blob/3574ddf0edc8555454c7044126e786a6c29444dc/tools/gyp/pylib/gyp/xcodeproj_file.py#L640-L700 | ||
syoyo/tinygltf | e7f1ff5c59d3ca2489923beb239bdf93d863498f | deps/cpplint.py | python | CleansedLines.NumLines | (self) | return self.num_lines | Returns the number of lines represented. | Returns the number of lines represented. | [
"Returns",
"the",
"number",
"of",
"lines",
"represented",
"."
] | def NumLines(self):
"""Returns the number of lines represented."""
return self.num_lines | [
"def",
"NumLines",
"(",
"self",
")",
":",
"return",
"self",
".",
"num_lines"
] | https://github.com/syoyo/tinygltf/blob/e7f1ff5c59d3ca2489923beb239bdf93d863498f/deps/cpplint.py#L1313-L1315 | |
dmlc/xgboost | 2775c2a1abd4b5b759ff517617434c8b9aeb4cc0 | python-package/xgboost/training.py | python | CVPack.update | (self, iteration, fobj) | Update the boosters for one iteration | Update the boosters for one iteration | [
"Update",
"the",
"boosters",
"for",
"one",
"iteration"
] | def update(self, iteration, fobj):
""""Update the boosters for one iteration"""
self.bst.update(self.dtrain, iteration, fobj) | [
"def",
"update",
"(",
"self",
",",
"iteration",
",",
"fobj",
")",
":",
"self",
".",
"bst",
".",
"update",
"(",
"self",
".",
"dtrain",
",",
"iteration",
",",
"fobj",
")"
] | https://github.com/dmlc/xgboost/blob/2775c2a1abd4b5b759ff517617434c8b9aeb4cc0/python-package/xgboost/training.py#L201-L203 | ||
kismetwireless/kismet | a7c0dc270c960fb1f58bd9cec4601c201885fd4e | capture_bt_geiger/KismetCaptureBtGeiger/kismetexternal/__init__.py | python | ExternalInterface.run | (self) | Enter a blocking loop until the IO exits | Enter a blocking loop until the IO exits | [
"Enter",
"a",
"blocking",
"loop",
"until",
"the",
"IO",
"exits"
] | def run(self):
"""
Enter a blocking loop until the IO exits
"""
try:
# Bring up the IO loop task; it's the only task we absolutely care
# about. Other tasks can come and go, if this one dies, we have
# to shut down.
# From this point onwards we exist inside this asyncio wait
self.loop.add_signal_handler(signal.SIGINT, self.kill)
self.loop.add_signal_handler(signal.SIGTERM, self.kill)
self.loop.add_signal_handler(signal.SIGQUIT, self.kill)
self.main_io_task = self.loop.create_task(self.__io_loop())
if self.debug:
print("kismetexternal api running async loop forever")
self.loop.run_forever()
self.running = False
self.kill()
except Exception as e:
if self.running:
self.kill() | [
"def",
"run",
"(",
"self",
")",
":",
"try",
":",
"# Bring up the IO loop task; it's the only task we absolutely care",
"# about. Other tasks can come and go, if this one dies, we have",
"# to shut down.",
"# From this point onwards we exist inside this asyncio wait",
"self",
".",
"loop",
".",
"add_signal_handler",
"(",
"signal",
".",
"SIGINT",
",",
"self",
".",
"kill",
")",
"self",
".",
"loop",
".",
"add_signal_handler",
"(",
"signal",
".",
"SIGTERM",
",",
"self",
".",
"kill",
")",
"self",
".",
"loop",
".",
"add_signal_handler",
"(",
"signal",
".",
"SIGQUIT",
",",
"self",
".",
"kill",
")",
"self",
".",
"main_io_task",
"=",
"self",
".",
"loop",
".",
"create_task",
"(",
"self",
".",
"__io_loop",
"(",
")",
")",
"if",
"self",
".",
"debug",
":",
"print",
"(",
"\"kismetexternal api running async loop forever\"",
")",
"self",
".",
"loop",
".",
"run_forever",
"(",
")",
"self",
".",
"running",
"=",
"False",
"self",
".",
"kill",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"if",
"self",
".",
"running",
":",
"self",
".",
"kill",
"(",
")"
] | https://github.com/kismetwireless/kismet/blob/a7c0dc270c960fb1f58bd9cec4601c201885fd4e/capture_bt_geiger/KismetCaptureBtGeiger/kismetexternal/__init__.py#L368-L396 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/numbers.py | python | Integral.__lshift__ | (self, other) | self << other | self << other | [
"self",
"<<",
"other"
] | def __lshift__(self, other):
"""self << other"""
raise NotImplementedError | [
"def",
"__lshift__",
"(",
"self",
",",
"other",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/numbers.py#L321-L323 | ||
sumoprojects/sumokoin | 2857d0bffd36bf2aa579ef80518f4cb099c98b05 | thirdparty/unbound/pythonmod/examples/inplace_callbacks.py | python | init_standard | (id, env) | return True | New version of the init function.
The function's signature is the same as the C counterpart and allows for
extra functionality during init.
..note:: This function is preferred by unbound over the old init function.
..note:: The previously accessible configuration options can now be found in
env.cgf. | New version of the init function.
The function's signature is the same as the C counterpart and allows for
extra functionality during init.
..note:: This function is preferred by unbound over the old init function.
..note:: The previously accessible configuration options can now be found in
env.cgf. | [
"New",
"version",
"of",
"the",
"init",
"function",
".",
"The",
"function",
"s",
"signature",
"is",
"the",
"same",
"as",
"the",
"C",
"counterpart",
"and",
"allows",
"for",
"extra",
"functionality",
"during",
"init",
".",
"..",
"note",
"::",
"This",
"function",
"is",
"preferred",
"by",
"unbound",
"over",
"the",
"old",
"init",
"function",
".",
"..",
"note",
"::",
"The",
"previously",
"accessible",
"configuration",
"options",
"can",
"now",
"be",
"found",
"in",
"env",
".",
"cgf",
"."
] | def init_standard(id, env):
"""New version of the init function.
The function's signature is the same as the C counterpart and allows for
extra functionality during init.
..note:: This function is preferred by unbound over the old init function.
..note:: The previously accessible configuration options can now be found in
env.cgf.
"""
log_info("python: inited script {}".format(env.cfg.python_script))
# Register the inplace_reply_callback function as an inplace callback
# function when answering a resolved query.
if not register_inplace_cb_reply(inplace_reply_callback, env, id):
return False
# Register the inplace_cache_callback function as an inplace callback
# function when answering from cache.
if not register_inplace_cb_reply_cache(inplace_cache_callback, env, id):
return False
# Register the inplace_local_callback function as an inplace callback
# function when answering from local data.
if not register_inplace_cb_reply_local(inplace_local_callback, env, id):
return False
# Register the inplace_servfail_callback function as an inplace callback
# function when answering with SERVFAIL.
if not register_inplace_cb_reply_servfail(inplace_servfail_callback, env, id):
return False
return True | [
"def",
"init_standard",
"(",
"id",
",",
"env",
")",
":",
"log_info",
"(",
"\"python: inited script {}\"",
".",
"format",
"(",
"env",
".",
"cfg",
".",
"python_script",
")",
")",
"# Register the inplace_reply_callback function as an inplace callback",
"# function when answering a resolved query.",
"if",
"not",
"register_inplace_cb_reply",
"(",
"inplace_reply_callback",
",",
"env",
",",
"id",
")",
":",
"return",
"False",
"# Register the inplace_cache_callback function as an inplace callback",
"# function when answering from cache.",
"if",
"not",
"register_inplace_cb_reply_cache",
"(",
"inplace_cache_callback",
",",
"env",
",",
"id",
")",
":",
"return",
"False",
"# Register the inplace_local_callback function as an inplace callback",
"# function when answering from local data.",
"if",
"not",
"register_inplace_cb_reply_local",
"(",
"inplace_local_callback",
",",
"env",
",",
"id",
")",
":",
"return",
"False",
"# Register the inplace_servfail_callback function as an inplace callback",
"# function when answering with SERVFAIL.",
"if",
"not",
"register_inplace_cb_reply_servfail",
"(",
"inplace_servfail_callback",
",",
"env",
",",
"id",
")",
":",
"return",
"False",
"return",
"True"
] | https://github.com/sumoprojects/sumokoin/blob/2857d0bffd36bf2aa579ef80518f4cb099c98b05/thirdparty/unbound/pythonmod/examples/inplace_callbacks.py#L184-L214 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/dis.py | python | _test | () | Simple test program to disassemble a file. | Simple test program to disassemble a file. | [
"Simple",
"test",
"program",
"to",
"disassemble",
"a",
"file",
"."
] | def _test():
"""Simple test program to disassemble a file."""
if sys.argv[1:]:
if sys.argv[2:]:
sys.stderr.write("usage: python dis.py [-|file]\n")
sys.exit(2)
fn = sys.argv[1]
if not fn or fn == "-":
fn = None
else:
fn = None
if fn is None:
f = sys.stdin
else:
f = open(fn)
source = f.read()
if fn is not None:
f.close()
else:
fn = "<stdin>"
code = compile(source, fn, "exec")
dis(code) | [
"def",
"_test",
"(",
")",
":",
"if",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
":",
"if",
"sys",
".",
"argv",
"[",
"2",
":",
"]",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"usage: python dis.py [-|file]\\n\"",
")",
"sys",
".",
"exit",
"(",
"2",
")",
"fn",
"=",
"sys",
".",
"argv",
"[",
"1",
"]",
"if",
"not",
"fn",
"or",
"fn",
"==",
"\"-\"",
":",
"fn",
"=",
"None",
"else",
":",
"fn",
"=",
"None",
"if",
"fn",
"is",
"None",
":",
"f",
"=",
"sys",
".",
"stdin",
"else",
":",
"f",
"=",
"open",
"(",
"fn",
")",
"source",
"=",
"f",
".",
"read",
"(",
")",
"if",
"fn",
"is",
"not",
"None",
":",
"f",
".",
"close",
"(",
")",
"else",
":",
"fn",
"=",
"\"<stdin>\"",
"code",
"=",
"compile",
"(",
"source",
",",
"fn",
",",
"\"exec\"",
")",
"dis",
"(",
"code",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/dis.py#L203-L224 | ||
wisdompeak/LeetCode | ef729c1249ead3ead47f1a94b5eeb5958a69e152 | Math/077.Combinations/077.Combinations_recursive.py | python | Solution.combine | (self, n, k) | return results | :type n: int
:type k: int
:rtype: List[List[int]] | :type n: int
:type k: int
:rtype: List[List[int]] | [
":",
"type",
"n",
":",
"int",
":",
"type",
"k",
":",
"int",
":",
"rtype",
":",
"List",
"[",
"List",
"[",
"int",
"]]"
] | def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
results = []
def DFS(start,nums):
if (len(nums)==k):
results.append(nums)
return
if (len(nums)+n-start+1<k):
return
for i in range(start,n+1):
DFS(i+1,nums+[i])
nums = []
DFS(1,nums)
return results | [
"def",
"combine",
"(",
"self",
",",
"n",
",",
"k",
")",
":",
"results",
"=",
"[",
"]",
"def",
"DFS",
"(",
"start",
",",
"nums",
")",
":",
"if",
"(",
"len",
"(",
"nums",
")",
"==",
"k",
")",
":",
"results",
".",
"append",
"(",
"nums",
")",
"return",
"if",
"(",
"len",
"(",
"nums",
")",
"+",
"n",
"-",
"start",
"+",
"1",
"<",
"k",
")",
":",
"return",
"for",
"i",
"in",
"range",
"(",
"start",
",",
"n",
"+",
"1",
")",
":",
"DFS",
"(",
"i",
"+",
"1",
",",
"nums",
"+",
"[",
"i",
"]",
")",
"nums",
"=",
"[",
"]",
"DFS",
"(",
"1",
",",
"nums",
")",
"return",
"results"
] | https://github.com/wisdompeak/LeetCode/blob/ef729c1249ead3ead47f1a94b5eeb5958a69e152/Math/077.Combinations/077.Combinations_recursive.py#L2-L19 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py2/numpy/fft/helper.py | python | fftshift | (x, axes=None) | return roll(x, shift, axes) | Shift the zero-frequency component to the center of the spectrum.
This function swaps half-spaces for all axes listed (defaults to all).
Note that ``y[0]`` is the Nyquist component only if ``len(x)`` is even.
Parameters
----------
x : array_like
Input array.
axes : int or shape tuple, optional
Axes over which to shift. Default is None, which shifts all axes.
Returns
-------
y : ndarray
The shifted array.
See Also
--------
ifftshift : The inverse of `fftshift`.
Examples
--------
>>> freqs = np.fft.fftfreq(10, 0.1)
>>> freqs
array([ 0., 1., 2., 3., 4., -5., -4., -3., -2., -1.])
>>> np.fft.fftshift(freqs)
array([-5., -4., -3., -2., -1., 0., 1., 2., 3., 4.])
Shift the zero-frequency component only along the second axis:
>>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3)
>>> freqs
array([[ 0., 1., 2.],
[ 3., 4., -4.],
[-3., -2., -1.]])
>>> np.fft.fftshift(freqs, axes=(1,))
array([[ 2., 0., 1.],
[-4., 3., 4.],
[-1., -3., -2.]]) | Shift the zero-frequency component to the center of the spectrum. | [
"Shift",
"the",
"zero",
"-",
"frequency",
"component",
"to",
"the",
"center",
"of",
"the",
"spectrum",
"."
] | def fftshift(x, axes=None):
"""
Shift the zero-frequency component to the center of the spectrum.
This function swaps half-spaces for all axes listed (defaults to all).
Note that ``y[0]`` is the Nyquist component only if ``len(x)`` is even.
Parameters
----------
x : array_like
Input array.
axes : int or shape tuple, optional
Axes over which to shift. Default is None, which shifts all axes.
Returns
-------
y : ndarray
The shifted array.
See Also
--------
ifftshift : The inverse of `fftshift`.
Examples
--------
>>> freqs = np.fft.fftfreq(10, 0.1)
>>> freqs
array([ 0., 1., 2., 3., 4., -5., -4., -3., -2., -1.])
>>> np.fft.fftshift(freqs)
array([-5., -4., -3., -2., -1., 0., 1., 2., 3., 4.])
Shift the zero-frequency component only along the second axis:
>>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3)
>>> freqs
array([[ 0., 1., 2.],
[ 3., 4., -4.],
[-3., -2., -1.]])
>>> np.fft.fftshift(freqs, axes=(1,))
array([[ 2., 0., 1.],
[-4., 3., 4.],
[-1., -3., -2.]])
"""
x = asarray(x)
if axes is None:
axes = tuple(range(x.ndim))
shift = [dim // 2 for dim in x.shape]
elif isinstance(axes, integer_types):
shift = x.shape[axes] // 2
else:
shift = [x.shape[ax] // 2 for ax in axes]
return roll(x, shift, axes) | [
"def",
"fftshift",
"(",
"x",
",",
"axes",
"=",
"None",
")",
":",
"x",
"=",
"asarray",
"(",
"x",
")",
"if",
"axes",
"is",
"None",
":",
"axes",
"=",
"tuple",
"(",
"range",
"(",
"x",
".",
"ndim",
")",
")",
"shift",
"=",
"[",
"dim",
"//",
"2",
"for",
"dim",
"in",
"x",
".",
"shape",
"]",
"elif",
"isinstance",
"(",
"axes",
",",
"integer_types",
")",
":",
"shift",
"=",
"x",
".",
"shape",
"[",
"axes",
"]",
"//",
"2",
"else",
":",
"shift",
"=",
"[",
"x",
".",
"shape",
"[",
"ax",
"]",
"//",
"2",
"for",
"ax",
"in",
"axes",
"]",
"return",
"roll",
"(",
"x",
",",
"shift",
",",
"axes",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/fft/helper.py#L28-L81 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/dataset/text/utils.py | python | Vocab.from_dataset | (cls, dataset, columns=None, freq_range=None, top_k=None, special_tokens=None, special_first=True) | return vocab | Build a vocab from a dataset.
This would collect all unique words in a dataset and return a vocab within
the frequency range specified by user in freq_range. User would be warned if no words fall into the frequency.
Words in vocab are ordered from the highest frequency to the lowest frequency. Words with the same frequency
would be ordered lexicographically.
Args:
dataset(Dataset): dataset to build vocab from.
columns(list[str], optional): column names to get words from. It can be a list of column names.
(default=None, where all columns will be used. If any column isn't string type, will return error).
freq_range(tuple, optional): A tuple of integers (min_frequency, max_frequency). Words within the frequency
range would be kept. 0 <= min_frequency <= max_frequency <= total_words. min_frequency=0 is the same as
min_frequency=1. max_frequency > total_words is the same as max_frequency = total_words.
min_frequency/max_frequency can be None, which corresponds to 0/total_words separately
(default=None, all words are included).
top_k(int, optional): top_k is greater than 0. Number of words to be built into vocab. top_k means most
frequent words are taken. top_k is taken after freq_range. If not enough top_k, all words will be taken
(default=None, all words are included).
special_tokens(list, optional): A list of strings, each one is a special token. For example
special_tokens=["<pad>","<unk>"] (default=None, no special tokens will be added).
special_first(bool, optional): Whether special_tokens will be prepended/appended to vocab. If special_tokens
is specified and special_first is set to True, special_tokens will be prepended (default=True).
Returns:
Vocab, vocab built from the dataset.
Examples:
>>> dataset = ds.TextFileDataset("/path/to/sentence/piece/vocab/file", shuffle=False)
>>> vocab = text.Vocab.from_dataset(dataset, "text", freq_range=None, top_k=None,
... special_tokens=["<pad>", "<unk>"],
... special_first=True)
>>> dataset = dataset.map(operations=text.Lookup(vocab, "<unk>"), input_columns=["text"]) | Build a vocab from a dataset. | [
"Build",
"a",
"vocab",
"from",
"a",
"dataset",
"."
] | def from_dataset(cls, dataset, columns=None, freq_range=None, top_k=None, special_tokens=None, special_first=True):
"""
Build a vocab from a dataset.
This would collect all unique words in a dataset and return a vocab within
the frequency range specified by user in freq_range. User would be warned if no words fall into the frequency.
Words in vocab are ordered from the highest frequency to the lowest frequency. Words with the same frequency
would be ordered lexicographically.
Args:
dataset(Dataset): dataset to build vocab from.
columns(list[str], optional): column names to get words from. It can be a list of column names.
(default=None, where all columns will be used. If any column isn't string type, will return error).
freq_range(tuple, optional): A tuple of integers (min_frequency, max_frequency). Words within the frequency
range would be kept. 0 <= min_frequency <= max_frequency <= total_words. min_frequency=0 is the same as
min_frequency=1. max_frequency > total_words is the same as max_frequency = total_words.
min_frequency/max_frequency can be None, which corresponds to 0/total_words separately
(default=None, all words are included).
top_k(int, optional): top_k is greater than 0. Number of words to be built into vocab. top_k means most
frequent words are taken. top_k is taken after freq_range. If not enough top_k, all words will be taken
(default=None, all words are included).
special_tokens(list, optional): A list of strings, each one is a special token. For example
special_tokens=["<pad>","<unk>"] (default=None, no special tokens will be added).
special_first(bool, optional): Whether special_tokens will be prepended/appended to vocab. If special_tokens
is specified and special_first is set to True, special_tokens will be prepended (default=True).
Returns:
Vocab, vocab built from the dataset.
Examples:
>>> dataset = ds.TextFileDataset("/path/to/sentence/piece/vocab/file", shuffle=False)
>>> vocab = text.Vocab.from_dataset(dataset, "text", freq_range=None, top_k=None,
... special_tokens=["<pad>", "<unk>"],
... special_first=True)
>>> dataset = dataset.map(operations=text.Lookup(vocab, "<unk>"), input_columns=["text"])
"""
vocab = Vocab()
vocab.c_vocab = dataset.build_vocab(columns, freq_range, top_k, special_tokens, special_first)
return vocab | [
"def",
"from_dataset",
"(",
"cls",
",",
"dataset",
",",
"columns",
"=",
"None",
",",
"freq_range",
"=",
"None",
",",
"top_k",
"=",
"None",
",",
"special_tokens",
"=",
"None",
",",
"special_first",
"=",
"True",
")",
":",
"vocab",
"=",
"Vocab",
"(",
")",
"vocab",
".",
"c_vocab",
"=",
"dataset",
".",
"build_vocab",
"(",
"columns",
",",
"freq_range",
",",
"top_k",
",",
"special_tokens",
",",
"special_first",
")",
"return",
"vocab"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/dataset/text/utils.py#L102-L140 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/saved_model/signature_serialization.py | python | _validate_inputs | (concrete_function) | Raises error if input type is tf.Variable. | Raises error if input type is tf.Variable. | [
"Raises",
"error",
"if",
"input",
"type",
"is",
"tf",
".",
"Variable",
"."
] | def _validate_inputs(concrete_function):
"""Raises error if input type is tf.Variable."""
if any(isinstance(inp, resource_variable_ops.VariableSpec)
for inp in nest.flatten(
concrete_function.structured_input_signature)):
raise ValueError(
f"Unable to serialize concrete_function '{concrete_function.name}'"
f"with tf.Variable input. Functions that expect tf.Variable "
"inputs cannot be exported as signatures.") | [
"def",
"_validate_inputs",
"(",
"concrete_function",
")",
":",
"if",
"any",
"(",
"isinstance",
"(",
"inp",
",",
"resource_variable_ops",
".",
"VariableSpec",
")",
"for",
"inp",
"in",
"nest",
".",
"flatten",
"(",
"concrete_function",
".",
"structured_input_signature",
")",
")",
":",
"raise",
"ValueError",
"(",
"f\"Unable to serialize concrete_function '{concrete_function.name}'\"",
"f\"with tf.Variable input. Functions that expect tf.Variable \"",
"\"inputs cannot be exported as signatures.\"",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/saved_model/signature_serialization.py#L64-L72 | ||
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/count-pairs-of-nodes.py | python | Solution2.countPairs | (self, n, edges, queries) | return result | :type n: int
:type edges: List[List[int]]
:type queries: List[int]
:rtype: List[int] | :type n: int
:type edges: List[List[int]]
:type queries: List[int]
:rtype: List[int] | [
":",
"type",
"n",
":",
"int",
":",
"type",
"edges",
":",
"List",
"[",
"List",
"[",
"int",
"]]",
":",
"type",
"queries",
":",
"List",
"[",
"int",
"]",
":",
"rtype",
":",
"List",
"[",
"int",
"]"
] | def countPairs(self, n, edges, queries):
"""
:type n: int
:type edges: List[List[int]]
:type queries: List[int]
:rtype: List[int]
"""
degree = [0]*(n+1)
shared = collections.Counter((min(n1, n2), max(n1, n2)) for n1, n2 in edges)
for n1, n2 in edges:
degree[n1] += 1
degree[n2] += 1
sorted_degree = sorted(degree)
result = []
for k, q in enumerate(queries):
left, right = 1, n
cnt = 0
while left < right:
if q < sorted_degree[left]+sorted_degree[right]:
cnt += right-left
right -= 1
else:
left += 1
for (i, j), shared_degree in shared.iteritems():
if degree[i]+degree[j]-shared_degree <= q < degree[i]+degree[j]:
cnt -= 1
result.append(cnt)
return result | [
"def",
"countPairs",
"(",
"self",
",",
"n",
",",
"edges",
",",
"queries",
")",
":",
"degree",
"=",
"[",
"0",
"]",
"*",
"(",
"n",
"+",
"1",
")",
"shared",
"=",
"collections",
".",
"Counter",
"(",
"(",
"min",
"(",
"n1",
",",
"n2",
")",
",",
"max",
"(",
"n1",
",",
"n2",
")",
")",
"for",
"n1",
",",
"n2",
"in",
"edges",
")",
"for",
"n1",
",",
"n2",
"in",
"edges",
":",
"degree",
"[",
"n1",
"]",
"+=",
"1",
"degree",
"[",
"n2",
"]",
"+=",
"1",
"sorted_degree",
"=",
"sorted",
"(",
"degree",
")",
"result",
"=",
"[",
"]",
"for",
"k",
",",
"q",
"in",
"enumerate",
"(",
"queries",
")",
":",
"left",
",",
"right",
"=",
"1",
",",
"n",
"cnt",
"=",
"0",
"while",
"left",
"<",
"right",
":",
"if",
"q",
"<",
"sorted_degree",
"[",
"left",
"]",
"+",
"sorted_degree",
"[",
"right",
"]",
":",
"cnt",
"+=",
"right",
"-",
"left",
"right",
"-=",
"1",
"else",
":",
"left",
"+=",
"1",
"for",
"(",
"i",
",",
"j",
")",
",",
"shared_degree",
"in",
"shared",
".",
"iteritems",
"(",
")",
":",
"if",
"degree",
"[",
"i",
"]",
"+",
"degree",
"[",
"j",
"]",
"-",
"shared_degree",
"<=",
"q",
"<",
"degree",
"[",
"i",
"]",
"+",
"degree",
"[",
"j",
"]",
":",
"cnt",
"-=",
"1",
"result",
".",
"append",
"(",
"cnt",
")",
"return",
"result"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/count-pairs-of-nodes.py#L44-L71 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/quantization/tools/quantize_graph.py | python | GraphRewriter.add_eightbit_prologue_nodes | (self, original_node) | return all_input_names | Adds input conversion nodes to handle quantizing the underlying node. | Adds input conversion nodes to handle quantizing the underlying node. | [
"Adds",
"input",
"conversion",
"nodes",
"to",
"handle",
"quantizing",
"the",
"underlying",
"node",
"."
] | def add_eightbit_prologue_nodes(self, original_node):
"""Adds input conversion nodes to handle quantizing the underlying node."""
namespace_prefix = original_node.name + "_eightbit"
reshape_dims_name, reduction_dims_name = self.add_common_quantization_nodes(
namespace_prefix)
input_names = []
min_max_names = []
for original_input_name in original_node.input:
quantize_input_name, min_input_name, max_input_name = (
self.eightbitize_input_to_node(namespace_prefix, original_input_name,
reshape_dims_name,
reduction_dims_name))
input_names.append(quantize_input_name)
min_max_names.append(min_input_name)
min_max_names.append(max_input_name)
all_input_names = []
all_input_names.extend(input_names)
all_input_names.extend(min_max_names)
return all_input_names | [
"def",
"add_eightbit_prologue_nodes",
"(",
"self",
",",
"original_node",
")",
":",
"namespace_prefix",
"=",
"original_node",
".",
"name",
"+",
"\"_eightbit\"",
"reshape_dims_name",
",",
"reduction_dims_name",
"=",
"self",
".",
"add_common_quantization_nodes",
"(",
"namespace_prefix",
")",
"input_names",
"=",
"[",
"]",
"min_max_names",
"=",
"[",
"]",
"for",
"original_input_name",
"in",
"original_node",
".",
"input",
":",
"quantize_input_name",
",",
"min_input_name",
",",
"max_input_name",
"=",
"(",
"self",
".",
"eightbitize_input_to_node",
"(",
"namespace_prefix",
",",
"original_input_name",
",",
"reshape_dims_name",
",",
"reduction_dims_name",
")",
")",
"input_names",
".",
"append",
"(",
"quantize_input_name",
")",
"min_max_names",
".",
"append",
"(",
"min_input_name",
")",
"min_max_names",
".",
"append",
"(",
"max_input_name",
")",
"all_input_names",
"=",
"[",
"]",
"all_input_names",
".",
"extend",
"(",
"input_names",
")",
"all_input_names",
".",
"extend",
"(",
"min_max_names",
")",
"return",
"all_input_names"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/quantization/tools/quantize_graph.py#L480-L498 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_pytorch/pytorch_binding/pytorch_nndct/quantization/module_transform.py | python | ModuleTransformer._match_node_with_inputs | (self, node, model_topo, pattern, matched_nodes) | return match | Match pattern at this node, and continue to match at its inputs. | Match pattern at this node, and continue to match at its inputs. | [
"Match",
"pattern",
"at",
"this",
"node",
"and",
"continue",
"to",
"match",
"at",
"its",
"inputs",
"."
] | def _match_node_with_inputs(self, node, model_topo, pattern, matched_nodes):
"""Match pattern at this node, and continue to match at its inputs."""
if node.name in matched_nodes:
return None
# Only match module nodes.
if not node.module:
return None
matched = False
if pattern.module_name == '*':
matched = True
else:
module_names = pattern.module_name.split('|')
for module_name in module_names:
if node.module._get_name() == module_name:
matched = True
break
if not matched:
return None
match = NodeMatch(node)
if len(pattern.inputs) == 0:
# Leaf node in pattern.
return match
if len(pattern.inputs) != len(node.inputs):
return None
for i, input_pattern in enumerate(pattern.inputs):
input_node = model_topo.node(node.inputs[i])
input_match = self._match_node_with_inputs(input_node, model_topo,
pattern.inputs[i],
matched_nodes)
if not input_match:
return None
match.inputs.append(input_match)
return match | [
"def",
"_match_node_with_inputs",
"(",
"self",
",",
"node",
",",
"model_topo",
",",
"pattern",
",",
"matched_nodes",
")",
":",
"if",
"node",
".",
"name",
"in",
"matched_nodes",
":",
"return",
"None",
"# Only match module nodes.",
"if",
"not",
"node",
".",
"module",
":",
"return",
"None",
"matched",
"=",
"False",
"if",
"pattern",
".",
"module_name",
"==",
"'*'",
":",
"matched",
"=",
"True",
"else",
":",
"module_names",
"=",
"pattern",
".",
"module_name",
".",
"split",
"(",
"'|'",
")",
"for",
"module_name",
"in",
"module_names",
":",
"if",
"node",
".",
"module",
".",
"_get_name",
"(",
")",
"==",
"module_name",
":",
"matched",
"=",
"True",
"break",
"if",
"not",
"matched",
":",
"return",
"None",
"match",
"=",
"NodeMatch",
"(",
"node",
")",
"if",
"len",
"(",
"pattern",
".",
"inputs",
")",
"==",
"0",
":",
"# Leaf node in pattern.",
"return",
"match",
"if",
"len",
"(",
"pattern",
".",
"inputs",
")",
"!=",
"len",
"(",
"node",
".",
"inputs",
")",
":",
"return",
"None",
"for",
"i",
",",
"input_pattern",
"in",
"enumerate",
"(",
"pattern",
".",
"inputs",
")",
":",
"input_node",
"=",
"model_topo",
".",
"node",
"(",
"node",
".",
"inputs",
"[",
"i",
"]",
")",
"input_match",
"=",
"self",
".",
"_match_node_with_inputs",
"(",
"input_node",
",",
"model_topo",
",",
"pattern",
".",
"inputs",
"[",
"i",
"]",
",",
"matched_nodes",
")",
"if",
"not",
"input_match",
":",
"return",
"None",
"match",
".",
"inputs",
".",
"append",
"(",
"input_match",
")",
"return",
"match"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_pytorch/pytorch_binding/pytorch_nndct/quantization/module_transform.py#L237-L276 | |
microsoft/CNTK | e9396480025b9ca457d26b6f33dd07c474c6aa04 | bindings/python/cntk/variables.py | python | VariableMixin.owner | (self) | return super(VariableMixin, self).owner() | The function this variable is an output of. | The function this variable is an output of. | [
"The",
"function",
"this",
"variable",
"is",
"an",
"output",
"of",
"."
] | def owner(self):
'''
The function this variable is an output of.
'''
if self.is_output == False:
raise RuntimeError('called owner() on a variable that is not an output variable')
return super(VariableMixin, self).owner() | [
"def",
"owner",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_output",
"==",
"False",
":",
"raise",
"RuntimeError",
"(",
"'called owner() on a variable that is not an output variable'",
")",
"return",
"super",
"(",
"VariableMixin",
",",
"self",
")",
".",
"owner",
"(",
")"
] | https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/bindings/python/cntk/variables.py#L143-L149 | |
openthread/openthread | 9fcdbed9c526c70f1556d1ed84099c1535c7cd32 | tools/harness-thci/OpenThread_WpanCtl.py | python | OpenThread_WpanCtl.__setRouterUpgradeThreshold | (self, iThreshold) | set router upgrade threshold
Args:
iThreshold: the number of active routers on the Thread network
partition below which a REED may decide to become a Router.
Returns:
True: successful to set the ROUTER_UPGRADE_THRESHOLD
False: fail to set ROUTER_UPGRADE_THRESHOLD | set router upgrade threshold | [
"set",
"router",
"upgrade",
"threshold"
] | def __setRouterUpgradeThreshold(self, iThreshold):
"""set router upgrade threshold
Args:
iThreshold: the number of active routers on the Thread network
partition below which a REED may decide to become a Router.
Returns:
True: successful to set the ROUTER_UPGRADE_THRESHOLD
False: fail to set ROUTER_UPGRADE_THRESHOLD
"""
print('call __setRouterUpgradeThreshold')
try:
cmd = self.wpan_cmd_prefix + 'setprop Thread:RouterUpgradeThreshold %s' % str(iThreshold)
return self.__sendCommand(cmd)[0] != 'Fail'
except Exception as e:
ModuleHelper.WriteIntoDebugLogger('setRouterUpgradeThreshold() Error: ' + str(e)) | [
"def",
"__setRouterUpgradeThreshold",
"(",
"self",
",",
"iThreshold",
")",
":",
"print",
"(",
"'call __setRouterUpgradeThreshold'",
")",
"try",
":",
"cmd",
"=",
"self",
".",
"wpan_cmd_prefix",
"+",
"'setprop Thread:RouterUpgradeThreshold %s'",
"%",
"str",
"(",
"iThreshold",
")",
"return",
"self",
".",
"__sendCommand",
"(",
"cmd",
")",
"[",
"0",
"]",
"!=",
"'Fail'",
"except",
"Exception",
"as",
"e",
":",
"ModuleHelper",
".",
"WriteIntoDebugLogger",
"(",
"'setRouterUpgradeThreshold() Error: '",
"+",
"str",
"(",
"e",
")",
")"
] | https://github.com/openthread/openthread/blob/9fcdbed9c526c70f1556d1ed84099c1535c7cd32/tools/harness-thci/OpenThread_WpanCtl.py#L328-L344 | ||
GrammaTech/gtirb | 415dd72e1e3c475004d013723c16cdcb29c0826e | python/gtirb/block.py | python | ByteBlock.ir | (self) | return self.module.ir | Get the IR this node ultimately belongs to. | Get the IR this node ultimately belongs to. | [
"Get",
"the",
"IR",
"this",
"node",
"ultimately",
"belongs",
"to",
"."
] | def ir(self) -> typing.Optional["IR"]:
"""Get the IR this node ultimately belongs to."""
if self.module is None:
return None
return self.module.ir | [
"def",
"ir",
"(",
"self",
")",
"->",
"typing",
".",
"Optional",
"[",
"\"IR\"",
"]",
":",
"if",
"self",
".",
"module",
"is",
"None",
":",
"return",
"None",
"return",
"self",
".",
"module",
".",
"ir"
] | https://github.com/GrammaTech/gtirb/blob/415dd72e1e3c475004d013723c16cdcb29c0826e/python/gtirb/block.py#L148-L152 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | native_client_sdk/src/build_tools/manifest_util.py | python | SDKManifest.__init__ | (self) | Create a new SDKManifest object with default contents | Create a new SDKManifest object with default contents | [
"Create",
"a",
"new",
"SDKManifest",
"object",
"with",
"default",
"contents"
] | def __init__(self):
"""Create a new SDKManifest object with default contents"""
self._manifest_data = {
"manifest_version": MANIFEST_VERSION,
"bundles": [],
} | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"_manifest_data",
"=",
"{",
"\"manifest_version\"",
":",
"MANIFEST_VERSION",
",",
"\"bundles\"",
":",
"[",
"]",
",",
"}"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/native_client_sdk/src/build_tools/manifest_util.py#L307-L312 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Runtime/VART/vart/trace/vaitrace/writer/txt/convert.py | python | print_cpu_func_table | (cpp_summary, py_summary) | ['vitis::ai::ConfigurableDpuTaskImp::setInputImageBGR_1,657,CPU,0.474,0.488,0.652,\n',
'xir::XrtCu::run,1314,CPU,0.063,7.181,21.457,\n', 'vitis::ai::DpuTaskImp::run,657,CPU,13.180,14.381,21.618,\n'] | ['vitis::ai::ConfigurableDpuTaskImp::setInputImageBGR_1,657,CPU,0.474,0.488,0.652,\n',
'xir::XrtCu::run,1314,CPU,0.063,7.181,21.457,\n', 'vitis::ai::DpuTaskImp::run,657,CPU,13.180,14.381,21.618,\n'] | [
"[",
"vitis",
"::",
"ai",
"::",
"ConfigurableDpuTaskImp",
"::",
"setInputImageBGR_1",
"657",
"CPU",
"0",
".",
"474",
"0",
".",
"488",
"0",
".",
"652",
"\\",
"n",
"xir",
"::",
"XrtCu",
"::",
"run",
"1314",
"CPU",
"0",
".",
"063",
"7",
".",
"181",
"21",
".",
"457",
"\\",
"n",
"vitis",
"::",
"ai",
"::",
"DpuTaskImp",
"::",
"run",
"657",
"CPU",
"13",
".",
"180",
"14",
".",
"381",
"21",
".",
"618",
"\\",
"n",
"]"
] | def print_cpu_func_table(cpp_summary, py_summary):
"""
['vitis::ai::ConfigurableDpuTaskImp::setInputImageBGR_1,657,CPU,0.474,0.488,0.652,\n',
'xir::XrtCu::run,1314,CPU,0.063,7.181,21.457,\n', 'vitis::ai::DpuTaskImp::run,657,CPU,13.180,14.381,21.618,\n']
"""
header = ['Function', 'Device', 'Runs', 'AverageRunTime(ms)']
pr_data = []
pr_data.append(header)
cpu_func_summary = cpp_summary + py_summary
if len(cpu_func_summary) == 0:
return
for row in cpp_summary:
items = row.strip().split(',')
function_name = items[0]
dev = "CPU"
runs = items[1]
min_t = items[3]
ave_t = items[4]
max_t = items[5]
pr_data.append([function_name, dev, runs, ave_t])
for row in py_summary:
items = row.strip().split(',')
function_name = "%s@py" % items[0]
dev = "CPU"
runs = items[1]
min_t = items[3]
ave_t = items[4]
max_t = items[5]
pr_data.append([function_name, dev, runs, ave_t])
print("\nCPU Functions(Not in Graph, e.g.: pre/post-processing, vai-runtime):", file=output_f)
print_ascii_table(pr_data, output_f) | [
"def",
"print_cpu_func_table",
"(",
"cpp_summary",
",",
"py_summary",
")",
":",
"header",
"=",
"[",
"'Function'",
",",
"'Device'",
",",
"'Runs'",
",",
"'AverageRunTime(ms)'",
"]",
"pr_data",
"=",
"[",
"]",
"pr_data",
".",
"append",
"(",
"header",
")",
"cpu_func_summary",
"=",
"cpp_summary",
"+",
"py_summary",
"if",
"len",
"(",
"cpu_func_summary",
")",
"==",
"0",
":",
"return",
"for",
"row",
"in",
"cpp_summary",
":",
"items",
"=",
"row",
".",
"strip",
"(",
")",
".",
"split",
"(",
"','",
")",
"function_name",
"=",
"items",
"[",
"0",
"]",
"dev",
"=",
"\"CPU\"",
"runs",
"=",
"items",
"[",
"1",
"]",
"min_t",
"=",
"items",
"[",
"3",
"]",
"ave_t",
"=",
"items",
"[",
"4",
"]",
"max_t",
"=",
"items",
"[",
"5",
"]",
"pr_data",
".",
"append",
"(",
"[",
"function_name",
",",
"dev",
",",
"runs",
",",
"ave_t",
"]",
")",
"for",
"row",
"in",
"py_summary",
":",
"items",
"=",
"row",
".",
"strip",
"(",
")",
".",
"split",
"(",
"','",
")",
"function_name",
"=",
"\"%s@py\"",
"%",
"items",
"[",
"0",
"]",
"dev",
"=",
"\"CPU\"",
"runs",
"=",
"items",
"[",
"1",
"]",
"min_t",
"=",
"items",
"[",
"3",
"]",
"ave_t",
"=",
"items",
"[",
"4",
"]",
"max_t",
"=",
"items",
"[",
"5",
"]",
"pr_data",
".",
"append",
"(",
"[",
"function_name",
",",
"dev",
",",
"runs",
",",
"ave_t",
"]",
")",
"print",
"(",
"\"\\nCPU Functions(Not in Graph, e.g.: pre/post-processing, vai-runtime):\"",
",",
"file",
"=",
"output_f",
")",
"print_ascii_table",
"(",
"pr_data",
",",
"output_f",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Runtime/VART/vart/trace/vaitrace/writer/txt/convert.py#L169-L211 | ||
google/earthenterprise | 0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9 | earth_enterprise/src/server/wsgi/common/postgres_manager.py | python | PostgresConnection._Cursor | (self) | Opens a cursor to perform PostgreSQL command in database session.
Yields:
context manager that will be bound to cursor object.
Raises:
psycopg2.Error/Warning in case of error. | Opens a cursor to perform PostgreSQL command in database session. | [
"Opens",
"a",
"cursor",
"to",
"perform",
"PostgreSQL",
"command",
"in",
"database",
"session",
"."
] | def _Cursor(self):
"""Opens a cursor to perform PostgreSQL command in database session.
Yields:
context manager that will be bound to cursor object.
Raises:
psycopg2.Error/Warning in case of error.
"""
assert self._connection
cursor = self._connection.cursor()
try:
yield cursor
except psycopg2.Warning as w:
self._connection.rollback()
raise w
except psycopg2.Error as e:
self._connection.rollback()
raise e
else:
self._connection.commit()
finally:
cursor.close() | [
"def",
"_Cursor",
"(",
"self",
")",
":",
"assert",
"self",
".",
"_connection",
"cursor",
"=",
"self",
".",
"_connection",
".",
"cursor",
"(",
")",
"try",
":",
"yield",
"cursor",
"except",
"psycopg2",
".",
"Warning",
"as",
"w",
":",
"self",
".",
"_connection",
".",
"rollback",
"(",
")",
"raise",
"w",
"except",
"psycopg2",
".",
"Error",
"as",
"e",
":",
"self",
".",
"_connection",
".",
"rollback",
"(",
")",
"raise",
"e",
"else",
":",
"self",
".",
"_connection",
".",
"commit",
"(",
")",
"finally",
":",
"cursor",
".",
"close",
"(",
")"
] | https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/server/wsgi/common/postgres_manager.py#L296-L319 | ||
rapidsai/cudf | d5b2448fc69f17509304d594f029d0df56984962 | python/cudf/cudf/core/frame.py | python | Frame.mean | (
self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs
) | return self._reduce(
"mean",
axis=axis,
skipna=skipna,
level=level,
numeric_only=numeric_only,
**kwargs,
) | Return the mean of the values for the requested axis.
Parameters
----------
axis : {0 or 'index', 1 or 'columns'}
Axis for the function to be applied on.
skipna : bool, default True
Exclude NA/null values when computing the result.
level : int or level name, default None
If the axis is a MultiIndex (hierarchical), count along a
particular level, collapsing into a Series.
numeric_only : bool, default None
Include only float, int, boolean columns. If None, will attempt to
use everything, then use only numeric data. Not implemented for
Series.
**kwargs
Additional keyword arguments to be passed to the function.
Returns
-------
mean : Series or DataFrame (if level specified)
Examples
--------
>>> import cudf
>>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]})
>>> df.mean()
a 2.5
b 8.5
dtype: float64 | Return the mean of the values for the requested axis. | [
"Return",
"the",
"mean",
"of",
"the",
"values",
"for",
"the",
"requested",
"axis",
"."
] | def mean(
self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs
):
"""
Return the mean of the values for the requested axis.
Parameters
----------
axis : {0 or 'index', 1 or 'columns'}
Axis for the function to be applied on.
skipna : bool, default True
Exclude NA/null values when computing the result.
level : int or level name, default None
If the axis is a MultiIndex (hierarchical), count along a
particular level, collapsing into a Series.
numeric_only : bool, default None
Include only float, int, boolean columns. If None, will attempt to
use everything, then use only numeric data. Not implemented for
Series.
**kwargs
Additional keyword arguments to be passed to the function.
Returns
-------
mean : Series or DataFrame (if level specified)
Examples
--------
>>> import cudf
>>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]})
>>> df.mean()
a 2.5
b 8.5
dtype: float64
"""
return self._reduce(
"mean",
axis=axis,
skipna=skipna,
level=level,
numeric_only=numeric_only,
**kwargs,
) | [
"def",
"mean",
"(",
"self",
",",
"axis",
"=",
"None",
",",
"skipna",
"=",
"None",
",",
"level",
"=",
"None",
",",
"numeric_only",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_reduce",
"(",
"\"mean\"",
",",
"axis",
"=",
"axis",
",",
"skipna",
"=",
"skipna",
",",
"level",
"=",
"level",
",",
"numeric_only",
"=",
"numeric_only",
",",
"*",
"*",
"kwargs",
",",
")"
] | https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/frame.py#L3988-L4030 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/numbers.py | python | Real.__rdivmod__ | (self, other) | return (other // self, other % self) | divmod(other, self): The pair (self // other, self % other).
Sometimes this can be computed faster than the pair of
operations. | divmod(other, self): The pair (self // other, self % other). | [
"divmod",
"(",
"other",
"self",
")",
":",
"The",
"pair",
"(",
"self",
"//",
"other",
"self",
"%",
"other",
")",
"."
] | def __rdivmod__(self, other):
"""divmod(other, self): The pair (self // other, self % other).
Sometimes this can be computed faster than the pair of
operations.
"""
return (other // self, other % self) | [
"def",
"__rdivmod__",
"(",
"self",
",",
"other",
")",
":",
"return",
"(",
"other",
"//",
"self",
",",
"other",
"%",
"self",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/numbers.py#L205-L211 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/tools/gyp/pylib/gyp/MSVSUserFile.py | python | Writer.AddConfig | (self, name) | Adds a configuration to the project.
Args:
name: Configuration name. | Adds a configuration to the project. | [
"Adds",
"a",
"configuration",
"to",
"the",
"project",
"."
] | def AddConfig(self, name):
"""Adds a configuration to the project.
Args:
name: Configuration name.
"""
self.configurations[name] = ['Configuration', {'Name': name}] | [
"def",
"AddConfig",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"configurations",
"[",
"name",
"]",
"=",
"[",
"'Configuration'",
",",
"{",
"'Name'",
":",
"name",
"}",
"]"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/gyp/pylib/gyp/MSVSUserFile.py#L70-L76 | ||
p4lang/PI | 38d87e81253feff9fff0660d662c885be78fb719 | tools/cpplint.py | python | _CppLintState.SetFilters | (self, filters) | Sets the error-message filters.
These filters are applied when deciding whether to emit a given
error message.
Args:
filters: A string of comma-separated filters (eg "+whitespace/indent").
Each filter should start with + or -; else we die.
Raises:
ValueError: The comma-separated filters did not all start with '+' or '-'.
E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter" | Sets the error-message filters. | [
"Sets",
"the",
"error",
"-",
"message",
"filters",
"."
] | def SetFilters(self, filters):
"""Sets the error-message filters.
These filters are applied when deciding whether to emit a given
error message.
Args:
filters: A string of comma-separated filters (eg "+whitespace/indent").
Each filter should start with + or -; else we die.
Raises:
ValueError: The comma-separated filters did not all start with '+' or '-'.
E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
"""
# Default filters always have less priority than the flag ones.
self.filters = _DEFAULT_FILTERS[:]
self.AddFilters(filters) | [
"def",
"SetFilters",
"(",
"self",
",",
"filters",
")",
":",
"# Default filters always have less priority than the flag ones.",
"self",
".",
"filters",
"=",
"_DEFAULT_FILTERS",
"[",
":",
"]",
"self",
".",
"AddFilters",
"(",
"filters",
")"
] | https://github.com/p4lang/PI/blob/38d87e81253feff9fff0660d662c885be78fb719/tools/cpplint.py#L1293-L1309 | ||
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2class.py | python | uCSIsHiragana | (code) | return ret | Check whether the character is part of Hiragana UCS Block | Check whether the character is part of Hiragana UCS Block | [
"Check",
"whether",
"the",
"character",
"is",
"part",
"of",
"Hiragana",
"UCS",
"Block"
] | def uCSIsHiragana(code):
"""Check whether the character is part of Hiragana UCS Block """
ret = libxml2mod.xmlUCSIsHiragana(code)
return ret | [
"def",
"uCSIsHiragana",
"(",
"code",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlUCSIsHiragana",
"(",
"code",
")",
"return",
"ret"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L1822-L1825 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros_comm/rospy/src/rospy/client.py | python | spin | () | Blocks until ROS node is shutdown. Yields activity to other threads.
@raise ROSInitException: if node is not in a properly initialized state | Blocks until ROS node is shutdown. Yields activity to other threads. | [
"Blocks",
"until",
"ROS",
"node",
"is",
"shutdown",
".",
"Yields",
"activity",
"to",
"other",
"threads",
"."
] | def spin():
"""
Blocks until ROS node is shutdown. Yields activity to other threads.
@raise ROSInitException: if node is not in a properly initialized state
"""
if not rospy.core.is_initialized():
raise rospy.exceptions.ROSInitException("client code must call rospy.init_node() first")
logdebug("node[%s, %s] entering spin(), pid[%s]", rospy.core.get_caller_id(), rospy.core.get_node_uri(), os.getpid())
try:
while not rospy.core.is_shutdown():
rospy.rostime.wallsleep(0.5)
except KeyboardInterrupt:
logdebug("keyboard interrupt, shutting down")
rospy.core.signal_shutdown('keyboard interrupt') | [
"def",
"spin",
"(",
")",
":",
"if",
"not",
"rospy",
".",
"core",
".",
"is_initialized",
"(",
")",
":",
"raise",
"rospy",
".",
"exceptions",
".",
"ROSInitException",
"(",
"\"client code must call rospy.init_node() first\"",
")",
"logdebug",
"(",
"\"node[%s, %s] entering spin(), pid[%s]\"",
",",
"rospy",
".",
"core",
".",
"get_caller_id",
"(",
")",
",",
"rospy",
".",
"core",
".",
"get_node_uri",
"(",
")",
",",
"os",
".",
"getpid",
"(",
")",
")",
"try",
":",
"while",
"not",
"rospy",
".",
"core",
".",
"is_shutdown",
"(",
")",
":",
"rospy",
".",
"rostime",
".",
"wallsleep",
"(",
"0.5",
")",
"except",
"KeyboardInterrupt",
":",
"logdebug",
"(",
"\"keyboard interrupt, shutting down\"",
")",
"rospy",
".",
"core",
".",
"signal_shutdown",
"(",
"'keyboard interrupt'",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rospy/src/rospy/client.py#L118-L132 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | gpu/command_buffer/build_gles2_cmd_buffer.py | python | Function.GetCmdArgs | (self) | return self.cmd_args | Gets the command args for this function. | Gets the command args for this function. | [
"Gets",
"the",
"command",
"args",
"for",
"this",
"function",
"."
] | def GetCmdArgs(self):
"""Gets the command args for this function."""
return self.cmd_args | [
"def",
"GetCmdArgs",
"(",
"self",
")",
":",
"return",
"self",
".",
"cmd_args"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/gpu/command_buffer/build_gles2_cmd_buffer.py#L6409-L6411 | |
trailofbits/llvm-sanitizer-tutorial | d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99 | llvm/projects/compiler-rt/lib/sanitizer_common/scripts/cpplint.py | python | _VerboseLevel | () | return _cpplint_state.verbose_level | Returns the module's verbosity setting. | Returns the module's verbosity setting. | [
"Returns",
"the",
"module",
"s",
"verbosity",
"setting",
"."
] | def _VerboseLevel():
"""Returns the module's verbosity setting."""
return _cpplint_state.verbose_level | [
"def",
"_VerboseLevel",
"(",
")",
":",
"return",
"_cpplint_state",
".",
"verbose_level"
] | https://github.com/trailofbits/llvm-sanitizer-tutorial/blob/d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99/llvm/projects/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L641-L643 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/tensor_array_ops.py | python | _EagerTensorArray.flow | (self) | return self._flow | For compatibility; flows are not meaningful when eager is enabled. | For compatibility; flows are not meaningful when eager is enabled. | [
"For",
"compatibility",
";",
"flows",
"are",
"not",
"meaningful",
"when",
"eager",
"is",
"enabled",
"."
] | def flow(self):
"""For compatibility; flows are not meaningful when eager is enabled."""
return self._flow | [
"def",
"flow",
"(",
"self",
")",
":",
"return",
"self",
".",
"_flow"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/tensor_array_ops.py#L730-L732 | |
dartsim/dart | 495c82120c836005f2d136d4a50c8cc997fb879b | tools/cpplint.py | python | _ClassifyInclude | (fileinfo, include, is_system) | return _OTHER_HEADER | Figures out what kind of header 'include' is.
Args:
fileinfo: The current file cpplint is running over. A FileInfo instance.
include: The path to a #included file.
is_system: True if the #include used <> rather than "".
Returns:
One of the _XXX_HEADER constants.
For example:
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True)
_C_SYS_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True)
_CPP_SYS_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False)
_LIKELY_MY_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'),
... 'bar/foo_other_ext.h', False)
_POSSIBLE_MY_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False)
_OTHER_HEADER | Figures out what kind of header 'include' is. | [
"Figures",
"out",
"what",
"kind",
"of",
"header",
"include",
"is",
"."
] | def _ClassifyInclude(fileinfo, include, is_system):
"""Figures out what kind of header 'include' is.
Args:
fileinfo: The current file cpplint is running over. A FileInfo instance.
include: The path to a #included file.
is_system: True if the #include used <> rather than "".
Returns:
One of the _XXX_HEADER constants.
For example:
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True)
_C_SYS_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True)
_CPP_SYS_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False)
_LIKELY_MY_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'),
... 'bar/foo_other_ext.h', False)
_POSSIBLE_MY_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False)
_OTHER_HEADER
"""
# This is a list of all standard c++ header files, except
# those already checked for above.
is_cpp_h = include in _CPP_HEADERS
if is_system:
if is_cpp_h:
return _CPP_SYS_HEADER
else:
return _C_SYS_HEADER
# If the target file and the include we're checking share a
# basename when we drop common extensions, and the include
# lives in . , then it's likely to be owned by the target file.
target_dir, target_base = (
os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName())))
include_dir, include_base = os.path.split(_DropCommonSuffixes(include))
if target_base == include_base and (
include_dir == target_dir or
include_dir == os.path.normpath(target_dir + '/../public')):
return _LIKELY_MY_HEADER
# If the target and include share some initial basename
# component, it's possible the target is implementing the
# include, so it's allowed to be first, but we'll never
# complain if it's not there.
target_first_component = _RE_FIRST_COMPONENT.match(target_base)
include_first_component = _RE_FIRST_COMPONENT.match(include_base)
if (target_first_component and include_first_component and
target_first_component.group(0) ==
include_first_component.group(0)):
return _POSSIBLE_MY_HEADER
return _OTHER_HEADER | [
"def",
"_ClassifyInclude",
"(",
"fileinfo",
",",
"include",
",",
"is_system",
")",
":",
"# This is a list of all standard c++ header files, except",
"# those already checked for above.",
"is_cpp_h",
"=",
"include",
"in",
"_CPP_HEADERS",
"if",
"is_system",
":",
"if",
"is_cpp_h",
":",
"return",
"_CPP_SYS_HEADER",
"else",
":",
"return",
"_C_SYS_HEADER",
"# If the target file and the include we're checking share a",
"# basename when we drop common extensions, and the include",
"# lives in . , then it's likely to be owned by the target file.",
"target_dir",
",",
"target_base",
"=",
"(",
"os",
".",
"path",
".",
"split",
"(",
"_DropCommonSuffixes",
"(",
"fileinfo",
".",
"RepositoryName",
"(",
")",
")",
")",
")",
"include_dir",
",",
"include_base",
"=",
"os",
".",
"path",
".",
"split",
"(",
"_DropCommonSuffixes",
"(",
"include",
")",
")",
"if",
"target_base",
"==",
"include_base",
"and",
"(",
"include_dir",
"==",
"target_dir",
"or",
"include_dir",
"==",
"os",
".",
"path",
".",
"normpath",
"(",
"target_dir",
"+",
"'/../public'",
")",
")",
":",
"return",
"_LIKELY_MY_HEADER",
"# If the target and include share some initial basename",
"# component, it's possible the target is implementing the",
"# include, so it's allowed to be first, but we'll never",
"# complain if it's not there.",
"target_first_component",
"=",
"_RE_FIRST_COMPONENT",
".",
"match",
"(",
"target_base",
")",
"include_first_component",
"=",
"_RE_FIRST_COMPONENT",
".",
"match",
"(",
"include_base",
")",
"if",
"(",
"target_first_component",
"and",
"include_first_component",
"and",
"target_first_component",
".",
"group",
"(",
"0",
")",
"==",
"include_first_component",
".",
"group",
"(",
"0",
")",
")",
":",
"return",
"_POSSIBLE_MY_HEADER",
"return",
"_OTHER_HEADER"
] | https://github.com/dartsim/dart/blob/495c82120c836005f2d136d4a50c8cc997fb879b/tools/cpplint.py#L3477-L3533 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tarfile.py | python | TarInfo._decode_pax_field | (self, value, encoding, fallback_encoding, fallback_errors) | Decode a single field from a pax record. | Decode a single field from a pax record. | [
"Decode",
"a",
"single",
"field",
"from",
"a",
"pax",
"record",
"."
] | def _decode_pax_field(self, value, encoding, fallback_encoding, fallback_errors):
"""Decode a single field from a pax record.
"""
try:
return value.decode(encoding, "strict")
except UnicodeDecodeError:
return value.decode(fallback_encoding, fallback_errors) | [
"def",
"_decode_pax_field",
"(",
"self",
",",
"value",
",",
"encoding",
",",
"fallback_encoding",
",",
"fallback_errors",
")",
":",
"try",
":",
"return",
"value",
".",
"decode",
"(",
"encoding",
",",
"\"strict\"",
")",
"except",
"UnicodeDecodeError",
":",
"return",
"value",
".",
"decode",
"(",
"fallback_encoding",
",",
"fallback_errors",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tarfile.py#L1350-L1356 | ||
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/_ffi/function.py | python | list_global_func_names | () | return fnames | Get list of global functions registered.
Returns
-------
names : list
List of global functions names. | Get list of global functions registered. | [
"Get",
"list",
"of",
"global",
"functions",
"registered",
"."
] | def list_global_func_names():
"""Get list of global functions registered.
Returns
-------
names : list
List of global functions names.
"""
plist = ctypes.POINTER(ctypes.c_char_p)()
size = ctypes.c_uint()
check_call(_LIB.MXNetFuncListGlobalNames(ctypes.byref(size),
ctypes.byref(plist)))
fnames = []
for i in range(size.value):
fnames.append(py_str(plist[i]))
return fnames | [
"def",
"list_global_func_names",
"(",
")",
":",
"plist",
"=",
"ctypes",
".",
"POINTER",
"(",
"ctypes",
".",
"c_char_p",
")",
"(",
")",
"size",
"=",
"ctypes",
".",
"c_uint",
"(",
")",
"check_call",
"(",
"_LIB",
".",
"MXNetFuncListGlobalNames",
"(",
"ctypes",
".",
"byref",
"(",
"size",
")",
",",
"ctypes",
".",
"byref",
"(",
"plist",
")",
")",
")",
"fnames",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"size",
".",
"value",
")",
":",
"fnames",
".",
"append",
"(",
"py_str",
"(",
"plist",
"[",
"i",
"]",
")",
")",
"return",
"fnames"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/_ffi/function.py#L91-L107 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/lib2to3/main.py | python | diff_texts | (a, b, filename) | return difflib.unified_diff(a, b, filename, filename,
"(original)", "(refactored)",
lineterm="") | Return a unified diff of two strings. | Return a unified diff of two strings. | [
"Return",
"a",
"unified",
"diff",
"of",
"two",
"strings",
"."
] | def diff_texts(a, b, filename):
"""Return a unified diff of two strings."""
a = a.splitlines()
b = b.splitlines()
return difflib.unified_diff(a, b, filename, filename,
"(original)", "(refactored)",
lineterm="") | [
"def",
"diff_texts",
"(",
"a",
",",
"b",
",",
"filename",
")",
":",
"a",
"=",
"a",
".",
"splitlines",
"(",
")",
"b",
"=",
"b",
".",
"splitlines",
"(",
")",
"return",
"difflib",
".",
"unified_diff",
"(",
"a",
",",
"b",
",",
"filename",
",",
"filename",
",",
"\"(original)\"",
",",
"\"(refactored)\"",
",",
"lineterm",
"=",
"\"\"",
")"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/lib2to3/main.py#L15-L21 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib2to3/pytree.py | python | LeafPattern.__init__ | (self, type=None, content=None, name=None) | Initializer. Takes optional type, content, and name.
The type, if given must be a token type (< 256). If not given,
this matches any *leaf* node; the content may still be required.
The content, if given, must be a string.
If a name is given, the matching node is stored in the results
dict under that key. | Initializer. Takes optional type, content, and name. | [
"Initializer",
".",
"Takes",
"optional",
"type",
"content",
"and",
"name",
"."
] | def __init__(self, type=None, content=None, name=None):
"""
Initializer. Takes optional type, content, and name.
The type, if given must be a token type (< 256). If not given,
this matches any *leaf* node; the content may still be required.
The content, if given, must be a string.
If a name is given, the matching node is stored in the results
dict under that key.
"""
if type is not None:
assert 0 <= type < 256, type
if content is not None:
assert isinstance(content, basestring), repr(content)
self.type = type
self.content = content
self.name = name | [
"def",
"__init__",
"(",
"self",
",",
"type",
"=",
"None",
",",
"content",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"type",
"is",
"not",
"None",
":",
"assert",
"0",
"<=",
"type",
"<",
"256",
",",
"type",
"if",
"content",
"is",
"not",
"None",
":",
"assert",
"isinstance",
"(",
"content",
",",
"basestring",
")",
",",
"repr",
"(",
"content",
")",
"self",
".",
"type",
"=",
"type",
"self",
".",
"content",
"=",
"content",
"self",
".",
"name",
"=",
"name"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib2to3/pytree.py#L536-L554 | ||
nasa/trick | 7b85aa66329d62fe8816462627c09a353aac8299 | share/trick/pymods/trick/variable_server.py | python | VariableServer.checkpoint | (self, filename) | Dump a checkpoint.
Parameters
----------
filename : str
The checkpoint file name. The checkpoint will be saved in the
directory containing the sim's input file. | Dump a checkpoint. | [
"Dump",
"a",
"checkpoint",
"."
] | def checkpoint(self, filename):
"""
Dump a checkpoint.
Parameters
----------
filename : str
The checkpoint file name. The checkpoint will be saved in the
directory containing the sim's input file.
"""
self.send('trick.checkpoint("' + filename + '")') | [
"def",
"checkpoint",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"send",
"(",
"'trick.checkpoint(\"'",
"+",
"filename",
"+",
"'\")'",
")"
] | https://github.com/nasa/trick/blob/7b85aa66329d62fe8816462627c09a353aac8299/share/trick/pymods/trick/variable_server.py#L832-L842 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqt/mantidqt/plotting/functions.py | python | plot_from_names | (names, errors, overplot, fig=None, show_colorfill_btn=False, advanced=False,
superplot=False) | Given a list of names of workspaces, raise a dialog asking for the
a selection of what to plot and then plot it.
:param names: A list of workspace names
:param errors: If true then error bars will be plotted on the points
:param overplot: If true then the add to the current figure if one
exists and it is a compatible figure
:param fig: If not None then use this figure object to plot
:param advanced: If true then the advanced options will be shown in the spectra selector dialog.
:return: The figure containing the plot or None if selection was cancelled | Given a list of names of workspaces, raise a dialog asking for the
a selection of what to plot and then plot it. | [
"Given",
"a",
"list",
"of",
"names",
"of",
"workspaces",
"raise",
"a",
"dialog",
"asking",
"for",
"the",
"a",
"selection",
"of",
"what",
"to",
"plot",
"and",
"then",
"plot",
"it",
"."
] | def plot_from_names(names, errors, overplot, fig=None, show_colorfill_btn=False, advanced=False,
superplot=False):
"""
Given a list of names of workspaces, raise a dialog asking for the
a selection of what to plot and then plot it.
:param names: A list of workspace names
:param errors: If true then error bars will be plotted on the points
:param overplot: If true then the add to the current figure if one
exists and it is a compatible figure
:param fig: If not None then use this figure object to plot
:param advanced: If true then the advanced options will be shown in the spectra selector dialog.
:return: The figure containing the plot or None if selection was cancelled
"""
# Get workspaces from ADS with names
workspaces = AnalysisDataService.Instance().retrieveWorkspaces(names, unrollGroups=True)
try:
# Get selected spectra from all MatrixWorkspaces
selection = get_spectra_selection(workspaces, show_colorfill_btn=show_colorfill_btn, overplot=overplot,
advanced=advanced)
except Exception as exc:
LOGGER.warning(format(str(exc)))
selection = None
if selection is None:
return None
elif selection == 'colorfill':
# plot mesh for color fill
return pcolormesh_from_names(names)
log_values = None
if advanced:
errors = selection.errors
nums = selection.spectra if selection.spectra is not None else selection.wksp_indices
if selection.log_name not in ['Workspace name', 'Workspace index']:
log_values = []
counter = 0
for workspace in workspaces:
for _ in nums:
if selection.custom_log_values is not None:
log_values.append(
get_single_workspace_log_value(counter, log_values=selection.custom_log_values))
counter += 1
else:
log_values.append(
get_single_workspace_log_value(1, matrix_ws=workspace, log_name=selection.log_name))
if selection.plot_type == selection.Surface or selection.plot_type == selection.Contour:
if selection.spectra is not None:
plot_index = workspaces[0].getIndexFromSpectrumNumber(selection.spectra[0])
else:
plot_index = selection.wksp_indices[0]
# import here to avoid circular import
from mantid.plots.surfacecontourplots import plot as plot_surface_or_contour
return plot_surface_or_contour(selection.plot_type, int(plot_index), selection.axis_name, selection.log_name,
selection.custom_log_values, workspaces)
else:
return plot(selection.workspaces, spectrum_nums=selection.spectra,
wksp_indices=selection.wksp_indices,
errors=errors, overplot=overplot, fig=fig, tiled=selection.plot_type == selection.Tiled,
waterfall=selection.plot_type == selection.Waterfall,
log_name=selection.log_name, log_values=log_values, superplot=superplot) | [
"def",
"plot_from_names",
"(",
"names",
",",
"errors",
",",
"overplot",
",",
"fig",
"=",
"None",
",",
"show_colorfill_btn",
"=",
"False",
",",
"advanced",
"=",
"False",
",",
"superplot",
"=",
"False",
")",
":",
"# Get workspaces from ADS with names",
"workspaces",
"=",
"AnalysisDataService",
".",
"Instance",
"(",
")",
".",
"retrieveWorkspaces",
"(",
"names",
",",
"unrollGroups",
"=",
"True",
")",
"try",
":",
"# Get selected spectra from all MatrixWorkspaces",
"selection",
"=",
"get_spectra_selection",
"(",
"workspaces",
",",
"show_colorfill_btn",
"=",
"show_colorfill_btn",
",",
"overplot",
"=",
"overplot",
",",
"advanced",
"=",
"advanced",
")",
"except",
"Exception",
"as",
"exc",
":",
"LOGGER",
".",
"warning",
"(",
"format",
"(",
"str",
"(",
"exc",
")",
")",
")",
"selection",
"=",
"None",
"if",
"selection",
"is",
"None",
":",
"return",
"None",
"elif",
"selection",
"==",
"'colorfill'",
":",
"# plot mesh for color fill",
"return",
"pcolormesh_from_names",
"(",
"names",
")",
"log_values",
"=",
"None",
"if",
"advanced",
":",
"errors",
"=",
"selection",
".",
"errors",
"nums",
"=",
"selection",
".",
"spectra",
"if",
"selection",
".",
"spectra",
"is",
"not",
"None",
"else",
"selection",
".",
"wksp_indices",
"if",
"selection",
".",
"log_name",
"not",
"in",
"[",
"'Workspace name'",
",",
"'Workspace index'",
"]",
":",
"log_values",
"=",
"[",
"]",
"counter",
"=",
"0",
"for",
"workspace",
"in",
"workspaces",
":",
"for",
"_",
"in",
"nums",
":",
"if",
"selection",
".",
"custom_log_values",
"is",
"not",
"None",
":",
"log_values",
".",
"append",
"(",
"get_single_workspace_log_value",
"(",
"counter",
",",
"log_values",
"=",
"selection",
".",
"custom_log_values",
")",
")",
"counter",
"+=",
"1",
"else",
":",
"log_values",
".",
"append",
"(",
"get_single_workspace_log_value",
"(",
"1",
",",
"matrix_ws",
"=",
"workspace",
",",
"log_name",
"=",
"selection",
".",
"log_name",
")",
")",
"if",
"selection",
".",
"plot_type",
"==",
"selection",
".",
"Surface",
"or",
"selection",
".",
"plot_type",
"==",
"selection",
".",
"Contour",
":",
"if",
"selection",
".",
"spectra",
"is",
"not",
"None",
":",
"plot_index",
"=",
"workspaces",
"[",
"0",
"]",
".",
"getIndexFromSpectrumNumber",
"(",
"selection",
".",
"spectra",
"[",
"0",
"]",
")",
"else",
":",
"plot_index",
"=",
"selection",
".",
"wksp_indices",
"[",
"0",
"]",
"# import here to avoid circular import",
"from",
"mantid",
".",
"plots",
".",
"surfacecontourplots",
"import",
"plot",
"as",
"plot_surface_or_contour",
"return",
"plot_surface_or_contour",
"(",
"selection",
".",
"plot_type",
",",
"int",
"(",
"plot_index",
")",
",",
"selection",
".",
"axis_name",
",",
"selection",
".",
"log_name",
",",
"selection",
".",
"custom_log_values",
",",
"workspaces",
")",
"else",
":",
"return",
"plot",
"(",
"selection",
".",
"workspaces",
",",
"spectrum_nums",
"=",
"selection",
".",
"spectra",
",",
"wksp_indices",
"=",
"selection",
".",
"wksp_indices",
",",
"errors",
"=",
"errors",
",",
"overplot",
"=",
"overplot",
",",
"fig",
"=",
"fig",
",",
"tiled",
"=",
"selection",
".",
"plot_type",
"==",
"selection",
".",
"Tiled",
",",
"waterfall",
"=",
"selection",
".",
"plot_type",
"==",
"selection",
".",
"Waterfall",
",",
"log_name",
"=",
"selection",
".",
"log_name",
",",
"log_values",
"=",
"log_values",
",",
"superplot",
"=",
"superplot",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/plotting/functions.py#L127-L193 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/idlelib/rpc.py | python | SocketIO.exithook | (self) | override for specific exit action | override for specific exit action | [
"override",
"for",
"specific",
"exit",
"action"
] | def exithook(self):
"override for specific exit action"
os._exit(0) | [
"def",
"exithook",
"(",
"self",
")",
":",
"os",
".",
"_exit",
"(",
"0",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/idlelib/rpc.py#L145-L147 | ||
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | PNEANet.FltAttrValueEI | (self, *args) | return _snap.PNEANet_FltAttrValueEI(self, *args) | FltAttrValueEI(PNEANet self, TInt EId, TFltV & Values)
Parameters:
EId: TInt const &
Values: TFltV &
FltAttrValueEI(PNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TFltV & Values)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Values: TFltV & | FltAttrValueEI(PNEANet self, TInt EId, TFltV & Values) | [
"FltAttrValueEI",
"(",
"PNEANet",
"self",
"TInt",
"EId",
"TFltV",
"&",
"Values",
")"
] | def FltAttrValueEI(self, *args):
"""
FltAttrValueEI(PNEANet self, TInt EId, TFltV & Values)
Parameters:
EId: TInt const &
Values: TFltV &
FltAttrValueEI(PNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TFltV & Values)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Values: TFltV &
"""
return _snap.PNEANet_FltAttrValueEI(self, *args) | [
"def",
"FltAttrValueEI",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_snap",
".",
"PNEANet_FltAttrValueEI",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L23596-L23612 | |
cmu-db/bustub | fe1b9e984bd2967997b52df872c873d80f71cf7d | build_support/cpplint.py | python | CheckIncludeLine | (filename, clean_lines, linenum, include_state, error) | Check rules that are applicable to #include lines.
Strings on #include lines are NOT removed from elided line, to make
certain tasks easier. However, to prevent false positives, checks
applicable to #include lines in CheckLanguage must be put here.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
include_state: An _IncludeState instance in which the headers are inserted.
error: The function to call with any errors found. | Check rules that are applicable to #include lines. | [
"Check",
"rules",
"that",
"are",
"applicable",
"to",
"#include",
"lines",
"."
] | def CheckIncludeLine(filename, clean_lines, linenum, include_state, error):
"""Check rules that are applicable to #include lines.
Strings on #include lines are NOT removed from elided line, to make
certain tasks easier. However, to prevent false positives, checks
applicable to #include lines in CheckLanguage must be put here.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
include_state: An _IncludeState instance in which the headers are inserted.
error: The function to call with any errors found.
"""
fileinfo = FileInfo(filename)
line = clean_lines.lines[linenum]
# "include" should use the new style "foo/bar.h" instead of just "bar.h"
# Only do this check if the included header follows google naming
# conventions. If not, assume that it's a 3rd party API that
# requires special include conventions.
#
# We also make an exception for Lua headers, which follow google
# naming convention but not the include convention.
match = Match(r'#include\s*"([^/]+\.h)"', line)
if match and not _THIRD_PARTY_HEADERS_PATTERN.match(match.group(1)):
error(filename, linenum, 'build/include_subdir', 4,
'Include the directory when naming .h files')
# we shouldn't include a file more than once. actually, there are a
# handful of instances where doing so is okay, but in general it's
# not.
match = _RE_PATTERN_INCLUDE.search(line)
if match:
include = match.group(2)
is_system = (match.group(1) == '<')
duplicate_line = include_state.FindHeader(include)
if duplicate_line >= 0:
error(filename, linenum, 'build/include', 4,
'"%s" already included at %s:%s' %
(include, filename, duplicate_line))
return
for extension in GetNonHeaderExtensions():
if (include.endswith('.' + extension) and
os.path.dirname(fileinfo.RepositoryName()) != os.path.dirname(include)):
error(filename, linenum, 'build/include', 4,
'Do not include .' + extension + ' files from other packages')
return
# We DO want to include a 3rd party looking header if it matches the
# filename. Otherwise we get an erroneous error "...should include its
# header" error later.
third_src_header = False
for ext in GetHeaderExtensions():
basefilename = filename[0:len(filename) - len(fileinfo.Extension())]
headerfile = basefilename + '.' + ext
headername = FileInfo(headerfile).RepositoryName()
if headername in include or include in headername:
third_src_header = True
break
if third_src_header or not _THIRD_PARTY_HEADERS_PATTERN.match(include):
include_state.include_list[-1].append((include, linenum))
# We want to ensure that headers appear in the right order:
# 1) for foo.cc, foo.h (preferred location)
# 2) c system files
# 3) cpp system files
# 4) for foo.cc, foo.h (deprecated location)
# 5) other google headers
#
# We classify each include statement as one of those 5 types
# using a number of techniques. The include_state object keeps
# track of the highest type seen, and complains if we see a
# lower type after that.
error_message = include_state.CheckNextIncludeOrder(
_ClassifyInclude(fileinfo, include, is_system))
if error_message:
error(filename, linenum, 'build/include_order', 4,
'%s. Should be: %s.h, c system, c++ system, other.' %
(error_message, fileinfo.BaseName()))
canonical_include = include_state.CanonicalizeAlphabeticalOrder(include)
if not include_state.IsInAlphabeticalOrder(
clean_lines, linenum, canonical_include):
error(filename, linenum, 'build/include_alpha', 4,
'Include "%s" not in alphabetical order' % include)
include_state.SetLastHeader(canonical_include) | [
"def",
"CheckIncludeLine",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"include_state",
",",
"error",
")",
":",
"fileinfo",
"=",
"FileInfo",
"(",
"filename",
")",
"line",
"=",
"clean_lines",
".",
"lines",
"[",
"linenum",
"]",
"# \"include\" should use the new style \"foo/bar.h\" instead of just \"bar.h\"",
"# Only do this check if the included header follows google naming",
"# conventions. If not, assume that it's a 3rd party API that",
"# requires special include conventions.",
"#",
"# We also make an exception for Lua headers, which follow google",
"# naming convention but not the include convention.",
"match",
"=",
"Match",
"(",
"r'#include\\s*\"([^/]+\\.h)\"'",
",",
"line",
")",
"if",
"match",
"and",
"not",
"_THIRD_PARTY_HEADERS_PATTERN",
".",
"match",
"(",
"match",
".",
"group",
"(",
"1",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/include_subdir'",
",",
"4",
",",
"'Include the directory when naming .h files'",
")",
"# we shouldn't include a file more than once. actually, there are a",
"# handful of instances where doing so is okay, but in general it's",
"# not.",
"match",
"=",
"_RE_PATTERN_INCLUDE",
".",
"search",
"(",
"line",
")",
"if",
"match",
":",
"include",
"=",
"match",
".",
"group",
"(",
"2",
")",
"is_system",
"=",
"(",
"match",
".",
"group",
"(",
"1",
")",
"==",
"'<'",
")",
"duplicate_line",
"=",
"include_state",
".",
"FindHeader",
"(",
"include",
")",
"if",
"duplicate_line",
">=",
"0",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/include'",
",",
"4",
",",
"'\"%s\" already included at %s:%s'",
"%",
"(",
"include",
",",
"filename",
",",
"duplicate_line",
")",
")",
"return",
"for",
"extension",
"in",
"GetNonHeaderExtensions",
"(",
")",
":",
"if",
"(",
"include",
".",
"endswith",
"(",
"'.'",
"+",
"extension",
")",
"and",
"os",
".",
"path",
".",
"dirname",
"(",
"fileinfo",
".",
"RepositoryName",
"(",
")",
")",
"!=",
"os",
".",
"path",
".",
"dirname",
"(",
"include",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/include'",
",",
"4",
",",
"'Do not include .'",
"+",
"extension",
"+",
"' files from other packages'",
")",
"return",
"# We DO want to include a 3rd party looking header if it matches the",
"# filename. Otherwise we get an erroneous error \"...should include its",
"# header\" error later.",
"third_src_header",
"=",
"False",
"for",
"ext",
"in",
"GetHeaderExtensions",
"(",
")",
":",
"basefilename",
"=",
"filename",
"[",
"0",
":",
"len",
"(",
"filename",
")",
"-",
"len",
"(",
"fileinfo",
".",
"Extension",
"(",
")",
")",
"]",
"headerfile",
"=",
"basefilename",
"+",
"'.'",
"+",
"ext",
"headername",
"=",
"FileInfo",
"(",
"headerfile",
")",
".",
"RepositoryName",
"(",
")",
"if",
"headername",
"in",
"include",
"or",
"include",
"in",
"headername",
":",
"third_src_header",
"=",
"True",
"break",
"if",
"third_src_header",
"or",
"not",
"_THIRD_PARTY_HEADERS_PATTERN",
".",
"match",
"(",
"include",
")",
":",
"include_state",
".",
"include_list",
"[",
"-",
"1",
"]",
".",
"append",
"(",
"(",
"include",
",",
"linenum",
")",
")",
"# We want to ensure that headers appear in the right order:",
"# 1) for foo.cc, foo.h (preferred location)",
"# 2) c system files",
"# 3) cpp system files",
"# 4) for foo.cc, foo.h (deprecated location)",
"# 5) other google headers",
"#",
"# We classify each include statement as one of those 5 types",
"# using a number of techniques. The include_state object keeps",
"# track of the highest type seen, and complains if we see a",
"# lower type after that.",
"error_message",
"=",
"include_state",
".",
"CheckNextIncludeOrder",
"(",
"_ClassifyInclude",
"(",
"fileinfo",
",",
"include",
",",
"is_system",
")",
")",
"if",
"error_message",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/include_order'",
",",
"4",
",",
"'%s. Should be: %s.h, c system, c++ system, other.'",
"%",
"(",
"error_message",
",",
"fileinfo",
".",
"BaseName",
"(",
")",
")",
")",
"canonical_include",
"=",
"include_state",
".",
"CanonicalizeAlphabeticalOrder",
"(",
"include",
")",
"if",
"not",
"include_state",
".",
"IsInAlphabeticalOrder",
"(",
"clean_lines",
",",
"linenum",
",",
"canonical_include",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/include_alpha'",
",",
"4",
",",
"'Include \"%s\" not in alphabetical order'",
"%",
"include",
")",
"include_state",
".",
"SetLastHeader",
"(",
"canonical_include",
")"
] | https://github.com/cmu-db/bustub/blob/fe1b9e984bd2967997b52df872c873d80f71cf7d/build_support/cpplint.py#L4777-L4864 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/lib/io/file_io.py | python | copy_v2 | (src, dst, overwrite=False) | Copies data from `src` to `dst`.
>>> with open("/tmp/x", "w") as f:
... f.write("asdf")
...
4
>>> tf.io.gfile.exists("/tmp/x")
True
>>> tf.io.gfile.copy("/tmp/x", "/tmp/y")
>>> tf.io.gfile.exists("/tmp/y")
True
>>> tf.io.gfile.remove("/tmp/y")
You can also specify the URI scheme for selecting a different filesystem:
>>> with open("/tmp/x", "w") as f:
... f.write("asdf")
...
4
>>> tf.io.gfile.copy("/tmp/x", "file:///tmp/y")
>>> tf.io.gfile.exists("/tmp/y")
True
>>> tf.io.gfile.remove("/tmp/y")
Note that you need to always specify a file name, even if moving into a new
directory. This is because some cloud filesystems don't have the concept of a
directory.
>>> with open("/tmp/x", "w") as f:
... f.write("asdf")
...
4
>>> tf.io.gfile.mkdir("/tmp/new_dir")
>>> tf.io.gfile.copy("/tmp/x", "/tmp/new_dir/y")
>>> tf.io.gfile.exists("/tmp/new_dir/y")
True
>>> tf.io.gfile.rmtree("/tmp/new_dir")
If you want to prevent errors if the path already exists, you can use
`overwrite` argument:
>>> with open("/tmp/x", "w") as f:
... f.write("asdf")
...
4
>>> tf.io.gfile.copy("/tmp/x", "file:///tmp/y")
>>> tf.io.gfile.copy("/tmp/x", "file:///tmp/y", overwrite=True)
>>> tf.io.gfile.remove("/tmp/y")
Note that the above will still result in an error if you try to overwrite a
directory with a file.
Note that you cannot copy a directory, only file arguments are supported.
Args:
src: string, name of the file whose contents need to be copied
dst: string, name of the file to which to copy to
overwrite: boolean, if false it's an error for `dst` to be occupied by an
existing file.
Raises:
errors.OpError: If the operation fails. | Copies data from `src` to `dst`. | [
"Copies",
"data",
"from",
"src",
"to",
"dst",
"."
] | def copy_v2(src, dst, overwrite=False):
"""Copies data from `src` to `dst`.
>>> with open("/tmp/x", "w") as f:
... f.write("asdf")
...
4
>>> tf.io.gfile.exists("/tmp/x")
True
>>> tf.io.gfile.copy("/tmp/x", "/tmp/y")
>>> tf.io.gfile.exists("/tmp/y")
True
>>> tf.io.gfile.remove("/tmp/y")
You can also specify the URI scheme for selecting a different filesystem:
>>> with open("/tmp/x", "w") as f:
... f.write("asdf")
...
4
>>> tf.io.gfile.copy("/tmp/x", "file:///tmp/y")
>>> tf.io.gfile.exists("/tmp/y")
True
>>> tf.io.gfile.remove("/tmp/y")
Note that you need to always specify a file name, even if moving into a new
directory. This is because some cloud filesystems don't have the concept of a
directory.
>>> with open("/tmp/x", "w") as f:
... f.write("asdf")
...
4
>>> tf.io.gfile.mkdir("/tmp/new_dir")
>>> tf.io.gfile.copy("/tmp/x", "/tmp/new_dir/y")
>>> tf.io.gfile.exists("/tmp/new_dir/y")
True
>>> tf.io.gfile.rmtree("/tmp/new_dir")
If you want to prevent errors if the path already exists, you can use
`overwrite` argument:
>>> with open("/tmp/x", "w") as f:
... f.write("asdf")
...
4
>>> tf.io.gfile.copy("/tmp/x", "file:///tmp/y")
>>> tf.io.gfile.copy("/tmp/x", "file:///tmp/y", overwrite=True)
>>> tf.io.gfile.remove("/tmp/y")
Note that the above will still result in an error if you try to overwrite a
directory with a file.
Note that you cannot copy a directory, only file arguments are supported.
Args:
src: string, name of the file whose contents need to be copied
dst: string, name of the file to which to copy to
overwrite: boolean, if false it's an error for `dst` to be occupied by an
existing file.
Raises:
errors.OpError: If the operation fails.
"""
_pywrap_file_io.CopyFile(
compat.path_to_bytes(src), compat.path_to_bytes(dst), overwrite) | [
"def",
"copy_v2",
"(",
"src",
",",
"dst",
",",
"overwrite",
"=",
"False",
")",
":",
"_pywrap_file_io",
".",
"CopyFile",
"(",
"compat",
".",
"path_to_bytes",
"(",
"src",
")",
",",
"compat",
".",
"path_to_bytes",
"(",
"dst",
")",
",",
"overwrite",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/lib/io/file_io.py#L515-L580 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/ops/tensor_array_grad.py | python | _TensorArrayUnpackGrad | (op, flow) | return [None, grad, flow] | Gradient for TensorArrayUnpack.
Args:
op: Forward TensorArrayUnpack op.
flow: Gradient `Tensor` flow to TensorArrayUnpack.
Returns:
A grad `Tensor`, the gradient created in upstream ReadGrads or PackGrad. | Gradient for TensorArrayUnpack. | [
"Gradient",
"for",
"TensorArrayUnpack",
"."
] | def _TensorArrayUnpackGrad(op, flow):
"""Gradient for TensorArrayUnpack.
Args:
op: Forward TensorArrayUnpack op.
flow: Gradient `Tensor` flow to TensorArrayUnpack.
Returns:
A grad `Tensor`, the gradient created in upstream ReadGrads or PackGrad.
"""
handle = op.inputs[0]
dtype = op.get_attr("T")
grad_source = _GetGradSource(flow)
g = tensor_array_ops.TensorArray(dtype=dtype, handle=handle).grad(
source=grad_source, flow=flow)
grad = g.pack()
return [None, grad, flow] | [
"def",
"_TensorArrayUnpackGrad",
"(",
"op",
",",
"flow",
")",
":",
"handle",
"=",
"op",
".",
"inputs",
"[",
"0",
"]",
"dtype",
"=",
"op",
".",
"get_attr",
"(",
"\"T\"",
")",
"grad_source",
"=",
"_GetGradSource",
"(",
"flow",
")",
"g",
"=",
"tensor_array_ops",
".",
"TensorArray",
"(",
"dtype",
"=",
"dtype",
",",
"handle",
"=",
"handle",
")",
".",
"grad",
"(",
"source",
"=",
"grad_source",
",",
"flow",
"=",
"flow",
")",
"grad",
"=",
"g",
".",
"pack",
"(",
")",
"return",
"[",
"None",
",",
"grad",
",",
"flow",
"]"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/tensor_array_grad.py#L147-L163 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/pty.py | python | slave_open | (tty_name) | return result | slave_open(tty_name) -> slave_fd
Open the pty slave and acquire the controlling terminal, returning
opened filedescriptor.
Deprecated, use openpty() instead. | slave_open(tty_name) -> slave_fd
Open the pty slave and acquire the controlling terminal, returning
opened filedescriptor.
Deprecated, use openpty() instead. | [
"slave_open",
"(",
"tty_name",
")",
"-",
">",
"slave_fd",
"Open",
"the",
"pty",
"slave",
"and",
"acquire",
"the",
"controlling",
"terminal",
"returning",
"opened",
"filedescriptor",
".",
"Deprecated",
"use",
"openpty",
"()",
"instead",
"."
] | def slave_open(tty_name):
"""slave_open(tty_name) -> slave_fd
Open the pty slave and acquire the controlling terminal, returning
opened filedescriptor.
Deprecated, use openpty() instead."""
result = os.open(tty_name, os.O_RDWR)
try:
from fcntl import ioctl, I_PUSH
except ImportError:
return result
try:
ioctl(result, I_PUSH, "ptem")
ioctl(result, I_PUSH, "ldterm")
except IOError:
pass
return result | [
"def",
"slave_open",
"(",
"tty_name",
")",
":",
"result",
"=",
"os",
".",
"open",
"(",
"tty_name",
",",
"os",
".",
"O_RDWR",
")",
"try",
":",
"from",
"fcntl",
"import",
"ioctl",
",",
"I_PUSH",
"except",
"ImportError",
":",
"return",
"result",
"try",
":",
"ioctl",
"(",
"result",
",",
"I_PUSH",
",",
"\"ptem\"",
")",
"ioctl",
"(",
"result",
",",
"I_PUSH",
",",
"\"ldterm\"",
")",
"except",
"IOError",
":",
"pass",
"return",
"result"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/pty.py#L72-L88 | |
cvxpy/cvxpy | 5165b4fb750dfd237de8659383ef24b4b2e33aaf | cvxpy/atoms/affine/transpose.py | python | transpose.is_hermitian | (self) | return self.args[0].is_hermitian() | Is the expression Hermitian? | Is the expression Hermitian? | [
"Is",
"the",
"expression",
"Hermitian?"
] | def is_hermitian(self) -> bool:
"""Is the expression Hermitian?
"""
return self.args[0].is_hermitian() | [
"def",
"is_hermitian",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"args",
"[",
"0",
"]",
".",
"is_hermitian",
"(",
")"
] | https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/atoms/affine/transpose.py#L58-L61 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/grid.py | python | Grid.GetColAt | (*args, **kwargs) | return _grid.Grid_GetColAt(*args, **kwargs) | GetColAt(self, int colPos) -> int | GetColAt(self, int colPos) -> int | [
"GetColAt",
"(",
"self",
"int",
"colPos",
")",
"-",
">",
"int"
] | def GetColAt(*args, **kwargs):
"""GetColAt(self, int colPos) -> int"""
return _grid.Grid_GetColAt(*args, **kwargs) | [
"def",
"GetColAt",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"Grid_GetColAt",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/grid.py#L1866-L1868 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/xml/sax/handler.py | python | ContentHandler.endElementNS | (self, name, qname) | Signals the end of an element in namespace mode.
The name parameter contains the name of the element type, just
as with the startElementNS event. | Signals the end of an element in namespace mode. | [
"Signals",
"the",
"end",
"of",
"an",
"element",
"in",
"namespace",
"mode",
"."
] | def endElementNS(self, name, qname):
"""Signals the end of an element in namespace mode.
The name parameter contains the name of the element type, just
as with the startElementNS event.""" | [
"def",
"endElementNS",
"(",
"self",
",",
"name",
",",
"qname",
")",
":"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/xml/sax/handler.py#L152-L156 | ||
netket/netket | 0d534e54ecbf25b677ea72af6b85947979420652 | netket/hilbert/discrete_hilbert.py | python | DiscreteHilbert.__init__ | (self, shape: Tuple[int, ...]) | Initializes a discrete Hilbert space with a basis of given shape.
Args:
shape: The local dimension of the Hilbert space for each degree
of freedom. | Initializes a discrete Hilbert space with a basis of given shape. | [
"Initializes",
"a",
"discrete",
"Hilbert",
"space",
"with",
"a",
"basis",
"of",
"given",
"shape",
"."
] | def __init__(self, shape: Tuple[int, ...]):
"""
Initializes a discrete Hilbert space with a basis of given shape.
Args:
shape: The local dimension of the Hilbert space for each degree
of freedom.
"""
self._shape = shape
super().__init__() | [
"def",
"__init__",
"(",
"self",
",",
"shape",
":",
"Tuple",
"[",
"int",
",",
"...",
"]",
")",
":",
"self",
".",
"_shape",
"=",
"shape",
"super",
"(",
")",
".",
"__init__",
"(",
")"
] | https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/netket/hilbert/discrete_hilbert.py#L61-L71 | ||
hakuna-m/wubiuefi | caec1af0a09c78fd5a345180ada1fe45e0c63493 | src/openpgp/sap/pkt/Packet.py | python | create_Packet | (pkttype, body_d) | return pktclass(pkttype)(tag_d + length_d + body_d) | Create a Packet instance of the appropriate type.
:Parameters:
- `pkttype`: integer packet type constant (see
`OpenPGP.constant.packets`)
- `body_d`: string comprising the packet body
:Returns: `Packet` subclass instance | Create a Packet instance of the appropriate type. | [
"Create",
"a",
"Packet",
"instance",
"of",
"the",
"appropriate",
"type",
"."
] | def create_Packet(pkttype, body_d):
"""Create a Packet instance of the appropriate type.
:Parameters:
- `pkttype`: integer packet type constant (see
`OpenPGP.constant.packets`)
- `body_d`: string comprising the packet body
:Returns: `Packet` subclass instance
"""
tag_d = create_Tag(pkttype)._d
length_d = create_NewLength(len(body_d))._d
return pktclass(pkttype)(tag_d + length_d + body_d) | [
"def",
"create_Packet",
"(",
"pkttype",
",",
"body_d",
")",
":",
"tag_d",
"=",
"create_Tag",
"(",
"pkttype",
")",
".",
"_d",
"length_d",
"=",
"create_NewLength",
"(",
"len",
"(",
"body_d",
")",
")",
".",
"_d",
"return",
"pktclass",
"(",
"pkttype",
")",
"(",
"tag_d",
"+",
"length_d",
"+",
"body_d",
")"
] | https://github.com/hakuna-m/wubiuefi/blob/caec1af0a09c78fd5a345180ada1fe45e0c63493/src/openpgp/sap/pkt/Packet.py#L446-L458 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | Menu.__init__ | (self, *args, **kwargs) | __init__(self, String title=EmptyString, long style=0) -> Menu | __init__(self, String title=EmptyString, long style=0) -> Menu | [
"__init__",
"(",
"self",
"String",
"title",
"=",
"EmptyString",
"long",
"style",
"=",
"0",
")",
"-",
">",
"Menu"
] | def __init__(self, *args, **kwargs):
"""__init__(self, String title=EmptyString, long style=0) -> Menu"""
_core_.Menu_swiginit(self,_core_.new_Menu(*args, **kwargs))
self._setOORInfo(self) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_core_",
".",
"Menu_swiginit",
"(",
"self",
",",
"_core_",
".",
"new_Menu",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"self",
".",
"_setOORInfo",
"(",
"self",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L11997-L12000 | ||
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | src/pybind/mgr/cephadm/module.py | python | CephadmOrchestrator.drain_host | (self, hostname) | return "Scheduled to remove the following daemons from host '{}'\n{}".format(hostname, daemons_table) | Drain all daemons from a host.
:param host: host name | Drain all daemons from a host.
:param host: host name | [
"Drain",
"all",
"daemons",
"from",
"a",
"host",
".",
":",
"param",
"host",
":",
"host",
"name"
] | def drain_host(self, hostname):
# type: (str) -> str
"""
Drain all daemons from a host.
:param host: host name
"""
self.add_host_label(hostname, '_no_schedule')
daemons: List[orchestrator.DaemonDescription] = self.cache.get_daemons_by_host(hostname)
osds_to_remove = [d.daemon_id for d in daemons if d.daemon_type == 'osd']
self.remove_osds(osds_to_remove)
daemons_table = ""
daemons_table += "{:<20} {:<15}\n".format("type", "id")
daemons_table += "{:<20} {:<15}\n".format("-" * 20, "-" * 15)
for d in daemons:
daemons_table += "{:<20} {:<15}\n".format(d.daemon_type, d.daemon_id)
return "Scheduled to remove the following daemons from host '{}'\n{}".format(hostname, daemons_table) | [
"def",
"drain_host",
"(",
"self",
",",
"hostname",
")",
":",
"# type: (str) -> str",
"self",
".",
"add_host_label",
"(",
"hostname",
",",
"'_no_schedule'",
")",
"daemons",
":",
"List",
"[",
"orchestrator",
".",
"DaemonDescription",
"]",
"=",
"self",
".",
"cache",
".",
"get_daemons_by_host",
"(",
"hostname",
")",
"osds_to_remove",
"=",
"[",
"d",
".",
"daemon_id",
"for",
"d",
"in",
"daemons",
"if",
"d",
".",
"daemon_type",
"==",
"'osd'",
"]",
"self",
".",
"remove_osds",
"(",
"osds_to_remove",
")",
"daemons_table",
"=",
"\"\"",
"daemons_table",
"+=",
"\"{:<20} {:<15}\\n\"",
".",
"format",
"(",
"\"type\"",
",",
"\"id\"",
")",
"daemons_table",
"+=",
"\"{:<20} {:<15}\\n\"",
".",
"format",
"(",
"\"-\"",
"*",
"20",
",",
"\"-\"",
"*",
"15",
")",
"for",
"d",
"in",
"daemons",
":",
"daemons_table",
"+=",
"\"{:<20} {:<15}\\n\"",
".",
"format",
"(",
"d",
".",
"daemon_type",
",",
"d",
".",
"daemon_id",
")",
"return",
"\"Scheduled to remove the following daemons from host '{}'\\n{}\"",
".",
"format",
"(",
"hostname",
",",
"daemons_table",
")"
] | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/pybind/mgr/cephadm/module.py#L2704-L2723 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/serialize.py | python | _reduce_function | (func, globs) | return _reduce_code(func.__code__), globs, func.__name__, cells | Reduce a Python function and its globals to picklable components.
If there are cell variables (i.e. references to a closure), their
values will be frozen. | Reduce a Python function and its globals to picklable components.
If there are cell variables (i.e. references to a closure), their
values will be frozen. | [
"Reduce",
"a",
"Python",
"function",
"and",
"its",
"globals",
"to",
"picklable",
"components",
".",
"If",
"there",
"are",
"cell",
"variables",
"(",
"i",
".",
"e",
".",
"references",
"to",
"a",
"closure",
")",
"their",
"values",
"will",
"be",
"frozen",
"."
] | def _reduce_function(func, globs):
"""
Reduce a Python function and its globals to picklable components.
If there are cell variables (i.e. references to a closure), their
values will be frozen.
"""
if func.__closure__:
cells = [cell.cell_contents for cell in func.__closure__]
else:
cells = None
return _reduce_code(func.__code__), globs, func.__name__, cells | [
"def",
"_reduce_function",
"(",
"func",
",",
"globs",
")",
":",
"if",
"func",
".",
"__closure__",
":",
"cells",
"=",
"[",
"cell",
".",
"cell_contents",
"for",
"cell",
"in",
"func",
".",
"__closure__",
"]",
"else",
":",
"cells",
"=",
"None",
"return",
"_reduce_code",
"(",
"func",
".",
"__code__",
")",
",",
"globs",
",",
"func",
".",
"__name__",
",",
"cells"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/serialize.py#L67-L77 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/stc.py | python | StyledTextCtrl.VCHomeExtend | (*args, **kwargs) | return _stc.StyledTextCtrl_VCHomeExtend(*args, **kwargs) | VCHomeExtend(self)
Like VCHome but extending selection to new caret position. | VCHomeExtend(self) | [
"VCHomeExtend",
"(",
"self",
")"
] | def VCHomeExtend(*args, **kwargs):
"""
VCHomeExtend(self)
Like VCHome but extending selection to new caret position.
"""
return _stc.StyledTextCtrl_VCHomeExtend(*args, **kwargs) | [
"def",
"VCHomeExtend",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_VCHomeExtend",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L4588-L4594 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/model/trajectory.py | python | Trajectory.deriv | (self,t,endBehavior='halt') | return self.deriv_state(t,endBehavior) | Evaluates the trajectory velocity using piecewise linear
interpolation.
Args:
t (float): The time at which to evaluate the segment
endBehavior (str): If 'loop' then the trajectory loops forever.
Returns:
(:obj:`list` of :obj:`float`): the velocity (derivative) at time t | Evaluates the trajectory velocity using piecewise linear
interpolation. | [
"Evaluates",
"the",
"trajectory",
"velocity",
"using",
"piecewise",
"linear",
"interpolation",
"."
] | def deriv(self,t,endBehavior='halt'):
"""Evaluates the trajectory velocity using piecewise linear
interpolation.
Args:
t (float): The time at which to evaluate the segment
endBehavior (str): If 'loop' then the trajectory loops forever.
Returns:
(:obj:`list` of :obj:`float`): the velocity (derivative) at time t
"""
return self.deriv_state(t,endBehavior) | [
"def",
"deriv",
"(",
"self",
",",
"t",
",",
"endBehavior",
"=",
"'halt'",
")",
":",
"return",
"self",
".",
"deriv_state",
"(",
"t",
",",
"endBehavior",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/model/trajectory.py#L166-L177 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/richtext.py | python | RichTextBuffer.GetStyleForNewParagraph | (*args, **kwargs) | return _richtext.RichTextBuffer_GetStyleForNewParagraph(*args, **kwargs) | GetStyleForNewParagraph(self, RichTextBuffer buffer, long pos, bool caretPosition=False,
bool lookUpNewParaStyle=False) -> RichTextAttr | GetStyleForNewParagraph(self, RichTextBuffer buffer, long pos, bool caretPosition=False,
bool lookUpNewParaStyle=False) -> RichTextAttr | [
"GetStyleForNewParagraph",
"(",
"self",
"RichTextBuffer",
"buffer",
"long",
"pos",
"bool",
"caretPosition",
"=",
"False",
"bool",
"lookUpNewParaStyle",
"=",
"False",
")",
"-",
">",
"RichTextAttr"
] | def GetStyleForNewParagraph(*args, **kwargs):
"""
GetStyleForNewParagraph(self, RichTextBuffer buffer, long pos, bool caretPosition=False,
bool lookUpNewParaStyle=False) -> RichTextAttr
"""
return _richtext.RichTextBuffer_GetStyleForNewParagraph(*args, **kwargs) | [
"def",
"GetStyleForNewParagraph",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextBuffer_GetStyleForNewParagraph",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L2537-L2542 | |
nyuwireless-unipd/ns3-mmwave | 4ff9e87e8079764e04cbeccd8e85bff15ae16fb3 | src/visualizer/visualizer/core.py | python | Node.get_position | (self) | return (self.canvas_item.get_property("center_x"), self.canvas_item.get_property("center_y")) | !
Get position function.
@param self: class object.
@return x and y position | !
Get position function. | [
"!",
"Get",
"position",
"function",
"."
] | def get_position(self):
"""!
Get position function.
@param self: class object.
@return x and y position
"""
return (self.canvas_item.get_property("center_x"), self.canvas_item.get_property("center_y")) | [
"def",
"get_position",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"canvas_item",
".",
"get_property",
"(",
"\"center_x\"",
")",
",",
"self",
".",
"canvas_item",
".",
"get_property",
"(",
"\"center_y\"",
")",
")"
] | https://github.com/nyuwireless-unipd/ns3-mmwave/blob/4ff9e87e8079764e04cbeccd8e85bff15ae16fb3/src/visualizer/visualizer/core.py#L442-L449 | |
ablab/spades | 3a754192b88540524ce6fb69eef5ea9273a38465 | assembler/ext/src/python_libs/joblib3/numpy_pickle.py | python | hex_str | (an_int) | return '{0:#x}'.format(an_int) | Converts an int to an hexadecimal string | Converts an int to an hexadecimal string | [
"Converts",
"an",
"int",
"to",
"an",
"hexadecimal",
"string"
] | def hex_str(an_int):
"""Converts an int to an hexadecimal string
"""
return '{0:#x}'.format(an_int) | [
"def",
"hex_str",
"(",
"an_int",
")",
":",
"return",
"'{0:#x}'",
".",
"format",
"(",
"an_int",
")"
] | https://github.com/ablab/spades/blob/3a754192b88540524ce6fb69eef5ea9273a38465/assembler/ext/src/python_libs/joblib3/numpy_pickle.py#L38-L41 | |
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPMS_KDF_SCHEME_KDF2.__init__ | (self, hashAlg = TPM_ALG_ID.NULL) | These structures are used to define the key derivation for symmetric
secret sharing using asymmetric methods. A secret sharing scheme is
required in any asymmetric key with the decrypt attribute SET.
Attributes:
hashAlg (TPM_ALG_ID): The hash algorithm used to digest the message | These structures are used to define the key derivation for symmetric
secret sharing using asymmetric methods. A secret sharing scheme is
required in any asymmetric key with the decrypt attribute SET. | [
"These",
"structures",
"are",
"used",
"to",
"define",
"the",
"key",
"derivation",
"for",
"symmetric",
"secret",
"sharing",
"using",
"asymmetric",
"methods",
".",
"A",
"secret",
"sharing",
"scheme",
"is",
"required",
"in",
"any",
"asymmetric",
"key",
"with",
"the",
"decrypt",
"attribute",
"SET",
"."
] | def __init__(self, hashAlg = TPM_ALG_ID.NULL):
""" These structures are used to define the key derivation for symmetric
secret sharing using asymmetric methods. A secret sharing scheme is
required in any asymmetric key with the decrypt attribute SET.
Attributes:
hashAlg (TPM_ALG_ID): The hash algorithm used to digest the message
"""
super(TPMS_KDF_SCHEME_KDF2, self).__init__(hashAlg) | [
"def",
"__init__",
"(",
"self",
",",
"hashAlg",
"=",
"TPM_ALG_ID",
".",
"NULL",
")",
":",
"super",
"(",
"TPMS_KDF_SCHEME_KDF2",
",",
"self",
")",
".",
"__init__",
"(",
"hashAlg",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L6831-L6839 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/Finder/Standard_Suite.py | python | Standard_Suite_Events.close | (self, _object, _attributes={}, **_arguments) | close: Close an object
Required argument: the object to close
Keyword argument _attributes: AppleEvent attribute dictionary | close: Close an object
Required argument: the object to close
Keyword argument _attributes: AppleEvent attribute dictionary | [
"close",
":",
"Close",
"an",
"object",
"Required",
"argument",
":",
"the",
"object",
"to",
"close",
"Keyword",
"argument",
"_attributes",
":",
"AppleEvent",
"attribute",
"dictionary"
] | def close(self, _object, _attributes={}, **_arguments):
"""close: Close an object
Required argument: the object to close
Keyword argument _attributes: AppleEvent attribute dictionary
"""
_code = 'core'
_subcode = 'clos'
if _arguments: raise TypeError, 'No optional args expected'
_arguments['----'] = _object
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.get('errn', 0):
raise aetools.Error, aetools.decodeerror(_arguments)
# XXXX Optionally decode result
if _arguments.has_key('----'):
return _arguments['----'] | [
"def",
"close",
"(",
"self",
",",
"_object",
",",
"_attributes",
"=",
"{",
"}",
",",
"*",
"*",
"_arguments",
")",
":",
"_code",
"=",
"'core'",
"_subcode",
"=",
"'clos'",
"if",
"_arguments",
":",
"raise",
"TypeError",
",",
"'No optional args expected'",
"_arguments",
"[",
"'----'",
"]",
"=",
"_object",
"_reply",
",",
"_arguments",
",",
"_attributes",
"=",
"self",
".",
"send",
"(",
"_code",
",",
"_subcode",
",",
"_arguments",
",",
"_attributes",
")",
"if",
"_arguments",
".",
"get",
"(",
"'errn'",
",",
"0",
")",
":",
"raise",
"aetools",
".",
"Error",
",",
"aetools",
".",
"decodeerror",
"(",
"_arguments",
")",
"# XXXX Optionally decode result",
"if",
"_arguments",
".",
"has_key",
"(",
"'----'",
")",
":",
"return",
"_arguments",
"[",
"'----'",
"]"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/Finder/Standard_Suite.py#L16-L34 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/backend.py | python | batch_dot | (x, y, axes=None) | return out | Batchwise dot product.
`batch_dot` is used to compute dot product of `x` and `y` when
`x` and `y` are data in batch, i.e. in a shape of
`(batch_size, :)`.
`batch_dot` results in a tensor or variable with less dimensions
than the input. If the number of dimensions is reduced to 1,
we use `expand_dims` to make sure that ndim is at least 2.
Arguments:
x: Keras tensor or variable with `ndim >= 2`.
y: Keras tensor or variable with `ndim >= 2`.
axes: list of (or single) int with target dimensions.
The lengths of `axes[0]` and `axes[1]` should be the same.
Returns:
A tensor with shape equal to the concatenation of `x`'s shape
(less the dimension that was summed over) and `y`'s shape
(less the batch dimension and the dimension that was summed over).
If the final rank is 1, we reshape it to `(batch_size, 1)`.
Examples:
Assume `x = [[1, 2], [3, 4]]` and `y = [[5, 6], [7, 8]]`
`batch_dot(x, y, axes=1) = [[17, 53]]` which is the main diagonal
of `x.dot(y.T)`, although we never have to calculate the off-diagonal
elements.
Shape inference:
Let `x`'s shape be `(100, 20)` and `y`'s shape be `(100, 30, 20)`.
If `axes` is (1, 2), to find the output shape of resultant tensor,
loop through each dimension in `x`'s shape and `y`'s shape:
* `x.shape[0]` : 100 : append to output shape
* `x.shape[1]` : 20 : do not append to output shape,
dimension 1 of `x` has been summed over. (`dot_axes[0]` = 1)
* `y.shape[0]` : 100 : do not append to output shape,
always ignore first dimension of `y`
* `y.shape[1]` : 30 : append to output shape
* `y.shape[2]` : 20 : do not append to output shape,
dimension 2 of `y` has been summed over. (`dot_axes[1]` = 2)
`output_shape` = `(100, 30)`
```python
>>> x_batch = K.ones(shape=(32, 20, 1))
>>> y_batch = K.ones(shape=(32, 30, 20))
>>> xy_batch_dot = K.batch_dot(x_batch, y_batch, axes=[1, 2])
>>> K.int_shape(xy_batch_dot)
(32, 1, 30)
``` | Batchwise dot product. | [
"Batchwise",
"dot",
"product",
"."
] | def batch_dot(x, y, axes=None):
"""Batchwise dot product.
`batch_dot` is used to compute dot product of `x` and `y` when
`x` and `y` are data in batch, i.e. in a shape of
`(batch_size, :)`.
`batch_dot` results in a tensor or variable with less dimensions
than the input. If the number of dimensions is reduced to 1,
we use `expand_dims` to make sure that ndim is at least 2.
Arguments:
x: Keras tensor or variable with `ndim >= 2`.
y: Keras tensor or variable with `ndim >= 2`.
axes: list of (or single) int with target dimensions.
The lengths of `axes[0]` and `axes[1]` should be the same.
Returns:
A tensor with shape equal to the concatenation of `x`'s shape
(less the dimension that was summed over) and `y`'s shape
(less the batch dimension and the dimension that was summed over).
If the final rank is 1, we reshape it to `(batch_size, 1)`.
Examples:
Assume `x = [[1, 2], [3, 4]]` and `y = [[5, 6], [7, 8]]`
`batch_dot(x, y, axes=1) = [[17, 53]]` which is the main diagonal
of `x.dot(y.T)`, although we never have to calculate the off-diagonal
elements.
Shape inference:
Let `x`'s shape be `(100, 20)` and `y`'s shape be `(100, 30, 20)`.
If `axes` is (1, 2), to find the output shape of resultant tensor,
loop through each dimension in `x`'s shape and `y`'s shape:
* `x.shape[0]` : 100 : append to output shape
* `x.shape[1]` : 20 : do not append to output shape,
dimension 1 of `x` has been summed over. (`dot_axes[0]` = 1)
* `y.shape[0]` : 100 : do not append to output shape,
always ignore first dimension of `y`
* `y.shape[1]` : 30 : append to output shape
* `y.shape[2]` : 20 : do not append to output shape,
dimension 2 of `y` has been summed over. (`dot_axes[1]` = 2)
`output_shape` = `(100, 30)`
```python
>>> x_batch = K.ones(shape=(32, 20, 1))
>>> y_batch = K.ones(shape=(32, 30, 20))
>>> xy_batch_dot = K.batch_dot(x_batch, y_batch, axes=[1, 2])
>>> K.int_shape(xy_batch_dot)
(32, 1, 30)
```
"""
if isinstance(axes, int):
axes = (axes, axes)
x_ndim = ndim(x)
y_ndim = ndim(y)
if axes is None:
# behaves like tf.batch_matmul as default
axes = [x_ndim - 1, y_ndim - 2]
if x_ndim > y_ndim:
diff = x_ndim - y_ndim
y = array_ops.reshape(y,
array_ops.concat(
[array_ops.shape(y), [1] * (diff)], axis=0))
elif y_ndim > x_ndim:
diff = y_ndim - x_ndim
x = array_ops.reshape(x,
array_ops.concat(
[array_ops.shape(x), [1] * (diff)], axis=0))
else:
diff = 0
if ndim(x) == 2 and ndim(y) == 2:
if axes[0] == axes[1]:
out = math_ops.reduce_sum(math_ops.multiply(x, y), axes[0])
else:
out = math_ops.reduce_sum(
math_ops.multiply(array_ops.transpose(x, [1, 0]), y), axes[1])
else:
adj_x = None if axes[0] == ndim(x) - 1 else True
adj_y = True if axes[1] == ndim(y) - 1 else None
out = math_ops.matmul(x, y, adjoint_a=adj_x, adjoint_b=adj_y)
if diff:
if x_ndim > y_ndim:
idx = x_ndim + y_ndim - 3
else:
idx = x_ndim - 1
out = array_ops.squeeze(out, list(range(idx, idx + diff)))
if ndim(out) == 1:
out = expand_dims(out, 1)
return out | [
"def",
"batch_dot",
"(",
"x",
",",
"y",
",",
"axes",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"axes",
",",
"int",
")",
":",
"axes",
"=",
"(",
"axes",
",",
"axes",
")",
"x_ndim",
"=",
"ndim",
"(",
"x",
")",
"y_ndim",
"=",
"ndim",
"(",
"y",
")",
"if",
"axes",
"is",
"None",
":",
"# behaves like tf.batch_matmul as default",
"axes",
"=",
"[",
"x_ndim",
"-",
"1",
",",
"y_ndim",
"-",
"2",
"]",
"if",
"x_ndim",
">",
"y_ndim",
":",
"diff",
"=",
"x_ndim",
"-",
"y_ndim",
"y",
"=",
"array_ops",
".",
"reshape",
"(",
"y",
",",
"array_ops",
".",
"concat",
"(",
"[",
"array_ops",
".",
"shape",
"(",
"y",
")",
",",
"[",
"1",
"]",
"*",
"(",
"diff",
")",
"]",
",",
"axis",
"=",
"0",
")",
")",
"elif",
"y_ndim",
">",
"x_ndim",
":",
"diff",
"=",
"y_ndim",
"-",
"x_ndim",
"x",
"=",
"array_ops",
".",
"reshape",
"(",
"x",
",",
"array_ops",
".",
"concat",
"(",
"[",
"array_ops",
".",
"shape",
"(",
"x",
")",
",",
"[",
"1",
"]",
"*",
"(",
"diff",
")",
"]",
",",
"axis",
"=",
"0",
")",
")",
"else",
":",
"diff",
"=",
"0",
"if",
"ndim",
"(",
"x",
")",
"==",
"2",
"and",
"ndim",
"(",
"y",
")",
"==",
"2",
":",
"if",
"axes",
"[",
"0",
"]",
"==",
"axes",
"[",
"1",
"]",
":",
"out",
"=",
"math_ops",
".",
"reduce_sum",
"(",
"math_ops",
".",
"multiply",
"(",
"x",
",",
"y",
")",
",",
"axes",
"[",
"0",
"]",
")",
"else",
":",
"out",
"=",
"math_ops",
".",
"reduce_sum",
"(",
"math_ops",
".",
"multiply",
"(",
"array_ops",
".",
"transpose",
"(",
"x",
",",
"[",
"1",
",",
"0",
"]",
")",
",",
"y",
")",
",",
"axes",
"[",
"1",
"]",
")",
"else",
":",
"adj_x",
"=",
"None",
"if",
"axes",
"[",
"0",
"]",
"==",
"ndim",
"(",
"x",
")",
"-",
"1",
"else",
"True",
"adj_y",
"=",
"True",
"if",
"axes",
"[",
"1",
"]",
"==",
"ndim",
"(",
"y",
")",
"-",
"1",
"else",
"None",
"out",
"=",
"math_ops",
".",
"matmul",
"(",
"x",
",",
"y",
",",
"adjoint_a",
"=",
"adj_x",
",",
"adjoint_b",
"=",
"adj_y",
")",
"if",
"diff",
":",
"if",
"x_ndim",
">",
"y_ndim",
":",
"idx",
"=",
"x_ndim",
"+",
"y_ndim",
"-",
"3",
"else",
":",
"idx",
"=",
"x_ndim",
"-",
"1",
"out",
"=",
"array_ops",
".",
"squeeze",
"(",
"out",
",",
"list",
"(",
"range",
"(",
"idx",
",",
"idx",
"+",
"diff",
")",
")",
")",
"if",
"ndim",
"(",
"out",
")",
"==",
"1",
":",
"out",
"=",
"expand_dims",
"(",
"out",
",",
"1",
")",
"return",
"out"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/backend.py#L1702-L1790 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/dataset/text/utils.py | python | Vocab.tokens_to_ids | (self, tokens) | return self.c_vocab.tokens_to_ids(tokens) | Converts a token string or a sequence of tokens in a single integer id or a sequence of ids.
If token does not exist, return id with value -1.
Args:
tokens(Union[str, list[str]]): One or several token(s) to convert to token id(s).
Returns:
The token id or list of token ids.
Examples:
>>> vocab = text.Vocab.from_list(["w1", "w2", "w3"], special_tokens=["<unk>"], special_first=True)
>>> ids = vocab.tokens_to_ids(["w1", "w3"]) | Converts a token string or a sequence of tokens in a single integer id or a sequence of ids.
If token does not exist, return id with value -1. | [
"Converts",
"a",
"token",
"string",
"or",
"a",
"sequence",
"of",
"tokens",
"in",
"a",
"single",
"integer",
"id",
"or",
"a",
"sequence",
"of",
"ids",
".",
"If",
"token",
"does",
"not",
"exist",
"return",
"id",
"with",
"value",
"-",
"1",
"."
] | def tokens_to_ids(self, tokens):
"""
Converts a token string or a sequence of tokens in a single integer id or a sequence of ids.
If token does not exist, return id with value -1.
Args:
tokens(Union[str, list[str]]): One or several token(s) to convert to token id(s).
Returns:
The token id or list of token ids.
Examples:
>>> vocab = text.Vocab.from_list(["w1", "w2", "w3"], special_tokens=["<unk>"], special_first=True)
>>> ids = vocab.tokens_to_ids(["w1", "w3"])
"""
check_vocab(self.c_vocab)
if isinstance(tokens, str):
tokens = [tokens]
return self.c_vocab.tokens_to_ids(tokens) | [
"def",
"tokens_to_ids",
"(",
"self",
",",
"tokens",
")",
":",
"check_vocab",
"(",
"self",
".",
"c_vocab",
")",
"if",
"isinstance",
"(",
"tokens",
",",
"str",
")",
":",
"tokens",
"=",
"[",
"tokens",
"]",
"return",
"self",
".",
"c_vocab",
".",
"tokens_to_ids",
"(",
"tokens",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/dataset/text/utils.py#L59-L77 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/aui.py | python | AuiMDIChildFrame.GetIcon | (*args, **kwargs) | return _aui.AuiMDIChildFrame_GetIcon(*args, **kwargs) | GetIcon(self) -> Icon | GetIcon(self) -> Icon | [
"GetIcon",
"(",
"self",
")",
"-",
">",
"Icon"
] | def GetIcon(*args, **kwargs):
"""GetIcon(self) -> Icon"""
return _aui.AuiMDIChildFrame_GetIcon(*args, **kwargs) | [
"def",
"GetIcon",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiMDIChildFrame_GetIcon",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/aui.py#L1554-L1556 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/_op_impl/tbe/bn_training_reduce.py | python | _bn_training_reduce_tbe | () | return | BNTrainingReduce TBE register | BNTrainingReduce TBE register | [
"BNTrainingReduce",
"TBE",
"register"
] | def _bn_training_reduce_tbe():
"""BNTrainingReduce TBE register"""
return | [
"def",
"_bn_training_reduce_tbe",
"(",
")",
":",
"return"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/bn_training_reduce.py#L36-L38 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/telemetry/telemetry/page/extensions_profile_creator.py | python | ExtensionsProfileCreator.DidRunTest | (self, browser, results) | Run before exit. | Run before exit. | [
"Run",
"before",
"exit",
"."
] | def DidRunTest(self, browser, results):
"""Run before exit."""
# Do some basic sanity checks to make sure the profile is complete.
installed_extensions = browser.extensions.keys()
if not len(installed_extensions) == len(self._extensions_to_install):
# Diagnosing errors:
# Too many extensions: Managed environment may be installing additional
# extensions.
raise Exception("Unexpected number of extensions installed in browser",
installed_extensions)
# Check that files on this list exist and have content.
expected_files = [
os.path.join('Default', 'Network Action Predictor')]
for filename in expected_files:
filename = os.path.join(self._output_profile_path, filename)
if not os.path.getsize(filename) > 0:
raise Exception("Profile not complete: %s is zero length." % filename)
self._CleanupExtensionInstallFiles() | [
"def",
"DidRunTest",
"(",
"self",
",",
"browser",
",",
"results",
")",
":",
"# Do some basic sanity checks to make sure the profile is complete.",
"installed_extensions",
"=",
"browser",
".",
"extensions",
".",
"keys",
"(",
")",
"if",
"not",
"len",
"(",
"installed_extensions",
")",
"==",
"len",
"(",
"self",
".",
"_extensions_to_install",
")",
":",
"# Diagnosing errors:",
"# Too many extensions: Managed environment may be installing additional",
"# extensions.",
"raise",
"Exception",
"(",
"\"Unexpected number of extensions installed in browser\"",
",",
"installed_extensions",
")",
"# Check that files on this list exist and have content.",
"expected_files",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"'Default'",
",",
"'Network Action Predictor'",
")",
"]",
"for",
"filename",
"in",
"expected_files",
":",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_output_profile_path",
",",
"filename",
")",
"if",
"not",
"os",
".",
"path",
".",
"getsize",
"(",
"filename",
")",
">",
"0",
":",
"raise",
"Exception",
"(",
"\"Profile not complete: %s is zero length.\"",
"%",
"filename",
")",
"self",
".",
"_CleanupExtensionInstallFiles",
"(",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/telemetry/page/extensions_profile_creator.py#L177-L196 | ||
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/traci/_vehicle.py | python | VehicleDomain.getSpeedFactor | (self, vehID) | return self._getUniversal(tc.VAR_SPEED_FACTOR, vehID) | getSpeedFactor(string) -> double
Returns the chosen speed factor for this vehicle. | getSpeedFactor(string) -> double | [
"getSpeedFactor",
"(",
"string",
")",
"-",
">",
"double"
] | def getSpeedFactor(self, vehID):
"""getSpeedFactor(string) -> double
Returns the chosen speed factor for this vehicle.
"""
return self._getUniversal(tc.VAR_SPEED_FACTOR, vehID) | [
"def",
"getSpeedFactor",
"(",
"self",
",",
"vehID",
")",
":",
"return",
"self",
".",
"_getUniversal",
"(",
"tc",
".",
"VAR_SPEED_FACTOR",
",",
"vehID",
")"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_vehicle.py#L534-L539 | |
InsightSoftwareConsortium/ITK | 87acfce9a93d928311c38bc371b666b515b9f19d | Modules/ThirdParty/pygccxml/src/pygccxml/declarations/templates.py | python | split_recursive | (decl_string) | return __THE_PARSER.split_recursive(decl_string) | returns [(name, [arguments])] | returns [(name, [arguments])] | [
"returns",
"[",
"(",
"name",
"[",
"arguments",
"]",
")",
"]"
] | def split_recursive(decl_string):
"""returns [(name, [arguments])]"""
return __THE_PARSER.split_recursive(decl_string) | [
"def",
"split_recursive",
"(",
"decl_string",
")",
":",
"return",
"__THE_PARSER",
".",
"split_recursive",
"(",
"decl_string",
")"
] | https://github.com/InsightSoftwareConsortium/ITK/blob/87acfce9a93d928311c38bc371b666b515b9f19d/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/templates.py#L62-L64 | |
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/blessings/blessings/__init__.py | python | Terminal.color | (self) | return ParametrizingString(self._foreground_color, self.normal) | Return a capability that sets the foreground color.
The capability is unparametrized until called and passed a number
(0-15), at which point it returns another string which represents a
specific color change. This second string can further be called to
color a piece of text and set everything back to normal afterward.
:arg num: The number, 0-15, of the color | Return a capability that sets the foreground color. | [
"Return",
"a",
"capability",
"that",
"sets",
"the",
"foreground",
"color",
"."
] | def color(self):
"""Return a capability that sets the foreground color.
The capability is unparametrized until called and passed a number
(0-15), at which point it returns another string which represents a
specific color change. This second string can further be called to
color a piece of text and set everything back to normal afterward.
:arg num: The number, 0-15, of the color
"""
return ParametrizingString(self._foreground_color, self.normal) | [
"def",
"color",
"(",
"self",
")",
":",
"return",
"ParametrizingString",
"(",
"self",
".",
"_foreground_color",
",",
"self",
".",
"normal",
")"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/blessings/blessings/__init__.py#L215-L226 | |
Tencent/CMONGO | c40380caa14e05509f46993aa8b8da966b09b0b5 | src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Environment.py | python | _delete_duplicates | (l, keep_last) | return result | Delete duplicates from a sequence, keeping the first or last. | Delete duplicates from a sequence, keeping the first or last. | [
"Delete",
"duplicates",
"from",
"a",
"sequence",
"keeping",
"the",
"first",
"or",
"last",
"."
] | def _delete_duplicates(l, keep_last):
"""Delete duplicates from a sequence, keeping the first or last."""
seen={}
result=[]
if keep_last: # reverse in & out, then keep first
l.reverse()
for i in l:
try:
if i not in seen:
result.append(i)
seen[i]=1
except TypeError:
# probably unhashable. Just keep it.
result.append(i)
if keep_last:
result.reverse()
return result | [
"def",
"_delete_duplicates",
"(",
"l",
",",
"keep_last",
")",
":",
"seen",
"=",
"{",
"}",
"result",
"=",
"[",
"]",
"if",
"keep_last",
":",
"# reverse in & out, then keep first",
"l",
".",
"reverse",
"(",
")",
"for",
"i",
"in",
"l",
":",
"try",
":",
"if",
"i",
"not",
"in",
"seen",
":",
"result",
".",
"append",
"(",
"i",
")",
"seen",
"[",
"i",
"]",
"=",
"1",
"except",
"TypeError",
":",
"# probably unhashable. Just keep it.",
"result",
".",
"append",
"(",
"i",
")",
"if",
"keep_last",
":",
"result",
".",
"reverse",
"(",
")",
"return",
"result"
] | https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Environment.py#L168-L184 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/email/message.py | python | Message.get_content_maintype | (self) | return ctype.split('/')[0] | Return the message's main content type.
This is the `maintype' part of the string returned by
get_content_type(). | Return the message's main content type. | [
"Return",
"the",
"message",
"s",
"main",
"content",
"type",
"."
] | def get_content_maintype(self):
"""Return the message's main content type.
This is the `maintype' part of the string returned by
get_content_type().
"""
ctype = self.get_content_type()
return ctype.split('/')[0] | [
"def",
"get_content_maintype",
"(",
"self",
")",
":",
"ctype",
"=",
"self",
".",
"get_content_type",
"(",
")",
"return",
"ctype",
".",
"split",
"(",
"'/'",
")",
"[",
"0",
"]"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/email/message.py#L456-L463 | |
codilime/veles | e65de5a7c268129acffcdb03034efd8d256d025c | python/veles/data/bindata.py | python | BinData.octets_per_element | (self) | return (self._width + 7) // 8 | Returns how many octets each element takes in the raw data. | Returns how many octets each element takes in the raw data. | [
"Returns",
"how",
"many",
"octets",
"each",
"element",
"takes",
"in",
"the",
"raw",
"data",
"."
] | def octets_per_element(self):
"""
Returns how many octets each element takes in the raw data.
"""
return (self._width + 7) // 8 | [
"def",
"octets_per_element",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"_width",
"+",
"7",
")",
"//",
"8"
] | https://github.com/codilime/veles/blob/e65de5a7c268129acffcdb03034efd8d256d025c/python/veles/data/bindata.py#L129-L133 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | Quantize.Quantize | (*args, **kwargs) | return _core_.Quantize_Quantize(*args, **kwargs) | Quantize(Image src, Image dest, int desiredNoColours=236, int flags=wxQUANTIZE_INCLUDE_WINDOWS_COLOURS|wxQUANTIZE_FILL_DESTINATION_IMAGE) -> bool
Reduce the colours in the source image and put the result into the
destination image, setting the palette in the destination if
needed. Both images may be the same, to overwrite the source image. | Quantize(Image src, Image dest, int desiredNoColours=236, int flags=wxQUANTIZE_INCLUDE_WINDOWS_COLOURS|wxQUANTIZE_FILL_DESTINATION_IMAGE) -> bool | [
"Quantize",
"(",
"Image",
"src",
"Image",
"dest",
"int",
"desiredNoColours",
"=",
"236",
"int",
"flags",
"=",
"wxQUANTIZE_INCLUDE_WINDOWS_COLOURS|wxQUANTIZE_FILL_DESTINATION_IMAGE",
")",
"-",
">",
"bool"
] | def Quantize(*args, **kwargs):
"""
Quantize(Image src, Image dest, int desiredNoColours=236, int flags=wxQUANTIZE_INCLUDE_WINDOWS_COLOURS|wxQUANTIZE_FILL_DESTINATION_IMAGE) -> bool
Reduce the colours in the source image and put the result into the
destination image, setting the palette in the destination if
needed. Both images may be the same, to overwrite the source image.
"""
return _core_.Quantize_Quantize(*args, **kwargs) | [
"def",
"Quantize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Quantize_Quantize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L4086-L4094 | |
shedskin/shedskin | ae88dbca7b1d9671cd8be448cb0b497122758936 | examples/msp_ss.py | python | usage | () | print some help message | print some help message | [
"print",
"some",
"help",
"message"
] | def usage():
"""print some help message"""
sys.stderr.write("""
USAGE: %s [options] [file]
Version: %s
If "-" is specified as file the data is read from the stdinput.
A file ending with ".txt" is considered to be in TIText format,
'.a43' and '.hex' as IntelHex and all other filenames are
considered as ELF files.
General options:
-h, --help Show this help screen.
-c, --comport=port Specify the communication port to be used.
(Default is 0)
0->COM1 / ttyS0
1->COM2 / ttyS1
etc.
-P, --password=file Specify a file with the interrupt vectors that
are used as password. This can be any file that
has previously been used to program the device.
(e.g. -P INT_VECT.TXT).
-f, --framesize=num Max. number of data bytes within one transmitted
frame (16 to 240 in steps of 16) (e.g. -f 240).
-m, --erasecycles=num Number of mass erase cycles (default is 1). Some
old F149 devices need additional erase cycles.
On newer devices it is no longer needed. (e.g. for
an old F149: -m20)
-U, --unpatched Do not download the BSL patch, even when it is
needed. This is used when a program is downloaded
into RAM and executed from there (and where flash
programming is not needed.)
-D, --debug Increase level of debug messages. This won't be
very useful for the average user...
-I, --intelhex Force fileformat to IntelHex
-T, --titext Force fileformat to be TIText
-N, --notimeout Don't use timeout on serial port (use with care)
-B, --bsl=bsl.txt Load and use new BSL from the TI Text file
-S, --speed=baud Reconfigure speed, only possible with newer
MSP403-BSL versions (>1.5, read slaa089a.pdf for
details). If the --bsl option is not used, an
internal BSL replacement will be loaded.
Needs a target with at least 2kB RAM!
Possible values are 9600, 19200, 38400
(default 9600)
-1, --f1x Specify CPU family, in case autodetect fails
-4, --f4x Specify CPU family, in case autodetect fails
--F1x and --f2x are only needed when the "change
baudrate" feature is used and the autodetect feature
fails. If the device ID that is uploaded is known, it
has precedence to the command line option.
--invert-reset Invert signal on RST pin (used for some BSL hardware)
--invert-test Invert signal on TEST/TCK pin (used for some BSL
hardware)
--swap-reset-test Swap the RST and TEST pins (used for some BSL hardware)
--telos-latch Special twiddle in BSL reset for Telos hardware
--telos-i2c DTR/RTS map via an I2C switch to TCK/RST in Telos Rev.B
--telos Implies options --invert-reset, --invert-test,
--swap-reset-test, and --telos-latch
--telosb Implies options --swap-reset-test, --telos-i2c,
--no-BSL-download, and --speed=38400
--tmote Identical operation to --telosb
--no-BSL-download Do not download replacement BSL (disable automatic)
--force-BSL-download Download replacement BSL even if not needed (the one
in the device would have the required features)
--slow Add delays when operating the conrol pins. Useful if
the pins/circuit has high capacitance.
Program Flow Specifiers:
-e, --masserase Mass Erase (clear all flash memory)
-E, --erasecheck Erase Check by file
-p, --program Program file
-v, --verify Verify by file
The order of the above options matters! The table is ordered by normal
execution order. For the options "Epv" a file must be specified.
Program flow specifiers default to "pvr" if a file is given.
Don't forget to specify "e" or "eE" when programming flash!
Data retreiving:
-u, --upload=addr Upload a datablock (see also: -s).
-s, --size=num Size of the data block do upload. (Default is 2)
-x, --hex Show a hexadecimal display of the uploaded data.
(Default)
-b, --bin Get binary uploaded data. This can be used
to redirect the output into a file.
Do before exit:
-g, --go=address Start programm execution at specified address.
This implies option --wait.
-r, --reset Reset connected MSP430. Starts application.
This is a normal device reset and will start
the programm that is specified in the reset
vector. (see also -g)
-w, --wait Wait for <ENTER> before closing serial port.
If it says "NAK received" it's probably because you specified no or a
wrong password.
""" % (sys.argv[0], VERSION)) | [
"def",
"usage",
"(",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"\"\"\nUSAGE: %s [options] [file]\nVersion: %s\n\nIf \"-\" is specified as file the data is read from the stdinput.\nA file ending with \".txt\" is considered to be in TIText format,\n'.a43' and '.hex' as IntelHex and all other filenames are\nconsidered as ELF files.\n\nGeneral options:\n -h, --help Show this help screen.\n -c, --comport=port Specify the communication port to be used.\n (Default is 0)\n 0->COM1 / ttyS0\n 1->COM2 / ttyS1\n etc.\n -P, --password=file Specify a file with the interrupt vectors that\n are used as password. This can be any file that\n has previously been used to program the device.\n (e.g. -P INT_VECT.TXT).\n -f, --framesize=num Max. number of data bytes within one transmitted\n frame (16 to 240 in steps of 16) (e.g. -f 240).\n -m, --erasecycles=num Number of mass erase cycles (default is 1). Some\n old F149 devices need additional erase cycles.\n On newer devices it is no longer needed. (e.g. for\n an old F149: -m20)\n -U, --unpatched Do not download the BSL patch, even when it is\n needed. This is used when a program is downloaded\n into RAM and executed from there (and where flash\n programming is not needed.)\n -D, --debug Increase level of debug messages. This won't be\n very useful for the average user...\n -I, --intelhex Force fileformat to IntelHex\n -T, --titext Force fileformat to be TIText\n -N, --notimeout Don't use timeout on serial port (use with care)\n -B, --bsl=bsl.txt Load and use new BSL from the TI Text file\n -S, --speed=baud Reconfigure speed, only possible with newer\n MSP403-BSL versions (>1.5, read slaa089a.pdf for\n details). If the --bsl option is not used, an\n internal BSL replacement will be loaded.\n Needs a target with at least 2kB RAM!\n Possible values are 9600, 19200, 38400\n (default 9600)\n -1, --f1x Specify CPU family, in case autodetect fails\n -4, --f4x Specify CPU family, in case autodetect fails\n --F1x and --f2x are only needed when the \"change\n baudrate\" feature is used and the autodetect feature\n fails. If the device ID that is uploaded is known, it\n has precedence to the command line option.\n --invert-reset Invert signal on RST pin (used for some BSL hardware)\n --invert-test Invert signal on TEST/TCK pin (used for some BSL\n hardware)\n --swap-reset-test Swap the RST and TEST pins (used for some BSL hardware)\n --telos-latch Special twiddle in BSL reset for Telos hardware\n --telos-i2c DTR/RTS map via an I2C switch to TCK/RST in Telos Rev.B\n --telos Implies options --invert-reset, --invert-test,\n --swap-reset-test, and --telos-latch\n --telosb Implies options --swap-reset-test, --telos-i2c,\n --no-BSL-download, and --speed=38400\n --tmote Identical operation to --telosb\n --no-BSL-download Do not download replacement BSL (disable automatic)\n --force-BSL-download Download replacement BSL even if not needed (the one\n in the device would have the required features)\n --slow Add delays when operating the conrol pins. Useful if\n the pins/circuit has high capacitance.\n\nProgram Flow Specifiers:\n -e, --masserase Mass Erase (clear all flash memory)\n -E, --erasecheck Erase Check by file\n -p, --program Program file\n -v, --verify Verify by file\n\nThe order of the above options matters! The table is ordered by normal\nexecution order. For the options \"Epv\" a file must be specified.\nProgram flow specifiers default to \"pvr\" if a file is given.\nDon't forget to specify \"e\" or \"eE\" when programming flash!\n\nData retreiving:\n -u, --upload=addr Upload a datablock (see also: -s).\n -s, --size=num Size of the data block do upload. (Default is 2)\n -x, --hex Show a hexadecimal display of the uploaded data.\n (Default)\n -b, --bin Get binary uploaded data. This can be used\n to redirect the output into a file.\n\nDo before exit:\n -g, --go=address Start programm execution at specified address.\n This implies option --wait.\n -r, --reset Reset connected MSP430. Starts application.\n This is a normal device reset and will start\n the programm that is specified in the reset\n vector. (see also -g)\n -w, --wait Wait for <ENTER> before closing serial port.\n\nIf it says \"NAK received\" it's probably because you specified no or a\nwrong password.\n\"\"\"",
"%",
"(",
"sys",
".",
"argv",
"[",
"0",
"]",
",",
"VERSION",
")",
")"
] | https://github.com/shedskin/shedskin/blob/ae88dbca7b1d9671cd8be448cb0b497122758936/examples/msp_ss.py#L1203-L1301 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/email/_header_value_parser.py | python | get_extended_attribute | (value) | return attribute, value | [CFWS] 1*extended_attrtext [CFWS]
This is like the non-extended version except we allow % characters, so that
we can pick up an encoded value as a single string. | [CFWS] 1*extended_attrtext [CFWS] | [
"[",
"CFWS",
"]",
"1",
"*",
"extended_attrtext",
"[",
"CFWS",
"]"
] | def get_extended_attribute(value):
""" [CFWS] 1*extended_attrtext [CFWS]
This is like the non-extended version except we allow % characters, so that
we can pick up an encoded value as a single string.
"""
# XXX: should we have an ExtendedAttribute TokenList?
attribute = Attribute()
if value and value[0] in CFWS_LEADER:
token, value = get_cfws(value)
attribute.append(token)
if value and value[0] in EXTENDED_ATTRIBUTE_ENDS:
raise errors.HeaderParseError(
"expected token but found '{}'".format(value))
token, value = get_extended_attrtext(value)
attribute.append(token)
if value and value[0] in CFWS_LEADER:
token, value = get_cfws(value)
attribute.append(token)
return attribute, value | [
"def",
"get_extended_attribute",
"(",
"value",
")",
":",
"# XXX: should we have an ExtendedAttribute TokenList?",
"attribute",
"=",
"Attribute",
"(",
")",
"if",
"value",
"and",
"value",
"[",
"0",
"]",
"in",
"CFWS_LEADER",
":",
"token",
",",
"value",
"=",
"get_cfws",
"(",
"value",
")",
"attribute",
".",
"append",
"(",
"token",
")",
"if",
"value",
"and",
"value",
"[",
"0",
"]",
"in",
"EXTENDED_ATTRIBUTE_ENDS",
":",
"raise",
"errors",
".",
"HeaderParseError",
"(",
"\"expected token but found '{}'\"",
".",
"format",
"(",
"value",
")",
")",
"token",
",",
"value",
"=",
"get_extended_attrtext",
"(",
"value",
")",
"attribute",
".",
"append",
"(",
"token",
")",
"if",
"value",
"and",
"value",
"[",
"0",
"]",
"in",
"CFWS_LEADER",
":",
"token",
",",
"value",
"=",
"get_cfws",
"(",
"value",
")",
"attribute",
".",
"append",
"(",
"token",
")",
"return",
"attribute",
",",
"value"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/email/_header_value_parser.py#L2218-L2238 | |
su2code/SU2 | 72b2fa977b64b9683a388920f05298a40d39e5c5 | SU2_PY/FSI_tools/FSIInterface.py | python | Interface.relaxSolidPosition | (self,FSI_config) | Apply solid displacement under-relaxation. | Apply solid displacement under-relaxation. | [
"Apply",
"solid",
"displacement",
"under",
"-",
"relaxation",
"."
] | def relaxSolidPosition(self,FSI_config):
"""
Apply solid displacement under-relaxation.
"""
if self.have_MPI:
myid = self.comm.Get_rank()
else:
myid = 0
# --- Set the Aitken coefficient for the relaxation ---
if FSI_config['AITKEN_RELAX'] == 'STATIC':
self.aitkenParam = FSI_config['AITKEN_PARAM']
elif FSI_config['AITKEN_RELAX'] == 'DYNAMIC':
self.setAitkenCoefficient(FSI_config)
else:
self.aitkenParam = 1.0
self.MPIPrint('Aitken under-relaxation step with parameter {}'.format(self.aitkenParam))
# --- Relax the solid interface position ---
self.solidInterface_array_DispX += self.aitkenParam*self.solidInterfaceResidual_array_X
self.solidInterface_array_DispY += self.aitkenParam*self.solidInterfaceResidual_array_Y
self.solidInterface_array_DispZ += self.aitkenParam*self.solidInterfaceResidual_array_Z | [
"def",
"relaxSolidPosition",
"(",
"self",
",",
"FSI_config",
")",
":",
"if",
"self",
".",
"have_MPI",
":",
"myid",
"=",
"self",
".",
"comm",
".",
"Get_rank",
"(",
")",
"else",
":",
"myid",
"=",
"0",
"# --- Set the Aitken coefficient for the relaxation ---",
"if",
"FSI_config",
"[",
"'AITKEN_RELAX'",
"]",
"==",
"'STATIC'",
":",
"self",
".",
"aitkenParam",
"=",
"FSI_config",
"[",
"'AITKEN_PARAM'",
"]",
"elif",
"FSI_config",
"[",
"'AITKEN_RELAX'",
"]",
"==",
"'DYNAMIC'",
":",
"self",
".",
"setAitkenCoefficient",
"(",
"FSI_config",
")",
"else",
":",
"self",
".",
"aitkenParam",
"=",
"1.0",
"self",
".",
"MPIPrint",
"(",
"'Aitken under-relaxation step with parameter {}'",
".",
"format",
"(",
"self",
".",
"aitkenParam",
")",
")",
"# --- Relax the solid interface position ---",
"self",
".",
"solidInterface_array_DispX",
"+=",
"self",
".",
"aitkenParam",
"*",
"self",
".",
"solidInterfaceResidual_array_X",
"self",
".",
"solidInterface_array_DispY",
"+=",
"self",
".",
"aitkenParam",
"*",
"self",
".",
"solidInterfaceResidual_array_Y",
"self",
".",
"solidInterface_array_DispZ",
"+=",
"self",
".",
"aitkenParam",
"*",
"self",
".",
"solidInterfaceResidual_array_Z"
] | https://github.com/su2code/SU2/blob/72b2fa977b64b9683a388920f05298a40d39e5c5/SU2_PY/FSI_tools/FSIInterface.py#L1630-L1652 | ||
NervanaSystems/ngraph | f677a119765ca30636cf407009dabd118664951f | python/src/ngraph/ops.py | python | avg_pool | (
data_batch: NodeInput,
strides: List[int],
pads_begin: TensorShape,
pads_end: TensorShape,
kernel_shape: TensorShape,
exclude_pad: bool,
rounding_type: str = "floor",
auto_pad: Optional[str] = None,
name: Optional[str] = None,
) | return _get_node_factory().create(
"AvgPool",
[as_node(data_batch)],
{
"strides": strides,
"pads_begin": pads_begin,
"pads_end": pads_end,
"kernel": kernel_shape,
"exclude_pad": exclude_pad,
"rounding_type": rounding_type.upper(),
"auto_pad": auto_pad.upper(),
},
) | Return average pooling node.
:param data_batch: The input node providing data.
:param strides: The window movement strides.
:param pads_begin: The input data optional padding below filled with zeros.
:param pads_end: The input data optional padding below filled with zeros.
:param kernel_shape: The pooling window shape.
:param exclude_pad: Whether or not to include zero padding in average computations.
:param rounding_type: Determines used rounding schema when computing output shape. Acceptable
values are: ['floor', 'ceil']
:param auto_pad: Determines how the padding is calculated. Acceptable values:
[None, 'same_upper', 'same_lower', 'valid']
:param name: Optional name for the new output node.
:return: New node with AvgPool operation applied on its data. | Return average pooling node. | [
"Return",
"average",
"pooling",
"node",
"."
] | def avg_pool(
data_batch: NodeInput,
strides: List[int],
pads_begin: TensorShape,
pads_end: TensorShape,
kernel_shape: TensorShape,
exclude_pad: bool,
rounding_type: str = "floor",
auto_pad: Optional[str] = None,
name: Optional[str] = None,
) -> Node:
"""Return average pooling node.
:param data_batch: The input node providing data.
:param strides: The window movement strides.
:param pads_begin: The input data optional padding below filled with zeros.
:param pads_end: The input data optional padding below filled with zeros.
:param kernel_shape: The pooling window shape.
:param exclude_pad: Whether or not to include zero padding in average computations.
:param rounding_type: Determines used rounding schema when computing output shape. Acceptable
values are: ['floor', 'ceil']
:param auto_pad: Determines how the padding is calculated. Acceptable values:
[None, 'same_upper', 'same_lower', 'valid']
:param name: Optional name for the new output node.
:return: New node with AvgPool operation applied on its data.
"""
if auto_pad is None:
auto_pad = "explicit"
return _get_node_factory().create(
"AvgPool",
[as_node(data_batch)],
{
"strides": strides,
"pads_begin": pads_begin,
"pads_end": pads_end,
"kernel": kernel_shape,
"exclude_pad": exclude_pad,
"rounding_type": rounding_type.upper(),
"auto_pad": auto_pad.upper(),
},
) | [
"def",
"avg_pool",
"(",
"data_batch",
":",
"NodeInput",
",",
"strides",
":",
"List",
"[",
"int",
"]",
",",
"pads_begin",
":",
"TensorShape",
",",
"pads_end",
":",
"TensorShape",
",",
"kernel_shape",
":",
"TensorShape",
",",
"exclude_pad",
":",
"bool",
",",
"rounding_type",
":",
"str",
"=",
"\"floor\"",
",",
"auto_pad",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
")",
"->",
"Node",
":",
"if",
"auto_pad",
"is",
"None",
":",
"auto_pad",
"=",
"\"explicit\"",
"return",
"_get_node_factory",
"(",
")",
".",
"create",
"(",
"\"AvgPool\"",
",",
"[",
"as_node",
"(",
"data_batch",
")",
"]",
",",
"{",
"\"strides\"",
":",
"strides",
",",
"\"pads_begin\"",
":",
"pads_begin",
",",
"\"pads_end\"",
":",
"pads_end",
",",
"\"kernel\"",
":",
"kernel_shape",
",",
"\"exclude_pad\"",
":",
"exclude_pad",
",",
"\"rounding_type\"",
":",
"rounding_type",
".",
"upper",
"(",
")",
",",
"\"auto_pad\"",
":",
"auto_pad",
".",
"upper",
"(",
")",
",",
"}",
",",
")"
] | https://github.com/NervanaSystems/ngraph/blob/f677a119765ca30636cf407009dabd118664951f/python/src/ngraph/ops.py#L1842-L1883 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/ops/distributions/distribution.py | python | _copy_fn | (fn) | return types.FunctionType(
code=fn.__code__, globals=fn.__globals__,
name=fn.__name__, argdefs=fn.__defaults__,
closure=fn.__closure__) | Create a deep copy of fn.
Args:
fn: a callable
Returns:
A `FunctionType`: a deep copy of fn.
Raises:
TypeError: if `fn` is not a callable. | Create a deep copy of fn. | [
"Create",
"a",
"deep",
"copy",
"of",
"fn",
"."
] | def _copy_fn(fn):
"""Create a deep copy of fn.
Args:
fn: a callable
Returns:
A `FunctionType`: a deep copy of fn.
Raises:
TypeError: if `fn` is not a callable.
"""
if not callable(fn):
raise TypeError("fn is not callable: %s" % fn)
# The blessed way to copy a function. copy.deepcopy fails to create a
# non-reference copy. Since:
# types.FunctionType == type(lambda: None),
# and the docstring for the function type states:
#
# function(code, globals[, name[, argdefs[, closure]]])
#
# Create a function object from a code object and a dictionary.
# ...
#
# Here we can use this to create a new function with the old function's
# code, globals, closure, etc.
return types.FunctionType(
code=fn.__code__, globals=fn.__globals__,
name=fn.__name__, argdefs=fn.__defaults__,
closure=fn.__closure__) | [
"def",
"_copy_fn",
"(",
"fn",
")",
":",
"if",
"not",
"callable",
"(",
"fn",
")",
":",
"raise",
"TypeError",
"(",
"\"fn is not callable: %s\"",
"%",
"fn",
")",
"# The blessed way to copy a function. copy.deepcopy fails to create a",
"# non-reference copy. Since:",
"# types.FunctionType == type(lambda: None),",
"# and the docstring for the function type states:",
"#",
"# function(code, globals[, name[, argdefs[, closure]]])",
"#",
"# Create a function object from a code object and a dictionary.",
"# ...",
"#",
"# Here we can use this to create a new function with the old function's",
"# code, globals, closure, etc.",
"return",
"types",
".",
"FunctionType",
"(",
"code",
"=",
"fn",
".",
"__code__",
",",
"globals",
"=",
"fn",
".",
"__globals__",
",",
"name",
"=",
"fn",
".",
"__name__",
",",
"argdefs",
"=",
"fn",
".",
"__defaults__",
",",
"closure",
"=",
"fn",
".",
"__closure__",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/distributions/distribution.py#L58-L87 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/idlelib/replace.py | python | ReplaceDialog.create_entries | (self) | Create base and additional label and text entry widgets. | Create base and additional label and text entry widgets. | [
"Create",
"base",
"and",
"additional",
"label",
"and",
"text",
"entry",
"widgets",
"."
] | def create_entries(self):
"Create base and additional label and text entry widgets."
SearchDialogBase.create_entries(self)
self.replent = self.make_entry("Replace with:", self.replvar)[0] | [
"def",
"create_entries",
"(",
"self",
")",
":",
"SearchDialogBase",
".",
"create_entries",
"(",
"self",
")",
"self",
".",
"replent",
"=",
"self",
".",
"make_entry",
"(",
"\"Replace with:\"",
",",
"self",
".",
"replvar",
")",
"[",
"0",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/idlelib/replace.py#L76-L79 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/Inelastic/IndirectCommon.py | python | CheckHistSame | (in1WS, name1, in2WS, name2) | Check workspaces have same number of histograms and bin boundaries
Args:
@param in1WS - first 2D workspace
@param name1 - single-word descriptor of first 2D workspace
@param in2WS - second 2D workspace
@param name2 - single-word descriptor of second 2D workspace
Returns:
@return None
Raises:
Valuerror: number of histograms is different
Valuerror: number of bin boundaries in the histograms is different | Check workspaces have same number of histograms and bin boundaries | [
"Check",
"workspaces",
"have",
"same",
"number",
"of",
"histograms",
"and",
"bin",
"boundaries"
] | def CheckHistSame(in1WS, name1, in2WS, name2):
"""
Check workspaces have same number of histograms and bin boundaries
Args:
@param in1WS - first 2D workspace
@param name1 - single-word descriptor of first 2D workspace
@param in2WS - second 2D workspace
@param name2 - single-word descriptor of second 2D workspace
Returns:
@return None
Raises:
Valuerror: number of histograms is different
Valuerror: number of bin boundaries in the histograms is different
"""
num_hist_1 = s_api.mtd[in1WS].getNumberHistograms() # no. of hist/groups in WS1
x_1 = s_api.mtd[in1WS].readX(0)
x_len_1 = len(x_1)
num_hist_2 = s_api.mtd[in2WS].getNumberHistograms() # no. of hist/groups in WS2
x_2 = s_api.mtd[in2WS].readX(0)
x_len_2 = len(x_2)
if num_hist_1 != num_hist_2: # Check that no. groups are the same
error_1 = '%s (%s) histograms (%d)' % (name1, in1WS, num_hist_1)
error_2 = '%s (%s) histograms (%d)' % (name2, in2WS, num_hist_2)
error = error_1 + ' not = ' + error_2
raise ValueError(error)
elif x_len_1 != x_len_2:
error_1 = '%s (%s) array length (%d)' % (name1, in1WS, x_len_1)
error_2 = '%s (%s) array length (%d)' % (name2, in2WS, x_len_2)
error = error_1 + ' not = ' + error_2
raise ValueError(error) | [
"def",
"CheckHistSame",
"(",
"in1WS",
",",
"name1",
",",
"in2WS",
",",
"name2",
")",
":",
"num_hist_1",
"=",
"s_api",
".",
"mtd",
"[",
"in1WS",
"]",
".",
"getNumberHistograms",
"(",
")",
"# no. of hist/groups in WS1",
"x_1",
"=",
"s_api",
".",
"mtd",
"[",
"in1WS",
"]",
".",
"readX",
"(",
"0",
")",
"x_len_1",
"=",
"len",
"(",
"x_1",
")",
"num_hist_2",
"=",
"s_api",
".",
"mtd",
"[",
"in2WS",
"]",
".",
"getNumberHistograms",
"(",
")",
"# no. of hist/groups in WS2",
"x_2",
"=",
"s_api",
".",
"mtd",
"[",
"in2WS",
"]",
".",
"readX",
"(",
"0",
")",
"x_len_2",
"=",
"len",
"(",
"x_2",
")",
"if",
"num_hist_1",
"!=",
"num_hist_2",
":",
"# Check that no. groups are the same",
"error_1",
"=",
"'%s (%s) histograms (%d)'",
"%",
"(",
"name1",
",",
"in1WS",
",",
"num_hist_1",
")",
"error_2",
"=",
"'%s (%s) histograms (%d)'",
"%",
"(",
"name2",
",",
"in2WS",
",",
"num_hist_2",
")",
"error",
"=",
"error_1",
"+",
"' not = '",
"+",
"error_2",
"raise",
"ValueError",
"(",
"error",
")",
"elif",
"x_len_1",
"!=",
"x_len_2",
":",
"error_1",
"=",
"'%s (%s) array length (%d)'",
"%",
"(",
"name1",
",",
"in1WS",
",",
"x_len_1",
")",
"error_2",
"=",
"'%s (%s) array length (%d)'",
"%",
"(",
"name2",
",",
"in2WS",
",",
"x_len_2",
")",
"error",
"=",
"error_1",
"+",
"' not = '",
"+",
"error_2",
"raise",
"ValueError",
"(",
"error",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Inelastic/IndirectCommon.py#L367-L399 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/listobject.py | python | _raise_if_error | (context, builder, status, msg) | Raise an internal error depending on the value of *status* | Raise an internal error depending on the value of *status* | [
"Raise",
"an",
"internal",
"error",
"depending",
"on",
"the",
"value",
"of",
"*",
"status",
"*"
] | def _raise_if_error(context, builder, status, msg):
"""Raise an internal error depending on the value of *status*
"""
ok_status = status.type(int(ListStatus.LIST_OK))
with builder.if_then(builder.icmp_signed('!=', status, ok_status),
likely=True):
context.call_conv.return_user_exc(builder, RuntimeError, (msg,)) | [
"def",
"_raise_if_error",
"(",
"context",
",",
"builder",
",",
"status",
",",
"msg",
")",
":",
"ok_status",
"=",
"status",
".",
"type",
"(",
"int",
"(",
"ListStatus",
".",
"LIST_OK",
")",
")",
"with",
"builder",
".",
"if_then",
"(",
"builder",
".",
"icmp_signed",
"(",
"'!='",
",",
"status",
",",
"ok_status",
")",
",",
"likely",
"=",
"True",
")",
":",
"context",
".",
"call_conv",
".",
"return_user_exc",
"(",
"builder",
",",
"RuntimeError",
",",
"(",
"msg",
",",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/listobject.py#L88-L94 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/syntax/_javascript.py | python | SyntaxData.GetSyntaxSpec | (self) | Syntax Specifications | Syntax Specifications | [
"Syntax",
"Specifications"
] | def GetSyntaxSpec(self):
"""Syntax Specifications """
if self.LangId == synglob.ID_LANG_HTML:
return SYNTAX_ITEMS
else:
return _cpp.SYNTAX_ITEMS | [
"def",
"GetSyntaxSpec",
"(",
"self",
")",
":",
"if",
"self",
".",
"LangId",
"==",
"synglob",
".",
"ID_LANG_HTML",
":",
"return",
"SYNTAX_ITEMS",
"else",
":",
"return",
"_cpp",
".",
"SYNTAX_ITEMS"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/syntax/_javascript.py#L86-L91 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/distutils/exec_command.py | python | exec_command | (command, execute_in='', use_shell=None, use_tee=None,
_with_python = 1, **env ) | return st | Return (status,output) of executed command.
.. deprecated:: 1.17
Use subprocess.Popen instead
Parameters
----------
command : str
A concatenated string of executable and arguments.
execute_in : str
Before running command ``cd execute_in`` and after ``cd -``.
use_shell : {bool, None}, optional
If True, execute ``sh -c command``. Default None (True)
use_tee : {bool, None}, optional
If True use tee. Default None (True)
Returns
-------
res : str
Both stdout and stderr messages.
Notes
-----
On NT, DOS systems the returned status is correct for external commands.
Wild cards will not work for non-posix systems or when use_shell=0. | Return (status,output) of executed command. | [
"Return",
"(",
"status",
"output",
")",
"of",
"executed",
"command",
"."
] | def exec_command(command, execute_in='', use_shell=None, use_tee=None,
_with_python = 1, **env ):
"""
Return (status,output) of executed command.
.. deprecated:: 1.17
Use subprocess.Popen instead
Parameters
----------
command : str
A concatenated string of executable and arguments.
execute_in : str
Before running command ``cd execute_in`` and after ``cd -``.
use_shell : {bool, None}, optional
If True, execute ``sh -c command``. Default None (True)
use_tee : {bool, None}, optional
If True use tee. Default None (True)
Returns
-------
res : str
Both stdout and stderr messages.
Notes
-----
On NT, DOS systems the returned status is correct for external commands.
Wild cards will not work for non-posix systems or when use_shell=0.
"""
# 2019-01-30, 1.17
warnings.warn('exec_command is deprecated since NumPy v1.17, use '
'subprocess.Popen instead', DeprecationWarning, stacklevel=1)
log.debug('exec_command(%r,%s)' % (command,
','.join(['%s=%r'%kv for kv in env.items()])))
if use_tee is None:
use_tee = os.name=='posix'
if use_shell is None:
use_shell = os.name=='posix'
execute_in = os.path.abspath(execute_in)
oldcwd = os.path.abspath(os.getcwd())
if __name__[-12:] == 'exec_command':
exec_dir = os.path.dirname(os.path.abspath(__file__))
elif os.path.isfile('exec_command.py'):
exec_dir = os.path.abspath('.')
else:
exec_dir = os.path.abspath(sys.argv[0])
if os.path.isfile(exec_dir):
exec_dir = os.path.dirname(exec_dir)
if oldcwd!=execute_in:
os.chdir(execute_in)
log.debug('New cwd: %s' % execute_in)
else:
log.debug('Retaining cwd: %s' % oldcwd)
oldenv = _preserve_environment( list(env.keys()) )
_update_environment( **env )
try:
st = _exec_command(command,
use_shell=use_shell,
use_tee=use_tee,
**env)
finally:
if oldcwd!=execute_in:
os.chdir(oldcwd)
log.debug('Restored cwd to %s' % oldcwd)
_update_environment(**oldenv)
return st | [
"def",
"exec_command",
"(",
"command",
",",
"execute_in",
"=",
"''",
",",
"use_shell",
"=",
"None",
",",
"use_tee",
"=",
"None",
",",
"_with_python",
"=",
"1",
",",
"*",
"*",
"env",
")",
":",
"# 2019-01-30, 1.17",
"warnings",
".",
"warn",
"(",
"'exec_command is deprecated since NumPy v1.17, use '",
"'subprocess.Popen instead'",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"1",
")",
"log",
".",
"debug",
"(",
"'exec_command(%r,%s)'",
"%",
"(",
"command",
",",
"','",
".",
"join",
"(",
"[",
"'%s=%r'",
"%",
"kv",
"for",
"kv",
"in",
"env",
".",
"items",
"(",
")",
"]",
")",
")",
")",
"if",
"use_tee",
"is",
"None",
":",
"use_tee",
"=",
"os",
".",
"name",
"==",
"'posix'",
"if",
"use_shell",
"is",
"None",
":",
"use_shell",
"=",
"os",
".",
"name",
"==",
"'posix'",
"execute_in",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"execute_in",
")",
"oldcwd",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"getcwd",
"(",
")",
")",
"if",
"__name__",
"[",
"-",
"12",
":",
"]",
"==",
"'exec_command'",
":",
"exec_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
"elif",
"os",
".",
"path",
".",
"isfile",
"(",
"'exec_command.py'",
")",
":",
"exec_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"'.'",
")",
"else",
":",
"exec_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"sys",
".",
"argv",
"[",
"0",
"]",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"exec_dir",
")",
":",
"exec_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"exec_dir",
")",
"if",
"oldcwd",
"!=",
"execute_in",
":",
"os",
".",
"chdir",
"(",
"execute_in",
")",
"log",
".",
"debug",
"(",
"'New cwd: %s'",
"%",
"execute_in",
")",
"else",
":",
"log",
".",
"debug",
"(",
"'Retaining cwd: %s'",
"%",
"oldcwd",
")",
"oldenv",
"=",
"_preserve_environment",
"(",
"list",
"(",
"env",
".",
"keys",
"(",
")",
")",
")",
"_update_environment",
"(",
"*",
"*",
"env",
")",
"try",
":",
"st",
"=",
"_exec_command",
"(",
"command",
",",
"use_shell",
"=",
"use_shell",
",",
"use_tee",
"=",
"use_tee",
",",
"*",
"*",
"env",
")",
"finally",
":",
"if",
"oldcwd",
"!=",
"execute_in",
":",
"os",
".",
"chdir",
"(",
"oldcwd",
")",
"log",
".",
"debug",
"(",
"'Restored cwd to %s'",
"%",
"oldcwd",
")",
"_update_environment",
"(",
"*",
"*",
"oldenv",
")",
"return",
"st"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/distutils/exec_command.py#L177-L250 | |
KratosMultiphysics/Kratos | 0000833054ed0503424eb28205d6508d9ca6cbbc | applications/SolidMechanicsApplication/python_scripts/convergence_criteria_factory.py | python | ConvergenceCriterion.__init__ | (self, custom_settings, dofs_list) | Create a convergence criterion from json parameters. | Create a convergence criterion from json parameters. | [
"Create",
"a",
"convergence",
"criterion",
"from",
"json",
"parameters",
"."
] | def __init__(self, custom_settings, dofs_list):
"""
Create a convergence criterion from json parameters.
"""
default_settings = KratosMultiphysics.Parameters("""
{
"convergence_criterion": "Residual_criterion",
"variable_relative_tolerance": 1.0e-4,
"variable_absolute_tolerance": 1.0e-9,
"residual_relative_tolerance": 1.0e-4,
"residual_absolute_tolerance": 1.0e-9,
"separate_dofs" : true,
"echo_level": 0
}
""")
# Overwrite the default settings with user-provided parameters
self.settings = custom_settings
self.settings.ValidateAndAssignDefaults(default_settings)
self.dofs = []
for i in range(0, dofs_list.size() ):
self.dofs.append(dofs_list[i].GetString())
# add default DISPLACEMENT dof
if( len(self.dofs) == 0 or (len(self.dofs) == 1 and self.dofs[0] =="ROTATION") ):
self.dofs.append('DISPLACEMENT') | [
"def",
"__init__",
"(",
"self",
",",
"custom_settings",
",",
"dofs_list",
")",
":",
"default_settings",
"=",
"KratosMultiphysics",
".",
"Parameters",
"(",
"\"\"\"\n {\n \"convergence_criterion\": \"Residual_criterion\",\n \"variable_relative_tolerance\": 1.0e-4,\n \"variable_absolute_tolerance\": 1.0e-9,\n \"residual_relative_tolerance\": 1.0e-4,\n \"residual_absolute_tolerance\": 1.0e-9,\n \"separate_dofs\" : true,\n \"echo_level\": 0\n }\n \"\"\"",
")",
"# Overwrite the default settings with user-provided parameters",
"self",
".",
"settings",
"=",
"custom_settings",
"self",
".",
"settings",
".",
"ValidateAndAssignDefaults",
"(",
"default_settings",
")",
"self",
".",
"dofs",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"dofs_list",
".",
"size",
"(",
")",
")",
":",
"self",
".",
"dofs",
".",
"append",
"(",
"dofs_list",
"[",
"i",
"]",
".",
"GetString",
"(",
")",
")",
"# add default DISPLACEMENT dof",
"if",
"(",
"len",
"(",
"self",
".",
"dofs",
")",
"==",
"0",
"or",
"(",
"len",
"(",
"self",
".",
"dofs",
")",
"==",
"1",
"and",
"self",
".",
"dofs",
"[",
"0",
"]",
"==",
"\"ROTATION\"",
")",
")",
":",
"self",
".",
"dofs",
".",
"append",
"(",
"'DISPLACEMENT'",
")"
] | https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/SolidMechanicsApplication/python_scripts/convergence_criteria_factory.py#L11-L37 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py2/numpy/lib/format.py | python | read_array_header_1_0 | (fp) | return _read_array_header(fp, version=(1, 0)) | Read an array header from a filelike object using the 1.0 file format
version.
This will leave the file object located just after the header.
Parameters
----------
fp : filelike object
A file object or something with a `.read()` method like a file.
Returns
-------
shape : tuple of int
The shape of the array.
fortran_order : bool
The array data will be written out directly if it is either
C-contiguous or Fortran-contiguous. Otherwise, it will be made
contiguous before writing it out.
dtype : dtype
The dtype of the file's data.
Raises
------
ValueError
If the data is invalid. | Read an array header from a filelike object using the 1.0 file format
version. | [
"Read",
"an",
"array",
"header",
"from",
"a",
"filelike",
"object",
"using",
"the",
"1",
".",
"0",
"file",
"format",
"version",
"."
] | def read_array_header_1_0(fp):
"""
Read an array header from a filelike object using the 1.0 file format
version.
This will leave the file object located just after the header.
Parameters
----------
fp : filelike object
A file object or something with a `.read()` method like a file.
Returns
-------
shape : tuple of int
The shape of the array.
fortran_order : bool
The array data will be written out directly if it is either
C-contiguous or Fortran-contiguous. Otherwise, it will be made
contiguous before writing it out.
dtype : dtype
The dtype of the file's data.
Raises
------
ValueError
If the data is invalid.
"""
return _read_array_header(fp, version=(1, 0)) | [
"def",
"read_array_header_1_0",
"(",
"fp",
")",
":",
"return",
"_read_array_header",
"(",
"fp",
",",
"version",
"=",
"(",
"1",
",",
"0",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/lib/format.py#L414-L443 | |
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/psutil/psutil/__init__.py | python | Process.wait | (self, timeout=None) | return self._proc.wait(timeout) | Wait for process to terminate and, if process is a children
of os.getpid(), also return its exit code, else None.
If the process is already terminated immediately return None
instead of raising NoSuchProcess.
If timeout (in seconds) is specified and process is still alive
raise TimeoutExpired.
To wait for multiple Process(es) use psutil.wait_procs(). | Wait for process to terminate and, if process is a children
of os.getpid(), also return its exit code, else None. | [
"Wait",
"for",
"process",
"to",
"terminate",
"and",
"if",
"process",
"is",
"a",
"children",
"of",
"os",
".",
"getpid",
"()",
"also",
"return",
"its",
"exit",
"code",
"else",
"None",
"."
] | def wait(self, timeout=None):
"""Wait for process to terminate and, if process is a children
of os.getpid(), also return its exit code, else None.
If the process is already terminated immediately return None
instead of raising NoSuchProcess.
If timeout (in seconds) is specified and process is still alive
raise TimeoutExpired.
To wait for multiple Process(es) use psutil.wait_procs().
"""
if timeout is not None and not timeout >= 0:
raise ValueError("timeout must be a positive integer")
return self._proc.wait(timeout) | [
"def",
"wait",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"timeout",
"is",
"not",
"None",
"and",
"not",
"timeout",
">=",
"0",
":",
"raise",
"ValueError",
"(",
"\"timeout must be a positive integer\"",
")",
"return",
"self",
".",
"_proc",
".",
"wait",
"(",
"timeout",
")"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/psutil/psutil/__init__.py#L1036-L1050 | |
malaterre/GDCM | d1fe2137730ffc6c9ac033ded27e7bf70d0ac577 | Applications/Python/wado.py | python | err | (msg) | Function to handle errors | Function to handle errors | [
"Function",
"to",
"handle",
"errors"
] | def err(msg):
"""Function to handle errors"""
raise Exception, msg | [
"def",
"err",
"(",
"msg",
")",
":",
"raise",
"Exception",
",",
"msg"
] | https://github.com/malaterre/GDCM/blob/d1fe2137730ffc6c9ac033ded27e7bf70d0ac577/Applications/Python/wado.py#L59-L61 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/telemetry/internal/backends/chrome/cros_browser_with_oobe.py | python | CrOSBrowserWithOOBE.oobe_exists | (self) | return self._browser_backend.oobe_exists | True if the login/oobe/screenlock webui exists. This is more lightweight
than accessing the oobe property. | True if the login/oobe/screenlock webui exists. This is more lightweight
than accessing the oobe property. | [
"True",
"if",
"the",
"login",
"/",
"oobe",
"/",
"screenlock",
"webui",
"exists",
".",
"This",
"is",
"more",
"lightweight",
"than",
"accessing",
"the",
"oobe",
"property",
"."
] | def oobe_exists(self):
"""True if the login/oobe/screenlock webui exists. This is more lightweight
than accessing the oobe property.
"""
return self._browser_backend.oobe_exists | [
"def",
"oobe_exists",
"(",
"self",
")",
":",
"return",
"self",
".",
"_browser_backend",
".",
"oobe_exists"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/internal/backends/chrome/cros_browser_with_oobe.py#L24-L28 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/protobuf/python/stubout.py | python | StubOutForTesting.SmartUnsetAll | (self) | Reverses all the SmartSet() calls, restoring things to their original
definition. Its okay to call SmartUnsetAll() repeatedly, as later calls
have no effect if no SmartSet() calls have been made. | Reverses all the SmartSet() calls, restoring things to their original
definition. Its okay to call SmartUnsetAll() repeatedly, as later calls
have no effect if no SmartSet() calls have been made. | [
"Reverses",
"all",
"the",
"SmartSet",
"()",
"calls",
"restoring",
"things",
"to",
"their",
"original",
"definition",
".",
"Its",
"okay",
"to",
"call",
"SmartUnsetAll",
"()",
"repeatedly",
"as",
"later",
"calls",
"have",
"no",
"effect",
"if",
"no",
"SmartSet",
"()",
"calls",
"have",
"been",
"made",
"."
] | def SmartUnsetAll(self):
"""Reverses all the SmartSet() calls, restoring things to their original
definition. Its okay to call SmartUnsetAll() repeatedly, as later calls
have no effect if no SmartSet() calls have been made.
"""
self.stubs.reverse()
for args in self.stubs:
setattr(*args)
self.stubs = [] | [
"def",
"SmartUnsetAll",
"(",
"self",
")",
":",
"self",
".",
"stubs",
".",
"reverse",
"(",
")",
"for",
"args",
"in",
"self",
".",
"stubs",
":",
"setattr",
"(",
"*",
"args",
")",
"self",
".",
"stubs",
"=",
"[",
"]"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/protobuf/python/stubout.py#L96-L107 | ||
pytorch/ELF | e851e786ced8d26cf470f08a6b9bf7e413fc63f7 | src_py/rlpytorch/model_interface.py | python | ModelInterface.update_model | (self, key, model, save_old_model=False) | If the key is present, update an old model. Does not deep copy it.
If the key is not present, add it (no deep copy).
Args:
key(str): the key in ``models`` to be updated
model(`Model`): updated model | If the key is present, update an old model. Does not deep copy it.
If the key is not present, add it (no deep copy). | [
"If",
"the",
"key",
"is",
"present",
"update",
"an",
"old",
"model",
".",
"Does",
"not",
"deep",
"copy",
"it",
".",
"If",
"the",
"key",
"is",
"not",
"present",
"add",
"it",
"(",
"no",
"deep",
"copy",
")",
"."
] | def update_model(self, key, model, save_old_model=False):
''' If the key is present, update an old model. Does not deep copy it.
If the key is not present, add it (no deep copy).
Args:
key(str): the key in ``models`` to be updated
model(`Model`): updated model
'''
# print("Updating model " + key)
if key not in self.models:
self.add_model(key, model)
return
if save_old_model:
self.old_models.append(self.models[key].clone().cpu())
if len(self.old_models) > 20:
self.old_models.popleft()
self.models[key].load_from(model) | [
"def",
"update_model",
"(",
"self",
",",
"key",
",",
"model",
",",
"save_old_model",
"=",
"False",
")",
":",
"# print(\"Updating model \" + key)",
"if",
"key",
"not",
"in",
"self",
".",
"models",
":",
"self",
".",
"add_model",
"(",
"key",
",",
"model",
")",
"return",
"if",
"save_old_model",
":",
"self",
".",
"old_models",
".",
"append",
"(",
"self",
".",
"models",
"[",
"key",
"]",
".",
"clone",
"(",
")",
".",
"cpu",
"(",
")",
")",
"if",
"len",
"(",
"self",
".",
"old_models",
")",
">",
"20",
":",
"self",
".",
"old_models",
".",
"popleft",
"(",
")",
"self",
".",
"models",
"[",
"key",
"]",
".",
"load_from",
"(",
"model",
")"
] | https://github.com/pytorch/ELF/blob/e851e786ced8d26cf470f08a6b9bf7e413fc63f7/src_py/rlpytorch/model_interface.py#L182-L200 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/platform.py | python | release | () | return uname()[2] | Returns the system's release, e.g. '2.2.0' or 'NT'
An empty string is returned if the value cannot be determined. | Returns the system's release, e.g. '2.2.0' or 'NT' | [
"Returns",
"the",
"system",
"s",
"release",
"e",
".",
"g",
".",
"2",
".",
"2",
".",
"0",
"or",
"NT"
] | def release():
""" Returns the system's release, e.g. '2.2.0' or 'NT'
An empty string is returned if the value cannot be determined.
"""
return uname()[2] | [
"def",
"release",
"(",
")",
":",
"return",
"uname",
"(",
")",
"[",
"2",
"]"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/platform.py#L1322-L1329 | |
llvm/llvm-project | ffa6262cb4e2a335d26416fad39a581b4f98c5f4 | lldb/third_party/Python/module/pexpect-4.6/pexpect/screen.py | python | constrain | (n, min, max) | return n | This returns a number, n constrained to the min and max bounds. | This returns a number, n constrained to the min and max bounds. | [
"This",
"returns",
"a",
"number",
"n",
"constrained",
"to",
"the",
"min",
"and",
"max",
"bounds",
"."
] | def constrain (n, min, max):
'''This returns a number, n constrained to the min and max bounds. '''
if n < min:
return min
if n > max:
return max
return n | [
"def",
"constrain",
"(",
"n",
",",
"min",
",",
"max",
")",
":",
"if",
"n",
"<",
"min",
":",
"return",
"min",
"if",
"n",
">",
"max",
":",
"return",
"max",
"return",
"n"
] | https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/lldb/third_party/Python/module/pexpect-4.6/pexpect/screen.py#L60-L68 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.