nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/redis/client.py
python
Redis.setex
(self, name, value, time)
return self.execute_command('SETEX', name, time, value)
Set the value of key ``name`` to ``value`` that expires in ``time`` seconds. ``time`` can be represented by an integer or a Python timedelta object.
Set the value of key ``name`` to ``value`` that expires in ``time`` seconds. ``time`` can be represented by an integer or a Python timedelta object.
[ "Set", "the", "value", "of", "key", "name", "to", "value", "that", "expires", "in", "time", "seconds", ".", "time", "can", "be", "represented", "by", "an", "integer", "or", "a", "Python", "timedelta", "object", "." ]
def setex(self, name, value, time): """ Set the value of key ``name`` to ``value`` that expires in ``time`` seconds. ``time`` can be represented by an integer or a Python timedelta object. """ if isinstance(time, datetime.timedelta): time = time.seconds + time.days * 24 * 3600 return self.execute_command('SETEX', name, time, value)
[ "def", "setex", "(", "self", ",", "name", ",", "value", ",", "time", ")", ":", "if", "isinstance", "(", "time", ",", "datetime", ".", "timedelta", ")", ":", "time", "=", "time", ".", "seconds", "+", "time", ".", "days", "*", "24", "*", "3600", "r...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/redis/client.py#L2270-L2278
iclavera/learning_to_adapt
bd7d99ba402521c96631e7d09714128f549db0f1
learning_to_adapt/mujoco_py/mjtypes.py
python
MjModelWrapper.dof_frictional
(self, value)
[]
def dof_frictional(self, value): val_ptr = np.array(value, dtype=np.float64).ctypes.data_as(POINTER(c_ubyte)) memmove(self._wrapped.contents.dof_frictional, val_ptr, self.nv*1 * sizeof(c_ubyte))
[ "def", "dof_frictional", "(", "self", ",", "value", ")", ":", "val_ptr", "=", "np", ".", "array", "(", "value", ",", "dtype", "=", "np", ".", "float64", ")", ".", "ctypes", ".", "data_as", "(", "POINTER", "(", "c_ubyte", ")", ")", "memmove", "(", "...
https://github.com/iclavera/learning_to_adapt/blob/bd7d99ba402521c96631e7d09714128f549db0f1/learning_to_adapt/mujoco_py/mjtypes.py#L4123-L4125
Delta-ML/delta
31dfebc8f20b7cb282b62f291ff25a87e403cc86
delta/data/feat/speech_feature.py
python
powspec_feat
(samples, sr=8000, nfft=512, winlen=0.025, winstep=0.01, lowfreq=0, highfreq=None, preemph=0.97)
return feat
return : [nframe, nfft / 2 + 1]
return : [nframe, nfft / 2 + 1]
[ "return", ":", "[", "nframe", "nfft", "/", "2", "+", "1", "]" ]
def powspec_feat(samples, sr=8000, nfft=512, winlen=0.025, winstep=0.01, lowfreq=0, highfreq=None, preemph=0.97): ''' return : [nframe, nfft / 2 + 1] ''' feat = psf.powerspec( samples, nfft=nfft, samplerate=sr, winlen=winlen, winstep=winstep, lowfreq=lowfreq, highfreq=highfreq, preemph=preemph) return feat
[ "def", "powspec_feat", "(", "samples", ",", "sr", "=", "8000", ",", "nfft", "=", "512", ",", "winlen", "=", "0.025", ",", "winstep", "=", "0.01", ",", "lowfreq", "=", "0", ",", "highfreq", "=", "None", ",", "preemph", "=", "0.97", ")", ":", "feat",...
https://github.com/Delta-ML/delta/blob/31dfebc8f20b7cb282b62f291ff25a87e403cc86/delta/data/feat/speech_feature.py#L253-L271
AndrewAnnex/SpiceyPy
9f8b626338f119bacd39ef2ba94a6f71bd6341c0
src/spiceypy/spiceypy.py
python
lx4uns
(string: str, first: int)
return last.value, nchar.value
Scan a string from a specified starting position for the end of an unsigned integer. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lx4uns_c.html :param string: Any character string. :param first: First character to scan from in string. :return: last and nchar
Scan a string from a specified starting position for the end of an unsigned integer.
[ "Scan", "a", "string", "from", "a", "specified", "starting", "position", "for", "the", "end", "of", "an", "unsigned", "integer", "." ]
def lx4uns(string: str, first: int) -> Tuple[int, int]: """ Scan a string from a specified starting position for the end of an unsigned integer. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lx4uns_c.html :param string: Any character string. :param first: First character to scan from in string. :return: last and nchar """ string = stypes.string_to_char_p(string) first = ctypes.c_int(first) last = ctypes.c_int() nchar = ctypes.c_int() libspice.lx4uns_c(string, first, ctypes.byref(last), ctypes.byref(nchar)) return last.value, nchar.value
[ "def", "lx4uns", "(", "string", ":", "str", ",", "first", ":", "int", ")", "->", "Tuple", "[", "int", ",", "int", "]", ":", "string", "=", "stypes", ".", "string_to_char_p", "(", "string", ")", "first", "=", "ctypes", ".", "c_int", "(", "first", ")...
https://github.com/AndrewAnnex/SpiceyPy/blob/9f8b626338f119bacd39ef2ba94a6f71bd6341c0/src/spiceypy/spiceypy.py#L8614-L8630
PaddlePaddle/PaddleX
2bab73f81ab54e328204e7871e6ae4a82e719f5d
paddlex_restful/restful/model.py
python
get_model_details
(data, workspace)
return { 'status': 1, 'dataset_attr': dataset_attr, 'task_params': task_params, 'eval_result': eval_result }
获取模型详情。 Args: data为dict, key包括'mid'模型id
获取模型详情。
[ "获取模型详情。" ]
def get_model_details(data, workspace): """获取模型详情。 Args: data为dict, key包括'mid'模型id """ mid = data['mid'] if mid in workspace.pretrained_models: model_path = workspace.pretrained_models[mid].path elif mid in workspace.exported_models: model_path = workspace.exported_models[mid].path else: raise "模型{}不存在".format(mid) dataset_file = osp.join(model_path, 'statis.pkl') dataset_info = pickle.load(open(dataset_file, 'rb')) dataset_attr = { 'name': dataset_info['name'], 'desc': dataset_info['desc'], 'labels': dataset_info['labels'], 'train_num': len(dataset_info['train_files']), 'val_num': len(dataset_info['val_files']), 'test_num': len(dataset_info['test_files']) } task_params_file = osp.join(model_path, 'params.pkl') task_params = pickle.load(open(task_params_file, 'rb')) eval_result_file = osp.join(model_path, 'eval_res.pkl') eval_result = pickle.load(open(eval_result_file, 'rb')) #model_file = {'task_attr': task_params_file, 'eval_result': eval_result_file} return { 'status': 1, 'dataset_attr': dataset_attr, 'task_params': task_params, 'eval_result': eval_result }
[ "def", "get_model_details", "(", "data", ",", "workspace", ")", ":", "mid", "=", "data", "[", "'mid'", "]", "if", "mid", "in", "workspace", ".", "pretrained_models", ":", "model_path", "=", "workspace", ".", "pretrained_models", "[", "mid", "]", ".", "path...
https://github.com/PaddlePaddle/PaddleX/blob/2bab73f81ab54e328204e7871e6ae4a82e719f5d/paddlex_restful/restful/model.py#L278-L312
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/xml/dom/expatbuilder.py
python
ExpatBuilder.__init__
(self, options=None)
[]
def __init__(self, options=None): if options is None: options = xmlbuilder.Options() self._options = options if self._options.filter is not None: self._filter = FilterVisibilityController(self._options.filter) else: self._filter = None # This *really* doesn't do anything in this case, so # override it with something fast & minimal. self._finish_start_element = id self._parser = None self.reset()
[ "def", "__init__", "(", "self", ",", "options", "=", "None", ")", ":", "if", "options", "is", "None", ":", "options", "=", "xmlbuilder", ".", "Options", "(", ")", "self", ".", "_options", "=", "options", "if", "self", ".", "_options", ".", "filter", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/xml/dom/expatbuilder.py#L137-L149
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/functools.py
python
cmp_to_key
(mycmp)
return K
Convert a cmp= function into a key= function
Convert a cmp= function into a key= function
[ "Convert", "a", "cmp", "=", "function", "into", "a", "key", "=", "function" ]
def cmp_to_key(mycmp): """Convert a cmp= function into a key= function""" class K(object): __slots__ = ['obj'] def __init__(self, obj, *args): self.obj = obj def __lt__(self, other): return mycmp(self.obj, other.obj) < 0 def __gt__(self, other): return mycmp(self.obj, other.obj) > 0 def __eq__(self, other): return mycmp(self.obj, other.obj) == 0 def __le__(self, other): return mycmp(self.obj, other.obj) <= 0 def __ge__(self, other): return mycmp(self.obj, other.obj) >= 0 def __ne__(self, other): return mycmp(self.obj, other.obj) != 0 def __hash__(self): raise TypeError('hash not implemented') return K
[ "def", "cmp_to_key", "(", "mycmp", ")", ":", "class", "K", "(", "object", ")", ":", "__slots__", "=", "[", "'obj'", "]", "def", "__init__", "(", "self", ",", "obj", ",", "*", "args", ")", ":", "self", ".", "obj", "=", "obj", "def", "__lt__", "(",...
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/functools.py#L80-L100
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/werkzeug/wrappers.py
python
CommonRequestDescriptorsMixin.mimetype_params
(self)
return self._parsed_content_type[1]
The mimetype parameters as dict. For example if the content type is ``text/html; charset=utf-8`` the params would be ``{'charset': 'utf-8'}``.
The mimetype parameters as dict. For example if the content type is ``text/html; charset=utf-8`` the params would be ``{'charset': 'utf-8'}``.
[ "The", "mimetype", "parameters", "as", "dict", ".", "For", "example", "if", "the", "content", "type", "is", "text", "/", "html", ";", "charset", "=", "utf", "-", "8", "the", "params", "would", "be", "{", "charset", ":", "utf", "-", "8", "}", "." ]
def mimetype_params(self): """The mimetype parameters as dict. For example if the content type is ``text/html; charset=utf-8`` the params would be ``{'charset': 'utf-8'}``. """ self._parse_content_type() return self._parsed_content_type[1]
[ "def", "mimetype_params", "(", "self", ")", ":", "self", ".", "_parse_content_type", "(", ")", "return", "self", ".", "_parsed_content_type", "[", "1", "]" ]
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/werkzeug/wrappers.py#L1594-L1600
Qiskit/qiskit-terra
b66030e3b9192efdd3eb95cf25c6545fe0a13da4
qiskit/circuit/quantumcircuit.py
python
QuantumCircuit.fredkin
( self, control_qubit: QubitSpecifier, target_qubit1: QubitSpecifier, target_qubit2: QubitSpecifier, )
return self.cswap(control_qubit, target_qubit1, target_qubit2)
Apply :class:`~qiskit.circuit.library.CSwapGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit1: The qubit(s) targeted by the gate. target_qubit2: The qubit(s) targeted by the gate. Returns: A handle to the instructions created. See Also: QuantumCircuit.cswap: the same function with a different name.
Apply :class:`~qiskit.circuit.library.CSwapGate`.
[ "Apply", ":", "class", ":", "~qiskit", ".", "circuit", ".", "library", ".", "CSwapGate", "." ]
def fredkin( self, control_qubit: QubitSpecifier, target_qubit1: QubitSpecifier, target_qubit2: QubitSpecifier, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CSwapGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit1: The qubit(s) targeted by the gate. target_qubit2: The qubit(s) targeted by the gate. Returns: A handle to the instructions created. See Also: QuantumCircuit.cswap: the same function with a different name. """ return self.cswap(control_qubit, target_qubit1, target_qubit2)
[ "def", "fredkin", "(", "self", ",", "control_qubit", ":", "QubitSpecifier", ",", "target_qubit1", ":", "QubitSpecifier", ",", "target_qubit2", ":", "QubitSpecifier", ",", ")", "->", "InstructionSet", ":", "return", "self", ".", "cswap", "(", "control_qubit", ","...
https://github.com/Qiskit/qiskit-terra/blob/b66030e3b9192efdd3eb95cf25c6545fe0a13da4/qiskit/circuit/quantumcircuit.py#L3352-L3373
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/modbus/cover.py
python
ModbusCover.__init__
( self, hub: ModbusHub, config: dict[str, Any], )
Initialize the modbus cover.
Initialize the modbus cover.
[ "Initialize", "the", "modbus", "cover", "." ]
def __init__( self, hub: ModbusHub, config: dict[str, Any], ) -> None: """Initialize the modbus cover.""" super().__init__(hub, config) self._state_closed = config[CONF_STATE_CLOSED] self._state_closing = config[CONF_STATE_CLOSING] self._state_open = config[CONF_STATE_OPEN] self._state_opening = config[CONF_STATE_OPENING] self._status_register = config.get(CONF_STATUS_REGISTER) self._status_register_type = config[CONF_STATUS_REGISTER_TYPE] self._attr_supported_features = SUPPORT_OPEN | SUPPORT_CLOSE self._attr_is_closed = False # If we read cover status from coil, and not from optional status register, # we interpret boolean value False as closed cover, and value True as open cover. # Intermediate states are not supported in such a setup. if self._input_type == CALL_TYPE_COIL: self._write_type = CALL_TYPE_WRITE_COIL self._write_address = self._address if self._status_register is None: self._state_closed = False self._state_open = True self._state_closing = None self._state_opening = None else: # If we read cover status from the main register (i.e., an optional # status register is not specified), we need to make sure the register_type # is set to "holding". self._write_type = CALL_TYPE_WRITE_REGISTER self._write_address = self._address if self._status_register: self._address = self._status_register self._input_type = self._status_register_type
[ "def", "__init__", "(", "self", ",", "hub", ":", "ModbusHub", ",", "config", ":", "dict", "[", "str", ",", "Any", "]", ",", ")", "->", "None", ":", "super", "(", ")", ".", "__init__", "(", "hub", ",", "config", ")", "self", ".", "_state_closed", ...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/modbus/cover.py#L62-L98
GoogleCloudPlatform/PerfKitBenchmarker
6e3412d7d5e414b8ca30ed5eaf970cef1d919a67
perfkitbenchmarker/linux_packages/tensorflow.py
python
GetTensorFlowVersion
(vm)
return stdout.strip()
Returns the version of tensorflow installed on the vm. Args: vm: the target vm on which to check the tensorflow version Returns: installed python tensorflow version as a string
Returns the version of tensorflow installed on the vm.
[ "Returns", "the", "version", "of", "tensorflow", "installed", "on", "the", "vm", "." ]
def GetTensorFlowVersion(vm): """Returns the version of tensorflow installed on the vm. Args: vm: the target vm on which to check the tensorflow version Returns: installed python tensorflow version as a string """ stdout, _ = vm.RemoteCommand( ('echo -e "import tensorflow\nprint(tensorflow.__version__)" | {0} python' .format(GetEnvironmentVars(vm))) ) return stdout.strip()
[ "def", "GetTensorFlowVersion", "(", "vm", ")", ":", "stdout", ",", "_", "=", "vm", ".", "RemoteCommand", "(", "(", "'echo -e \"import tensorflow\\nprint(tensorflow.__version__)\" | {0} python'", ".", "format", "(", "GetEnvironmentVars", "(", "vm", ")", ")", ")", ")"...
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/6e3412d7d5e414b8ca30ed5eaf970cef1d919a67/perfkitbenchmarker/linux_packages/tensorflow.py#L71-L84
wmayner/pyphi
299fccd4a8152dcfa4bb989d7d739e245343b0a5
pyphi/models/actual_causation.py
python
CausalLink.phi
(self)
return self.alpha
Alias for |alpha| for PyPhi utility functions.
Alias for |alpha| for PyPhi utility functions.
[ "Alias", "for", "|alpha|", "for", "PyPhi", "utility", "functions", "." ]
def phi(self): """Alias for |alpha| for PyPhi utility functions.""" return self.alpha
[ "def", "phi", "(", "self", ")", ":", "return", "self", ".", "alpha" ]
https://github.com/wmayner/pyphi/blob/299fccd4a8152dcfa4bb989d7d739e245343b0a5/pyphi/models/actual_causation.py#L171-L173
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/modelcluster/utils.py
python
sort_by_fields
(items, fields)
Sort a list of objects on the given fields. The field list works analogously to queryset.order_by(*fields): each field is either a property of the object, or is prefixed by '-' (e.g. '-name') to indicate reverse ordering.
Sort a list of objects on the given fields. The field list works analogously to queryset.order_by(*fields): each field is either a property of the object, or is prefixed by '-' (e.g. '-name') to indicate reverse ordering.
[ "Sort", "a", "list", "of", "objects", "on", "the", "given", "fields", ".", "The", "field", "list", "works", "analogously", "to", "queryset", ".", "order_by", "(", "*", "fields", ")", ":", "each", "field", "is", "either", "a", "property", "of", "the", "...
def sort_by_fields(items, fields): """ Sort a list of objects on the given fields. The field list works analogously to queryset.order_by(*fields): each field is either a property of the object, or is prefixed by '-' (e.g. '-name') to indicate reverse ordering. """ # To get the desired behaviour, we need to order by keys in reverse order # See: https://docs.python.org/2/howto/sorting.html#sort-stability-and-complex-sorts for key in reversed(fields): # Check if this key has been reversed reverse = False if key[0] == '-': reverse = True key = key[1:] # Sort # Use a tuple of (v is not None, v) as the key, to ensure that None sorts before other values, # as comparing directly with None breaks on python3 items.sort(key=lambda x: (getattr(x, key) is not None, getattr(x, key)), reverse=reverse)
[ "def", "sort_by_fields", "(", "items", ",", "fields", ")", ":", "# To get the desired behaviour, we need to order by keys in reverse order", "# See: https://docs.python.org/2/howto/sorting.html#sort-stability-and-complex-sorts", "for", "key", "in", "reversed", "(", "fields", ")", "...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/modelcluster/utils.py#L1-L19
rucio/rucio
6d0d358e04f5431f0b9a98ae40f31af0ddff4833
lib/rucio/common/utils.py
python
sizefmt
(num, human=True)
Print human readable file sizes
Print human readable file sizes
[ "Print", "human", "readable", "file", "sizes" ]
def sizefmt(num, human=True): """ Print human readable file sizes """ if num is None: return '0.0 B' try: num = int(num) if human: for unit in ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z']: if abs(num) < 1000.0: return "%3.3f %sB" % (num, unit) num /= 1000.0 return "%.1f %sB" % (num, 'Y') else: return str(num) except OverflowError: return 'Inf'
[ "def", "sizefmt", "(", "num", ",", "human", "=", "True", ")", ":", "if", "num", "is", "None", ":", "return", "'0.0 B'", "try", ":", "num", "=", "int", "(", "num", ")", "if", "human", ":", "for", "unit", "in", "[", "''", ",", "'k'", ",", "'M'", ...
https://github.com/rucio/rucio/blob/6d0d358e04f5431f0b9a98ae40f31af0ddff4833/lib/rucio/common/utils.py#L864-L881
EasonLiao/CudaTree
fcd9c7f4dbac00c105bbfbff9f55db1d29747fc7
cudatree/base_tree.py
python
BaseTree.gpu_predict
(self, inputs, predict_kernel)
return predict_res_gpu.get()
[]
def gpu_predict(self, inputs, predict_kernel): def get_grid_size(n_samples): blocks_need = int(math.ceil(float(n_samples) / 16)) MAX_GRID = 65535 gy = 1 gx = MAX_GRID if gx >= blocks_need: gx = blocks_need else: gy = int(math.ceil(float(blocks_need) / gx)) return (gx, gy) n_predict = inputs.shape[0] predict_gpu = gpuarray.to_gpu(inputs) left_child_gpu = gpuarray.to_gpu(self.left_children) right_child_gpu = gpuarray.to_gpu(self.right_children) threshold_gpu = gpuarray.to_gpu(self.feature_threshold_array) value_gpu = gpuarray.to_gpu(self.values_array) feature_gpu = gpuarray.to_gpu(self.feature_idx_array) predict_res_gpu = gpuarray.zeros(n_predict, \ dtype=self.dtype_labels) grid = get_grid_size(n_predict) predict_kernel.prepared_call( grid, (512, 1, 1), left_child_gpu.ptr, right_child_gpu.ptr, feature_gpu.ptr, threshold_gpu.ptr, value_gpu.ptr, predict_gpu.ptr, predict_res_gpu.ptr, self.n_features, n_predict) return predict_res_gpu.get()
[ "def", "gpu_predict", "(", "self", ",", "inputs", ",", "predict_kernel", ")", ":", "def", "get_grid_size", "(", "n_samples", ")", ":", "blocks_need", "=", "int", "(", "math", ".", "ceil", "(", "float", "(", "n_samples", ")", "/", "16", ")", ")", "MAX_G...
https://github.com/EasonLiao/CudaTree/blob/fcd9c7f4dbac00c105bbfbff9f55db1d29747fc7/cudatree/base_tree.py#L44-L81
baidu/DuReader
43577e29435f5abcb7b02ce6a0019b3f42b1221d
MRQA2019-D-NET/server/bert_server/task_reader/mrqa.py
python
get_final_text
(pred_text, orig_text, do_lower_case, verbose)
return output_text
Project the tokenized prediction back to the original text.
Project the tokenized prediction back to the original text.
[ "Project", "the", "tokenized", "prediction", "back", "to", "the", "original", "text", "." ]
def get_final_text(pred_text, orig_text, do_lower_case, verbose): """Project the tokenized prediction back to the original text.""" # When we created the data, we kept track of the alignment between original # (whitespace tokenized) tokens and our WordPiece tokenized tokens. So # now `orig_text` contains the span of our original text corresponding to the # span that we predicted. # # However, `orig_text` may contain extra characters that we don't want in # our prediction. # # For example, let's say: # pred_text = steve smith # orig_text = Steve Smith's # # We don't want to return `orig_text` because it contains the extra "'s". # # We don't want to return `pred_text` because it's already been normalized # (the MRQA eval script also does punctuation stripping/lower casing but # our tokenizer does additional normalization like stripping accent # characters). # # What we really want to return is "Steve Smith". # # Therefore, we have to apply a semi-complicated alignment heruistic between # `pred_text` and `orig_text` to get a character-to-charcter alignment. This # can fail in certain cases in which case we just return `orig_text`. def _strip_spaces(text): ns_chars = [] ns_to_s_map = collections.OrderedDict() for (i, c) in enumerate(text): if c == " ": continue ns_to_s_map[len(ns_chars)] = i ns_chars.append(c) ns_text = "".join(ns_chars) return (ns_text, ns_to_s_map) # We first tokenize `orig_text`, strip whitespace from the result # and `pred_text`, and check if they are the same length. If they are # NOT the same length, the heuristic has failed. If they are the same # length, we assume the characters are one-to-one aligned. tokenizer = tokenization.BasicTokenizer(do_lower_case=do_lower_case) tok_text = " ".join(tokenizer.tokenize(orig_text)) start_position = tok_text.find(pred_text) if start_position == -1: if verbose: print("Unable to find text: '%s' in '%s'" % (pred_text, orig_text)) return orig_text end_position = start_position + len(pred_text) - 1 (orig_ns_text, orig_ns_to_s_map) = _strip_spaces(orig_text) (tok_ns_text, tok_ns_to_s_map) = _strip_spaces(tok_text) if len(orig_ns_text) != len(tok_ns_text): if verbose: print("Length not equal after stripping spaces: '%s' vs '%s'", orig_ns_text, tok_ns_text) return orig_text # We then project the characters in `pred_text` back to `orig_text` using # the character-to-character alignment. tok_s_to_ns_map = {} for (i, tok_index) in six.iteritems(tok_ns_to_s_map): tok_s_to_ns_map[tok_index] = i orig_start_position = None if start_position in tok_s_to_ns_map: ns_start_position = tok_s_to_ns_map[start_position] if ns_start_position in orig_ns_to_s_map: orig_start_position = orig_ns_to_s_map[ns_start_position] if orig_start_position is None: if verbose: print("Couldn't map start position") return orig_text orig_end_position = None if end_position in tok_s_to_ns_map: ns_end_position = tok_s_to_ns_map[end_position] if ns_end_position in orig_ns_to_s_map: orig_end_position = orig_ns_to_s_map[ns_end_position] if orig_end_position is None: if verbose: print("Couldn't map end position") return orig_text output_text = orig_text[orig_start_position:(orig_end_position + 1)] return output_text
[ "def", "get_final_text", "(", "pred_text", ",", "orig_text", ",", "do_lower_case", ",", "verbose", ")", ":", "# When we created the data, we kept track of the alignment between original", "# (whitespace tokenized) tokens and our WordPiece tokenized tokens. So", "# now `orig_text` contain...
https://github.com/baidu/DuReader/blob/43577e29435f5abcb7b02ce6a0019b3f42b1221d/MRQA2019-D-NET/server/bert_server/task_reader/mrqa.py#L805-L897
gramps-project/gramps
04d4651a43eb210192f40a9f8c2bad8ee8fa3753
gramps/gui/plug/report/_bookdialog.py
python
BookSelector.on_open_clicked
(self, obj)
Run the BookListDisplay dialog to present the choice of books to open.
Run the BookListDisplay dialog to present the choice of books to open.
[ "Run", "the", "BookListDisplay", "dialog", "to", "present", "the", "choice", "of", "books", "to", "open", "." ]
def on_open_clicked(self, obj): """ Run the BookListDisplay dialog to present the choice of books to open. """ booklistdisplay = BookListDisplay(self.book_list, nodelete=True, dosave=False, parent=self.window) booklistdisplay.top.destroy() book = booklistdisplay.selection if book: self.open_book(book) self.name_entry.set_text(book.get_name()) self.book.set_name(book.get_name())
[ "def", "on_open_clicked", "(", "self", ",", "obj", ")", ":", "booklistdisplay", "=", "BookListDisplay", "(", "self", ".", "book_list", ",", "nodelete", "=", "True", ",", "dosave", "=", "False", ",", "parent", "=", "self", ".", "window", ")", "booklistdispl...
https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/gui/plug/report/_bookdialog.py#L776-L787
deepset-ai/haystack
79fdda8a7cf393d774803608a4874f2a6e63cf6f
haystack/nodes/extractor/entity.py
python
EntityExtractor.extract
(self, text)
return entities
This function can be called to perform entity extraction when using the node in isolation.
This function can be called to perform entity extraction when using the node in isolation.
[ "This", "function", "can", "be", "called", "to", "perform", "entity", "extraction", "when", "using", "the", "node", "in", "isolation", "." ]
def extract(self, text): """ This function can be called to perform entity extraction when using the node in isolation. """ entities = self.model(text) return entities
[ "def", "extract", "(", "self", ",", "text", ")", ":", "entities", "=", "self", ".", "model", "(", "text", ")", "return", "entities" ]
https://github.com/deepset-ai/haystack/blob/79fdda8a7cf393d774803608a4874f2a6e63cf6f/haystack/nodes/extractor/entity.py#L50-L55
Chaffelson/nipyapi
d3b186fd701ce308c2812746d98af9120955e810
nipyapi/registry/api_client.py
python
ApiClient.__deserialize_object
(self, value)
return value
Return a original value. :return: object.
Return a original value.
[ "Return", "a", "original", "value", "." ]
def __deserialize_object(self, value): """ Return a original value. :return: object. """ return value
[ "def", "__deserialize_object", "(", "self", ",", "value", ")", ":", "return", "value" ]
https://github.com/Chaffelson/nipyapi/blob/d3b186fd701ce308c2812746d98af9120955e810/nipyapi/registry/api_client.py#L573-L579
napalm-automation/napalm
ad1ff72000d0de59f25c8847694f51a4ad5aca86
napalm/nxos/nxos.py
python
NXOSDriver.get_bgp_neighbors
(self)
return results
af_name_dict = { 'af-id': {'safi': "af-name"}, 'af-id': {'safi': "af-name"}, 'af-id': {'safi': "af-name"} }
af_name_dict = { 'af-id': {'safi': "af-name"}, 'af-id': {'safi': "af-name"}, 'af-id': {'safi': "af-name"} }
[ "af_name_dict", "=", "{", "af", "-", "id", ":", "{", "safi", ":", "af", "-", "name", "}", "af", "-", "id", ":", "{", "safi", ":", "af", "-", "name", "}", "af", "-", "id", ":", "{", "safi", ":", "af", "-", "name", "}", "}" ]
def get_bgp_neighbors(self): results = {} bgp_state_dict = { "Idle": {"is_up": False, "is_enabled": True}, "Active": {"is_up": False, "is_enabled": True}, "Open": {"is_up": False, "is_enabled": True}, "Established": {"is_up": True, "is_enabled": True}, "Closing": {"is_up": True, "is_enabled": True}, "Shutdown": {"is_up": False, "is_enabled": False}, } """ af_name_dict = { 'af-id': {'safi': "af-name"}, 'af-id': {'safi': "af-name"}, 'af-id': {'safi': "af-name"} } """ af_name_dict = { 1: {1: "ipv4", 128: "vpnv4"}, 2: {1: "ipv6", 128: "vpnv6"}, 25: {70: "l2vpn"}, } try: cmd = "show bgp all summary vrf all" vrf_list = self._get_command_table(cmd, "TABLE_vrf", "ROW_vrf") except NXAPICommandError: vrf_list = [] for vrf_dict in vrf_list: result_vrf_dict = {"router_id": str(vrf_dict["vrf-router-id"]), "peers": {}} af_list = vrf_dict.get("TABLE_af", {}).get("ROW_af", []) if isinstance(af_list, dict): af_list = [af_list] for af_dict in af_list: saf_dict = af_dict.get("TABLE_saf", {}).get("ROW_saf", {}) neighbors_list = saf_dict.get("TABLE_neighbor", {}).get( "ROW_neighbor", [] ) if isinstance(neighbors_list, dict): neighbors_list = [neighbors_list] for neighbor_dict in neighbors_list: neighborid = napalm.base.helpers.ip(neighbor_dict["neighborid"]) remoteas = as_number(neighbor_dict["neighboras"]) state = str(neighbor_dict["state"]) bgp_state = bgp_state_dict[state] afid_dict = af_name_dict[int(af_dict["af-id"])] safi_name = afid_dict[int(saf_dict["safi"])] result_peer_dict = { "local_as": as_number(vrf_dict["vrf-local-as"]), "remote_as": remoteas, "remote_id": neighborid, "is_enabled": bgp_state["is_enabled"], "uptime": -1, "description": "", "is_up": bgp_state["is_up"], "address_family": { safi_name: { "sent_prefixes": -1, "accepted_prefixes": -1, "received_prefixes": int( neighbor_dict["prefixreceived"] ), } }, } result_vrf_dict["peers"][neighborid] = result_peer_dict vrf_name = vrf_dict["vrf-name-out"] if vrf_name == "default": vrf_name = "global" results[vrf_name] = result_vrf_dict return results
[ "def", "get_bgp_neighbors", "(", "self", ")", ":", "results", "=", "{", "}", "bgp_state_dict", "=", "{", "\"Idle\"", ":", "{", "\"is_up\"", ":", "False", ",", "\"is_enabled\"", ":", "True", "}", ",", "\"Active\"", ":", "{", "\"is_up\"", ":", "False", ","...
https://github.com/napalm-automation/napalm/blob/ad1ff72000d0de59f25c8847694f51a4ad5aca86/napalm/nxos/nxos.py#L926-L1004
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_storageclass.py
python
Utils.exists
(results, _name)
return False
Check to see if the results include the name
Check to see if the results include the name
[ "Check", "to", "see", "if", "the", "results", "include", "the", "name" ]
def exists(results, _name): ''' Check to see if the results include the name ''' if not results: return False if Utils.find_result(results, _name): return True return False
[ "def", "exists", "(", "results", ",", "_name", ")", ":", "if", "not", "results", ":", "return", "False", "if", "Utils", ".", "find_result", "(", "results", ",", "_name", ")", ":", "return", "True", "return", "False" ]
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_storageclass.py#L1246-L1254
flow-project/flow
a511c41c48e6b928bb2060de8ad1ef3c3e3d9554
flow/core/kernel/vehicle/aimsun.py
python
AimsunKernelVehicle.get_human_ids
(self)
return self.__human_ids
See parent class.
See parent class.
[ "See", "parent", "class", "." ]
def get_human_ids(self): """See parent class.""" return self.__human_ids
[ "def", "get_human_ids", "(", "self", ")", ":", "return", "self", ".", "__human_ids" ]
https://github.com/flow-project/flow/blob/a511c41c48e6b928bb2060de8ad1ef3c3e3d9554/flow/core/kernel/vehicle/aimsun.py#L602-L604
biopython/biopython
2dd97e71762af7b046d7f7f8a4f1e38db6b06c86
Bio/Phylo/BaseTree.py
python
TreeMixin.prune
(self, target=None, **kwargs)
return parent
Prunes a terminal clade from the tree. If taxon is from a bifurcation, the connecting node will be collapsed and its branch length added to remaining terminal node. This might be no longer be a meaningful value. :returns: parent clade of the pruned target
Prunes a terminal clade from the tree.
[ "Prunes", "a", "terminal", "clade", "from", "the", "tree", "." ]
def prune(self, target=None, **kwargs): """Prunes a terminal clade from the tree. If taxon is from a bifurcation, the connecting node will be collapsed and its branch length added to remaining terminal node. This might be no longer be a meaningful value. :returns: parent clade of the pruned target """ if "terminal" in kwargs and kwargs["terminal"]: raise ValueError("target must be terminal") path = self.get_path(target, terminal=True, **kwargs) if not path: raise ValueError("can't find a matching target below this root") if len(path) == 1: parent = self.root else: parent = path[-2] parent.clades.remove(path[-1]) if len(parent) == 1: # We deleted a branch from a bifurcation if parent == self.root: # If we're at the root, move the root upwards # NB: This loses the length of the original branch newroot = parent.clades[0] newroot.branch_length = None parent = self.root = newroot else: # If we're not at the root, collapse this parent child = parent.clades[0] if child.branch_length is not None: child.branch_length += parent.branch_length or 0.0 if len(path) < 3: grandparent = self.root else: grandparent = path[-3] # Replace parent with child at the same place in grandparent index = grandparent.clades.index(parent) grandparent.clades.pop(index) grandparent.clades.insert(index, child) parent = grandparent return parent
[ "def", "prune", "(", "self", ",", "target", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "\"terminal\"", "in", "kwargs", "and", "kwargs", "[", "\"terminal\"", "]", ":", "raise", "ValueError", "(", "\"target must be terminal\"", ")", "path", "=", ...
https://github.com/biopython/biopython/blob/2dd97e71762af7b046d7f7f8a4f1e38db6b06c86/Bio/Phylo/BaseTree.py#L666-L708
Teradata/stacki
a8085dce179dbe903f65f136f4b63bcc076cc057
common/src/stack/command/stack/commands/__init__.py
python
Command.endOutput
(self, header=[], padChar='-', trimOwner=False, trimHeader=False)
Pretty prints the output list buffer.
Pretty prints the output list buffer.
[ "Pretty", "prints", "the", "output", "list", "buffer", "." ]
def endOutput(self, header=[], padChar='-', trimOwner=False, trimHeader=False): """ Pretty prints the output list buffer. """ # Handle the simple case of no output, and bail out # early. We do this to avoid printing out nothing # but a header w/o any rows. if not self.output: return # The OUTPUT-FORMAT option can change the default from # human readable text to something else. Currently # supports: # # json - text json # python - text python # binary - marshalled python # text - default (for humans) format = self._params.get('output-format') if not format: format = 'text' tokens = format.split(':') if len(tokens) == 1: format = tokens[0] format_args = None else: format = tokens[0] format_args = tokens[1].lower() if format in ['col', 'shell', 'json', 'python', 'binary']: if not header: # need to build a generic header if len(self.output) > 0: rows = len(self.output[0]) else: rows = 0 header = [] for i in range(0, rows): header.append('col-%d' % i) list = [] for line in self.output: dict = {} for i in range(0, len(header)): if header[i]: key = header[i] val = line[i] if key in dict: if not isinstance(dict[key], list): dict[key] = [dict[key]] dict[key].append(val) else: dict[key] = val list.append(dict) if format == 'col': for row in list: try: self.addText('%s\n' % row[format_args]) except KeyError: pass elif format == 'shell': rows = len(list) for i in range(0, rows): if rows > 1: n = '%d_' % i else: n = '' for k, v in list[i].items(): self.addText('stack_%s%s="%s"\n' % (n, k, v)) self.addText('\n') elif format == 'python': self.addText('%s' % list) elif format == 'binary': self.addText(marshal.dumps(list)) else: self.addText(json.dumps(list, indent=8)) return if format == 'null': return # By default always display the owner (col 0), but if # all lines have no owner set skip it. # # If trimOwner=True optimize the output to not display # the owner IFF all lines have the same owner. This # looks like grep output across multiple or single # files. if trimOwner: owner = '' startOfLine = 1 for line in self.output: if not owner: owner = line[0] if not owner == line[0]: startOfLine = 0 else: startOfLine = 1 for line in self.output: if line[0]: startOfLine = 0 # Add the header to the output and start formatting. We # keep the header optional and separate from the output # so the above decision (startOfLine) can be made. if header and not trimHeader: list = [] for field in header: if field: list.append(field.upper()) else: list.append('') output = [list] output.extend(self.output) else: output = self.output colwidth = [] for line in output: for i in range(0, len(line)): if len(colwidth) <= i: colwidth.append(0) if not isinstance(line[i], str): if line[i] is None: itemlen = 0 else: itemlen = len(repr(line[i])) else: itemlen = len(line[i]) if itemlen > colwidth[i]: colwidth[i] = itemlen # If we know the output is too long for the terminal # switch from table view to a field view that will # display nicer (e.g. stack list os boot). if self.width and header and startOfLine == 0 and (sum(colwidth) + len(line)) > self.width: maxWidth = 0 for label in output[0]: n = len(label) if n > maxWidth: maxWidth = n for line in output[1:]: for i in range(0, len(line)): if line[i] in [None, 'None']: s = '' else: s = str(line[i]) if s: self.addText('%s%s%s %s\n' % ( self.colors['bold']['code'], output[0][i].ljust(maxWidth), self.colors['reset']['code'], s)) self.addText('\n') return if header: isHeader = True else: isHeader = False o = '' for line in output: list = [] for i in range(startOfLine, len(line)): if line[i] in [None, 'None']: s = '' else: s = str(line[i]) # fill "cell" with padChar so it's as long # as the longest field/header. if padChar != '' and i != len(line) - 1: if s: o = s.ljust(colwidth[i]) else: o = ''.ljust(colwidth[i], padChar) # *BUT* if this is the last column, it might be super # long, so only pad it out as long as the header. elif padChar != '' and i == len(line) - 1 and not s: o = ''.ljust(len(output[0][i]), padChar) else: o = s if isHeader: o = '%s%s%s' % ( self.colors['bold']['code'], o, self.colors['reset']['code'] ) list.append(o) self.addText('%s\n' % ' '.join(list)) isHeader = False
[ "def", "endOutput", "(", "self", ",", "header", "=", "[", "]", ",", "padChar", "=", "'-'", ",", "trimOwner", "=", "False", ",", "trimHeader", "=", "False", ")", ":", "# Handle the simple case of no output, and bail out", "# early. We do this to avoid printing out not...
https://github.com/Teradata/stacki/blob/a8085dce179dbe903f65f136f4b63bcc076cc057/common/src/stack/command/stack/commands/__init__.py#L1372-L1581
antonylesuisse/qweb
2d6964a3e5cae90414c4f873eb770591f569dfe0
qweb_python/qweb/qweb.py
python
qweb_control
(self,jump='main',p=[])
return 1
qweb_control(self,jump='main',p=[]): A simple function to handle the controler part of your application. It dispatch the control to the jump argument, while ensuring that prefix function have been called. qweb_control replace '/' to '_' and strip '_' from the jump argument. name1 name1_name2 name1_name2_name3
qweb_control(self,jump='main',p=[]): A simple function to handle the controler part of your application. It dispatch the control to the jump argument, while ensuring that prefix function have been called.
[ "qweb_control", "(", "self", "jump", "=", "main", "p", "=", "[]", ")", ":", "A", "simple", "function", "to", "handle", "the", "controler", "part", "of", "your", "application", ".", "It", "dispatch", "the", "control", "to", "the", "jump", "argument", "whi...
def qweb_control(self,jump='main',p=[]): """ qweb_control(self,jump='main',p=[]): A simple function to handle the controler part of your application. It dispatch the control to the jump argument, while ensuring that prefix function have been called. qweb_control replace '/' to '_' and strip '_' from the jump argument. name1 name1_name2 name1_name2_name3 """ jump=jump.replace('/','_').strip('_') if not hasattr(self,jump): return 0 done={} todo=[] while 1: if jump!=None: tmp="" todo=[] for i in jump.split("_"): tmp+=i+"_"; if not done.has_key(tmp[:-1]): todo.append(tmp[:-1]) jump=None elif len(todo): i=todo.pop(0) done[i]=1 if hasattr(self,i): f=getattr(self,i) r=f(*p) if isinstance(r,types.StringType): jump=r else: break return 1
[ "def", "qweb_control", "(", "self", ",", "jump", "=", "'main'", ",", "p", "=", "[", "]", ")", ":", "jump", "=", "jump", ".", "replace", "(", "'/'", ",", "'_'", ")", ".", "strip", "(", "'_'", ")", "if", "not", "hasattr", "(", "self", ",", "jump"...
https://github.com/antonylesuisse/qweb/blob/2d6964a3e5cae90414c4f873eb770591f569dfe0/qweb_python/qweb/qweb.py#L729-L766
byt3bl33d3r/pth-toolkit
3641cdc76c0f52275315c9b18bf08b22521bd4d7
lib/python2.7/site-packages/samba/upgradehelpers.py
python
update_dns_account_password
(samdb, secrets_ldb, names)
Update (change) the password of the dns both in the SAM db and in secret one :param samdb: An LDB object related to the sam.ldb file of a given provision :param secrets_ldb: An LDB object related to the secrets.ldb file of a given provision :param names: List of key provision parameters
Update (change) the password of the dns both in the SAM db and in secret one
[ "Update", "(", "change", ")", "the", "password", "of", "the", "dns", "both", "in", "the", "SAM", "db", "and", "in", "secret", "one" ]
def update_dns_account_password(samdb, secrets_ldb, names): """Update (change) the password of the dns both in the SAM db and in secret one :param samdb: An LDB object related to the sam.ldb file of a given provision :param secrets_ldb: An LDB object related to the secrets.ldb file of a given provision :param names: List of key provision parameters""" expression = "samAccountName=dns-%s" % names.netbiosname secrets_msg = secrets_ldb.search(expression=expression) if len(secrets_msg) == 1: res = samdb.search(expression=expression, attrs=[]) assert(len(res) == 1) msg = ldb.Message(res[0].dn) machinepass = samba.generate_random_password(128, 255) mputf16 = machinepass.encode('utf-16-le') msg["clearTextPassword"] = ldb.MessageElement(mputf16, ldb.FLAG_MOD_REPLACE, "clearTextPassword") samdb.modify(msg) res = samdb.search(expression=expression, attrs=["msDs-keyVersionNumber"]) assert(len(res) == 1) kvno = str(res[0]["msDs-keyVersionNumber"]) msg = ldb.Message(secrets_msg[0].dn) msg["secret"] = ldb.MessageElement(machinepass, ldb.FLAG_MOD_REPLACE, "secret") msg["msDS-KeyVersionNumber"] = ldb.MessageElement(kvno, ldb.FLAG_MOD_REPLACE, "msDS-KeyVersionNumber") secrets_ldb.modify(msg)
[ "def", "update_dns_account_password", "(", "samdb", ",", "secrets_ldb", ",", "names", ")", ":", "expression", "=", "\"samAccountName=dns-%s\"", "%", "names", ".", "netbiosname", "secrets_msg", "=", "secrets_ldb", ".", "search", "(", "expression", "=", "expression", ...
https://github.com/byt3bl33d3r/pth-toolkit/blob/3641cdc76c0f52275315c9b18bf08b22521bd4d7/lib/python2.7/site-packages/samba/upgradehelpers.py#L762-L799
pygments/pygments
cd3ad20dfc8a6cb43e2c0b22b14446dcc0a554d7
pygments/lexers/robotframework.py
python
TestCaseTable._tokenize
(self, value, index)
return _Table._tokenize(self, value, index)
[]
def _tokenize(self, value, index): if index == 0: if value: self._test_template = None return GherkinTokenizer().tokenize(value, TC_KW_NAME) if index == 1 and self._is_setting(value): if self._is_template(value): self._test_template = False self._tokenizer = self._setting_class(self.set_test_template) else: self._tokenizer = self._setting_class() if index == 1 and self._is_for_loop(value): self._tokenizer = ForLoop() if index == 1 and self._is_empty(value): return [(value, SYNTAX)] return _Table._tokenize(self, value, index)
[ "def", "_tokenize", "(", "self", ",", "value", ",", "index", ")", ":", "if", "index", "==", "0", ":", "if", "value", ":", "self", ".", "_test_template", "=", "None", "return", "GherkinTokenizer", "(", ")", ".", "tokenize", "(", "value", ",", "TC_KW_NAM...
https://github.com/pygments/pygments/blob/cd3ad20dfc8a6cb43e2c0b22b14446dcc0a554d7/pygments/lexers/robotframework.py#L387-L402
replit-archive/empythoned
977ec10ced29a3541a4973dc2b59910805695752
cpython/Lib/lib-tk/Tkinter.py
python
Listbox.scan_dragto
(self, x, y)
Adjust the view of the listbox to 10 times the difference between X and Y and the coordinates given in scan_mark.
Adjust the view of the listbox to 10 times the difference between X and Y and the coordinates given in scan_mark.
[ "Adjust", "the", "view", "of", "the", "listbox", "to", "10", "times", "the", "difference", "between", "X", "and", "Y", "and", "the", "coordinates", "given", "in", "scan_mark", "." ]
def scan_dragto(self, x, y): """Adjust the view of the listbox to 10 times the difference between X and Y and the coordinates given in scan_mark.""" self.tk.call(self._w, 'scan', 'dragto', x, y)
[ "def", "scan_dragto", "(", "self", ",", "x", ",", "y", ")", ":", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "'scan'", ",", "'dragto'", ",", "x", ",", "y", ")" ]
https://github.com/replit-archive/empythoned/blob/977ec10ced29a3541a4973dc2b59910805695752/cpython/Lib/lib-tk/Tkinter.py#L2526-L2530
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/setuptools/command/sdist.py
python
sdist.read_manifest
(self)
Read the manifest file (named by 'self.manifest') and use it to fill in 'self.filelist', the list of files to include in the source distribution.
Read the manifest file (named by 'self.manifest') and use it to fill in 'self.filelist', the list of files to include in the source distribution.
[ "Read", "the", "manifest", "file", "(", "named", "by", "self", ".", "manifest", ")", "and", "use", "it", "to", "fill", "in", "self", ".", "filelist", "the", "list", "of", "files", "to", "include", "in", "the", "source", "distribution", "." ]
def read_manifest(self): """Read the manifest file (named by 'self.manifest') and use it to fill in 'self.filelist', the list of files to include in the source distribution. """ log.info("reading manifest file '%s'", self.manifest) manifest = open(self.manifest, 'rb') for line in manifest: # The manifest must contain UTF-8. See #303. if six.PY3: try: line = line.decode('UTF-8') except UnicodeDecodeError: log.warn("%r not UTF-8 decodable -- skipping" % line) continue # ignore comments and blank lines line = line.strip() if line.startswith('#') or not line: continue self.filelist.append(line) manifest.close()
[ "def", "read_manifest", "(", "self", ")", ":", "log", ".", "info", "(", "\"reading manifest file '%s'\"", ",", "self", ".", "manifest", ")", "manifest", "=", "open", "(", "self", ".", "manifest", ",", "'rb'", ")", "for", "line", "in", "manifest", ":", "#...
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/setuptools/command/sdist.py#L182-L202
lazylibrarian/LazyLibrarian
ae3c14e9db9328ce81765e094ab2a14ed7155624
lib/zipfile.py
python
ZipFile.__del__
(self)
Call the "close()" method in case the user forgot.
Call the "close()" method in case the user forgot.
[ "Call", "the", "close", "()", "method", "in", "case", "the", "user", "forgot", "." ]
def __del__(self): """Call the "close()" method in case the user forgot.""" self.close()
[ "def", "__del__", "(", "self", ")", ":", "self", ".", "close", "(", ")" ]
https://github.com/lazylibrarian/LazyLibrarian/blob/ae3c14e9db9328ce81765e094ab2a14ed7155624/lib/zipfile.py#L1257-L1259
jamiecaesar/securecrt-tools
f3cbb49223a485fc9af86e9799b5c940f19e8027
s_AireOS_collect_wlan_detail.py
python
get_wlan_detail
(session, to_cvs=False)
return output
A function that captures the WLC AireOS wlan & remote-lan & guest-lan details and returns an output list :param session: The script object that represents this script being executed :type session: session.Session :return: A list of wlan details :rtype: list of lists
A function that captures the WLC AireOS wlan & remote-lan & guest-lan details and returns an output list
[ "A", "function", "that", "captures", "the", "WLC", "AireOS", "wlan", "&", "remote", "-", "lan", "&", "guest", "-", "lan", "details", "and", "returns", "an", "output", "list" ]
def get_wlan_detail(session, to_cvs=False): """ A function that captures the WLC AireOS wlan & remote-lan & guest-lan details and returns an output list :param session: The script object that represents this script being executed :type session: session.Session :return: A list of wlan details :rtype: list of lists """ # Get the show wlan summary send_cmd = "show wlan summary" raw_wlan_summary = session.get_command_output(send_cmd) # Get the show remote-lan summary send_cmd = "show remote-lan summary" raw_rlan_summary = session.get_command_output(send_cmd) # Get the show guest-lan summary send_cmd = "show guest-lan summary" raw_glan_summary = session.get_command_output(send_cmd) template_file = session.script.get_template("cisco_aireos_show_wlan_summary.template") wlan_summary_dict = utilities.textfsm_parse_to_dict(raw_wlan_summary, template_file) rlan_summary_dict = utilities.textfsm_parse_to_dict(raw_rlan_summary, template_file) glan_summary_dict = utilities.textfsm_parse_to_dict(raw_glan_summary, template_file) output_raw = '' output_list = [] for wlan_entry in wlan_summary_dict: send_cmd = "show wlan " + format(wlan_entry["WLAN_Identifier"]) output_list.append(session.get_command_output(send_cmd)) raw_rlan_detail = '' for wlan_entry in rlan_summary_dict: send_cmd = "show remote-lan " + format(wlan_entry["WLAN_Identifier"]) output_list.append(session.get_command_output(send_cmd)) raw_glan_detail = '' for wlan_entry in glan_summary_dict: send_cmd = "show guest-lan " + format(wlan_entry["WLAN_Identifier"]) output_list.append(session.get_command_output(send_cmd)) output = [] first = True for output_raw in output_list: # TextFSM template for parsing "show wlan <WLAN-ID>" output template_file = session.script.get_template("cisco_aireos_show_wlan_detail.template") if first: output = utilities.textfsm_parse_to_list(output_raw, template_file, add_header=True) first = False else: output.append(utilities.textfsm_parse_to_list(output_raw, template_file, add_header=False)[0]) if to_cvs: output_filename = session.create_output_filename("wlan-detail", ext=".csv") utilities.list_of_lists_to_csv(output, output_filename) return output
[ "def", "get_wlan_detail", "(", "session", ",", "to_cvs", "=", "False", ")", ":", "# Get the show wlan summary", "send_cmd", "=", "\"show wlan summary\"", "raw_wlan_summary", "=", "session", ".", "get_command_output", "(", "send_cmd", ")", "# Get the show remote-lan summar...
https://github.com/jamiecaesar/securecrt-tools/blob/f3cbb49223a485fc9af86e9799b5c940f19e8027/s_AireOS_collect_wlan_detail.py#L57-L114
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/jinja2/compiler.py
python
CodeGenerator.visit_Filter
(self, node, frame)
[]
def visit_Filter(self, node, frame): if self.environment.is_async: self.write('await auto_await(') self.write(self.filters[node.name] + '(') func = self.environment.filters.get(node.name) if func is None: self.fail('no filter named %r' % node.name, node.lineno) if getattr(func, 'contextfilter', False): self.write('context, ') elif getattr(func, 'evalcontextfilter', False): self.write('context.eval_ctx, ') elif getattr(func, 'environmentfilter', False): self.write('environment, ') # if the filter node is None we are inside a filter block # and want to write to the current buffer if node.node is not None: self.visit(node.node, frame) elif frame.eval_ctx.volatile: self.write('(context.eval_ctx.autoescape and' ' Markup(concat(%s)) or concat(%s))' % (frame.buffer, frame.buffer)) elif frame.eval_ctx.autoescape: self.write('Markup(concat(%s))' % frame.buffer) else: self.write('concat(%s)' % frame.buffer) self.signature(node, frame) self.write(')') if self.environment.is_async: self.write(')')
[ "def", "visit_Filter", "(", "self", ",", "node", ",", "frame", ")", ":", "if", "self", ".", "environment", ".", "is_async", ":", "self", ".", "write", "(", "'await auto_await('", ")", "self", ".", "write", "(", "self", ".", "filters", "[", "node", ".",...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/jinja2/compiler.py#L1572-L1601
paylogic/py2deb
28e671231c2dcf7dc7b4963ed75d8cbe4a8778e9
py2deb/utils.py
python
embed_install_prefix
(handle, install_prefix)
return handle
Embed Python snippet that adds custom installation prefix to module search path. :param handle: A file-like object containing an executable Python script. :param install_prefix: The pathname of the custom installation prefix (a string). :returns: A file-like object containing the modified Python script.
Embed Python snippet that adds custom installation prefix to module search path.
[ "Embed", "Python", "snippet", "that", "adds", "custom", "installation", "prefix", "to", "module", "search", "path", "." ]
def embed_install_prefix(handle, install_prefix): """ Embed Python snippet that adds custom installation prefix to module search path. :param handle: A file-like object containing an executable Python script. :param install_prefix: The pathname of the custom installation prefix (a string). :returns: A file-like object containing the modified Python script. """ # Make sure the first line of the file contains something that looks like a # Python hashbang so we don't try to embed Python code in files like shell # scripts :-). if detect_python_script(handle): lines = handle.readlines() # We need to choose where to inject our line into the Python script. # This is trickier than it might seem at first, because of conflicting # concerns: # # 1) We want our line to be the first one to be executed so that any # later imports respect the custom installation prefix. # # 2) Our line cannot be the very first line because we would break the # hashbang of the script, without which it won't be executable. # # 3) Python has the somewhat obscure `from __future__ import ...' # statement which must precede all other statements. # # Our first step is to skip all comments, taking care of point two. insertion_point = 0 while insertion_point < len(lines) and lines[insertion_point].startswith(b'#'): insertion_point += 1 # The next step is to bump the insertion point if we find any `from # __future__ import ...' statements. for i, line in enumerate(lines): if re.match(b'^\\s*from\\s+__future__\\s+import\\s+', line): insertion_point = i + 1 lines.insert(insertion_point, ('import sys; sys.path.insert(0, %r)\n' % install_prefix).encode('UTF-8')) # Turn the modified contents back into a file-like object. handle = BytesIO(b''.join(lines)) else: # Reset the file pointer of handle, so its contents can be read again later. handle.seek(0) return handle
[ "def", "embed_install_prefix", "(", "handle", ",", "install_prefix", ")", ":", "# Make sure the first line of the file contains something that looks like a", "# Python hashbang so we don't try to embed Python code in files like shell", "# scripts :-).", "if", "detect_python_script", "(", ...
https://github.com/paylogic/py2deb/blob/28e671231c2dcf7dc7b4963ed75d8cbe4a8778e9/py2deb/utils.py#L265-L306
deschler/django-modeltranslation
391e2b33b86e935a9000f65e75a9a96f3af98e81
modeltranslation/utils.py
python
build_css_class
(localized_fieldname, prefix='')
return '%s-%s' % (prefix, css_class) if prefix else css_class
Returns a css class based on ``localized_fieldname`` which is easily splittable and capable of regionalized language codes. Takes an optional ``prefix`` which is prepended to the returned string.
Returns a css class based on ``localized_fieldname`` which is easily splittable and capable of regionalized language codes.
[ "Returns", "a", "css", "class", "based", "on", "localized_fieldname", "which", "is", "easily", "splittable", "and", "capable", "of", "regionalized", "language", "codes", "." ]
def build_css_class(localized_fieldname, prefix=''): """ Returns a css class based on ``localized_fieldname`` which is easily splittable and capable of regionalized language codes. Takes an optional ``prefix`` which is prepended to the returned string. """ bits = localized_fieldname.split('_') css_class = '' if len(bits) == 1: css_class = str(localized_fieldname) elif len(bits) == 2: # Fieldname without underscore and short language code # Examples: # 'foo_de' --> 'foo-de', # 'bar_en' --> 'bar-en' css_class = '-'.join(bits) elif len(bits) > 2: # Try regionalized language code # Examples: # 'foo_es_ar' --> 'foo-es_ar', # 'foo_bar_zh_tw' --> 'foo_bar-zh_tw' css_class = _join_css_class(bits, 2) if not css_class: # Try short language code # Examples: # 'foo_bar_de' --> 'foo_bar-de', # 'foo_bar_baz_de' --> 'foo_bar_baz-de' css_class = _join_css_class(bits, 1) return '%s-%s' % (prefix, css_class) if prefix else css_class
[ "def", "build_css_class", "(", "localized_fieldname", ",", "prefix", "=", "''", ")", ":", "bits", "=", "localized_fieldname", ".", "split", "(", "'_'", ")", "css_class", "=", "''", "if", "len", "(", "bits", ")", "==", "1", ":", "css_class", "=", "str", ...
https://github.com/deschler/django-modeltranslation/blob/391e2b33b86e935a9000f65e75a9a96f3af98e81/modeltranslation/utils.py#L66-L95
kuri65536/python-for-android
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
python-modules/twisted/twisted/internet/protocol.py
python
ProcessProtocol.outConnectionLost
(self)
This will be called when stdout is closed.
This will be called when stdout is closed.
[ "This", "will", "be", "called", "when", "stdout", "is", "closed", "." ]
def outConnectionLost(self): """ This will be called when stdout is closed. """
[ "def", "outConnectionLost", "(", "self", ")", ":" ]
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python-modules/twisted/twisted/internet/protocol.py#L578-L581
ldx/python-iptables
542efdb739b4e3ef6f28274d23b506bf0027eec2
iptc/ip6tc.py
python
Table6._init
(self, name, autocommit)
Here *name* is the name of the table to instantiate, if it has already been instantiated the existing cached object is returned. *Autocommit* specifies that any low-level iptables operation should be committed immediately, making changes visible in the kernel.
Here *name* is the name of the table to instantiate, if it has already been instantiated the existing cached object is returned. *Autocommit* specifies that any low-level iptables operation should be committed immediately, making changes visible in the kernel.
[ "Here", "*", "name", "*", "is", "the", "name", "of", "the", "table", "to", "instantiate", "if", "it", "has", "already", "been", "instantiated", "the", "existing", "cached", "object", "is", "returned", ".", "*", "Autocommit", "*", "specifies", "that", "any"...
def _init(self, name, autocommit): """ Here *name* is the name of the table to instantiate, if it has already been instantiated the existing cached object is returned. *Autocommit* specifies that any low-level iptables operation should be committed immediately, making changes visible in the kernel. """ self._iptc = ip6tc() # to keep references to functions self._handle = None self.name = name self.autocommit = autocommit self.refresh()
[ "def", "_init", "(", "self", ",", "name", ",", "autocommit", ")", ":", "self", ".", "_iptc", "=", "ip6tc", "(", ")", "# to keep references to functions", "self", ".", "_handle", "=", "None", "self", ".", "name", "=", "name", "self", ".", "autocommit", "=...
https://github.com/ldx/python-iptables/blob/542efdb739b4e3ef6f28274d23b506bf0027eec2/iptc/ip6tc.py#L595-L606
samuelclay/NewsBlur
2c45209df01a1566ea105e04d499367f32ac9ad2
apps/reader/views.py
python
mark_social_stories_as_read
(request)
return data
[]
def mark_social_stories_as_read(request): code = 1 errors = [] data = {} r = redis.Redis(connection_pool=settings.REDIS_PUBSUB_POOL) users_feeds_stories = request.POST.get('users_feeds_stories', "{}") users_feeds_stories = json.decode(users_feeds_stories) for social_user_id, feeds in list(users_feeds_stories.items()): for feed_id, story_ids in list(feeds.items()): feed_id = int(feed_id) try: socialsub = MSocialSubscription.objects.get(user_id=request.user.pk, subscription_user_id=social_user_id) data = socialsub.mark_story_ids_as_read(story_ids, feed_id, request=request) except OperationError as e: code = -1 errors.append("Already read story: %s" % e) except MSocialSubscription.DoesNotExist: MSocialSubscription.mark_unsub_story_ids_as_read(request.user.pk, social_user_id, story_ids, feed_id, request=request) except Feed.DoesNotExist: duplicate_feed = DuplicateFeed.objects.filter(duplicate_feed_id=feed_id) if duplicate_feed: try: socialsub = MSocialSubscription.objects.get(user_id=request.user.pk, subscription_user_id=social_user_id) data = socialsub.mark_story_ids_as_read(story_ids, duplicate_feed[0].feed.pk, request=request) except (UserSubscription.DoesNotExist, Feed.DoesNotExist): code = -1 errors.append("No feed exists for feed_id %d." % feed_id) else: continue r.publish(request.user.username, 'feed:%s' % feed_id) r.publish(request.user.username, 'social:%s' % social_user_id) data.update(code=code, errors=errors) return data
[ "def", "mark_social_stories_as_read", "(", "request", ")", ":", "code", "=", "1", "errors", "=", "[", "]", "data", "=", "{", "}", "r", "=", "redis", ".", "Redis", "(", "connection_pool", "=", "settings", ".", "REDIS_PUBSUB_POOL", ")", "users_feeds_stories", ...
https://github.com/samuelclay/NewsBlur/blob/2c45209df01a1566ea105e04d499367f32ac9ad2/apps/reader/views.py#L1827-L1865
mysql/mysql-utilities
08276b2258bf9739f53406b354b21195ff69a261
mysql/utilities/common/options_parser.py
python
MySQLOptionsParser.get_groups_as_dict
(self, *args)
return options
Returns options as dictionary of dictionaries. Returns options from all the groups specified as arguments. For each group the option are contained in a dictionary. The order in which the groups are specified is unimportant. Also options are not overridden in between the groups. *args[in] Each group to be returned can be requested by providing its name as an argument. Returns an dictionary of dictionaries
Returns options as dictionary of dictionaries.
[ "Returns", "options", "as", "dictionary", "of", "dictionaries", "." ]
def get_groups_as_dict(self, *args): """Returns options as dictionary of dictionaries. Returns options from all the groups specified as arguments. For each group the option are contained in a dictionary. The order in which the groups are specified is unimportant. Also options are not overridden in between the groups. *args[in] Each group to be returned can be requested by providing its name as an argument. Returns an dictionary of dictionaries """ if len(args) == 0: args = self._options_dict.keys() options = dict() for group in args: try: options[group] = dict(self._options_dict[group]) except KeyError: pass for group in options.keys(): for key in options[group].keys(): if key == '__name__' or key.startswith('!'): del options[group][key] else: options[group][key] = options[group][key][0] return options
[ "def", "get_groups_as_dict", "(", "self", ",", "*", "args", ")", ":", "if", "len", "(", "args", ")", "==", "0", ":", "args", "=", "self", ".", "_options_dict", ".", "keys", "(", ")", "options", "=", "dict", "(", ")", "for", "group", "in", "args", ...
https://github.com/mysql/mysql-utilities/blob/08276b2258bf9739f53406b354b21195ff69a261/mysql/utilities/common/options_parser.py#L269-L298
demisto/content
5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07
Packs/GoogleCloudCompute/Integrations/GoogleCloudCompute/GoogleCloudCompute.py
python
set_snapshot_labels
(args)
parameter: (dict) labels A list of labels to apply for this resource. parameter: (number) labelFingerprint The fingerprint of the previous set of labels for this resource, used to detect conflicts. parameter: (string) name Name or ID of the resource for this request.
parameter: (dict) labels A list of labels to apply for this resource. parameter: (number) labelFingerprint The fingerprint of the previous set of labels for this resource, used to detect conflicts. parameter: (string) name Name or ID of the resource for this request.
[ "parameter", ":", "(", "dict", ")", "labels", "A", "list", "of", "labels", "to", "apply", "for", "this", "resource", ".", "parameter", ":", "(", "number", ")", "labelFingerprint", "The", "fingerprint", "of", "the", "previous", "set", "of", "labels", "for",...
def set_snapshot_labels(args): """" parameter: (dict) labels A list of labels to apply for this resource. parameter: (number) labelFingerprint The fingerprint of the previous set of labels for this resource, used to detect conflicts. parameter: (string) name Name or ID of the resource for this request. """ project = SERVICE_ACT_PROJECT_ID name = args.get('name') labels = args.get('labels') labels = parse_labels(labels) body = {'labels': labels} if args.get('labelFingerprint'): body.update({'labelFingerprint': args.get('labelFingerprint')}) request = get_compute().snapshots().setLabels(project=project, resource=name, body=body) response = request.execute() data_res = { 'status': response.get('status'), 'kind': response.get('kind'), 'name': response.get('name'), 'id': response.get('id'), 'progress': response.get('progress'), 'operationType': response.get('operationType') } ec = {'GoogleCloudCompute.Operations(val.id === obj.id)': response} return_outputs( tableToMarkdown('Google Cloud Compute Operations', data_res, removeNull=True), ec, response )
[ "def", "set_snapshot_labels", "(", "args", ")", ":", "project", "=", "SERVICE_ACT_PROJECT_ID", "name", "=", "args", ".", "get", "(", "'name'", ")", "labels", "=", "args", ".", "get", "(", "'labels'", ")", "labels", "=", "parse_labels", "(", "labels", ")", ...
https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/GoogleCloudCompute/Integrations/GoogleCloudCompute/GoogleCloudCompute.py#L4289-L4325
collinsctk/PyQYT
7af3673955f94ff1b2df2f94220cd2dab2e252af
ExtentionPackages/scapy/utils6.py
python
in6_6to4ExtractAddr
(addr)
return inet_ntop(socket.AF_INET, addr[2:6])
Extract IPv4 address embbeded in 6to4 address. Passed address must be a 6to4 addrees. None is returned on error.
Extract IPv4 address embbeded in 6to4 address. Passed address must be a 6to4 addrees. None is returned on error.
[ "Extract", "IPv4", "address", "embbeded", "in", "6to4", "address", ".", "Passed", "address", "must", "be", "a", "6to4", "addrees", ".", "None", "is", "returned", "on", "error", "." ]
def in6_6to4ExtractAddr(addr): """ Extract IPv4 address embbeded in 6to4 address. Passed address must be a 6to4 addrees. None is returned on error. """ try: addr = inet_pton(socket.AF_INET6, addr) except: return None if addr[:2] != b" \x02": return None return inet_ntop(socket.AF_INET, addr[2:6])
[ "def", "in6_6to4ExtractAddr", "(", "addr", ")", ":", "try", ":", "addr", "=", "inet_pton", "(", "socket", ".", "AF_INET6", ",", "addr", ")", "except", ":", "return", "None", "if", "addr", "[", ":", "2", "]", "!=", "b\" \\x02\"", ":", "return", "None", ...
https://github.com/collinsctk/PyQYT/blob/7af3673955f94ff1b2df2f94220cd2dab2e252af/ExtentionPackages/scapy/utils6.py#L386-L397
stopstalk/stopstalk-deployment
10c3ab44c4ece33ae515f6888c15033db2004bb1
aws_lambda/spoj_aws_lambda_function/lambda_code/pip/_vendor/chardet/cli/chardetect.py
python
description_of
(lines, name='stdin')
Return a string describing the probable encoding of a file or list of strings. :param lines: The lines to get the encoding of. :type lines: Iterable of bytes :param name: Name of file or collection of lines :type name: str
Return a string describing the probable encoding of a file or list of strings.
[ "Return", "a", "string", "describing", "the", "probable", "encoding", "of", "a", "file", "or", "list", "of", "strings", "." ]
def description_of(lines, name='stdin'): """ Return a string describing the probable encoding of a file or list of strings. :param lines: The lines to get the encoding of. :type lines: Iterable of bytes :param name: Name of file or collection of lines :type name: str """ u = UniversalDetector() for line in lines: line = bytearray(line) u.feed(line) # shortcut out of the loop to save reading further - particularly useful if we read a BOM. if u.done: break u.close() result = u.result if PY2: name = name.decode(sys.getfilesystemencoding(), 'ignore') if result['encoding']: return '{0}: {1} with confidence {2}'.format(name, result['encoding'], result['confidence']) else: return '{0}: no result'.format(name)
[ "def", "description_of", "(", "lines", ",", "name", "=", "'stdin'", ")", ":", "u", "=", "UniversalDetector", "(", ")", "for", "line", "in", "lines", ":", "line", "=", "bytearray", "(", "line", ")", "u", ".", "feed", "(", "line", ")", "# shortcut out of...
https://github.com/stopstalk/stopstalk-deployment/blob/10c3ab44c4ece33ae515f6888c15033db2004bb1/aws_lambda/spoj_aws_lambda_function/lambda_code/pip/_vendor/chardet/cli/chardetect.py#L26-L51
graalvm/mx
29c0debab406352df3af246be2f8973be5db69ae
mx.py
python
TimeStampFile.exists
(self)
return exists(self.path)
[]
def exists(self): return exists(self.path)
[ "def", "exists", "(", "self", ")", ":", "return", "exists", "(", "self", ".", "path", ")" ]
https://github.com/graalvm/mx/blob/29c0debab406352df3af246be2f8973be5db69ae/mx.py#L15428-L15429
shiweibsw/Translation-Tools
2fbbf902364e557fa7017f9a74a8797b7440c077
venv/Lib/site-packages/pip-9.0.3-py3.6.egg/pip/_vendor/appdirs.py
python
_get_win_folder_with_pywin32
(csidl_name)
return dir
[]
def _get_win_folder_with_pywin32(csidl_name): from win32com.shell import shellcon, shell dir = shell.SHGetFolderPath(0, getattr(shellcon, csidl_name), 0, 0) # Try to make this a unicode path because SHGetFolderPath does # not return unicode strings when there is unicode data in the # path. try: dir = unicode(dir) # Downgrade to short path name if have highbit chars. See # <http://bugs.activestate.com/show_bug.cgi?id=85099>. has_high_char = False for c in dir: if ord(c) > 255: has_high_char = True break if has_high_char: try: import win32api dir = win32api.GetShortPathName(dir) except ImportError: pass except UnicodeError: pass return dir
[ "def", "_get_win_folder_with_pywin32", "(", "csidl_name", ")", ":", "from", "win32com", ".", "shell", "import", "shellcon", ",", "shell", "dir", "=", "shell", ".", "SHGetFolderPath", "(", "0", ",", "getattr", "(", "shellcon", ",", "csidl_name", ")", ",", "0"...
https://github.com/shiweibsw/Translation-Tools/blob/2fbbf902364e557fa7017f9a74a8797b7440c077/venv/Lib/site-packages/pip-9.0.3-py3.6.egg/pip/_vendor/appdirs.py#L429-L453
eirannejad/pyRevit
49c0b7eb54eb343458ce1365425e6552d0c47d44
site-packages/sqlalchemy/sql/base.py
python
DialectKWArgs.dialect_options
(self)
return util.PopulateDict( util.portable_instancemethod(self._kw_reg_for_dialect_cls) )
A collection of keyword arguments specified as dialect-specific options to this construct. This is a two-level nested registry, keyed to ``<dialect_name>`` and ``<argument_name>``. For example, the ``postgresql_where`` argument would be locatable as:: arg = my_object.dialect_options['postgresql']['where'] .. versionadded:: 0.9.2 .. seealso:: :attr:`.DialectKWArgs.dialect_kwargs` - flat dictionary form
A collection of keyword arguments specified as dialect-specific options to this construct.
[ "A", "collection", "of", "keyword", "arguments", "specified", "as", "dialect", "-", "specific", "options", "to", "this", "construct", "." ]
def dialect_options(self): """A collection of keyword arguments specified as dialect-specific options to this construct. This is a two-level nested registry, keyed to ``<dialect_name>`` and ``<argument_name>``. For example, the ``postgresql_where`` argument would be locatable as:: arg = my_object.dialect_options['postgresql']['where'] .. versionadded:: 0.9.2 .. seealso:: :attr:`.DialectKWArgs.dialect_kwargs` - flat dictionary form """ return util.PopulateDict( util.portable_instancemethod(self._kw_reg_for_dialect_cls) )
[ "def", "dialect_options", "(", "self", ")", ":", "return", "util", ".", "PopulateDict", "(", "util", ".", "portable_instancemethod", "(", "self", ".", "_kw_reg_for_dialect_cls", ")", ")" ]
https://github.com/eirannejad/pyRevit/blob/49c0b7eb54eb343458ce1365425e6552d0c47d44/site-packages/sqlalchemy/sql/base.py#L249-L269
yuanxiaosc/Schema-based-Knowledge-Extraction
ac0f07cd1088f24cb8f76c271fd2b49ea6100ca8
bert/modeling.py
python
create_attention_mask_from_input_mask
(from_tensor, to_mask)
return mask
Create 3D attention mask from a 2D tensor mask. Args: from_tensor: 2D or 3D Tensor of shape [batch_size, from_seq_length, ...]. to_mask: int32 Tensor of shape [batch_size, to_seq_length]. Returns: float Tensor of shape [batch_size, from_seq_length, to_seq_length].
Create 3D attention mask from a 2D tensor mask.
[ "Create", "3D", "attention", "mask", "from", "a", "2D", "tensor", "mask", "." ]
def create_attention_mask_from_input_mask(from_tensor, to_mask): """Create 3D attention mask from a 2D tensor mask. Args: from_tensor: 2D or 3D Tensor of shape [batch_size, from_seq_length, ...]. to_mask: int32 Tensor of shape [batch_size, to_seq_length]. Returns: float Tensor of shape [batch_size, from_seq_length, to_seq_length]. """ from_shape = get_shape_list(from_tensor, expected_rank=[2, 3]) batch_size = from_shape[0] from_seq_length = from_shape[1] to_shape = get_shape_list(to_mask, expected_rank=2) to_seq_length = to_shape[1] to_mask = tf.cast( tf.reshape(to_mask, [batch_size, 1, to_seq_length]), tf.float32) # We don't assume that `from_tensor` is a mask (although it could be). We # don't actually care if we attend *from* padding tokens (only *to* padding) # tokens so we create a tensor of all ones. # # `broadcast_ones` = [batch_size, from_seq_length, 1] broadcast_ones = tf.ones( shape=[batch_size, from_seq_length, 1], dtype=tf.float32) # Here we broadcast along two dimensions to create the mask. mask = broadcast_ones * to_mask return mask
[ "def", "create_attention_mask_from_input_mask", "(", "from_tensor", ",", "to_mask", ")", ":", "from_shape", "=", "get_shape_list", "(", "from_tensor", ",", "expected_rank", "=", "[", "2", ",", "3", "]", ")", "batch_size", "=", "from_shape", "[", "0", "]", "fro...
https://github.com/yuanxiaosc/Schema-based-Knowledge-Extraction/blob/ac0f07cd1088f24cb8f76c271fd2b49ea6100ca8/bert/modeling.py#L524-L555
feeluown/FeelUOwn
ec104689add09c351e6ca4133a5d0632294b3784
feeluown/models/models.py
python
BaseModel.list
(cls, identifier_list)
Model batch get method
Model batch get method
[ "Model", "batch", "get", "method" ]
def list(cls, identifier_list): """Model batch get method"""
[ "def", "list", "(", "cls", ",", "identifier_list", ")", ":" ]
https://github.com/feeluown/FeelUOwn/blob/ec104689add09c351e6ca4133a5d0632294b3784/feeluown/models/models.py#L52-L53
WikidPad/WikidPad
558109638807bc76b4672922686e416ab2d5f79c
WikidPad/lib/pwiki/PersonalWikiFrame.py
python
PersonalWikiFrame.requireReadAccess
(self)
Check flag in WikiDocument if database is readable. If not, take measures to re-establish it. If read access is probably possible, return True
Check flag in WikiDocument if database is readable. If not, take measures to re-establish it. If read access is probably possible, return True
[ "Check", "flag", "in", "WikiDocument", "if", "database", "is", "readable", ".", "If", "not", "take", "measures", "to", "re", "-", "establish", "it", ".", "If", "read", "access", "is", "probably", "possible", "return", "True" ]
def requireReadAccess(self): """ Check flag in WikiDocument if database is readable. If not, take measures to re-establish it. If read access is probably possible, return True """ wd = self.getWikiDocument() if wd is None: wx.MessageBox(_("This operation requires an open database"), _('No open database'), wx.OK, self) return False if not wd.getReadAccessFailed(): return True while True: wd = self.getWikiDocument() if wd is None: return False self.SetFocus() answer = wx.MessageBox(_("No connection to database. " "Try to reconnect?"), _('Reconnect database?'), wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION, self) if answer != wx.YES: return False self.showStatusMessage(_("Trying to reconnect database..."), 0, "reconnect") try: try: wd.reconnect() wd.setNoAutoSaveFlag(False) wd.setReadAccessFailed(False) self.requireWriteAccess() # Just to test it # TODO ? return True # Success except DbReadAccessError as e: sys.stderr.write(_("Error while trying to reconnect:\n")) traceback.print_exc() self.SetFocus() self.displayErrorMessage(_('Error while reconnecting ' 'database'), e) finally: self.dropStatusMessageByKey("reconnect")
[ "def", "requireReadAccess", "(", "self", ")", ":", "wd", "=", "self", ".", "getWikiDocument", "(", ")", "if", "wd", "is", "None", ":", "wx", ".", "MessageBox", "(", "_", "(", "\"This operation requires an open database\"", ")", ",", "_", "(", "'No open datab...
https://github.com/WikidPad/WikidPad/blob/558109638807bc76b4672922686e416ab2d5f79c/WikidPad/lib/pwiki/PersonalWikiFrame.py#L3596-L3640
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/accounts/v1/credential/aws.py
python
AwsPage.get_instance
(self, payload)
return AwsInstance(self._version, payload, )
Build an instance of AwsInstance :param dict payload: Payload response from the API :returns: twilio.rest.accounts.v1.credential.aws.AwsInstance :rtype: twilio.rest.accounts.v1.credential.aws.AwsInstance
Build an instance of AwsInstance
[ "Build", "an", "instance", "of", "AwsInstance" ]
def get_instance(self, payload): """ Build an instance of AwsInstance :param dict payload: Payload response from the API :returns: twilio.rest.accounts.v1.credential.aws.AwsInstance :rtype: twilio.rest.accounts.v1.credential.aws.AwsInstance """ return AwsInstance(self._version, payload, )
[ "def", "get_instance", "(", "self", ",", "payload", ")", ":", "return", "AwsInstance", "(", "self", ".", "_version", ",", "payload", ",", ")" ]
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/accounts/v1/credential/aws.py#L182-L191
weechat/scripts
99ec0e7eceefabb9efb0f11ec26d45d6e8e84335
python/minesweeper.py
python
minesweeper_config_cb
(data, option, value)
return weechat.WEECHAT_RC_OK
Called when a script option is changed.
Called when a script option is changed.
[ "Called", "when", "a", "script", "option", "is", "changed", "." ]
def minesweeper_config_cb(data, option, value): """Called when a script option is changed.""" global minesweeper_settings pos = option.rfind('.') if pos > 0: name = option[pos+1:] if name in minesweeper_settings: minesweeper_settings[name] = value if name == 'color_digits': minesweeper_set_colors() elif name == 'zoom': minesweeper_adjust_zoom() minesweeper_display() return weechat.WEECHAT_RC_OK
[ "def", "minesweeper_config_cb", "(", "data", ",", "option", ",", "value", ")", ":", "global", "minesweeper_settings", "pos", "=", "option", ".", "rfind", "(", "'.'", ")", "if", "pos", ">", "0", ":", "name", "=", "option", "[", "pos", "+", "1", ":", "...
https://github.com/weechat/scripts/blob/99ec0e7eceefabb9efb0f11ec26d45d6e8e84335/python/minesweeper.py#L250-L263
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/functions/special/error_functions.py
python
expint.fdiff
(self, argindex)
[]
def fdiff(self, argindex): from sympy import meijerg nu, z = self.args if argindex == 1: return -z**(nu - 1)*meijerg([], [1, 1], [0, 0, 1 - nu], [], z) elif argindex == 2: return -expint(nu - 1, z) else: raise ArgumentIndexError(self, argindex)
[ "def", "fdiff", "(", "self", ",", "argindex", ")", ":", "from", "sympy", "import", "meijerg", "nu", ",", "z", "=", "self", ".", "args", "if", "argindex", "==", "1", ":", "return", "-", "z", "**", "(", "nu", "-", "1", ")", "*", "meijerg", "(", "...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/functions/special/error_functions.py#L1220-L1228
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/states/smartos.py
python
vm_absent
(name, archive=False)
return ret
Ensure vm is absent on the computenode name : string hostname of vm archive : boolean toggle archiving of vm on removal .. note:: State ID is used as hostname. Hostnames must be unique.
Ensure vm is absent on the computenode
[ "Ensure", "vm", "is", "absent", "on", "the", "computenode" ]
def vm_absent(name, archive=False): """ Ensure vm is absent on the computenode name : string hostname of vm archive : boolean toggle archiving of vm on removal .. note:: State ID is used as hostname. Hostnames must be unique. """ name = name.lower() ret = {"name": name, "changes": {}, "result": None, "comment": ""} if name not in __salt__["vmadm.list"](order="hostname"): # we're good ret["result"] = True ret["comment"] = "vm {} is absent".format(name) else: # delete vm if not __opts__["test"]: # set archive to true if needed if archive: __salt__["vmadm.update"]( vm=name, key="hostname", archive_on_delete=True ) ret["result"] = __salt__["vmadm.delete"](name, key="hostname") else: ret["result"] = True if not isinstance(ret["result"], bool) and ret["result"].get("Error"): ret["result"] = False ret["comment"] = "failed to delete vm {}".format(name) else: ret["comment"] = "vm {} deleted".format(name) ret["changes"][name] = None return ret
[ "def", "vm_absent", "(", "name", ",", "archive", "=", "False", ")", ":", "name", "=", "name", ".", "lower", "(", ")", "ret", "=", "{", "\"name\"", ":", "name", ",", "\"changes\"", ":", "{", "}", ",", "\"result\"", ":", "None", ",", "\"comment\"", "...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/states/smartos.py#L1204-L1245
ceronman/typeannotations
7a3bffbb3b7e690b6f064f70a586820e3a741c5f
annotation/typed.py
python
_check_return_type
(signature, return_value)
return return_value
Check that the return value of a function matches the signature.
Check that the return value of a function matches the signature.
[ "Check", "that", "the", "return", "value", "of", "a", "function", "matches", "the", "signature", "." ]
def _check_return_type(signature, return_value): """Check that the return value of a function matches the signature.""" annotation = signature.return_annotation if annotation is EMPTY_ANNOTATION: annotation = AnyType if not _check_type_constraint(return_value, annotation): raise TypeError('Incorrect return type') return return_value
[ "def", "_check_return_type", "(", "signature", ",", "return_value", ")", ":", "annotation", "=", "signature", ".", "return_annotation", "if", "annotation", "is", "EMPTY_ANNOTATION", ":", "annotation", "=", "AnyType", "if", "not", "_check_type_constraint", "(", "retu...
https://github.com/ceronman/typeannotations/blob/7a3bffbb3b7e690b6f064f70a586820e3a741c5f/annotation/typed.py#L470-L477
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
src/oci/waf/waf_client_composite_operations.py
python
WafClientCompositeOperations.delete_network_address_list_and_wait_for_state
(self, network_address_list_id, wait_for_states=[], operation_kwargs={}, waiter_kwargs={})
Calls :py:func:`~oci.waf.WafClient.delete_network_address_list` and waits for the :py:class:`~oci.waf.models.WorkRequest` to enter the given state(s). :param str network_address_list_id: (required) The `OCID`__ of the NetworkAddressList. __ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm :param list[str] wait_for_states: An array of states to wait on. These should be valid values for :py:attr:`~oci.waf.models.WorkRequest.status` :param dict operation_kwargs: A dictionary of keyword arguments to pass to :py:func:`~oci.waf.WafClient.delete_network_address_list` :param dict waiter_kwargs: A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds`` as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
Calls :py:func:`~oci.waf.WafClient.delete_network_address_list` and waits for the :py:class:`~oci.waf.models.WorkRequest` to enter the given state(s).
[ "Calls", ":", "py", ":", "func", ":", "~oci", ".", "waf", ".", "WafClient", ".", "delete_network_address_list", "and", "waits", "for", "the", ":", "py", ":", "class", ":", "~oci", ".", "waf", ".", "models", ".", "WorkRequest", "to", "enter", "the", "gi...
def delete_network_address_list_and_wait_for_state(self, network_address_list_id, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}): """ Calls :py:func:`~oci.waf.WafClient.delete_network_address_list` and waits for the :py:class:`~oci.waf.models.WorkRequest` to enter the given state(s). :param str network_address_list_id: (required) The `OCID`__ of the NetworkAddressList. __ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm :param list[str] wait_for_states: An array of states to wait on. These should be valid values for :py:attr:`~oci.waf.models.WorkRequest.status` :param dict operation_kwargs: A dictionary of keyword arguments to pass to :py:func:`~oci.waf.WafClient.delete_network_address_list` :param dict waiter_kwargs: A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds`` as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait """ operation_result = None try: operation_result = self.client.delete_network_address_list(network_address_list_id, **operation_kwargs) except oci.exceptions.ServiceError as e: if e.status == 404: return WAIT_RESOURCE_NOT_FOUND else: raise e if not wait_for_states: return operation_result lowered_wait_for_states = [w.lower() for w in wait_for_states] wait_for_resource_id = operation_result.headers['opc-work-request-id'] try: waiter_result = oci.wait_until( self.client, self.client.get_work_request(wait_for_resource_id), evaluate_response=lambda r: getattr(r.data, 'status') and getattr(r.data, 'status').lower() in lowered_wait_for_states, **waiter_kwargs ) result_to_return = waiter_result return result_to_return except Exception as e: raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e)
[ "def", "delete_network_address_list_and_wait_for_state", "(", "self", ",", "network_address_list_id", ",", "wait_for_states", "=", "[", "]", ",", "operation_kwargs", "=", "{", "}", ",", "waiter_kwargs", "=", "{", "}", ")", ":", "operation_result", "=", "None", "tr...
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/waf/waf_client_composite_operations.py#L269-L315
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e
java/java2py/java2python-0.5.1/java2python/compiler/template.py
python
Class.iterBases
(self)
return chain(*(h(self) for h in self.configHandlers('Base')))
Yields the base classes for this type.
Yields the base classes for this type.
[ "Yields", "the", "base", "classes", "for", "this", "type", "." ]
def iterBases(self): """ Yields the base classes for this type. """ return chain(*(h(self) for h in self.configHandlers('Base')))
[ "def", "iterBases", "(", "self", ")", ":", "return", "chain", "(", "*", "(", "h", "(", "self", ")", "for", "h", "in", "self", ".", "configHandlers", "(", "'Base'", ")", ")", ")" ]
https://github.com/TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials/blob/5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e/java/java2py/java2python-0.5.1/java2python/compiler/template.py#L410-L412
WPO-Foundation/wptagent
94470f007294213f900dcd9a207678b5b9fce5d3
ws4py/utf8validator.py
python
Utf8Validator.reset
(self)
Reset validator to start new incremental UTF-8 decode/validation.
Reset validator to start new incremental UTF-8 decode/validation.
[ "Reset", "validator", "to", "start", "new", "incremental", "UTF", "-", "8", "decode", "/", "validation", "." ]
def reset(self): """ Reset validator to start new incremental UTF-8 decode/validation. """ self.state = Utf8Validator.UTF8_ACCEPT self.codepoint = 0 self.i = 0
[ "def", "reset", "(", "self", ")", ":", "self", ".", "state", "=", "Utf8Validator", ".", "UTF8_ACCEPT", "self", ".", "codepoint", "=", "0", "self", ".", "i", "=", "0" ]
https://github.com/WPO-Foundation/wptagent/blob/94470f007294213f900dcd9a207678b5b9fce5d3/ws4py/utf8validator.py#L84-L90
glumpy/glumpy
46a7635c08d3a200478397edbe0371a6c59cd9d7
examples/galaxy_simulation.py
python
Galaxy.__len__
(self)
return 0
Number of particles
Number of particles
[ "Number", "of", "particles" ]
def __len__(self): """ Number of particles """ if self._particles is not None: return len(self._particles) return 0
[ "def", "__len__", "(", "self", ")", ":", "if", "self", ".", "_particles", "is", "not", "None", ":", "return", "len", "(", "self", ".", "_particles", ")", "return", "0" ]
https://github.com/glumpy/glumpy/blob/46a7635c08d3a200478397edbe0371a6c59cd9d7/examples/galaxy_simulation.py#L100-L105
privacyidea/privacyidea
9490c12ddbf77a34ac935b082d09eb583dfafa2c
privacyidea/api/token.py
python
list_api
()
Display the list of tokens. Using different parameters you can choose, which tokens you want to get and also in which format you want to get the information (*outform*). :query serial: Display the token data of this single token. You can do a not strict matching by specifying a serial like "*OATH*". :query type: Display only token of type. You ca do a non strict matching by specifying a tokentype like "*otp*", to file hotp and totp tokens. :query user: display tokens of this user :query tokenrealm: takes a realm, only the tokens in this realm will be displayed :query basestring description: Display token with this kind of description :query sortby: sort the output by column :query sortdir: asc/desc :query page: request a certain page :query assigned: Only return assigned (True) or not assigned (False) tokens :query active: Only return active (True) or inactive (False) tokens :query pagesize: limit the number of returned tokens :query user_fields: additional user fields from the userid resolver of the owner (user) :query outform: if set to "csv", than the token list will be given in CSV :return: a json result with the data being a list of token dictionaries:: { "data": [ { <token1> }, { <token2> } ]} :rtype: json
Display the list of tokens. Using different parameters you can choose, which tokens you want to get and also in which format you want to get the information (*outform*).
[ "Display", "the", "list", "of", "tokens", ".", "Using", "different", "parameters", "you", "can", "choose", "which", "tokens", "you", "want", "to", "get", "and", "also", "in", "which", "format", "you", "want", "to", "get", "the", "information", "(", "*", ...
def list_api(): """ Display the list of tokens. Using different parameters you can choose, which tokens you want to get and also in which format you want to get the information (*outform*). :query serial: Display the token data of this single token. You can do a not strict matching by specifying a serial like "*OATH*". :query type: Display only token of type. You ca do a non strict matching by specifying a tokentype like "*otp*", to file hotp and totp tokens. :query user: display tokens of this user :query tokenrealm: takes a realm, only the tokens in this realm will be displayed :query basestring description: Display token with this kind of description :query sortby: sort the output by column :query sortdir: asc/desc :query page: request a certain page :query assigned: Only return assigned (True) or not assigned (False) tokens :query active: Only return active (True) or inactive (False) tokens :query pagesize: limit the number of returned tokens :query user_fields: additional user fields from the userid resolver of the owner (user) :query outform: if set to "csv", than the token list will be given in CSV :return: a json result with the data being a list of token dictionaries:: { "data": [ { <token1> }, { <token2> } ]} :rtype: json """ param = request.all_data user = request.User serial = getParam(param, "serial", optional) page = int(getParam(param, "page", optional, default=1)) tokentype = getParam(param, "type", optional) description = getParam(param, "description", optional) sort = getParam(param, "sortby", optional, default="serial") sdir = getParam(param, "sortdir", optional, default="asc") psize = int(getParam(param, "pagesize", optional, default=15)) realm = getParam(param, "tokenrealm", optional) userid = getParam(param, "userid", optional) resolver = getParam(param, "resolver", optional) ufields = getParam(param, "user_fields", optional) output_format = getParam(param, "outform", optional) assigned = getParam(param, "assigned", optional) active = getParam(param, "active", optional) tokeninfokey = getParam(param, "infokey", optional) tokeninfovalue = getParam(param, "infovalue", optional) tokeninfo = None if tokeninfokey and tokeninfovalue: tokeninfo = {tokeninfokey: tokeninfovalue} if assigned: assigned = assigned.lower() == "true" if active: active = active.lower() == "true" user_fields = [] if ufields: user_fields = [u.strip() for u in ufields.split(",")] # allowed_realms determines, which realms the admin would be allowed to see # In certain cases like for users, we do not have allowed_realms allowed_realms = getattr(request, "pi_allowed_realms", None) g.audit_object.log({'info': "realm: {0!s}".format((allowed_realms))}) # get list of tokens as a dictionary tokens = get_tokens_paginate(serial=serial, realm=realm, page=page, user=user, assigned=assigned, psize=psize, active=active, sortby=sort, sortdir=sdir, tokentype=tokentype, resolver=resolver, description=description, userid=userid, allowed_realms=allowed_realms, tokeninfo=tokeninfo) g.audit_object.log({"success": True}) if output_format == "csv": return send_csv_result(tokens) else: return send_result(tokens)
[ "def", "list_api", "(", ")", ":", "param", "=", "request", ".", "all_data", "user", "=", "request", ".", "User", "serial", "=", "getParam", "(", "param", ",", "\"serial\"", ",", "optional", ")", "page", "=", "int", "(", "getParam", "(", "param", ",", ...
https://github.com/privacyidea/privacyidea/blob/9490c12ddbf77a34ac935b082d09eb583dfafa2c/privacyidea/api/token.py#L350-L428
lk-geimfari/mimesis
36653b49f28719c0a2aa20fef6c6df3911811b32
mimesis/providers/address.py
python
Address.address
(self)
return fmt.format( st_num=st_num, st_name=st_name, st_sfx=self.street_suffix(), )
Generate a random full address. :return: Full address.
Generate a random full address.
[ "Generate", "a", "random", "full", "address", "." ]
def address(self) -> str: """Generate a random full address. :return: Full address. """ fmt: str = self.extract(["address_fmt"]) st_num = self.street_number() st_name = self.street_name() if self.locale in SHORTENED_ADDRESS_FMT: return fmt.format( st_num=st_num, st_name=st_name, ) if self.locale == "ja": return fmt.format( self.random.choice(self.extract(["city"])), # Generate list of random integers # in amount of 3, from 1 to 100. *self.random.randints(amount=3, a=1, b=100), ) return fmt.format( st_num=st_num, st_name=st_name, st_sfx=self.street_suffix(), )
[ "def", "address", "(", "self", ")", "->", "str", ":", "fmt", ":", "str", "=", "self", ".", "extract", "(", "[", "\"address_fmt\"", "]", ")", "st_num", "=", "self", ".", "street_number", "(", ")", "st_name", "=", "self", ".", "street_name", "(", ")", ...
https://github.com/lk-geimfari/mimesis/blob/36653b49f28719c0a2aa20fef6c6df3911811b32/mimesis/providers/address.py#L91-L119
awslabs/deeplearning-benchmark
3e9a906422b402869537f91056ae771b66487a8e
tensorflow_benchmark/tf_cnn_benchmarks/variable_mgr.py
python
sum_grad_and_var_all_reduce
(grad_and_vars, num_workers, alg, gpu_indices, aux_devices=None, num_shards=1)
return result
Apply all-reduce algorithm over specified gradient tensors.
Apply all-reduce algorithm over specified gradient tensors.
[ "Apply", "all", "-", "reduce", "algorithm", "over", "specified", "gradient", "tensors", "." ]
def sum_grad_and_var_all_reduce(grad_and_vars, num_workers, alg, gpu_indices, aux_devices=None, num_shards=1): """Apply all-reduce algorithm over specified gradient tensors.""" # Note that each grad_and_vars looks like the following: # ((grad0_gpu0, var0_gpu0), ... , (grad0_gpuN, var0_gpuN)) scaled_grads = [g for g, _ in grad_and_vars] if alg == 'nccl': summed_grads = nccl.all_sum(scaled_grads) elif alg == 'xring': summed_grads = all_reduce.build_ring_all_reduce( scaled_grads, num_workers, num_shards, gpu_indices, tf.add) elif alg == 'nccl/xring': summed_grads = all_reduce.build_nccl_then_ring(scaled_grads, num_shards, tf.add) elif alg == 'nccl/rechd': summed_grads = all_reduce.build_nccl_then_recursive_hd(scaled_grads, tf.add) elif alg == 'nccl/pscpu': summed_grads = all_reduce.build_nccl_then_shuffle( scaled_grads, aux_devices, tf.add, tf.add_n) elif alg == 'pscpu/pscpu': summed_grads = all_reduce.build_shuffle_then_shuffle( scaled_grads, aux_devices, # TODO(tucker): devise a way of better specifying the device set # for the second level. [aux_devices[0]], tf.add_n) elif alg in ['pscpu', 'psgpu']: summed_grads = all_reduce.build_shuffle_all_reduce( scaled_grads, aux_devices, tf.add_n) else: raise ValueError('unsupported all_reduce alg: ', alg) result = [] for (_, v), g in zip(grad_and_vars, summed_grads): result.append([g, v]) return result
[ "def", "sum_grad_and_var_all_reduce", "(", "grad_and_vars", ",", "num_workers", ",", "alg", ",", "gpu_indices", ",", "aux_devices", "=", "None", ",", "num_shards", "=", "1", ")", ":", "# Note that each grad_and_vars looks like the following:", "# ((grad0_gpu0, var0_gpu0),...
https://github.com/awslabs/deeplearning-benchmark/blob/3e9a906422b402869537f91056ae771b66487a8e/tensorflow_benchmark/tf_cnn_benchmarks/variable_mgr.py#L1006-L1041
timonwong/OmniMarkupPreviewer
21921ac7a99d2b5924a2219b33679a5b53621392
OmniMarkupLib/Renderers/libs/python2/genshi/filters/transform.py
python
InvertTransformation.__call__
(self, stream)
Apply the transform filter to the marked stream. :param stream: the marked event stream to filter
Apply the transform filter to the marked stream.
[ "Apply", "the", "transform", "filter", "to", "the", "marked", "stream", "." ]
def __call__(self, stream): """Apply the transform filter to the marked stream. :param stream: the marked event stream to filter """ for mark, event in stream: if mark: yield None, event else: yield OUTSIDE, event
[ "def", "__call__", "(", "self", ",", "stream", ")", ":", "for", "mark", ",", "event", "in", "stream", ":", "if", "mark", ":", "yield", "None", ",", "event", "else", ":", "yield", "OUTSIDE", ",", "event" ]
https://github.com/timonwong/OmniMarkupPreviewer/blob/21921ac7a99d2b5924a2219b33679a5b53621392/OmniMarkupLib/Renderers/libs/python2/genshi/filters/transform.py#L779-L788
kirthevasank/nasbot
3c745dc986be30e3721087c8fa768099032a0802
opt/gp_bandit.py
python
GPBandit._create_init_gp
(self)
Creates an initial GP.
Creates an initial GP.
[ "Creates", "an", "initial", "GP", "." ]
def _create_init_gp(self): """ Creates an initial GP. """ reg_X = self.pre_eval_points + self.history.query_points reg_Y = np.concatenate((self.pre_eval_vals, self.history.query_vals), axis=0) range_Y = reg_Y.max() - reg_Y.min() mean_func = lambda x: np.array([np.median(reg_Y)] * len(x)) kernel = self.domain.get_default_kernel(range_Y) noise_var = (reg_Y.std()**2)/10 self.gp = GP(reg_X, reg_Y, kernel, mean_func, noise_var)
[ "def", "_create_init_gp", "(", "self", ")", ":", "reg_X", "=", "self", ".", "pre_eval_points", "+", "self", ".", "history", ".", "query_points", "reg_Y", "=", "np", ".", "concatenate", "(", "(", "self", ".", "pre_eval_vals", ",", "self", ".", "history", ...
https://github.com/kirthevasank/nasbot/blob/3c745dc986be30e3721087c8fa768099032a0802/opt/gp_bandit.py#L237-L245
jbjorne/TEES
caf19a4a1352ac59f5dc13a8684cc42ce4342d9d
Utils/Menu.py
python
Menu.setDefault
(self, key)
[]
def setDefault(self, key): for option in self.options: option.isDefault = False self.optDict[key].isDefault = True
[ "def", "setDefault", "(", "self", ",", "key", ")", ":", "for", "option", "in", "self", ".", "options", ":", "option", ".", "isDefault", "=", "False", "self", ".", "optDict", "[", "key", "]", ".", "isDefault", "=", "True" ]
https://github.com/jbjorne/TEES/blob/caf19a4a1352ac59f5dc13a8684cc42ce4342d9d/Utils/Menu.py#L68-L71
tahoe-lafs/tahoe-lafs
766a53b5208c03c45ca0a98e97eee76870276aa1
src/allmydata/interfaces.py
python
IClientStatus.list_recent_uploads
()
Return a list of IUploadStatus objects for the most recently started uploads.
Return a list of IUploadStatus objects for the most recently started uploads.
[ "Return", "a", "list", "of", "IUploadStatus", "objects", "for", "the", "most", "recently", "started", "uploads", "." ]
def list_recent_uploads(): """Return a list of IUploadStatus objects for the most recently started uploads."""
[ "def", "list_recent_uploads", "(", ")", ":" ]
https://github.com/tahoe-lafs/tahoe-lafs/blob/766a53b5208c03c45ca0a98e97eee76870276aa1/src/allmydata/interfaces.py#L2656-L2658
open-cogsci/OpenSesame
c4a3641b097a80a76937edbd8c365f036bcc9705
libqtopensesame/qtopensesamerun.py
python
qtopensesamerun.run
(self)
Does not actual run the experiment, but marks the application for running later.
Does not actual run the experiment, but marks the application for running later.
[ "Does", "not", "actual", "run", "the", "experiment", "but", "marks", "the", "application", "for", "running", "later", "." ]
def run(self): """ Does not actual run the experiment, but marks the application for running later. """ self.run = True self.options.experiment = str(self.ui.edit_experiment.text()) self.options.subject = self.ui.spinbox_subject_nr.value() self.options.logfile = str(self.ui.edit_logfile.text()) self.options.fullscreen = self.ui.checkbox_fullscreen.isChecked() self.options.custom_resolution = \ self.ui.checkbox_custom_resolution.isChecked() self.options.width = self.ui.spinbox_width.value() self.options.height = self.ui.spinbox_height.value() self.options.pylink = self.ui.checkbox_pylink.isChecked() self.close()
[ "def", "run", "(", "self", ")", ":", "self", ".", "run", "=", "True", "self", ".", "options", ".", "experiment", "=", "str", "(", "self", ".", "ui", ".", "edit_experiment", ".", "text", "(", ")", ")", "self", ".", "options", ".", "subject", "=", ...
https://github.com/open-cogsci/OpenSesame/blob/c4a3641b097a80a76937edbd8c365f036bcc9705/libqtopensesame/qtopensesamerun.py#L99-L116
donggong1/memae-anomaly-detection
ceece7714fb241e82ef3f3785d3d1ed86c28113e
utils/utils.py
python
tensor2numpy
(tensor_in)
return nparray_out
Transfer pythrch tensor to numpy array
Transfer pythrch tensor to numpy array
[ "Transfer", "pythrch", "tensor", "to", "numpy", "array" ]
def tensor2numpy(tensor_in): """Transfer pythrch tensor to numpy array""" nparray_out = (tensor_in.data).cpu().numpy() return nparray_out
[ "def", "tensor2numpy", "(", "tensor_in", ")", ":", "nparray_out", "=", "(", "tensor_in", ".", "data", ")", ".", "cpu", "(", ")", ".", "numpy", "(", ")", "return", "nparray_out" ]
https://github.com/donggong1/memae-anomaly-detection/blob/ceece7714fb241e82ef3f3785d3d1ed86c28113e/utils/utils.py#L30-L33
deepgram/kur
fd0c120e50815c1e5be64e5dde964dcd47234556
kur/backend/backend.py
python
Backend.evaluate
(self, model, data, post_processor=None)
Evaluates the model on a batch ofdata.
Evaluates the model on a batch ofdata.
[ "Evaluates", "the", "model", "on", "a", "batch", "ofdata", "." ]
def evaluate(self, model, data, post_processor=None): """ Evaluates the model on a batch ofdata. """ raise NotImplementedError
[ "def", "evaluate", "(", "self", ",", "model", ",", "data", ",", "post_processor", "=", "None", ")", ":", "raise", "NotImplementedError" ]
https://github.com/deepgram/kur/blob/fd0c120e50815c1e5be64e5dde964dcd47234556/kur/backend/backend.py#L566-L569
cw1204772/AIC2018_iamai
9c3720ba5eeb94e02deed303f32acaaa80aa893d
ReID/MCT.py
python
multi_camera_matching
(opt,MCT)
Multi-camera matching
Multi-camera matching
[ "Multi", "-", "camera", "matching" ]
def multi_camera_matching(opt,MCT): """Multi-camera matching""" print('multi camera matching...') if opt.method == 'cluster': idxs = [] tracks = [] for i in range(len(MCT)): for j in range(len(MCT[i])): tracks.append(MCT[i][j]) idxs.append((i,j)) classes = clustering(opt, tracks) with open(os.path.join(opt.output_dir, 'cluster.pkl'), 'wb') as f: pickle.dump(classes, f) # dict order by clustered class classified_Trackers = defaultdict(list) for k in range(len(classes)): classified_Trackers[classes[k]].append(idxs[k]) # Check every cluster class Final_ID = [] for c in classified_Trackers.keys(): Trackers = classified_Trackers[c] if len(Trackers) >= 4: locs = set([i for i, j in Trackers]) if locs & {0,1,2,3} == {0,1,2,3}: Final_ID.append([MCT[i][j] for i, j in Trackers]) del classified_Trackers print('%d qualified clusters!' % len(Final_ID)) # check constraint and merge tracks = [] for t_list in tqdm(Final_ID): tracks.append(merge_tracks(opt, t_list)) return tracks elif args.method == 'bottom_up_cluster': all_tracks = [] # clustering within same location for i, loc_tracks in enumerate(MCT): print('Loc%d' % (i+1)) opt.k = len(loc_tracks) // opt.n classes = clustering(opt, loc_tracks) with open(os.path.join(opt.output_dir, 'Loc%d_cluster.pkl' % (i+1)), 'wb') as f: pickle.dump(classes, f) #with open(os.path.join(opt.output_dir, 'Loc%d_cluster.pkl' % (i+1)), 'rb') as f: # classes = pickle.load(f) for class_id in tqdm(np.unique(classes).tolist()): select = np.where(classes == class_id)[0] tracks = [loc_tracks[j] for j in select.tolist()] track = merge_tracks(opt, tracks) assert debug_frame(track.dump()) all_tracks.append(track) # clustering with all locations opt.k = len(all_tracks) // opt.n classes = clustering(opt, all_tracks) with open(os.path.join(opt.output_dir, 'all_loc_cluster.pkl'), 'wb') as f: pickle.dump(classes, f) #with open(os.path.join(opt.output_dir, 'all_loc_cluster.pkl'), 'rb') as f: # classes = pickle.load(f) clusters = [] for class_id in tqdm(np.unique(classes).tolist()): select = np.where(classes == class_id)[0] tracks = [all_tracks[j] for j in select.tolist()] for t in tracks: assert debug_frame(t.dump()) track = merge_tracks(opt, tracks) if debug_loc(track.dump(), loc_seq_id): clusters.append(track) print('%d qualified clusters!' % len(clusters)) return clusters elif opt.method == 're-rank-4' or opt.method == 're-rank-all': print('reranking...') # First cluster every Location Locs = [[],[],[],[]] for i,loc_tracks in enumerate(MCT): print('Loc%d'%(i+1)) opt.k = len(loc_tracks)//opt.n classes = clustering(opt,loc_tracks) with open(os.path.join(opt.output_dir, 'Loc%d_cluster.pkl' % (i+1)), 'wb') as f: pickle.dump(classes, f) #with open(os.path.join('/home/cw1204772/Dataset/AIC2018/MCT/fasta_joint_vanilla_biased_knn_avg','Loc%d_cluster.pkl'%(i+1)),'rb') as f: # classes = pickle.load(f) for class_id in tqdm(np.unique(classes).tolist()): select = np.where(classes == class_id)[0] tracks = [loc_tracks[j] for j in select.tolist()] track = merge_tracks(opt,tracks) assert debug_frame(track.dump()) Locs[i].append(track) with open(os.path.join(opt.output_dir,'Locs.pkl'),'wb') as f: pickle.dump(Locs,f) #with open(os.path.join(opt.output_dir,'Locs.pkl'),'rb') as f: # Locs = pickle.load(f) ############### ''' with open(os.path.join(opt.output_dir,'Loc4_cluster.pkl'), 'rb') as f: classes = pickle.load(f) temp = [] for class_id in tqdm(np.unique(classes).tolist()): select = np.where(classes == class_id)[0] tracks = [MCT[3][j] for j in select.tolist()] track = merge_tracks(opt,tracks) assert debug_frame(track.dump()) temp.append(track) Locs[3] = temp with open(os.path.join(opt.output_dir,'Locs.pkl'),'wb') as f: pickle.dump(Locs,f) ''' ############### q_idx = list(range(len(Locs[3]))) if opt.method == 're-rank-all': tracks = Locs[3] + Locs[0] + Locs[1] + Locs[2] dis_matrix = compute_distance(tracks) rank_list = re_ranking(dis_matrix, q_idx) outputs = [] for i, ranks in enumerate(rank_list): track = tracks[q_idx[i]] for idx in ranks[:opt.n]: track = priority_merge(track, tracks[idx]) if debug_loc(track.dump(), loc_seq_id): outputs.append(track) return outputs elif opt.method == 're-rank-4': q_idx = list(range(len(Locs[3]))) multi_loc_tracks = [] for i in [0,1,2]: tracks = Locs[3] + Locs[i] dis_matrix = compute_distance(tracks) rank_list = re_ranking(dis_matrix, q_idx) with open(os.path.join(opt.output_dir, 're_rank%d.pkl' % i), 'wb') as f: pickle.dump(rank_list, f) #with open(os.path.join(opt.output_dir, 're_rank%d.pkl' % i), 'rb') as f: # rank_list = pickle.load(f) #rank_list = [[len(tracks)-1], [], [len(tracks)-1,len(tracks)-2]] #for i in range(len(q_idx)-3): # rank_list.append([]) assert len(rank_list)==len(q_idx) single_loc_tracks = [] for j, ranks in enumerate(rank_list): #print(ranks) if len(ranks)==0: single_loc_tracks.append(None) #print('None') else: track = copy.copy(tracks[ranks[0]]) if len(ranks) > 1: for idx in ranks[1:]: track = priority_merge(track, tracks[idx]) if tracks[idx].dump() is None: sys.exit('not right!') #print(track.dump()) single_loc_tracks.append(track) if single_loc_tracks[-1].dump() is None: print(i,j) print(ranks) sys.exit('not right!') #if j == 2: # print(single_loc_tracks[-1].dump()) # sys.exit() #if j == 5: sys.exit() multi_loc_tracks.append(single_loc_tracks) with open(os.path.join(opt.output_dir, 'after_re_ranking.pkl'), 'wb') as f: pickle.dump(multi_loc_tracks, f) #with open(os.path.join(opt.output_dir, 'after_re_ranking.pkl'), 'rb') as f: # multi_loc_tracks = pickle.load(f) #print(multi_loc_tracks[0][2].dump()) outputs = [] for i, idx in enumerate(q_idx): track = Locs[3][idx] for j in range(len(multi_loc_tracks)): #print('--------------------') #print(j,i) #if multi_loc_tracks[j][i].dump() is None: #print(j,i) #print(multi_loc_tracks[j][i] is not None) #print(multi_loc_tracks[j][i].dump().shape) if multi_loc_tracks[j][i] is not None: #print(multi_loc_tracks[j][i].dump()) #print(multi_loc_tracks[j][i].dump().shape) #print(track.dump().shape) multi_loc_tracks[j][i].merge(track) #print(multi_loc_tracks[0][2].dump()) if debug_loc(track.dump(), loc_seq_id): outputs.append(track) return outputs elif opt.method == 'biased_knn': ref_tracks = [] tgt_tracks = [] # clustering within same location for i, loc_tracks in enumerate(MCT): print('Loc%d' % (i+1)) opt.k = len(loc_tracks) // opt.n classes = clustering(opt, loc_tracks) with open(os.path.join(opt.output_dir, 'Loc%d_cluster.pkl' % (i+1)), 'wb') as f: pickle.dump(classes, f) #with open(os.path.join(opt.output_dir, 'Loc%d_cluster.pkl' % (i+1)), 'rb') as f: # classes = pickle.load(f) for class_id in tqdm(np.unique(classes).tolist()): select = np.where(classes == class_id)[0] tracks = [loc_tracks[j] for j in select.tolist()] track = merge_tracks(opt, tracks) assert debug_frame(track.dump()) if i == 3: ref_tracks.append(track) else: tgt_tracks.append(track) #with open(os.path.join(opt.output_dir, 'ref_tracks.pkl'), 'wb') as f: # pickle.dump(ref_tracks, f) #with open(os.path.join(opt.output_dir, 'tgt_tracks.pkl'), 'wb') as f: # pickle.dump(tgt_tracks, f) #with open(os.path.join(opt.output_dir, 'ref_tracks.pkl'), 'rb') as f: # ref_tracks = pickle.load(f) #with open(os.path.join(opt.output_dir, 'tgt_tracks.pkl'), 'rb') as f: # tgt_tracks = pickle.load(f) # K nearest neighbor classifier features = [] targets = [] for i, t in enumerate(ref_tracks): features.append(t.summarized_feature()) targets.append(i) features = np.stack(features, axis=0) targets = np.array(targets) print('start knn...') knn = KNeighborsClassifier(n_neighbors=1, n_jobs=-1) knn.fit(features, targets) features = [] for t in tgt_tracks: features.append(t.summarized_feature(opt.sum)) features = np.stack(features, axis=0) print('predicting...') classes = knn.predict(features) for class_id in tqdm(np.unique(classes).tolist()): select = np.where(classes == class_id)[0] tracks = [tgt_tracks[i] for i in select.tolist()] track = merge_tracks(opt, tracks, [ref_tracks[class_id]]) ref_tracks[class_id] = merge_tracks(opt, [ref_tracks[class_id], track]) # Filter out tracks that does not appear in all 4 locations outputs = [] for t in ref_tracks: if debug_loc(t.dump(), loc_seq_id): outputs.append(t) print('%d qualified clusters!' % len(outputs)) return outputs elif opt.method == 'biased_biased_knn': # cluster with loc 3 & 4 ref_tracks = [] for i in range(2,3+1): ref_tracks += MCT[i] opt.k = 2000 ref_classes = clustering(opt, ref_tracks) with open('ref_classes.pkl', 'wb') as f: pickle.dump(ref_classes, f) #with open('ref_classes.pkl', 'rb') as f: # ref_classes = pickle.load(f) # build knn features = [t.summarized_feature() for t in ref_tracks] features = np.stack(features, axis=0) print('start knn...') knn = KNeighborsClassifier(n_neighbors=1, n_jobs=-1) knn.fit(features, ref_classes) with open('train_knn.pkl', 'wb') as f: pickle.dump(knn, f) #with open('train_knn.pkl', 'rb') as f: # knn = pickle.load(f) # classify loc 1 & 2 with knn tgt_tracks = [] for i in range(0,1+1): tgt_tracks += MCT[i] features = [t.summarized_feature() for t in tgt_tracks] features = np.stack(features, axis=0) print('predicting...') tgt_classes = knn.predict(features) with open('tgt_classes.pkl', 'wb') as f: pickle.dump(tgt_classes, f) #with open('tgt_classes.pkl', 'rb') as f: # tgt_classes = pickle.load(f) # merge and check constraint outputs = [] for class_id in tqdm(np.unique(ref_classes).tolist()): ref_select = np.where(ref_classes == class_id)[0] ref_t = [ref_tracks[i] for i in ref_select.tolist()] tgt_select = np.where(tgt_classes == class_id)[0] tgt_t = [tgt_tracks[i] for i in tgt_select.tolist()] track = merge_tracks(opt, ref_t+tgt_t, ref_t) if debug_loc(track.dump(), loc_seq_id): outputs.append(track) print('%d qualified clusters!' % len(outputs)) return outputs ''' elif opt.method == 'hac': tracks = [] # clustering within same location for i, loc_tracks in enumerate(MCT): print('Loc%d' % (i+1)) opt.k = len(loc_tracks) // opt.n #classes = clustering(opt, loc_tracks) #with open(os.path.join(opt.output_dir, 'Loc%d_cluster.pkl' % (i+1)), 'wb') as f: # pickle.dump(classes, f) with open(os.path.join(opt.output_dir, 'Loc%d_cluster.pkl' % (i+1)), 'rb') as f: classes = pickle.load(f) for class_id in tqdm(np.unique(classes).tolist()): select = np.where(classes == class_id)[0] tracks = [loc_tracks[j] for j in select.tolist()] track = merge_tracks(opt, tracks) assert debug_frame(track.dump()) tracks.append(track) # HAC features = [t.summarized_feature(opt.sum) for t in tracks] #knn_graph = kneighbors_graph(features, 30, include_self=False, n_jobs=-1) #with open(os.path.join(opt.output_dir, 'knn_graph.pkl'), 'wb') as f: # pickle.dump(knn_graph, f) hac = AgglomerativeClustering(linkage='ward', connectivity=None, n_clusters=opt.k) classes = hac.fit_predict(features) with open(os.path.join(opt.output_dir, 'hac_classes.pkl'), 'wb') as f: pickle.dump(classes, f) # merge and check constraint outputs = [] for class_id in tqdm(np.unique(classes).tolist()): select = np.where(classes == class_id)[0] t = [tracks[i] for i in select.tolist()] track = merge_tracks(opt, t) if debug_loc(track.dump(), loc_seq_id): outputs.append(track) print('%d qualified clusters!' % len(outputs)) return outputs ''' else: raise NotImplementedError('Unrecognized MCT method!')
[ "def", "multi_camera_matching", "(", "opt", ",", "MCT", ")", ":", "print", "(", "'multi camera matching...'", ")", "if", "opt", ".", "method", "==", "'cluster'", ":", "idxs", "=", "[", "]", "tracks", "=", "[", "]", "for", "i", "in", "range", "(", "len"...
https://github.com/cw1204772/AIC2018_iamai/blob/9c3720ba5eeb94e02deed303f32acaaa80aa893d/ReID/MCT.py#L140-L500
yihui-he/KL-Loss
66c0ed9e886a2218f4cf88c0efd4f40199bff54a
detectron/utils/blob.py
python
zeros
(shape, int32=False)
return np.zeros(shape, dtype=np.int32 if int32 else np.float32)
Return a blob of all zeros of the given shape with the correct float or int data type.
Return a blob of all zeros of the given shape with the correct float or int data type.
[ "Return", "a", "blob", "of", "all", "zeros", "of", "the", "given", "shape", "with", "the", "correct", "float", "or", "int", "data", "type", "." ]
def zeros(shape, int32=False): """Return a blob of all zeros of the given shape with the correct float or int data type. """ return np.zeros(shape, dtype=np.int32 if int32 else np.float32)
[ "def", "zeros", "(", "shape", ",", "int32", "=", "False", ")", ":", "return", "np", ".", "zeros", "(", "shape", ",", "dtype", "=", "np", ".", "int32", "if", "int32", "else", "np", ".", "float32", ")" ]
https://github.com/yihui-he/KL-Loss/blob/66c0ed9e886a2218f4cf88c0efd4f40199bff54a/detectron/utils/blob.py#L128-L132
llSourcell/AI_Artist
3038c06c2e389b9c919c881c9a169efe2fd7810e
lib/python2.7/site-packages/pip/_vendor/ipaddress.py
python
_BaseV6._parse_hextet
(cls, hextet_str)
return int(hextet_str, 16)
Convert an IPv6 hextet string into an integer. Args: hextet_str: A string, the number to parse. Returns: The hextet as an integer. Raises: ValueError: if the input isn't strictly a hex number from [0..FFFF].
Convert an IPv6 hextet string into an integer.
[ "Convert", "an", "IPv6", "hextet", "string", "into", "an", "integer", "." ]
def _parse_hextet(cls, hextet_str): """Convert an IPv6 hextet string into an integer. Args: hextet_str: A string, the number to parse. Returns: The hextet as an integer. Raises: ValueError: if the input isn't strictly a hex number from [0..FFFF]. """ # Whitelist the characters, since int() allows a lot of bizarre stuff. if not cls._HEX_DIGITS.issuperset(hextet_str): raise ValueError("Only hex digits permitted in %r" % hextet_str) # We do the length check second, since the invalid character error # is likely to be more informative for the user if len(hextet_str) > 4: msg = "At most 4 characters permitted in %r" raise ValueError(msg % hextet_str) # Length check means we can skip checking the integer value return int(hextet_str, 16)
[ "def", "_parse_hextet", "(", "cls", ",", "hextet_str", ")", ":", "# Whitelist the characters, since int() allows a lot of bizarre stuff.", "if", "not", "cls", ".", "_HEX_DIGITS", ".", "issuperset", "(", "hextet_str", ")", ":", "raise", "ValueError", "(", "\"Only hex dig...
https://github.com/llSourcell/AI_Artist/blob/3038c06c2e389b9c919c881c9a169efe2fd7810e/lib/python2.7/site-packages/pip/_vendor/ipaddress.py#L1854-L1877
blasty/moneyshot
0541356cca38e57ec03a30b6dff1d38c0c7dfd00
colors.py
python
fg
(col)
return "\x1b[%dm" % (30 + color_tbl.index(col))
[]
def fg(col): return "\x1b[%dm" % (30 + color_tbl.index(col))
[ "def", "fg", "(", "col", ")", ":", "return", "\"\\x1b[%dm\"", "%", "(", "30", "+", "color_tbl", ".", "index", "(", "col", ")", ")" ]
https://github.com/blasty/moneyshot/blob/0541356cca38e57ec03a30b6dff1d38c0c7dfd00/colors.py#L4-L5
hadrianl/huobi
7cfceba39189552489c1d9c88169f93109ee76ba
huobitrade/service.py
python
HBRestAPI.margin_to_exchange
(self, symbol, currency, amount, _async=False)
return api_key_post(params, path, _async=_async, url=self.url)
借贷账户划出至现货账户 :param amount: :param currency: :param symbol: :return:
借贷账户划出至现货账户 :param amount: :param currency: :param symbol: :return:
[ "借贷账户划出至现货账户", ":", "param", "amount", ":", ":", "param", "currency", ":", ":", "param", "symbol", ":", ":", "return", ":" ]
def margin_to_exchange(self, symbol, currency, amount, _async=False): """ 借贷账户划出至现货账户 :param amount: :param currency: :param symbol: :return: """ params = {'symbol': symbol, 'currency': currency, 'amount': amount} path = '/v1/dw/transfer-out/margin' return api_key_post(params, path, _async=_async, url=self.url)
[ "def", "margin_to_exchange", "(", "self", ",", "symbol", ",", "currency", ",", "amount", ",", "_async", "=", "False", ")", ":", "params", "=", "{", "'symbol'", ":", "symbol", ",", "'currency'", ":", "currency", ",", "'amount'", ":", "amount", "}", "path"...
https://github.com/hadrianl/huobi/blob/7cfceba39189552489c1d9c88169f93109ee76ba/huobitrade/service.py#L532-L543
khanhnamle1994/natural-language-processing
01d450d5ac002b0156ef4cf93a07cb508c1bcdc5
assignment1/.env/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/_collections.py
python
HTTPHeaderDict.extend
(self, *args, **kwargs)
Generic import function for any type of header-like object. Adapted version of MutableMapping.update in order to insert items with self.add instead of self.__setitem__
Generic import function for any type of header-like object. Adapted version of MutableMapping.update in order to insert items with self.add instead of self.__setitem__
[ "Generic", "import", "function", "for", "any", "type", "of", "header", "-", "like", "object", ".", "Adapted", "version", "of", "MutableMapping", ".", "update", "in", "order", "to", "insert", "items", "with", "self", ".", "add", "instead", "of", "self", "."...
def extend(self, *args, **kwargs): """Generic import function for any type of header-like object. Adapted version of MutableMapping.update in order to insert items with self.add instead of self.__setitem__ """ if len(args) > 1: raise TypeError("extend() takes at most 1 positional " "arguments ({0} given)".format(len(args))) other = args[0] if len(args) >= 1 else () if isinstance(other, HTTPHeaderDict): for key, val in other.iteritems(): self.add(key, val) elif isinstance(other, Mapping): for key in other: self.add(key, other[key]) elif hasattr(other, "keys"): for key in other.keys(): self.add(key, other[key]) else: for key, value in other: self.add(key, value) for key, value in kwargs.items(): self.add(key, value)
[ "def", "extend", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "args", ")", ">", "1", ":", "raise", "TypeError", "(", "\"extend() takes at most 1 positional \"", "\"arguments ({0} given)\"", ".", "format", "(", "len", ...
https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/_collections.py#L231-L255
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/scipy/signal/ltisys.py
python
bode
(system, w=None, n=100)
return w, mag, phase
Calculate Bode magnitude and phase data of a continuous-time system. Parameters ---------- system : an instance of the LTI class or a tuple describing the system. The following gives the number of elements in the tuple and the interpretation: * 1 (instance of `lti`) * 2 (num, den) * 3 (zeros, poles, gain) * 4 (A, B, C, D) w : array_like, optional Array of frequencies (in rad/s). Magnitude and phase data is calculated for every value in this array. If not given a reasonable set will be calculated. n : int, optional Number of frequency points to compute if `w` is not given. The `n` frequencies are logarithmically spaced in an interval chosen to include the influence of the poles and zeros of the system. Returns ------- w : 1D ndarray Frequency array [rad/s] mag : 1D ndarray Magnitude array [dB] phase : 1D ndarray Phase array [deg] Notes ----- If (num, den) is passed in for ``system``, coefficients for both the numerator and denominator should be specified in descending exponent order (e.g. ``s^2 + 3s + 5`` would be represented as ``[1, 3, 5]``). .. versionadded:: 0.11.0 Examples -------- >>> from scipy import signal >>> import matplotlib.pyplot as plt >>> sys = signal.TransferFunction([1], [1, 1]) >>> w, mag, phase = signal.bode(sys) >>> plt.figure() >>> plt.semilogx(w, mag) # Bode magnitude plot >>> plt.figure() >>> plt.semilogx(w, phase) # Bode phase plot >>> plt.show()
Calculate Bode magnitude and phase data of a continuous-time system.
[ "Calculate", "Bode", "magnitude", "and", "phase", "data", "of", "a", "continuous", "-", "time", "system", "." ]
def bode(system, w=None, n=100): """ Calculate Bode magnitude and phase data of a continuous-time system. Parameters ---------- system : an instance of the LTI class or a tuple describing the system. The following gives the number of elements in the tuple and the interpretation: * 1 (instance of `lti`) * 2 (num, den) * 3 (zeros, poles, gain) * 4 (A, B, C, D) w : array_like, optional Array of frequencies (in rad/s). Magnitude and phase data is calculated for every value in this array. If not given a reasonable set will be calculated. n : int, optional Number of frequency points to compute if `w` is not given. The `n` frequencies are logarithmically spaced in an interval chosen to include the influence of the poles and zeros of the system. Returns ------- w : 1D ndarray Frequency array [rad/s] mag : 1D ndarray Magnitude array [dB] phase : 1D ndarray Phase array [deg] Notes ----- If (num, den) is passed in for ``system``, coefficients for both the numerator and denominator should be specified in descending exponent order (e.g. ``s^2 + 3s + 5`` would be represented as ``[1, 3, 5]``). .. versionadded:: 0.11.0 Examples -------- >>> from scipy import signal >>> import matplotlib.pyplot as plt >>> sys = signal.TransferFunction([1], [1, 1]) >>> w, mag, phase = signal.bode(sys) >>> plt.figure() >>> plt.semilogx(w, mag) # Bode magnitude plot >>> plt.figure() >>> plt.semilogx(w, phase) # Bode phase plot >>> plt.show() """ w, y = freqresp(system, w=w, n=n) mag = 20.0 * numpy.log10(abs(y)) phase = numpy.unwrap(numpy.arctan2(y.imag, y.real)) * 180.0 / numpy.pi return w, mag, phase
[ "def", "bode", "(", "system", ",", "w", "=", "None", ",", "n", "=", "100", ")", ":", "w", ",", "y", "=", "freqresp", "(", "system", ",", "w", "=", "w", ",", "n", "=", "n", ")", "mag", "=", "20.0", "*", "numpy", ".", "log10", "(", "abs", "...
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/scipy/signal/ltisys.py#L2341-L2402
golismero/golismero
7d605b937e241f51c1ca4f47b20f755eeefb9d76
thirdparty_libs/dns/grange.py
python
from_text
(text)
return (start, stop, step)
Convert the text form of a range in a GENERATE statement to an integer. @param text: the textual range @type text: string @return: The start, stop and step values. @rtype: tuple
Convert the text form of a range in a GENERATE statement to an integer.
[ "Convert", "the", "text", "form", "of", "a", "range", "in", "a", "GENERATE", "statement", "to", "an", "integer", "." ]
def from_text(text): """Convert the text form of a range in a GENERATE statement to an integer. @param text: the textual range @type text: string @return: The start, stop and step values. @rtype: tuple """ # TODO, figure out the bounds on start, stop and step. import pdb step = 1 cur = '' state = 0 # state 0 1 2 3 4 # x - y / z for c in text: if c == '-' and state == 0: start = int(cur) cur = '' state = 2 elif c == '/': stop = int(cur) cur = '' state = 4 elif c.isdigit(): cur += c else: raise dns.exception.SyntaxError("Could not parse %s" % (c)) if state in (1, 3): raise dns.exception.SyntaxError if state == 2: stop = int(cur) if state == 4: step = int(cur) assert step >= 1 assert start >= 0 assert start <= stop # TODO, can start == stop? return (start, stop, step)
[ "def", "from_text", "(", "text", ")", ":", "# TODO, figure out the bounds on start, stop and step.", "import", "pdb", "step", "=", "1", "cur", "=", "''", "state", "=", "0", "# state 0 1 2 3 4", "# x - y / z", "for", "c", "in", "text", ":", "if", "c", "...
https://github.com/golismero/golismero/blob/7d605b937e241f51c1ca4f47b20f755eeefb9d76/thirdparty_libs/dns/grange.py#L20-L65
XX-net/XX-Net
a9898cfcf0084195fb7e69b6bc834e59aecdf14f
python3.8.2/Lib/datetime.py
python
timedelta.total_seconds
(self)
return ((self.days * 86400 + self.seconds) * 10**6 + self.microseconds) / 10**6
Total seconds in the duration.
Total seconds in the duration.
[ "Total", "seconds", "in", "the", "duration", "." ]
def total_seconds(self): """Total seconds in the duration.""" return ((self.days * 86400 + self.seconds) * 10**6 + self.microseconds) / 10**6
[ "def", "total_seconds", "(", "self", ")", ":", "return", "(", "(", "self", ".", "days", "*", "86400", "+", "self", ".", "seconds", ")", "*", "10", "**", "6", "+", "self", ".", "microseconds", ")", "/", "10", "**", "6" ]
https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/datetime.py#L615-L618
qibinlou/SinaWeibo-Emotion-Classification
f336fc104abd68b0ec4180fe2ed80fafe49cb790
nltk/corpus/reader/wordnet.py
python
WordNetCorpusReader._compute_max_depth
(self, pos, simulate_root)
Compute the max depth for the given part of speech. This is used by the lch similarity metric.
Compute the max depth for the given part of speech. This is used by the lch similarity metric.
[ "Compute", "the", "max", "depth", "for", "the", "given", "part", "of", "speech", ".", "This", "is", "used", "by", "the", "lch", "similarity", "metric", "." ]
def _compute_max_depth(self, pos, simulate_root): """ Compute the max depth for the given part of speech. This is used by the lch similarity metric. """ depth = 0 for ii in self.all_synsets(pos): try: depth = max(depth, ii.max_depth()) except RuntimeError: print ii if simulate_root: depth += 1 self._max_depth[pos] = depth
[ "def", "_compute_max_depth", "(", "self", ",", "pos", ",", "simulate_root", ")", ":", "depth", "=", "0", "for", "ii", "in", "self", ".", "all_synsets", "(", "pos", ")", ":", "try", ":", "depth", "=", "max", "(", "depth", ",", "ii", ".", "max_depth", ...
https://github.com/qibinlou/SinaWeibo-Emotion-Classification/blob/f336fc104abd68b0ec4180fe2ed80fafe49cb790/nltk/corpus/reader/wordnet.py#L943-L956
misterch0c/shadowbroker
e3a069bea47a2c1009697941ac214adc6f90aa8d
windows/Resources/Python/Core/Lib/zipfile.py
python
ZipFile.setpassword
(self, pwd)
Set default password for encrypted files.
Set default password for encrypted files.
[ "Set", "default", "password", "for", "encrypted", "files", "." ]
def setpassword(self, pwd): """Set default password for encrypted files.""" self.pwd = pwd
[ "def", "setpassword", "(", "self", ",", "pwd", ")", ":", "self", ".", "pwd", "=", "pwd" ]
https://github.com/misterch0c/shadowbroker/blob/e3a069bea47a2c1009697941ac214adc6f90aa8d/windows/Resources/Python/Core/Lib/zipfile.py#L695-L697
marcomusy/vedo
246bb78a406c4f97fe6f7d2a4d460909c830de87
examples/simulations/particle_simulator.py
python
Particle.__init__
(self, pos, charge, mass, radius, color, vel, fixed, negligible)
Creates a new particle with specified properties (in SI units) pos: XYZ starting position of the particle, in meters charge: charge of the particle, in Coulombs mass: mass of the particle, in kg radius: radius of the particle, in meters. No effect on simulation color: color of the particle. If None, a default color will be chosen vel: initial velocity vector, in m/s fixed: if True, particle will remain fixed in place negligible: assume charge is small wrt other charges to speed up calculation
Creates a new particle with specified properties (in SI units)
[ "Creates", "a", "new", "particle", "with", "specified", "properties", "(", "in", "SI", "units", ")" ]
def __init__(self, pos, charge, mass, radius, color, vel, fixed, negligible): """ Creates a new particle with specified properties (in SI units) pos: XYZ starting position of the particle, in meters charge: charge of the particle, in Coulombs mass: mass of the particle, in kg radius: radius of the particle, in meters. No effect on simulation color: color of the particle. If None, a default color will be chosen vel: initial velocity vector, in m/s fixed: if True, particle will remain fixed in place negligible: assume charge is small wrt other charges to speed up calculation """ self.pos = vector(pos) self.radius = radius self.charge = charge self.mass = mass self.vel = vector(vel) self.fixed = fixed self.negligible = negligible self.color = color if plt: self.vsphere = Sphere(pos, r=radius, c=color).addTrail(alpha=1, maxlength=1, n=50) plt.add(self.vsphere, render=False)
[ "def", "__init__", "(", "self", ",", "pos", ",", "charge", ",", "mass", ",", "radius", ",", "color", ",", "vel", ",", "fixed", ",", "negligible", ")", ":", "self", ".", "pos", "=", "vector", "(", "pos", ")", "self", ".", "radius", "=", "radius", ...
https://github.com/marcomusy/vedo/blob/246bb78a406c4f97fe6f7d2a4d460909c830de87/examples/simulations/particle_simulator.py#L69-L92
sympy/sympy
d822fcba181155b85ff2b29fe525adbafb22b448
sympy/combinatorics/permutations.py
python
_af_commutes_with
(a, b)
return not any(a[b[i]] != b[a[i]] for i in range(len(a) - 1))
Checks if the two permutations with array forms given by ``a`` and ``b`` commute. Examples ======== >>> from sympy.combinatorics.permutations import _af_commutes_with >>> _af_commutes_with([1, 2, 0], [0, 2, 1]) False See Also ======== Permutation, commutes_with
Checks if the two permutations with array forms given by ``a`` and ``b`` commute.
[ "Checks", "if", "the", "two", "permutations", "with", "array", "forms", "given", "by", "a", "and", "b", "commute", "." ]
def _af_commutes_with(a, b): """ Checks if the two permutations with array forms given by ``a`` and ``b`` commute. Examples ======== >>> from sympy.combinatorics.permutations import _af_commutes_with >>> _af_commutes_with([1, 2, 0], [0, 2, 1]) False See Also ======== Permutation, commutes_with """ return not any(a[b[i]] != b[a[i]] for i in range(len(a) - 1))
[ "def", "_af_commutes_with", "(", "a", ",", "b", ")", ":", "return", "not", "any", "(", "a", "[", "b", "[", "i", "]", "]", "!=", "b", "[", "a", "[", "i", "]", "]", "for", "i", "in", "range", "(", "len", "(", "a", ")", "-", "1", ")", ")" ]
https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/combinatorics/permutations.py#L221-L238
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/utils/ui.py
python
RateLimiter.__init__
(self, min_update_interval_seconds)
[]
def __init__(self, min_update_interval_seconds): self._min_update_interval_seconds = min_update_interval_seconds self._last_update = 0
[ "def", "__init__", "(", "self", ",", "min_update_interval_seconds", ")", ":", "self", ".", "_min_update_interval_seconds", "=", "min_update_interval_seconds", "self", ".", "_last_update", "=", "0" ]
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/utils/ui.py#L236-L238
wrenfairbank/telegram_gcloner
5a64fa95c19c58032f2c64323358a4cb42cf1a30
telegram_gcloner/handlers/get_help.py
python
init
(dispatcher: Dispatcher)
Provide handlers initialization.
Provide handlers initialization.
[ "Provide", "handlers", "initialization", "." ]
def init(dispatcher: Dispatcher): """Provide handlers initialization.""" dispatcher.add_handler(CommandHandler('help', get_help))
[ "def", "init", "(", "dispatcher", ":", "Dispatcher", ")", ":", "dispatcher", ".", "add_handler", "(", "CommandHandler", "(", "'help'", ",", "get_help", ")", ")" ]
https://github.com/wrenfairbank/telegram_gcloner/blob/5a64fa95c19c58032f2c64323358a4cb42cf1a30/telegram_gcloner/handlers/get_help.py#L14-L16
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/galgebra/ga.py
python
MV.__add_ab__
(self, b)
return selfb
[]
def __add_ab__(self, b): # self += b selfb = MV() selfb.obj += b.obj return selfb
[ "def", "__add_ab__", "(", "self", ",", "b", ")", ":", "# self += b", "selfb", "=", "MV", "(", ")", "selfb", ".", "obj", "+=", "b", ".", "obj", "return", "selfb" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/galgebra/ga.py#L567-L570
minerllabs/minerl
0123527c334c96ebb3f0cf313df1552fa4302691
minerl/data/util/__init__.py
python
OrderedJobStreamer._ordered_job_streamer
(self)
[]
def _ordered_job_streamer(self): ex = self.executor(self.max_workers) def end_processes(): if ex is not None: if ex._processes is not None: for process in ex._processes.values(): try: process.kill() except: print("couldn;t kill process") pass ex.shutdown(wait=False) atexit.register(end_processes) try: results = queue.Queue() # Enqueue jobs for arg in tqdm.tqdm(self.job_args): results.put(ex.submit(self.job, arg)) # Dequeu jobs and push them to a queue. while not results.empty() and not self._should_exit: future = results.get() if future.exception(): raise future.exception() res = future.result() while not self._should_exit: try: self.output_queue.put(res, block=True, timeout=1) break except queue.Full: pass return except Exception: # abort workers immediately if anything goes wrong for process in ex._processes.values(): process.kill() raise finally: ex.shutdown(wait=False)
[ "def", "_ordered_job_streamer", "(", "self", ")", ":", "ex", "=", "self", ".", "executor", "(", "self", ".", "max_workers", ")", "def", "end_processes", "(", ")", ":", "if", "ex", "is", "not", "None", ":", "if", "ex", ".", "_processes", "is", "not", ...
https://github.com/minerllabs/minerl/blob/0123527c334c96ebb3f0cf313df1552fa4302691/minerl/data/util/__init__.py#L175-L220
fengsp/rc
32c4d4e2cb7ba734b2dbd9bd83bcc85a2f09499f
rc/cache.py
python
BaseCache.set_many
(self, mapping, expire=None)
return rv
Sets multiple keys and values using dictionary. The values expires in time seconds. :param mapping: a dictionary with key/values to set :param expire: expiration time :return: whether all keys has been set
Sets multiple keys and values using dictionary. The values expires in time seconds.
[ "Sets", "multiple", "keys", "and", "values", "using", "dictionary", ".", "The", "values", "expires", "in", "time", "seconds", "." ]
def set_many(self, mapping, expire=None): """Sets multiple keys and values using dictionary. The values expires in time seconds. :param mapping: a dictionary with key/values to set :param expire: expiration time :return: whether all keys has been set """ if not mapping: return True rv = True for key, value in mapping.iteritems(): if not self.set(key, value, expire): rv = False return rv
[ "def", "set_many", "(", "self", ",", "mapping", ",", "expire", "=", "None", ")", ":", "if", "not", "mapping", ":", "return", "True", "rv", "=", "True", "for", "key", ",", "value", "in", "mapping", ".", "iteritems", "(", ")", ":", "if", "not", "self...
https://github.com/fengsp/rc/blob/32c4d4e2cb7ba734b2dbd9bd83bcc85a2f09499f/rc/cache.py#L112-L126
gammapy/gammapy
735b25cd5bbed35e2004d633621896dcd5295e8b
gammapy/modeling/models/core.py
python
DatasetModels.from_dict
(cls, data, path="")
return models
Create from dict.
Create from dict.
[ "Create", "from", "dict", "." ]
def from_dict(cls, data, path=""): """Create from dict.""" from . import MODEL_REGISTRY, SkyModel models = [] for component in data["components"]: model_cls = MODEL_REGISTRY.get_cls(component["type"]) model = model_cls.from_dict(component) models.append(model) models = cls(models) if "covariance" in data: filename = data["covariance"] path = make_path(path) if not (path / filename).exists(): path, filename = split(filename) models.read_covariance(path, filename, format="ascii.fixed_width") shared_register = {} for model in models: if isinstance(model, SkyModel): submodels = [ model.spectral_model, model.spatial_model, model.temporal_model, ] for submodel in submodels: if submodel is not None: shared_register = _set_link(shared_register, submodel) else: shared_register = _set_link(shared_register, model) return models
[ "def", "from_dict", "(", "cls", ",", "data", ",", "path", "=", "\"\"", ")", ":", "from", ".", "import", "MODEL_REGISTRY", ",", "SkyModel", "models", "=", "[", "]", "for", "component", "in", "data", "[", "\"components\"", "]", ":", "model_cls", "=", "MO...
https://github.com/gammapy/gammapy/blob/735b25cd5bbed35e2004d633621896dcd5295e8b/gammapy/modeling/models/core.py#L382-L416
Huangying-Zhan/DF-VO
6a2ec43fc6209d9058ae1709d779c5ada68a31f3
libs/datasets/kinect.py
python
Kinect.update_gt_pose
(self)
Update GT pose according to sync pairs
Update GT pose according to sync pairs
[ "Update", "GT", "pose", "according", "to", "sync", "pairs" ]
def update_gt_pose(self): """Update GT pose according to sync pairs """ # Update gt pose self.tmp_gt_poses = {} sorted_timestamps = sorted(list(self.rgb_d_pose_pair.keys())) gt_pose_0_time = self.rgb_d_pose_pair[sorted_timestamps[0]]['pose'] gt_pose_0 = self.gt_poses[gt_pose_0_time] i = 0 for rgb_stamp in sorted(list(self.rgb_d_pose_pair.keys())): if self.rgb_d_pose_pair[rgb_stamp].get('pose', -1) != -1: self.tmp_gt_poses[i] = np.linalg.inv(gt_pose_0) @ self.gt_poses[self.rgb_d_pose_pair[rgb_stamp]['pose']] else: self.tmp_gt_poses[i] = np.eye(4) i += 1 self.gt_poses = copy.deepcopy(self.tmp_gt_poses)
[ "def", "update_gt_pose", "(", "self", ")", ":", "# Update gt pose", "self", ".", "tmp_gt_poses", "=", "{", "}", "sorted_timestamps", "=", "sorted", "(", "list", "(", "self", ".", "rgb_d_pose_pair", ".", "keys", "(", ")", ")", ")", "gt_pose_0_time", "=", "s...
https://github.com/Huangying-Zhan/DF-VO/blob/6a2ec43fc6209d9058ae1709d779c5ada68a31f3/libs/datasets/kinect.py#L102-L118
microsoft/azure-devops-python-api
451cade4c475482792cbe9e522c1fee32393139e
azure-devops/azure/devops/v6_0/git/git_client_base.py
python
GitClientBase.create_pull_request_status
(self, status, repository_id, pull_request_id, project=None)
return self._deserialize('GitPullRequestStatus', response)
CreatePullRequestStatus. [Preview API] Create a pull request status. :param :class:`<GitPullRequestStatus> <azure.devops.v6_0.git.models.GitPullRequestStatus>` status: Pull request status to create. :param str repository_id: The repository ID of the pull request’s target branch. :param int pull_request_id: ID of the pull request. :param str project: Project ID or project name :rtype: :class:`<GitPullRequestStatus> <azure.devops.v6_0.git.models.GitPullRequestStatus>`
CreatePullRequestStatus. [Preview API] Create a pull request status. :param :class:`<GitPullRequestStatus> <azure.devops.v6_0.git.models.GitPullRequestStatus>` status: Pull request status to create. :param str repository_id: The repository ID of the pull request’s target branch. :param int pull_request_id: ID of the pull request. :param str project: Project ID or project name :rtype: :class:`<GitPullRequestStatus> <azure.devops.v6_0.git.models.GitPullRequestStatus>`
[ "CreatePullRequestStatus", ".", "[", "Preview", "API", "]", "Create", "a", "pull", "request", "status", ".", ":", "param", ":", "class", ":", "<GitPullRequestStatus", ">", "<azure", ".", "devops", ".", "v6_0", ".", "git", ".", "models", ".", "GitPullRequestS...
def create_pull_request_status(self, status, repository_id, pull_request_id, project=None): """CreatePullRequestStatus. [Preview API] Create a pull request status. :param :class:`<GitPullRequestStatus> <azure.devops.v6_0.git.models.GitPullRequestStatus>` status: Pull request status to create. :param str repository_id: The repository ID of the pull request’s target branch. :param int pull_request_id: ID of the pull request. :param str project: Project ID or project name :rtype: :class:`<GitPullRequestStatus> <azure.devops.v6_0.git.models.GitPullRequestStatus>` """ route_values = {} if project is not None: route_values['project'] = self._serialize.url('project', project, 'str') if repository_id is not None: route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str') if pull_request_id is not None: route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int') content = self._serialize.body(status, 'GitPullRequestStatus') response = self._send(http_method='POST', location_id='b5f6bb4f-8d1e-4d79-8d11-4c9172c99c35', version='6.0-preview.1', route_values=route_values, content=content) return self._deserialize('GitPullRequestStatus', response)
[ "def", "create_pull_request_status", "(", "self", ",", "status", ",", "repository_id", ",", "pull_request_id", ",", "project", "=", "None", ")", ":", "route_values", "=", "{", "}", "if", "project", "is", "not", "None", ":", "route_values", "[", "'project'", ...
https://github.com/microsoft/azure-devops-python-api/blob/451cade4c475482792cbe9e522c1fee32393139e/azure-devops/azure/devops/v6_0/git/git_client_base.py#L2273-L2295
jameslyons/pycipher
8f1d7cf3cba4e12171e27d9ce723ad890194de19
pycipher/enigma.py
python
Enigma.encipher
(self,string)
return ret
Encipher string using Enigma M3 cipher according to initialised key. Punctuation and whitespace are removed from the input. Example:: ciphertext = Enigma(settings=('A','A','A'),rotors=(1,2,3),reflector='B', ringstellung=('F','V','N'),steckers=[('P','O'),('M','L'), ('I','U'),('K','J'),('N','H'),('Y','T'),('G','B'),('V','F'), ('R','E'),('D','C')])).encipher(plaintext) :param string: The string to encipher. :returns: The enciphered string.
Encipher string using Enigma M3 cipher according to initialised key. Punctuation and whitespace are removed from the input.
[ "Encipher", "string", "using", "Enigma", "M3", "cipher", "according", "to", "initialised", "key", ".", "Punctuation", "and", "whitespace", "are", "removed", "from", "the", "input", "." ]
def encipher(self,string): """Encipher string using Enigma M3 cipher according to initialised key. Punctuation and whitespace are removed from the input. Example:: ciphertext = Enigma(settings=('A','A','A'),rotors=(1,2,3),reflector='B', ringstellung=('F','V','N'),steckers=[('P','O'),('M','L'), ('I','U'),('K','J'),('N','H'),('Y','T'),('G','B'),('V','F'), ('R','E'),('D','C')])).encipher(plaintext) :param string: The string to encipher. :returns: The enciphered string. """ string = self.remove_punctuation(string) ret = '' for c in string.upper(): if c.isalpha(): ret += self.encipher_char(c) else: ret += c return ret
[ "def", "encipher", "(", "self", ",", "string", ")", ":", "string", "=", "self", ".", "remove_punctuation", "(", "string", ")", "ret", "=", "''", "for", "c", "in", "string", ".", "upper", "(", ")", ":", "if", "c", ".", "isalpha", "(", ")", ":", "r...
https://github.com/jameslyons/pycipher/blob/8f1d7cf3cba4e12171e27d9ce723ad890194de19/pycipher/enigma.py#L128-L147
aabouzaid/netbox-as-ansible-inventory
0582ecfdb4a5c9faaf0d63c441a39988b02b0be0
netbox/netbox.py
python
NetboxAsInventory.add_host_to_group
(server_name, group_value, inventory_dict)
return inventory_dict
Add a host to a single group. It checks if host in a group and adds the host to that group. The group will be added if it's not in the inventory. Args: server_name: String, the server that will be added to a group. group_value: String, name that will be used as a group in the inventory. inventory_dict: Dict, the inventory which will be updated. Returns: The dict "inventory_dict" after adding the host to its group/s.
Add a host to a single group.
[ "Add", "a", "host", "to", "a", "single", "group", "." ]
def add_host_to_group(server_name, group_value, inventory_dict): """Add a host to a single group. It checks if host in a group and adds the host to that group. The group will be added if it's not in the inventory. Args: server_name: String, the server that will be added to a group. group_value: String, name that will be used as a group in the inventory. inventory_dict: Dict, the inventory which will be updated. Returns: The dict "inventory_dict" after adding the host to its group/s. """ # The value could be None/null. if server_name and group_value: # If the group not in the inventory it will be add. if group_value not in inventory_dict: inventory_dict.update({group_value: []}) # If the host not in the group it will be add. if server_name not in inventory_dict[group_value]: inventory_dict[group_value].append(server_name) return inventory_dict
[ "def", "add_host_to_group", "(", "server_name", ",", "group_value", ",", "inventory_dict", ")", ":", "# The value could be None/null.", "if", "server_name", "and", "group_value", ":", "# If the group not in the inventory it will be add.", "if", "group_value", "not", "in", "...
https://github.com/aabouzaid/netbox-as-ansible-inventory/blob/0582ecfdb4a5c9faaf0d63c441a39988b02b0be0/netbox/netbox.py#L195-L219
mdiazcl/fuzzbunch-debian
2b76c2249ade83a389ae3badb12a1bd09901fd2c
windows/Resources/Python/Core/Lib/distutils/util.py
python
byte_compile
(py_files, optimize=0, force=0, prefix=None, base_dir=None, verbose=1, dry_run=0, direct=None)
return
Byte-compile a collection of Python source files to either .pyc or .pyo files in the same directory. 'py_files' is a list of files to compile; any files that don't end in ".py" are silently skipped. 'optimize' must be one of the following: 0 - don't optimize (generate .pyc) 1 - normal optimization (like "python -O") 2 - extra optimization (like "python -OO") If 'force' is true, all files are recompiled regardless of timestamps. The source filename encoded in each bytecode file defaults to the filenames listed in 'py_files'; you can modify these with 'prefix' and 'basedir'. 'prefix' is a string that will be stripped off of each source filename, and 'base_dir' is a directory name that will be prepended (after 'prefix' is stripped). You can supply either or both (or neither) of 'prefix' and 'base_dir', as you wish. If 'dry_run' is true, doesn't actually do anything that would affect the filesystem. Byte-compilation is either done directly in this interpreter process with the standard py_compile module, or indirectly by writing a temporary script and executing it. Normally, you should let 'byte_compile()' figure out to use direct compilation or not (see the source for details). The 'direct' flag is used by the script generated in indirect mode; unless you know what you're doing, leave it set to None.
Byte-compile a collection of Python source files to either .pyc or .pyo files in the same directory. 'py_files' is a list of files to compile; any files that don't end in ".py" are silently skipped. 'optimize' must be one of the following: 0 - don't optimize (generate .pyc) 1 - normal optimization (like "python -O") 2 - extra optimization (like "python -OO") If 'force' is true, all files are recompiled regardless of timestamps. The source filename encoded in each bytecode file defaults to the filenames listed in 'py_files'; you can modify these with 'prefix' and 'basedir'. 'prefix' is a string that will be stripped off of each source filename, and 'base_dir' is a directory name that will be prepended (after 'prefix' is stripped). You can supply either or both (or neither) of 'prefix' and 'base_dir', as you wish. If 'dry_run' is true, doesn't actually do anything that would affect the filesystem. Byte-compilation is either done directly in this interpreter process with the standard py_compile module, or indirectly by writing a temporary script and executing it. Normally, you should let 'byte_compile()' figure out to use direct compilation or not (see the source for details). The 'direct' flag is used by the script generated in indirect mode; unless you know what you're doing, leave it set to None.
[ "Byte", "-", "compile", "a", "collection", "of", "Python", "source", "files", "to", "either", ".", "pyc", "or", ".", "pyo", "files", "in", "the", "same", "directory", ".", "py_files", "is", "a", "list", "of", "files", "to", "compile", ";", "any", "file...
def byte_compile(py_files, optimize=0, force=0, prefix=None, base_dir=None, verbose=1, dry_run=0, direct=None): """Byte-compile a collection of Python source files to either .pyc or .pyo files in the same directory. 'py_files' is a list of files to compile; any files that don't end in ".py" are silently skipped. 'optimize' must be one of the following: 0 - don't optimize (generate .pyc) 1 - normal optimization (like "python -O") 2 - extra optimization (like "python -OO") If 'force' is true, all files are recompiled regardless of timestamps. The source filename encoded in each bytecode file defaults to the filenames listed in 'py_files'; you can modify these with 'prefix' and 'basedir'. 'prefix' is a string that will be stripped off of each source filename, and 'base_dir' is a directory name that will be prepended (after 'prefix' is stripped). You can supply either or both (or neither) of 'prefix' and 'base_dir', as you wish. If 'dry_run' is true, doesn't actually do anything that would affect the filesystem. Byte-compilation is either done directly in this interpreter process with the standard py_compile module, or indirectly by writing a temporary script and executing it. Normally, you should let 'byte_compile()' figure out to use direct compilation or not (see the source for details). The 'direct' flag is used by the script generated in indirect mode; unless you know what you're doing, leave it set to None. """ if sys.dont_write_bytecode: raise DistutilsByteCompileError('byte-compiling is disabled.') if direct is None: direct = __debug__ and optimize == 0 if not direct: try: from tempfile import mkstemp script_fd, script_name = mkstemp('.py') except ImportError: from tempfile import mktemp script_fd, script_name = None, mktemp('.py') log.info("writing byte-compilation script '%s'", script_name) if not dry_run: if script_fd is not None: script = os.fdopen(script_fd, 'w') else: script = open(script_name, 'w') script.write('from distutils.util import byte_compile\nfiles = [\n') script.write(string.join(map(repr, py_files), ',\n') + ']\n') script.write('\nbyte_compile(files, optimize=%r, force=%r,\n prefix=%r, base_dir=%r,\n verbose=%r, dry_run=0,\n direct=1)\n' % (optimize, force, prefix, base_dir, verbose)) script.close() cmd = [sys.executable, script_name] if optimize == 1: cmd.insert(1, '-O') elif optimize == 2: cmd.insert(1, '-OO') spawn(cmd, dry_run=dry_run) execute(os.remove, (script_name,), 'removing %s' % script_name, dry_run=dry_run) else: from py_compile import compile for file in py_files: if file[-3:] != '.py': continue cfile = file + (__debug__ and 'c' or 'o') dfile = file if prefix: if file[:len(prefix)] != prefix: raise ValueError, "invalid prefix: filename %r doesn't start with %r" % ( file, prefix) dfile = dfile[len(prefix):] if base_dir: dfile = os.path.join(base_dir, dfile) cfile_base = os.path.basename(cfile) if direct: if force or newer(file, cfile): log.info('byte-compiling %s to %s', file, cfile_base) if not dry_run: compile(file, cfile, dfile) else: log.debug('skipping byte-compilation of %s to %s', file, cfile_base) return
[ "def", "byte_compile", "(", "py_files", ",", "optimize", "=", "0", ",", "force", "=", "0", ",", "prefix", "=", "None", ",", "base_dir", "=", "None", ",", "verbose", "=", "1", ",", "dry_run", "=", "0", ",", "direct", "=", "None", ")", ":", "if", "...
https://github.com/mdiazcl/fuzzbunch-debian/blob/2b76c2249ade83a389ae3badb12a1bd09901fd2c/windows/Resources/Python/Core/Lib/distutils/util.py#L342-L423
TadaSoftware/PyNFe
a54de70b92553596f09a57cbe3a207880eafcd93
pynfe/entidades/notafiscal.py
python
NotaFiscal.adicionar_observacao_contribuinte
(self, **kwargs)
return obj
u"""Adiciona uma instancia de Observacao do Contribuinte
u"""Adiciona uma instancia de Observacao do Contribuinte
[ "u", "Adiciona", "uma", "instancia", "de", "Observacao", "do", "Contribuinte" ]
def adicionar_observacao_contribuinte(self, **kwargs): u"""Adiciona uma instancia de Observacao do Contribuinte""" obj = NotaFiscalObservacaoContribuinte(**kwargs) self.observacoes_contribuinte.append(obj) return obj
[ "def", "adicionar_observacao_contribuinte", "(", "self", ",", "*", "*", "kwargs", ")", ":", "obj", "=", "NotaFiscalObservacaoContribuinte", "(", "*", "*", "kwargs", ")", "self", ".", "observacoes_contribuinte", ".", "append", "(", "obj", ")", "return", "obj" ]
https://github.com/TadaSoftware/PyNFe/blob/a54de70b92553596f09a57cbe3a207880eafcd93/pynfe/entidades/notafiscal.py#L435-L439
fabianp/mord
ef578a79bf8374d84b77f246454b06d81a620630
mord/threshold_based.py
python
obj_margin
(x0, X, y, alpha, n_class, weights, L, sample_weight)
return obj
Objective function for the general margin-based formulation
Objective function for the general margin-based formulation
[ "Objective", "function", "for", "the", "general", "margin", "-", "based", "formulation" ]
def obj_margin(x0, X, y, alpha, n_class, weights, L, sample_weight): """ Objective function for the general margin-based formulation """ w = x0[:X.shape[1]] c = x0[X.shape[1]:] theta = L.dot(c) loss_fd = weights[y] Xw = X.dot(w) Alpha = theta[:, None] - Xw # (n_class - 1, n_samples) S = np.sign(np.arange(n_class - 1)[:, None] - y + 0.5) err = loss_fd.T * log_loss(S * Alpha) if sample_weight is not None: err *= sample_weight obj = np.sum(err) obj += alpha * 0.5 * (np.dot(w, w)) return obj
[ "def", "obj_margin", "(", "x0", ",", "X", ",", "y", ",", "alpha", ",", "n_class", ",", "weights", ",", "L", ",", "sample_weight", ")", ":", "w", "=", "x0", "[", ":", "X", ".", "shape", "[", "1", "]", "]", "c", "=", "x0", "[", "X", ".", "sha...
https://github.com/fabianp/mord/blob/ef578a79bf8374d84b77f246454b06d81a620630/mord/threshold_based.py#L33-L52
python-mechanize/mechanize
3cd4d19ee701d9aa458fa23b7515c268d3f1cef0
mechanize/_form_controls.py
python
HTMLForm._pairs_and_controls
(self)
return pairs
Return sequence of (index, key, value, control_index) of totally ordered pairs suitable for urlencoding. control_index is the index of the control in self.controls
Return sequence of (index, key, value, control_index) of totally ordered pairs suitable for urlencoding.
[ "Return", "sequence", "of", "(", "index", "key", "value", "control_index", ")", "of", "totally", "ordered", "pairs", "suitable", "for", "urlencoding", "." ]
def _pairs_and_controls(self): """Return sequence of (index, key, value, control_index) of totally ordered pairs suitable for urlencoding. control_index is the index of the control in self.controls """ pairs = [] for control_index in range(len(self.controls)): control = self.controls[control_index] for ii, key, val in control._totally_ordered_pairs(): if ii is None: ii = -1 pairs.append((ii, key, val, control_index)) # stable sort by ONLY first item in tuple pairs.sort() return pairs
[ "def", "_pairs_and_controls", "(", "self", ")", ":", "pairs", "=", "[", "]", "for", "control_index", "in", "range", "(", "len", "(", "self", ".", "controls", ")", ")", ":", "control", "=", "self", ".", "controls", "[", "control_index", "]", "for", "ii"...
https://github.com/python-mechanize/mechanize/blob/3cd4d19ee701d9aa458fa23b7515c268d3f1cef0/mechanize/_form_controls.py#L2488-L2505
quic/aimet
dae9bae9a77ca719aa7553fefde4768270fc3518
TrainingExtensions/tensorflow/src/python/aimet_tensorflow/bias_correction.py
python
BiasCorrection._get_quantized_weights
(weight_tensor, quant_params)
return q_wt_tensor
helper function to get quantized dequantized weights :param weight_tensor: weight tensor :param quant_params: quantization params such as mode, rounding etc :return: quantized de-quantized weight tensor
helper function to get quantized dequantized weights :param weight_tensor: weight tensor :param quant_params: quantization params such as mode, rounding etc :return: quantized de-quantized weight tensor
[ "helper", "function", "to", "get", "quantized", "dequantized", "weights", ":", "param", "weight_tensor", ":", "weight", "tensor", ":", "param", "quant_params", ":", "quantization", "params", "such", "as", "mode", "rounding", "etc", ":", "return", ":", "quantized...
def _get_quantized_weights(weight_tensor, quant_params): """ helper function to get quantized dequantized weights :param weight_tensor: weight tensor :param quant_params: quantization params such as mode, rounding etc :return: quantized de-quantized weight tensor """ q_wt_tensor = weight_tensor quant_mode = libpymo.QuantizationMode.QUANTIZATION_TF_ENHANCED if quant_params.quant_mode == QuantScheme.post_training_tf or quant_params.quant_mode == 'tf': quant_mode = libpymo.QuantizationMode.QUANTIZATION_TF round_mode = libpymo.RoundingMode.ROUND_NEAREST if quant_params.round_mode == 'stochastic': round_mode = libpymo.RoundingMode.ROUND_STOCHASTIC bitwidth = 8 # use tensorQuantizerForPython to get quantizeDequantize weights encoding_analyzer = libpymo.EncodingAnalyzerForPython(quant_mode) encoding_analyzer.updateStats(weight_tensor, quant_params.use_cuda) encoding, is_encoding_valid = encoding_analyzer.computeEncoding(bitwidth, False, False, False) if is_encoding_valid: tensor_quantizer = libpymo.TensorQuantizationSimForPython() q_wt_tensor = tensor_quantizer.quantizeDequantize(weight_tensor, encoding, round_mode, quant_params.use_cuda) return q_wt_tensor
[ "def", "_get_quantized_weights", "(", "weight_tensor", ",", "quant_params", ")", ":", "q_wt_tensor", "=", "weight_tensor", "quant_mode", "=", "libpymo", ".", "QuantizationMode", ".", "QUANTIZATION_TF_ENHANCED", "if", "quant_params", ".", "quant_mode", "==", "QuantScheme...
https://github.com/quic/aimet/blob/dae9bae9a77ca719aa7553fefde4768270fc3518/TrainingExtensions/tensorflow/src/python/aimet_tensorflow/bias_correction.py#L291-L320
liiight/notifiers
cf42feb55029482fa07b2cb0e40daecd375a6446
notifiers_cli/utils/dynamic_click.py
python
clean_data
(data: dict)
return new_data
Removes all empty values and converts tuples into lists
Removes all empty values and converts tuples into lists
[ "Removes", "all", "empty", "values", "and", "converts", "tuples", "into", "lists" ]
def clean_data(data: dict) -> dict: """Removes all empty values and converts tuples into lists""" new_data = {} for key, value in data.items(): # Verify that only explicitly passed args get passed on if not isinstance(value, bool) and not value: continue # Multiple choice command are passed as tuples, convert to list to match schema if isinstance(value, tuple): value = list(value) new_data[key] = value return new_data
[ "def", "clean_data", "(", "data", ":", "dict", ")", "->", "dict", ":", "new_data", "=", "{", "}", "for", "key", ",", "value", "in", "data", ".", "items", "(", ")", ":", "# Verify that only explicitly passed args get passed on", "if", "not", "isinstance", "("...
https://github.com/liiight/notifiers/blob/cf42feb55029482fa07b2cb0e40daecd375a6446/notifiers_cli/utils/dynamic_click.py#L70-L82
Amulet-Team/Amulet-Map-Editor
e99619ba6aab855173b9f7c203455944ab97f89a
versioneer.py
python
register_vcs_handler
(vcs, method)
return decorate
Decorator to mark a method as the handler for a particular VCS.
Decorator to mark a method as the handler for a particular VCS.
[ "Decorator", "to", "mark", "a", "method", "as", "the", "handler", "for", "a", "particular", "VCS", "." ]
def register_vcs_handler(vcs, method): # decorator """Decorator to mark a method as the handler for a particular VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate
[ "def", "register_vcs_handler", "(", "vcs", ",", "method", ")", ":", "# decorator", "def", "decorate", "(", "f", ")", ":", "\"\"\"Store f in HANDLERS[vcs][method].\"\"\"", "if", "vcs", "not", "in", "HANDLERS", ":", "HANDLERS", "[", "vcs", "]", "=", "{", "}", ...
https://github.com/Amulet-Team/Amulet-Map-Editor/blob/e99619ba6aab855173b9f7c203455944ab97f89a/versioneer.py#L378-L388
OmkarPathak/pygorithm
be35813729a0151da1ac9ba013453a61ffa249b8
pygorithm/data_structures/trie.py
python
Trie.search
(self, word)
Searches for given word in trie. We want to find the last node for the word. If we can't, then it means the word is not in the trie.
Searches for given word in trie. We want to find the last node for the word. If we can't, then it means the word is not in the trie.
[ "Searches", "for", "given", "word", "in", "trie", ".", "We", "want", "to", "find", "the", "last", "node", "for", "the", "word", ".", "If", "we", "can", "t", "then", "it", "means", "the", "word", "is", "not", "in", "the", "trie", "." ]
def search(self, word): """ Searches for given word in trie. We want to find the last node for the word. If we can't, then it means the word is not in the trie. """ if self.find_final_node(word): return True else: return False
[ "def", "search", "(", "self", ",", "word", ")", ":", "if", "self", ".", "find_final_node", "(", "word", ")", ":", "return", "True", "else", ":", "return", "False" ]
https://github.com/OmkarPathak/pygorithm/blob/be35813729a0151da1ac9ba013453a61ffa249b8/pygorithm/data_structures/trie.py#L41-L49
pnprog/goreviewpartner
cbcc486cd4c51fb6fc3bc0a1eab61ff34298dadf
gomill/sgf.py
python
Sgf_game.extend_main_sequence
(self)
return self.get_last_node().new_child()
Create a new Tree_node and add to the 'leftmost' variation. Returns the new node.
Create a new Tree_node and add to the 'leftmost' variation.
[ "Create", "a", "new", "Tree_node", "and", "add", "to", "the", "leftmost", "variation", "." ]
def extend_main_sequence(self): """Create a new Tree_node and add to the 'leftmost' variation. Returns the new node. """ return self.get_last_node().new_child()
[ "def", "extend_main_sequence", "(", "self", ")", ":", "return", "self", ".", "get_last_node", "(", ")", ".", "new_child", "(", ")" ]
https://github.com/pnprog/goreviewpartner/blob/cbcc486cd4c51fb6fc3bc0a1eab61ff34298dadf/gomill/sgf.py#L708-L714
linksense/LightNet
58353b28d33e69cc877db878c4a888aabc2118ce
models/rfshufflenetv2plus.py
python
conv3x3
(in_channels, out_channels, stride=1, bias=True, groups=1, dilate=1)
return nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=dilate, bias=bias, groups=groups, dilation=dilate)
3x3 convolution with padding
3x3 convolution with padding
[ "3x3", "convolution", "with", "padding" ]
def conv3x3(in_channels, out_channels, stride=1, bias=True, groups=1, dilate=1): """3x3 convolution with padding """ return nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=dilate, bias=bias, groups=groups, dilation=dilate)
[ "def", "conv3x3", "(", "in_channels", ",", "out_channels", ",", "stride", "=", "1", ",", "bias", "=", "True", ",", "groups", "=", "1", ",", "dilate", "=", "1", ")", ":", "return", "nn", ".", "Conv2d", "(", "in_channels", ",", "out_channels", ",", "ke...
https://github.com/linksense/LightNet/blob/58353b28d33e69cc877db878c4a888aabc2118ce/models/rfshufflenetv2plus.py#L11-L15
LCAV/pyroomacoustics
15a86425b68969b2109860ca3614f0cbf92b1bd0
pyroomacoustics/beamforming.py
python
Beamformer.steering_vector_2D_from_point
(self, frequency, source, attn=True, ff=False)
Creates a steering vector for a particular frequency and source Args: frequency source: location in cartesian coordinates attn: include attenuation factor if True ff: uses far-field distance if true Return: A 2x1 ndarray containing the steering vector.
Creates a steering vector for a particular frequency and source Args: frequency source: location in cartesian coordinates attn: include attenuation factor if True ff: uses far-field distance if true Return: A 2x1 ndarray containing the steering vector.
[ "Creates", "a", "steering", "vector", "for", "a", "particular", "frequency", "and", "source", "Args", ":", "frequency", "source", ":", "location", "in", "cartesian", "coordinates", "attn", ":", "include", "attenuation", "factor", "if", "True", "ff", ":", "uses...
def steering_vector_2D_from_point(self, frequency, source, attn=True, ff=False): """Creates a steering vector for a particular frequency and source Args: frequency source: location in cartesian coordinates attn: include attenuation factor if True ff: uses far-field distance if true Return: A 2x1 ndarray containing the steering vector. """ X = np.array(source) if X.ndim == 1: X = source[:, np.newaxis] omega = 2 * np.pi * frequency # normalize for far-field if requested if ff: # unit vectors pointing towards sources p = X - self.center p /= np.linalg.norm(p) # The projected microphone distances on the unit vectors D = -1 * np.dot(self.R.T, p) # subtract minimum in each column D -= np.min(D) else: D = distance(self.R, X) phase = np.exp(-1j * omega * D / constants.get("c")) if attn: # TO DO 1: This will mean slightly different absolute value for # every entry, even within the same steering vector. Perhaps a # better paradigm is far-field with phase carrier. return 1.0 / (4 * np.pi) / D * phase else: return phase
[ "def", "steering_vector_2D_from_point", "(", "self", ",", "frequency", ",", "source", ",", "attn", "=", "True", ",", "ff", "=", "False", ")", ":", "X", "=", "np", ".", "array", "(", "source", ")", "if", "X", ".", "ndim", "==", "1", ":", "X", "=", ...
https://github.com/LCAV/pyroomacoustics/blob/15a86425b68969b2109860ca3614f0cbf92b1bd0/pyroomacoustics/beamforming.py#L672-L713