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
thinkle/gourmet
8af29c8ded24528030e5ae2ea3461f61c1e5a575
gourmet/plugin.py
python
PrefsPlugin.remove
(self)
[]
def remove (self): if self.notebook: self.notebook.remove_page(self.page_no)
[ "def", "remove", "(", "self", ")", ":", "if", "self", ".", "notebook", ":", "self", ".", "notebook", ".", "remove_page", "(", "self", ".", "page_no", ")" ]
https://github.com/thinkle/gourmet/blob/8af29c8ded24528030e5ae2ea3461f61c1e5a575/gourmet/plugin.py#L610-L612
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/motech/dhis2/entities_helpers.py
python
generate_value
(requests, attr_id, generator_params, case_trigger_info)
return response.json()["value"]
Sends a request to DHIS2 to generate a value for a generated attribute, like a unique ID. DHIS2 may require parameters to generate the value. Returns the value. Example value source:: { "case_property": "dhis2_unique_id", "is_generated": True, "generator_params": { "ORG_UNIT_CODE": { "case_owner_ancestor_location_field": "dhis2_org_unit_code" } } }
Sends a request to DHIS2 to generate a value for a generated attribute, like a unique ID. DHIS2 may require parameters to generate the value. Returns the value.
[ "Sends", "a", "request", "to", "DHIS2", "to", "generate", "a", "value", "for", "a", "generated", "attribute", "like", "a", "unique", "ID", ".", "DHIS2", "may", "require", "parameters", "to", "generate", "the", "value", ".", "Returns", "the", "value", "." ]
def generate_value(requests, attr_id, generator_params, case_trigger_info): """ Sends a request to DHIS2 to generate a value for a generated attribute, like a unique ID. DHIS2 may require parameters to generate the value. Returns the value. Example value source:: { "case_property": "dhis2_unique_id", "is_generated": True, "generator_params": { "ORG_UNIT_CODE": { "case_owner_ancestor_location_field": "dhis2_org_unit_code" } } } """ params = {name: get_value(vsc, case_trigger_info) for name, vsc in generator_params.items()} response = requests.get( f"/api/trackedEntityAttributes/{attr_id}/generate", params=params, raise_for_status=True ) return response.json()["value"]
[ "def", "generate_value", "(", "requests", ",", "attr_id", ",", "generator_params", ",", "case_trigger_info", ")", ":", "params", "=", "{", "name", ":", "get_value", "(", "vsc", ",", "case_trigger_info", ")", "for", "name", ",", "vsc", "in", "generator_params",...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/motech/dhis2/entities_helpers.py#L373-L397
trakt/Plex-Trakt-Scrobbler
aeb0bfbe62fad4b06c164f1b95581da7f35dce0b
Trakttv.bundle/Contents/Libraries/FreeBSD/x86_64/ucs4/cryptography/x509/base.py
python
CertificateBuilder.public_key
(self, key)
return CertificateBuilder( self._issuer_name, self._subject_name, key, self._serial_number, self._not_valid_before, self._not_valid_after, self._extensions )
Sets the requestor's public key (as found in the signing request).
Sets the requestor's public key (as found in the signing request).
[ "Sets", "the", "requestor", "s", "public", "key", "(", "as", "found", "in", "the", "signing", "request", ")", "." ]
def public_key(self, key): """ Sets the requestor's public key (as found in the signing request). """ if not isinstance(key, (dsa.DSAPublicKey, rsa.RSAPublicKey, ec.EllipticCurvePublicKey)): raise TypeError('Expecting one of DSAPublicKey, RSAPublicKey,' ' or EllipticCurvePublicKey.') if self._public_key is not None: raise ValueError('The public key may only be set once.') return CertificateBuilder( self._issuer_name, self._subject_name, key, self._serial_number, self._not_valid_before, self._not_valid_after, self._extensions )
[ "def", "public_key", "(", "self", ",", "key", ")", ":", "if", "not", "isinstance", "(", "key", ",", "(", "dsa", ".", "DSAPublicKey", ",", "rsa", ".", "RSAPublicKey", ",", "ec", ".", "EllipticCurvePublicKey", ")", ")", ":", "raise", "TypeError", "(", "'...
https://github.com/trakt/Plex-Trakt-Scrobbler/blob/aeb0bfbe62fad4b06c164f1b95581da7f35dce0b/Trakttv.bundle/Contents/Libraries/FreeBSD/x86_64/ucs4/cryptography/x509/base.py#L418-L432
perdy/flama
8c429eaa909ccb2cbcd1cd09dcf50da73af2f00e
flama/injection.py
python
Injector.resolve
(self, func)
return kwargs, consts, steps
Inspects a function and creates a resolution list of all components needed to run it. returning :param func: function to resolve. :return: the keyword arguments, consts for that function and the steps to resolve all components.
Inspects a function and creates a resolution list of all components needed to run it. returning
[ "Inspects", "a", "function", "and", "creates", "a", "resolution", "list", "of", "all", "components", "needed", "to", "run", "it", ".", "returning" ]
def resolve(self, func) -> typing.Tuple[typing.Dict, typing.Dict, typing.List]: """ Inspects a function and creates a resolution list of all components needed to run it. returning :param func: function to resolve. :return: the keyword arguments, consts for that function and the steps to resolve all components. """ seen_state = set(self.initial) steps = [] kwargs = {} consts = {} signature = inspect.signature(func) for parameter in signature.parameters.values(): try: steps += self.resolve_parameter(parameter, kwargs, consts, seen_state=seen_state) except ComponentNotFound as e: e.function = func.__name__ raise e return kwargs, consts, steps
[ "def", "resolve", "(", "self", ",", "func", ")", "->", "typing", ".", "Tuple", "[", "typing", ".", "Dict", ",", "typing", ".", "Dict", ",", "typing", ".", "List", "]", ":", "seen_state", "=", "set", "(", "self", ".", "initial", ")", "steps", "=", ...
https://github.com/perdy/flama/blob/8c429eaa909ccb2cbcd1cd09dcf50da73af2f00e/flama/injection.py#L121-L143
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/combinat/sloane_functions.py
python
A000961.__init__
(self)
r""" Prime powers INPUT: - ``n`` -- non negative integer OUTPUT: - ``integer`` -- function value EXAMPLES:: sage: a = sloane.A000961;a Prime powers. sage: a(0) Traceback (most recent call last): ... ValueError: input n (=0) must be a positive integer sage: a(2) 2 sage: a(12) 17 sage: a.list(12) [1, 2, 3, 4, 5, 7, 8, 9, 11, 13, 16, 17] AUTHORS: - Jaap Spies (2007-01-25)
r""" Prime powers
[ "r", "Prime", "powers" ]
def __init__(self): r""" Prime powers INPUT: - ``n`` -- non negative integer OUTPUT: - ``integer`` -- function value EXAMPLES:: sage: a = sloane.A000961;a Prime powers. sage: a(0) Traceback (most recent call last): ... ValueError: input n (=0) must be a positive integer sage: a(2) 2 sage: a(12) 17 sage: a.list(12) [1, 2, 3, 4, 5, 7, 8, 9, 11, 13, 16, 17] AUTHORS: - Jaap Spies (2007-01-25) """ SloaneSequence.__init__(self, offset=1) self._b = [1] self._n = 2
[ "def", "__init__", "(", "self", ")", ":", "SloaneSequence", ".", "__init__", "(", "self", ",", "offset", "=", "1", ")", "self", ".", "_b", "=", "[", "1", "]", "self", ".", "_n", "=", "2" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/sloane_functions.py#L3555-L3588
rhinstaller/anaconda
63edc8680f1b05cbfe11bef28703acba808c5174
pyanaconda/modules/network/installation.py
python
NetworkInstallationTask._copy_file_to_root
(self, root, config_file, overwrite=False, follow_symlinks=True)
Copy the file to target system. :param root: path to the root of the target system :type root: str :param config_file: path of the file :type config_file: str :param overwrite: overwrite existing configuration file :type overwrite: bool
Copy the file to target system.
[ "Copy", "the", "file", "to", "target", "system", "." ]
def _copy_file_to_root(self, root, config_file, overwrite=False, follow_symlinks=True): """Copy the file to target system. :param root: path to the root of the target system :type root: str :param config_file: path of the file :type config_file: str :param overwrite: overwrite existing configuration file :type overwrite: bool """ if not os.path.isfile(config_file): return fpath = os.path.normpath(root + config_file) if (os.path.isfile(fpath) or os.path.islink(fpath)) and not overwrite: return if not os.path.isdir(os.path.dirname(fpath)): make_directories(os.path.dirname(fpath)) shutil.copy(config_file, fpath, follow_symlinks=follow_symlinks)
[ "def", "_copy_file_to_root", "(", "self", ",", "root", ",", "config_file", ",", "overwrite", "=", "False", ",", "follow_symlinks", "=", "True", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "config_file", ")", ":", "return", "fpath", "=",...
https://github.com/rhinstaller/anaconda/blob/63edc8680f1b05cbfe11bef28703acba808c5174/pyanaconda/modules/network/installation.py#L230-L247
Antergos/Cnchi
13ac2209da9432d453e0097cf48a107640b563a9
src/parted3/fs_module.py
python
get_uuid
(part)
return ""
Get partition UUID
Get partition UUID
[ "Get", "partition", "UUID" ]
def get_uuid(part): """ Get partition UUID """ info = get_info(part) if "UUID" in info.keys(): return info['UUID'] logging.error("Can't get partition %s UUID", part) return ""
[ "def", "get_uuid", "(", "part", ")", ":", "info", "=", "get_info", "(", "part", ")", "if", "\"UUID\"", "in", "info", ".", "keys", "(", ")", ":", "return", "info", "[", "'UUID'", "]", "logging", ".", "error", "(", "\"Can't get partition %s UUID\"", ",", ...
https://github.com/Antergos/Cnchi/blob/13ac2209da9432d453e0097cf48a107640b563a9/src/parted3/fs_module.py#L52-L58
isnowfy/pydown
71ecc891868cd2a34b7e5fe662c99474f2d0fd7f
pygments/lexers/text.py
python
TexLexer.analyse_text
(text)
[]
def analyse_text(text): for start in ("\\documentclass", "\\input", "\\documentstyle", "\\relax"): if text[:len(start)] == start: return True
[ "def", "analyse_text", "(", "text", ")", ":", "for", "start", "in", "(", "\"\\\\documentclass\"", ",", "\"\\\\input\"", ",", "\"\\\\documentstyle\"", ",", "\"\\\\relax\"", ")", ":", "if", "text", "[", ":", "len", "(", "start", ")", "]", "==", "start", ":",...
https://github.com/isnowfy/pydown/blob/71ecc891868cd2a34b7e5fe662c99474f2d0fd7f/pygments/lexers/text.py#L449-L453
Droidtown/ArticutAPI
ee415bb30c9722a85334d54d7015d5ad3870205f
ArticutAPI.py
python
Articut.getContentWordLIST
(self, parseResultDICT, indexWithPOS=True)
return self.POS.getContentWordLIST(parseResultDICT, indexWithPOS)
取出斷詞結果中的實詞 (content word)。 每個句子內的實詞為一個 list。
取出斷詞結果中的實詞 (content word)。 每個句子內的實詞為一個 list。
[ "取出斷詞結果中的實詞", "(", "content", "word", ")", "。", "每個句子內的實詞為一個", "list。" ]
def getContentWordLIST(self, parseResultDICT, indexWithPOS=True): ''' 取出斷詞結果中的實詞 (content word)。 每個句子內的實詞為一個 list。 ''' return self.POS.getContentWordLIST(parseResultDICT, indexWithPOS)
[ "def", "getContentWordLIST", "(", "self", ",", "parseResultDICT", ",", "indexWithPOS", "=", "True", ")", ":", "return", "self", ".", "POS", ".", "getContentWordLIST", "(", "parseResultDICT", ",", "indexWithPOS", ")" ]
https://github.com/Droidtown/ArticutAPI/blob/ee415bb30c9722a85334d54d7015d5ad3870205f/ArticutAPI.py#L250-L255
mit-han-lab/data-efficient-gans
6858275f08f43a33026844c8c2ac4e703e8a07ba
DiffAugment-biggan-cifar/eval.py
python
run_eval
(config)
[]
def run_eval(config): # update config (see train.py for explanation) config['resolution'] = utils.imsize_dict[config['dataset']] config['n_classes'] = utils.nclass_dict[config['dataset']] config['G_activation'] = utils.activation_dict[config['G_nl']] config['D_activation'] = utils.activation_dict[config['D_nl']] config = utils.update_config_roots(config) config['skip_init'] = True config['no_optim'] = True device = 'cuda' model = __import__(config['model']) G = model.Generator(**config).cuda() G_batch_size = max(config['G_batch_size'], config['batch_size']) z_, y_ = utils.prepare_z_y(G_batch_size, G.dim_z, config['n_classes'], device=device, fp16=config['G_fp16'], z_var=config['z_var']) get_inception_metrics = inception_tf.prepare_inception_metrics(config['dataset'], config['parallel'], config) G.load_state_dict(torch.load(dnnlib.util.open_file_or_url(config['network']))) if config['G_eval_mode']: G.eval() else: G.train() sample = functools.partial(utils.sample, G=G, z_=z_, y_=y_, config=config) IS_list = [] FID_list = [] for _ in tqdm(range(config['repeat'])): IS, _, FID = get_inception_metrics(sample, config['num_inception_images'], num_splits=10, prints=False) IS_list.append(IS) FID_list.append(FID) if config['repeat'] > 1: print('IS mean: {}, std: {}'.format(np.mean(IS_list), np.std(IS_list))) print('FID mean: {}, std: {}'.format(np.mean(FID_list), np.std(FID_list))) else: print('IS: {}'.format(np.mean(IS_list))) print('FID: {}'.format(np.mean(FID_list)))
[ "def", "run_eval", "(", "config", ")", ":", "# update config (see train.py for explanation)", "config", "[", "'resolution'", "]", "=", "utils", ".", "imsize_dict", "[", "config", "[", "'dataset'", "]", "]", "config", "[", "'n_classes'", "]", "=", "utils", ".", ...
https://github.com/mit-han-lab/data-efficient-gans/blob/6858275f08f43a33026844c8c2ac4e703e8a07ba/DiffAugment-biggan-cifar/eval.py#L11-L49
9miao/Firefly
fd2795b8c26de6ab63bbec23d11f18c3dfb39a50
gfirefly/netconnect/protoc.py
python
LiberateFactory.doConnectionMade
(self,conn)
当连接建立时的处理
当连接建立时的处理
[ "当连接建立时的处理" ]
def doConnectionMade(self,conn): '''当连接建立时的处理''' pass
[ "def", "doConnectionMade", "(", "self", ",", "conn", ")", ":", "pass" ]
https://github.com/9miao/Firefly/blob/fd2795b8c26de6ab63bbec23d11f18c3dfb39a50/gfirefly/netconnect/protoc.py#L86-L88
nedbat/coveragepy
d004b18a1ad59ec89b89c96c03a789a55cc51693
coverage/control.py
python
Coverage.current
(cls)
Get the latest started `Coverage` instance, if any. Returns: a `Coverage` instance, or None. .. versionadded:: 5.0
Get the latest started `Coverage` instance, if any.
[ "Get", "the", "latest", "started", "Coverage", "instance", "if", "any", "." ]
def current(cls): """Get the latest started `Coverage` instance, if any. Returns: a `Coverage` instance, or None. .. versionadded:: 5.0 """ if cls._instances: return cls._instances[-1] else: return None
[ "def", "current", "(", "cls", ")", ":", "if", "cls", ".", "_instances", ":", "return", "cls", ".", "_instances", "[", "-", "1", "]", "else", ":", "return", "None" ]
https://github.com/nedbat/coveragepy/blob/d004b18a1ad59ec89b89c96c03a789a55cc51693/coverage/control.py#L90-L101
MontrealCorpusTools/Montreal-Forced-Aligner
63473f9a4fabd31eec14e1e5022882f85cfdaf31
montreal_forced_aligner/alignment/base.py
python
CorpusAligner.ctms_to_textgrids_non_mp
(self)
Parse CTM files to TextGrids without using multiprocessing
Parse CTM files to TextGrids without using multiprocessing
[ "Parse", "CTM", "files", "to", "TextGrids", "without", "using", "multiprocessing" ]
def ctms_to_textgrids_non_mp(self) -> None: """ Parse CTM files to TextGrids without using multiprocessing """ self.log_debug("Not using multiprocessing for TextGrid export") export_errors = {} w_args = self.word_ctm_arguments() p_args = self.phone_ctm_arguments() for j in self.jobs: word_arguments = w_args[j.name] phone_arguments = p_args[j.name] self.logger.debug(f"Parsing ctms for job {j.name}...") for dict_name in word_arguments.dictionaries: with open(word_arguments.ctm_paths[dict_name], "r") as f: for line in f: line = line.strip() if line == "": continue interval = process_ctm_line(line) utt = self.utterances[interval.utterance] dictionary = self.get_dictionary(utt.speaker_name) label = dictionary.reversed_word_mapping[int(interval.label)] interval.label = label utt.add_word_intervals(interval) for dict_name in phone_arguments.dictionaries: with open(phone_arguments.ctm_paths[dict_name], "r") as f: for line in f: line = line.strip() if line == "": continue interval = process_ctm_line(line) utt = self.utterances[interval.utterance] dictionary = self.get_dictionary(utt.speaker_name) label = dictionary.reversed_phone_mapping[int(interval.label)] if self.position_dependent_phones: for p in dictionary.positions: if label.endswith(p): label = label[: -1 * len(p)] interval.label = label utt.add_phone_intervals(interval) for file in self.files: data = file.aligned_data backup_output_directory = None if not self.overwrite: backup_output_directory = self.backup_output_directory os.makedirs(backup_output_directory, exist_ok=True) output_path = file.construct_output_path(self.textgrid_output, backup_output_directory) export_textgrid(data, output_path, file.duration, self.frame_shift) if export_errors: self.logger.warning( f"There were {len(export_errors)} errors encountered in generating TextGrids. " f"Check the output_errors.txt file in {os.path.join(self.textgrid_output)} " f"for more details" ) output_textgrid_writing_errors(self.textgrid_output, export_errors)
[ "def", "ctms_to_textgrids_non_mp", "(", "self", ")", "->", "None", ":", "self", ".", "log_debug", "(", "\"Not using multiprocessing for TextGrid export\"", ")", "export_errors", "=", "{", "}", "w_args", "=", "self", ".", "word_ctm_arguments", "(", ")", "p_args", "...
https://github.com/MontrealCorpusTools/Montreal-Forced-Aligner/blob/63473f9a4fabd31eec14e1e5022882f85cfdaf31/montreal_forced_aligner/alignment/base.py#L372-L433
brannondorsey/PassGAN
5eeca016908d3ecc7a78a2d2b66154cb61d19f44
tflib/__init__.py
python
delete_param_aliases
()
[]
def delete_param_aliases(): _param_aliases.clear()
[ "def", "delete_param_aliases", "(", ")", ":", "_param_aliases", ".", "clear", "(", ")" ]
https://github.com/brannondorsey/PassGAN/blob/5eeca016908d3ecc7a78a2d2b66154cb61d19f44/tflib/__init__.py#L47-L48
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.4/django/core/cache/backends/base.py
python
BaseCache.clear
(self)
Remove *all* values from the cache at once.
Remove *all* values from the cache at once.
[ "Remove", "*", "all", "*", "values", "from", "the", "cache", "at", "once", "." ]
def clear(self): """Remove *all* values from the cache at once.""" raise NotImplementedError
[ "def", "clear", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.4/django/core/cache/backends/base.py#L183-L185
beeware/ouroboros
a29123c6fab6a807caffbb7587cf548e0c370296
ouroboros/base64.py
python
urlsafe_b64encode
(s)
return b64encode(s).translate(_urlsafe_encode_translation)
Encode a byte string using a url-safe Base64 alphabet. s is the byte string to encode. The encoded byte string is returned. The alphabet uses '-' instead of '+' and '_' instead of '/'.
Encode a byte string using a url-safe Base64 alphabet.
[ "Encode", "a", "byte", "string", "using", "a", "url", "-", "safe", "Base64", "alphabet", "." ]
def urlsafe_b64encode(s): """Encode a byte string using a url-safe Base64 alphabet. s is the byte string to encode. The encoded byte string is returned. The alphabet uses '-' instead of '+' and '_' instead of '/'. """ return b64encode(s).translate(_urlsafe_encode_translation)
[ "def", "urlsafe_b64encode", "(", "s", ")", ":", "return", "b64encode", "(", "s", ")", ".", "translate", "(", "_urlsafe_encode_translation", ")" ]
https://github.com/beeware/ouroboros/blob/a29123c6fab6a807caffbb7587cf548e0c370296/ouroboros/base64.py#L114-L121
aws/sagemaker-python-sdk
9d259b316f7f43838c16f35c10e98a110b56735b
src/sagemaker/session.py
python
Session.wait_for_compilation_job
(self, job, poll=5)
return desc
Wait for an Amazon SageMaker Neo compilation job to complete. Args: job (str): Name of the compilation job to wait for. poll (int): Polling interval in seconds (default: 5). Returns: (dict): Return value from the ``DescribeCompilationJob`` API. Raises: exceptions.UnexpectedStatusException: If the compilation job fails.
Wait for an Amazon SageMaker Neo compilation job to complete.
[ "Wait", "for", "an", "Amazon", "SageMaker", "Neo", "compilation", "job", "to", "complete", "." ]
def wait_for_compilation_job(self, job, poll=5): """Wait for an Amazon SageMaker Neo compilation job to complete. Args: job (str): Name of the compilation job to wait for. poll (int): Polling interval in seconds (default: 5). Returns: (dict): Return value from the ``DescribeCompilationJob`` API. Raises: exceptions.UnexpectedStatusException: If the compilation job fails. """ desc = _wait_until(lambda: _compilation_job_status(self.sagemaker_client, job), poll) self._check_job_status(job, desc, "CompilationJobStatus") return desc
[ "def", "wait_for_compilation_job", "(", "self", ",", "job", ",", "poll", "=", "5", ")", ":", "desc", "=", "_wait_until", "(", "lambda", ":", "_compilation_job_status", "(", "self", ".", "sagemaker_client", ",", "job", ")", ",", "poll", ")", "self", ".", ...
https://github.com/aws/sagemaker-python-sdk/blob/9d259b316f7f43838c16f35c10e98a110b56735b/src/sagemaker/session.py#L3212-L3227
clips/pattern
d25511f9ca7ed9356b801d8663b8b5168464e68f
pattern/vector/stemmer.py
python
case_sensitive
(stem, word)
return "".join(ch)
Applies the letter case of the word to the stem: Ponies => Poni
Applies the letter case of the word to the stem: Ponies => Poni
[ "Applies", "the", "letter", "case", "of", "the", "word", "to", "the", "stem", ":", "Ponies", "=", ">", "Poni" ]
def case_sensitive(stem, word): """ Applies the letter case of the word to the stem: Ponies => Poni """ ch = [] for i in range(len(stem)): if word[i] == word[i].upper(): ch.append(stem[i].upper()) else: ch.append(stem[i]) return "".join(ch)
[ "def", "case_sensitive", "(", "stem", ",", "word", ")", ":", "ch", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "stem", ")", ")", ":", "if", "word", "[", "i", "]", "==", "word", "[", "i", "]", ".", "upper", "(", ")", ":", "ch"...
https://github.com/clips/pattern/blob/d25511f9ca7ed9356b801d8663b8b5168464e68f/pattern/vector/stemmer.py#L319-L329
ninuxorg/nodeshot
2466f0a55f522b2696026f196436ce7ba3f1e5c6
nodeshot/networking/links/models/link.py
python
Link.ensure
(self, status, cost)
ensure link properties correspond to the specified ones perform save operation only if necessary
ensure link properties correspond to the specified ones perform save operation only if necessary
[ "ensure", "link", "properties", "correspond", "to", "the", "specified", "ones", "perform", "save", "operation", "only", "if", "necessary" ]
def ensure(self, status, cost): """ ensure link properties correspond to the specified ones perform save operation only if necessary """ changed = False status_id = LINK_STATUS[status] if self.status != status_id: self.status = status_id changed = True if self.metric_value != cost: self.metric_value = cost changed = True if changed: self.save()
[ "def", "ensure", "(", "self", ",", "status", ",", "cost", ")", ":", "changed", "=", "False", "status_id", "=", "LINK_STATUS", "[", "status", "]", "if", "self", ".", "status", "!=", "status_id", ":", "self", ".", "status", "=", "status_id", "changed", "...
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/links/models/link.py#L280-L294
openedx/edx-platform
68dd185a0ab45862a2a61e0f803d7e03d2be71b5
openedx/core/lib/blockstore_api/methods.py
python
write_draft_file
(draft_uuid, path, contents)
Create or overwrite the file at 'path' in the specified draft with the given contents. To delete a file, pass contents=None. If you don't know the draft's UUID, look it up using get_or_create_bundle_draft() Does not return anything.
Create or overwrite the file at 'path' in the specified draft with the given contents. To delete a file, pass contents=None.
[ "Create", "or", "overwrite", "the", "file", "at", "path", "in", "the", "specified", "draft", "with", "the", "given", "contents", ".", "To", "delete", "a", "file", "pass", "contents", "=", "None", "." ]
def write_draft_file(draft_uuid, path, contents): """ Create or overwrite the file at 'path' in the specified draft with the given contents. To delete a file, pass contents=None. If you don't know the draft's UUID, look it up using get_or_create_bundle_draft() Does not return anything. """ api_request('patch', api_url('drafts', str(draft_uuid)), json={ 'files': { path: encode_str_for_draft(contents) if contents is not None else None, }, })
[ "def", "write_draft_file", "(", "draft_uuid", ",", "path", ",", "contents", ")", ":", "api_request", "(", "'patch'", ",", "api_url", "(", "'drafts'", ",", "str", "(", "draft_uuid", ")", ")", ",", "json", "=", "{", "'files'", ":", "{", "path", ":", "enc...
https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/openedx/core/lib/blockstore_api/methods.py#L373-L387
Textualize/rich
d39626143036188cb2c9e1619e836540f5b627f8
rich/__main__.py
python
make_test_card
()
return table
Get a renderable that demonstrates a number of features.
Get a renderable that demonstrates a number of features.
[ "Get", "a", "renderable", "that", "demonstrates", "a", "number", "of", "features", "." ]
def make_test_card() -> Table: """Get a renderable that demonstrates a number of features.""" table = Table.grid(padding=1, pad_edge=True) table.title = "Rich features" table.add_column("Feature", no_wrap=True, justify="center", style="bold red") table.add_column("Demonstration") color_table = Table( box=None, expand=False, show_header=False, show_edge=False, pad_edge=False, ) color_table.add_row( # "[bold yellow]256[/] colors or [bold green]16.7 million[/] colors [blue](if supported by your terminal)[/].", ( "✓ [bold green]4-bit color[/]\n" "✓ [bold blue]8-bit color[/]\n" "✓ [bold magenta]Truecolor (16.7 million)[/]\n" "✓ [bold yellow]Dumb terminals[/]\n" "✓ [bold cyan]Automatic color conversion" ), ColorBox(), ) table.add_row("Colors", color_table) table.add_row( "Styles", "All ansi styles: [bold]bold[/], [dim]dim[/], [italic]italic[/italic], [underline]underline[/], [strike]strikethrough[/], [reverse]reverse[/], and even [blink]blink[/].", ) lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque in metus sed sapien ultricies pretium a at justo. Maecenas luctus velit et auctor maximus." lorem_table = Table.grid(padding=1, collapse_padding=True) lorem_table.pad_edge = False lorem_table.add_row( Text(lorem, justify="left", style="green"), Text(lorem, justify="center", style="yellow"), Text(lorem, justify="right", style="blue"), Text(lorem, justify="full", style="red"), ) table.add_row( "Text", Group( Text.from_markup( """Word wrap text. Justify [green]left[/], [yellow]center[/], [blue]right[/] or [red]full[/].\n""" ), lorem_table, ), ) def comparison(renderable1: RenderableType, renderable2: RenderableType) -> Table: table = Table(show_header=False, pad_edge=False, box=None, expand=True) table.add_column("1", ratio=1) table.add_column("2", ratio=1) table.add_row(renderable1, renderable2) return table table.add_row( "Asian\nlanguage\nsupport", ":flag_for_china: 该库支持中文,日文和韩文文本!\n:flag_for_japan: ライブラリは中国語、日本語、韓国語のテキストをサポートしています\n:flag_for_south_korea: 이 라이브러리는 중국어, 일본어 및 한국어 텍스트를 지원합니다", ) markup_example = ( "[bold magenta]Rich[/] supports a simple [i]bbcode[/i]-like [b]markup[/b] for [yellow]color[/], [underline]style[/], and emoji! " ":+1: :apple: :ant: :bear: :baguette_bread: :bus: " ) table.add_row("Markup", markup_example) example_table = Table( show_edge=False, show_header=True, expand=False, row_styles=["none", "dim"], box=box.SIMPLE, ) example_table.add_column("[green]Date", style="green", no_wrap=True) example_table.add_column("[blue]Title", style="blue") example_table.add_column( "[cyan]Production Budget", style="cyan", justify="right", no_wrap=True, ) example_table.add_column( "[magenta]Box Office", style="magenta", justify="right", no_wrap=True, ) example_table.add_row( "Dec 20, 2019", "Star Wars: The Rise of Skywalker", "$275,000,000", "$375,126,118", ) example_table.add_row( "May 25, 2018", "[b]Solo[/]: A Star Wars Story", "$275,000,000", "$393,151,347", ) example_table.add_row( "Dec 15, 2017", "Star Wars Ep. VIII: The Last Jedi", "$262,000,000", "[bold]$1,332,539,889[/bold]", ) example_table.add_row( "May 19, 1999", "Star Wars Ep. [b]I[/b]: [i]The phantom Menace", "$115,000,000", "$1,027,044,677", ) table.add_row("Tables", example_table) code = '''\ def iter_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]: """Iterate and generate a tuple with a flag for last value.""" iter_values = iter(values) try: previous_value = next(iter_values) except StopIteration: return for value in iter_values: yield False, previous_value previous_value = value yield True, previous_value''' pretty_data = { "foo": [ 3.1427, ( "Paul Atreides", "Vladimir Harkonnen", "Thufir Hawat", ), ], "atomic": (False, True, None), } table.add_row( "Syntax\nhighlighting\n&\npretty\nprinting", comparison( Syntax(code, "python3", line_numbers=True, indent_guides=True), Pretty(pretty_data, indent_guides=True), ), ) markdown_example = """\ # Markdown Supports much of the *markdown* __syntax__! - Headers - Basic formatting: **bold**, *italic*, `code` - Block quotes - Lists, and more... """ table.add_row( "Markdown", comparison("[cyan]" + markdown_example, Markdown(markdown_example)) ) table.add_row( "+more!", """Progress bars, columns, styled logging handler, tracebacks, etc...""", ) return table
[ "def", "make_test_card", "(", ")", "->", "Table", ":", "table", "=", "Table", ".", "grid", "(", "padding", "=", "1", ",", "pad_edge", "=", "True", ")", "table", ".", "title", "=", "\"Rich features\"", "table", ".", "add_column", "(", "\"Feature\"", ",", ...
https://github.com/Textualize/rich/blob/d39626143036188cb2c9e1619e836540f5b627f8/rich/__main__.py#L39-L207
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/logic/boolalg.py
python
Equivalent.args
(self)
return tuple(ordered(self._argset))
[]
def args(self): return tuple(ordered(self._argset))
[ "def", "args", "(", "self", ")", ":", "return", "tuple", "(", "ordered", "(", "self", ".", "_argset", ")", ")" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/logic/boolalg.py#L714-L715
dpgaspar/Flask-AppBuilder
557249f33b66d02a48c1322ef21324b815abe18e
flask_appbuilder/security/registerviews.py
python
BaseRegisterUser.add_registration
(self, username, first_name, last_name, email, password="")
Add a registration request for the user. :rtype : RegisterUser
Add a registration request for the user.
[ "Add", "a", "registration", "request", "for", "the", "user", "." ]
def add_registration(self, username, first_name, last_name, email, password=""): """ Add a registration request for the user. :rtype : RegisterUser """ register_user = self.appbuilder.sm.add_register_user( username, first_name, last_name, email, password ) if register_user: if self.send_email(register_user): flash(as_unicode(self.message), "info") return register_user else: flash(as_unicode(self.error_message), "danger") self.appbuilder.sm.del_register_user(register_user) return None
[ "def", "add_registration", "(", "self", ",", "username", ",", "first_name", ",", "last_name", ",", "email", ",", "password", "=", "\"\"", ")", ":", "register_user", "=", "self", ".", "appbuilder", ".", "sm", ".", "add_register_user", "(", "username", ",", ...
https://github.com/dpgaspar/Flask-AppBuilder/blob/557249f33b66d02a48c1322ef21324b815abe18e/flask_appbuilder/security/registerviews.py#L102-L118
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/Django-1.11.29/django/templatetags/i18n.py
python
do_translate
(parser, token)
return TranslateNode(message_string, noop, asvar, message_context)
This will mark a string for translation and will translate the string for the current language. Usage:: {% trans "this is a test" %} This will mark the string for translation so it will be pulled out by mark-messages.py into the .po files and will run the string through the translation engine. There is a second form:: {% trans "this is a test" noop %} This will only mark for translation, but will return the string unchanged. Use it when you need to store values into forms that should be translated later on. You can use variables instead of constant strings to translate stuff you marked somewhere else:: {% trans variable %} This will just try to translate the contents of the variable ``variable``. Make sure that the string in there is something that is in the .po file. It is possible to store the translated string into a variable:: {% trans "this is a test" as var %} {{ var }} Contextual translations are also supported:: {% trans "this is a test" context "greeting" %} This is equivalent to calling pgettext instead of (u)gettext.
This will mark a string for translation and will translate the string for the current language.
[ "This", "will", "mark", "a", "string", "for", "translation", "and", "will", "translate", "the", "string", "for", "the", "current", "language", "." ]
def do_translate(parser, token): """ This will mark a string for translation and will translate the string for the current language. Usage:: {% trans "this is a test" %} This will mark the string for translation so it will be pulled out by mark-messages.py into the .po files and will run the string through the translation engine. There is a second form:: {% trans "this is a test" noop %} This will only mark for translation, but will return the string unchanged. Use it when you need to store values into forms that should be translated later on. You can use variables instead of constant strings to translate stuff you marked somewhere else:: {% trans variable %} This will just try to translate the contents of the variable ``variable``. Make sure that the string in there is something that is in the .po file. It is possible to store the translated string into a variable:: {% trans "this is a test" as var %} {{ var }} Contextual translations are also supported:: {% trans "this is a test" context "greeting" %} This is equivalent to calling pgettext instead of (u)gettext. """ bits = token.split_contents() if len(bits) < 2: raise TemplateSyntaxError("'%s' takes at least one argument" % bits[0]) message_string = parser.compile_filter(bits[1]) remaining = bits[2:] noop = False asvar = None message_context = None seen = set() invalid_context = {'as', 'noop'} while remaining: option = remaining.pop(0) if option in seen: raise TemplateSyntaxError( "The '%s' option was specified more than once." % option, ) elif option == 'noop': noop = True elif option == 'context': try: value = remaining.pop(0) except IndexError: msg = "No argument provided to the '%s' tag for the context option." % bits[0] six.reraise(TemplateSyntaxError, TemplateSyntaxError(msg), sys.exc_info()[2]) if value in invalid_context: raise TemplateSyntaxError( "Invalid argument '%s' provided to the '%s' tag for the context option" % (value, bits[0]), ) message_context = parser.compile_filter(value) elif option == 'as': try: value = remaining.pop(0) except IndexError: msg = "No argument provided to the '%s' tag for the as option." % bits[0] six.reraise(TemplateSyntaxError, TemplateSyntaxError(msg), sys.exc_info()[2]) asvar = value else: raise TemplateSyntaxError( "Unknown argument for '%s' tag: '%s'. The only options " "available are 'noop', 'context' \"xxx\", and 'as VAR'." % ( bits[0], option, ) ) seen.add(option) return TranslateNode(message_string, noop, asvar, message_context)
[ "def", "do_translate", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", "<", "2", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes at least one argument\"", "%", "bits", "[", ...
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/Django-1.11.29/django/templatetags/i18n.py#L328-L416
qutebrowser/qutebrowser
3a2aaaacbf97f4bf0c72463f3da94ed2822a5442
qutebrowser/misc/sessions.py
python
SessionManager._save_all
(self, *, only_window=None, with_private=False)
return data
Get a dict with data for all windows/tabs.
Get a dict with data for all windows/tabs.
[ "Get", "a", "dict", "with", "data", "for", "all", "windows", "/", "tabs", "." ]
def _save_all(self, *, only_window=None, with_private=False): """Get a dict with data for all windows/tabs.""" data: _JsonType = {'windows': []} if only_window is not None: winlist: Iterable[int] = [only_window] else: winlist = objreg.window_registry for win_id in sorted(winlist): tabbed_browser = objreg.get('tabbed-browser', scope='window', window=win_id) main_window = objreg.get('main-window', scope='window', window=win_id) # We could be in the middle of destroying a window here if sip.isdeleted(main_window): continue if tabbed_browser.is_private and not with_private: continue win_data: _JsonType = {} active_window = objects.qapp.activeWindow() if getattr(active_window, 'win_id', None) == win_id: win_data['active'] = True win_data['geometry'] = bytes(main_window.saveGeometry()) win_data['tabs'] = [] if tabbed_browser.is_private: win_data['private'] = True for i, tab in enumerate(tabbed_browser.widgets()): active = i == tabbed_browser.widget.currentIndex() win_data['tabs'].append(self._save_tab(tab, active)) data['windows'].append(win_data) return data
[ "def", "_save_all", "(", "self", ",", "*", ",", "only_window", "=", "None", ",", "with_private", "=", "False", ")", ":", "data", ":", "_JsonType", "=", "{", "'windows'", ":", "[", "]", "}", "if", "only_window", "is", "not", "None", ":", "winlist", ":...
https://github.com/qutebrowser/qutebrowser/blob/3a2aaaacbf97f4bf0c72463f3da94ed2822a5442/qutebrowser/misc/sessions.py#L267-L300
edisonlz/fastor
342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3
base/site-packages/gdata/youtube/service.py
python
YouTubeService.GetYouTubeVideoCommentFeed
(self, uri=None, video_id=None)
return self.Get( uri, converter=gdata.youtube.YouTubeVideoCommentFeedFromString)
Retrieve a YouTubeVideoCommentFeed. Either a uri or a video_id must be provided. Args: uri: An optional string representing the URI of the comment feed that is to be retrieved. video_id: An optional string representing the ID of the video for which to retrieve the comment feed. Returns: A YouTubeVideoCommentFeed if successfully retrieved. Raises: YouTubeError: You must provide at least a uri or a video_id to the GetYouTubeVideoCommentFeed() method.
Retrieve a YouTubeVideoCommentFeed.
[ "Retrieve", "a", "YouTubeVideoCommentFeed", "." ]
def GetYouTubeVideoCommentFeed(self, uri=None, video_id=None): """Retrieve a YouTubeVideoCommentFeed. Either a uri or a video_id must be provided. Args: uri: An optional string representing the URI of the comment feed that is to be retrieved. video_id: An optional string representing the ID of the video for which to retrieve the comment feed. Returns: A YouTubeVideoCommentFeed if successfully retrieved. Raises: YouTubeError: You must provide at least a uri or a video_id to the GetYouTubeVideoCommentFeed() method. """ if uri is None and video_id is None: raise YouTubeError('You must provide at least a uri or a video_id ' 'to the GetYouTubeVideoCommentFeed() method') elif video_id and not uri: uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'comments') return self.Get( uri, converter=gdata.youtube.YouTubeVideoCommentFeedFromString)
[ "def", "GetYouTubeVideoCommentFeed", "(", "self", ",", "uri", "=", "None", ",", "video_id", "=", "None", ")", ":", "if", "uri", "is", "None", "and", "video_id", "is", "None", ":", "raise", "YouTubeError", "(", "'You must provide at least a uri or a video_id '", ...
https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/gdata/youtube/service.py#L241-L265
cms-dev/cms
0401c5336b34b1731736045da4877fef11889274
cms/grading/scoring.py
python
_task_score_max
(score_details_tokened)
return max_score
Compute score using the "max" score mode. This was used in IOI 2013-2016. The score of a participant on a task is the maximum score amongst all submissions (not yet computed scores count as 0.0). score_details_tokened ([(float|None, object|None, bool)]): a tuple for each submission of the user in the task, containing score, score details (each None if not scored yet) and if the submission was tokened. return (float): the score.
Compute score using the "max" score mode.
[ "Compute", "score", "using", "the", "max", "score", "mode", "." ]
def _task_score_max(score_details_tokened): """Compute score using the "max" score mode. This was used in IOI 2013-2016. The score of a participant on a task is the maximum score amongst all submissions (not yet computed scores count as 0.0). score_details_tokened ([(float|None, object|None, bool)]): a tuple for each submission of the user in the task, containing score, score details (each None if not scored yet) and if the submission was tokened. return (float): the score. """ max_score = 0.0 for score, _, _ in score_details_tokened: if score is not None: max_score = max(max_score, score) return max_score
[ "def", "_task_score_max", "(", "score_details_tokened", ")", ":", "max_score", "=", "0.0", "for", "score", ",", "_", ",", "_", "in", "score_details_tokened", ":", "if", "score", "is", "not", "None", ":", "max_score", "=", "max", "(", "max_score", ",", "sco...
https://github.com/cms-dev/cms/blob/0401c5336b34b1731736045da4877fef11889274/cms/grading/scoring.py#L257-L277
makerbot/ReplicatorG
d6f2b07785a5a5f1e172fb87cb4303b17c575d5d
skein_engines/skeinforge-47/fabmetheus_utilities/geometry/solids/group.py
python
Group.__init__
(self)
Add empty lists.
Add empty lists.
[ "Add", "empty", "lists", "." ]
def __init__(self): "Add empty lists." dictionary.Dictionary.__init__(self) self.matrix4X4 = matrix.Matrix()
[ "def", "__init__", "(", "self", ")", ":", "dictionary", ".", "Dictionary", ".", "__init__", "(", "self", ")", "self", ".", "matrix4X4", "=", "matrix", ".", "Matrix", "(", ")" ]
https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-47/fabmetheus_utilities/geometry/solids/group.py#L43-L46
ifwe/digsby
f5fe00244744aa131e07f09348d10563f3d8fa99
digsby/src/common/spelling/spellcheck.py
python
SpellChecker.Suggest
(self,word,count=None)
return [self._decode(s) for s in suggestions]
Return a list of suggested replacement words if the word is spelled incorrectly Returns an empty list if the word is correctly spelled
Return a list of suggested replacement words if the word is spelled incorrectly Returns an empty list if the word is correctly spelled
[ "Return", "a", "list", "of", "suggested", "replacement", "words", "if", "the", "word", "is", "spelled", "incorrectly", "Returns", "an", "empty", "list", "if", "the", "word", "is", "correctly", "spelled" ]
def Suggest(self,word,count=None): """ Return a list of suggested replacement words if the word is spelled incorrectly Returns an empty list if the word is correctly spelled """ if self.spellengine is None: return [] if not word: return [] if not count: count = self._pref("max_suggestions") suggestions = self.spellengine.suggest(self._encode(word)) if len(suggestions) > count: suggestions = suggestions[:count] return [self._decode(s) for s in suggestions]
[ "def", "Suggest", "(", "self", ",", "word", ",", "count", "=", "None", ")", ":", "if", "self", ".", "spellengine", "is", "None", ":", "return", "[", "]", "if", "not", "word", ":", "return", "[", "]", "if", "not", "count", ":", "count", "=", "self...
https://github.com/ifwe/digsby/blob/f5fe00244744aa131e07f09348d10563f3d8fa99/digsby/src/common/spelling/spellcheck.py#L412-L432
mypaint/mypaint
90b36dbc7b8bd2f323383f7edf608a5e0a3a1a33
lib/floodfill.py
python
FloodFillArguments.skip_empty_dst
(self)
return ( self.lock_alpha or self.mode in [ myplib.CombineSourceAtop, myplib.CombineDestinationOut, myplib.CombineDestinationIn, ] )
If true, compositing to empty tiles does nothing
If true, compositing to empty tiles does nothing
[ "If", "true", "compositing", "to", "empty", "tiles", "does", "nothing" ]
def skip_empty_dst(self): """If true, compositing to empty tiles does nothing""" return ( self.lock_alpha or self.mode in [ myplib.CombineSourceAtop, myplib.CombineDestinationOut, myplib.CombineDestinationIn, ] )
[ "def", "skip_empty_dst", "(", "self", ")", ":", "return", "(", "self", ".", "lock_alpha", "or", "self", ".", "mode", "in", "[", "myplib", ".", "CombineSourceAtop", ",", "myplib", ".", "CombineDestinationOut", ",", "myplib", ".", "CombineDestinationIn", ",", ...
https://github.com/mypaint/mypaint/blob/90b36dbc7b8bd2f323383f7edf608a5e0a3a1a33/lib/floodfill.py#L246-L254
numenta/nupic
b9ebedaf54f49a33de22d8d44dff7c765cdb5548
external/linux32/lib/python2.6/site-packages/matplotlib/ticker.py
python
LogFormatter.format_data_short
(self,value)
return '%1.3g'%value
return a short formatted string representation of a number
return a short formatted string representation of a number
[ "return", "a", "short", "formatted", "string", "representation", "of", "a", "number" ]
def format_data_short(self,value): 'return a short formatted string representation of a number' return '%1.3g'%value
[ "def", "format_data_short", "(", "self", ",", "value", ")", ":", "return", "'%1.3g'", "%", "value" ]
https://github.com/numenta/nupic/blob/b9ebedaf54f49a33de22d8d44dff7c765cdb5548/external/linux32/lib/python2.6/site-packages/matplotlib/ticker.py#L526-L528
Yelp/paasta
6c08c04a577359509575c794b973ea84d72accf9
paasta_tools/marathon_tools.py
python
MarathonServiceConfig.get_healthchecks
( self, service_namespace_config: ServiceNamespaceConfig )
return healthchecks
Returns a list of healthchecks per `the Marathon docs`_. If you have an http service, it uses the default endpoint that smartstack uses. (/status currently) Otherwise these do *not* use the same thresholds as smartstack in order to not produce a negative feedback loop, where mesos aggressively kills tasks because they are slow, which causes other things to be slow, etc. If the mode of the service is None, indicating that it was not specified in the service config and smartstack is not used by the service, no healthchecks are passed to Marathon. This ensures that it falls back to Mesos' knowledge of the task state as described in `the Marathon docs`_. In this case, we provide an empty array of healthchecks per `the Marathon API docs`_ (scroll down to the healthChecks subsection). .. _the Marathon docs: https://mesosphere.github.io/marathon/docs/health-checks.html .. _the Marathon API docs: https://mesosphere.github.io/marathon/docs/rest-api.html#post-/v2/apps :param service_config: service config hash :returns: list of healthcheck definitions for marathon
Returns a list of healthchecks per `the Marathon docs`_.
[ "Returns", "a", "list", "of", "healthchecks", "per", "the", "Marathon", "docs", "_", "." ]
def get_healthchecks( self, service_namespace_config: ServiceNamespaceConfig ) -> List[HealthcheckDict]: """Returns a list of healthchecks per `the Marathon docs`_. If you have an http service, it uses the default endpoint that smartstack uses. (/status currently) Otherwise these do *not* use the same thresholds as smartstack in order to not produce a negative feedback loop, where mesos aggressively kills tasks because they are slow, which causes other things to be slow, etc. If the mode of the service is None, indicating that it was not specified in the service config and smartstack is not used by the service, no healthchecks are passed to Marathon. This ensures that it falls back to Mesos' knowledge of the task state as described in `the Marathon docs`_. In this case, we provide an empty array of healthchecks per `the Marathon API docs`_ (scroll down to the healthChecks subsection). .. _the Marathon docs: https://mesosphere.github.io/marathon/docs/health-checks.html .. _the Marathon API docs: https://mesosphere.github.io/marathon/docs/rest-api.html#post-/v2/apps :param service_config: service config hash :returns: list of healthcheck definitions for marathon""" mode = self.get_healthcheck_mode(service_namespace_config) graceperiodseconds = self.get_healthcheck_grace_period_seconds() intervalseconds = self.get_healthcheck_interval_seconds() timeoutseconds = self.get_healthcheck_timeout_seconds() maxconsecutivefailures = self.get_healthcheck_max_consecutive_failures() if mode == "http" or mode == "https": http_path = self.get_healthcheck_uri(service_namespace_config) protocol = f"MESOS_{mode.upper()}" healthchecks = [ HealthcheckDict( { "protocol": protocol, "path": http_path, "gracePeriodSeconds": graceperiodseconds, "intervalSeconds": intervalseconds, "portIndex": 0, "timeoutSeconds": timeoutseconds, "maxConsecutiveFailures": maxconsecutivefailures, } ) ] elif mode == "tcp": healthchecks = [ HealthcheckDict( { "protocol": "TCP", "gracePeriodSeconds": graceperiodseconds, "intervalSeconds": intervalseconds, "portIndex": 0, "timeoutSeconds": timeoutseconds, "maxConsecutiveFailures": maxconsecutivefailures, } ) ] elif mode == "cmd": healthchecks = [ HealthcheckDict( { "protocol": "COMMAND", "command": self.get_healthcheck_cmd(), "gracePeriodSeconds": graceperiodseconds, "intervalSeconds": intervalseconds, "timeoutSeconds": timeoutseconds, "maxConsecutiveFailures": maxconsecutivefailures, } ) ] elif mode is None: healthchecks = [] else: raise InvalidHealthcheckMode( "Unknown mode: %s. Only acceptable healthcheck modes are http/https/tcp/cmd" % mode ) return healthchecks
[ "def", "get_healthchecks", "(", "self", ",", "service_namespace_config", ":", "ServiceNamespaceConfig", ")", "->", "List", "[", "HealthcheckDict", "]", ":", "mode", "=", "self", ".", "get_healthcheck_mode", "(", "service_namespace_config", ")", "graceperiodseconds", "...
https://github.com/Yelp/paasta/blob/6c08c04a577359509575c794b973ea84d72accf9/paasta_tools/marathon_tools.py#L768-L848
MeanEYE/Sunflower
1024bbdde3b8e202ddad3553b321a7b6230bffc9
sunflower/gui/main_window.py
python
MainWindow.register_column_editor_extension
(self, extension)
Register column editor extension
Register column editor extension
[ "Register", "column", "editor", "extension" ]
def register_column_editor_extension(self, extension): """Register column editor extension""" self.column_editor_extensions.append(extension)
[ "def", "register_column_editor_extension", "(", "self", ",", "extension", ")", ":", "self", ".", "column_editor_extensions", ".", "append", "(", "extension", ")" ]
https://github.com/MeanEYE/Sunflower/blob/1024bbdde3b8e202ddad3553b321a7b6230bffc9/sunflower/gui/main_window.py#L2273-L2275
seppius-xbmc-repo/ru
d0879d56ec8243b2c7af44fda5cf3d1ff77fd2e2
script.yandex.tvguide/source.py
python
Channel.__init__
(self, id, title, logo = None)
[]
def __init__(self, id, title, logo = None): self.id = id self.title = title self.logo = logo
[ "def", "__init__", "(", "self", ",", "id", ",", "title", ",", "logo", "=", "None", ")", ":", "self", ".", "id", "=", "id", "self", ".", "title", "=", "title", "self", ".", "logo", "=", "logo" ]
https://github.com/seppius-xbmc-repo/ru/blob/d0879d56ec8243b2c7af44fda5cf3d1ff77fd2e2/script.yandex.tvguide/source.py#L17-L20
wxWidgets/Phoenix
b2199e299a6ca6d866aa6f3d0888499136ead9d6
wx/lib/ogl/composit.py
python
CompositeShape.OnEndDragLeft
(self, x, y, keys = 0, attachment = 0)
The end drag left handler.
The end drag left handler.
[ "The", "end", "drag", "left", "handler", "." ]
def OnEndDragLeft(self, x, y, keys = 0, attachment = 0): """The end drag left handler.""" if self._canvas.HasCapture(): self._canvas.ReleaseMouse() if not self._draggable: if self._parent: self._parent.GetEventHandler().OnEndDragLeft(x, y, keys, 0) return dc = wx.ClientDC(self.GetCanvas()) self.GetCanvas().PrepareDC(dc) dc.SetLogicalFunction(wx.COPY) self.Erase(dc) xx, yy = self._canvas.Snap(x, y) offsetX = xx - _objectStartX offsetY = yy - _objectStartY self.Move(dc, self.GetX() + offsetX, self.GetY() + offsetY) if self._canvas and not self._canvas.GetQuickEditMode(): self._canvas.Redraw(dc)
[ "def", "OnEndDragLeft", "(", "self", ",", "x", ",", "y", ",", "keys", "=", "0", ",", "attachment", "=", "0", ")", ":", "if", "self", ".", "_canvas", ".", "HasCapture", "(", ")", ":", "self", ".", "_canvas", ".", "ReleaseMouse", "(", ")", "if", "n...
https://github.com/wxWidgets/Phoenix/blob/b2199e299a6ca6d866aa6f3d0888499136ead9d6/wx/lib/ogl/composit.py#L501-L524
ChineseGLUE/ChineseGLUE
1591b85cf5427c2ff60f718d359ecb71d2b44879
baselines/models/ernie/run_squad.py
python
read_squad_examples
(input_file, is_training)
return examples
Read a SQuAD json file into a list of SquadExample.
Read a SQuAD json file into a list of SquadExample.
[ "Read", "a", "SQuAD", "json", "file", "into", "a", "list", "of", "SquadExample", "." ]
def read_squad_examples(input_file, is_training): """Read a SQuAD json file into a list of SquadExample.""" with tf.gfile.Open(input_file, "r") as reader: input_data = json.load(reader)["data"] def is_whitespace(c): if c == " " or c == "\t" or c == "\r" or c == "\n" or ord(c) == 0x202F: return True return False examples = [] for entry in input_data: for paragraph in entry["paragraphs"]: paragraph_text = paragraph["context"] doc_tokens = [] char_to_word_offset = [] prev_is_whitespace = True for c in paragraph_text: if is_whitespace(c): prev_is_whitespace = True else: if prev_is_whitespace: doc_tokens.append(c) else: doc_tokens[-1] += c prev_is_whitespace = False char_to_word_offset.append(len(doc_tokens) - 1) for qa in paragraph["qas"]: qas_id = qa["id"] question_text = qa["question"] start_position = None end_position = None orig_answer_text = None is_impossible = False if is_training: if FLAGS.version_2_with_negative: is_impossible = qa["is_impossible"] if (len(qa["answers"]) != 1) and (not is_impossible): raise ValueError( "For training, each question should have exactly 1 answer.") if not is_impossible: answer = qa["answers"][0] orig_answer_text = answer["text"] answer_offset = answer["answer_start"] answer_length = len(orig_answer_text) start_position = char_to_word_offset[answer_offset] end_position = char_to_word_offset[answer_offset + answer_length - 1] # Only add answers where the text can be exactly recovered from the # document. If this CAN'T happen it's likely due to weird Unicode # stuff so we will just skip the example. # # Note that this means for training mode, every example is NOT # guaranteed to be preserved. actual_text = " ".join( doc_tokens[start_position:(end_position + 1)]) cleaned_answer_text = " ".join( tokenization.whitespace_tokenize(orig_answer_text)) if actual_text.find(cleaned_answer_text) == -1: tf.logging.warning("Could not find answer: '%s' vs. '%s'", actual_text, cleaned_answer_text) continue else: start_position = -1 end_position = -1 orig_answer_text = "" example = SquadExample( qas_id=qas_id, question_text=question_text, doc_tokens=doc_tokens, orig_answer_text=orig_answer_text, start_position=start_position, end_position=end_position, is_impossible=is_impossible) examples.append(example) return examples
[ "def", "read_squad_examples", "(", "input_file", ",", "is_training", ")", ":", "with", "tf", ".", "gfile", ".", "Open", "(", "input_file", ",", "\"r\"", ")", "as", "reader", ":", "input_data", "=", "json", ".", "load", "(", "reader", ")", "[", "\"data\""...
https://github.com/ChineseGLUE/ChineseGLUE/blob/1591b85cf5427c2ff60f718d359ecb71d2b44879/baselines/models/ernie/run_squad.py#L227-L306
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_openshift/library/oc_adm_ca_server_cert.py
python
CAServerCert.__init__
(self, config, verbose=False)
Constructor for oadm ca
Constructor for oadm ca
[ "Constructor", "for", "oadm", "ca" ]
def __init__(self, config, verbose=False): ''' Constructor for oadm ca ''' super(CAServerCert, self).__init__(None, config.kubeconfig, verbose) self.config = config self.verbose = verbose
[ "def", "__init__", "(", "self", ",", "config", ",", "verbose", "=", "False", ")", ":", "super", "(", "CAServerCert", ",", "self", ")", ".", "__init__", "(", "None", ",", "config", ".", "kubeconfig", ",", "verbose", ")", "self", ".", "config", "=", "c...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_openshift/library/oc_adm_ca_server_cert.py#L1504-L1510
Bitmessage/PyBitmessage
97612b049e0453867d6d90aa628f8e7b007b4d85
src/bitmessageqt/messageview.py
python
MessageView.setContent
(self, data)
Set message content from argument
Set message content from argument
[ "Set", "message", "content", "from", "argument" ]
def setContent(self, data): """Set message content from argument""" self.html = SafeHTMLParser() self.html.reset() self.html.reset_safe() self.html.allow_picture = True self.html.feed(data) self.html.close() self.showPlain()
[ "def", "setContent", "(", "self", ",", "data", ")", ":", "self", ".", "html", "=", "SafeHTMLParser", "(", ")", "self", ".", "html", ".", "reset", "(", ")", "self", ".", "html", ".", "reset_safe", "(", ")", "self", ".", "html", ".", "allow_picture", ...
https://github.com/Bitmessage/PyBitmessage/blob/97612b049e0453867d6d90aa628f8e7b007b4d85/src/bitmessageqt/messageview.py#L155-L163
JetBrains/python-skeletons
95ad24b666e475998e5d1cc02ed53a2188036167
numpy/core/__init__.py
python
int8.__rand__
(self, *args, **kwargs)
Return value&self.
Return value&self.
[ "Return", "value&self", "." ]
def __rand__(self, *args, **kwargs): # real signature unknown """ Return value&self. """ pass
[ "def", "__rand__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# real signature unknown", "pass" ]
https://github.com/JetBrains/python-skeletons/blob/95ad24b666e475998e5d1cc02ed53a2188036167/numpy/core/__init__.py#L1221-L1223
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/twisted/twisted/conch/insults/insults.py
python
ITerminalTransport.shiftOut
()
Activate the G1 character set.
Activate the G1 character set.
[ "Activate", "the", "G1", "character", "set", "." ]
def shiftOut(): """Activate the G1 character set. """
[ "def", "shiftOut", "(", ")", ":" ]
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/twisted/twisted/conch/insults/insults.py#L165-L167
theotherp/nzbhydra
4b03d7f769384b97dfc60dade4806c0fc987514e
libs/requests/packages/urllib3/util/ssl_.py
python
assert_fingerprint
(cert, fingerprint)
Checks if given fingerprint matches the supplied certificate. :param cert: Certificate as bytes object. :param fingerprint: Fingerprint as string of hexdigits, can be interspersed by colons.
Checks if given fingerprint matches the supplied certificate.
[ "Checks", "if", "given", "fingerprint", "matches", "the", "supplied", "certificate", "." ]
def assert_fingerprint(cert, fingerprint): """ Checks if given fingerprint matches the supplied certificate. :param cert: Certificate as bytes object. :param fingerprint: Fingerprint as string of hexdigits, can be interspersed by colons. """ fingerprint = fingerprint.replace(':', '').lower() digest_length = len(fingerprint) hashfunc = HASHFUNC_MAP.get(digest_length) if not hashfunc: raise SSLError( 'Fingerprint of invalid length: {0}'.format(fingerprint)) # We need encode() here for py32; works on py2 and p33. fingerprint_bytes = unhexlify(fingerprint.encode()) cert_digest = hashfunc(cert).digest() if not _const_compare_digest(cert_digest, fingerprint_bytes): raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".' .format(fingerprint, hexlify(cert_digest)))
[ "def", "assert_fingerprint", "(", "cert", ",", "fingerprint", ")", ":", "fingerprint", "=", "fingerprint", ".", "replace", "(", "':'", ",", "''", ")", ".", "lower", "(", ")", "digest_length", "=", "len", "(", "fingerprint", ")", "hashfunc", "=", "HASHFUNC_...
https://github.com/theotherp/nzbhydra/blob/4b03d7f769384b97dfc60dade4806c0fc987514e/libs/requests/packages/urllib3/util/ssl_.py#L148-L172
smart-mobile-software/gitstack
d9fee8f414f202143eb6e620529e8e5539a2af56
python/Lib/site-packages/django/utils/safestring.py
python
mark_safe
(s)
return SafeString(str(s))
Explicitly mark a string as safe for (HTML) output purposes. The returned object can be used everywhere a string or unicode object is appropriate. Can be called multiple times on a single string.
Explicitly mark a string as safe for (HTML) output purposes. The returned object can be used everywhere a string or unicode object is appropriate.
[ "Explicitly", "mark", "a", "string", "as", "safe", "for", "(", "HTML", ")", "output", "purposes", ".", "The", "returned", "object", "can", "be", "used", "everywhere", "a", "string", "or", "unicode", "object", "is", "appropriate", "." ]
def mark_safe(s): """ Explicitly mark a string as safe for (HTML) output purposes. The returned object can be used everywhere a string or unicode object is appropriate. Can be called multiple times on a single string. """ if isinstance(s, SafeData): return s if isinstance(s, str) or (isinstance(s, Promise) and s._delegate_str): return SafeString(s) if isinstance(s, (unicode, Promise)): return SafeUnicode(s) return SafeString(str(s))
[ "def", "mark_safe", "(", "s", ")", ":", "if", "isinstance", "(", "s", ",", "SafeData", ")", ":", "return", "s", "if", "isinstance", "(", "s", ",", "str", ")", "or", "(", "isinstance", "(", "s", ",", "Promise", ")", "and", "s", ".", "_delegate_str",...
https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/site-packages/django/utils/safestring.py#L89-L102
ni/nidaqmx-python
62fc6b48cbbb330fe1bcc9aedadc86610a1269b6
nidaqmx/_task_modules/channels/ci_channel.py
python
CIChannel.ci_pulse_ticks_dig_fltr_timebase_rate
(self, val)
[]
def ci_pulse_ticks_dig_fltr_timebase_rate(self, val): cfunc = lib_importer.windll.DAQmxSetCIPulseTicksDigFltrTimebaseRate if cfunc.argtypes is None: with cfunc.arglock: if cfunc.argtypes is None: cfunc.argtypes = [ lib_importer.task_handle, ctypes_byte_str, ctypes.c_double] error_code = cfunc( self._handle, self._name, val) check_for_error(error_code)
[ "def", "ci_pulse_ticks_dig_fltr_timebase_rate", "(", "self", ",", "val", ")", ":", "cfunc", "=", "lib_importer", ".", "windll", ".", "DAQmxSetCIPulseTicksDigFltrTimebaseRate", "if", "cfunc", ".", "argtypes", "is", "None", ":", "with", "cfunc", ".", "arglock", ":",...
https://github.com/ni/nidaqmx-python/blob/62fc6b48cbbb330fe1bcc9aedadc86610a1269b6/nidaqmx/_task_modules/channels/ci_channel.py#L7529-L7540
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/auth/__init__.py
python
create_auth_code
(hass, client_id: str, credential: Credentials)
return hass.data[DOMAIN](client_id, credential)
Create an authorization code to fetch tokens.
Create an authorization code to fetch tokens.
[ "Create", "an", "authorization", "code", "to", "fetch", "tokens", "." ]
def create_auth_code(hass, client_id: str, credential: Credentials) -> str: """Create an authorization code to fetch tokens.""" return hass.data[DOMAIN](client_id, credential)
[ "def", "create_auth_code", "(", "hass", ",", "client_id", ":", "str", ",", "credential", ":", "Credentials", ")", "->", "str", ":", "return", "hass", ".", "data", "[", "DOMAIN", "]", "(", "client_id", ",", "credential", ")" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/auth/__init__.py#L185-L187
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/future/backports/urllib/request.py
python
URLopener.retrieve
(self, url, filename=None, reporthook=None, data=None)
return result
retrieve(url) returns (filename, headers) for a local object or (tempfilename, headers) for a remote object.
retrieve(url) returns (filename, headers) for a local object or (tempfilename, headers) for a remote object.
[ "retrieve", "(", "url", ")", "returns", "(", "filename", "headers", ")", "for", "a", "local", "object", "or", "(", "tempfilename", "headers", ")", "for", "a", "remote", "object", "." ]
def retrieve(self, url, filename=None, reporthook=None, data=None): """retrieve(url) returns (filename, headers) for a local object or (tempfilename, headers) for a remote object.""" url = unwrap(to_bytes(url)) if self.tempcache and url in self.tempcache: return self.tempcache[url] type, url1 = splittype(url) if filename is None and (not type or type == 'file'): try: fp = self.open_local_file(url1) hdrs = fp.info() fp.close() return url2pathname(splithost(url1)[1]), hdrs except IOError as msg: pass fp = self.open(url, data) try: headers = fp.info() if filename: tfp = open(filename, 'wb') else: import tempfile garbage, path = splittype(url) garbage, path = splithost(path or "") path, garbage = splitquery(path or "") path, garbage = splitattr(path or "") suffix = os.path.splitext(path)[1] (fd, filename) = tempfile.mkstemp(suffix) self.__tempfiles.append(filename) tfp = os.fdopen(fd, 'wb') try: result = filename, headers if self.tempcache is not None: self.tempcache[url] = result bs = 1024*8 size = -1 read = 0 blocknum = 0 if "content-length" in headers: size = int(headers["Content-Length"]) if reporthook: reporthook(blocknum, bs, size) while 1: block = fp.read(bs) if not block: break read += len(block) tfp.write(block) blocknum += 1 if reporthook: reporthook(blocknum, bs, size) finally: tfp.close() finally: fp.close() # raise exception if actual size does not match content-length header if size >= 0 and read < size: raise ContentTooShortError( "retrieval incomplete: got only %i out of %i bytes" % (read, size), result) return result
[ "def", "retrieve", "(", "self", ",", "url", ",", "filename", "=", "None", ",", "reporthook", "=", "None", ",", "data", "=", "None", ")", ":", "url", "=", "unwrap", "(", "to_bytes", "(", "url", ")", ")", "if", "self", ".", "tempcache", "and", "url",...
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/future/backports/urllib/request.py#L1722-L1784
amymcgovern/pyparrot
bf4775ec1199b282e4edde1e4a8e018dcc8725e0
pyparrot/utils/vlc.py
python
libvlc_set_app_id
(p_instance, id, version, icon)
return f(p_instance, id, version, icon)
Sets some meta-information about the application. See also L{libvlc_set_user_agent}(). @param p_instance: LibVLC instance. @param id: Java-style application identifier, e.g. "com.acme.foobar". @param version: application version numbers, e.g. "1.2.3". @param icon: application icon name, e.g. "foobar". @version: LibVLC 2.1.0 or later.
Sets some meta-information about the application. See also L{libvlc_set_user_agent}().
[ "Sets", "some", "meta", "-", "information", "about", "the", "application", ".", "See", "also", "L", "{", "libvlc_set_user_agent", "}", "()", "." ]
def libvlc_set_app_id(p_instance, id, version, icon): '''Sets some meta-information about the application. See also L{libvlc_set_user_agent}(). @param p_instance: LibVLC instance. @param id: Java-style application identifier, e.g. "com.acme.foobar". @param version: application version numbers, e.g. "1.2.3". @param icon: application icon name, e.g. "foobar". @version: LibVLC 2.1.0 or later. ''' f = _Cfunctions.get('libvlc_set_app_id', None) or \ _Cfunction('libvlc_set_app_id', ((1,), (1,), (1,), (1,),), None, None, Instance, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p) return f(p_instance, id, version, icon)
[ "def", "libvlc_set_app_id", "(", "p_instance", ",", "id", ",", "version", ",", "icon", ")", ":", "f", "=", "_Cfunctions", ".", "get", "(", "'libvlc_set_app_id'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_set_app_id'", ",", "(", "(", "1", ",", "...
https://github.com/amymcgovern/pyparrot/blob/bf4775ec1199b282e4edde1e4a8e018dcc8725e0/pyparrot/utils/vlc.py#L4453-L4465
makerbot/ReplicatorG
d6f2b07785a5a5f1e172fb87cb4303b17c575d5d
skein_engines/skeinforge-47/skeinforge_application/skeinforge_plugins/craft_plugins/oozebane.py
python
OozebaneSkein.getAddBeforeStartupLines
(self, line)
return self.getLinearMoveWithFeedRate( self.operatingFeedRateMinute, location )
Get and / or add before the startup lines.
Get and / or add before the startup lines.
[ "Get", "and", "/", "or", "add", "before", "the", "startup", "lines", "." ]
def getAddBeforeStartupLines(self, line): "Get and / or add before the startup lines." distanceThreadBeginning = self.getDistanceToThreadBeginning() if distanceThreadBeginning == None: return line splitLine = gcodec.getSplitLineBeforeBracketSemicolon(line) self.extruderInactiveLongEnough = False self.isStartupEarly = True location = gcodec.getLocationFromSplitLine(self.oldLocation, splitLine) segment = self.oldLocation - location segmentLength = segment.magnitude() distanceBack = self.earlyStartupDistance - distanceThreadBeginning if segmentLength <= 0.0: print('This should never happen, segmentLength is zero in getAddBeforeStartupLines in oozebane.') print(line) self.extruderInactiveLongEnough = True self.isStartupEarly = False return line locationBack = location + segment * distanceBack / segmentLength self.distanceFeedRate.addLine( self.getLinearMoveWithFeedRate( gcodec.getFeedRateMinute( self.feedRateMinute, splitLine ) , locationBack ) ) self.distanceFeedRate.addLine('M101') if self.isCloseToEither( locationBack, location, self.oldLocation ): return '' return self.getLinearMoveWithFeedRate( self.operatingFeedRateMinute, location )
[ "def", "getAddBeforeStartupLines", "(", "self", ",", "line", ")", ":", "distanceThreadBeginning", "=", "self", ".", "getDistanceToThreadBeginning", "(", ")", "if", "distanceThreadBeginning", "==", "None", ":", "return", "line", "splitLine", "=", "gcodec", ".", "ge...
https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-47/skeinforge_application/skeinforge_plugins/craft_plugins/oozebane.py#L202-L225
jrzaurin/pytorch-widedeep
8b4c3a8acbf06b385c821d7111b1139a16b4f480
pytorch_widedeep/models/tabnet/_utils.py
python
create_explain_matrix
(model: WideDeep)
return csc_matrix(reducing_matrix)
Returns a sparse matrix used to compute the feature importances after training Parameters ---------- model: WideDeep object of type ``WideDeep`` Examples -------- >>> from pytorch_widedeep.models import TabNet, WideDeep >>> from pytorch_widedeep.models.tabnet._utils import create_explain_matrix >>> embed_input = [("a", 4, 2), ("b", 4, 2), ("c", 4, 2)] >>> cont_cols = ["d", "e"] >>> column_idx = {k: v for v, k in enumerate(["a", "b", "c", "d", "e"])} >>> deeptabular = TabNet(column_idx=column_idx, embed_input=embed_input, continuous_cols=cont_cols) >>> model = WideDeep(deeptabular=deeptabular) >>> reduce_mtx = create_explain_matrix(model) >>> reduce_mtx.todense() matrix([[1., 0., 0., 0., 0.], [1., 0., 0., 0., 0.], [0., 1., 0., 0., 0.], [0., 1., 0., 0., 0.], [0., 0., 1., 0., 0.], [0., 0., 1., 0., 0.], [0., 0., 0., 1., 0.], [0., 0., 0., 0., 1.]])
Returns a sparse matrix used to compute the feature importances after training
[ "Returns", "a", "sparse", "matrix", "used", "to", "compute", "the", "feature", "importances", "after", "training" ]
def create_explain_matrix(model: WideDeep) -> csc_matrix: """ Returns a sparse matrix used to compute the feature importances after training Parameters ---------- model: WideDeep object of type ``WideDeep`` Examples -------- >>> from pytorch_widedeep.models import TabNet, WideDeep >>> from pytorch_widedeep.models.tabnet._utils import create_explain_matrix >>> embed_input = [("a", 4, 2), ("b", 4, 2), ("c", 4, 2)] >>> cont_cols = ["d", "e"] >>> column_idx = {k: v for v, k in enumerate(["a", "b", "c", "d", "e"])} >>> deeptabular = TabNet(column_idx=column_idx, embed_input=embed_input, continuous_cols=cont_cols) >>> model = WideDeep(deeptabular=deeptabular) >>> reduce_mtx = create_explain_matrix(model) >>> reduce_mtx.todense() matrix([[1., 0., 0., 0., 0.], [1., 0., 0., 0., 0.], [0., 1., 0., 0., 0.], [0., 1., 0., 0., 0.], [0., 0., 1., 0., 0.], [0., 0., 1., 0., 0.], [0., 0., 0., 1., 0.], [0., 0., 0., 0., 1.]]) """ ( embed_input, column_idx, embed_and_cont_dim, ) = _extract_tabnet_params(model) n_feat = len(column_idx) col_embeds = {e[0]: e[2] - 1 for e in embed_input} embed_colname = [e[0] for e in embed_input] cont_colname = [c for c in column_idx.keys() if c not in embed_colname] embed_cum_counter = 0 indices_trick = [] for colname, idx in column_idx.items(): if colname in cont_colname: indices_trick.append([idx + embed_cum_counter]) elif colname in embed_colname: indices_trick.append( range( # type: ignore[arg-type] idx + embed_cum_counter, idx + embed_cum_counter + col_embeds[colname] + 1, ) ) embed_cum_counter += col_embeds[colname] reducing_matrix = np.zeros((embed_and_cont_dim, n_feat)) for i, cols in enumerate(indices_trick): reducing_matrix[cols, i] = 1 return csc_matrix(reducing_matrix)
[ "def", "create_explain_matrix", "(", "model", ":", "WideDeep", ")", "->", "csc_matrix", ":", "(", "embed_input", ",", "column_idx", ",", "embed_and_cont_dim", ",", ")", "=", "_extract_tabnet_params", "(", "model", ")", "n_feat", "=", "len", "(", "column_idx", ...
https://github.com/jrzaurin/pytorch-widedeep/blob/8b4c3a8acbf06b385c821d7111b1139a16b4f480/pytorch_widedeep/models/tabnet/_utils.py#L7-L66
keiffster/program-y
8c99b56f8c32f01a7b9887b5daae9465619d0385
src/programy/services/rest/newsapi/newsapi.py
python
NewsAPI.hacker_news
(api_key, max_articles, sort, reverse)
return NewsAPI._get_data(NewsAPI.HACKER_NEWS, api_key, max_articles, sort, reverse)
[]
def hacker_news(api_key, max_articles, sort, reverse): return NewsAPI._get_data(NewsAPI.HACKER_NEWS, api_key, max_articles, sort, reverse)
[ "def", "hacker_news", "(", "api_key", ",", "max_articles", ",", "sort", ",", "reverse", ")", ":", "return", "NewsAPI", ".", "_get_data", "(", "NewsAPI", ".", "HACKER_NEWS", ",", "api_key", ",", "max_articles", ",", "sort", ",", "reverse", ")" ]
https://github.com/keiffster/program-y/blob/8c99b56f8c32f01a7b9887b5daae9465619d0385/src/programy/services/rest/newsapi/newsapi.py#L364-L365
ClusterLabs/pcs
1f225199e02c8d20456bb386f4c913c3ff21ac78
pcs/resource.py
python
_format_desc
(indentation, desc)
return output.rstrip()
Commandline options: no options
Commandline options: no options
[ "Commandline", "options", ":", "no", "options" ]
def _format_desc(indentation, desc): """ Commandline options: no options """ desc = " ".join(desc.split()) dummy_rows, columns = utils.getTerminalSize() columns = max(int(columns), 40) afterindent = columns - indentation if afterindent < 1: afterindent = columns output = "" first = True for line in textwrap.wrap(desc, afterindent): if not first: output += " " * indentation output += line output += "\n" first = False return output.rstrip()
[ "def", "_format_desc", "(", "indentation", ",", "desc", ")", ":", "desc", "=", "\" \"", ".", "join", "(", "desc", ".", "split", "(", ")", ")", "dummy_rows", ",", "columns", "=", "utils", ".", "getTerminalSize", "(", ")", "columns", "=", "max", "(", "...
https://github.com/ClusterLabs/pcs/blob/1f225199e02c8d20456bb386f4c913c3ff21ac78/pcs/resource.py#L544-L564
007gzs/dingtalk-sdk
7979da2e259fdbc571728cae2425a04dbc65850a
dingtalk/client/api/taobao.py
python
TbYingXiao.taobao_ump_tool_add
( self, content )
return self._top_request( "taobao.ump.tool.add", { "content": content }, result_processor=lambda x: x["tool_id"] )
新增优惠工具 新增优惠工具。通过ump sdk来完成将积木块拼装成为工具的操作,再使用本接口上传优惠工具。 文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=10713 :param content: 工具内容,由sdk里面的MarketingTool生成的json字符串
新增优惠工具 新增优惠工具。通过ump sdk来完成将积木块拼装成为工具的操作,再使用本接口上传优惠工具。 文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=10713
[ "新增优惠工具", "新增优惠工具。通过ump", "sdk来完成将积木块拼装成为工具的操作,再使用本接口上传优惠工具。", "文档地址:https", ":", "//", "open", "-", "doc", ".", "dingtalk", ".", "com", "/", "docs", "/", "api", ".", "htm?apiId", "=", "10713" ]
def taobao_ump_tool_add( self, content ): """ 新增优惠工具 新增优惠工具。通过ump sdk来完成将积木块拼装成为工具的操作,再使用本接口上传优惠工具。 文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=10713 :param content: 工具内容,由sdk里面的MarketingTool生成的json字符串 """ return self._top_request( "taobao.ump.tool.add", { "content": content }, result_processor=lambda x: x["tool_id"] )
[ "def", "taobao_ump_tool_add", "(", "self", ",", "content", ")", ":", "return", "self", ".", "_top_request", "(", "\"taobao.ump.tool.add\"", ",", "{", "\"content\"", ":", "content", "}", ",", "result_processor", "=", "lambda", "x", ":", "x", "[", "\"tool_id\"",...
https://github.com/007gzs/dingtalk-sdk/blob/7979da2e259fdbc571728cae2425a04dbc65850a/dingtalk/client/api/taobao.py#L25409-L25426
F8LEFT/DecLLVM
d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c
python/idaapi.py
python
is_type_ptr
(*args)
return _idaapi.is_type_ptr(*args)
is_type_ptr(t) -> bool
is_type_ptr(t) -> bool
[ "is_type_ptr", "(", "t", ")", "-", ">", "bool" ]
def is_type_ptr(*args): """ is_type_ptr(t) -> bool """ return _idaapi.is_type_ptr(*args)
[ "def", "is_type_ptr", "(", "*", "args", ")", ":", "return", "_idaapi", ".", "is_type_ptr", "(", "*", "args", ")" ]
https://github.com/F8LEFT/DecLLVM/blob/d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c/python/idaapi.py#L28310-L28314
pulp/pulp
a0a28d804f997b6f81c391378aff2e4c90183df9
server/pulp/plugins/profiler.py
python
Profiler.update_profile
(self, consumer, content_type, profile, config)
return profile
Notification that the consumer has reported the installed unit profile. The profiler has this opportunity to translate the reported profile. If a profile cannot be translated, the profiler should raise an appropriate exception. See: Profile Translation examples in class documentation. :param consumer: A consumer. :type consumer: pulp.plugins.model.Consumer :param content_type: The content type id that corresponds to the profile :type content_type: basestring :param profile: The reported profile. :type profile: list :param config: plugin configuration :type config: pulp.plugins.config.PluginCallConfiguration :return: The translated profile. :rtype: list
Notification that the consumer has reported the installed unit profile. The profiler has this opportunity to translate the reported profile. If a profile cannot be translated, the profiler should raise an appropriate exception. See: Profile Translation examples in class documentation.
[ "Notification", "that", "the", "consumer", "has", "reported", "the", "installed", "unit", "profile", ".", "The", "profiler", "has", "this", "opportunity", "to", "translate", "the", "reported", "profile", ".", "If", "a", "profile", "cannot", "be", "translated", ...
def update_profile(self, consumer, content_type, profile, config): """ Notification that the consumer has reported the installed unit profile. The profiler has this opportunity to translate the reported profile. If a profile cannot be translated, the profiler should raise an appropriate exception. See: Profile Translation examples in class documentation. :param consumer: A consumer. :type consumer: pulp.plugins.model.Consumer :param content_type: The content type id that corresponds to the profile :type content_type: basestring :param profile: The reported profile. :type profile: list :param config: plugin configuration :type config: pulp.plugins.config.PluginCallConfiguration :return: The translated profile. :rtype: list """ return profile
[ "def", "update_profile", "(", "self", ",", "consumer", ",", "content_type", ",", "profile", ",", "config", ")", ":", "return", "profile" ]
https://github.com/pulp/pulp/blob/a0a28d804f997b6f81c391378aff2e4c90183df9/server/pulp/plugins/profiler.py#L97-L116
JulianEberius/SublimePythonIDE
d70e40abc0c9f347af3204c7b910e0d6bfd6e459
server/lib/python_all/jedi/evaluate/docstrings.py
python
_execute_types_in_stmt
(evaluator, stmt)
return chain.from_iterable(_execute_array_values(evaluator, d) for d in definitions)
Executing all types or general elements that we find in a statement. This doesn't include tuple, list and dict literals, because the stuff they contain is executed. (Used as type information).
Executing all types or general elements that we find in a statement. This doesn't include tuple, list and dict literals, because the stuff they contain is executed. (Used as type information).
[ "Executing", "all", "types", "or", "general", "elements", "that", "we", "find", "in", "a", "statement", ".", "This", "doesn", "t", "include", "tuple", "list", "and", "dict", "literals", "because", "the", "stuff", "they", "contain", "is", "executed", ".", "...
def _execute_types_in_stmt(evaluator, stmt): """ Executing all types or general elements that we find in a statement. This doesn't include tuple, list and dict literals, because the stuff they contain is executed. (Used as type information). """ definitions = evaluator.eval_element(stmt) return chain.from_iterable(_execute_array_values(evaluator, d) for d in definitions)
[ "def", "_execute_types_in_stmt", "(", "evaluator", ",", "stmt", ")", ":", "definitions", "=", "evaluator", ".", "eval_element", "(", "stmt", ")", "return", "chain", ".", "from_iterable", "(", "_execute_array_values", "(", "evaluator", ",", "d", ")", "for", "d"...
https://github.com/JulianEberius/SublimePythonIDE/blob/d70e40abc0c9f347af3204c7b910e0d6bfd6e459/server/lib/python_all/jedi/evaluate/docstrings.py#L150-L157
aalto-speech/morfessor
5314d3ebc1bea60b2145e96e0efaf8b21211af71
morfessor/baseline.py
python
AnnotatedCorpusEncoding.set_count
(self, construction, count)
Set an initial count for each construction. Missing constructions are penalized
Set an initial count for each construction. Missing constructions are penalized
[ "Set", "an", "initial", "count", "for", "each", "construction", ".", "Missing", "constructions", "are", "penalized" ]
def set_count(self, construction, count): """Set an initial count for each construction. Missing constructions are penalized """ annot_count = self.constructions[construction] if count > 0: self.logtokensum += annot_count * math.log(count) else: self.logtokensum += annot_count * self.penalty
[ "def", "set_count", "(", "self", ",", "construction", ",", "count", ")", ":", "annot_count", "=", "self", ".", "constructions", "[", "construction", "]", "if", "count", ">", "0", ":", "self", ".", "logtokensum", "+=", "annot_count", "*", "math", ".", "lo...
https://github.com/aalto-speech/morfessor/blob/5314d3ebc1bea60b2145e96e0efaf8b21211af71/morfessor/baseline.py#L1308-L1316
openedx/edx-platform
68dd185a0ab45862a2a61e0f803d7e03d2be71b5
lms/djangoapps/lti_provider/signature_validator.py
python
SignatureValidator.check_nonce
(self, nonce)
return nonce is not None and 0 < len(nonce) <= 64
Verify that the nonce value that accompanies the OAuth signature is valid. This method is concerned only with the structure of the nonce; the validate_timestamp_and_nonce method will check that the nonce has not been used within the specified time frame. This method signature is required by the oauthlib library. :return: True if the OAuth nonce is valid, or False if it is not.
Verify that the nonce value that accompanies the OAuth signature is valid. This method is concerned only with the structure of the nonce; the validate_timestamp_and_nonce method will check that the nonce has not been used within the specified time frame. This method signature is required by the oauthlib library.
[ "Verify", "that", "the", "nonce", "value", "that", "accompanies", "the", "OAuth", "signature", "is", "valid", ".", "This", "method", "is", "concerned", "only", "with", "the", "structure", "of", "the", "nonce", ";", "the", "validate_timestamp_and_nonce", "method"...
def check_nonce(self, nonce): """ Verify that the nonce value that accompanies the OAuth signature is valid. This method is concerned only with the structure of the nonce; the validate_timestamp_and_nonce method will check that the nonce has not been used within the specified time frame. This method signature is required by the oauthlib library. :return: True if the OAuth nonce is valid, or False if it is not. """ return nonce is not None and 0 < len(nonce) <= 64
[ "def", "check_nonce", "(", "self", ",", "nonce", ")", ":", "return", "nonce", "is", "not", "None", "and", "0", "<", "len", "(", "nonce", ")", "<=", "64" ]
https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/lms/djangoapps/lti_provider/signature_validator.py#L45-L55
certtools/intelmq
7c1ab88b77bcbb30c7cabca5bb3525ad4aaac138
intelmq/lib/bot.py
python
Bot.__handle_sigterm_signal
(self, signum: int, stack: Optional[object])
Calls when a SIGTERM is received. Stops the bot.
Calls when a SIGTERM is received. Stops the bot.
[ "Calls", "when", "a", "SIGTERM", "is", "received", ".", "Stops", "the", "bot", "." ]
def __handle_sigterm_signal(self, signum: int, stack: Optional[object]): """ Calls when a SIGTERM is received. Stops the bot. """ self.logger.info("Received SIGTERM.") self.stop(exitcode=0)
[ "def", "__handle_sigterm_signal", "(", "self", ",", "signum", ":", "int", ",", "stack", ":", "Optional", "[", "object", "]", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Received SIGTERM.\"", ")", "self", ".", "stop", "(", "exitcode", "=", "0", ...
https://github.com/certtools/intelmq/blob/7c1ab88b77bcbb30c7cabca5bb3525ad4aaac138/intelmq/lib/bot.py#L255-L260
celery/celery
95015a1d5a60d94d8e1e02da4b9cf16416c747e2
celery/utils/timer2.py
python
Timer.__bool__
(self)
return True
``bool(timer)``.
``bool(timer)``.
[ "bool", "(", "timer", ")", "." ]
def __bool__(self): """``bool(timer)``.""" return True
[ "def", "__bool__", "(", "self", ")", ":", "return", "True" ]
https://github.com/celery/celery/blob/95015a1d5a60d94d8e1e02da4b9cf16416c747e2/celery/utils/timer2.py#L147-L149
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/full/traceback.py
python
FrameSummary.__init__
(self, filename, lineno, name, *, lookup_line=True, locals=None, line=None)
Construct a FrameSummary. :param lookup_line: If True, `linecache` is consulted for the source code line. Otherwise, the line will be looked up when first needed. :param locals: If supplied the frame locals, which will be captured as object representations. :param line: If provided, use this instead of looking up the line in the linecache.
Construct a FrameSummary.
[ "Construct", "a", "FrameSummary", "." ]
def __init__(self, filename, lineno, name, *, lookup_line=True, locals=None, line=None): """Construct a FrameSummary. :param lookup_line: If True, `linecache` is consulted for the source code line. Otherwise, the line will be looked up when first needed. :param locals: If supplied the frame locals, which will be captured as object representations. :param line: If provided, use this instead of looking up the line in the linecache. """ self.filename = filename self.lineno = lineno self.name = name self._line = line if lookup_line: self.line self.locals = {k: repr(v) for k, v in locals.items()} if locals else None
[ "def", "__init__", "(", "self", ",", "filename", ",", "lineno", ",", "name", ",", "*", ",", "lookup_line", "=", "True", ",", "locals", "=", "None", ",", "line", "=", "None", ")", ":", "self", ".", "filename", "=", "filename", "self", ".", "lineno", ...
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/traceback.py#L259-L276
SebKuzminsky/pycam
55e3129f518e470040e79bb00515b4bfcf36c172
pycam/Gui/ControlsGTK.py
python
ParameterSection._update_widgets_visibility
(self, widget=None)
[]
def _update_widgets_visibility(self, widget=None): # Hide and show labels (or other items) that share a row with a # configured item (according to its visibility). visibility_collector = [] for widget in self._widgets: table_row = self._get_table_row_of_widget(widget.widget) is_visible = widget.widget.props.visible visibility_collector.append(is_visible) for child in self._table.get_children(): if widget == child: continue if self._get_child_row(child) == table_row: if is_visible: child.show() else: child.hide() # hide the complete section if all items are hidden if any(visibility_collector): self._table.show() else: self._table.hide()
[ "def", "_update_widgets_visibility", "(", "self", ",", "widget", "=", "None", ")", ":", "# Hide and show labels (or other items) that share a row with a", "# configured item (according to its visibility).", "visibility_collector", "=", "[", "]", "for", "widget", "in", "self", ...
https://github.com/SebKuzminsky/pycam/blob/55e3129f518e470040e79bb00515b4bfcf36c172/pycam/Gui/ControlsGTK.py#L329-L349
googledatalab/pydatalab
1c86e26a0d24e3bc8097895ddeab4d0607be4c40
solutionbox/ml_workbench/tensorflow/transform.py
python
EmitAsBatchDoFn.process
(self, element)
[]
def process(self, element): self._cached.append(element) if len(self._cached) >= self._batch_size: emit = self._cached self._cached = [] yield emit
[ "def", "process", "(", "self", ",", "element", ")", ":", "self", ".", "_cached", ".", "append", "(", "element", ")", "if", "len", "(", "self", ".", "_cached", ")", ">=", "self", ".", "_batch_size", ":", "emit", "=", "self", ".", "_cached", "self", ...
https://github.com/googledatalab/pydatalab/blob/1c86e26a0d24e3bc8097895ddeab4d0607be4c40/solutionbox/ml_workbench/tensorflow/transform.py#L253-L258
beeware/ouroboros
a29123c6fab6a807caffbb7587cf548e0c370296
ouroboros/idlelib/AutoCompleteWindow.py
python
AutoCompleteWindow._complete_string
(self, s)
return first_comp[:i]
Assuming that s is the prefix of a string in self.completions, return the longest string which is a prefix of all the strings which s is a prefix of them. If s is not a prefix of a string, return s.
Assuming that s is the prefix of a string in self.completions, return the longest string which is a prefix of all the strings which s is a prefix of them. If s is not a prefix of a string, return s.
[ "Assuming", "that", "s", "is", "the", "prefix", "of", "a", "string", "in", "self", ".", "completions", "return", "the", "longest", "string", "which", "is", "a", "prefix", "of", "all", "the", "strings", "which", "s", "is", "a", "prefix", "of", "them", "...
def _complete_string(self, s): """Assuming that s is the prefix of a string in self.completions, return the longest string which is a prefix of all the strings which s is a prefix of them. If s is not a prefix of a string, return s.""" first = self._binary_search(s) if self.completions[first][:len(s)] != s: # There is not even one completion which s is a prefix of. return s # Find the end of the range of completions where s is a prefix of. i = first + 1 j = len(self.completions) while j > i: m = (i + j) // 2 if self.completions[m][:len(s)] != s: j = m else: i = m + 1 last = i-1 if first == last: # only one possible completion return self.completions[first] # We should return the maximum prefix of first and last first_comp = self.completions[first] last_comp = self.completions[last] min_len = min(len(first_comp), len(last_comp)) i = len(s) while i < min_len and first_comp[i] == last_comp[i]: i += 1 return first_comp[:i]
[ "def", "_complete_string", "(", "self", ",", "s", ")", ":", "first", "=", "self", ".", "_binary_search", "(", "s", ")", "if", "self", ".", "completions", "[", "first", "]", "[", ":", "len", "(", "s", ")", "]", "!=", "s", ":", "# There is not even one...
https://github.com/beeware/ouroboros/blob/a29123c6fab6a807caffbb7587cf548e0c370296/ouroboros/idlelib/AutoCompleteWindow.py#L82-L111
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/sqlalchemy/orm/session.py
python
_SessionClassMethods.close_all
(cls)
Close *all* sessions in memory.
Close *all* sessions in memory.
[ "Close", "*", "all", "*", "sessions", "in", "memory", "." ]
def close_all(cls): """Close *all* sessions in memory.""" for sess in _sessions.values(): sess.close()
[ "def", "close_all", "(", "cls", ")", ":", "for", "sess", "in", "_sessions", ".", "values", "(", ")", ":", "sess", ".", "close", "(", ")" ]
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/sqlalchemy/orm/session.py#L52-L56
dragonbook/V2V-PoseNet-pytorch
90045b61c45f18dc20b410e2de14bd22be55fe0e
src/v2v_util.py
python
discretize
(coord, cropped_size)
return (coord - min_normalized) / scale
[-1, 1] -> [0, cropped_size]
[-1, 1] -> [0, cropped_size]
[ "[", "-", "1", "1", "]", "-", ">", "[", "0", "cropped_size", "]" ]
def discretize(coord, cropped_size): '''[-1, 1] -> [0, cropped_size]''' min_normalized = -1 max_normalized = 1 scale = (max_normalized - min_normalized) / cropped_size return (coord - min_normalized) / scale
[ "def", "discretize", "(", "coord", ",", "cropped_size", ")", ":", "min_normalized", "=", "-", "1", "max_normalized", "=", "1", "scale", "=", "(", "max_normalized", "-", "min_normalized", ")", "/", "cropped_size", "return", "(", "coord", "-", "min_normalized", ...
https://github.com/dragonbook/V2V-PoseNet-pytorch/blob/90045b61c45f18dc20b410e2de14bd22be55fe0e/src/v2v_util.py#L5-L10
chromium/web-page-replay
472351e1122bb1beb936952c7e75ae58bf8a69f1
adb_install_cert.py
python
AndroidCertInstaller._remove
(file_name)
Deletes file.
Deletes file.
[ "Deletes", "file", "." ]
def _remove(file_name): """Deletes file.""" if os.path.exists(file_name): os.remove(file_name)
[ "def", "_remove", "(", "file_name", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "file_name", ")", ":", "os", ".", "remove", "(", "file_name", ")" ]
https://github.com/chromium/web-page-replay/blob/472351e1122bb1beb936952c7e75ae58bf8a69f1/adb_install_cert.py#L129-L132
pvlib/pvlib-python
1ab0eb20f9cd9fb9f7a0ddf35f81283f2648e34a
pvlib/pvsystem.py
python
PVSystem.i_from_v
(self, resistance_shunt, resistance_series, nNsVth, voltage, saturation_current, photocurrent)
return i_from_v(resistance_shunt, resistance_series, nNsVth, voltage, saturation_current, photocurrent)
Wrapper around the :py:func:`pvlib.pvsystem.i_from_v` function. See :py:func:`pvsystem.i_from_v` for details
Wrapper around the :py:func:`pvlib.pvsystem.i_from_v` function.
[ "Wrapper", "around", "the", ":", "py", ":", "func", ":", "pvlib", ".", "pvsystem", ".", "i_from_v", "function", "." ]
def i_from_v(self, resistance_shunt, resistance_series, nNsVth, voltage, saturation_current, photocurrent): """Wrapper around the :py:func:`pvlib.pvsystem.i_from_v` function. See :py:func:`pvsystem.i_from_v` for details """ return i_from_v(resistance_shunt, resistance_series, nNsVth, voltage, saturation_current, photocurrent)
[ "def", "i_from_v", "(", "self", ",", "resistance_shunt", ",", "resistance_series", ",", "nNsVth", ",", "voltage", ",", "saturation_current", ",", "photocurrent", ")", ":", "return", "i_from_v", "(", "resistance_shunt", ",", "resistance_series", ",", "nNsVth", ",",...
https://github.com/pvlib/pvlib-python/blob/1ab0eb20f9cd9fb9f7a0ddf35f81283f2648e34a/pvlib/pvsystem.py#L935-L942
project-alice-assistant/ProjectAlice
9e0ba019643bdae0a5535c9fa4180739231dc361
core/base/SkillManager.py
python
SkillManager.downloadSkills
(self, skills: Union[str, List[str]])
return repositories
Clones skills. Existence of the skill online is checked :param skills: :return: Dict: a dict of created repositories
Clones skills. Existence of the skill online is checked :param skills: :return: Dict: a dict of created repositories
[ "Clones", "skills", ".", "Existence", "of", "the", "skill", "online", "is", "checked", ":", "param", "skills", ":", ":", "return", ":", "Dict", ":", "a", "dict", "of", "created", "repositories" ]
def downloadSkills(self, skills: Union[str, List[str]]) -> Optional[Dict]: """ Clones skills. Existence of the skill online is checked :param skills: :return: Dict: a dict of created repositories """ if isinstance(skills, str): skills = [skills] repositories = dict() for skillName in skills: try: tag = self.SkillStoreManager.getSkillUpdateTag(skillName=skillName) response = requests.get(f'{constants.GITHUB_RAW_URL}/skill_{skillName}/{tag}/{skillName}.install') if response.status_code != 200: raise GithubNotFound self.logInfo(f'Now downloading **{skillName}** version **{tag}**') with suppress(): # Increment download counter requests.get(f'https://skills.projectalice.ch/{skillName}') installFile = response.json() if not self.ConfigManager.getAliceConfigByName('devMode'): self.checkSkillConditions(installer=installFile) source = self.getGitRemoteSourceUrl(skillName=skillName, doAuth=False) try: repository = self.getSkillRepository(skillName=skillName) except PathNotFoundException: repository = Repository.clone(url=source, directory=self.getSkillDirectory(skillName=skillName), makeDir=True) except NotGitRepository: shutil.rmtree(self.getSkillDirectory(skillName=skillName), ignore_errors=True) repository = Repository.clone(url=source, directory=self.getSkillDirectory(skillName=skillName), makeDir=True) except: raise repository.checkout(tag=tag) repositories[skillName] = repository except GithubNotFound: if skillName in self.NEEDED_SKILLS: self._busyInstalling.clear() self.logFatal(f"Skill **{skillName}** is required but wasn't found in released skills, cannot continue") return repositories else: self.logError(f'Skill "{skillName}" not found in released skills') continue except SkillNotConditionCompliant as e: if self.notCompliantSkill(skillName=skillName, exception=e): continue else: self._busyInstalling.clear() return repositories except Exception as e: if skillName in self.NEEDED_SKILLS: self._busyInstalling.clear() self.logFatal(f'Error downloading skill **{skillName}** and it is required, cannot continue: {e}') return repositories else: self.logError(f'Error downloading skill "{skillName}": {e}') continue return repositories
[ "def", "downloadSkills", "(", "self", ",", "skills", ":", "Union", "[", "str", ",", "List", "[", "str", "]", "]", ")", "->", "Optional", "[", "Dict", "]", ":", "if", "isinstance", "(", "skills", ",", "str", ")", ":", "skills", "=", "[", "skills", ...
https://github.com/project-alice-assistant/ProjectAlice/blob/9e0ba019643bdae0a5535c9fa4180739231dc361/core/base/SkillManager.py#L410-L474
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
ansible/roles/lib_oa_openshift/library/oc_adm_registry.py
python
Service.find_external_ips
(self, inc_external_ip)
return val
find a specific external IP
find a specific external IP
[ "find", "a", "specific", "external", "IP" ]
def find_external_ips(self, inc_external_ip): ''' find a specific external IP ''' val = None try: idx = self.get_external_ips().index(inc_external_ip) val = self.get_external_ips()[idx] except ValueError: pass return val
[ "def", "find_external_ips", "(", "self", ",", "inc_external_ip", ")", ":", "val", "=", "None", "try", ":", "idx", "=", "self", ".", "get_external_ips", "(", ")", ".", "index", "(", "inc_external_ip", ")", "val", "=", "self", ".", "get_external_ips", "(", ...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/ansible/roles/lib_oa_openshift/library/oc_adm_registry.py#L2207-L2216
DongjunLee/transformer-tensorflow
b6585fa7504f0f35327f2a3994dac7b06b6036f7
data_loader.py
python
IteratorInitializerHook.__init__
(self)
[]
def __init__(self): super(IteratorInitializerHook, self).__init__() self.iterator_initializer_func = None
[ "def", "__init__", "(", "self", ")", ":", "super", "(", "IteratorInitializerHook", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "iterator_initializer_func", "=", "None" ]
https://github.com/DongjunLee/transformer-tensorflow/blob/b6585fa7504f0f35327f2a3994dac7b06b6036f7/data_loader.py#L24-L26
deepgully/me
f7ad65edc2fe435310c6676bc2e322cfe5d4c8f0
libs/mako/codegen.py
python
_GenerateRenderMethod.write_def_decl
(self, node, identifiers)
write a locally-available callable referencing a top-level def
write a locally-available callable referencing a top-level def
[ "write", "a", "locally", "-", "available", "callable", "referencing", "a", "top", "-", "level", "def" ]
def write_def_decl(self, node, identifiers): """write a locally-available callable referencing a top-level def""" funcname = node.funcname namedecls = node.get_argument_expressions() nameargs = node.get_argument_expressions(include_defaults=False) if not self.in_def and ( len(self.identifiers.locally_assigned) > 0 or len(self.identifiers.argument_declared) > 0): nameargs.insert(0, 'context.locals_(__M_locals)') else: nameargs.insert(0, 'context') self.printer.writeline("def %s(%s):" % (funcname, ",".join(namedecls))) self.printer.writeline( "return render_%s(%s)" % (funcname, ",".join(nameargs))) self.printer.writeline(None)
[ "def", "write_def_decl", "(", "self", ",", "node", ",", "identifiers", ")", ":", "funcname", "=", "node", ".", "funcname", "namedecls", "=", "node", ".", "get_argument_expressions", "(", ")", "nameargs", "=", "node", ".", "get_argument_expressions", "(", "incl...
https://github.com/deepgully/me/blob/f7ad65edc2fe435310c6676bc2e322cfe5d4c8f0/libs/mako/codegen.py#L535-L550
floooh/fips
5ce5aebfc7c69778cab03ef5f8830928f2bad6d4
mod/tools/cmake.py
python
run_gen
(cfg, fips_dir, project_dir, build_dir, toolchain_path, defines)
return res == 0
run cmake tool to generate build files :param cfg: a fips config object :param project_dir: absolute path to project (must have root CMakeLists.txt file) :param build_dir: absolute path to build directory (where cmake files are generated) :param toolchain: toolchain path or None :returns: True if cmake returned successful
run cmake tool to generate build files
[ "run", "cmake", "tool", "to", "generate", "build", "files" ]
def run_gen(cfg, fips_dir, project_dir, build_dir, toolchain_path, defines) : """run cmake tool to generate build files :param cfg: a fips config object :param project_dir: absolute path to project (must have root CMakeLists.txt file) :param build_dir: absolute path to build directory (where cmake files are generated) :param toolchain: toolchain path or None :returns: True if cmake returned successful """ cmdLine = 'cmake' if cfg['generator'] != 'Default' : cmdLine += ' -G "{}"'.format(cfg['generator']) if cfg['generator-platform'] : cmdLine += ' -A "{}"'.format(cfg['generator-platform']) if cfg['generator-toolset'] : cmdLine += ' -T "{}"'.format(cfg['generator-toolset']) cmdLine += ' -DCMAKE_BUILD_TYPE={}'.format(cfg['build_type']) if toolchain_path is not None : cmdLine += ' -DCMAKE_TOOLCHAIN_FILE={}'.format(toolchain_path) cmdLine += ' -DFIPS_CONFIG={}'.format(cfg['name']) if cfg['defines'] is not None : for key in cfg['defines'] : val = cfg['defines'][key] if type(val) is bool : cmdLine += ' -D{}={}'.format(key, 'ON' if val else 'OFF') else : cmdLine += ' -D{}="{}"'.format(key, val) for key in defines : cmdLine += ' -D{}={}'.format(key, defines[key]) cmdLine += ' -B' + build_dir cmdLine += ' -H' + project_dir print(cmdLine) res = subprocess.call(cmdLine, cwd=build_dir, shell=True) return res == 0
[ "def", "run_gen", "(", "cfg", ",", "fips_dir", ",", "project_dir", ",", "build_dir", ",", "toolchain_path", ",", "defines", ")", ":", "cmdLine", "=", "'cmake'", "if", "cfg", "[", "'generator'", "]", "!=", "'Default'", ":", "cmdLine", "+=", "' -G \"{}\"'", ...
https://github.com/floooh/fips/blob/5ce5aebfc7c69778cab03ef5f8830928f2bad6d4/mod/tools/cmake.py#L33-L67
caiiiac/Machine-Learning-with-Python
1a26c4467da41ca4ebc3d5bd789ea942ef79422f
MachineLearning/venv/lib/python3.5/site-packages/pip/_vendor/requests/utils.py
python
guess_json_utf
(data)
return None
:rtype: str
:rtype: str
[ ":", "rtype", ":", "str" ]
def guess_json_utf(data): """ :rtype: str """ # JSON always starts with two ASCII characters, so detection is as # easy as counting the nulls and from their location and count # determine the encoding. Also detect a BOM, if present. sample = data[:4] if sample in (codecs.BOM_UTF32_LE, codecs.BOM32_BE): return 'utf-32' # BOM included if sample[:3] == codecs.BOM_UTF8: return 'utf-8-sig' # BOM included, MS style (discouraged) if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE): return 'utf-16' # BOM included nullcount = sample.count(_null) if nullcount == 0: return 'utf-8' if nullcount == 2: if sample[::2] == _null2: # 1st and 3rd are null return 'utf-16-be' if sample[1::2] == _null2: # 2nd and 4th are null return 'utf-16-le' # Did not detect 2 valid UTF-16 ascii-range characters if nullcount == 3: if sample[:3] == _null3: return 'utf-32-be' if sample[1:] == _null3: return 'utf-32-le' # Did not detect a valid UTF-32 ascii-range character return None
[ "def", "guess_json_utf", "(", "data", ")", ":", "# JSON always starts with two ASCII characters, so detection is as", "# easy as counting the nulls and from their location and count", "# determine the encoding. Also detect a BOM, if present.", "sample", "=", "data", "[", ":", "4", "]",...
https://github.com/caiiiac/Machine-Learning-with-Python/blob/1a26c4467da41ca4ebc3d5bd789ea942ef79422f/MachineLearning/venv/lib/python3.5/site-packages/pip/_vendor/requests/utils.py#L697-L726
karmab/kcli
fff2a2632841f54d9346b437821585df0ec659d7
kvirt/krpc/kcli_pb2_grpc.py
python
KconfigServicer.delete_plan
(self, request, context)
Missing associated documentation comment in .proto file
Missing associated documentation comment in .proto file
[ "Missing", "associated", "documentation", "comment", "in", ".", "proto", "file" ]
def delete_plan(self, request, context): """Missing associated documentation comment in .proto file""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!')
[ "def", "delete_plan", "(", "self", ",", "request", ",", "context", ")", ":", "context", ".", "set_code", "(", "grpc", ".", "StatusCode", ".", "UNIMPLEMENTED", ")", "context", ".", "set_details", "(", "'Method not implemented!'", ")", "raise", "NotImplementedErro...
https://github.com/karmab/kcli/blob/fff2a2632841f54d9346b437821585df0ec659d7/kvirt/krpc/kcli_pb2_grpc.py#L978-L982
pavlov99/json-rpc
00b24a9e811d9ca89ec3b1570195c881687bbef4
jsonrpc/dispatcher.py
python
Dispatcher.add_method
(self, f=None, name=None)
return f
Add a method to the dispatcher. Parameters ---------- f : callable Callable to be added. name : str, optional Name to register (the default is function **f** name) Notes ----- When used as a decorator keeps callable object unmodified. Examples -------- Use as method >>> d = Dispatcher() >>> d.add_method(lambda a, b: a + b, name="sum") <function __main__.<lambda>> Or use as decorator >>> d = Dispatcher() >>> @d.add_method def mymethod(*args, **kwargs): print(args, kwargs) Or use as a decorator with a different function name >>> d = Dispatcher() >>> @d.add_method(name="my.method") def mymethod(*args, **kwargs): print(args, kwargs)
Add a method to the dispatcher.
[ "Add", "a", "method", "to", "the", "dispatcher", "." ]
def add_method(self, f=None, name=None): """ Add a method to the dispatcher. Parameters ---------- f : callable Callable to be added. name : str, optional Name to register (the default is function **f** name) Notes ----- When used as a decorator keeps callable object unmodified. Examples -------- Use as method >>> d = Dispatcher() >>> d.add_method(lambda a, b: a + b, name="sum") <function __main__.<lambda>> Or use as decorator >>> d = Dispatcher() >>> @d.add_method def mymethod(*args, **kwargs): print(args, kwargs) Or use as a decorator with a different function name >>> d = Dispatcher() >>> @d.add_method(name="my.method") def mymethod(*args, **kwargs): print(args, kwargs) """ if name and not f: return functools.partial(self.add_method, name=name) self.method_map[name or f.__name__] = f return f
[ "def", "add_method", "(", "self", ",", "f", "=", "None", ",", "name", "=", "None", ")", ":", "if", "name", "and", "not", "f", ":", "return", "functools", ".", "partial", "(", "self", ".", "add_method", ",", "name", "=", "name", ")", "self", ".", ...
https://github.com/pavlov99/json-rpc/blob/00b24a9e811d9ca89ec3b1570195c881687bbef4/jsonrpc/dispatcher.py#L70-L111
rasterio/rasterio
a66f8731d30399ff6a6a640510139550792d4d2b
rasterio/env.py
python
Env.default_options
(cls)
return { 'GTIFF_IMPLICIT_JPEG_OVR': False, "RASTERIO_ENV": True }
Default configuration options Parameters ---------- None Returns ------- dict
Default configuration options
[ "Default", "configuration", "options" ]
def default_options(cls): """Default configuration options Parameters ---------- None Returns ------- dict """ return { 'GTIFF_IMPLICIT_JPEG_OVR': False, "RASTERIO_ENV": True }
[ "def", "default_options", "(", "cls", ")", ":", "return", "{", "'GTIFF_IMPLICIT_JPEG_OVR'", ":", "False", ",", "\"RASTERIO_ENV\"", ":", "True", "}" ]
https://github.com/rasterio/rasterio/blob/a66f8731d30399ff6a6a640510139550792d4d2b/rasterio/env.py#L95-L109
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/settings/views.py
python
ApiKeyView.column_names
(self)
return [ _("Name"), _("API Key"), _("Project"), _("IP Allowlist"), _("Created"), _("Delete"), ]
[]
def column_names(self): return [ _("Name"), _("API Key"), _("Project"), _("IP Allowlist"), _("Created"), _("Delete"), ]
[ "def", "column_names", "(", "self", ")", ":", "return", "[", "_", "(", "\"Name\"", ")", ",", "_", "(", "\"API Key\"", ")", ",", "_", "(", "\"Project\"", ")", ",", "_", "(", "\"IP Allowlist\"", ")", ",", "_", "(", "\"Created\"", ")", ",", "_", "(", ...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/settings/views.py#L619-L627
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
src/oci/osp_gateway/invoice_service_client.py
python
InvoiceServiceClient.get_invoice
(self, osp_home_region, compartment_id, internal_invoice_id, **kwargs)
Returns an invoice by invoice id :param str osp_home_region: (required) The home region's public name of the logged in user. :param str compartment_id: (required) The `OCID`__ of the compartment. __ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm :param str internal_invoice_id: (required) The identifier of the invoice. :param str opc_request_id: (optional) The unique Oracle-assigned identifier for the request. If you need to contact Oracle about a particular request, please provide the request ID. :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type :class:`~oci.osp_gateway.models.Invoice` :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/ospgateway/get_invoice.py.html>`__ to see an example of how to use get_invoice API.
Returns an invoice by invoice id
[ "Returns", "an", "invoice", "by", "invoice", "id" ]
def get_invoice(self, osp_home_region, compartment_id, internal_invoice_id, **kwargs): """ Returns an invoice by invoice id :param str osp_home_region: (required) The home region's public name of the logged in user. :param str compartment_id: (required) The `OCID`__ of the compartment. __ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm :param str internal_invoice_id: (required) The identifier of the invoice. :param str opc_request_id: (optional) The unique Oracle-assigned identifier for the request. If you need to contact Oracle about a particular request, please provide the request ID. :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type :class:`~oci.osp_gateway.models.Invoice` :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/ospgateway/get_invoice.py.html>`__ to see an example of how to use get_invoice API. """ resource_path = "/invoices/{internalInvoiceId}" method = "GET" # Don't accept unknown kwargs expected_kwargs = [ "retry_strategy", "opc_request_id" ] extra_kwargs = [_key for _key in six.iterkeys(kwargs) if _key not in expected_kwargs] if extra_kwargs: raise ValueError( "get_invoice got unknown kwargs: {!r}".format(extra_kwargs)) path_params = { "internalInvoiceId": internal_invoice_id } path_params = {k: v for (k, v) in six.iteritems(path_params) if v is not missing} for (k, v) in six.iteritems(path_params): if v is None or (isinstance(v, six.string_types) and len(v.strip()) == 0): raise ValueError('Parameter {} cannot be None, whitespace or empty string'.format(k)) query_params = { "ospHomeRegion": osp_home_region, "compartmentId": compartment_id } query_params = {k: v for (k, v) in six.iteritems(query_params) if v is not missing and v is not None} header_params = { "accept": "application/json", "content-type": "application/json", "opc-request-id": kwargs.get("opc_request_id", missing) } header_params = {k: v for (k, v) in six.iteritems(header_params) if v is not missing and v is not None} retry_strategy = self.base_client.get_preferred_retry_strategy( operation_retry_strategy=kwargs.get('retry_strategy'), client_retry_strategy=self.retry_strategy ) if retry_strategy: if not isinstance(retry_strategy, retry.NoneRetryStrategy): self.base_client.add_opc_client_retries_header(header_params) retry_strategy.add_circuit_breaker_callback(self.circuit_breaker_callback) return retry_strategy.make_retrying_call( self.base_client.call_api, resource_path=resource_path, method=method, path_params=path_params, query_params=query_params, header_params=header_params, response_type="Invoice") else: return self.base_client.call_api( resource_path=resource_path, method=method, path_params=path_params, query_params=query_params, header_params=header_params, response_type="Invoice")
[ "def", "get_invoice", "(", "self", ",", "osp_home_region", ",", "compartment_id", ",", "internal_invoice_id", ",", "*", "*", "kwargs", ")", ":", "resource_path", "=", "\"/invoices/{internalInvoiceId}\"", "method", "=", "\"GET\"", "# Don't accept unknown kwargs", "expect...
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/osp_gateway/invoice_service_client.py#L197-L291
menpo/menpo
a61500656c4fc2eea82497684f13cc31a605550b
menpo/shape/graph.py
python
Graph.vertices
(self)
return range(self.adjacency_matrix.shape[0])
r""" Returns the `list` of vertices. :type: `list`
r""" Returns the `list` of vertices.
[ "r", "Returns", "the", "list", "of", "vertices", "." ]
def vertices(self): r""" Returns the `list` of vertices. :type: `list` """ return range(self.adjacency_matrix.shape[0])
[ "def", "vertices", "(", "self", ")", ":", "return", "range", "(", "self", ".", "adjacency_matrix", ".", "shape", "[", "0", "]", ")" ]
https://github.com/menpo/menpo/blob/a61500656c4fc2eea82497684f13cc31a605550b/menpo/shape/graph.py#L262-L268
jkehler/awslambda-psycopg2
c7b1b2f6382bbe5893d95c4e7f4b5ffdf05ab3b4
with_ssl_support/psycopg2-3.7/pool.py
python
AbstractConnectionPool._putconn
(self, conn, key=None, close=False)
Put away a connection.
Put away a connection.
[ "Put", "away", "a", "connection", "." ]
def _putconn(self, conn, key=None, close=False): """Put away a connection.""" if self.closed: raise PoolError("connection pool is closed") if key is None: key = self._rused.get(id(conn)) if key is None: raise PoolError("trying to put unkeyed connection") if len(self._pool) < self.minconn and not close: # Return the connection into a consistent state before putting # it back into the pool if not conn.closed: status = conn.info.transaction_status if status == _ext.TRANSACTION_STATUS_UNKNOWN: # server connection lost conn.close() elif status != _ext.TRANSACTION_STATUS_IDLE: # connection in error or in transaction conn.rollback() self._pool.append(conn) else: # regular idle connection self._pool.append(conn) # If the connection is closed, we just discard it. else: conn.close() # here we check for the presence of key because it can happen that a # thread tries to put back a connection after a call to close if not self.closed or key in self._used: del self._used[key] del self._rused[id(conn)]
[ "def", "_putconn", "(", "self", ",", "conn", ",", "key", "=", "None", ",", "close", "=", "False", ")", ":", "if", "self", ".", "closed", ":", "raise", "PoolError", "(", "\"connection pool is closed\"", ")", "if", "key", "is", "None", ":", "key", "=", ...
https://github.com/jkehler/awslambda-psycopg2/blob/c7b1b2f6382bbe5893d95c4e7f4b5ffdf05ab3b4/with_ssl_support/psycopg2-3.7/pool.py#L94-L127
nitishsrivastava/deepnet
f4e4ff207923e01552c96038a1e2c29eb5d16160
cudamat/cudamat.py
python
CUDAMatrix.apply_softmax_grad
(self, labels, target = None)
return target
Apply softmax derivative, where labels are the correct labels.
Apply softmax derivative, where labels are the correct labels.
[ "Apply", "softmax", "derivative", "where", "labels", "are", "the", "correct", "labels", "." ]
def apply_softmax_grad(self, labels, target = None): """ Apply softmax derivative, where labels are the correct labels. """ if not target: target = self assert labels.shape == (1, self.shape[1]) assert target.shape == self.shape if isinstance(labels, CUDAMatrix): err_code = _cudamat.apply_softmax_grad(self.p_mat, labels.p_mat, target.p_mat) else: raise ValueError, "labels must be of type CUDAMatrix." if err_code: raise generate_exception(err_code) return target
[ "def", "apply_softmax_grad", "(", "self", ",", "labels", ",", "target", "=", "None", ")", ":", "if", "not", "target", ":", "target", "=", "self", "assert", "labels", ".", "shape", "==", "(", "1", ",", "self", ".", "shape", "[", "1", "]", ")", "asse...
https://github.com/nitishsrivastava/deepnet/blob/f4e4ff207923e01552c96038a1e2c29eb5d16160/cudamat/cudamat.py#L1319-L1336
cloudkick/libcloud
9c8605e1518c6b5e2511f0780e1946089a7256dd
libcloud/compute/drivers/dummy.py
python
DummyNodeDriver.list_nodes
(self)
return self.nl
List the nodes known to a particular driver; There are two default nodes created at the beginning >>> from libcloud.compute.drivers.dummy import DummyNodeDriver >>> driver = DummyNodeDriver(0) >>> node_list=driver.list_nodes() >>> sorted([node.name for node in node_list ]) ['dummy-1', 'dummy-2'] each item in the list returned is a node object from which you can carry out any node actions you wish >>> node_list[0].reboot() True As more nodes are added, list_nodes will return them >>> node=driver.create_node() >>> sorted([node.name for node in driver.list_nodes()]) ['dummy-1', 'dummy-2', 'dummy-3']
List the nodes known to a particular driver; There are two default nodes created at the beginning
[ "List", "the", "nodes", "known", "to", "a", "particular", "driver", ";", "There", "are", "two", "default", "nodes", "created", "at", "the", "beginning" ]
def list_nodes(self): """ List the nodes known to a particular driver; There are two default nodes created at the beginning >>> from libcloud.compute.drivers.dummy import DummyNodeDriver >>> driver = DummyNodeDriver(0) >>> node_list=driver.list_nodes() >>> sorted([node.name for node in node_list ]) ['dummy-1', 'dummy-2'] each item in the list returned is a node object from which you can carry out any node actions you wish >>> node_list[0].reboot() True As more nodes are added, list_nodes will return them >>> node=driver.create_node() >>> sorted([node.name for node in driver.list_nodes()]) ['dummy-1', 'dummy-2', 'dummy-3'] """ return self.nl
[ "def", "list_nodes", "(", "self", ")", ":", "return", "self", ".", "nl" ]
https://github.com/cloudkick/libcloud/blob/9c8605e1518c6b5e2511f0780e1946089a7256dd/libcloud/compute/drivers/dummy.py#L108-L131
TurboWay/spiderman
168f18552e0abb06187388b542d6a0df057ba852
download.py
python
DownLoad.delete
(self)
return self.redisctrl.keys_del([self.redis_key])
:return: 删除 redis key
:return: 删除 redis key
[ ":", "return", ":", "删除", "redis", "key" ]
def delete(self): """ :return: 删除 redis key """ return self.redisctrl.keys_del([self.redis_key])
[ "def", "delete", "(", "self", ")", ":", "return", "self", ".", "redisctrl", ".", "keys_del", "(", "[", "self", ".", "redis_key", "]", ")" ]
https://github.com/TurboWay/spiderman/blob/168f18552e0abb06187388b542d6a0df057ba852/download.py#L67-L71
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/encodings/cp1026.py
python
Codec.decode
(self,input,errors='strict')
return codecs.charmap_decode(input,errors,decoding_table)
[]
def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_table)
[ "def", "decode", "(", "self", ",", "input", ",", "errors", "=", "'strict'", ")", ":", "return", "codecs", ".", "charmap_decode", "(", "input", ",", "errors", ",", "decoding_table", ")" ]
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/encodings/cp1026.py#L14-L15
cirla/tulipy
5f3049a47574f97e28fb78e9cf3787ed610941f9
tulipy/__init__.py
python
atr
(high, low, close, period)
return lib.atr([high, low, close], [period])
Average True Range
Average True Range
[ "Average", "True", "Range" ]
def atr(high, low, close, period): """ Average True Range """ return lib.atr([high, low, close], [period])
[ "def", "atr", "(", "high", ",", "low", ",", "close", ",", "period", ")", ":", "return", "lib", ".", "atr", "(", "[", "high", ",", "low", ",", "close", "]", ",", "[", "period", "]", ")" ]
https://github.com/cirla/tulipy/blob/5f3049a47574f97e28fb78e9cf3787ed610941f9/tulipy/__init__.py#L214-L219
TurboWay/spiderman
168f18552e0abb06187388b542d6a0df057ba852
SP/pipelines/pipelines_hdfs.py
python
HdfsPipeline.buckets2db
(self, bucketsize=None)
:param bucketsize: 桶大小 :return: 遍历每个桶,将满足条件的桶,入库并清空桶
:param bucketsize: 桶大小 :return: 遍历每个桶,将满足条件的桶,入库并清空桶
[ ":", "param", "bucketsize", ":", "桶大小", ":", "return", ":", "遍历每个桶,将满足条件的桶,入库并清空桶" ]
def buckets2db(self, bucketsize=None): """ :param bucketsize: 桶大小 :return: 遍历每个桶,将满足条件的桶,入库并清空桶 """ if bucketsize is None: bucketsize = self.bucketsize for tablename, items in self.buckets_map.items(): # 遍历每个桶,将满足条件的桶,入库并清空桶 if len(items) >= bucketsize: new_items = [] cols, col_default = self.table_cols_map.get(tablename) for item in items: keyid = rowkey() new_item = {'keyid': keyid} for field in cols: value = item.get(field, col_default.get(field)) new_item[field] = str(value).replace(self.delimiter, '').replace('\n', '') new_item['bizdate'] = self.bizdate # 增加非业务字段 new_item['ctime'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) new_item['spider'] = self.name value = self.delimiter.join(new_item.values()) new_items.append(value) # 每张表是都是一个文件夹 folder = f"{self.dir}/{tablename}" self.client.makedirs(folder) filename = f"{folder}/data.txt" info = self.client.status(filename, strict=False) if not info: self.client.write(filename, data='', overwrite=True, encoding=self.encoding) try: content = '\n'.join(new_items) + '\n' self.client.write(filename, data=content, overwrite=False, append=True, encoding=self.encoding) logger.info(f"保存成功 <= 文件名:{filename} 记录数:{len(items)}") except Exception as e: logger.error(f"保存失败 <= 文件名:{filename} 错误原因:{e}") logger.warning(f"重新保存 <= 文件名:{tablename} 当前批次保存异常, 自动切换成逐行保存...") for new_item in new_items: try: content = new_item + '\n' self.client.write(filename, data=content, overwrite=False, append=True, encoding=self.encoding) logger.info(f"保存成功 <= 文件名:{tablename} 记录数:1") except Exception as e: logger.error(f"丢弃 <= 表名:{tablename} 丢弃原因:{e}") finally: items.clear()
[ "def", "buckets2db", "(", "self", ",", "bucketsize", "=", "None", ")", ":", "if", "bucketsize", "is", "None", ":", "bucketsize", "=", "self", ".", "bucketsize", "for", "tablename", ",", "items", "in", "self", ".", "buckets_map", ".", "items", "(", ")", ...
https://github.com/TurboWay/spiderman/blob/168f18552e0abb06187388b542d6a0df057ba852/SP/pipelines/pipelines_hdfs.py#L79-L127
PyTorchLightning/pytorch-lightning
5914fb748fb53d826ab337fc2484feab9883a104
pytorch_lightning/loops/optimization/manual_loop.py
python
ManualOptimization.on_run_end
(self)
return output
Returns the result of this loop, i.e., the post-processed outputs from the training step.
Returns the result of this loop, i.e., the post-processed outputs from the training step.
[ "Returns", "the", "result", "of", "this", "loop", "i", ".", "e", ".", "the", "post", "-", "processed", "outputs", "from", "the", "training", "step", "." ]
def on_run_end(self) -> _OUTPUTS_TYPE: """Returns the result of this loop, i.e., the post-processed outputs from the training step.""" output, self._output = self._output, {} # free memory return output
[ "def", "on_run_end", "(", "self", ")", "->", "_OUTPUTS_TYPE", ":", "output", ",", "self", ".", "_output", "=", "self", ".", "_output", ",", "{", "}", "# free memory", "return", "output" ]
https://github.com/PyTorchLightning/pytorch-lightning/blob/5914fb748fb53d826ab337fc2484feab9883a104/pytorch_lightning/loops/optimization/manual_loop.py#L126-L129
pwnieexpress/pwn_plug_sources
1a23324f5dc2c3de20f9c810269b6a29b2758cad
src/voiper/sulley/impacket/smb.py
python
SMB.disconnect_tree
(self, tid)
[]
def disconnect_tree(self, tid): smb = NewSMBPacket() smb['Tid'] = tid smb.addCommand(SMBCommand(SMB.SMB_COM_TREE_DISCONNECT)) self.sendSMB(smb) smb = self.recvSMB()
[ "def", "disconnect_tree", "(", "self", ",", "tid", ")", ":", "smb", "=", "NewSMBPacket", "(", ")", "smb", "[", "'Tid'", "]", "=", "tid", "smb", ".", "addCommand", "(", "SMBCommand", "(", "SMB", ".", "SMB_COM_TREE_DISCONNECT", ")", ")", "self", ".", "se...
https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/voiper/sulley/impacket/smb.py#L1496-L1502
CPqD/RouteFlow
3f406b9c1a0796f40a86eb1194990cdd2c955f4d
pox/pox/lib/ioworker/io_worker.py
python
IOWorker.close_handler
(self, callback)
Handler to call when data is available to read
Handler to call when data is available to read
[ "Handler", "to", "call", "when", "data", "is", "available", "to", "read" ]
def close_handler (self, callback): """ Handler to call when data is available to read """ # Not sure if this is a good idea, but it might be... if self.close_handler is not None or callback is not None: log.debug("Resetting close_handler on %s?", self) if callback is None: callback = _dummy_handler self._custom_close_handler = callback
[ "def", "close_handler", "(", "self", ",", "callback", ")", ":", "# Not sure if this is a good idea, but it might be...", "if", "self", ".", "close_handler", "is", "not", "None", "or", "callback", "is", "not", "None", ":", "log", ".", "debug", "(", "\"Resetting clo...
https://github.com/CPqD/RouteFlow/blob/3f406b9c1a0796f40a86eb1194990cdd2c955f4d/pox/pox/lib/ioworker/io_worker.py#L153-L161
sabnzbd/sabnzbd
52d21e94d3cc6e30764a833fe2a256783d1a8931
sabnzbd/dirscanner.py
python
DirScanner.newspeed
(self)
We're notified of a scan speed change
We're notified of a scan speed change
[ "We", "re", "notified", "of", "a", "scan", "speed", "change" ]
def newspeed(self): """We're notified of a scan speed change""" # If set to 0, use None so the wait() is forever self.dirscan_speed = cfg.dirscan_speed() or None with self.loop_condition: self.loop_condition.notify()
[ "def", "newspeed", "(", "self", ")", ":", "# If set to 0, use None so the wait() is forever", "self", ".", "dirscan_speed", "=", "cfg", ".", "dirscan_speed", "(", ")", "or", "None", "with", "self", ".", "loop_condition", ":", "self", ".", "loop_condition", ".", ...
https://github.com/sabnzbd/sabnzbd/blob/52d21e94d3cc6e30764a833fe2a256783d1a8931/sabnzbd/dirscanner.py#L98-L103
openstack/tempest
fe0ac89a5a1c43fa908a76759cd99eea3b1f9853
tempest/lib/services/image/v2/namespaces_client.py
python
NamespacesClient.show_namespace
(self, namespace)
return rest_client.ResponseBody(resp, body)
Show namespace details. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/image/v2/metadefs-index.html#get-namespace-details
Show namespace details.
[ "Show", "namespace", "details", "." ]
def show_namespace(self, namespace): """Show namespace details. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/image/v2/metadefs-index.html#get-namespace-details """ url = 'metadefs/namespaces/%s' % namespace resp, body = self.get(url) self.expected_success(200, resp.status) body = json.loads(body) return rest_client.ResponseBody(resp, body)
[ "def", "show_namespace", "(", "self", ",", "namespace", ")", ":", "url", "=", "'metadefs/namespaces/%s'", "%", "namespace", "resp", ",", "body", "=", "self", ".", "get", "(", "url", ")", "self", ".", "expected_success", "(", "200", ",", "resp", ".", "sta...
https://github.com/openstack/tempest/blob/fe0ac89a5a1c43fa908a76759cd99eea3b1f9853/tempest/lib/services/image/v2/namespaces_client.py#L50-L61
microsoft/MPNet
081523a788c1556f28dd90cbc629810f48b083fb
pretraining/fairseq/trainer.py
python
Trainer.get_model
(self)
return self._model
Get the (non-wrapped) model instance.
Get the (non-wrapped) model instance.
[ "Get", "the", "(", "non", "-", "wrapped", ")", "model", "instance", "." ]
def get_model(self): """Get the (non-wrapped) model instance.""" return self._model
[ "def", "get_model", "(", "self", ")", ":", "return", "self", ".", "_model" ]
https://github.com/microsoft/MPNet/blob/081523a788c1556f28dd90cbc629810f48b083fb/pretraining/fairseq/trainer.py#L575-L577
tendenci/tendenci
0f2c348cc0e7d41bc56f50b00ce05544b083bf1d
tendenci/apps/helpdesk/signals.py
python
init_signals
()
[]
def init_signals(): post_save.connect(create_usersettings, sender=User, weak=False)
[ "def", "init_signals", "(", ")", ":", "post_save", ".", "connect", "(", "create_usersettings", ",", "sender", "=", "User", ",", "weak", "=", "False", ")" ]
https://github.com/tendenci/tendenci/blob/0f2c348cc0e7d41bc56f50b00ce05544b083bf1d/tendenci/apps/helpdesk/signals.py#L19-L20
golismero/golismero
7d605b937e241f51c1ca4f47b20f755eeefb9d76
thirdparty_libs/django/db/models/sql/compiler.py
python
SQLDateCompiler.results_iter
(self)
Returns an iterator over the results from executing this query.
Returns an iterator over the results from executing this query.
[ "Returns", "an", "iterator", "over", "the", "results", "from", "executing", "this", "query", "." ]
def results_iter(self): """ Returns an iterator over the results from executing this query. """ resolve_columns = hasattr(self, 'resolve_columns') if resolve_columns: from django.db.models.fields import DateTimeField fields = [DateTimeField()] else: from django.db.backends.util import typecast_timestamp needs_string_cast = self.connection.features.needs_datetime_string_cast offset = len(self.query.extra_select) for rows in self.execute_sql(MULTI): for row in rows: date = row[offset] if resolve_columns: date = self.resolve_columns(row, fields)[offset] elif needs_string_cast: date = typecast_timestamp(str(date)) yield date
[ "def", "results_iter", "(", "self", ")", ":", "resolve_columns", "=", "hasattr", "(", "self", ",", "'resolve_columns'", ")", "if", "resolve_columns", ":", "from", "django", ".", "db", ".", "models", ".", "fields", "import", "DateTimeField", "fields", "=", "[...
https://github.com/golismero/golismero/blob/7d605b937e241f51c1ca4f47b20f755eeefb9d76/thirdparty_libs/django/db/models/sql/compiler.py#L1095-L1115
networkx/networkx
1620568e36702b1cfeaf1c0277b167b6cb93e48d
networkx/algorithms/clique.py
python
make_max_clique_graph
(G, create_using=None)
return B
Returns the maximal clique graph of the given graph. The nodes of the maximal clique graph of `G` are the cliques of `G` and an edge joins two cliques if the cliques are not disjoint. Parameters ---------- G : NetworkX graph create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Returns ------- NetworkX graph A graph whose nodes are the cliques of `G` and whose edges join two cliques if they are not disjoint. Notes ----- This function behaves like the following code:: import networkx as nx G = nx.make_clique_bipartite(G) cliques = [v for v in G.nodes() if G.nodes[v]['bipartite'] == 0] G = nx.bipartite.project(G, cliques) G = nx.relabel_nodes(G, {-v: v - 1 for v in G}) It should be faster, though, since it skips all the intermediate steps.
Returns the maximal clique graph of the given graph.
[ "Returns", "the", "maximal", "clique", "graph", "of", "the", "given", "graph", "." ]
def make_max_clique_graph(G, create_using=None): """Returns the maximal clique graph of the given graph. The nodes of the maximal clique graph of `G` are the cliques of `G` and an edge joins two cliques if the cliques are not disjoint. Parameters ---------- G : NetworkX graph create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Returns ------- NetworkX graph A graph whose nodes are the cliques of `G` and whose edges join two cliques if they are not disjoint. Notes ----- This function behaves like the following code:: import networkx as nx G = nx.make_clique_bipartite(G) cliques = [v for v in G.nodes() if G.nodes[v]['bipartite'] == 0] G = nx.bipartite.project(G, cliques) G = nx.relabel_nodes(G, {-v: v - 1 for v in G}) It should be faster, though, since it skips all the intermediate steps. """ if create_using is None: B = G.__class__() else: B = nx.empty_graph(0, create_using) cliques = list(enumerate(set(c) for c in find_cliques(G))) # Add a numbered node for each clique. B.add_nodes_from(i for i, c in cliques) # Join cliques by an edge if they share a node. clique_pairs = combinations(cliques, 2) B.add_edges_from((i, j) for (i, c1), (j, c2) in clique_pairs if c1 & c2) return B
[ "def", "make_max_clique_graph", "(", "G", ",", "create_using", "=", "None", ")", ":", "if", "create_using", "is", "None", ":", "B", "=", "G", ".", "__class__", "(", ")", "else", ":", "B", "=", "nx", ".", "empty_graph", "(", "0", ",", "create_using", ...
https://github.com/networkx/networkx/blob/1620568e36702b1cfeaf1c0277b167b6cb93e48d/networkx/algorithms/clique.py#L301-L344
IBM/lale
b4d6829c143a4735b06083a0e6c70d2cca244162
lale/search/search_space_grid.py
python
search_space_to_grids
(hp: SearchSpace)
return SearchSpaceToGridVisitor.run(hp)
[]
def search_space_to_grids(hp: SearchSpace) -> List[SearchSpaceGrid]: return SearchSpaceToGridVisitor.run(hp)
[ "def", "search_space_to_grids", "(", "hp", ":", "SearchSpace", ")", "->", "List", "[", "SearchSpaceGrid", "]", ":", "return", "SearchSpaceToGridVisitor", ".", "run", "(", "hp", ")" ]
https://github.com/IBM/lale/blob/b4d6829c143a4735b06083a0e6c70d2cca244162/lale/search/search_space_grid.py#L112-L113
gem/oq-engine
1bdb88f3914e390abcbd285600bfd39477aae47c
openquake/baselib/general.py
python
detach_process
()
Detach the current process from the controlling terminal by using a double fork. Can be used only on platforms with fork (no Windows).
Detach the current process from the controlling terminal by using a double fork. Can be used only on platforms with fork (no Windows).
[ "Detach", "the", "current", "process", "from", "the", "controlling", "terminal", "by", "using", "a", "double", "fork", ".", "Can", "be", "used", "only", "on", "platforms", "with", "fork", "(", "no", "Windows", ")", "." ]
def detach_process(): """ Detach the current process from the controlling terminal by using a double fork. Can be used only on platforms with fork (no Windows). """ # see https://pagure.io/python-daemon/blob/master/f/daemon/daemon.py and # https://stackoverflow.com/questions/45911705/why-use-os-setsid-in-python def fork_then_exit_parent(): pid = os.fork() if pid: # in parent os._exit(0) fork_then_exit_parent() os.setsid() fork_then_exit_parent()
[ "def", "detach_process", "(", ")", ":", "# see https://pagure.io/python-daemon/blob/master/f/daemon/daemon.py and", "# https://stackoverflow.com/questions/45911705/why-use-os-setsid-in-python", "def", "fork_then_exit_parent", "(", ")", ":", "pid", "=", "os", ".", "fork", "(", ")"...
https://github.com/gem/oq-engine/blob/1bdb88f3914e390abcbd285600bfd39477aae47c/openquake/baselib/general.py#L1267-L1280
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/combinat/skew_tableau.py
python
StandardSkewTableaux_shape.__iter__
(self)
An iterator for all the standard skew tableaux whose shape is the skew partition ``skp``. The standard skew tableaux are ordered lexicographically by the word obtained from their row reading. EXAMPLES:: sage: StandardSkewTableaux([[3, 2, 1], [1, 1]]).list() [[[None, 2, 3], [None, 4], [1]], [[None, 1, 2], [None, 3], [4]], [[None, 1, 2], [None, 4], [3]], [[None, 1, 3], [None, 4], [2]], [[None, 1, 4], [None, 3], [2]], [[None, 1, 4], [None, 2], [3]], [[None, 1, 3], [None, 2], [4]], [[None, 2, 4], [None, 3], [1]]]
An iterator for all the standard skew tableaux whose shape is the skew partition ``skp``. The standard skew tableaux are ordered lexicographically by the word obtained from their row reading.
[ "An", "iterator", "for", "all", "the", "standard", "skew", "tableaux", "whose", "shape", "is", "the", "skew", "partition", "skp", ".", "The", "standard", "skew", "tableaux", "are", "ordered", "lexicographically", "by", "the", "word", "obtained", "from", "their...
def __iter__(self): """ An iterator for all the standard skew tableaux whose shape is the skew partition ``skp``. The standard skew tableaux are ordered lexicographically by the word obtained from their row reading. EXAMPLES:: sage: StandardSkewTableaux([[3, 2, 1], [1, 1]]).list() [[[None, 2, 3], [None, 4], [1]], [[None, 1, 2], [None, 3], [4]], [[None, 1, 2], [None, 4], [3]], [[None, 1, 3], [None, 4], [2]], [[None, 1, 4], [None, 3], [2]], [[None, 1, 4], [None, 2], [3]], [[None, 1, 3], [None, 2], [4]], [[None, 2, 4], [None, 3], [1]]] """ dag = self.skp.to_dag(format="tuple") le_list = list(dag.topological_sort_generator()) empty = [[None] * row_length for row_length in self.skp.outer()] for le in le_list: yield self.element_class(self, _label_skew(le, empty))
[ "def", "__iter__", "(", "self", ")", ":", "dag", "=", "self", ".", "skp", ".", "to_dag", "(", "format", "=", "\"tuple\"", ")", "le_list", "=", "list", "(", "dag", ".", "topological_sort_generator", "(", ")", ")", "empty", "=", "[", "[", "None", "]", ...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/skew_tableau.py#L2040-L2065
inspurer/WorkAttendanceSystem
1221e2d67bdf5bb15fe99517cc3ded58ccb066df
V2.0/venv/Lib/site-packages/pip-9.0.1-py3.5.egg/pip/_vendor/pyparsing.py
python
ParserElement.split
(self, instring, maxsplit=_MAX_INT, includeSeparators=False)
Generator method to split a string using the given expression as a separator. May be called with optional C{maxsplit} argument, to limit the number of splits; and the optional C{includeSeparators} argument (default=C{False}), if the separating matching text should be included in the split results. Example:: punc = oneOf(list(".,;:/-!?")) print(list(punc.split("This, this?, this sentence, is badly punctuated!"))) prints:: ['This', ' this', '', ' this sentence', ' is badly punctuated', '']
Generator method to split a string using the given expression as a separator. May be called with optional C{maxsplit} argument, to limit the number of splits; and the optional C{includeSeparators} argument (default=C{False}), if the separating matching text should be included in the split results. Example:: punc = oneOf(list(".,;:/-!?")) print(list(punc.split("This, this?, this sentence, is badly punctuated!"))) prints:: ['This', ' this', '', ' this sentence', ' is badly punctuated', '']
[ "Generator", "method", "to", "split", "a", "string", "using", "the", "given", "expression", "as", "a", "separator", ".", "May", "be", "called", "with", "optional", "C", "{", "maxsplit", "}", "argument", "to", "limit", "the", "number", "of", "splits", ";", ...
def split(self, instring, maxsplit=_MAX_INT, includeSeparators=False): """ Generator method to split a string using the given expression as a separator. May be called with optional C{maxsplit} argument, to limit the number of splits; and the optional C{includeSeparators} argument (default=C{False}), if the separating matching text should be included in the split results. Example:: punc = oneOf(list(".,;:/-!?")) print(list(punc.split("This, this?, this sentence, is badly punctuated!"))) prints:: ['This', ' this', '', ' this sentence', ' is badly punctuated', ''] """ splits = 0 last = 0 for t,s,e in self.scanString(instring, maxMatches=maxsplit): yield instring[last:s] if includeSeparators: yield t[0] last = e yield instring[last:]
[ "def", "split", "(", "self", ",", "instring", ",", "maxsplit", "=", "_MAX_INT", ",", "includeSeparators", "=", "False", ")", ":", "splits", "=", "0", "last", "=", "0", "for", "t", ",", "s", ",", "e", "in", "self", ".", "scanString", "(", "instring", ...
https://github.com/inspurer/WorkAttendanceSystem/blob/1221e2d67bdf5bb15fe99517cc3ded58ccb066df/V2.0/venv/Lib/site-packages/pip-9.0.1-py3.5.egg/pip/_vendor/pyparsing.py#L1758-L1778
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/http/cookiejar.py
python
DefaultCookiePolicy.is_not_allowed
(self, domain)
return True
[]
def is_not_allowed(self, domain): if self._allowed_domains is None: return False for allowed_domain in self._allowed_domains: if user_domain_match(domain, allowed_domain): return False return True
[ "def", "is_not_allowed", "(", "self", ",", "domain", ")", ":", "if", "self", ".", "_allowed_domains", "is", "None", ":", "return", "False", "for", "allowed_domain", "in", "self", ".", "_allowed_domains", ":", "if", "user_domain_match", "(", "domain", ",", "a...
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/http/cookiejar.py#L925-L931
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/celery/beat.py
python
Scheduler.send_task
(self, *args, **kwargs)
return self.app.send_task(*args, **kwargs)
[]
def send_task(self, *args, **kwargs): return self.app.send_task(*args, **kwargs)
[ "def", "send_task", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "app", ".", "send_task", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/celery/beat.py#L313-L314