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
hudora/huBarcode
e89cc42a4325aaab20297fecd33a785061633bed
hubarcode/datamatrix/textencoder.py
python
TextEncoder.pad
(self)
Pad out the encoded text to the correct word length
Pad out the encoded text to the correct word length
[ "Pad", "out", "the", "encoded", "text", "to", "the", "correct", "word", "length" ]
def pad(self): """Pad out the encoded text to the correct word length""" unpadded_len = len(self.codewords) log.debug("Unpadded data size: %d bytes", unpadded_len) # Work out how big the matrix needs to be for self.size_index, length in enumerate(data_word_length): if length >= unpadded_len: break if self.size_index > 8: log.error("Data too big") sys.exit(0) # Number of characters with which the data will be padded padsize = length - unpadded_len log.debug("Pad size: %d bytes", padsize) # First pad character is 129 if padsize: self.codewords += chr(129) def rand253(pos): """generate the next padding character""" rnd = ((149 * pos) % 253) + 1 return (129 + rnd) % 254 # Remaining pad characters generated by 253-state algorithm for i in range(1, padsize): self.codewords += chr(rand253(unpadded_len + i + 1)) log.debug("Word size after padding: %d bytes", len(self.codewords))
[ "def", "pad", "(", "self", ")", ":", "unpadded_len", "=", "len", "(", "self", ".", "codewords", ")", "log", ".", "debug", "(", "\"Unpadded data size: %d bytes\"", ",", "unpadded_len", ")", "# Work out how big the matrix needs to be", "for", "self", ".", "size_in...
https://github.com/hudora/huBarcode/blob/e89cc42a4325aaab20297fecd33a785061633bed/hubarcode/datamatrix/textencoder.py#L82-L115
algolia/color-extractor
3f1d5753cb418a3461d9b350e907c4d1d693d590
color_extractor/name.py
python
Name._knn_args
()
return { 'n_neighbors': 50, 'weights': 'distance', 'n_jobs': -1, }
Return the default arguments used by the `KNeighborsClassifier`
Return the default arguments used by the `KNeighborsClassifier`
[ "Return", "the", "default", "arguments", "used", "by", "the", "KNeighborsClassifier" ]
def _knn_args(): """Return the default arguments used by the `KNeighborsClassifier`""" return { 'n_neighbors': 50, 'weights': 'distance', 'n_jobs': -1, }
[ "def", "_knn_args", "(", ")", ":", "return", "{", "'n_neighbors'", ":", "50", ",", "'weights'", ":", "'distance'", ",", "'n_jobs'", ":", "-", "1", ",", "}" ]
https://github.com/algolia/color-extractor/blob/3f1d5753cb418a3461d9b350e907c4d1d693d590/color_extractor/name.py#L123-L129
jacoxu/encoder_decoder
6829c3bc42105aedfd1b8a81c81be19df4326c0a
keras/models.py
python
Sequential._check_generator_output
(self, generator_output, stop)
return X, y, sample_weight
Validates the output of a generator. On error, calls stop.set(). # Arguments generator_output: output of a data generator. stop: threading event to be called to interrupt training/evaluation.
Validates the output of a generator. On error, calls stop.set().
[ "Validates", "the", "output", "of", "a", "generator", ".", "On", "error", "calls", "stop", ".", "set", "()", "." ]
def _check_generator_output(self, generator_output, stop): '''Validates the output of a generator. On error, calls stop.set(). # Arguments generator_output: output of a data generator. stop: threading event to be called to interrupt training/evaluation. ''' if not hasattr(generator_output, '__len__'): stop.set() raise Exception('The generator output must be a tuple. Found: ' + str(type(generator_output))) if len(generator_output) == 2: X, y = generator_output if type(X) == list: assert len(set([len(a) for a in X] + [len(y)])) == 1 else: assert len(X) == len(y) X = [X] sample_weight = None elif len(generator_output) == 3: X, y, sample_weight = generator_output if type(X) == list: assert len(set([len(a) for a in X] + [len(y), len(sample_weight)])) == 1 else: assert len(X) == len(y) == len(sample_weight) X = [X] else: stop.set() raise Exception('The generator output tuple must have ' '2 or 3 elements.') sample_weight = standardize_weights(y, sample_weight=sample_weight, sample_weight_mode=self.sample_weight_mode) return X, y, sample_weight
[ "def", "_check_generator_output", "(", "self", ",", "generator_output", ",", "stop", ")", ":", "if", "not", "hasattr", "(", "generator_output", ",", "'__len__'", ")", ":", "stop", ".", "set", "(", ")", "raise", "Exception", "(", "'The generator output must be a ...
https://github.com/jacoxu/encoder_decoder/blob/6829c3bc42105aedfd1b8a81c81be19df4326c0a/keras/models.py#L912-L948
OUCMachineLearning/OUCML
5b54337d7c0316084cb1a74befda2bba96137d4a
GAN/人脸还原SCFEGAN/ui/ui.py
python
Ui_Form.setupUi
(self, Form)
[]
def setupUi(self, Form): Form.setObjectName("Form") Form.resize(1200, 660) self.pushButton = QtWidgets.QPushButton(Form) self.pushButton.setGeometry(QtCore.QRect(10, 10, 97, 27)) self.pushButton.setObjectName("pushButton") self.pushButton_2 = QtWidgets.QPushButton(Form) self.pushButton_2.setGeometry(QtCore.QRect(130, 10, 97, 27)) self.pushButton_2.setObjectName("pushButton_2") self.pushButton_3 = QtWidgets.QPushButton(Form) self.pushButton_3.setGeometry(QtCore.QRect(250, 10, 97, 27)) self.pushButton_3.setObjectName("pushButton_3") self.pushButton_4 = QtWidgets.QPushButton(Form) self.pushButton_4.setGeometry(QtCore.QRect(370, 10, 97, 27)) self.pushButton_4.setObjectName("pushButton_4") self.pushButton_5 = QtWidgets.QPushButton(Form) self.pushButton_5.setGeometry(QtCore.QRect(560, 360, 81, 27)) self.pushButton_5.setObjectName("pushButton_5") self.pushButton_6 = QtWidgets.QPushButton(Form) self.pushButton_6.setGeometry(QtCore.QRect(490, 40, 97, 27)) self.pushButton_6.setObjectName("pushButton_6") self.pushButton_7 = QtWidgets.QPushButton(Form) self.pushButton_7.setGeometry(QtCore.QRect(490, 10, 97, 27)) self.pushButton_7.setObjectName("pushButton_7") self.pushButton_8 = QtWidgets.QPushButton(Form) self.pushButton_8.setGeometry(QtCore.QRect(370, 40, 97, 27)) self.pushButton_8.setObjectName("pushButton_8") self.graphicsView = QtWidgets.QGraphicsView(Form) self.graphicsView.setGeometry(QtCore.QRect(20, 120, 512, 512)) self.graphicsView.setObjectName("graphicsView") self.graphicsView_2 = QtWidgets.QGraphicsView(Form) self.graphicsView_2.setGeometry(QtCore.QRect(660, 120, 512, 512)) self.graphicsView_2.setObjectName("graphicsView_2") self.saveImg = QtWidgets.QPushButton(Form) self.saveImg.setGeometry(QtCore.QRect(610, 10, 97, 27)) self.saveImg.setObjectName("saveImg") self.arrangement = QtWidgets.QPushButton(Form) self.arrangement.setGeometry(QtCore.QRect(610, 40, 97, 27)) self.arrangement.setObjectName("arrangement") self.retranslateUi(Form) self.pushButton.clicked.connect(Form.open) self.pushButton_2.clicked.connect(Form.mask_mode) self.pushButton_3.clicked.connect(Form.sketch_mode) self.pushButton_4.clicked.connect(Form.stroke_mode) self.pushButton_5.clicked.connect(Form.complete) self.pushButton_6.clicked.connect(Form.undo) self.pushButton_7.clicked.connect(Form.color_change_mode) self.pushButton_8.clicked.connect(Form.clear) self.saveImg.clicked.connect(Form.save_img) self.arrangement.clicked.connect(Form.arrange) QtCore.QMetaObject.connectSlotsByName(Form)
[ "def", "setupUi", "(", "self", ",", "Form", ")", ":", "Form", ".", "setObjectName", "(", "\"Form\"", ")", "Form", ".", "resize", "(", "1200", ",", "660", ")", "self", ".", "pushButton", "=", "QtWidgets", ".", "QPushButton", "(", "Form", ")", "self", ...
https://github.com/OUCMachineLearning/OUCML/blob/5b54337d7c0316084cb1a74befda2bba96137d4a/GAN/人脸还原SCFEGAN/ui/ui.py#L4-L60
seann999/ssd_tensorflow
f381dba71029a329a2b23763b804289eb8069b4b
vgg/utils.py
python
load_image
(path, size=224)
return resized_img
[]
def load_image(path, size=224): # load image img = skimage.io.imread(path) img = img / 255.0 assert (0 <= img).all() and (img <= 1.0).all() # print "Original Image Shape: ", img.shape # we crop image from center short_edge = min(img.shape[:2]) yy = int((img.shape[0] - short_edge) / 2) xx = int((img.shape[1] - short_edge) / 2) crop_img = img[yy: yy + short_edge, xx: xx + short_edge] # resize to 224, 224 resized_img = skimage.transform.resize(crop_img, (size, size)) return resized_img
[ "def", "load_image", "(", "path", ",", "size", "=", "224", ")", ":", "# load image", "img", "=", "skimage", ".", "io", ".", "imread", "(", "path", ")", "img", "=", "img", "/", "255.0", "assert", "(", "0", "<=", "img", ")", ".", "all", "(", ")", ...
https://github.com/seann999/ssd_tensorflow/blob/f381dba71029a329a2b23763b804289eb8069b4b/vgg/utils.py#L12-L25
ckiplab/ckiptagger
50add4192087927342f0bc19137a169c608f8ebe
src/model_ws.py
python
Model.predict_label_for_a_batch
(self, sample_list)
return prediction_list
Generate token label sequence for each sample in the mini-batch. prediction_list: [prediction] prediction: [token_label]
Generate token label sequence for each sample in the mini-batch. prediction_list: [prediction] prediction: [token_label]
[ "Generate", "token", "label", "sequence", "for", "each", "sample", "in", "the", "mini", "-", "batch", ".", "prediction_list", ":", "[", "prediction", "]", "prediction", ":", "[", "token_label", "]" ]
def predict_label_for_a_batch(self, sample_list): """Generate token label sequence for each sample in the mini-batch. prediction_list: [prediction] prediction: [token_label] """ ( input_length, w_k, w_v, _, _, ) = self.get_formatted_input(sample_list) logits = self.sess.run( # [batch, length, output_d] self.logits, feed_dict = { self.bilstm.kr: 1.0, self.input_length: input_length, self.w_k: w_k, self.w_v: w_v, } ) labelindex_sequence_list = np.argmax(logits, axis=2) # [batch, length] prediction_list = [] for b, labelindex_sequence in enumerate(labelindex_sequence_list): prediction = [] for label_index in labelindex_sequence[:input_length[b]]: token_label = self.tokenlabel_list[label_index] prediction.append(token_label) prediction[0] = "B" prediction_list.append(prediction) return prediction_list
[ "def", "predict_label_for_a_batch", "(", "self", ",", "sample_list", ")", ":", "(", "input_length", ",", "w_k", ",", "w_v", ",", "_", ",", "_", ",", ")", "=", "self", ".", "get_formatted_input", "(", "sample_list", ")", "logits", "=", "self", ".", "sess"...
https://github.com/ckiplab/ckiptagger/blob/50add4192087927342f0bc19137a169c608f8ebe/src/model_ws.py#L399-L432
nltk/nltk
3f74ac55681667d7ef78b664557487145f51eb02
nltk/inference/api.py
python
BaseProverCommand.prove
(self, verbose=False)
return self._result
Perform the actual proof. Store the result to prevent unnecessary re-proving.
Perform the actual proof. Store the result to prevent unnecessary re-proving.
[ "Perform", "the", "actual", "proof", ".", "Store", "the", "result", "to", "prevent", "unnecessary", "re", "-", "proving", "." ]
def prove(self, verbose=False): """ Perform the actual proof. Store the result to prevent unnecessary re-proving. """ if self._result is None: self._result, self._proof = self._prover._prove( self.goal(), self.assumptions(), verbose ) return self._result
[ "def", "prove", "(", "self", ",", "verbose", "=", "False", ")", ":", "if", "self", ".", "_result", "is", "None", ":", "self", ".", "_result", ",", "self", ".", "_proof", "=", "self", ".", "_prover", ".", "_prove", "(", "self", ".", "goal", "(", "...
https://github.com/nltk/nltk/blob/3f74ac55681667d7ef78b664557487145f51eb02/nltk/inference/api.py#L279-L288
pilotmoon/PopClip-Extensions
29fc472befc09ee350092ac70283bd9fdb456cb6
source/PushbulletPython/requests/api.py
python
head
(url, **kwargs)
return request('head', url, **kwargs)
Sends a HEAD request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes.
Sends a HEAD request. Returns :class:`Response` object.
[ "Sends", "a", "HEAD", "request", ".", "Returns", ":", "class", ":", "Response", "object", "." ]
def head(url, **kwargs): """Sends a HEAD request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. """ kwargs.setdefault('allow_redirects', False) return request('head', url, **kwargs)
[ "def", "head", "(", "url", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'allow_redirects'", ",", "False", ")", "return", "request", "(", "'head'", ",", "url", ",", "*", "*", "kwargs", ")" ]
https://github.com/pilotmoon/PopClip-Extensions/blob/29fc472befc09ee350092ac70283bd9fdb456cb6/source/PushbulletPython/requests/api.py#L69-L77
optuna/optuna
2c44c1a405ba059efd53f4b9c8e849d20fb95c0a
optuna/_transform.py
python
_SearchSpaceTransform.transform
(self, params: Dict[str, Any])
return trans_params
Transform a parameter configuration from actual values to continuous space. Args: params: A parameter configuration to transform. Returns: A 1-dimensional ``numpy.ndarray`` holding the transformed parameters in the configuration.
Transform a parameter configuration from actual values to continuous space.
[ "Transform", "a", "parameter", "configuration", "from", "actual", "values", "to", "continuous", "space", "." ]
def transform(self, params: Dict[str, Any]) -> numpy.ndarray: """Transform a parameter configuration from actual values to continuous space. Args: params: A parameter configuration to transform. Returns: A 1-dimensional ``numpy.ndarray`` holding the transformed parameters in the configuration. """ trans_params = numpy.zeros(self._bounds.shape[0], dtype=numpy.float64) bound_idx = 0 for name, distribution in self._search_space.items(): assert name in params, "Parameter configuration must contain all distributions." param = params[name] if isinstance(distribution, CategoricalDistribution): choice_idx = distribution.to_internal_repr(param) trans_params[bound_idx + choice_idx] = 1 bound_idx += len(distribution.choices) else: trans_params[bound_idx] = _transform_numerical_param( param, distribution, self._transform_log ) bound_idx += 1 return trans_params
[ "def", "transform", "(", "self", ",", "params", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "numpy", ".", "ndarray", ":", "trans_params", "=", "numpy", ".", "zeros", "(", "self", ".", "_bounds", ".", "shape", "[", "0", "]", ",", "dtype", ...
https://github.com/optuna/optuna/blob/2c44c1a405ba059efd53f4b9c8e849d20fb95c0a/optuna/_transform.py#L98-L127
psychopy/psychopy
01b674094f38d0e0bd51c45a6f66f671d7041696
psychopy/app/builder/builder.py
python
RoutineCanvas.getMaxTime
(self)
return maxTime
Return the max time to be drawn in the window
Return the max time to be drawn in the window
[ "Return", "the", "max", "time", "to", "be", "drawn", "in", "the", "window" ]
def getMaxTime(self): """Return the max time to be drawn in the window """ maxTime, nonSlip = self.routine.getMaxTime() if self.routine.hasOnlyStaticComp(): maxTime = int(maxTime) + 1.0 return maxTime
[ "def", "getMaxTime", "(", "self", ")", ":", "maxTime", ",", "nonSlip", "=", "self", ".", "routine", ".", "getMaxTime", "(", ")", "if", "self", ".", "routine", ".", "hasOnlyStaticComp", "(", ")", ":", "maxTime", "=", "int", "(", "maxTime", ")", "+", "...
https://github.com/psychopy/psychopy/blob/01b674094f38d0e0bd51c45a6f66f671d7041696/psychopy/app/builder/builder.py#L1828-L1834
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pip/_vendor/html5lib/_inputstream.py
python
EncodingBytes.previous
(self)
return self[p:p + 1]
[]
def previous(self): p = self._position if p >= len(self): raise StopIteration elif p < 0: raise TypeError self._position = p = p - 1 return self[p:p + 1]
[ "def", "previous", "(", "self", ")", ":", "p", "=", "self", ".", "_position", "if", "p", ">=", "len", "(", "self", ")", ":", "raise", "StopIteration", "elif", "p", "<", "0", ":", "raise", "TypeError", "self", ".", "_position", "=", "p", "=", "p", ...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pip/_vendor/html5lib/_inputstream.py#L611-L618
mitmproxy/mitmproxy
1abb8f69217910c8623bd1339da2502aed98ff0d
mitmproxy/contrib/urwid/raw_display.py
python
Screen._setup_G1
(self)
Initialize the G1 character set to graphics mode if required.
Initialize the G1 character set to graphics mode if required.
[ "Initialize", "the", "G1", "character", "set", "to", "graphics", "mode", "if", "required", "." ]
def _setup_G1(self): """ Initialize the G1 character set to graphics mode if required. """ if self._setup_G1_done: return while True: try: self.write(escape.DESIGNATE_G1_SPECIAL) self.flush() break except IOError: pass self._setup_G1_done = True
[ "def", "_setup_G1", "(", "self", ")", ":", "if", "self", ".", "_setup_G1_done", ":", "return", "while", "True", ":", "try", ":", "self", ".", "write", "(", "escape", ".", "DESIGNATE_G1_SPECIAL", ")", "self", ".", "flush", "(", ")", "break", "except", "...
https://github.com/mitmproxy/mitmproxy/blob/1abb8f69217910c8623bd1339da2502aed98ff0d/mitmproxy/contrib/urwid/raw_display.py#L747-L761
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/states/dvs.py
python
mod_init
(low)
return True
Init function
Init function
[ "Init", "function" ]
def mod_init(low): """ Init function """ return True
[ "def", "mod_init", "(", "low", ")", ":", "return", "True" ]
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/states/dvs.py#L239-L243
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
bin/x86/Debug/scripting_engine/Lib/site-packages/Crypto/Util/asn1.py
python
DerInteger.decode
(self, derEle, noLeftOvers=0)
return tlvLength
Decode a complete INTEGER DER element, and re-initializes this object with it. @param derEle A complete INTEGER DER element. It must start with a DER INTEGER tag. @param noLeftOvers Indicate whether it is acceptable to complete the parsing of the DER element and find that not all bytes in derEle have been used. @return Index of the first unused byte in the given DER element. Raises a ValueError exception if the DER element is not a valid non-negative INTEGER. Raises an IndexError exception if the DER element is too short.
Decode a complete INTEGER DER element, and re-initializes this object with it.
[ "Decode", "a", "complete", "INTEGER", "DER", "element", "and", "re", "-", "initializes", "this", "object", "with", "it", "." ]
def decode(self, derEle, noLeftOvers=0): """Decode a complete INTEGER DER element, and re-initializes this object with it. @param derEle A complete INTEGER DER element. It must start with a DER INTEGER tag. @param noLeftOvers Indicate whether it is acceptable to complete the parsing of the DER element and find that not all bytes in derEle have been used. @return Index of the first unused byte in the given DER element. Raises a ValueError exception if the DER element is not a valid non-negative INTEGER. Raises an IndexError exception if the DER element is too short. """ tlvLength = DerObject.decode(self, derEle, noLeftOvers) if self.typeTag!=self.typeTags['INTEGER']: raise ValueError ("Not a DER INTEGER.") if bord(self.payload[0])>127: raise ValueError ("Negative INTEGER.") self.value = bytes_to_long(self.payload) return tlvLength
[ "def", "decode", "(", "self", ",", "derEle", ",", "noLeftOvers", "=", "0", ")", ":", "tlvLength", "=", "DerObject", ".", "decode", "(", "self", ",", "derEle", ",", "noLeftOvers", ")", "if", "self", ".", "typeTag", "!=", "self", ".", "typeTags", "[", ...
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/bin/x86/Debug/scripting_engine/Lib/site-packages/Crypto/Util/asn1.py#L128-L149
HSLCY/ABSA-BERT-pair
7d238eb8c772946b9e572373c144b11151e4187f
optimization.py
python
BERTAdam.step
(self, closure=None)
return loss
Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss.
Performs a single optimization step.
[ "Performs", "a", "single", "optimization", "step", "." ]
def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for group in self.param_groups: for p in group['params']: if p.grad is None: continue grad = p.grad.data if grad.is_sparse: raise RuntimeError('Adam does not support sparse gradients, please consider SparseAdam instead') state = self.state[p] # State initialization if len(state) == 0: state['step'] = 0 # Exponential moving average of gradient values state['next_m'] = torch.zeros_like(p.data) # Exponential moving average of squared gradient values state['next_v'] = torch.zeros_like(p.data) next_m, next_v = state['next_m'], state['next_v'] beta1, beta2 = group['b1'], group['b2'] # Add grad clipping if group['max_grad_norm'] > 0: clip_grad_norm_(p, group['max_grad_norm']) # Decay the first and second moment running average coefficient # In-place operations to update the averages at the same time next_m.mul_(beta1).add_(1 - beta1, grad) next_v.mul_(beta2).addcmul_(1 - beta2, grad, grad) update = next_m / (next_v.sqrt() + group['e']) # Just adding the square of the weights to the loss function is *not* # the correct way of using L2 regularization/weight decay with Adam, # since that will interact with the m and v parameters in strange ways. # # Instead we want ot decay the weights in a manner that doesn't interact # with the m/v parameters. This is equivalent to adding the square # of the weights to the loss with plain (non-momentum) SGD. if group['weight_decay_rate'] > 0.0: update += group['weight_decay_rate'] * p.data if group['t_total'] != -1: schedule_fct = SCHEDULES[group['schedule']] lr_scheduled = group['lr'] * schedule_fct(state['step']/group['t_total'], group['warmup']) else: lr_scheduled = group['lr'] update_with_lr = lr_scheduled * update p.data.add_(-update_with_lr) state['step'] += 1 # step_size = lr_scheduled * math.sqrt(bias_correction2) / bias_correction1 # bias_correction1 = 1 - beta1 ** state['step'] # bias_correction2 = 1 - beta2 ** state['step'] return loss
[ "def", "step", "(", "self", ",", "closure", "=", "None", ")", ":", "loss", "=", "None", "if", "closure", "is", "not", "None", ":", "loss", "=", "closure", "(", ")", "for", "group", "in", "self", ".", "param_groups", ":", "for", "p", "in", "group", ...
https://github.com/HSLCY/ABSA-BERT-pair/blob/7d238eb8c772946b9e572373c144b11151e4187f/optimization.py#L108-L175
KhronosGroup/NNEF-Tools
c913758ca687dab8cb7b49e8f1556819a2d0ca25
nnef_tools/conversion/converter.py
python
Converter._check_conditions
(self, op, transform)
return error
[]
def _check_conditions(self, op, transform): op_inputs = list(self._tensor_map[tensor] for tensor in op.inputs) op_outputs = list(self._tensor_map[tensor] for tensor in op.outputs) op_attribs = self._add_default_attribs(op.attribs, transform.defaults, op_inputs, op_outputs, op.type, op.name) using = {'_type_': op.type, '_name_': op.name, **self._global_attribs()} for key, item in six.iteritems(transform.using): value = self._evaluate(op_attribs, op_inputs, op_outputs, item, using) self._check_value(value, 'using', key, op.type, op.name) using[key] = value error = None if transform.cond is not None: for condition, message in transform.cond.items(): if not self._evaluate(op_attribs, op_inputs, op_outputs, condition, using): error = message if error is None else error + ', ' + message return error
[ "def", "_check_conditions", "(", "self", ",", "op", ",", "transform", ")", ":", "op_inputs", "=", "list", "(", "self", ".", "_tensor_map", "[", "tensor", "]", "for", "tensor", "in", "op", ".", "inputs", ")", "op_outputs", "=", "list", "(", "self", ".",...
https://github.com/KhronosGroup/NNEF-Tools/blob/c913758ca687dab8cb7b49e8f1556819a2d0ca25/nnef_tools/conversion/converter.py#L208-L225
lovelylain/pyctp
fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d
lts/ctp/ApiStruct.py
python
QryTradingAccount.__init__
(self, BrokerID='', InvestorID='')
[]
def __init__(self, BrokerID='', InvestorID=''): self.BrokerID = '' #经纪公司代码, char[11] self.InvestorID = ''
[ "def", "__init__", "(", "self", ",", "BrokerID", "=", "''", ",", "InvestorID", "=", "''", ")", ":", "self", ".", "BrokerID", "=", "''", "#经纪公司代码, char[11]", "self", ".", "InvestorID", "=", "''" ]
https://github.com/lovelylain/pyctp/blob/fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d/lts/ctp/ApiStruct.py#L1247-L1249
ethereum/trinity
6383280c5044feb06695ac2f7bc1100b7bcf4fe0
p2p/discovery.py
python
DiscoveryService.bootstrap
(self)
[]
async def bootstrap(self) -> None: bonding_queries = [] for node in self.bootstrap_nodes: uri = node.uri() pubkey, _, uri_tail = uri.partition('@') pubkey_head = pubkey[:16] pubkey_tail = pubkey[-8:] self.logger.debug("full-bootnode: %s", uri) self.logger.debug("bootnode: %s...%s@%s", pubkey_head, pubkey_tail, uri_tail) # Upon startup we want to force a new bond with our bootnodes. That ensures we only # query the ones that are still reachable and that we tell them about our latest ENR, # which might have changed. self.invalidate_bond(node.id) bonding_queries.append((self.bond, node.id)) bonded = await trio_utils.gather(*bonding_queries) successful_bonds = len([item for item in bonded if item is True]) if not successful_bonds: self.logger.warning("Failed to bond with any bootstrap nodes %s", self.bootstrap_nodes) return else: self.logger.info( "Bonded with %d bootstrap nodes, performing initial lookup", successful_bonds) await self.lookup_random()
[ "async", "def", "bootstrap", "(", "self", ")", "->", "None", ":", "bonding_queries", "=", "[", "]", "for", "node", "in", "self", ".", "bootstrap_nodes", ":", "uri", "=", "node", ".", "uri", "(", ")", "pubkey", ",", "_", ",", "uri_tail", "=", "uri", ...
https://github.com/ethereum/trinity/blob/6383280c5044feb06695ac2f7bc1100b7bcf4fe0/p2p/discovery.py#L701-L727
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/sklearn/utils/__init__.py
python
indices_to_mask
(indices, mask_length)
return mask
Convert list of indices to boolean mask. Parameters ---------- indices : list-like List of integers treated as indices. mask_length : int Length of boolean mask to be generated. Returns ------- mask : 1d boolean nd-array Boolean array that is True where indices are present, else False.
Convert list of indices to boolean mask.
[ "Convert", "list", "of", "indices", "to", "boolean", "mask", "." ]
def indices_to_mask(indices, mask_length): """Convert list of indices to boolean mask. Parameters ---------- indices : list-like List of integers treated as indices. mask_length : int Length of boolean mask to be generated. Returns ------- mask : 1d boolean nd-array Boolean array that is True where indices are present, else False. """ if mask_length <= np.max(indices): raise ValueError("mask_length must be greater than max(indices)") mask = np.zeros(mask_length, dtype=np.bool) mask[indices] = True return mask
[ "def", "indices_to_mask", "(", "indices", ",", "mask_length", ")", ":", "if", "mask_length", "<=", "np", ".", "max", "(", "indices", ")", ":", "raise", "ValueError", "(", "\"mask_length must be greater than max(indices)\"", ")", "mask", "=", "np", ".", "zeros", ...
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/sklearn/utils/__init__.py#L424-L445
lxdock/lxdock
f71006d130bc8b53603eea36a546003495437493
lxdock/cli/main.py
python
LXDock.status
(self, args)
[]
def status(self, args): self.project.status(container_names=args.name)
[ "def", "status", "(", "self", ",", "args", ")", ":", "self", ".", "project", ".", "status", "(", "container_names", "=", "args", ".", "name", ")" ]
https://github.com/lxdock/lxdock/blob/f71006d130bc8b53603eea36a546003495437493/lxdock/cli/main.py#L226-L227
vmware/pyvcloud
d72c615fa41b8ea5ab049a929e18d8ba6460fc59
pyvcloud/vcd/vm.py
python
VM.get_memory
(self)
return int( self.resource.VmSpecSection.MemoryResourceMb.Configured.text)
Returns the amount of memory in MB. :return: amount of memory in MB. :rtype: int
Returns the amount of memory in MB.
[ "Returns", "the", "amount", "of", "memory", "in", "MB", "." ]
def get_memory(self): """Returns the amount of memory in MB. :return: amount of memory in MB. :rtype: int """ self.get_resource() return int( self.resource.VmSpecSection.MemoryResourceMb.Configured.text)
[ "def", "get_memory", "(", "self", ")", ":", "self", ".", "get_resource", "(", ")", "return", "int", "(", "self", ".", "resource", ".", "VmSpecSection", ".", "MemoryResourceMb", ".", "Configured", ".", "text", ")" ]
https://github.com/vmware/pyvcloud/blob/d72c615fa41b8ea5ab049a929e18d8ba6460fc59/pyvcloud/vcd/vm.py#L137-L146
AndroBugs/AndroBugs_Framework
7fd3a2cb1cf65a9af10b7ed2129701d4451493fe
tools/modified/androguard/core/bytecodes/dvm.py
python
Instruction.get_output
(self, idx=-1)
Return an additional output of the instruction :rtype: string
Return an additional output of the instruction
[ "Return", "an", "additional", "output", "of", "the", "instruction" ]
def get_output(self, idx=-1): """ Return an additional output of the instruction :rtype: string """ raise("not implemented")
[ "def", "get_output", "(", "self", ",", "idx", "=", "-", "1", ")", ":", "raise", "(", "\"not implemented\"", ")" ]
https://github.com/AndroBugs/AndroBugs_Framework/blob/7fd3a2cb1cf65a9af10b7ed2129701d4451493fe/tools/modified/androguard/core/bytecodes/dvm.py#L3876-L3882
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/pip/_vendor/urllib3/poolmanager.py
python
PoolManager.connection_from_host
(self, host, port=None, scheme='http', pool_kwargs=None)
return self.connection_from_context(request_context)
Get a :class:`ConnectionPool` based on the host, port, and scheme. If ``port`` isn't given, it will be derived from the ``scheme`` using ``urllib3.connectionpool.port_by_scheme``. If ``pool_kwargs`` is provided, it is merged with the instance's ``connection_pool_kw`` variable and used to create the new connection pool, if one is needed.
Get a :class:`ConnectionPool` based on the host, port, and scheme.
[ "Get", "a", ":", "class", ":", "ConnectionPool", "based", "on", "the", "host", "port", "and", "scheme", "." ]
def connection_from_host(self, host, port=None, scheme='http', pool_kwargs=None): """ Get a :class:`ConnectionPool` based on the host, port, and scheme. If ``port`` isn't given, it will be derived from the ``scheme`` using ``urllib3.connectionpool.port_by_scheme``. If ``pool_kwargs`` is provided, it is merged with the instance's ``connection_pool_kw`` variable and used to create the new connection pool, if one is needed. """ if not host: raise LocationValueError("No host specified.") request_context = self._merge_pool_kwargs(pool_kwargs) request_context['scheme'] = scheme or 'http' if not port: port = port_by_scheme.get(request_context['scheme'].lower(), 80) request_context['port'] = port request_context['host'] = host return self.connection_from_context(request_context)
[ "def", "connection_from_host", "(", "self", ",", "host", ",", "port", "=", "None", ",", "scheme", "=", "'http'", ",", "pool_kwargs", "=", "None", ")", ":", "if", "not", "host", ":", "raise", "LocationValueError", "(", "\"No host specified.\"", ")", "request_...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/pip/_vendor/urllib3/poolmanager.py#L206-L227
pybliometrics-dev/pybliometrics
26ad9656e5a1d4c80774937706a0df85776f07d0
pybliometrics/scopus/abstract_retrieval.py
python
AbstractRetrieval.refcount
(self)
Number of references of an article. Note: Requires either the FULL view or REF view.
Number of references of an article. Note: Requires either the FULL view or REF view.
[ "Number", "of", "references", "of", "an", "article", ".", "Note", ":", "Requires", "either", "the", "FULL", "view", "or", "REF", "view", "." ]
def refcount(self) -> Optional[int]: """Number of references of an article. Note: Requires either the FULL view or REF view. """ try: # REF view return int(self._ref['@total-references']) except KeyError: # FULL view try: return int(self._ref['@refcount']) except KeyError: return None
[ "def", "refcount", "(", "self", ")", "->", "Optional", "[", "int", "]", ":", "try", ":", "# REF view", "return", "int", "(", "self", ".", "_ref", "[", "'@total-references'", "]", ")", "except", "KeyError", ":", "# FULL view", "try", ":", "return", "int",...
https://github.com/pybliometrics-dev/pybliometrics/blob/26ad9656e5a1d4c80774937706a0df85776f07d0/pybliometrics/scopus/abstract_retrieval.py#L414-L424
limodou/uliweb
8bc827fa6bf7bf58aa8136b6c920fe2650c52422
uliweb/utils/date.py
python
to_timezone
(dt, tzinfo=None)
Convert a datetime to timezone
Convert a datetime to timezone
[ "Convert", "a", "datetime", "to", "timezone" ]
def to_timezone(dt, tzinfo=None): """ Convert a datetime to timezone """ if not dt: return dt tz = pick_timezone(tzinfo, __timezone__) if not tz: return dt dttz = getattr(dt, 'tzinfo', None) if not dttz: return dt.replace(tzinfo=tz) else: return dt.astimezone(tz)
[ "def", "to_timezone", "(", "dt", ",", "tzinfo", "=", "None", ")", ":", "if", "not", "dt", ":", "return", "dt", "tz", "=", "pick_timezone", "(", "tzinfo", ",", "__timezone__", ")", "if", "not", "tz", ":", "return", "dt", "dttz", "=", "getattr", "(", ...
https://github.com/limodou/uliweb/blob/8bc827fa6bf7bf58aa8136b6c920fe2650c52422/uliweb/utils/date.py#L146-L159
pantsbuild/pex
473c6ac732ed4bc338b4b20a9ec930d1d722c9b4
pex/vendor/_vendored/pip/pip/_vendor/pep517/_in_process.py
python
get_requires_for_build_sdist
(config_settings)
Invoke the optional get_requires_for_build_wheel hook Returns [] if the hook is not defined.
Invoke the optional get_requires_for_build_wheel hook
[ "Invoke", "the", "optional", "get_requires_for_build_wheel", "hook" ]
def get_requires_for_build_sdist(config_settings): """Invoke the optional get_requires_for_build_wheel hook Returns [] if the hook is not defined. """ backend = _build_backend() try: hook = backend.get_requires_for_build_sdist except AttributeError: return [] else: return hook(config_settings)
[ "def", "get_requires_for_build_sdist", "(", "config_settings", ")", ":", "backend", "=", "_build_backend", "(", ")", "try", ":", "hook", "=", "backend", ".", "get_requires_for_build_sdist", "except", "AttributeError", ":", "return", "[", "]", "else", ":", "return"...
https://github.com/pantsbuild/pex/blob/473c6ac732ed4bc338b4b20a9ec930d1d722c9b4/pex/vendor/_vendored/pip/pip/_vendor/pep517/_in_process.py#L208-L219
tendenci/tendenci
0f2c348cc0e7d41bc56f50b00ce05544b083bf1d
tendenci/apps/files/models.py
python
File.icon
(self)
return static('images/icons/'+icons[self.type()])
[]
def icon(self): # if we don't know the type # we can't find an icon [to represent the file] if not self.type(): return None # map file-type to image file icons = { 'text': 'icon-ms-word-2007.gif', 'spreadsheet': 'icon-ms-excel-2007.gif', 'powerpoint': 'icon-ms-powerpoint-2007.gif', 'image': 'icon-ms-image-2007.png', 'pdf': 'icon-pdf.png', 'video': 'icon-wmv.png', 'zip': 'icon-zip.gif', } # return image path return static('images/icons/'+icons[self.type()])
[ "def", "icon", "(", "self", ")", ":", "# if we don't know the type", "# we can't find an icon [to represent the file]", "if", "not", "self", ".", "type", "(", ")", ":", "return", "None", "# map file-type to image file", "icons", "=", "{", "'text'", ":", "'icon-ms-word...
https://github.com/tendenci/tendenci/blob/0f2c348cc0e7d41bc56f50b00ce05544b083bf1d/tendenci/apps/files/models.py#L270-L289
jborean93/pypsrp
678df470648e9b82a1be82d6a08e056b2d3c413c
pypsrp/host.py
python
PSHostRawUserInterface.SetBufferContents2
(self, runspace, pipeline, origin, contents)
MI: 48 SHOULD copy the specified buffer cell array into the screen buffer at the specified coordinates (as specified in section 2.2.3.1). https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.host.pshostrawuserinterface.setbuffercontents :param runspace: The runspace the host call relates to :param pipeline: The pipeline (if any) that the call relates to :param origin: A GenericComplexObject that represents the coordinates, x and y are extended properties of this object origin.extended_properties['x'] origin.extended_properties['y'] :param contents: A rectangle of BufferCell objects to be copied to the screen buffer. This is also a GenericComplexObject which is a multi dimensional array. https://msdn.microsoft.com/en-us/library/dd340684.aspx # number of elements in each row contents.extended_properties['mal'] # each BufferCell is in this list, use mal to determine what # rows they are in contents.extended_properties['mae']
MI: 48 SHOULD copy the specified buffer cell array into the screen buffer at the specified coordinates (as specified in section 2.2.3.1). https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.host.pshostrawuserinterface.setbuffercontents
[ "MI", ":", "48", "SHOULD", "copy", "the", "specified", "buffer", "cell", "array", "into", "the", "screen", "buffer", "at", "the", "specified", "coordinates", "(", "as", "specified", "in", "section", "2", ".", "2", ".", "3", ".", "1", ")", ".", "https",...
def SetBufferContents2(self, runspace, pipeline, origin, contents): """ MI: 48 SHOULD copy the specified buffer cell array into the screen buffer at the specified coordinates (as specified in section 2.2.3.1). https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.host.pshostrawuserinterface.setbuffercontents :param runspace: The runspace the host call relates to :param pipeline: The pipeline (if any) that the call relates to :param origin: A GenericComplexObject that represents the coordinates, x and y are extended properties of this object origin.extended_properties['x'] origin.extended_properties['y'] :param contents: A rectangle of BufferCell objects to be copied to the screen buffer. This is also a GenericComplexObject which is a multi dimensional array. https://msdn.microsoft.com/en-us/library/dd340684.aspx # number of elements in each row contents.extended_properties['mal'] # each BufferCell is in this list, use mal to determine what # rows they are in contents.extended_properties['mae'] """ pass
[ "def", "SetBufferContents2", "(", "self", ",", "runspace", ",", "pipeline", ",", "origin", ",", "contents", ")", ":", "pass" ]
https://github.com/jborean93/pypsrp/blob/678df470648e9b82a1be82d6a08e056b2d3c413c/pypsrp/host.py#L837-L861
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/zwave_js/api.py
python
async_get_node
(orig_func: Callable)
return async_get_node_func
Decorate async function to get node.
Decorate async function to get node.
[ "Decorate", "async", "function", "to", "get", "node", "." ]
def async_get_node(orig_func: Callable) -> Callable: """Decorate async function to get node.""" @async_get_entry @wraps(orig_func) async def async_get_node_func( hass: HomeAssistant, connection: ActiveConnection, msg: dict, entry: ConfigEntry, client: Client, ) -> None: """Provide user specific data and store to function.""" node_id = msg[NODE_ID] node = client.driver.controller.nodes.get(node_id) if node is None: connection.send_error(msg[ID], ERR_NOT_FOUND, f"Node {node_id} not found") return await orig_func(hass, connection, msg, node) return async_get_node_func
[ "def", "async_get_node", "(", "orig_func", ":", "Callable", ")", "->", "Callable", ":", "@", "async_get_entry", "@", "wraps", "(", "orig_func", ")", "async", "def", "async_get_node_func", "(", "hass", ":", "HomeAssistant", ",", "connection", ":", "ActiveConnecti...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/zwave_js/api.py#L253-L274
hzy46/Deep-Learning-21-Examples
15c2d9edccad090cd67b033f24a43c544e5cba3e
chapter_5/research/object_detection/core/anchor_generator.py
python
AnchorGenerator.num_anchors_per_location
(self)
Returns the number of anchors per spatial location. Returns: a list of integers, one for each expected feature map to be passed to the `generate` function.
Returns the number of anchors per spatial location.
[ "Returns", "the", "number", "of", "anchors", "per", "spatial", "location", "." ]
def num_anchors_per_location(self): """Returns the number of anchors per spatial location. Returns: a list of integers, one for each expected feature map to be passed to the `generate` function. """ pass
[ "def", "num_anchors_per_location", "(", "self", ")", ":", "pass" ]
https://github.com/hzy46/Deep-Learning-21-Examples/blob/15c2d9edccad090cd67b033f24a43c544e5cba3e/chapter_5/research/object_detection/core/anchor_generator.py#L68-L75
timbrel/GitSavvy
c0a627c30da79cb10a5a33f30d92d177f78da0ab
core/git_mixins/stage_unstage.py
python
StageUnstageMixin.stage_file
(self, *fpath, force=True)
Given an absolute path or path relative to the repo's root, stage the file.
Given an absolute path or path relative to the repo's root, stage the file.
[ "Given", "an", "absolute", "path", "or", "path", "relative", "to", "the", "repo", "s", "root", "stage", "the", "file", "." ]
def stage_file(self, *fpath, force=True): # type: (str, bool) -> None """ Given an absolute path or path relative to the repo's root, stage the file. """ self.git( "add", "-f" if force else None, "--all", "--", *fpath )
[ "def", "stage_file", "(", "self", ",", "*", "fpath", ",", "force", "=", "True", ")", ":", "# type: (str, bool) -> None", "self", ".", "git", "(", "\"add\"", ",", "\"-f\"", "if", "force", "else", "None", ",", "\"--all\"", ",", "\"--\"", ",", "*", "fpath",...
https://github.com/timbrel/GitSavvy/blob/c0a627c30da79cb10a5a33f30d92d177f78da0ab/core/git_mixins/stage_unstage.py#L6-L18
chb/indivo_server
9826c67ab17d7fc0df935db327344fb0c7d237e5
indivo/views/reports/measurement.py
python
carenet_measurement_list
(*args, **kwargs)
return _measurement_list(*args, **kwargs)
List the measurement data for a given carenet. For 1:1 mapping of URLs to views. Just calls :py:meth:`~indivo.views.reports.measurement._measurement_list`.
List the measurement data for a given carenet.
[ "List", "the", "measurement", "data", "for", "a", "given", "carenet", "." ]
def carenet_measurement_list(*args, **kwargs): """ List the measurement data for a given carenet. For 1:1 mapping of URLs to views. Just calls :py:meth:`~indivo.views.reports.measurement._measurement_list`. """ return _measurement_list(*args, **kwargs)
[ "def", "carenet_measurement_list", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_measurement_list", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/chb/indivo_server/blob/9826c67ab17d7fc0df935db327344fb0c7d237e5/indivo/views/reports/measurement.py#L35-L42
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_vendored_deps/library/oc_adm_registry.py
python
Registry.create
(self)
return {'returncode': rval, 'results': results}
Create a registry
Create a registry
[ "Create", "a", "registry" ]
def create(self): '''Create a registry''' results = [] self.needs_update() # if the object is none, then we need to create it # if the object needs an update, then we should call replace # Handle the deploymentconfig if self.deploymentconfig is None: results.append(self._create(self.prepared_registry['deployment_file'])) elif self.prepared_registry['deployment_update']: results.append(self._replace(self.prepared_registry['deployment_file'])) # Handle the service if self.service is None: results.append(self._create(self.prepared_registry['service_file'])) elif self.prepared_registry['service_update']: results.append(self._replace(self.prepared_registry['service_file'])) # Clean up returned results rval = 0 for result in results: # pylint: disable=invalid-sequence-index if 'returncode' in result and result['returncode'] != 0: rval = result['returncode'] return {'returncode': rval, 'results': results}
[ "def", "create", "(", "self", ")", ":", "results", "=", "[", "]", "self", ".", "needs_update", "(", ")", "# if the object is none, then we need to create it", "# if the object needs an update, then we should call replace", "# Handle the deploymentconfig", "if", "self", ".", ...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_vendored_deps/library/oc_adm_registry.py#L2523-L2548
gaphor/gaphor
dfe8df33ef3b884afdadf7c91fc7740f8d3c2e88
gaphor/UML/umloverrides.py
python
property_navigability
(self: uml.Property)
Get navigability of an association end. If no association is related to the property, then unknown navigability is assumed.
Get navigability of an association end.
[ "Get", "navigability", "of", "an", "association", "end", "." ]
def property_navigability(self: uml.Property) -> list[bool | None]: """Get navigability of an association end. If no association is related to the property, then unknown navigability is assumed. """ assoc = self.association if not (assoc and self.opposite): return [None] # assume unknown owner = self.opposite.type if ( isinstance(owner, (uml.Class, uml.DataType, uml.Interface)) and isinstance(self.type, (uml.Class, uml.DataType, uml.Interface)) and (self in owner.ownedAttribute) or self in assoc.navigableOwnedEnd ): return [True] elif isinstance(assoc.ownedEnd, uml.ExtensionEnd): return [self is assoc.ownedEnd] elif assoc.ownedEnd is None or self in assoc.ownedEnd: return [None] else: return [False]
[ "def", "property_navigability", "(", "self", ":", "uml", ".", "Property", ")", "->", "list", "[", "bool", "|", "None", "]", ":", "assoc", "=", "self", ".", "association", "if", "not", "(", "assoc", "and", "self", ".", "opposite", ")", ":", "return", ...
https://github.com/gaphor/gaphor/blob/dfe8df33ef3b884afdadf7c91fc7740f8d3c2e88/gaphor/UML/umloverrides.py#L54-L76
SpaceNetChallenge/SpaceNet_Off_Nadir_Solutions
014c4ca27a70b5907a183e942228004c989dcbe4
number13/number13/src/create_patches_all.py
python
patches_and_cocoann
(gt, outdir_rgb, outdir_mpan, count=1,create_anns=True)
return annotations, images, counter
[]
def patches_and_cocoann(gt, outdir_rgb, outdir_mpan, count=1,create_anns=True): gt.index = gt.ImageId gt_flt = gt[gt.PolygonWKT_Geo != 'POLYGON EMPTY'] gv = gt_flt.ImageId.value_counts() annotations = [] images = [] counter = count for u in gt_flt.ImageId.unique(): try: pan_sharpen_dir = ''.join([RAW_DIR, gt.name, '/Pan-Sharpen/']) image_file = ''.join([pan_sharpen_dir, 'Pan-Sharpen', '_', u, '.tif']) img_rgb = tifffile.imread(image_file) if np.argmin(img_rgb.shape) == 0: img_rgb = np.transpose(img_rgb, (1, 2, 0)) img_rgb = img_rgb[:, :, [3, 2, 1, 0]] img_mpan = get_pan_sharpend(''.join([RAW_DIR, gt.name, '/']), u) except: print('load error..', u) continue if gv[u] > 1: poly = gt.loc[u].PolygonWKT_Pix.apply(lambda x: loads(x)).values.tolist() else: poly = [loads(gt.loc[u].PolygonWKT_Pix)] mask = util.mask_for_polygons(poly, im_size=imsize) img_patches_rgb, mask_patches, kp = patch_creator.create(img=img_rgb, mask=mask, nonzero=True) img_patches_mpan, _, _ = patch_creator.create(img=img_mpan, mask=mask, nonzero=True) for i, k in enumerate(kp.keys()): file_name_rgb = os.path.join(outdir_rgb, ''.join([u, '_', str(k), '.tif'])) file_name_mpan = os.path.join(outdir_mpan, ''.join([u, '_', str(k), '.tif'])) if create_anns: anns, images_d, counter = create_coco_anns(file_name_rgb, counter, mask_patches[i].squeeze()) annotations.extend(anns) images.extend(images_d) tifffile.imsave(file_name_mpan, img_patches_mpan[i].astype('uint16')) tifffile.imsave(file_name_rgb, img_patches_rgb[i].astype('uint16')) if DEBUG: break return annotations, images, counter
[ "def", "patches_and_cocoann", "(", "gt", ",", "outdir_rgb", ",", "outdir_mpan", ",", "count", "=", "1", ",", "create_anns", "=", "True", ")", ":", "gt", ".", "index", "=", "gt", ".", "ImageId", "gt_flt", "=", "gt", "[", "gt", ".", "PolygonWKT_Geo", "!=...
https://github.com/SpaceNetChallenge/SpaceNet_Off_Nadir_Solutions/blob/014c4ca27a70b5907a183e942228004c989dcbe4/number13/number13/src/create_patches_all.py#L85-L124
lawsie/guizero
1c3011a3b0930175beaec3aa2f5503bf9339a0a3
guizero/utilities.py
python
AnimationPlayer.stop
(self)
Stops the animation
Stops the animation
[ "Stops", "the", "animation" ]
def stop(self): """ Stops the animation """ self._running = False
[ "def", "stop", "(", "self", ")", ":", "self", ".", "_running", "=", "False" ]
https://github.com/lawsie/guizero/blob/1c3011a3b0930175beaec3aa2f5503bf9339a0a3/guizero/utilities.py#L292-L296
sigmavirus24/github3.py
f642a27833d6bef93daf5bb27b35e5ddbcfbb773
src/github3/github.py
python
GitHub.create_key
(self, title, key, read_only=False)
return self._instance_or_null(users.Key, json)
Create a new key for the authenticated user. :param str title: (required), key title :param str key: (required), actual key contents, accepts path as a string or file-like object :param bool read_only: (optional), restrict key access to read-only, default to False :returns: created key :rtype: :class:`~github3.users.Key`
Create a new key for the authenticated user.
[ "Create", "a", "new", "key", "for", "the", "authenticated", "user", "." ]
def create_key(self, title, key, read_only=False): """Create a new key for the authenticated user. :param str title: (required), key title :param str key: (required), actual key contents, accepts path as a string or file-like object :param bool read_only: (optional), restrict key access to read-only, default to False :returns: created key :rtype: :class:`~github3.users.Key` """ json = None if title and key: data = {"title": title, "key": key, "read_only": read_only} url = self._build_url("user", "keys") req = self._post(url, data=data) json = self._json(req, 201) return self._instance_or_null(users.Key, json)
[ "def", "create_key", "(", "self", ",", "title", ",", "key", ",", "read_only", "=", "False", ")", ":", "json", "=", "None", "if", "title", "and", "key", ":", "data", "=", "{", "\"title\"", ":", "title", ",", "\"key\"", ":", "key", ",", "\"read_only\""...
https://github.com/sigmavirus24/github3.py/blob/f642a27833d6bef93daf5bb27b35e5ddbcfbb773/src/github3/github.py#L714-L736
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/hosts/views_auth.py
python
load_batch_auth
(request)
[]
def load_batch_auth(request): if 'buf' in request.POST: buf = request.POST['buf'] list_buf = buf.splitlines() list_buf = [l for l in list_buf if l and not re.match('#', l)] num = 0 for l in list_buf: logger.error('save %s' % l) try: (ip, remoteuser, authtype, password) = re.split('\s+', l)[:4] ip, created = models.IP.objects.get_or_create(ip=ip) logger.error('ip [%s] created[%s]' %(ip, created)) remoteuser, created = models.RemoteUser.objects.get_or_create(name=remoteuser) logger.error('remoteuser [%s] created[%s]' %(remoteuser, created)) obj_auth = models.AuthByIpAndRemoteUser(ip=ip, remoteUser=remoteuser, authtype=authtype, password=password) obj_auth.validate_unique() obj_auth.save() num += 1 except: logger.error('%s' % traceback.format_exc()) messages.info(request, 'load %s auths, filter %s ones' % (num, len(list_buf) - num)) return HttpResponseRedirect('/admin/hosts/authbyipandremoteuser/') elif 'buf' in request.GET: logger.error(request.GET) return HttpResponseRedirect('/admin/hosts/authbyipandremoteuser/')
[ "def", "load_batch_auth", "(", "request", ")", ":", "if", "'buf'", "in", "request", ".", "POST", ":", "buf", "=", "request", ".", "POST", "[", "'buf'", "]", "list_buf", "=", "buf", ".", "splitlines", "(", ")", "list_buf", "=", "[", "l", "for", "l", ...
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/hosts/views_auth.py#L25-L51
timkpaine/pyEX
254acd2b0cf7cb7183100106f4ecc11d1860c46a
pyEX/stocks/iex.py
python
iexOfficialPrice
(symbol=None, token="", version="stable", format="json")
return _get("deep/official-price", token=token, version=version, format=format)
The Official Price message is used to disseminate the IEX Official Opening and Closing Prices. These messages will be provided only for IEX Listed Securities. https://iexcloud.io/docs/api/#deep-official-price Args: symbol (str): Ticker to request token (str): Access token version (str): API version format (str): return format, defaults to json Returns: dict: result
The Official Price message is used to disseminate the IEX Official Opening and Closing Prices.
[ "The", "Official", "Price", "message", "is", "used", "to", "disseminate", "the", "IEX", "Official", "Opening", "and", "Closing", "Prices", "." ]
def iexOfficialPrice(symbol=None, token="", version="stable", format="json"): """The Official Price message is used to disseminate the IEX Official Opening and Closing Prices. These messages will be provided only for IEX Listed Securities. https://iexcloud.io/docs/api/#deep-official-price Args: symbol (str): Ticker to request token (str): Access token version (str): API version format (str): return format, defaults to json Returns: dict: result """ _raiseIfNotStr(symbol) if symbol: return _get( "deep/official-price?symbols=" + _quoteSymbols(symbol), token=token, version=version, format=format, ) return _get("deep/official-price", token=token, version=version, format=format)
[ "def", "iexOfficialPrice", "(", "symbol", "=", "None", ",", "token", "=", "\"\"", ",", "version", "=", "\"stable\"", ",", "format", "=", "\"json\"", ")", ":", "_raiseIfNotStr", "(", "symbol", ")", "if", "symbol", ":", "return", "_get", "(", "\"deep/officia...
https://github.com/timkpaine/pyEX/blob/254acd2b0cf7cb7183100106f4ecc11d1860c46a/pyEX/stocks/iex.py#L350-L374
Calysto/calysto_scheme
15bf81987870bcae1264e5a0a06feb9a8ee12b8b
calysto_scheme/scheme.py
python
try_body_hat
(x)
return cadr_hat(x)
[]
def try_body_hat(x): return cadr_hat(x)
[ "def", "try_body_hat", "(", "x", ")", ":", "return", "cadr_hat", "(", "x", ")" ]
https://github.com/Calysto/calysto_scheme/blob/15bf81987870bcae1264e5a0a06feb9a8ee12b8b/calysto_scheme/scheme.py#L6853-L6854
qxf2/qxf2-page-object-model
8b2978e5bd2a5413d581f9e29a2098e5f5e742fd
utils/BrowserStack_Library.py
python
BrowserStack_Library.get_session_url
(self)
return session_url
Get the session URL
Get the session URL
[ "Get", "the", "session", "URL" ]
def get_session_url(self): "Get the session URL" build_id = self.get_build_id() session_id = self.get_active_session_id() session_url = self.browserstack_url + 'builds/%s/sessions/%s'%(build_id,session_id) return session_url
[ "def", "get_session_url", "(", "self", ")", ":", "build_id", "=", "self", ".", "get_build_id", "(", ")", "session_id", "=", "self", ".", "get_active_session_id", "(", ")", "session_url", "=", "self", ".", "browserstack_url", "+", "'builds/%s/sessions/%s'", "%", ...
https://github.com/qxf2/qxf2-page-object-model/blob/8b2978e5bd2a5413d581f9e29a2098e5f5e742fd/utils/BrowserStack_Library.py#L63-L69
CvvT/dumpDex
92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1
python/idaapi.py
python
cinsnptrvec_t.at
(self, *args)
return _idaapi.cinsnptrvec_t_at(self, *args)
at(self, n) -> cinsn_t
at(self, n) -> cinsn_t
[ "at", "(", "self", "n", ")", "-", ">", "cinsn_t" ]
def at(self, *args): """ at(self, n) -> cinsn_t """ return _idaapi.cinsnptrvec_t_at(self, *args)
[ "def", "at", "(", "self", ",", "*", "args", ")", ":", "return", "_idaapi", ".", "cinsnptrvec_t_at", "(", "self", ",", "*", "args", ")" ]
https://github.com/CvvT/dumpDex/blob/92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1/python/idaapi.py#L33968-L33972
freelawproject/courtlistener
ab3ae7bb6e5e836b286749113e7dbb403d470912
cl/search/views.py
python
check_pagination_depth
(page_number)
Check if the pagination is too deep (indicating a crawler)
Check if the pagination is too deep (indicating a crawler)
[ "Check", "if", "the", "pagination", "is", "too", "deep", "(", "indicating", "a", "crawler", ")" ]
def check_pagination_depth(page_number): """Check if the pagination is too deep (indicating a crawler)""" max_search_pagination_depth = 100 if page_number > max_search_pagination_depth: logger.warning( "Query depth of %s denied access (probably a crawler)", page_number, ) raise PermissionDenied
[ "def", "check_pagination_depth", "(", "page_number", ")", ":", "max_search_pagination_depth", "=", "100", "if", "page_number", ">", "max_search_pagination_depth", ":", "logger", ".", "warning", "(", "\"Query depth of %s denied access (probably a crawler)\"", ",", "page_number...
https://github.com/freelawproject/courtlistener/blob/ab3ae7bb6e5e836b286749113e7dbb403d470912/cl/search/views.py#L50-L58
WebwareForPython/DBUtils
798d5ad3bdfccdebc22fd3d7b16c8b9e86bdcaf7
dbutils/steady_db.py
python
SteadyDBCursor.__iter__
(self)
Make cursor compatible to the iteration protocol.
Make cursor compatible to the iteration protocol.
[ "Make", "cursor", "compatible", "to", "the", "iteration", "protocol", "." ]
def __iter__(self): """Make cursor compatible to the iteration protocol.""" cursor = self._cursor try: # use iterator provided by original cursor return iter(cursor) except TypeError: # create iterator if not provided return iter(cursor.fetchone, None)
[ "def", "__iter__", "(", "self", ")", ":", "cursor", "=", "self", ".", "_cursor", "try", ":", "# use iterator provided by original cursor", "return", "iter", "(", "cursor", ")", "except", "TypeError", ":", "# create iterator if not provided", "return", "iter", "(", ...
https://github.com/WebwareForPython/DBUtils/blob/798d5ad3bdfccdebc22fd3d7b16c8b9e86bdcaf7/dbutils/steady_db.py#L545-L551
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.4/django/forms/forms.py
python
BoundField.as_textarea
(self, attrs=None, **kwargs)
return self.as_widget(Textarea(), attrs, **kwargs)
Returns a string of HTML for representing this as a <textarea>.
Returns a string of HTML for representing this as a <textarea>.
[ "Returns", "a", "string", "of", "HTML", "for", "representing", "this", "as", "a", "<textarea", ">", "." ]
def as_textarea(self, attrs=None, **kwargs): "Returns a string of HTML for representing this as a <textarea>." return self.as_widget(Textarea(), attrs, **kwargs)
[ "def", "as_textarea", "(", "self", ",", "attrs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "as_widget", "(", "Textarea", "(", ")", ",", "attrs", ",", "*", "*", "kwargs", ")" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.4/django/forms/forms.py#L466-L468
Finance-Hub/FinanceHub
3968d9965e8e2c3b5850f1852b56c485859a9c89
dataapi/AWS/getb3derivatives.py
python
DI1.dv01
(self, code, t)
return dv01
compute the dv01 based on the last quote of date t. :param code: contract code :param t: reference date
compute the dv01 based on the last quote of date t. :param code: contract code :param t: reference date
[ "compute", "the", "dv01", "based", "on", "the", "last", "quote", "of", "date", "t", ".", ":", "param", "code", ":", "contract", "code", ":", "param", "t", ":", "reference", "date" ]
def dv01(self, code, t): """ compute the dv01 based on the last quote of date t. :param code: contract code :param t: reference date """ du = self.du2maturity(t, code) y = self.implied_yield(code, t) pu = self.theoretical_price(code, t) dPdy = pu * (-du/252) / (1 + y) dv01 = dPdy/10000 # changes to 1bp move return dv01
[ "def", "dv01", "(", "self", ",", "code", ",", "t", ")", ":", "du", "=", "self", ".", "du2maturity", "(", "t", ",", "code", ")", "y", "=", "self", ".", "implied_yield", "(", "code", ",", "t", ")", "pu", "=", "self", ".", "theoretical_price", "(", ...
https://github.com/Finance-Hub/FinanceHub/blob/3968d9965e8e2c3b5850f1852b56c485859a9c89/dataapi/AWS/getb3derivatives.py#L194-L205
mpenning/ciscoconfparse
a6a176e6ceac7c5f3e974272fa70273476ba84a3
ciscoconfparse/models_nxos.py
python
NXOSvPCLine.has_layer3_peer_router
(self)
return retval
[]
def has_layer3_peer_router(self): retval = self.re_match_iter_typed( r"^\s+(layer3\s+peer-router)", result_type=bool, default=False ) return retval
[ "def", "has_layer3_peer_router", "(", "self", ")", ":", "retval", "=", "self", ".", "re_match_iter_typed", "(", "r\"^\\s+(layer3\\s+peer-router)\"", ",", "result_type", "=", "bool", ",", "default", "=", "False", ")", "return", "retval" ]
https://github.com/mpenning/ciscoconfparse/blob/a6a176e6ceac7c5f3e974272fa70273476ba84a3/ciscoconfparse/models_nxos.py#L1806-L1810
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit /tools/inject/thirdparty/bottle/bottle.py
python
Route.call
(self)
return self._make_callback()
The route callback with all plugins applied. This property is created on demand and then cached to speed up subsequent requests.
The route callback with all plugins applied. This property is created on demand and then cached to speed up subsequent requests.
[ "The", "route", "callback", "with", "all", "plugins", "applied", ".", "This", "property", "is", "created", "on", "demand", "and", "then", "cached", "to", "speed", "up", "subsequent", "requests", "." ]
def call(self): ''' The route callback with all plugins applied. This property is created on demand and then cached to speed up subsequent requests.''' return self._make_callback()
[ "def", "call", "(", "self", ")", ":", "return", "self", ".", "_make_callback", "(", ")" ]
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit /tools/inject/thirdparty/bottle/bottle.py#L447-L450
d2l-ai/d2l-zh
1c2e25a557db446b5691c18e595e5664cc254730
d2l/torch.py
python
grad_clipping
(net, theta)
裁剪梯度 Defined in :numref:`sec_rnn_scratch`
裁剪梯度
[ "裁剪梯度" ]
def grad_clipping(net, theta): """裁剪梯度 Defined in :numref:`sec_rnn_scratch`""" if isinstance(net, nn.Module): params = [p for p in net.parameters() if p.requires_grad] else: params = net.params norm = torch.sqrt(sum(torch.sum((p.grad ** 2)) for p in params)) if norm > theta: for param in params: param.grad[:] *= theta / norm
[ "def", "grad_clipping", "(", "net", ",", "theta", ")", ":", "if", "isinstance", "(", "net", ",", "nn", ".", "Module", ")", ":", "params", "=", "[", "p", "for", "p", "in", "net", ".", "parameters", "(", ")", "if", "p", ".", "requires_grad", "]", "...
https://github.com/d2l-ai/d2l-zh/blob/1c2e25a557db446b5691c18e595e5664cc254730/d2l/torch.py#L711-L722
sahana/eden
1696fa50e90ce967df69f66b571af45356cc18da
modules/s3cfg.py
python
S3Config.get_gis_poi_create_resources
(self)
return self.gis.get("poi_create_resources", [{"c": "gis", # Controller "f": "poi", # Function "table": "gis_poi", # For permissions check # Default: #"type": "point", # Feature Type: point, line or polygon "label": T("Add PoI"), # Label #"tooltip": T("Add PoI"), # Tooltip "layer": "PoIs", # Layer Name to refresh "location": "button", # Location to access from }, ] )
List of resources which can be directly added to the main map. Includes the type (point, line or polygon) and where they are to be accessed from (button, menu or popup) Defaults to the generic 'gis_poi' resource as a point from a button @ToDo: Complete the button vs menu vs popup @ToDo: S3PoIWidget() to allow other resources to pickup the passed Lat/Lon/WKT
List of resources which can be directly added to the main map. Includes the type (point, line or polygon) and where they are to be accessed from (button, menu or popup)
[ "List", "of", "resources", "which", "can", "be", "directly", "added", "to", "the", "main", "map", ".", "Includes", "the", "type", "(", "point", "line", "or", "polygon", ")", "and", "where", "they", "are", "to", "be", "accessed", "from", "(", "button", ...
def get_gis_poi_create_resources(self): """ List of resources which can be directly added to the main map. Includes the type (point, line or polygon) and where they are to be accessed from (button, menu or popup) Defaults to the generic 'gis_poi' resource as a point from a button @ToDo: Complete the button vs menu vs popup @ToDo: S3PoIWidget() to allow other resources to pickup the passed Lat/Lon/WKT """ T = current.T return self.gis.get("poi_create_resources", [{"c": "gis", # Controller "f": "poi", # Function "table": "gis_poi", # For permissions check # Default: #"type": "point", # Feature Type: point, line or polygon "label": T("Add PoI"), # Label #"tooltip": T("Add PoI"), # Tooltip "layer": "PoIs", # Layer Name to refresh "location": "button", # Location to access from }, ] )
[ "def", "get_gis_poi_create_resources", "(", "self", ")", ":", "T", "=", "current", ".", "T", "return", "self", ".", "gis", ".", "get", "(", "\"poi_create_resources\"", ",", "[", "{", "\"c\"", ":", "\"gis\"", ",", "# Controller", "\"f\"", ":", "\"poi\"", ",...
https://github.com/sahana/eden/blob/1696fa50e90ce967df69f66b571af45356cc18da/modules/s3cfg.py#L1657-L1681
SteveDoyle2/pyNastran
eda651ac2d4883d95a34951f8a002ff94f642a1a
pyNastran/op2/tables/geom/edt.py
python
EDT._read_aesurfs
(self, data: bytes, n: int)
return n
Word Name Type Description 1 ID I Identification of an aerodynamic trim variable degree of freedom >0, no default 2 LABEL(2) CHAR4 Control Surface (CS) name, no default 4 LIST1 I Identification of a SET1 that contains the grids ids associated with this control surface 5 LIST2 I Identification of a SET1 that contains the grids ids associated with this control surface
Word Name Type Description 1 ID I Identification of an aerodynamic trim variable degree of freedom >0, no default 2 LABEL(2) CHAR4 Control Surface (CS) name, no default 4 LIST1 I Identification of a SET1 that contains the grids ids associated with this control surface 5 LIST2 I Identification of a SET1 that contains the grids ids associated with this control surface
[ "Word", "Name", "Type", "Description", "1", "ID", "I", "Identification", "of", "an", "aerodynamic", "trim", "variable", "degree", "of", "freedom", ">", "0", "no", "default", "2", "LABEL", "(", "2", ")", "CHAR4", "Control", "Surface", "(", "CS", ")", "nam...
def _read_aesurfs(self, data: bytes, n: int) -> int: """ Word Name Type Description 1 ID I Identification of an aerodynamic trim variable degree of freedom >0, no default 2 LABEL(2) CHAR4 Control Surface (CS) name, no default 4 LIST1 I Identification of a SET1 that contains the grids ids associated with this control surface 5 LIST2 I Identification of a SET1 that contains the grids ids associated with this control surface """ op2 = self.op2 ntotal = 20 * self.factor # 4 * 5 ndatai = len(data) - n ncards = ndatai // ntotal assert ndatai % ntotal == 0 if self.size == 4: struct1 = Struct(op2._endian + b'i 8s 2i') else: struct1 = Struct(op2._endian + b'i 16s 2i') for unused_i in range(ncards): edata = data[n:n + ntotal] out1 = struct1.unpack(edata) aesid, label_bytes, list1, list2 = out1 label = reshape_bytes_block_size(label_bytes, self.size) aesurfs = op2.add_aesurfs(aesid, label, list1, list2) str(aesurfs) n += ntotal return n
[ "def", "_read_aesurfs", "(", "self", ",", "data", ":", "bytes", ",", "n", ":", "int", ")", "->", "int", ":", "op2", "=", "self", ".", "op2", "ntotal", "=", "20", "*", "self", ".", "factor", "# 4 * 5", "ndatai", "=", "len", "(", "data", ")", "-", ...
https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/op2/tables/geom/edt.py#L2440-L2471
googlefonts/nototools
903a218f62256a286cde48c76b3051703f8a1de5
nototools/noto_lint.py
python
all_scripts
()
return frozenset(result)
Extends unicode scripts with pseudo-script 'Urdu'.
Extends unicode scripts with pseudo-script 'Urdu'.
[ "Extends", "unicode", "scripts", "with", "pseudo", "-", "script", "Urdu", "." ]
def all_scripts(): """Extends unicode scripts with pseudo-script 'Urdu'.""" result = set(unicode_data.all_scripts()) result.add("Urdu") return frozenset(result)
[ "def", "all_scripts", "(", ")", ":", "result", "=", "set", "(", "unicode_data", ".", "all_scripts", "(", ")", ")", "result", ".", "add", "(", "\"Urdu\"", ")", "return", "frozenset", "(", "result", ")" ]
https://github.com/googlefonts/nototools/blob/903a218f62256a286cde48c76b3051703f8a1de5/nototools/noto_lint.py#L68-L72
pycom/pycom-libraries
75d0e67cb421e0576a3a9677bb0d9d81f27ebdb7
pymesh/pymesh_frozen/lib/ble_rpc.py
python
RPCHandler.send_message_was_sent
(self, mac, msg_id)
return self.mesh.mesage_was_ack(mac, msg_id)
checks for ACK received for msg_id returns True if message was delivered to last node connected to BLE mobile
checks for ACK received for msg_id returns True if message was delivered to last node connected to BLE mobile
[ "checks", "for", "ACK", "received", "for", "msg_id", "returns", "True", "if", "message", "was", "delivered", "to", "last", "node", "connected", "to", "BLE", "mobile" ]
def send_message_was_sent(self, mac, msg_id): """ checks for ACK received for msg_id returns True if message was delivered to last node connected to BLE mobile """ error = False try: mac_int = int(mac) msg_id_int = int(msg_id) except: error = True if error: return False # mesh.mesage_was_ack(5, 12345) return self.mesh.mesage_was_ack(mac, msg_id)
[ "def", "send_message_was_sent", "(", "self", ",", "mac", ",", "msg_id", ")", ":", "error", "=", "False", "try", ":", "mac_int", "=", "int", "(", "mac", ")", "msg_id_int", "=", "int", "(", "msg_id", ")", "except", ":", "error", "=", "True", "if", "err...
https://github.com/pycom/pycom-libraries/blob/75d0e67cb421e0576a3a9677bb0d9d81f27ebdb7/pymesh/pymesh_frozen/lib/ble_rpc.py#L288-L300
sdaps/sdaps
51d1072185223f5e48512661e2c1e8399d63e876
sdaps/paths.py
python
init_gettext
(locale_dir)
Initialize gettext using the given directory containing the l10n data.
Initialize gettext using the given directory containing the l10n data.
[ "Initialize", "gettext", "using", "the", "given", "directory", "containing", "the", "l10n", "data", "." ]
def init_gettext(locale_dir): '''Initialize gettext using the given directory containing the l10n data. ''' gettext.bindtextdomain('sdaps', locale_dir) if hasattr(gettext, 'bind_textdomain_codeset'): gettext.bind_textdomain_codeset('sdaps', 'UTF-8') gettext.textdomain('sdaps') if hasattr(locale, 'bind_textdomain_codeset'): locale.bindtextdomain('sdaps', locale_dir) locale.bind_textdomain_codeset('sdaps', 'UTF-8') locale.textdomain('sdaps')
[ "def", "init_gettext", "(", "locale_dir", ")", ":", "gettext", ".", "bindtextdomain", "(", "'sdaps'", ",", "locale_dir", ")", "if", "hasattr", "(", "gettext", ",", "'bind_textdomain_codeset'", ")", ":", "gettext", ".", "bind_textdomain_codeset", "(", "'sdaps'", ...
https://github.com/sdaps/sdaps/blob/51d1072185223f5e48512661e2c1e8399d63e876/sdaps/paths.py#L89-L100
twisted/twisted
dee676b040dd38b847ea6fb112a712cb5e119490
src/twisted/internet/process.py
python
ProcessWriter.fileno
(self)
return self.fd
Return the fileno() of my process's stdin.
Return the fileno() of my process's stdin.
[ "Return", "the", "fileno", "()", "of", "my", "process", "s", "stdin", "." ]
def fileno(self): """ Return the fileno() of my process's stdin. """ return self.fd
[ "def", "fileno", "(", "self", ")", ":", "return", "self", ".", "fd" ]
https://github.com/twisted/twisted/blob/dee676b040dd38b847ea6fb112a712cb5e119490/src/twisted/internet/process.py#L157-L161
HewlettPackard/dlcookbook-dlbs
863ac1d7e72ad2fcafc78d8a13f67d35bc00c235
python/dlbs/data/imagenet/tensorflow_build_imagenet_data.py
python
_process_image_files_batch
(coder, thread_index, ranges, name, filenames, synsets, labels, humans, bboxes, num_shards)
Processes and saves list of images as TFRecord in 1 thread. Args: coder: instance of ImageCoder to provide TensorFlow image coding utils. thread_index: integer, unique batch to run index is within [0, len(ranges)). ranges: list of pairs of integers specifying ranges of each batches to analyze in parallel. name: string, unique identifier specifying the data set filenames: list of strings; each string is a path to an image file synsets: list of strings; each string is a unique WordNet ID labels: list of integer; each integer identifies the ground truth humans: list of strings; each string is a human-readable label bboxes: list of bounding boxes for each image. Note that each entry in this list might contain from 0+ entries corresponding to the number of bounding box annotations for the image. num_shards: integer number of shards for this data set.
Processes and saves list of images as TFRecord in 1 thread.
[ "Processes", "and", "saves", "list", "of", "images", "as", "TFRecord", "in", "1", "thread", "." ]
def _process_image_files_batch(coder, thread_index, ranges, name, filenames, synsets, labels, humans, bboxes, num_shards): """Processes and saves list of images as TFRecord in 1 thread. Args: coder: instance of ImageCoder to provide TensorFlow image coding utils. thread_index: integer, unique batch to run index is within [0, len(ranges)). ranges: list of pairs of integers specifying ranges of each batches to analyze in parallel. name: string, unique identifier specifying the data set filenames: list of strings; each string is a path to an image file synsets: list of strings; each string is a unique WordNet ID labels: list of integer; each integer identifies the ground truth humans: list of strings; each string is a human-readable label bboxes: list of bounding boxes for each image. Note that each entry in this list might contain from 0+ entries corresponding to the number of bounding box annotations for the image. num_shards: integer number of shards for this data set. """ # Each thread produces N shards where N = int(num_shards / num_threads). # For instance, if num_shards = 128, and the num_threads = 2, then the first # thread would produce shards [0, 64). num_threads = len(ranges) assert not num_shards % num_threads num_shards_per_batch = int(num_shards / num_threads) shard_ranges = np.linspace(ranges[thread_index][0], ranges[thread_index][1], num_shards_per_batch + 1).astype(int) num_files_in_thread = ranges[thread_index][1] - ranges[thread_index][0] counter = 0 for s in range(num_shards_per_batch): # Generate a sharded version of the file name, e.g. 'train-00002-of-00010' shard = thread_index * num_shards_per_batch + s output_filename = '%s-%.5d-of-%.5d' % (name, shard, num_shards) output_file = os.path.join(FLAGS.output_directory, output_filename) writer = tf.python_io.TFRecordWriter(output_file) shard_counter = 0 files_in_shard = np.arange(shard_ranges[s], shard_ranges[s + 1], dtype=int) for i in files_in_shard: filename = filenames[i] label = labels[i] synset = synsets[i] human = humans[i] bbox = bboxes[i] image_buffer, height, width = _process_image(filename, coder) example = _convert_to_example(filename, image_buffer, label, synset, human, bbox, height, width) writer.write(example.SerializeToString()) shard_counter += 1 counter += 1 if not counter % 1000: print('%s [thread %d]: Processed %d of %d images in thread batch.' % (datetime.now(), thread_index, counter, num_files_in_thread)) sys.stdout.flush() writer.close() print('%s [thread %d]: Wrote %d images to %s' % (datetime.now(), thread_index, shard_counter, output_file)) sys.stdout.flush() shard_counter = 0 print('%s [thread %d]: Wrote %d images to %d shards.' % (datetime.now(), thread_index, counter, num_files_in_thread)) sys.stdout.flush()
[ "def", "_process_image_files_batch", "(", "coder", ",", "thread_index", ",", "ranges", ",", "name", ",", "filenames", ",", "synsets", ",", "labels", ",", "humans", ",", "bboxes", ",", "num_shards", ")", ":", "# Each thread produces N shards where N = int(num_shards / ...
https://github.com/HewlettPackard/dlcookbook-dlbs/blob/863ac1d7e72ad2fcafc78d8a13f67d35bc00c235/python/dlbs/data/imagenet/tensorflow_build_imagenet_data.py#L340-L409
theotherp/nzbhydra
4b03d7f769384b97dfc60dade4806c0fc987514e
libs/flask_cache/__init__.py
python
Cache.delete_memoized
(self, f, *args, **kwargs)
Deletes the specified functions caches, based by given parameters. If parameters are given, only the functions that were memoized with them will be erased. Otherwise all versions of the caches will be forgotten. Example:: @cache.memoize(50) def random_func(): return random.randrange(1, 50) @cache.memoize() def param_func(a, b): return a+b+random.randrange(1, 50) .. code-block:: pycon >>> random_func() 43 >>> random_func() 43 >>> cache.delete_memoized('random_func') >>> random_func() 16 >>> param_func(1, 2) 32 >>> param_func(1, 2) 32 >>> param_func(2, 2) 47 >>> cache.delete_memoized('param_func', 1, 2) >>> param_func(1, 2) 13 >>> param_func(2, 2) 47 Delete memoized is also smart about instance methods vs class methods. When passing a instancemethod, it will only clear the cache related to that instance of that object. (object uniqueness can be overridden by defining the __repr__ method, such as user id). When passing a classmethod, it will clear all caches related across all instances of that class. Example:: class Adder(object): @cache.memoize() def add(self, b): return b + random.random() .. code-block:: pycon >>> adder1 = Adder() >>> adder2 = Adder() >>> adder1.add(3) 3.23214234 >>> adder2.add(3) 3.60898509 >>> cache.delete_memoized(adder.add) >>> adder1.add(3) 3.01348673 >>> adder2.add(3) 3.60898509 >>> cache.delete_memoized(Adder.add) >>> adder1.add(3) 3.53235667 >>> adder2.add(3) 3.72341788 :param fname: Name of the memoized function, or a reference to the function. :param \*args: A list of positional parameters used with memoized function. :param \**kwargs: A dict of named parameters used with memoized function. .. note:: Flask-Cache uses inspect to order kwargs into positional args when the function is memoized. If you pass a function reference into ``fname`` instead of the function name, Flask-Cache will be able to place the args/kwargs in the proper order, and delete the positional cache. However, if ``delete_memoized`` is just called with the name of the function, be sure to pass in potential arguments in the same order as defined in your function as args only, otherwise Flask-Cache will not be able to compute the same cache key. .. note:: Flask-Cache maintains an internal random version hash for the function. Using delete_memoized will only swap out the version hash, causing the memoize function to recompute results and put them into another key. This leaves any computed caches for this memoized function within the caching backend. It is recommended to use a very high timeout with memoize if using this function, so that when the version has is swapped, the old cached results would eventually be reclaimed by the caching backend.
Deletes the specified functions caches, based by given parameters. If parameters are given, only the functions that were memoized with them will be erased. Otherwise all versions of the caches will be forgotten.
[ "Deletes", "the", "specified", "functions", "caches", "based", "by", "given", "parameters", ".", "If", "parameters", "are", "given", "only", "the", "functions", "that", "were", "memoized", "with", "them", "will", "be", "erased", ".", "Otherwise", "all", "versi...
def delete_memoized(self, f, *args, **kwargs): """ Deletes the specified functions caches, based by given parameters. If parameters are given, only the functions that were memoized with them will be erased. Otherwise all versions of the caches will be forgotten. Example:: @cache.memoize(50) def random_func(): return random.randrange(1, 50) @cache.memoize() def param_func(a, b): return a+b+random.randrange(1, 50) .. code-block:: pycon >>> random_func() 43 >>> random_func() 43 >>> cache.delete_memoized('random_func') >>> random_func() 16 >>> param_func(1, 2) 32 >>> param_func(1, 2) 32 >>> param_func(2, 2) 47 >>> cache.delete_memoized('param_func', 1, 2) >>> param_func(1, 2) 13 >>> param_func(2, 2) 47 Delete memoized is also smart about instance methods vs class methods. When passing a instancemethod, it will only clear the cache related to that instance of that object. (object uniqueness can be overridden by defining the __repr__ method, such as user id). When passing a classmethod, it will clear all caches related across all instances of that class. Example:: class Adder(object): @cache.memoize() def add(self, b): return b + random.random() .. code-block:: pycon >>> adder1 = Adder() >>> adder2 = Adder() >>> adder1.add(3) 3.23214234 >>> adder2.add(3) 3.60898509 >>> cache.delete_memoized(adder.add) >>> adder1.add(3) 3.01348673 >>> adder2.add(3) 3.60898509 >>> cache.delete_memoized(Adder.add) >>> adder1.add(3) 3.53235667 >>> adder2.add(3) 3.72341788 :param fname: Name of the memoized function, or a reference to the function. :param \*args: A list of positional parameters used with memoized function. :param \**kwargs: A dict of named parameters used with memoized function. .. note:: Flask-Cache uses inspect to order kwargs into positional args when the function is memoized. If you pass a function reference into ``fname`` instead of the function name, Flask-Cache will be able to place the args/kwargs in the proper order, and delete the positional cache. However, if ``delete_memoized`` is just called with the name of the function, be sure to pass in potential arguments in the same order as defined in your function as args only, otherwise Flask-Cache will not be able to compute the same cache key. .. note:: Flask-Cache maintains an internal random version hash for the function. Using delete_memoized will only swap out the version hash, causing the memoize function to recompute results and put them into another key. This leaves any computed caches for this memoized function within the caching backend. It is recommended to use a very high timeout with memoize if using this function, so that when the version has is swapped, the old cached results would eventually be reclaimed by the caching backend. """ if not callable(f): raise DeprecationWarning("Deleting messages by relative name is no longer" " reliable, please switch to a function reference") try: if not args and not kwargs: self._memoize_version(f, reset=True) else: cache_key = f.make_cache_key(f.uncached, *args, **kwargs) self.cache.delete(cache_key) except Exception: if current_app.debug: raise logger.exception("Exception possibly due to cache backend.")
[ "def", "delete_memoized", "(", "self", ",", "f", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "callable", "(", "f", ")", ":", "raise", "DeprecationWarning", "(", "\"Deleting messages by relative name is no longer\"", "\" reliable, please switc...
https://github.com/theotherp/nzbhydra/blob/4b03d7f769384b97dfc60dade4806c0fc987514e/libs/flask_cache/__init__.py#L556-L671
rembo10/headphones
b3199605be1ebc83a7a8feab6b1e99b64014187c
lib/cherrypy/_cpcompat_subprocess.py
python
check_output
(*popenargs, **kwargs)
return output
r"""Run command with arguments and return its output as a byte string. If the exit code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and output in the output attribute. The arguments are the same as for the Popen constructor. Example: >>> check_output(["ls", "-l", "/dev/null"]) 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n' The stdout argument is not allowed as it is used internally. To capture standard error in the result, use stderr=STDOUT. >>> check_output(["/bin/sh", "-c", ... "ls -l non_existent_file ; exit 0"], ... stderr=STDOUT) 'ls: non_existent_file: No such file or directory\n'
r"""Run command with arguments and return its output as a byte string.
[ "r", "Run", "command", "with", "arguments", "and", "return", "its", "output", "as", "a", "byte", "string", "." ]
def check_output(*popenargs, **kwargs): r"""Run command with arguments and return its output as a byte string. If the exit code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and output in the output attribute. The arguments are the same as for the Popen constructor. Example: >>> check_output(["ls", "-l", "/dev/null"]) 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n' The stdout argument is not allowed as it is used internally. To capture standard error in the result, use stderr=STDOUT. >>> check_output(["/bin/sh", "-c", ... "ls -l non_existent_file ; exit 0"], ... stderr=STDOUT) 'ls: non_existent_file: No such file or directory\n' """ if 'stdout' in kwargs: raise ValueError('stdout argument not allowed, it will be overridden.') process = Popen(stdout=PIPE, *popenargs, **kwargs) output, unused_err = process.communicate() retcode = process.poll() if retcode: cmd = kwargs.get("args") if cmd is None: cmd = popenargs[0] raise CalledProcessError(retcode, cmd, output=output) return output
[ "def", "check_output", "(", "*", "popenargs", ",", "*", "*", "kwargs", ")", ":", "if", "'stdout'", "in", "kwargs", ":", "raise", "ValueError", "(", "'stdout argument not allowed, it will be overridden.'", ")", "process", "=", "Popen", "(", "stdout", "=", "PIPE",...
https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/cherrypy/_cpcompat_subprocess.py#L529-L559
cogeotiff/rio-cogeo
a07d914e2d898878417638bbc089179f01eb5b28
rio_cogeo/scripts/cli.py
python
create_tag_table
(tags: typing.Dict, sep: int)
return table
Helper method to create a table from dictionary of image tags -- used by info cli
Helper method to create a table from dictionary of image tags -- used by info cli
[ "Helper", "method", "to", "create", "a", "table", "from", "dictionary", "of", "image", "tags", "--", "used", "by", "info", "cli" ]
def create_tag_table(tags: typing.Dict, sep: int) -> str: """Helper method to create a table from dictionary of image tags -- used by info cli""" table = "" for idx, (k, v) in enumerate(tags.items()): name = f"{k}:" row = f"{click.style(name, bold=True):<{sep}} {v}" if idx + 1 != len(tags): row += "\n " table += row return table
[ "def", "create_tag_table", "(", "tags", ":", "typing", ".", "Dict", ",", "sep", ":", "int", ")", "->", "str", ":", "table", "=", "\"\"", "for", "idx", ",", "(", "k", ",", "v", ")", "in", "enumerate", "(", "tags", ".", "items", "(", ")", ")", ":...
https://github.com/cogeotiff/rio-cogeo/blob/a07d914e2d898878417638bbc089179f01eb5b28/rio_cogeo/scripts/cli.py#L24-L33
TeaPearce/precipitation-prediction-convLSTM-keras
03d3492f113637395cbdebbe5adf2a3461dbc0b4
precip_v09.py
python
fn_get_model_2D_timeD
()
return model
[]
def fn_get_model_2D_timeD(): t_frames, rows, cols = 15, 101, 101 input_shape = (t_frames, rows, cols, 1) inp = Input(shape=input_shape) inpN = BatchNormalization()(inp) c1 = Conv3D(filters=8, kernel_size= (5,5,5), strides=(1,1,1), activation='relu', kernel_initializer='glorot_uniform', padding='same')(inpN) c1 = BatchNormalization()(c1) c1 = Conv3D(filters=8, kernel_size= (5,5,5), strides=(1,1,1), activation='relu', kernel_initializer='glorot_uniform', padding='same')(c1) c1 = BatchNormalization()(c1) pool_1 = MaxPooling3D(pool_size=(2,3,3))(c1) drop_1 = Dropout(0.25)(pool_1) c2 = Conv3D(filters=16, kernel_size= (3,3,3), strides=(1,1,1), activation='relu', kernel_initializer='glorot_uniform', padding='same')(drop_1) c2 = BatchNormalization()(c2) c2 = Conv3D(filters=16, kernel_size= (3,3,3), strides=(1,1,1), activation='relu', kernel_initializer='glorot_uniform', padding='same')(c2) c2 = BatchNormalization()(c2) pool_2 = MaxPooling3D(pool_size=(1,3,3))(c2) drop_1 = Dropout(0.25)(pool_2) c3 = Conv3D(filters=32, kernel_size= (3,3,3), strides=(1,1,1), activation='relu', kernel_initializer='glorot_uniform', padding='same')(drop_1) c3 = BatchNormalization()(c3) c3 = Conv3D(filters=32, kernel_size= (3,3,3), strides=(1,1,1), activation='relu', kernel_initializer='glorot_uniform', padding='same')(c3) c3 = BatchNormalization()(c3) pool_3 = MaxPooling3D(pool_size=(1,2,2))(c3) drop_3 = Dropout(0.25)(pool_3) flat = Flatten()(drop_3) hidden_1 = Dense(1024, kernel_initializer='glorot_uniform', activation='relu')(flat) hidden_1 = BatchNormalization()(hidden_1) hidden_1 = Dropout(0.3)(hidden_1) hidden_2 = Dense(512, kernel_initializer='glorot_uniform', activation='relu')(hidden_1) hidden_2 = BatchNormalization()(hidden_2) hidden_2 = Dropout(0.3)(hidden_2) hidden_3 = Dense(124, kernel_initializer='glorot_uniform', activation='relu')(hidden_2) hidden_3 = BatchNormalization()(hidden_3) hidden_3 = Dropout(0.3)(hidden_3) hidden_4 = Dense(8, kernel_initializer='glorot_uniform', activation='relu')(hidden_3) hidden_4 = BatchNormalization()(hidden_4) hidden_4 = Dropout(0.3)(hidden_4) out = Dense(1, activation='relu')(hidden_4) model = Model(outputs=out, inputs=inp) print(model.summary()) return model
[ "def", "fn_get_model_2D_timeD", "(", ")", ":", "t_frames", ",", "rows", ",", "cols", "=", "15", ",", "101", ",", "101", "input_shape", "=", "(", "t_frames", ",", "rows", ",", "cols", ",", "1", ")", "inp", "=", "Input", "(", "shape", "=", "input_shape...
https://github.com/TeaPearce/precipitation-prediction-convLSTM-keras/blob/03d3492f113637395cbdebbe5adf2a3461dbc0b4/precip_v09.py#L510-L564
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/combinat/sf/sfa.py
python
SymmetricFunctionAlgebra_generic_Element.restrict_degree
(self, d, exact = True)
return self.parent()._from_dict(res)
r""" Return the degree ``d`` component of ``self``. INPUT: - ``d`` -- positive integer, degree of the terms to be returned - ``exact`` -- boolean, if ``True``, returns the terms of degree exactly ``d``, otherwise returns all terms of degree less than or equal to ``d`` OUTPUT: - the homogeneous component of ``self`` of degree ``d`` EXAMPLES:: sage: s = SymmetricFunctions(QQ).s() sage: z = s([4]) + s([2,1]) + s([1,1,1]) + s([1]) sage: z.restrict_degree(2) 0 sage: z.restrict_degree(1) s[1] sage: z.restrict_degree(3) s[1, 1, 1] + s[2, 1] sage: z.restrict_degree(3, exact=False) s[1] + s[1, 1, 1] + s[2, 1] sage: z.restrict_degree(0) 0
r""" Return the degree ``d`` component of ``self``.
[ "r", "Return", "the", "degree", "d", "component", "of", "self", "." ]
def restrict_degree(self, d, exact = True): r""" Return the degree ``d`` component of ``self``. INPUT: - ``d`` -- positive integer, degree of the terms to be returned - ``exact`` -- boolean, if ``True``, returns the terms of degree exactly ``d``, otherwise returns all terms of degree less than or equal to ``d`` OUTPUT: - the homogeneous component of ``self`` of degree ``d`` EXAMPLES:: sage: s = SymmetricFunctions(QQ).s() sage: z = s([4]) + s([2,1]) + s([1,1,1]) + s([1]) sage: z.restrict_degree(2) 0 sage: z.restrict_degree(1) s[1] sage: z.restrict_degree(3) s[1, 1, 1] + s[2, 1] sage: z.restrict_degree(3, exact=False) s[1] + s[1, 1, 1] + s[2, 1] sage: z.restrict_degree(0) 0 """ if exact: res = dict(x for x in self._monomial_coefficients.items() if sum(x[0]) == d) else: res = dict(x for x in self._monomial_coefficients.items() if sum(x[0]) <= d) return self.parent()._from_dict(res)
[ "def", "restrict_degree", "(", "self", ",", "d", ",", "exact", "=", "True", ")", ":", "if", "exact", ":", "res", "=", "dict", "(", "x", "for", "x", "in", "self", ".", "_monomial_coefficients", ".", "items", "(", ")", "if", "sum", "(", "x", "[", "...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/sf/sfa.py#L5090-L5125
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/urllib/parse.py
python
to_bytes
(url)
return url
to_bytes(u"URL") --> 'URL'.
to_bytes(u"URL") --> 'URL'.
[ "to_bytes", "(", "u", "URL", ")", "--", ">", "URL", "." ]
def to_bytes(url): """to_bytes(u"URL") --> 'URL'.""" # Most URL schemes require ASCII. If that changes, the conversion # can be relaxed. # XXX get rid of to_bytes() if isinstance(url, str): try: url = url.encode("ASCII").decode() except UnicodeError: raise UnicodeError("URL " + repr(url) + " contains non-ASCII characters") return url
[ "def", "to_bytes", "(", "url", ")", ":", "# Most URL schemes require ASCII. If that changes, the conversion", "# can be relaxed.", "# XXX get rid of to_bytes()", "if", "isinstance", "(", "url", ",", "str", ")", ":", "try", ":", "url", "=", "url", ".", "encode", "(", ...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/urllib/parse.py#L912-L923
nosmokingbandit/watcher
dadacd21a5790ee609058a98a17fcc8954d24439
lib/sqlalchemy/sql/selectable.py
python
FromClause.replace_selectable
(self, sqlutil, old, alias)
return sqlutil.ClauseAdapter(alias).traverse(self)
replace all occurrences of FromClause 'old' with the given Alias object, returning a copy of this :class:`.FromClause`.
replace all occurrences of FromClause 'old' with the given Alias object, returning a copy of this :class:`.FromClause`.
[ "replace", "all", "occurrences", "of", "FromClause", "old", "with", "the", "given", "Alias", "object", "returning", "a", "copy", "of", "this", ":", "class", ":", ".", "FromClause", "." ]
def replace_selectable(self, sqlutil, old, alias): """replace all occurrences of FromClause 'old' with the given Alias object, returning a copy of this :class:`.FromClause`. """ return sqlutil.ClauseAdapter(alias).traverse(self)
[ "def", "replace_selectable", "(", "self", ",", "sqlutil", ",", "old", ",", "alias", ")", ":", "return", "sqlutil", ".", "ClauseAdapter", "(", "alias", ")", ".", "traverse", "(", "self", ")" ]
https://github.com/nosmokingbandit/watcher/blob/dadacd21a5790ee609058a98a17fcc8954d24439/lib/sqlalchemy/sql/selectable.py#L560-L566
JaniceWuo/MovieRecommend
4c86db64ca45598917d304f535413df3bc9fea65
movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/ipaddress.py
python
IPv4Address.is_reserved
(self)
return self in self._constants._reserved_network
Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within the reserved IPv4 Network range.
Test if the address is otherwise IETF reserved.
[ "Test", "if", "the", "address", "is", "otherwise", "IETF", "reserved", "." ]
def is_reserved(self): """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within the reserved IPv4 Network range. """ return self in self._constants._reserved_network
[ "def", "is_reserved", "(", "self", ")", ":", "return", "self", "in", "self", ".", "_constants", ".", "_reserved_network" ]
https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/ipaddress.py#L1417-L1425
and3rson/clay
c271cecf6b6ea6465abcdd2444171b1a565a60a3
clay/songlist.py
python
SongListBox.is_context_menu_visible
(self)
return self.contents['body'][0] is self.overlay
Return ``True`` if context menu is currently being shown.
Return ``True`` if context menu is currently being shown.
[ "Return", "True", "if", "context", "menu", "is", "currently", "being", "shown", "." ]
def is_context_menu_visible(self): """ Return ``True`` if context menu is currently being shown. """ return self.contents['body'][0] is self.overlay
[ "def", "is_context_menu_visible", "(", "self", ")", ":", "return", "self", ".", "contents", "[", "'body'", "]", "[", "0", "]", "is", "self", ".", "overlay" ]
https://github.com/and3rson/clay/blob/c271cecf6b6ea6465abcdd2444171b1a565a60a3/clay/songlist.py#L588-L592
lisa-lab/pylearn2
af81e5c362f0df4df85c3e54e23b2adeec026055
pylearn2/expr/evaluation.py
python
all_pr
(pos_scores, neg_scores)
return precision, recall
Computes all possible precision and recall points given a list of scores assigned to the positive class and a list of scores assigned to the negative class. Parameters ---------- pos_scores : list List of floats. Higher values = more likely to belong to positive class. neg_scores : list List of floats. Higher values = more likely to belong to negative class. Returns ------- precision : list List of all possible precision values obtainable by varying the threshold of the detector. recall : list List of all possible recall values obtainable by varing the threshold of the detector. recall[i] is formed using the same threshold as precision[i]
Computes all possible precision and recall points given a list of scores assigned to the positive class and a list of scores assigned to the negative class.
[ "Computes", "all", "possible", "precision", "and", "recall", "points", "given", "a", "list", "of", "scores", "assigned", "to", "the", "positive", "class", "and", "a", "list", "of", "scores", "assigned", "to", "the", "negative", "class", "." ]
def all_pr(pos_scores, neg_scores): """ Computes all possible precision and recall points given a list of scores assigned to the positive class and a list of scores assigned to the negative class. Parameters ---------- pos_scores : list List of floats. Higher values = more likely to belong to positive class. neg_scores : list List of floats. Higher values = more likely to belong to negative class. Returns ------- precision : list List of all possible precision values obtainable by varying the threshold of the detector. recall : list List of all possible recall values obtainable by varing the threshold of the detector. recall[i] is formed using the same threshold as precision[i] """ # Attach labels to scores labeled_neg = [(x, 0) for x in neg_scores] labeled_pos = [(x, 1) for x in pos_scores] labeled = labeled_pos + labeled_neg # Sort labeled scores by descending score sorted_labeled = sorted(labeled, key=lambda x: -x[0]) label_chunks = [] # Group sorted labels into chunks of equal score prev_score = None cur_chunk = [] for score, label in sorted_labeled: if prev_score is None or prev_score == score: cur_chunk.append(label) else: label_chunks.append(cur_chunk) cur_chunk = [label] prev_score = score label_chunks.append(cur_chunk) # Initialize with threshold set to label all inputs as negative precision = [1.] recall = [0.] tp = 0 fp = 0 fn = len(pos_scores) count = fn # Incrementally raise threshold, with each increment chosen to # label everything with score >= t as positive, where t is the # score of the next tied chunk for label_chunk in label_chunks: for label in label_chunk: if label: fn -= 1 tp += 1 else: fp += 1 ap = tp + fp if ap == 0: precision.append(1.) else: precision.append(float(tp)/float(ap)) recall.append(float(tp)/count) return precision, recall
[ "def", "all_pr", "(", "pos_scores", ",", "neg_scores", ")", ":", "# Attach labels to scores", "labeled_neg", "=", "[", "(", "x", ",", "0", ")", "for", "x", "in", "neg_scores", "]", "labeled_pos", "=", "[", "(", "x", ",", "1", ")", "for", "x", "in", "...
https://github.com/lisa-lab/pylearn2/blob/af81e5c362f0df4df85c3e54e23b2adeec026055/pylearn2/expr/evaluation.py#L6-L77
HonglinChu/SiamTrackers
8471660b14f970578a43f077b28207d44a27e867
SiamCAR/SiamCAR/toolkit/datasets/video.py
python
Video.draw_box
(self, roi, img, linewidth, color, name=None)
return img
roi: rectangle or polygon img: numpy array img linewith: line width of the bbox
roi: rectangle or polygon img: numpy array img linewith: line width of the bbox
[ "roi", ":", "rectangle", "or", "polygon", "img", ":", "numpy", "array", "img", "linewith", ":", "line", "width", "of", "the", "bbox" ]
def draw_box(self, roi, img, linewidth, color, name=None): """ roi: rectangle or polygon img: numpy array img linewith: line width of the bbox """ if len(roi) > 6 and len(roi) % 2 == 0: pts = np.array(roi, np.int32).reshape(-1, 1, 2) color = tuple(map(int, color)) img = cv2.polylines(img, [pts], True, color, linewidth) pt = (pts[0, 0, 0], pts[0, 0, 1]-5) if name: img = cv2.putText(img, name, pt, cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, color, 1) elif len(roi) == 4: if not np.isnan(roi[0]): roi = list(map(int, roi)) color = tuple(map(int, color)) img = cv2.rectangle(img, (roi[0], roi[1]), (roi[0]+roi[2], roi[1]+roi[3]), color, linewidth) if name: img = cv2.putText(img, name, (roi[0], roi[1]-5), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, color, 1) return img
[ "def", "draw_box", "(", "self", ",", "roi", ",", "img", ",", "linewidth", ",", "color", ",", "name", "=", "None", ")", ":", "if", "len", "(", "roi", ")", ">", "6", "and", "len", "(", "roi", ")", "%", "2", "==", "0", ":", "pts", "=", "np", "...
https://github.com/HonglinChu/SiamTrackers/blob/8471660b14f970578a43f077b28207d44a27e867/SiamCAR/SiamCAR/toolkit/datasets/video.py#L84-L105
ivre/ivre
5728855b51c0ae2e59450a1c3a782febcad2128b
ivre/view.py
python
_extract_passive_HONEYPOT_HIT
(rec)
return { "ports": [ { "port": -1, "scripts": [ { "id": "scanner", "output": output, "scanner": structured_output, } ], } ] }
Handle {TCP,UDP}_HONEYPOT_HIT records
Handle {TCP,UDP}_HONEYPOT_HIT records
[ "Handle", "{", "TCP", "UDP", "}", "_HONEYPOT_HIT", "records" ]
def _extract_passive_HONEYPOT_HIT(rec): """Handle {TCP,UDP}_HONEYPOT_HIT records""" try: scanned_proto, scanned_port = rec["source"].split("/", 1) except ValueError: utils.LOGGER.warning("Unknown source in record [%r]", rec) return {} scanned_port = int(scanned_port) output = "Scanned port: %s" % rec["source"].replace("/", ": ") structured_output = { "ports": {"count": 1, scanned_proto: {"count": 1, "ports": [scanned_port]}} } if rec.get("infos", {}).get("service_name") == "scanner": structured_output["scanners"] = [ { "name": rec["infos"]["service_product"], "probes": [ {"proto": scanned_proto, "name": rec["infos"]["service_extrainfo"]} ], } ] output += "\nScanner:\n - %s [%s/%s]" % ( rec["infos"]["service_product"], rec["infos"]["service_extrainfo"], scanned_proto, ) if rec.get("value"): structured_output["probes"] = [{"proto": scanned_proto, "value": rec["value"]}] return { "ports": [ { "port": -1, "scripts": [ { "id": "scanner", "output": output, "scanner": structured_output, } ], } ] }
[ "def", "_extract_passive_HONEYPOT_HIT", "(", "rec", ")", ":", "try", ":", "scanned_proto", ",", "scanned_port", "=", "rec", "[", "\"source\"", "]", ".", "split", "(", "\"/\"", ",", "1", ")", "except", "ValueError", ":", "utils", ".", "LOGGER", ".", "warnin...
https://github.com/ivre/ivre/blob/5728855b51c0ae2e59450a1c3a782febcad2128b/ivre/view.py#L192-L233
Netflix-Skunkworks/diffy
259523466c7ad64de33ca125130f871b1e98ce48
diffy_api/analysis/views.py
python
AnalysisList.get
(self)
return data, 200
.. http:get:: /analysis The current list of analysiss **Example request**: .. sourcecode:: http GET /analysis HTTP/1.1 Host: example.com Accept: application/json, text/javascript **Example response**: .. sourcecode:: http HTTP/1.1 200 OK Vary: Accept Content-Type: text/javascript # TODO :statuscode 200: no error :statuscode 403: unauthenticated
.. http:get:: /analysis The current list of analysiss
[ "..", "http", ":", "get", "::", "/", "analysis", "The", "current", "list", "of", "analysiss" ]
def get(self): """ .. http:get:: /analysis The current list of analysiss **Example request**: .. sourcecode:: http GET /analysis HTTP/1.1 Host: example.com Accept: application/json, text/javascript **Example response**: .. sourcecode:: http HTTP/1.1 200 OK Vary: Accept Content-Type: text/javascript # TODO :statuscode 200: no error :statuscode 403: unauthenticated """ data = plugins.get(current_app.config["DIFFY_PERSISTENCE_PLUGIN"]).get_all( "analysis" ) return data, 200
[ "def", "get", "(", "self", ")", ":", "data", "=", "plugins", ".", "get", "(", "current_app", ".", "config", "[", "\"DIFFY_PERSISTENCE_PLUGIN\"", "]", ")", ".", "get_all", "(", "\"analysis\"", ")", "return", "data", ",", "200" ]
https://github.com/Netflix-Skunkworks/diffy/blob/259523466c7ad64de33ca125130f871b1e98ce48/diffy_api/analysis/views.py#L29-L54
volatilityfoundation/volatility3
168b0d0b053ab97a7cb096ef2048795cc54d885f
volatility3/cli/text_renderer.py
python
JsonLinesRenderer.output_result
(self, outfd, result)
Outputs the JSON results as JSON lines
Outputs the JSON results as JSON lines
[ "Outputs", "the", "JSON", "results", "as", "JSON", "lines" ]
def output_result(self, outfd, result): """Outputs the JSON results as JSON lines""" for line in result: outfd.write(json.dumps(line, sort_keys = True)) outfd.write("\n")
[ "def", "output_result", "(", "self", ",", "outfd", ",", "result", ")", ":", "for", "line", "in", "result", ":", "outfd", ".", "write", "(", "json", ".", "dumps", "(", "line", ",", "sort_keys", "=", "True", ")", ")", "outfd", ".", "write", "(", "\"\...
https://github.com/volatilityfoundation/volatility3/blob/168b0d0b053ab97a7cb096ef2048795cc54d885f/volatility3/cli/text_renderer.py#L372-L376
paypal/support
0c88c3d32644c897c30e12de8c8db00d065a76ea
support/async.py
python
killsock
(sock)
Attempts to cleanly shutdown a socket. Regardless of cleanliness, ensures that upon return, the socket is fully closed, catching any exceptions along the way. A safe and prompt way to dispose of the socket, freeing system resources.
Attempts to cleanly shutdown a socket. Regardless of cleanliness, ensures that upon return, the socket is fully closed, catching any exceptions along the way. A safe and prompt way to dispose of the socket, freeing system resources.
[ "Attempts", "to", "cleanly", "shutdown", "a", "socket", ".", "Regardless", "of", "cleanliness", "ensures", "that", "upon", "return", "the", "socket", "is", "fully", "closed", "catching", "any", "exceptions", "along", "the", "way", ".", "A", "safe", "and", "p...
def killsock(sock): """Attempts to cleanly shutdown a socket. Regardless of cleanliness, ensures that upon return, the socket is fully closed, catching any exceptions along the way. A safe and prompt way to dispose of the socket, freeing system resources. """ if hasattr(sock, '_sock'): ml.ld("Killing socket {0}/FD {1}", id(sock), sock._sock.fileno()) else: ml.ld("Killing socket {0}", id(sock)) try: # TODO: better ideas for how to get SHUT_RDWR constant? sock.shutdown(gevent.socket.SHUT_RDWR) except gevent.socket.error: pass # just being nice to the server, don't care if it fails except Exception as e: log_rec = context.get_context().log.info("SOCKET", "SHUTDOWN") log_rec.failure('error ({exc}) shutting down socket: {socket}', socket=sock, exc=e) try: sock.close() except gevent.socket.error: pass # just being nice to the server, don't care if it fails except Exception as e: log_rec = context.get_context().log.info("SOCKET", "CLOSE") log_rec.failure('error ({exc}) closing socket: {socket}', socket=sock, exc=e)
[ "def", "killsock", "(", "sock", ")", ":", "if", "hasattr", "(", "sock", ",", "'_sock'", ")", ":", "ml", ".", "ld", "(", "\"Killing socket {0}/FD {1}\"", ",", "id", "(", "sock", ")", ",", "sock", ".", "_sock", ".", "fileno", "(", ")", ")", "else", "...
https://github.com/paypal/support/blob/0c88c3d32644c897c30e12de8c8db00d065a76ea/support/async.py#L422-L448
zjhthu/OANet
51d71ff3f57161e912ec72420cd91cf7db64ab74
dump_match/transformations.py
python
euler_from_matrix
(matrix, axes='sxyz')
return ax, ay, az
Return Euler angles from rotation matrix for specified axis sequence. axes : One of 24 axis sequences as string or encoded tuple Note that many Euler angle triplets can describe one matrix. >>> R0 = euler_matrix(1, 2, 3, 'syxz') >>> al, be, ga = euler_from_matrix(R0, 'syxz') >>> R1 = euler_matrix(al, be, ga, 'syxz') >>> numpy.allclose(R0, R1) True >>> angles = (4*math.pi) * (numpy.random.random(3) - 0.5) >>> for axes in _AXES2TUPLE.keys(): ... R0 = euler_matrix(axes=axes, *angles) ... R1 = euler_matrix(axes=axes, *euler_from_matrix(R0, axes)) ... if not numpy.allclose(R0, R1): print(axes, "failed")
Return Euler angles from rotation matrix for specified axis sequence.
[ "Return", "Euler", "angles", "from", "rotation", "matrix", "for", "specified", "axis", "sequence", "." ]
def euler_from_matrix(matrix, axes='sxyz'): """Return Euler angles from rotation matrix for specified axis sequence. axes : One of 24 axis sequences as string or encoded tuple Note that many Euler angle triplets can describe one matrix. >>> R0 = euler_matrix(1, 2, 3, 'syxz') >>> al, be, ga = euler_from_matrix(R0, 'syxz') >>> R1 = euler_matrix(al, be, ga, 'syxz') >>> numpy.allclose(R0, R1) True >>> angles = (4*math.pi) * (numpy.random.random(3) - 0.5) >>> for axes in _AXES2TUPLE.keys(): ... R0 = euler_matrix(axes=axes, *angles) ... R1 = euler_matrix(axes=axes, *euler_from_matrix(R0, axes)) ... if not numpy.allclose(R0, R1): print(axes, "failed") """ try: firstaxis, parity, repetition, frame = _AXES2TUPLE[axes.lower()] except (AttributeError, KeyError): _TUPLE2AXES[axes] # validation firstaxis, parity, repetition, frame = axes i = firstaxis j = _NEXT_AXIS[i+parity] k = _NEXT_AXIS[i-parity+1] M = numpy.array(matrix, dtype=numpy.float64, copy=False)[:3, :3] if repetition: sy = math.sqrt(M[i, j]*M[i, j] + M[i, k]*M[i, k]) if sy > _EPS: ax = math.atan2( M[i, j], M[i, k]) ay = math.atan2( sy, M[i, i]) az = math.atan2( M[j, i], -M[k, i]) else: ax = math.atan2(-M[j, k], M[j, j]) ay = math.atan2( sy, M[i, i]) az = 0.0 else: cy = math.sqrt(M[i, i]*M[i, i] + M[j, i]*M[j, i]) if cy > _EPS: ax = math.atan2( M[k, j], M[k, k]) ay = math.atan2(-M[k, i], cy) az = math.atan2( M[j, i], M[i, i]) else: ax = math.atan2(-M[j, k], M[j, j]) ay = math.atan2(-M[k, i], cy) az = 0.0 if parity: ax, ay, az = -ax, -ay, -az if frame: ax, az = az, ax return ax, ay, az
[ "def", "euler_from_matrix", "(", "matrix", ",", "axes", "=", "'sxyz'", ")", ":", "try", ":", "firstaxis", ",", "parity", ",", "repetition", ",", "frame", "=", "_AXES2TUPLE", "[", "axes", ".", "lower", "(", ")", "]", "except", "(", "AttributeError", ",", ...
https://github.com/zjhthu/OANet/blob/51d71ff3f57161e912ec72420cd91cf7db64ab74/dump_match/transformations.py#L1112-L1167
GoogleCloudPlatform/PerfKitBenchmarker
6e3412d7d5e414b8ca30ed5eaf970cef1d919a67
perfkitbenchmarker/container_service.py
python
BaseContainerRegistry.LocalBuild
(self, image)
Build the image locally. Args: image: Instance of _ContainerImage representing the image to build.
Build the image locally.
[ "Build", "the", "image", "locally", "." ]
def LocalBuild(self, image): """Build the image locally. Args: image: Instance of _ContainerImage representing the image to build. """ build_cmd = [ 'docker', 'buildx', 'build', '--platform', FLAGS.container_cluster_architecture, '--no-cache', '--load', '-t', image.name, image.directory ] vm_util.IssueCommand(build_cmd)
[ "def", "LocalBuild", "(", "self", ",", "image", ")", ":", "build_cmd", "=", "[", "'docker'", ",", "'buildx'", ",", "'build'", ",", "'--platform'", ",", "FLAGS", ".", "container_cluster_architecture", ",", "'--no-cache'", ",", "'--load'", ",", "'-t'", ",", "i...
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/6e3412d7d5e414b8ca30ed5eaf970cef1d919a67/perfkitbenchmarker/container_service.py#L384-L396
mcahny/vps
138503edbc9e70de744dc0c9fa4b71c799a94d5d
mmdet/models/plugins/generalized_attention.py
python
GeneralizedAttention.__init__
(self, in_dim, spatial_range=-1, num_heads=9, position_embedding_dim=-1, position_magnitude=1, kv_stride=2, q_stride=1, attention_type='1111')
[]
def __init__(self, in_dim, spatial_range=-1, num_heads=9, position_embedding_dim=-1, position_magnitude=1, kv_stride=2, q_stride=1, attention_type='1111'): super(GeneralizedAttention, self).__init__() # hard range means local range for non-local operation self.position_embedding_dim = ( position_embedding_dim if position_embedding_dim > 0 else in_dim) self.position_magnitude = position_magnitude self.num_heads = num_heads self.channel_in = in_dim self.spatial_range = spatial_range self.kv_stride = kv_stride self.q_stride = q_stride self.attention_type = [bool(int(_)) for _ in attention_type] self.qk_embed_dim = in_dim // num_heads out_c = self.qk_embed_dim * num_heads if self.attention_type[0] or self.attention_type[1]: self.query_conv = nn.Conv2d( in_channels=in_dim, out_channels=out_c, kernel_size=1, bias=False) self.query_conv.kaiming_init = True if self.attention_type[0] or self.attention_type[2]: self.key_conv = nn.Conv2d( in_channels=in_dim, out_channels=out_c, kernel_size=1, bias=False) self.key_conv.kaiming_init = True self.v_dim = in_dim // num_heads self.value_conv = nn.Conv2d( in_channels=in_dim, out_channels=self.v_dim * num_heads, kernel_size=1, bias=False) self.value_conv.kaiming_init = True if self.attention_type[1] or self.attention_type[3]: self.appr_geom_fc_x = nn.Linear( self.position_embedding_dim // 2, out_c, bias=False) self.appr_geom_fc_x.kaiming_init = True self.appr_geom_fc_y = nn.Linear( self.position_embedding_dim // 2, out_c, bias=False) self.appr_geom_fc_y.kaiming_init = True if self.attention_type[2]: stdv = 1.0 / math.sqrt(self.qk_embed_dim * 2) appr_bias_value = -2 * stdv * torch.rand(out_c) + stdv self.appr_bias = nn.Parameter(appr_bias_value) if self.attention_type[3]: stdv = 1.0 / math.sqrt(self.qk_embed_dim * 2) geom_bias_value = -2 * stdv * torch.rand(out_c) + stdv self.geom_bias = nn.Parameter(geom_bias_value) self.proj_conv = nn.Conv2d( in_channels=self.v_dim * num_heads, out_channels=in_dim, kernel_size=1, bias=True) self.proj_conv.kaiming_init = True self.gamma = nn.Parameter(torch.zeros(1)) if self.spatial_range >= 0: # only works when non local is after 3*3 conv if in_dim == 256: max_len = 84 elif in_dim == 512: max_len = 42 max_len_kv = int((max_len - 1.0) / self.kv_stride + 1) local_constraint_map = np.ones( (max_len, max_len, max_len_kv, max_len_kv), dtype=np.int) for iy in range(max_len): for ix in range(max_len): local_constraint_map[iy, ix, max((iy - self.spatial_range) // self.kv_stride, 0):min( (iy + self.spatial_range + 1) // self.kv_stride + 1, max_len), max((ix - self.spatial_range) // self.kv_stride, 0):min( (ix + self.spatial_range + 1) // self.kv_stride + 1, max_len)] = 0 self.local_constraint_map = nn.Parameter( torch.from_numpy(local_constraint_map).byte(), requires_grad=False) if self.q_stride > 1: self.q_downsample = nn.AvgPool2d( kernel_size=1, stride=self.q_stride) else: self.q_downsample = None if self.kv_stride > 1: self.kv_downsample = nn.AvgPool2d( kernel_size=1, stride=self.kv_stride) else: self.kv_downsample = None self.init_weights()
[ "def", "__init__", "(", "self", ",", "in_dim", ",", "spatial_range", "=", "-", "1", ",", "num_heads", "=", "9", ",", "position_embedding_dim", "=", "-", "1", ",", "position_magnitude", "=", "1", ",", "kv_stride", "=", "2", ",", "q_stride", "=", "1", ",...
https://github.com/mcahny/vps/blob/138503edbc9e70de744dc0c9fa4b71c799a94d5d/mmdet/models/plugins/generalized_attention.py#L34-L151
tao12345666333/tornado-zh
e9e8519beb147d9e1290f6a4fa7d61123d1ecb1c
tornado/gen.py
python
Runner.register_callback
(self, key)
Adds ``key`` to the list of callbacks.
Adds ``key`` to the list of callbacks.
[ "Adds", "key", "to", "the", "list", "of", "callbacks", "." ]
def register_callback(self, key): """Adds ``key`` to the list of callbacks.""" if self.pending_callbacks is None: # Lazily initialize the old-style YieldPoint data structures. self.pending_callbacks = set() self.results = {} if key in self.pending_callbacks: raise KeyReuseError("key %r is already pending" % (key,)) self.pending_callbacks.add(key)
[ "def", "register_callback", "(", "self", ",", "key", ")", ":", "if", "self", ".", "pending_callbacks", "is", "None", ":", "# Lazily initialize the old-style YieldPoint data structures.", "self", ".", "pending_callbacks", "=", "set", "(", ")", "self", ".", "results",...
https://github.com/tao12345666333/tornado-zh/blob/e9e8519beb147d9e1290f6a4fa7d61123d1ecb1c/tornado/gen.py#L958-L966
robert/wavefunction-collapse
093d218e79f01cbb7787b898b458cc5d174ad7cb
main.py
python
render_colors
(matrix, colors)
Render the fully collapsed `matrix` using the given `colors. Arguments: matrix -- 2-D matrix of tiles colors -- dict of tile -> `colorama` color
Render the fully collapsed `matrix` using the given `colors.
[ "Render", "the", "fully", "collapsed", "matrix", "using", "the", "given", "colors", "." ]
def render_colors(matrix, colors): """Render the fully collapsed `matrix` using the given `colors. Arguments: matrix -- 2-D matrix of tiles colors -- dict of tile -> `colorama` color """ for row in matrix: output_row = [] for val in row: color = colors[val] output_row.append(color + val + colorama.Style.RESET_ALL) print("".join(output_row))
[ "def", "render_colors", "(", "matrix", ",", "colors", ")", ":", "for", "row", "in", "matrix", ":", "output_row", "=", "[", "]", "for", "val", "in", "row", ":", "color", "=", "colors", "[", "val", "]", "output_row", ".", "append", "(", "color", "+", ...
https://github.com/robert/wavefunction-collapse/blob/093d218e79f01cbb7787b898b458cc5d174ad7cb/main.py#L262-L275
zzzeek/sqlalchemy
fc5c54fcd4d868c2a4c7ac19668d72f506fe821e
lib/sqlalchemy/ext/asyncio/engine.py
python
AsyncTransaction.start
(self, is_ctxmanager=False)
return self
Start this :class:`_asyncio.AsyncTransaction` object's context outside of using a Python ``with:`` block.
Start this :class:`_asyncio.AsyncTransaction` object's context outside of using a Python ``with:`` block.
[ "Start", "this", ":", "class", ":", "_asyncio", ".", "AsyncTransaction", "object", "s", "context", "outside", "of", "using", "a", "Python", "with", ":", "block", "." ]
async def start(self, is_ctxmanager=False): """Start this :class:`_asyncio.AsyncTransaction` object's context outside of using a Python ``with:`` block. """ self.sync_transaction = self._assign_proxied( await greenlet_spawn( self.connection._sync_connection().begin_nested if self.nested else self.connection._sync_connection().begin ) ) if is_ctxmanager: self.sync_transaction.__enter__() return self
[ "async", "def", "start", "(", "self", ",", "is_ctxmanager", "=", "False", ")", ":", "self", ".", "sync_transaction", "=", "self", ".", "_assign_proxied", "(", "await", "greenlet_spawn", "(", "self", ".", "connection", ".", "_sync_connection", "(", ")", ".", ...
https://github.com/zzzeek/sqlalchemy/blob/fc5c54fcd4d868c2a4c7ac19668d72f506fe821e/lib/sqlalchemy/ext/asyncio/engine.py#L760-L775
JulianEberius/SublimePythonIDE
d70e40abc0c9f347af3204c7b910e0d6bfd6e459
server/lib/python3/rope/base/resourceobserver.py
python
ResourceObserver.resource_created
(self, resource)
Is called when a new resource is created
Is called when a new resource is created
[ "Is", "called", "when", "a", "new", "resource", "is", "created" ]
def resource_created(self, resource): """Is called when a new resource is created""" if self.created is not None: self.created(resource)
[ "def", "resource_created", "(", "self", ",", "resource", ")", ":", "if", "self", ".", "created", "is", "not", "None", ":", "self", ".", "created", "(", "resource", ")" ]
https://github.com/JulianEberius/SublimePythonIDE/blob/d70e40abc0c9f347af3204c7b910e0d6bfd6e459/server/lib/python3/rope/base/resourceobserver.py#L37-L40
wangzheng0822/algo
b2c1228ff915287ad7ebeae4355fa26854ea1557
python/12_sorts/merge_sort.py
python
_merge_sort_between
(a: List[int], low: int, high: int)
[]
def _merge_sort_between(a: List[int], low: int, high: int): # The indices are inclusive for both low and high. if low < high: mid = low + (high - low) // 2 _merge_sort_between(a, low, mid) _merge_sort_between(a, mid + 1, high) _merge(a, low, mid, high)
[ "def", "_merge_sort_between", "(", "a", ":", "List", "[", "int", "]", ",", "low", ":", "int", ",", "high", ":", "int", ")", ":", "# The indices are inclusive for both low and high.", "if", "low", "<", "high", ":", "mid", "=", "low", "+", "(", "high", "-"...
https://github.com/wangzheng0822/algo/blob/b2c1228ff915287ad7ebeae4355fa26854ea1557/python/12_sorts/merge_sort.py#L12-L18
playframework/play1
0ecac3bc2421ae2dbec27a368bf671eda1c9cba5
python/Lib/pydoc.py
python
TextDoc.docproperty
(self, object, name=None, mod=None, cl=None)
return self._docdescriptor(name, object, mod)
Produce text documentation for a property.
Produce text documentation for a property.
[ "Produce", "text", "documentation", "for", "a", "property", "." ]
def docproperty(self, object, name=None, mod=None, cl=None): """Produce text documentation for a property.""" return self._docdescriptor(name, object, mod)
[ "def", "docproperty", "(", "self", ",", "object", ",", "name", "=", "None", ",", "mod", "=", "None", ",", "cl", "=", "None", ")", ":", "return", "self", ".", "_docdescriptor", "(", "name", ",", "object", ",", "mod", ")" ]
https://github.com/playframework/play1/blob/0ecac3bc2421ae2dbec27a368bf671eda1c9cba5/python/Lib/pydoc.py#L1350-L1352
etetoolkit/ete
2b207357dc2a40ccad7bfd8f54964472c72e4726
ete3/tools/ete_build_lib/interface.py
python
clear_env
()
[]
def clear_env(): try: terminate_job_launcher() except: pass base_dir = GLOBALS["basedir"] lock_file = pjoin(base_dir, "alive") try: os.remove(lock_file) except Exception: print("could not remove lock file %s" %lock_file, file=sys.stderr) clear_tempdir()
[ "def", "clear_env", "(", ")", ":", "try", ":", "terminate_job_launcher", "(", ")", "except", ":", "pass", "base_dir", "=", "GLOBALS", "[", "\"basedir\"", "]", "lock_file", "=", "pjoin", "(", "base_dir", ",", "\"alive\"", ")", "try", ":", "os", ".", "remo...
https://github.com/etetoolkit/ete/blob/2b207357dc2a40ccad7bfd8f54964472c72e4726/ete3/tools/ete_build_lib/interface.py#L338-L351
Droidtown/ArticutAPI
ee415bb30c9722a85334d54d7015d5ad3870205f
WS_ArticutAPI.py
python
WS_Articut.bulk_getVerbStemLIST
(self, parseResultLIST, indexWithPOS=True)
return resultLIST
取出斷詞結果中的動詞 (verb)。此處指的是 ACTION_verb 標記的動詞詞彙。 每個句子內的動詞為一個 list。
取出斷詞結果中的動詞 (verb)。此處指的是 ACTION_verb 標記的動詞詞彙。 每個句子內的動詞為一個 list。
[ "取出斷詞結果中的動詞", "(", "verb", ")", "。此處指的是", "ACTION_verb", "標記的動詞詞彙。", "每個句子內的動詞為一個", "list。" ]
def bulk_getVerbStemLIST(self, parseResultLIST, indexWithPOS=True): ''' 取出斷詞結果中的動詞 (verb)。此處指的是 ACTION_verb 標記的動詞詞彙。 每個句子內的動詞為一個 list。 ''' resultLIST = [self.POS.getVerbStemLIST(x, indexWithPOS) for x in parseResultLIST] return resultLIST
[ "def", "bulk_getVerbStemLIST", "(", "self", ",", "parseResultLIST", ",", "indexWithPOS", "=", "True", ")", ":", "resultLIST", "=", "[", "self", ".", "POS", ".", "getVerbStemLIST", "(", "x", ",", "indexWithPOS", ")", "for", "x", "in", "parseResultLIST", "]", ...
https://github.com/Droidtown/ArticutAPI/blob/ee415bb30c9722a85334d54d7015d5ad3870205f/WS_ArticutAPI.py#L451-L457
bendmorris/static-python
2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473
Lib/venv/__init__.py
python
EnvBuilder.post_setup
(self, context)
Hook for post-setup modification of the venv. Subclasses may install additional packages or scripts here, add activation shell scripts, etc. :param context: The information for the environment creation request being processed.
Hook for post-setup modification of the venv. Subclasses may install additional packages or scripts here, add activation shell scripts, etc.
[ "Hook", "for", "post", "-", "setup", "modification", "of", "the", "venv", ".", "Subclasses", "may", "install", "additional", "packages", "or", "scripts", "here", "add", "activation", "shell", "scripts", "etc", "." ]
def post_setup(self, context): """ Hook for post-setup modification of the venv. Subclasses may install additional packages or scripts here, add activation shell scripts, etc. :param context: The information for the environment creation request being processed. """ pass
[ "def", "post_setup", "(", "self", ",", "context", ")", ":", "pass" ]
https://github.com/bendmorris/static-python/blob/2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473/Lib/venv/__init__.py#L242-L250
oleg-yaroshevskiy/quest_qa_labeling
730a9632314e54584f69f909d5e2ef74d843e02c
packages/fairseq-hacked/fairseq/models/roberta/model.py
python
RobertaEncoder.max_positions
(self)
return self.args.max_positions
Maximum output length supported by the encoder.
Maximum output length supported by the encoder.
[ "Maximum", "output", "length", "supported", "by", "the", "encoder", "." ]
def max_positions(self): """Maximum output length supported by the encoder.""" return self.args.max_positions
[ "def", "max_positions", "(", "self", ")", ":", "return", "self", ".", "args", ".", "max_positions" ]
https://github.com/oleg-yaroshevskiy/quest_qa_labeling/blob/730a9632314e54584f69f909d5e2ef74d843e02c/packages/fairseq-hacked/fairseq/models/roberta/model.py#L465-L467
openstack/heat
ea6633c35b04bb49c4a2858edc9df0a82d039478
heat/engine/stk_defn.py
python
ResourceProxy.action
(self)
return self._resource_data.action
The current action of the resource.
The current action of the resource.
[ "The", "current", "action", "of", "the", "resource", "." ]
def action(self): """The current action of the resource.""" if self._resource_data is None: return self.INIT return self._resource_data.action
[ "def", "action", "(", "self", ")", ":", "if", "self", ".", "_resource_data", "is", "None", ":", "return", "self", ".", "INIT", "return", "self", ".", "_resource_data", ".", "action" ]
https://github.com/openstack/heat/blob/ea6633c35b04bb49c4a2858edc9df0a82d039478/heat/engine/stk_defn.py#L198-L202
DonyorM/weresync
3c0094cb386358589c48bf48cb60f20acf961f9c
src/weresync/daemon/device.py
python
DeviceManager.get_part_uuid
(self, partition_num)
return self._get_blkid_info(partition_num, "PARTUUID")
Gets the PARTUUID for a given partition, if it exists. This is *not* the filesystem UUID and is different from `py:func:~.DeviceManager.get_partition_uuid`. :param partition_num: the number of the partition whose PARTUUID to get. :returns: a string containing the partition's PARTUUID.
Gets the PARTUUID for a given partition, if it exists. This is *not* the filesystem UUID and is different from `py:func:~.DeviceManager.get_partition_uuid`.
[ "Gets", "the", "PARTUUID", "for", "a", "given", "partition", "if", "it", "exists", ".", "This", "is", "*", "not", "*", "the", "filesystem", "UUID", "and", "is", "different", "from", "py", ":", "func", ":", "~", ".", "DeviceManager", ".", "get_partition_u...
def get_part_uuid(self, partition_num): """Gets the PARTUUID for a given partition, if it exists. This is *not* the filesystem UUID and is different from `py:func:~.DeviceManager.get_partition_uuid`. :param partition_num: the number of the partition whose PARTUUID to get. :returns: a string containing the partition's PARTUUID.""" return self._get_blkid_info(partition_num, "PARTUUID")
[ "def", "get_part_uuid", "(", "self", ",", "partition_num", ")", ":", "return", "self", ".", "_get_blkid_info", "(", "partition_num", ",", "\"PARTUUID\"", ")" ]
https://github.com/DonyorM/weresync/blob/3c0094cb386358589c48bf48cb60f20acf961f9c/src/weresync/daemon/device.py#L221-L229
microsoft/azure-devops-python-api
451cade4c475482792cbe9e522c1fee32393139e
azure-devops/azure/devops/v5_1/symbol/symbol_client.py
python
SymbolClient.check_availability
(self)
CheckAvailability. [Preview API] Check the availability of symbol service. This includes checking for feature flag, and possibly license in future. Note this is NOT an anonymous endpoint, and the caller will be redirected to authentication before hitting it.
CheckAvailability. [Preview API] Check the availability of symbol service. This includes checking for feature flag, and possibly license in future. Note this is NOT an anonymous endpoint, and the caller will be redirected to authentication before hitting it.
[ "CheckAvailability", ".", "[", "Preview", "API", "]", "Check", "the", "availability", "of", "symbol", "service", ".", "This", "includes", "checking", "for", "feature", "flag", "and", "possibly", "license", "in", "future", ".", "Note", "this", "is", "NOT", "a...
def check_availability(self): """CheckAvailability. [Preview API] Check the availability of symbol service. This includes checking for feature flag, and possibly license in future. Note this is NOT an anonymous endpoint, and the caller will be redirected to authentication before hitting it. """ self._send(http_method='GET', location_id='97c893cc-e861-4ef4-8c43-9bad4a963dee', version='5.1-preview.1')
[ "def", "check_availability", "(", "self", ")", ":", "self", ".", "_send", "(", "http_method", "=", "'GET'", ",", "location_id", "=", "'97c893cc-e861-4ef4-8c43-9bad4a963dee'", ",", "version", "=", "'5.1-preview.1'", ")" ]
https://github.com/microsoft/azure-devops-python-api/blob/451cade4c475482792cbe9e522c1fee32393139e/azure-devops/azure/devops/v5_1/symbol/symbol_client.py#L28-L34
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/plat-mac/lib-scriptpackages/StdSuites/AppleScript_Suite.py
python
AppleScript_Suite_Events.stop_log
(self, _no_object=None, _attributes={}, **_arguments)
stop log: Stop event logging in the script editor Keyword argument _attributes: AppleEvent attribute dictionary
stop log: Stop event logging in the script editor Keyword argument _attributes: AppleEvent attribute dictionary
[ "stop", "log", ":", "Stop", "event", "logging", "in", "the", "script", "editor", "Keyword", "argument", "_attributes", ":", "AppleEvent", "attribute", "dictionary" ]
def stop_log(self, _no_object=None, _attributes={}, **_arguments): """stop log: Stop event logging in the script editor Keyword argument _attributes: AppleEvent attribute dictionary """ _code = 'ToyS' _subcode = 'log0' if _arguments: raise TypeError, 'No optional args expected' if _no_object is not None: raise TypeError, 'No direct arg expected' _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.get('errn', 0): raise aetools.Error, aetools.decodeerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----']
[ "def", "stop_log", "(", "self", ",", "_no_object", "=", "None", ",", "_attributes", "=", "{", "}", ",", "*", "*", "_arguments", ")", ":", "_code", "=", "'ToyS'", "_subcode", "=", "'log0'", "if", "_arguments", ":", "raise", "TypeError", ",", "'No optional...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/plat-mac/lib-scriptpackages/StdSuites/AppleScript_Suite.py#L620-L637
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/cmd.py
python
Cmd.complete
(self, text, state)
Return the next possible completion for 'text'. If a command has not been entered, then complete against command list. Otherwise try to call complete_<command> to get list of completions.
Return the next possible completion for 'text'.
[ "Return", "the", "next", "possible", "completion", "for", "text", "." ]
def complete(self, text, state): """Return the next possible completion for 'text'. If a command has not been entered, then complete against command list. Otherwise try to call complete_<command> to get list of completions. """ if state == 0: import readline origline = readline.get_line_buffer() line = origline.lstrip() stripped = len(origline) - len(line) begidx = readline.get_begidx() - stripped endidx = readline.get_endidx() - stripped if begidx>0: cmd, args, foo = self.parseline(line) if cmd == '': compfunc = self.completedefault else: try: compfunc = getattr(self, 'complete_' + cmd) except AttributeError: compfunc = self.completedefault else: compfunc = self.completenames self.completion_matches = compfunc(text, line, begidx, endidx) try: return self.completion_matches[state] except IndexError: return None
[ "def", "complete", "(", "self", ",", "text", ",", "state", ")", ":", "if", "state", "==", "0", ":", "import", "readline", "origline", "=", "readline", ".", "get_line_buffer", "(", ")", "line", "=", "origline", ".", "lstrip", "(", ")", "stripped", "=", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/cmd.py#L255-L283
datafolklabs/cement
2d44d2c1821bda6bdfcfe605d244dc2dfb0b19a6
cement/cli/contrib/jinja2/filters.py
python
do_format
(value, *args, **kwargs)
return soft_unicode(value) % (kwargs or args)
Apply python string formatting on an object: .. sourcecode:: jinja {{ "%s - %s"|format("Hello?", "Foo!") }} -> Hello? - Foo!
Apply python string formatting on an object:
[ "Apply", "python", "string", "formatting", "on", "an", "object", ":" ]
def do_format(value, *args, **kwargs): """ Apply python string formatting on an object: .. sourcecode:: jinja {{ "%s - %s"|format("Hello?", "Foo!") }} -> Hello? - Foo! """ if args and kwargs: raise FilterArgumentError('can\'t handle positional and keyword ' 'arguments at the same time') return soft_unicode(value) % (kwargs or args)
[ "def", "do_format", "(", "value", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "args", "and", "kwargs", ":", "raise", "FilterArgumentError", "(", "'can\\'t handle positional and keyword '", "'arguments at the same time'", ")", "return", "soft_unicode",...
https://github.com/datafolklabs/cement/blob/2d44d2c1821bda6bdfcfe605d244dc2dfb0b19a6/cement/cli/contrib/jinja2/filters.py#L673-L685
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/src/lib/service.py
python
Service.get_external_ips
(self)
return self.get(Service.external_ips) or []
get a list of external_ips
get a list of external_ips
[ "get", "a", "list", "of", "external_ips" ]
def get_external_ips(self): ''' get a list of external_ips ''' return self.get(Service.external_ips) or []
[ "def", "get_external_ips", "(", "self", ")", ":", "return", "self", ".", "get", "(", "Service", ".", "external_ips", ")", "or", "[", "]" ]
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/src/lib/service.py#L146-L148
CvvT/dumpDex
92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1
python/idaapi.py
python
boolvec_t.clear
(self, *args)
return _idaapi.boolvec_t_clear(self, *args)
clear(self)
clear(self)
[ "clear", "(", "self", ")" ]
def clear(self, *args): """ clear(self) """ return _idaapi.boolvec_t_clear(self, *args)
[ "def", "clear", "(", "self", ",", "*", "args", ")", ":", "return", "_idaapi", ".", "boolvec_t_clear", "(", "self", ",", "*", "args", ")" ]
https://github.com/CvvT/dumpDex/blob/92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1/python/idaapi.py#L1634-L1638
holoviz/datashader
25578abde75c7fa28c6633b33cb8d8a1e433da67
datashader/reductions.py
python
FloatingReduction._create
(shape, array_module)
return array_module.full(shape, np.nan, dtype='f8')
[]
def _create(shape, array_module): return array_module.full(shape, np.nan, dtype='f8')
[ "def", "_create", "(", "shape", ",", "array_module", ")", ":", "return", "array_module", ".", "full", "(", "shape", ",", "np", ".", "nan", ",", "dtype", "=", "'f8'", ")" ]
https://github.com/holoviz/datashader/blob/25578abde75c7fa28c6633b33cb8d8a1e433da67/datashader/reductions.py#L464-L465
frePPLe/frepple
57aa612030b4fcd03cb9c613f83a7dac4f0e8d6d
freppledb/execute/management/commands/scheduletasks.py
python
Command.createScheduledTasks
(self, *args, **options)
Task scheduler that looks at the defined schedule and generates tasks at the right moment.
Task scheduler that looks at the defined schedule and generates tasks at the right moment.
[ "Task", "scheduler", "that", "looks", "at", "the", "defined", "schedule", "and", "generates", "tasks", "at", "the", "right", "moment", "." ]
def createScheduledTasks(self, *args, **options): """ Task scheduler that looks at the defined schedule and generates tasks at the right moment. """ database = options["database"] if database not in settings.DATABASES: raise CommandError("No database settings known for '%s'" % database) # Collect tasks # Note: use transaction and select_for_update to handle concurrent access now = datetime.now() created = False with transaction.atomic(using=database): for schedule in ( ScheduledTask.objects.all() .using(database) .filter(next_run__isnull=False, next_run__lte=now) .order_by("next_run", "name") .select_for_update(skip_locked=True) ): Task( name="scheduletasks", submitted=now, status="Waiting", user=schedule.user, arguments="--schedule='%s'" % schedule.name, ).save(using=database) schedule.computeNextRun(now + timedelta(seconds=1)) schedule.save(using=database) created = True # Launch the worker process if created: launchWorker(database) # Reschedule to run this task again at the next date earliest_next = ( ScheduledTask.objects.using(database) .filter(next_run__isnull=False, next_run__gt=now) .aggregate(Min("next_run")) )["next_run__min"] if earliest_next: retcode = 0 if os.name == "nt": # TODO For multi-tenancy possible we would also need to set the # FREPPLE_CONFIGDIR environment variable. It seems that isn't # possible with the Windows task scheduler. # TODO The task scheduler has a more powerful XML interface that # allows to define eg wake up of computer, run when not logged on, # priviliges, etc if "python" in sys.executable: # Development layout cmd = "%s %s scheduletasks --database=%s" % ( sys.executable.replace("python.exe", "pythonw.exe"), os.path.abspath(sys.argv[0]), database, ) else: # Windows installer cmd = '"%s" scheduletasks --database=%s' % ( sys.executable.replace("freppleserver.exe", "frepplectl.exe"), database, ) retcode = call( [ "schtasks", "/create", "/tn", "frePPLe scheduler on %s" % database, "/sc", "once", "/st", earliest_next.strftime("%H:%M"), "/sd", earliest_next.strftime("%m/%d/%Y"), "/f", "/tr", cmd, ] ) else: my_env = os.environ.copy() my_env["FREPPLE_CONFIGDIR"] = settings.FREPPLE_CONFIGDIR try: if which("frepplectl"): retcode = call( "echo frepplectl scheduletasks --database=%s | at %s" % (database, earliest_next.strftime("%H:%M %y-%m-%d")), env=my_env, shell=True, ) else: retcode = call( "echo %s scheduletasks --database=%s | at %s" % ( os.path.abspath(sys.argv[0]), database, earliest_next.strftime("%H:%M %y-%m-%d"), ), env=my_env, shell=True, ) except OSError as e: raise CommandError("Can't schedule the task: %s" % e) if retcode < 0: raise CommandError("Non-zero exit code when scheduling the task")
[ "def", "createScheduledTasks", "(", "self", ",", "*", "args", ",", "*", "*", "options", ")", ":", "database", "=", "options", "[", "\"database\"", "]", "if", "database", "not", "in", "settings", ".", "DATABASES", ":", "raise", "CommandError", "(", "\"No da...
https://github.com/frePPLe/frepple/blob/57aa612030b4fcd03cb9c613f83a7dac4f0e8d6d/freppledb/execute/management/commands/scheduletasks.py#L289-L395
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/site-packages/PIL/ImageStat.py
python
Stat._getcount
(self)
return v
Get total number of pixels in each layer
Get total number of pixels in each layer
[ "Get", "total", "number", "of", "pixels", "in", "each", "layer" ]
def _getcount(self): "Get total number of pixels in each layer" v = [] for i in range(0, len(self.h), 256): v.append(reduce(operator.add, self.h[i:i+256])) return v
[ "def", "_getcount", "(", "self", ")", ":", "v", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "self", ".", "h", ")", ",", "256", ")", ":", "v", ".", "append", "(", "reduce", "(", "operator", ".", "add", ",", "self", "...
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/PIL/ImageStat.py#L85-L91
sugarlabs/sugar
9fc581968c6a1df042bda29bb64f0c62e4444c78
src/jarabe/webservice/account.py
python
Account.get_description
(self)
get_description returns a brief description of the online service. The description is used in palette menuitems and on the webservices control panel. :returns: online-account name :rtype: string
get_description returns a brief description of the online service. The description is used in palette menuitems and on the webservices control panel.
[ "get_description", "returns", "a", "brief", "description", "of", "the", "online", "service", ".", "The", "description", "is", "used", "in", "palette", "menuitems", "and", "on", "the", "webservices", "control", "panel", "." ]
def get_description(self): ''' get_description returns a brief description of the online service. The description is used in palette menuitems and on the webservices control panel. :returns: online-account name :rtype: string ''' raise NotImplementedError
[ "def", "get_description", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/sugarlabs/sugar/blob/9fc581968c6a1df042bda29bb64f0c62e4444c78/src/jarabe/webservice/account.py#L29-L37
LexPredict/lexpredict-contraxsuite
1d5a2540d31f8f3f1adc442cfa13a7c007319899
contraxsuite_services/apps/analyze/ml/classify.py
python
ClassifierEngine.__call__
(self, use_tfidf: bool = True, **options)
return self.model
Just call activated class instance to classify data. :param use_tfidf: bool - whether to use TF IDF Transformer :param options: **dict - unpacked classifier algorithm options :return: ClassifyEngine instance with attributes listed in __init__
Just call activated class instance to classify data. :param use_tfidf: bool - whether to use TF IDF Transformer :param options: **dict - unpacked classifier algorithm options :return: ClassifyEngine instance with attributes listed in __init__
[ "Just", "call", "activated", "class", "instance", "to", "classify", "data", ".", ":", "param", "use_tfidf", ":", "bool", "-", "whether", "to", "use", "TF", "IDF", "Transformer", ":", "param", "options", ":", "**", "dict", "-", "unpacked", "classifier", "al...
def __call__(self, use_tfidf: bool = True, **options): """ Just call activated class instance to classify data. :param use_tfidf: bool - whether to use TF IDF Transformer :param options: **dict - unpacked classifier algorithm options :return: ClassifyEngine instance with attributes listed in __init__ """ self.use_tfidf = use_tfidf self.user_options = options self.model = self.get_model() return self.model
[ "def", "__call__", "(", "self", ",", "use_tfidf", ":", "bool", "=", "True", ",", "*", "*", "options", ")", ":", "self", ".", "use_tfidf", "=", "use_tfidf", "self", ".", "user_options", "=", "options", "self", ".", "model", "=", "self", ".", "get_model"...
https://github.com/LexPredict/lexpredict-contraxsuite/blob/1d5a2540d31f8f3f1adc442cfa13a7c007319899/contraxsuite_services/apps/analyze/ml/classify.py#L105-L115
Mellcap/MellPlayer
90b3210eaaed675552fd69717b6b953fd0e0b07d
mellplayer/api.py
python
Netease.song_detail
(self, song_ids)
return result
歌曲详情 http://music.163.com/api/song/detail?ids=[xxx, xxx]
歌曲详情 http://music.163.com/api/song/detail?ids=[xxx, xxx]
[ "歌曲详情", "http", ":", "//", "music", ".", "163", ".", "com", "/", "api", "/", "song", "/", "detail?ids", "=", "[", "xxx", "xxx", "]" ]
def song_detail(self, song_ids): ''' 歌曲详情 http://music.163.com/api/song/detail?ids=[xxx, xxx] ''' url = 'http://music.163.com/api/song/detail?ids=%s' % song_ids result = self._request(url) return result
[ "def", "song_detail", "(", "self", ",", "song_ids", ")", ":", "url", "=", "'http://music.163.com/api/song/detail?ids=%s'", "%", "song_ids", "result", "=", "self", ".", "_request", "(", "url", ")", "return", "result" ]
https://github.com/Mellcap/MellPlayer/blob/90b3210eaaed675552fd69717b6b953fd0e0b07d/mellplayer/api.py#L67-L74
tensorflow/ranking
94cccec8b4e71d2cc4489c61e2623522738c2924
tensorflow_ranking/python/metrics.py
python
precision_ia
(labels, predictions, weights=None, topn=None, name=None)
return tf.compat.v1.metrics.mean(precision_at_k, per_list_weights)
Computes Intent-Aware Precision as weighted average of relevant examples. Args: labels: A `Tensor` with shape [batch_size, list_size, subtopic_size]. A nonzero value means that the example covers the corresponding subtopic. predictions: A `Tensor` with shape [batch_size, list_size]. Each value is the ranking score of the corresponding example. weights: A `Tensor` of the same shape of predictions or [batch_size, 1]. The former case is per-example and the latter case is per-list. topn: A cutoff for how many examples to consider for this metric. name: A string used as the name for this metric. Returns: A metric for the weighted precision of the batch.
Computes Intent-Aware Precision as weighted average of relevant examples.
[ "Computes", "Intent", "-", "Aware", "Precision", "as", "weighted", "average", "of", "relevant", "examples", "." ]
def precision_ia(labels, predictions, weights=None, topn=None, name=None): """Computes Intent-Aware Precision as weighted average of relevant examples. Args: labels: A `Tensor` with shape [batch_size, list_size, subtopic_size]. A nonzero value means that the example covers the corresponding subtopic. predictions: A `Tensor` with shape [batch_size, list_size]. Each value is the ranking score of the corresponding example. weights: A `Tensor` of the same shape of predictions or [batch_size, 1]. The former case is per-example and the latter case is per-list. topn: A cutoff for how many examples to consider for this metric. name: A string used as the name for this metric. Returns: A metric for the weighted precision of the batch. """ metric = metrics_impl.PrecisionIAMetric(name, topn) with tf.compat.v1.name_scope(metric.name, 'precision_ia', (labels, predictions, weights)): # TODO: Add mask argument for metric.compute() call precision_at_k, per_list_weights = metric.compute(labels, predictions, weights) return tf.compat.v1.metrics.mean(precision_at_k, per_list_weights)
[ "def", "precision_ia", "(", "labels", ",", "predictions", ",", "weights", "=", "None", ",", "topn", "=", "None", ",", "name", "=", "None", ")", ":", "metric", "=", "metrics_impl", ".", "PrecisionIAMetric", "(", "name", ",", "topn", ")", "with", "tf", "...
https://github.com/tensorflow/ranking/blob/94cccec8b4e71d2cc4489c61e2623522738c2924/tensorflow_ranking/python/metrics.py#L414-L436
collinsctk/PyQYT
7af3673955f94ff1b2df2f94220cd2dab2e252af
ExtentionPackages/Crypto/Cipher/XOR.py
python
XORCipher.encrypt
(self, plaintext)
return self._cipher.encrypt(plaintext)
Encrypt a piece of data. :Parameters: plaintext : byte string The piece of data to encrypt. It can be of any size. :Return: the encrypted data (byte string, as long as the plaintext).
Encrypt a piece of data.
[ "Encrypt", "a", "piece", "of", "data", "." ]
def encrypt(self, plaintext): """Encrypt a piece of data. :Parameters: plaintext : byte string The piece of data to encrypt. It can be of any size. :Return: the encrypted data (byte string, as long as the plaintext). """ return self._cipher.encrypt(plaintext)
[ "def", "encrypt", "(", "self", ",", "plaintext", ")", ":", "return", "self", ".", "_cipher", ".", "encrypt", "(", "plaintext", ")" ]
https://github.com/collinsctk/PyQYT/blob/7af3673955f94ff1b2df2f94220cd2dab2e252af/ExtentionPackages/Crypto/Cipher/XOR.py#L48-L57