repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
raphaelm/python-sepaxml
sepaxml/debit.py
SepaDD._add_non_batch
def _add_non_batch(self, TX_nodes, PmtInf_nodes): """ Method to add a transaction as non batch, will fold the transaction together with the payment info node and append to the main xml. """ PmtInf_nodes['PmtInfNode'].append(PmtInf_nodes['PmtInfIdNode']) PmtInf_nodes['PmtI...
python
def _add_non_batch(self, TX_nodes, PmtInf_nodes): """ Method to add a transaction as non batch, will fold the transaction together with the payment info node and append to the main xml. """ PmtInf_nodes['PmtInfNode'].append(PmtInf_nodes['PmtInfIdNode']) PmtInf_nodes['PmtI...
[ "def", "_add_non_batch", "(", "self", ",", "TX_nodes", ",", "PmtInf_nodes", ")", ":", "PmtInf_nodes", "[", "'PmtInfNode'", "]", ".", "append", "(", "PmtInf_nodes", "[", "'PmtInfIdNode'", "]", ")", "PmtInf_nodes", "[", "'PmtInfNode'", "]", ".", "append", "(", ...
Method to add a transaction as non batch, will fold the transaction together with the payment info node and append to the main xml.
[ "Method", "to", "add", "a", "transaction", "as", "non", "batch", "will", "fold", "the", "transaction", "together", "with", "the", "payment", "info", "node", "and", "append", "to", "the", "main", "xml", "." ]
train
https://github.com/raphaelm/python-sepaxml/blob/187b699b1673c862002b2bae7e1bd62fe8623aec/sepaxml/debit.py#L236-L309
raphaelm/python-sepaxml
sepaxml/debit.py
SepaDD._finalize_batch
def _finalize_batch(self): """ Method to finalize the batch, this will iterate over the _batches dict and create a PmtInf node for each batch. The correct information (from the batch_key and batch_totals) will be inserted and the batch transaction nodes will be folded. Finally, t...
python
def _finalize_batch(self): """ Method to finalize the batch, this will iterate over the _batches dict and create a PmtInf node for each batch. The correct information (from the batch_key and batch_totals) will be inserted and the batch transaction nodes will be folded. Finally, t...
[ "def", "_finalize_batch", "(", "self", ")", ":", "for", "batch_meta", ",", "batch_nodes", "in", "self", ".", "_batches", ".", "items", "(", ")", ":", "batch_meta_split", "=", "batch_meta", ".", "split", "(", "\"::\"", ")", "PmtInf_nodes", "=", "self", ".",...
Method to finalize the batch, this will iterate over the _batches dict and create a PmtInf node for each batch. The correct information (from the batch_key and batch_totals) will be inserted and the batch transaction nodes will be folded. Finally, the batches will be added to the main XM...
[ "Method", "to", "finalize", "the", "batch", "this", "will", "iterate", "over", "the", "_batches", "dict", "and", "create", "a", "PmtInf", "node", "for", "each", "batch", ".", "The", "correct", "information", "(", "from", "the", "batch_key", "and", "batch_tot...
train
https://github.com/raphaelm/python-sepaxml/blob/187b699b1673c862002b2bae7e1bd62fe8623aec/sepaxml/debit.py#L362-L443
raphaelm/python-sepaxml
sepaxml/transfer.py
SepaTransfer.check_config
def check_config(self, config): """ Check the config file for required fields and validity. @param config: The config dict. @return: True if valid, error string if invalid paramaters where encountered. """ validation = "" required = ["name", "currency", "I...
python
def check_config(self, config): """ Check the config file for required fields and validity. @param config: The config dict. @return: True if valid, error string if invalid paramaters where encountered. """ validation = "" required = ["name", "currency", "I...
[ "def", "check_config", "(", "self", ",", "config", ")", ":", "validation", "=", "\"\"", "required", "=", "[", "\"name\"", ",", "\"currency\"", ",", "\"IBAN\"", ",", "\"BIC\"", "]", "for", "config_item", "in", "required", ":", "if", "config_item", "not", "i...
Check the config file for required fields and validity. @param config: The config dict. @return: True if valid, error string if invalid paramaters where encountered.
[ "Check", "the", "config", "file", "for", "required", "fields", "and", "validity", "." ]
train
https://github.com/raphaelm/python-sepaxml/blob/187b699b1673c862002b2bae7e1bd62fe8623aec/sepaxml/transfer.py#L17-L34
raphaelm/python-sepaxml
sepaxml/transfer.py
SepaTransfer.check_payment
def check_payment(self, payment): """ Check the payment for required fields and validity. @param payment: The payment dict @return: True if valid, error string if invalid paramaters where encountered. """ validation = "" required = ["name", "IBAN", "BIC", ...
python
def check_payment(self, payment): """ Check the payment for required fields and validity. @param payment: The payment dict @return: True if valid, error string if invalid paramaters where encountered. """ validation = "" required = ["name", "IBAN", "BIC", ...
[ "def", "check_payment", "(", "self", ",", "payment", ")", ":", "validation", "=", "\"\"", "required", "=", "[", "\"name\"", ",", "\"IBAN\"", ",", "\"BIC\"", ",", "\"amount\"", ",", "\"description\"", "]", "for", "config_item", "in", "required", ":", "if", ...
Check the payment for required fields and validity. @param payment: The payment dict @return: True if valid, error string if invalid paramaters where encountered.
[ "Check", "the", "payment", "for", "required", "fields", "and", "validity", "." ]
train
https://github.com/raphaelm/python-sepaxml/blob/187b699b1673c862002b2bae7e1bd62fe8623aec/sepaxml/transfer.py#L36-L61
raphaelm/python-sepaxml
sepaxml/transfer.py
SepaTransfer._create_header
def _create_header(self): """ Function to create the GroupHeader (GrpHdr) in the CstmrCdtTrfInitn Node """ # Retrieve the node to which we will append the group header. CstmrCdtTrfInitn_node = self._xml.find('CstmrCdtTrfInitn') # Create the header nodes. ...
python
def _create_header(self): """ Function to create the GroupHeader (GrpHdr) in the CstmrCdtTrfInitn Node """ # Retrieve the node to which we will append the group header. CstmrCdtTrfInitn_node = self._xml.find('CstmrCdtTrfInitn') # Create the header nodes. ...
[ "def", "_create_header", "(", "self", ")", ":", "# Retrieve the node to which we will append the group header.", "CstmrCdtTrfInitn_node", "=", "self", ".", "_xml", ".", "find", "(", "'CstmrCdtTrfInitn'", ")", "# Create the header nodes.", "GrpHdr_node", "=", "ET", ".", "E...
Function to create the GroupHeader (GrpHdr) in the CstmrCdtTrfInitn Node
[ "Function", "to", "create", "the", "GroupHeader", "(", "GrpHdr", ")", "in", "the", "CstmrCdtTrfInitn", "Node" ]
train
https://github.com/raphaelm/python-sepaxml/blob/187b699b1673c862002b2bae7e1bd62fe8623aec/sepaxml/transfer.py#L122-L153
raphaelm/python-sepaxml
sepaxml/transfer.py
SepaTransfer._create_PmtInf_node
def _create_PmtInf_node(self): """ Method to create the blank payment information nodes as a dict. """ ED = dict() # ED is element dict ED['PmtInfNode'] = ET.Element("PmtInf") ED['PmtInfIdNode'] = ET.Element("PmtInfId") ED['PmtMtdNode'] = ET.Element("PmtMtd") ...
python
def _create_PmtInf_node(self): """ Method to create the blank payment information nodes as a dict. """ ED = dict() # ED is element dict ED['PmtInfNode'] = ET.Element("PmtInf") ED['PmtInfIdNode'] = ET.Element("PmtInfId") ED['PmtMtdNode'] = ET.Element("PmtMtd") ...
[ "def", "_create_PmtInf_node", "(", "self", ")", ":", "ED", "=", "dict", "(", ")", "# ED is element dict", "ED", "[", "'PmtInfNode'", "]", "=", "ET", ".", "Element", "(", "\"PmtInf\"", ")", "ED", "[", "'PmtInfIdNode'", "]", "=", "ET", ".", "Element", "(",...
Method to create the blank payment information nodes as a dict.
[ "Method", "to", "create", "the", "blank", "payment", "information", "nodes", "as", "a", "dict", "." ]
train
https://github.com/raphaelm/python-sepaxml/blob/187b699b1673c862002b2bae7e1bd62fe8623aec/sepaxml/transfer.py#L155-L181
raphaelm/python-sepaxml
sepaxml/transfer.py
SepaTransfer._add_non_batch
def _add_non_batch(self, TX_nodes, PmtInf_nodes): """ Method to add a transaction as non batch, will fold the transaction together with the payment info node and append to the main xml. """ PmtInf_nodes['PmtInfNode'].append(PmtInf_nodes['PmtInfIdNode']) PmtInf_nodes['PmtI...
python
def _add_non_batch(self, TX_nodes, PmtInf_nodes): """ Method to add a transaction as non batch, will fold the transaction together with the payment info node and append to the main xml. """ PmtInf_nodes['PmtInfNode'].append(PmtInf_nodes['PmtInfIdNode']) PmtInf_nodes['PmtI...
[ "def", "_add_non_batch", "(", "self", ",", "TX_nodes", ",", "PmtInf_nodes", ")", ":", "PmtInf_nodes", "[", "'PmtInfNode'", "]", ".", "append", "(", "PmtInf_nodes", "[", "'PmtInfIdNode'", "]", ")", "PmtInf_nodes", "[", "'PmtInfNode'", "]", ".", "append", "(", ...
Method to add a transaction as non batch, will fold the transaction together with the payment info node and append to the main xml.
[ "Method", "to", "add", "a", "transaction", "as", "non", "batch", "will", "fold", "the", "transaction", "together", "with", "the", "payment", "info", "node", "and", "append", "to", "the", "main", "xml", "." ]
train
https://github.com/raphaelm/python-sepaxml/blob/187b699b1673c862002b2bae7e1bd62fe8623aec/sepaxml/transfer.py#L207-L260
raphaelm/python-sepaxml
sepaxml/transfer.py
SepaTransfer._add_batch
def _add_batch(self, TX_nodes, payment): """ Method to add a payment as a batch. The transaction details are already present. Will fold the nodes accordingly and the call the _add_to_batch_list function to store the batch. """ TX_nodes['PmtIdNode'].append(TX_nodes['EndToE...
python
def _add_batch(self, TX_nodes, payment): """ Method to add a payment as a batch. The transaction details are already present. Will fold the nodes accordingly and the call the _add_to_batch_list function to store the batch. """ TX_nodes['PmtIdNode'].append(TX_nodes['EndToE...
[ "def", "_add_batch", "(", "self", ",", "TX_nodes", ",", "payment", ")", ":", "TX_nodes", "[", "'PmtIdNode'", "]", ".", "append", "(", "TX_nodes", "[", "'EndToEnd_PmtId_Node'", "]", ")", "TX_nodes", "[", "'AmtNode'", "]", ".", "append", "(", "TX_nodes", "["...
Method to add a payment as a batch. The transaction details are already present. Will fold the nodes accordingly and the call the _add_to_batch_list function to store the batch.
[ "Method", "to", "add", "a", "payment", "as", "a", "batch", ".", "The", "transaction", "details", "are", "already", "present", ".", "Will", "fold", "the", "nodes", "accordingly", "and", "the", "call", "the", "_add_to_batch_list", "function", "to", "store", "t...
train
https://github.com/raphaelm/python-sepaxml/blob/187b699b1673c862002b2bae7e1bd62fe8623aec/sepaxml/transfer.py#L262-L288
raphaelm/python-sepaxml
sepaxml/transfer.py
SepaTransfer._add_to_batch_list
def _add_to_batch_list(self, TX, payment): """ Method to add a transaction to the batch list. The correct batch will be determined by the payment dict and the batch will be created if not existant. This will also add the payment amount to the respective batch total. """ ...
python
def _add_to_batch_list(self, TX, payment): """ Method to add a transaction to the batch list. The correct batch will be determined by the payment dict and the batch will be created if not existant. This will also add the payment amount to the respective batch total. """ ...
[ "def", "_add_to_batch_list", "(", "self", ",", "TX", ",", "payment", ")", ":", "batch_key", "=", "payment", ".", "get", "(", "'execution_date'", ",", "None", ")", "if", "batch_key", "in", "self", ".", "_batches", ".", "keys", "(", ")", ":", "self", "."...
Method to add a transaction to the batch list. The correct batch will be determined by the payment dict and the batch will be created if not existant. This will also add the payment amount to the respective batch total.
[ "Method", "to", "add", "a", "transaction", "to", "the", "batch", "list", ".", "The", "correct", "batch", "will", "be", "determined", "by", "the", "payment", "dict", "and", "the", "batch", "will", "be", "created", "if", "not", "existant", ".", "This", "wi...
train
https://github.com/raphaelm/python-sepaxml/blob/187b699b1673c862002b2bae7e1bd62fe8623aec/sepaxml/transfer.py#L290-L307
raphaelm/python-sepaxml
sepaxml/transfer.py
SepaTransfer._finalize_batch
def _finalize_batch(self): """ Method to finalize the batch, this will iterate over the _batches dict and create a PmtInf node for each batch. The correct information (from the batch_key and batch_totals) will be inserted and the batch transaction nodes will be folded. Finally, t...
python
def _finalize_batch(self): """ Method to finalize the batch, this will iterate over the _batches dict and create a PmtInf node for each batch. The correct information (from the batch_key and batch_totals) will be inserted and the batch transaction nodes will be folded. Finally, t...
[ "def", "_finalize_batch", "(", "self", ")", ":", "for", "batch_meta", ",", "batch_nodes", "in", "self", ".", "_batches", ".", "items", "(", ")", ":", "PmtInf_nodes", "=", "self", ".", "_create_PmtInf_node", "(", ")", "PmtInf_nodes", "[", "'PmtInfIdNode'", "]...
Method to finalize the batch, this will iterate over the _batches dict and create a PmtInf node for each batch. The correct information (from the batch_key and batch_totals) will be inserted and the batch transaction nodes will be folded. Finally, the batches will be added to the main XM...
[ "Method", "to", "finalize", "the", "batch", "this", "will", "iterate", "over", "the", "_batches", "dict", "and", "create", "a", "PmtInf", "node", "for", "each", "batch", ".", "The", "correct", "information", "(", "from", "the", "batch_key", "and", "batch_tot...
train
https://github.com/raphaelm/python-sepaxml/blob/187b699b1673c862002b2bae7e1bd62fe8623aec/sepaxml/transfer.py#L309-L369
jaijuneja/PyTLDR
pytldr/summarize/baseclass.py
BaseSummarizer._compute_matrix
def _compute_matrix(cls, sentences, weighting='frequency', norm=None): """ Compute the matrix of term frequencies given a list of sentences """ if norm not in ('l1', 'l2', None): raise ValueError('Parameter "norm" can only take values "l1", "l2" or None') # Initiali...
python
def _compute_matrix(cls, sentences, weighting='frequency', norm=None): """ Compute the matrix of term frequencies given a list of sentences """ if norm not in ('l1', 'l2', None): raise ValueError('Parameter "norm" can only take values "l1", "l2" or None') # Initiali...
[ "def", "_compute_matrix", "(", "cls", ",", "sentences", ",", "weighting", "=", "'frequency'", ",", "norm", "=", "None", ")", ":", "if", "norm", "not", "in", "(", "'l1'", ",", "'l2'", ",", "None", ")", ":", "raise", "ValueError", "(", "'Parameter \"norm\"...
Compute the matrix of term frequencies given a list of sentences
[ "Compute", "the", "matrix", "of", "term", "frequencies", "given", "a", "list", "of", "sentences" ]
train
https://github.com/jaijuneja/PyTLDR/blob/4ba2ab88dbbb1318a86bf4483264ab213e166b6b/pytldr/summarize/baseclass.py#L19-L46
jaijuneja/PyTLDR
pytldr/summarize/relevance.py
RelevanceSummarizer.summarize
def summarize(self, text, length=5, binary_matrix=True): """ Implements the method of summarization by relevance score, as described by Gong and Liu in the paper: Y. Gong and X. Liu (2001). Generic text summarization using relevance measure and latent semantic analysis. Proceedings of t...
python
def summarize(self, text, length=5, binary_matrix=True): """ Implements the method of summarization by relevance score, as described by Gong and Liu in the paper: Y. Gong and X. Liu (2001). Generic text summarization using relevance measure and latent semantic analysis. Proceedings of t...
[ "def", "summarize", "(", "self", ",", "text", ",", "length", "=", "5", ",", "binary_matrix", "=", "True", ")", ":", "text", "=", "self", ".", "_parse_input", "(", "text", ")", "sentences", ",", "unprocessed_sentences", "=", "self", ".", "_tokenizer", "."...
Implements the method of summarization by relevance score, as described by Gong and Liu in the paper: Y. Gong and X. Liu (2001). Generic text summarization using relevance measure and latent semantic analysis. Proceedings of the 24th International Conference on Research in Information Retrieval (SIGIR ...
[ "Implements", "the", "method", "of", "summarization", "by", "relevance", "score", "as", "described", "by", "Gong", "and", "Liu", "in", "the", "paper", ":" ]
train
https://github.com/jaijuneja/PyTLDR/blob/4ba2ab88dbbb1318a86bf4483264ab213e166b6b/pytldr/summarize/relevance.py#L8-L64
raphaelm/python-sepaxml
sepaxml/shared.py
SepaPaymentInitn._prepare_document
def _prepare_document(self): """ Build the main document node and set xml namespaces. """ self._xml = ET.Element("Document") self._xml.set("xmlns", "urn:iso:std:iso:20022:tech:xsd:" + self.schema) self._xml.set("xmlns:xsi", "htt...
python
def _prepare_document(self): """ Build the main document node and set xml namespaces. """ self._xml = ET.Element("Document") self._xml.set("xmlns", "urn:iso:std:iso:20022:tech:xsd:" + self.schema) self._xml.set("xmlns:xsi", "htt...
[ "def", "_prepare_document", "(", "self", ")", ":", "self", ".", "_xml", "=", "ET", ".", "Element", "(", "\"Document\"", ")", "self", ".", "_xml", ".", "set", "(", "\"xmlns\"", ",", "\"urn:iso:std:iso:20022:tech:xsd:\"", "+", "self", ".", "schema", ")", "se...
Build the main document node and set xml namespaces.
[ "Build", "the", "main", "document", "node", "and", "set", "xml", "namespaces", "." ]
train
https://github.com/raphaelm/python-sepaxml/blob/187b699b1673c862002b2bae7e1bd62fe8623aec/sepaxml/shared.py#L36-L50
raphaelm/python-sepaxml
sepaxml/shared.py
SepaPaymentInitn.export
def export(self, validate=True): """ Method to output the xml as string. It will finalize the batches and then calculate the checksums (amount sum and transaction count), fill these into the group header and output the XML. """ self._finalize_batch() ctrl_sum_tot...
python
def export(self, validate=True): """ Method to output the xml as string. It will finalize the batches and then calculate the checksums (amount sum and transaction count), fill these into the group header and output the XML. """ self._finalize_batch() ctrl_sum_tot...
[ "def", "export", "(", "self", ",", "validate", "=", "True", ")", ":", "self", ".", "_finalize_batch", "(", ")", "ctrl_sum_total", "=", "0", "nb_of_txs_total", "=", "0", "for", "ctrl_sum", "in", "self", ".", "_xml", ".", "iter", "(", "'CtrlSum'", ")", "...
Method to output the xml as string. It will finalize the batches and then calculate the checksums (amount sum and transaction count), fill these into the group header and output the XML.
[ "Method", "to", "output", "the", "xml", "as", "string", ".", "It", "will", "finalize", "the", "batches", "and", "then", "calculate", "the", "checksums", "(", "amount", "sum", "and", "transaction", "count", ")", "fill", "these", "into", "the", "group", "hea...
train
https://github.com/raphaelm/python-sepaxml/blob/187b699b1673c862002b2bae7e1bd62fe8623aec/sepaxml/shared.py#L58-L95
raphaelm/python-sepaxml
sepaxml/utils.py
get_rand_string
def get_rand_string(length=12, allowed_chars='0123456789abcdef'): """ Returns a securely generated random string. Taken from the Django project The default length of 12 with the a-z, A-Z, 0-9 character set returns a 71-bit value. log_2((26+26+10)^12) =~ 71 bits """ if not using_sysrandom: ...
python
def get_rand_string(length=12, allowed_chars='0123456789abcdef'): """ Returns a securely generated random string. Taken from the Django project The default length of 12 with the a-z, A-Z, 0-9 character set returns a 71-bit value. log_2((26+26+10)^12) =~ 71 bits """ if not using_sysrandom: ...
[ "def", "get_rand_string", "(", "length", "=", "12", ",", "allowed_chars", "=", "'0123456789abcdef'", ")", ":", "if", "not", "using_sysrandom", ":", "# This is ugly, and a hack, but it makes things better than", "# the alternative of predictability. This re-seeds the PRNG", "# usi...
Returns a securely generated random string. Taken from the Django project The default length of 12 with the a-z, A-Z, 0-9 character set returns a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
[ "Returns", "a", "securely", "generated", "random", "string", ".", "Taken", "from", "the", "Django", "project" ]
train
https://github.com/raphaelm/python-sepaxml/blob/187b699b1673c862002b2bae7e1bd62fe8623aec/sepaxml/utils.py#L16-L36
raphaelm/python-sepaxml
sepaxml/utils.py
make_msg_id
def make_msg_id(): """ Create a semi random message id, by using 12 char random hex string and a timestamp. @return: string consisting of timestamp, -, random value """ random_string = get_rand_string(12) timestamp = time.strftime("%Y%m%d%I%M%S") msg_id = timestamp + "-" + random_string ...
python
def make_msg_id(): """ Create a semi random message id, by using 12 char random hex string and a timestamp. @return: string consisting of timestamp, -, random value """ random_string = get_rand_string(12) timestamp = time.strftime("%Y%m%d%I%M%S") msg_id = timestamp + "-" + random_string ...
[ "def", "make_msg_id", "(", ")", ":", "random_string", "=", "get_rand_string", "(", "12", ")", "timestamp", "=", "time", ".", "strftime", "(", "\"%Y%m%d%I%M%S\"", ")", "msg_id", "=", "timestamp", "+", "\"-\"", "+", "random_string", "return", "msg_id" ]
Create a semi random message id, by using 12 char random hex string and a timestamp. @return: string consisting of timestamp, -, random value
[ "Create", "a", "semi", "random", "message", "id", "by", "using", "12", "char", "random", "hex", "string", "and", "a", "timestamp", "." ]
train
https://github.com/raphaelm/python-sepaxml/blob/187b699b1673c862002b2bae7e1bd62fe8623aec/sepaxml/utils.py#L39-L48
raphaelm/python-sepaxml
sepaxml/utils.py
make_id
def make_id(name): """ Create a random id combined with the creditor name. @return string consisting of name (truncated at 22 chars), -, 12 char rand hex string. """ name = re.sub(r'[^a-zA-Z0-9]', '', name) r = get_rand_string(12) if len(name) > 22: name = name[:22] return na...
python
def make_id(name): """ Create a random id combined with the creditor name. @return string consisting of name (truncated at 22 chars), -, 12 char rand hex string. """ name = re.sub(r'[^a-zA-Z0-9]', '', name) r = get_rand_string(12) if len(name) > 22: name = name[:22] return na...
[ "def", "make_id", "(", "name", ")", ":", "name", "=", "re", ".", "sub", "(", "r'[^a-zA-Z0-9]'", ",", "''", ",", "name", ")", "r", "=", "get_rand_string", "(", "12", ")", "if", "len", "(", "name", ")", ">", "22", ":", "name", "=", "name", "[", "...
Create a random id combined with the creditor name. @return string consisting of name (truncated at 22 chars), -, 12 char rand hex string.
[ "Create", "a", "random", "id", "combined", "with", "the", "creditor", "name", "." ]
train
https://github.com/raphaelm/python-sepaxml/blob/187b699b1673c862002b2bae7e1bd62fe8623aec/sepaxml/utils.py#L51-L61
raphaelm/python-sepaxml
sepaxml/utils.py
int_to_decimal_str
def int_to_decimal_str(integer): """ Helper to convert integers (representing cents) into decimal currency string. WARNING: DO NOT TRY TO DO THIS BY DIVISION, FLOATING POINT ERRORS ARE NO FUN IN FINANCIAL SYSTEMS. @param integer The amount in cents @return string The amount in currency with full...
python
def int_to_decimal_str(integer): """ Helper to convert integers (representing cents) into decimal currency string. WARNING: DO NOT TRY TO DO THIS BY DIVISION, FLOATING POINT ERRORS ARE NO FUN IN FINANCIAL SYSTEMS. @param integer The amount in cents @return string The amount in currency with full...
[ "def", "int_to_decimal_str", "(", "integer", ")", ":", "int_string", "=", "str", "(", "integer", ")", "if", "len", "(", "int_string", ")", "<", "2", ":", "return", "\"0.\"", "+", "int_string", ".", "zfill", "(", "2", ")", "else", ":", "return", "int_st...
Helper to convert integers (representing cents) into decimal currency string. WARNING: DO NOT TRY TO DO THIS BY DIVISION, FLOATING POINT ERRORS ARE NO FUN IN FINANCIAL SYSTEMS. @param integer The amount in cents @return string The amount in currency with full stop decimal separator
[ "Helper", "to", "convert", "integers", "(", "representing", "cents", ")", "into", "decimal", "currency", "string", ".", "WARNING", ":", "DO", "NOT", "TRY", "TO", "DO", "THIS", "BY", "DIVISION", "FLOATING", "POINT", "ERRORS", "ARE", "NO", "FUN", "IN", "FINA...
train
https://github.com/raphaelm/python-sepaxml/blob/187b699b1673c862002b2bae7e1bd62fe8623aec/sepaxml/utils.py#L64-L76
raphaelm/python-sepaxml
sepaxml/utils.py
decimal_str_to_int
def decimal_str_to_int(decimal_string): """ Helper to decimal currency string into integers (cents). WARNING: DO NOT TRY TO DO THIS BY CONVERSION AND MULTIPLICATION, FLOATING POINT ERRORS ARE NO FUN IN FINANCIAL SYSTEMS. @param string The amount in currency with full stop decimal separator @retu...
python
def decimal_str_to_int(decimal_string): """ Helper to decimal currency string into integers (cents). WARNING: DO NOT TRY TO DO THIS BY CONVERSION AND MULTIPLICATION, FLOATING POINT ERRORS ARE NO FUN IN FINANCIAL SYSTEMS. @param string The amount in currency with full stop decimal separator @retu...
[ "def", "decimal_str_to_int", "(", "decimal_string", ")", ":", "int_string", "=", "decimal_string", ".", "replace", "(", "'.'", ",", "''", ")", "int_string", "=", "int_string", ".", "lstrip", "(", "'0'", ")", "return", "int", "(", "int_string", ")" ]
Helper to decimal currency string into integers (cents). WARNING: DO NOT TRY TO DO THIS BY CONVERSION AND MULTIPLICATION, FLOATING POINT ERRORS ARE NO FUN IN FINANCIAL SYSTEMS. @param string The amount in currency with full stop decimal separator @return integer The amount in cents
[ "Helper", "to", "decimal", "currency", "string", "into", "integers", "(", "cents", ")", ".", "WARNING", ":", "DO", "NOT", "TRY", "TO", "DO", "THIS", "BY", "CONVERSION", "AND", "MULTIPLICATION", "FLOATING", "POINT", "ERRORS", "ARE", "NO", "FUN", "IN", "FINA...
train
https://github.com/raphaelm/python-sepaxml/blob/187b699b1673c862002b2bae7e1bd62fe8623aec/sepaxml/utils.py#L79-L89
NatLibFi/Skosify
skosify/rdftools/io.py
read_rdf
def read_rdf(sources, infmt): """Read a list of RDF files and/or RDF graphs. May raise an Exception.""" rdf = Graph() for source in sources: if isinstance(source, Graph): for triple in source: rdf.add(triple) continue if source == '-': f ...
python
def read_rdf(sources, infmt): """Read a list of RDF files and/or RDF graphs. May raise an Exception.""" rdf = Graph() for source in sources: if isinstance(source, Graph): for triple in source: rdf.add(triple) continue if source == '-': f ...
[ "def", "read_rdf", "(", "sources", ",", "infmt", ")", ":", "rdf", "=", "Graph", "(", ")", "for", "source", "in", "sources", ":", "if", "isinstance", "(", "source", ",", "Graph", ")", ":", "for", "triple", "in", "source", ":", "rdf", ".", "add", "("...
Read a list of RDF files and/or RDF graphs. May raise an Exception.
[ "Read", "a", "list", "of", "RDF", "files", "and", "/", "or", "RDF", "graphs", ".", "May", "raise", "an", "Exception", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/rdftools/io.py#L10-L40
NatLibFi/Skosify
skosify/skosify.py
mapping_get
def mapping_get(uri, mapping): """Look up the URI in the given mapping and return the result. Throws KeyError if no matching mapping was found. """ ln = localname(uri) # 1. try to match URI keys for k, v in mapping.items(): if k == uri: return v # 2. try to match local ...
python
def mapping_get(uri, mapping): """Look up the URI in the given mapping and return the result. Throws KeyError if no matching mapping was found. """ ln = localname(uri) # 1. try to match URI keys for k, v in mapping.items(): if k == uri: return v # 2. try to match local ...
[ "def", "mapping_get", "(", "uri", ",", "mapping", ")", ":", "ln", "=", "localname", "(", "uri", ")", "# 1. try to match URI keys", "for", "k", ",", "v", "in", "mapping", ".", "items", "(", ")", ":", "if", "k", "==", "uri", ":", "return", "v", "# 2. t...
Look up the URI in the given mapping and return the result. Throws KeyError if no matching mapping was found.
[ "Look", "up", "the", "URI", "in", "the", "given", "mapping", "and", "return", "the", "result", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/skosify.py#L26-L48
NatLibFi/Skosify
skosify/skosify.py
mapping_match
def mapping_match(uri, mapping): """Determine whether the given URI matches one of the given mappings. Returns True if a match was found, False otherwise. """ try: val = mapping_get(uri, mapping) return True except KeyError: return False
python
def mapping_match(uri, mapping): """Determine whether the given URI matches one of the given mappings. Returns True if a match was found, False otherwise. """ try: val = mapping_get(uri, mapping) return True except KeyError: return False
[ "def", "mapping_match", "(", "uri", ",", "mapping", ")", ":", "try", ":", "val", "=", "mapping_get", "(", "uri", ",", "mapping", ")", "return", "True", "except", "KeyError", ":", "return", "False" ]
Determine whether the given URI matches one of the given mappings. Returns True if a match was found, False otherwise.
[ "Determine", "whether", "the", "given", "URI", "matches", "one", "of", "the", "given", "mappings", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/skosify.py#L51-L61
NatLibFi/Skosify
skosify/skosify.py
in_general_ns
def in_general_ns(uri): """Return True iff the URI is in a well-known general RDF namespace. URI namespaces considered well-known are RDF, RDFS, OWL, SKOS and DC.""" RDFuri = RDF.uri RDFSuri = RDFS.uri for ns in (RDFuri, RDFSuri, OWL, SKOS, DC): if uri.startswith(ns): return Tr...
python
def in_general_ns(uri): """Return True iff the URI is in a well-known general RDF namespace. URI namespaces considered well-known are RDF, RDFS, OWL, SKOS and DC.""" RDFuri = RDF.uri RDFSuri = RDFS.uri for ns in (RDFuri, RDFSuri, OWL, SKOS, DC): if uri.startswith(ns): return Tr...
[ "def", "in_general_ns", "(", "uri", ")", ":", "RDFuri", "=", "RDF", ".", "uri", "RDFSuri", "=", "RDFS", ".", "uri", "for", "ns", "in", "(", "RDFuri", ",", "RDFSuri", ",", "OWL", ",", "SKOS", ",", "DC", ")", ":", "if", "uri", ".", "startswith", "(...
Return True iff the URI is in a well-known general RDF namespace. URI namespaces considered well-known are RDF, RDFS, OWL, SKOS and DC.
[ "Return", "True", "iff", "the", "URI", "is", "in", "a", "well", "-", "known", "general", "RDF", "namespace", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/skosify.py#L64-L74
NatLibFi/Skosify
skosify/skosify.py
get_concept_scheme
def get_concept_scheme(rdf): """Return a skos:ConceptScheme contained in the model. Returns None if no skos:ConceptScheme is present. """ # add explicit type for s, o in rdf.subject_objects(SKOS.inScheme): if not isinstance(o, Literal): rdf.add((o, RDF.type, SKOS.ConceptScheme))...
python
def get_concept_scheme(rdf): """Return a skos:ConceptScheme contained in the model. Returns None if no skos:ConceptScheme is present. """ # add explicit type for s, o in rdf.subject_objects(SKOS.inScheme): if not isinstance(o, Literal): rdf.add((o, RDF.type, SKOS.ConceptScheme))...
[ "def", "get_concept_scheme", "(", "rdf", ")", ":", "# add explicit type", "for", "s", ",", "o", "in", "rdf", ".", "subject_objects", "(", "SKOS", ".", "inScheme", ")", ":", "if", "not", "isinstance", "(", "o", ",", "Literal", ")", ":", "rdf", ".", "add...
Return a skos:ConceptScheme contained in the model. Returns None if no skos:ConceptScheme is present.
[ "Return", "a", "skos", ":", "ConceptScheme", "contained", "in", "the", "model", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/skosify.py#L77-L101
NatLibFi/Skosify
skosify/skosify.py
detect_namespace
def detect_namespace(rdf): """Try to automatically detect the URI namespace of the vocabulary. Return namespace as URIRef. """ # pick a concept conc = rdf.value(None, RDF.type, SKOS.Concept, any=True) if conc is None: logging.critical( "Namespace auto-detection failed. " ...
python
def detect_namespace(rdf): """Try to automatically detect the URI namespace of the vocabulary. Return namespace as URIRef. """ # pick a concept conc = rdf.value(None, RDF.type, SKOS.Concept, any=True) if conc is None: logging.critical( "Namespace auto-detection failed. " ...
[ "def", "detect_namespace", "(", "rdf", ")", ":", "# pick a concept", "conc", "=", "rdf", ".", "value", "(", "None", ",", "RDF", ".", "type", ",", "SKOS", ".", "Concept", ",", "any", "=", "True", ")", "if", "conc", "is", "None", ":", "logging", ".", ...
Try to automatically detect the URI namespace of the vocabulary. Return namespace as URIRef.
[ "Try", "to", "automatically", "detect", "the", "URI", "namespace", "of", "the", "vocabulary", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/skosify.py#L104-L130
NatLibFi/Skosify
skosify/skosify.py
create_concept_scheme
def create_concept_scheme(rdf, ns, lname=''): """Create a skos:ConceptScheme in the model and return it.""" ont = None if not ns: # see if there's an owl:Ontology and use that to determine namespace onts = list(rdf.subjects(RDF.type, OWL.Ontology)) if len(onts) > 1: onts...
python
def create_concept_scheme(rdf, ns, lname=''): """Create a skos:ConceptScheme in the model and return it.""" ont = None if not ns: # see if there's an owl:Ontology and use that to determine namespace onts = list(rdf.subjects(RDF.type, OWL.Ontology)) if len(onts) > 1: onts...
[ "def", "create_concept_scheme", "(", "rdf", ",", "ns", ",", "lname", "=", "''", ")", ":", "ont", "=", "None", "if", "not", "ns", ":", "# see if there's an owl:Ontology and use that to determine namespace", "onts", "=", "list", "(", "rdf", ".", "subjects", "(", ...
Create a skos:ConceptScheme in the model and return it.
[ "Create", "a", "skos", ":", "ConceptScheme", "in", "the", "model", "and", "return", "it", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/skosify.py#L133-L181
NatLibFi/Skosify
skosify/skosify.py
initialize_concept_scheme
def initialize_concept_scheme(rdf, cs, label, language, set_modified): """Initialize a concept scheme: Optionally add a label if the concept scheme doesn't have a label, and optionally add a dct:modified timestamp.""" # check whether the concept scheme is unlabeled, and label it if possible labels ...
python
def initialize_concept_scheme(rdf, cs, label, language, set_modified): """Initialize a concept scheme: Optionally add a label if the concept scheme doesn't have a label, and optionally add a dct:modified timestamp.""" # check whether the concept scheme is unlabeled, and label it if possible labels ...
[ "def", "initialize_concept_scheme", "(", "rdf", ",", "cs", ",", "label", ",", "language", ",", "set_modified", ")", ":", "# check whether the concept scheme is unlabeled, and label it if possible", "labels", "=", "list", "(", "rdf", ".", "objects", "(", "cs", ",", "...
Initialize a concept scheme: Optionally add a label if the concept scheme doesn't have a label, and optionally add a dct:modified timestamp.
[ "Initialize", "a", "concept", "scheme", ":", "Optionally", "add", "a", "label", "if", "the", "concept", "scheme", "doesn", "t", "have", "a", "label", "and", "optionally", "add", "a", "dct", ":", "modified", "timestamp", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/skosify.py#L184-L206
NatLibFi/Skosify
skosify/skosify.py
transform_sparql_update
def transform_sparql_update(rdf, update_query): """Perform a SPARQL Update transformation on the RDF data.""" logging.debug("performing SPARQL Update transformation") if update_query[0] == '@': # actual query should be read from file update_query = file(update_query[1:]).read() logging.debug...
python
def transform_sparql_update(rdf, update_query): """Perform a SPARQL Update transformation on the RDF data.""" logging.debug("performing SPARQL Update transformation") if update_query[0] == '@': # actual query should be read from file update_query = file(update_query[1:]).read() logging.debug...
[ "def", "transform_sparql_update", "(", "rdf", ",", "update_query", ")", ":", "logging", ".", "debug", "(", "\"performing SPARQL Update transformation\"", ")", "if", "update_query", "[", "0", "]", "==", "'@'", ":", "# actual query should be read from file", "update_query...
Perform a SPARQL Update transformation on the RDF data.
[ "Perform", "a", "SPARQL", "Update", "transformation", "on", "the", "RDF", "data", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/skosify.py#L209-L218
NatLibFi/Skosify
skosify/skosify.py
transform_sparql_construct
def transform_sparql_construct(rdf, construct_query): """Perform a SPARQL CONSTRUCT query on the RDF data and return a new graph.""" logging.debug("performing SPARQL CONSTRUCT transformation") if construct_query[0] == '@': # actual query should be read from file construct_query = file(construct_q...
python
def transform_sparql_construct(rdf, construct_query): """Perform a SPARQL CONSTRUCT query on the RDF data and return a new graph.""" logging.debug("performing SPARQL CONSTRUCT transformation") if construct_query[0] == '@': # actual query should be read from file construct_query = file(construct_q...
[ "def", "transform_sparql_construct", "(", "rdf", ",", "construct_query", ")", ":", "logging", ".", "debug", "(", "\"performing SPARQL CONSTRUCT transformation\"", ")", "if", "construct_query", "[", "0", "]", "==", "'@'", ":", "# actual query should be read from file", "...
Perform a SPARQL CONSTRUCT query on the RDF data and return a new graph.
[ "Perform", "a", "SPARQL", "CONSTRUCT", "query", "on", "the", "RDF", "data", "and", "return", "a", "new", "graph", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/skosify.py#L221-L235
NatLibFi/Skosify
skosify/skosify.py
transform_concepts
def transform_concepts(rdf, typemap): """Transform Concepts into new types, as defined by the config file.""" # find out all the types used in the model types = set() for s, o in rdf.subject_objects(RDF.type): if o not in typemap and in_general_ns(o): continue types.add(o) ...
python
def transform_concepts(rdf, typemap): """Transform Concepts into new types, as defined by the config file.""" # find out all the types used in the model types = set() for s, o in rdf.subject_objects(RDF.type): if o not in typemap and in_general_ns(o): continue types.add(o) ...
[ "def", "transform_concepts", "(", "rdf", ",", "typemap", ")", ":", "# find out all the types used in the model", "types", "=", "set", "(", ")", "for", "s", ",", "o", "in", "rdf", ".", "subject_objects", "(", "RDF", ".", "type", ")", ":", "if", "o", "not", ...
Transform Concepts into new types, as defined by the config file.
[ "Transform", "Concepts", "into", "new", "types", "as", "defined", "by", "the", "config", "file", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/skosify.py#L238-L260
NatLibFi/Skosify
skosify/skosify.py
transform_literals
def transform_literals(rdf, literalmap): """Transform literal properties of Concepts, as defined by config file.""" affected_types = (SKOS.Concept, SKOS.Collection, SKOSEXT.DeprecatedConcept) props = set() for t in affected_types: for conc in rdf.subjects(RDF.type, t): ...
python
def transform_literals(rdf, literalmap): """Transform literal properties of Concepts, as defined by config file.""" affected_types = (SKOS.Concept, SKOS.Collection, SKOSEXT.DeprecatedConcept) props = set() for t in affected_types: for conc in rdf.subjects(RDF.type, t): ...
[ "def", "transform_literals", "(", "rdf", ",", "literalmap", ")", ":", "affected_types", "=", "(", "SKOS", ".", "Concept", ",", "SKOS", ".", "Collection", ",", "SKOSEXT", ".", "DeprecatedConcept", ")", "props", "=", "set", "(", ")", "for", "t", "in", "aff...
Transform literal properties of Concepts, as defined by config file.
[ "Transform", "literal", "properties", "of", "Concepts", "as", "defined", "by", "config", "file", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/skosify.py#L263-L285
NatLibFi/Skosify
skosify/skosify.py
transform_relations
def transform_relations(rdf, relationmap): """Transform YSO-style concept relations into SKOS equivalents.""" affected_types = (SKOS.Concept, SKOS.Collection, SKOSEXT.DeprecatedConcept) props = set() for t in affected_types: for conc in rdf.subjects(RDF.type, t): ...
python
def transform_relations(rdf, relationmap): """Transform YSO-style concept relations into SKOS equivalents.""" affected_types = (SKOS.Concept, SKOS.Collection, SKOSEXT.DeprecatedConcept) props = set() for t in affected_types: for conc in rdf.subjects(RDF.type, t): ...
[ "def", "transform_relations", "(", "rdf", ",", "relationmap", ")", ":", "affected_types", "=", "(", "SKOS", ".", "Concept", ",", "SKOS", ".", "Collection", ",", "SKOSEXT", ".", "DeprecatedConcept", ")", "props", "=", "set", "(", ")", "for", "t", "in", "a...
Transform YSO-style concept relations into SKOS equivalents.
[ "Transform", "YSO", "-", "style", "concept", "relations", "into", "SKOS", "equivalents", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/skosify.py#L288-L309
NatLibFi/Skosify
skosify/skosify.py
transform_aggregate_concepts
def transform_aggregate_concepts(rdf, cs, relationmap, aggregates): """Transform YSO-style AggregateConcepts into skos:Concepts within their own skos:ConceptScheme, linked to the regular concepts with SKOS.narrowMatch relationships. If aggregates is False, remove all aggregate concepts instead....
python
def transform_aggregate_concepts(rdf, cs, relationmap, aggregates): """Transform YSO-style AggregateConcepts into skos:Concepts within their own skos:ConceptScheme, linked to the regular concepts with SKOS.narrowMatch relationships. If aggregates is False, remove all aggregate concepts instead....
[ "def", "transform_aggregate_concepts", "(", "rdf", ",", "cs", ",", "relationmap", ",", "aggregates", ")", ":", "if", "not", "aggregates", ":", "logging", ".", "debug", "(", "\"removing aggregate concepts\"", ")", "aggregate_concepts", "=", "[", "]", "relation", ...
Transform YSO-style AggregateConcepts into skos:Concepts within their own skos:ConceptScheme, linked to the regular concepts with SKOS.narrowMatch relationships. If aggregates is False, remove all aggregate concepts instead.
[ "Transform", "YSO", "-", "style", "AggregateConcepts", "into", "skos", ":", "Concepts", "within", "their", "own", "skos", ":", "ConceptScheme", "linked", "to", "the", "regular", "concepts", "with", "SKOS", ".", "narrowMatch", "relationships", ".", "If", "aggrega...
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/skosify.py#L413-L448
NatLibFi/Skosify
skosify/skosify.py
transform_deprecated_concepts
def transform_deprecated_concepts(rdf, cs): """Transform deprecated concepts so they are in their own concept scheme.""" deprecated_concepts = [] for conc in rdf.subjects(RDF.type, SKOSEXT.DeprecatedConcept): rdf.add((conc, RDF.type, SKOS.Concept)) rdf.add((conc, OWL.deprecated, Litera...
python
def transform_deprecated_concepts(rdf, cs): """Transform deprecated concepts so they are in their own concept scheme.""" deprecated_concepts = [] for conc in rdf.subjects(RDF.type, SKOSEXT.DeprecatedConcept): rdf.add((conc, RDF.type, SKOS.Concept)) rdf.add((conc, OWL.deprecated, Litera...
[ "def", "transform_deprecated_concepts", "(", "rdf", ",", "cs", ")", ":", "deprecated_concepts", "=", "[", "]", "for", "conc", "in", "rdf", ".", "subjects", "(", "RDF", ".", "type", ",", "SKOSEXT", ".", "DeprecatedConcept", ")", ":", "rdf", ".", "add", "(...
Transform deprecated concepts so they are in their own concept scheme.
[ "Transform", "deprecated", "concepts", "so", "they", "are", "in", "their", "own", "concept", "scheme", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/skosify.py#L451-L468
NatLibFi/Skosify
skosify/skosify.py
enrich_relations
def enrich_relations(rdf, enrich_mappings, use_narrower, use_transitive): """Enrich the SKOS relations according to SKOS semantics, including subproperties of broader and symmetric related properties. If use_narrower is True, include inverse narrower relations for all broader relations. If use_narrower ...
python
def enrich_relations(rdf, enrich_mappings, use_narrower, use_transitive): """Enrich the SKOS relations according to SKOS semantics, including subproperties of broader and symmetric related properties. If use_narrower is True, include inverse narrower relations for all broader relations. If use_narrower ...
[ "def", "enrich_relations", "(", "rdf", ",", "enrich_mappings", ",", "use_narrower", ",", "use_transitive", ")", ":", "# 1. first enrich mapping relationships (because they affect regular ones)", "if", "enrich_mappings", ":", "infer", ".", "skos_symmetric_mappings", "(", "rdf"...
Enrich the SKOS relations according to SKOS semantics, including subproperties of broader and symmetric related properties. If use_narrower is True, include inverse narrower relations for all broader relations. If use_narrower is False, instead remove all narrower relations, replacing them with inverse ...
[ "Enrich", "the", "SKOS", "relations", "according", "to", "SKOS", "semantics", "including", "subproperties", "of", "broader", "and", "symmetric", "related", "properties", ".", "If", "use_narrower", "is", "True", "include", "inverse", "narrower", "relations", "for", ...
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/skosify.py#L499-L543
NatLibFi/Skosify
skosify/skosify.py
setup_top_concepts
def setup_top_concepts(rdf, mark_top_concepts): """Determine the top concepts of each concept scheme and mark them using hasTopConcept/topConceptOf.""" for cs in sorted(rdf.subjects(RDF.type, SKOS.ConceptScheme)): for conc in sorted(rdf.subjects(SKOS.inScheme, cs)): if (conc, RDF.type, ...
python
def setup_top_concepts(rdf, mark_top_concepts): """Determine the top concepts of each concept scheme and mark them using hasTopConcept/topConceptOf.""" for cs in sorted(rdf.subjects(RDF.type, SKOS.ConceptScheme)): for conc in sorted(rdf.subjects(SKOS.inScheme, cs)): if (conc, RDF.type, ...
[ "def", "setup_top_concepts", "(", "rdf", ",", "mark_top_concepts", ")", ":", "for", "cs", "in", "sorted", "(", "rdf", ".", "subjects", "(", "RDF", ".", "type", ",", "SKOS", ".", "ConceptScheme", ")", ")", ":", "for", "conc", "in", "sorted", "(", "rdf",...
Determine the top concepts of each concept scheme and mark them using hasTopConcept/topConceptOf.
[ "Determine", "the", "top", "concepts", "of", "each", "concept", "scheme", "and", "mark", "them", "using", "hasTopConcept", "/", "topConceptOf", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/skosify.py#L546-L569
NatLibFi/Skosify
skosify/skosify.py
setup_concept_scheme
def setup_concept_scheme(rdf, defaultcs): """Make sure all concepts have an inScheme property, using the given default concept scheme if necessary.""" for conc in rdf.subjects(RDF.type, SKOS.Concept): # check concept scheme cs = rdf.value(conc, SKOS.inScheme, None, any=True) if cs is...
python
def setup_concept_scheme(rdf, defaultcs): """Make sure all concepts have an inScheme property, using the given default concept scheme if necessary.""" for conc in rdf.subjects(RDF.type, SKOS.Concept): # check concept scheme cs = rdf.value(conc, SKOS.inScheme, None, any=True) if cs is...
[ "def", "setup_concept_scheme", "(", "rdf", ",", "defaultcs", ")", ":", "for", "conc", "in", "rdf", ".", "subjects", "(", "RDF", ".", "type", ",", "SKOS", ".", "Concept", ")", ":", "# check concept scheme", "cs", "=", "rdf", ".", "value", "(", "conc", "...
Make sure all concepts have an inScheme property, using the given default concept scheme if necessary.
[ "Make", "sure", "all", "concepts", "have", "an", "inScheme", "property", "using", "the", "given", "default", "concept", "scheme", "if", "necessary", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/skosify.py#L572-L579
NatLibFi/Skosify
skosify/skosify.py
cleanup_classes
def cleanup_classes(rdf): """Remove unnecessary class definitions: definitions of SKOS classes or unused classes. If a class is also a skos:Concept or skos:Collection, remove the 'classness' of it but leave the Concept/Collection.""" for t in (OWL.Class, RDFS.Class): for cl in rdf.subjects...
python
def cleanup_classes(rdf): """Remove unnecessary class definitions: definitions of SKOS classes or unused classes. If a class is also a skos:Concept or skos:Collection, remove the 'classness' of it but leave the Concept/Collection.""" for t in (OWL.Class, RDFS.Class): for cl in rdf.subjects...
[ "def", "cleanup_classes", "(", "rdf", ")", ":", "for", "t", "in", "(", "OWL", ".", "Class", ",", "RDFS", ".", "Class", ")", ":", "for", "cl", "in", "rdf", ".", "subjects", "(", "RDF", ".", "type", ",", "t", ")", ":", "# SKOS classes may be safely rem...
Remove unnecessary class definitions: definitions of SKOS classes or unused classes. If a class is also a skos:Concept or skos:Collection, remove the 'classness' of it but leave the Concept/Collection.
[ "Remove", "unnecessary", "class", "definitions", ":", "definitions", "of", "SKOS", "classes", "or", "unused", "classes", ".", "If", "a", "class", "is", "also", "a", "skos", ":", "Concept", "or", "skos", ":", "Collection", "remove", "the", "classness", "of", ...
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/skosify.py#L582-L613
NatLibFi/Skosify
skosify/skosify.py
cleanup_properties
def cleanup_properties(rdf): """Remove unnecessary property definitions. Reemoves SKOS and DC property definitions and definitions of unused properties.""" for t in (RDF.Property, OWL.DatatypeProperty, OWL.ObjectProperty, OWL.SymmetricProperty, OWL.TransitiveProperty, OWL.In...
python
def cleanup_properties(rdf): """Remove unnecessary property definitions. Reemoves SKOS and DC property definitions and definitions of unused properties.""" for t in (RDF.Property, OWL.DatatypeProperty, OWL.ObjectProperty, OWL.SymmetricProperty, OWL.TransitiveProperty, OWL.In...
[ "def", "cleanup_properties", "(", "rdf", ")", ":", "for", "t", "in", "(", "RDF", ".", "Property", ",", "OWL", ".", "DatatypeProperty", ",", "OWL", ".", "ObjectProperty", ",", "OWL", ".", "SymmetricProperty", ",", "OWL", ".", "TransitiveProperty", ",", "OWL...
Remove unnecessary property definitions. Reemoves SKOS and DC property definitions and definitions of unused properties.
[ "Remove", "unnecessary", "property", "definitions", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/skosify.py#L616-L640
NatLibFi/Skosify
skosify/skosify.py
find_reachable
def find_reachable(rdf, res): """Return the set of reachable resources starting from the given resource, excluding the seen set of resources. Note that the seen set is modified in-place to reflect the ongoing traversal. """ starttime = time.time() # This is almost a non-recursive breadth...
python
def find_reachable(rdf, res): """Return the set of reachable resources starting from the given resource, excluding the seen set of resources. Note that the seen set is modified in-place to reflect the ongoing traversal. """ starttime = time.time() # This is almost a non-recursive breadth...
[ "def", "find_reachable", "(", "rdf", ",", "res", ")", ":", "starttime", "=", "time", ".", "time", "(", ")", "# This is almost a non-recursive breadth-first search algorithm, but a set", "# is used as the \"open\" set instead of a FIFO, and an arbitrary element of", "# the set is se...
Return the set of reachable resources starting from the given resource, excluding the seen set of resources. Note that the seen set is modified in-place to reflect the ongoing traversal.
[ "Return", "the", "set", "of", "reachable", "resources", "starting", "from", "the", "given", "resource", "excluding", "the", "seen", "set", "of", "resources", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/skosify.py#L643-L688
NatLibFi/Skosify
skosify/skosify.py
cleanup_unreachable
def cleanup_unreachable(rdf): """Remove triples which cannot be reached from the concepts by graph traversal.""" all_subjects = set(rdf.subjects()) logging.debug("total subject resources: %d", len(all_subjects)) reachable = find_reachable(rdf, SKOS.Concept) nonreachable = all_subjects - reach...
python
def cleanup_unreachable(rdf): """Remove triples which cannot be reached from the concepts by graph traversal.""" all_subjects = set(rdf.subjects()) logging.debug("total subject resources: %d", len(all_subjects)) reachable = find_reachable(rdf, SKOS.Concept) nonreachable = all_subjects - reach...
[ "def", "cleanup_unreachable", "(", "rdf", ")", ":", "all_subjects", "=", "set", "(", "rdf", ".", "subjects", "(", ")", ")", "logging", ".", "debug", "(", "\"total subject resources: %d\"", ",", "len", "(", "all_subjects", ")", ")", "reachable", "=", "find_re...
Remove triples which cannot be reached from the concepts by graph traversal.
[ "Remove", "triples", "which", "cannot", "be", "reached", "from", "the", "concepts", "by", "graph", "traversal", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/skosify.py#L691-L705
NatLibFi/Skosify
skosify/skosify.py
check_hierarchy
def check_hierarchy(rdf, break_cycles, keep_related, mark_top_concepts, eliminate_redundancy): """Check for, and optionally fix, problems in the skos:broader hierarchy using a recursive depth first search algorithm. :param Graph rdf: An rdflib.graph.Graph object. :param bool fix_cyc...
python
def check_hierarchy(rdf, break_cycles, keep_related, mark_top_concepts, eliminate_redundancy): """Check for, and optionally fix, problems in the skos:broader hierarchy using a recursive depth first search algorithm. :param Graph rdf: An rdflib.graph.Graph object. :param bool fix_cyc...
[ "def", "check_hierarchy", "(", "rdf", ",", "break_cycles", ",", "keep_related", ",", "mark_top_concepts", ",", "eliminate_redundancy", ")", ":", "starttime", "=", "time", ".", "time", "(", ")", "if", "check", ".", "hierarchy_cycles", "(", "rdf", ",", "break_cy...
Check for, and optionally fix, problems in the skos:broader hierarchy using a recursive depth first search algorithm. :param Graph rdf: An rdflib.graph.Graph object. :param bool fix_cycles: Break cycles. :param bool fix_disjoint_relations: Remoe skos:related overlapping with skos:broaderTransit...
[ "Check", "for", "and", "optionally", "fix", "problems", "in", "the", "skos", ":", "broader", "hierarchy", "using", "a", "recursive", "depth", "first", "search", "algorithm", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/skosify.py#L767-L791
NatLibFi/Skosify
skosify/skosify.py
skosify
def skosify(*sources, **config): """Convert, extend, and check SKOS vocabulary.""" cfg = Config() for key in config: if hasattr(cfg, key): setattr(cfg, key, config[key]) config = cfg namespaces = config.namespaces typemap = config.types literalmap = config.literals ...
python
def skosify(*sources, **config): """Convert, extend, and check SKOS vocabulary.""" cfg = Config() for key in config: if hasattr(cfg, key): setattr(cfg, key, config[key]) config = cfg namespaces = config.namespaces typemap = config.types literalmap = config.literals ...
[ "def", "skosify", "(", "*", "sources", ",", "*", "*", "config", ")", ":", "cfg", "=", "Config", "(", ")", "for", "key", "in", "config", ":", "if", "hasattr", "(", "cfg", ",", "key", ")", ":", "setattr", "(", "cfg", ",", "key", ",", "config", "[...
Convert, extend, and check SKOS vocabulary.
[ "Convert", "extend", "and", "check", "SKOS", "vocabulary", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/skosify.py#L794-L898
NatLibFi/Skosify
skosify/config.py
expand_curielike
def expand_curielike(namespaces, curie): """Expand a CURIE (or a CURIE-like string with a period instead of colon as separator) into URIRef. If the provided curie is not a CURIE, return it unchanged.""" if curie == '': return None if sys.version < '3' and not isinstance(curie, type(u'')): ...
python
def expand_curielike(namespaces, curie): """Expand a CURIE (or a CURIE-like string with a period instead of colon as separator) into URIRef. If the provided curie is not a CURIE, return it unchanged.""" if curie == '': return None if sys.version < '3' and not isinstance(curie, type(u'')): ...
[ "def", "expand_curielike", "(", "namespaces", ",", "curie", ")", ":", "if", "curie", "==", "''", ":", "return", "None", "if", "sys", ".", "version", "<", "'3'", "and", "not", "isinstance", "(", "curie", ",", "type", "(", "u''", ")", ")", ":", "# Pyth...
Expand a CURIE (or a CURIE-like string with a period instead of colon as separator) into URIRef. If the provided curie is not a CURIE, return it unchanged.
[ "Expand", "a", "CURIE", "(", "or", "a", "CURIE", "-", "like", "string", "with", "a", "period", "instead", "of", "colon", "as", "separator", ")", "into", "URIRef", ".", "If", "the", "provided", "curie", "is", "not", "a", "CURIE", "return", "it", "unchan...
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/config.py#L147-L173
NatLibFi/Skosify
skosify/config.py
expand_mapping_target
def expand_mapping_target(namespaces, val): """Expand a mapping target, expressed as a comma-separated list of CURIE-like strings potentially prefixed with ^ to express inverse properties, into a list of (uri, inverse) tuples, where uri is a URIRef and inverse is a boolean.""" vals = [v.strip() for...
python
def expand_mapping_target(namespaces, val): """Expand a mapping target, expressed as a comma-separated list of CURIE-like strings potentially prefixed with ^ to express inverse properties, into a list of (uri, inverse) tuples, where uri is a URIRef and inverse is a boolean.""" vals = [v.strip() for...
[ "def", "expand_mapping_target", "(", "namespaces", ",", "val", ")", ":", "vals", "=", "[", "v", ".", "strip", "(", ")", "for", "v", "in", "val", ".", "split", "(", "','", ")", "]", "ret", "=", "[", "]", "for", "v", "in", "vals", ":", "inverse", ...
Expand a mapping target, expressed as a comma-separated list of CURIE-like strings potentially prefixed with ^ to express inverse properties, into a list of (uri, inverse) tuples, where uri is a URIRef and inverse is a boolean.
[ "Expand", "a", "mapping", "target", "expressed", "as", "a", "comma", "-", "separated", "list", "of", "CURIE", "-", "like", "strings", "potentially", "prefixed", "with", "^", "to", "express", "inverse", "properties", "into", "a", "list", "of", "(", "uri", "...
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/config.py#L176-L190
NatLibFi/Skosify
skosify/config.py
Config.read_file
def read_file(self, cfgparser, file): """Read configuration from file.""" if hasattr(file, 'readline'): # we have a file object if sys.version_info >= (3, 2): cfgparser.read_file(file) # Added in Python 3.2 else: cfgparser.readfp(file...
python
def read_file(self, cfgparser, file): """Read configuration from file.""" if hasattr(file, 'readline'): # we have a file object if sys.version_info >= (3, 2): cfgparser.read_file(file) # Added in Python 3.2 else: cfgparser.readfp(file...
[ "def", "read_file", "(", "self", ",", "cfgparser", ",", "file", ")", ":", "if", "hasattr", "(", "file", ",", "'readline'", ")", ":", "# we have a file object", "if", "sys", ".", "version_info", ">=", "(", "3", ",", "2", ")", ":", "cfgparser", ".", "rea...
Read configuration from file.
[ "Read", "configuration", "from", "file", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/config.py#L101-L113
NatLibFi/Skosify
skosify/rdftools/modify.py
replace_subject
def replace_subject(rdf, fromuri, touri): """Replace occurrences of fromuri as subject with touri in given model. If touri=None, will delete all occurrences of fromuri instead. If touri is a list or tuple of URIRefs, all values will be inserted. """ if fromuri == touri: return for p, o...
python
def replace_subject(rdf, fromuri, touri): """Replace occurrences of fromuri as subject with touri in given model. If touri=None, will delete all occurrences of fromuri instead. If touri is a list or tuple of URIRefs, all values will be inserted. """ if fromuri == touri: return for p, o...
[ "def", "replace_subject", "(", "rdf", ",", "fromuri", ",", "touri", ")", ":", "if", "fromuri", "==", "touri", ":", "return", "for", "p", ",", "o", "in", "rdf", ".", "predicate_objects", "(", "fromuri", ")", ":", "rdf", ".", "remove", "(", "(", "fromu...
Replace occurrences of fromuri as subject with touri in given model. If touri=None, will delete all occurrences of fromuri instead. If touri is a list or tuple of URIRefs, all values will be inserted.
[ "Replace", "occurrences", "of", "fromuri", "as", "subject", "with", "touri", "in", "given", "model", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/rdftools/modify.py#L6-L21
NatLibFi/Skosify
skosify/rdftools/modify.py
replace_predicate
def replace_predicate(rdf, fromuri, touri, subjecttypes=None, inverse=False): """Replace occurrences of fromuri as predicate with touri in given model. If touri=None, will delete all occurrences of fromuri instead. If touri is a list or tuple of URIRef, all values will be inserted. If touri is a list o...
python
def replace_predicate(rdf, fromuri, touri, subjecttypes=None, inverse=False): """Replace occurrences of fromuri as predicate with touri in given model. If touri=None, will delete all occurrences of fromuri instead. If touri is a list or tuple of URIRef, all values will be inserted. If touri is a list o...
[ "def", "replace_predicate", "(", "rdf", ",", "fromuri", ",", "touri", ",", "subjecttypes", "=", "None", ",", "inverse", "=", "False", ")", ":", "if", "fromuri", "==", "touri", ":", "return", "for", "s", ",", "o", "in", "rdf", ".", "subject_objects", "(...
Replace occurrences of fromuri as predicate with touri in given model. If touri=None, will delete all occurrences of fromuri instead. If touri is a list or tuple of URIRef, all values will be inserted. If touri is a list of (URIRef, boolean) tuples, the boolean value will be used to determine whether a...
[ "Replace", "occurrences", "of", "fromuri", "as", "predicate", "with", "touri", "in", "given", "model", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/rdftools/modify.py#L24-L59
NatLibFi/Skosify
skosify/rdftools/modify.py
replace_object
def replace_object(rdf, fromuri, touri, predicate=None): """Replace all occurrences of fromuri as object with touri in the given model. If touri=None, will delete all occurrences of fromuri instead. If touri is a list or tuple of URIRef, all values will be inserted. If predicate is given, modify on...
python
def replace_object(rdf, fromuri, touri, predicate=None): """Replace all occurrences of fromuri as object with touri in the given model. If touri=None, will delete all occurrences of fromuri instead. If touri is a list or tuple of URIRef, all values will be inserted. If predicate is given, modify on...
[ "def", "replace_object", "(", "rdf", ",", "fromuri", ",", "touri", ",", "predicate", "=", "None", ")", ":", "if", "fromuri", "==", "touri", ":", "return", "for", "s", ",", "p", "in", "rdf", ".", "subject_predicates", "(", "fromuri", ")", ":", "if", "...
Replace all occurrences of fromuri as object with touri in the given model. If touri=None, will delete all occurrences of fromuri instead. If touri is a list or tuple of URIRef, all values will be inserted. If predicate is given, modify only triples with the given predicate.
[ "Replace", "all", "occurrences", "of", "fromuri", "as", "object", "with", "touri", "in", "the", "given", "model", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/rdftools/modify.py#L62-L81
NatLibFi/Skosify
skosify/rdftools/modify.py
replace_uri
def replace_uri(rdf, fromuri, touri): """Replace all occurrences of fromuri with touri in the given model. If touri is a list or tuple of URIRef, all values will be inserted. If touri=None, will delete all occurrences of fromuri instead. """ replace_subject(rdf, fromuri, touri) replace_predica...
python
def replace_uri(rdf, fromuri, touri): """Replace all occurrences of fromuri with touri in the given model. If touri is a list or tuple of URIRef, all values will be inserted. If touri=None, will delete all occurrences of fromuri instead. """ replace_subject(rdf, fromuri, touri) replace_predica...
[ "def", "replace_uri", "(", "rdf", ",", "fromuri", ",", "touri", ")", ":", "replace_subject", "(", "rdf", ",", "fromuri", ",", "touri", ")", "replace_predicate", "(", "rdf", ",", "fromuri", ",", "touri", ")", "replace_object", "(", "rdf", ",", "fromuri", ...
Replace all occurrences of fromuri with touri in the given model. If touri is a list or tuple of URIRef, all values will be inserted. If touri=None, will delete all occurrences of fromuri instead.
[ "Replace", "all", "occurrences", "of", "fromuri", "with", "touri", "in", "the", "given", "model", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/rdftools/modify.py#L84-L93
NatLibFi/Skosify
skosify/check.py
hierarchy_cycles
def hierarchy_cycles(rdf, fix=False): """Check if the graph contains skos:broader cycles and optionally break these. :param Graph rdf: An rdflib.graph.Graph object. :param bool fix: Fix the problem by removing any skos:broader that overlaps with skos:broaderTransitive. """ top_concepts = so...
python
def hierarchy_cycles(rdf, fix=False): """Check if the graph contains skos:broader cycles and optionally break these. :param Graph rdf: An rdflib.graph.Graph object. :param bool fix: Fix the problem by removing any skos:broader that overlaps with skos:broaderTransitive. """ top_concepts = so...
[ "def", "hierarchy_cycles", "(", "rdf", ",", "fix", "=", "False", ")", ":", "top_concepts", "=", "sorted", "(", "rdf", ".", "subject_objects", "(", "SKOS", ".", "hasTopConcept", ")", ")", "status", "=", "{", "}", "for", "cs", ",", "root", "in", "top_con...
Check if the graph contains skos:broader cycles and optionally break these. :param Graph rdf: An rdflib.graph.Graph object. :param bool fix: Fix the problem by removing any skos:broader that overlaps with skos:broaderTransitive.
[ "Check", "if", "the", "graph", "contains", "skos", ":", "broader", "cycles", "and", "optionally", "break", "these", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/check.py#L37-L58
NatLibFi/Skosify
skosify/check.py
disjoint_relations
def disjoint_relations(rdf, fix=False): """Check if the graph contains concepts connected by both of the semantically disjoint semantic skos:related and skos:broaderTransitive (S27), and optionally remove the involved skos:related relations. :param Graph rdf: An rdflib.graph.Graph object. :param bo...
python
def disjoint_relations(rdf, fix=False): """Check if the graph contains concepts connected by both of the semantically disjoint semantic skos:related and skos:broaderTransitive (S27), and optionally remove the involved skos:related relations. :param Graph rdf: An rdflib.graph.Graph object. :param bo...
[ "def", "disjoint_relations", "(", "rdf", ",", "fix", "=", "False", ")", ":", "for", "conc1", ",", "conc2", "in", "sorted", "(", "rdf", ".", "subject_objects", "(", "SKOS", ".", "related", ")", ")", ":", "if", "conc2", "in", "sorted", "(", "rdf", ".",...
Check if the graph contains concepts connected by both of the semantically disjoint semantic skos:related and skos:broaderTransitive (S27), and optionally remove the involved skos:related relations. :param Graph rdf: An rdflib.graph.Graph object. :param bool fix: Fix the problem by removing skos:relate...
[ "Check", "if", "the", "graph", "contains", "concepts", "connected", "by", "both", "of", "the", "semantically", "disjoint", "semantic", "skos", ":", "related", "and", "skos", ":", "broaderTransitive", "(", "S27", ")", "and", "optionally", "remove", "the", "invo...
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/check.py#L61-L85
NatLibFi/Skosify
skosify/check.py
hierarchical_redundancy
def hierarchical_redundancy(rdf, fix=False): """Check for and optionally remove extraneous skos:broader relations. :param Graph rdf: An rdflib.graph.Graph object. :param bool fix: Fix the problem by removing skos:broader relations between concepts that are otherwise connected by skos:broaderTransit...
python
def hierarchical_redundancy(rdf, fix=False): """Check for and optionally remove extraneous skos:broader relations. :param Graph rdf: An rdflib.graph.Graph object. :param bool fix: Fix the problem by removing skos:broader relations between concepts that are otherwise connected by skos:broaderTransit...
[ "def", "hierarchical_redundancy", "(", "rdf", ",", "fix", "=", "False", ")", ":", "for", "conc", ",", "parent1", "in", "rdf", ".", "subject_objects", "(", "SKOS", ".", "broader", ")", ":", "for", "parent2", "in", "rdf", ".", "objects", "(", "conc", ","...
Check for and optionally remove extraneous skos:broader relations. :param Graph rdf: An rdflib.graph.Graph object. :param bool fix: Fix the problem by removing skos:broader relations between concepts that are otherwise connected by skos:broaderTransitive.
[ "Check", "for", "and", "optionally", "remove", "extraneous", "skos", ":", "broader", "relations", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/check.py#L88-L114
NatLibFi/Skosify
skosify/rdftools/access.py
find_prop_overlap
def find_prop_overlap(rdf, prop1, prop2): """Generate (subject,object) pairs connected by two properties.""" for s, o in sorted(rdf.subject_objects(prop1)): if (s, prop2, o) in rdf: yield (s, o)
python
def find_prop_overlap(rdf, prop1, prop2): """Generate (subject,object) pairs connected by two properties.""" for s, o in sorted(rdf.subject_objects(prop1)): if (s, prop2, o) in rdf: yield (s, o)
[ "def", "find_prop_overlap", "(", "rdf", ",", "prop1", ",", "prop2", ")", ":", "for", "s", ",", "o", "in", "sorted", "(", "rdf", ".", "subject_objects", "(", "prop1", ")", ")", ":", "if", "(", "s", ",", "prop2", ",", "o", ")", "in", "rdf", ":", ...
Generate (subject,object) pairs connected by two properties.
[ "Generate", "(", "subject", "object", ")", "pairs", "connected", "by", "two", "properties", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/rdftools/access.py#L10-L14
NatLibFi/Skosify
skosify/infer.py
skos_related
def skos_related(rdf): """Make sure that skos:related is stated in both directions (S23).""" for s, o in rdf.subject_objects(SKOS.related): rdf.add((o, SKOS.related, s))
python
def skos_related(rdf): """Make sure that skos:related is stated in both directions (S23).""" for s, o in rdf.subject_objects(SKOS.related): rdf.add((o, SKOS.related, s))
[ "def", "skos_related", "(", "rdf", ")", ":", "for", "s", ",", "o", "in", "rdf", ".", "subject_objects", "(", "SKOS", ".", "related", ")", ":", "rdf", ".", "add", "(", "(", "o", ",", "SKOS", ".", "related", ",", "s", ")", ")" ]
Make sure that skos:related is stated in both directions (S23).
[ "Make", "sure", "that", "skos", ":", "related", "is", "stated", "in", "both", "directions", "(", "S23", ")", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/infer.py#L10-L13
NatLibFi/Skosify
skosify/infer.py
skos_topConcept
def skos_topConcept(rdf): """Infer skos:topConceptOf/skos:hasTopConcept (S8) and skos:inScheme (S7).""" for s, o in rdf.subject_objects(SKOS.hasTopConcept): rdf.add((o, SKOS.topConceptOf, s)) for s, o in rdf.subject_objects(SKOS.topConceptOf): rdf.add((o, SKOS.hasTopConcept, s)) for s, o...
python
def skos_topConcept(rdf): """Infer skos:topConceptOf/skos:hasTopConcept (S8) and skos:inScheme (S7).""" for s, o in rdf.subject_objects(SKOS.hasTopConcept): rdf.add((o, SKOS.topConceptOf, s)) for s, o in rdf.subject_objects(SKOS.topConceptOf): rdf.add((o, SKOS.hasTopConcept, s)) for s, o...
[ "def", "skos_topConcept", "(", "rdf", ")", ":", "for", "s", ",", "o", "in", "rdf", ".", "subject_objects", "(", "SKOS", ".", "hasTopConcept", ")", ":", "rdf", ".", "add", "(", "(", "o", ",", "SKOS", ".", "topConceptOf", ",", "s", ")", ")", "for", ...
Infer skos:topConceptOf/skos:hasTopConcept (S8) and skos:inScheme (S7).
[ "Infer", "skos", ":", "topConceptOf", "/", "skos", ":", "hasTopConcept", "(", "S8", ")", "and", "skos", ":", "inScheme", "(", "S7", ")", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/infer.py#L16-L23
NatLibFi/Skosify
skosify/infer.py
skos_hierarchical
def skos_hierarchical(rdf, narrower=True): """Infer skos:broader/skos:narrower (S25) but only keep skos:narrower on request. :param bool narrower: If set to False, skos:narrower will not be added, but rather removed. """ if narrower: for s, o in rdf.subject_objects(SKOS.broader): ...
python
def skos_hierarchical(rdf, narrower=True): """Infer skos:broader/skos:narrower (S25) but only keep skos:narrower on request. :param bool narrower: If set to False, skos:narrower will not be added, but rather removed. """ if narrower: for s, o in rdf.subject_objects(SKOS.broader): ...
[ "def", "skos_hierarchical", "(", "rdf", ",", "narrower", "=", "True", ")", ":", "if", "narrower", ":", "for", "s", ",", "o", "in", "rdf", ".", "subject_objects", "(", "SKOS", ".", "broader", ")", ":", "rdf", ".", "add", "(", "(", "o", ",", "SKOS", ...
Infer skos:broader/skos:narrower (S25) but only keep skos:narrower on request. :param bool narrower: If set to False, skos:narrower will not be added, but rather removed.
[ "Infer", "skos", ":", "broader", "/", "skos", ":", "narrower", "(", "S25", ")", "but", "only", "keep", "skos", ":", "narrower", "on", "request", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/infer.py#L26-L38
NatLibFi/Skosify
skosify/infer.py
skos_transitive
def skos_transitive(rdf, narrower=True): """Perform transitive closure inference (S22, S24).""" for conc in rdf.subjects(RDF.type, SKOS.Concept): for bt in rdf.transitive_objects(conc, SKOS.broader): if bt == conc: continue rdf.add((conc, SKOS.broaderTransitive, b...
python
def skos_transitive(rdf, narrower=True): """Perform transitive closure inference (S22, S24).""" for conc in rdf.subjects(RDF.type, SKOS.Concept): for bt in rdf.transitive_objects(conc, SKOS.broader): if bt == conc: continue rdf.add((conc, SKOS.broaderTransitive, b...
[ "def", "skos_transitive", "(", "rdf", ",", "narrower", "=", "True", ")", ":", "for", "conc", "in", "rdf", ".", "subjects", "(", "RDF", ".", "type", ",", "SKOS", ".", "Concept", ")", ":", "for", "bt", "in", "rdf", ".", "transitive_objects", "(", "conc...
Perform transitive closure inference (S22, S24).
[ "Perform", "transitive", "closure", "inference", "(", "S22", "S24", ")", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/infer.py#L41-L49
NatLibFi/Skosify
skosify/infer.py
skos_symmetric_mappings
def skos_symmetric_mappings(rdf, related=True): """Ensure that the symmetric mapping properties (skos:relatedMatch, skos:closeMatch and skos:exactMatch) are stated in both directions (S44). :param bool related: Add the skos:related super-property for all skos:relatedMatch relations (S41). """ ...
python
def skos_symmetric_mappings(rdf, related=True): """Ensure that the symmetric mapping properties (skos:relatedMatch, skos:closeMatch and skos:exactMatch) are stated in both directions (S44). :param bool related: Add the skos:related super-property for all skos:relatedMatch relations (S41). """ ...
[ "def", "skos_symmetric_mappings", "(", "rdf", ",", "related", "=", "True", ")", ":", "for", "s", ",", "o", "in", "rdf", ".", "subject_objects", "(", "SKOS", ".", "relatedMatch", ")", ":", "rdf", ".", "add", "(", "(", "o", ",", "SKOS", ".", "relatedMa...
Ensure that the symmetric mapping properties (skos:relatedMatch, skos:closeMatch and skos:exactMatch) are stated in both directions (S44). :param bool related: Add the skos:related super-property for all skos:relatedMatch relations (S41).
[ "Ensure", "that", "the", "symmetric", "mapping", "properties", "(", "skos", ":", "relatedMatch", "skos", ":", "closeMatch", "and", "skos", ":", "exactMatch", ")", "are", "stated", "in", "both", "directions", "(", "S44", ")", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/infer.py#L52-L69
NatLibFi/Skosify
skosify/infer.py
skos_hierarchical_mappings
def skos_hierarchical_mappings(rdf, narrower=True): """Infer skos:broadMatch/skos:narrowMatch (S43) and add the super-properties skos:broader/skos:narrower (S41). :param bool narrower: If set to False, skos:narrowMatch will not be added, but rather removed. """ for s, o in rdf.subject_objec...
python
def skos_hierarchical_mappings(rdf, narrower=True): """Infer skos:broadMatch/skos:narrowMatch (S43) and add the super-properties skos:broader/skos:narrower (S41). :param bool narrower: If set to False, skos:narrowMatch will not be added, but rather removed. """ for s, o in rdf.subject_objec...
[ "def", "skos_hierarchical_mappings", "(", "rdf", ",", "narrower", "=", "True", ")", ":", "for", "s", ",", "o", "in", "rdf", ".", "subject_objects", "(", "SKOS", ".", "broadMatch", ")", ":", "rdf", ".", "add", "(", "(", "s", ",", "SKOS", ".", "broader...
Infer skos:broadMatch/skos:narrowMatch (S43) and add the super-properties skos:broader/skos:narrower (S41). :param bool narrower: If set to False, skos:narrowMatch will not be added, but rather removed.
[ "Infer", "skos", ":", "broadMatch", "/", "skos", ":", "narrowMatch", "(", "S43", ")", "and", "add", "the", "super", "-", "properties", "skos", ":", "broader", "/", "skos", ":", "narrower", "(", "S41", ")", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/infer.py#L72-L91
NatLibFi/Skosify
skosify/infer.py
rdfs_classes
def rdfs_classes(rdf): """Perform RDFS subclass inference. Mark all resources with a subclass type with the upper class.""" # find out the subclass mappings upperclasses = {} # key: class val: set([superclass1, superclass2..]) for s, o in rdf.subject_objects(RDFS.subClassOf): upperclasses...
python
def rdfs_classes(rdf): """Perform RDFS subclass inference. Mark all resources with a subclass type with the upper class.""" # find out the subclass mappings upperclasses = {} # key: class val: set([superclass1, superclass2..]) for s, o in rdf.subject_objects(RDFS.subClassOf): upperclasses...
[ "def", "rdfs_classes", "(", "rdf", ")", ":", "# find out the subclass mappings", "upperclasses", "=", "{", "}", "# key: class val: set([superclass1, superclass2..])", "for", "s", ",", "o", "in", "rdf", ".", "subject_objects", "(", "RDFS", ".", "subClassOf", ")", ":"...
Perform RDFS subclass inference. Mark all resources with a subclass type with the upper class.
[ "Perform", "RDFS", "subclass", "inference", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/infer.py#L94-L112
NatLibFi/Skosify
skosify/infer.py
rdfs_properties
def rdfs_properties(rdf): """Perform RDFS subproperty inference. Add superproperties where subproperties have been used.""" # find out the subproperty mappings superprops = {} # key: property val: set([superprop1, superprop2..]) for s, o in rdf.subject_objects(RDFS.subPropertyOf): superpr...
python
def rdfs_properties(rdf): """Perform RDFS subproperty inference. Add superproperties where subproperties have been used.""" # find out the subproperty mappings superprops = {} # key: property val: set([superprop1, superprop2..]) for s, o in rdf.subject_objects(RDFS.subPropertyOf): superpr...
[ "def", "rdfs_properties", "(", "rdf", ")", ":", "# find out the subproperty mappings", "superprops", "=", "{", "}", "# key: property val: set([superprop1, superprop2..])", "for", "s", ",", "o", "in", "rdf", ".", "subject_objects", "(", "RDFS", ".", "subPropertyOf", ")...
Perform RDFS subproperty inference. Add superproperties where subproperties have been used.
[ "Perform", "RDFS", "subproperty", "inference", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/infer.py#L115-L133
stephenmcd/django-overextends
overextends/templatetags/overextends_tags.py
overextends
def overextends(parser, token): """ Extended version of Django's ``extends`` tag that allows circular inheritance to occur, eg a template can both be overridden and extended at once. """ bits = token.split_contents() if len(bits) != 2: raise TemplateSyntaxError("'%s' takes one argume...
python
def overextends(parser, token): """ Extended version of Django's ``extends`` tag that allows circular inheritance to occur, eg a template can both be overridden and extended at once. """ bits = token.split_contents() if len(bits) != 2: raise TemplateSyntaxError("'%s' takes one argume...
[ "def", "overextends", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", "!=", "2", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes one argument\"", "%", "bits", "[", "0", ...
Extended version of Django's ``extends`` tag that allows circular inheritance to occur, eg a template can both be overridden and extended at once.
[ "Extended", "version", "of", "Django", "s", "extends", "tag", "that", "allows", "circular", "inheritance", "to", "occur", "eg", "a", "template", "can", "both", "be", "overridden", "and", "extended", "at", "once", "." ]
train
https://github.com/stephenmcd/django-overextends/blob/5907bc94debd58acbddcbbc542472b9451475431/overextends/templatetags/overextends_tags.py#L136-L150
stephenmcd/django-overextends
overextends/templatetags/overextends_tags.py
OverExtendsNode.find_template
def find_template(self, name, context, peeking=False): """ Replacement for Django's ``find_template`` that uses the current template context to keep track of which template directories it has used when finding a template. This allows multiple templates with the same relative name...
python
def find_template(self, name, context, peeking=False): """ Replacement for Django's ``find_template`` that uses the current template context to keep track of which template directories it has used when finding a template. This allows multiple templates with the same relative name...
[ "def", "find_template", "(", "self", ",", "name", ",", "context", ",", "peeking", "=", "False", ")", ":", "# These imports want settings, which aren't available when this", "# module is imported to ``add_to_builtins``, so do them here.", "from", "django", ".", "conf", "import...
Replacement for Django's ``find_template`` that uses the current template context to keep track of which template directories it has used when finding a template. This allows multiple templates with the same relative name/path to be discovered, so that circular template inheritance can o...
[ "Replacement", "for", "Django", "s", "find_template", "that", "uses", "the", "current", "template", "context", "to", "keep", "track", "of", "which", "template", "directories", "it", "has", "used", "when", "finding", "a", "template", ".", "This", "allows", "mul...
train
https://github.com/stephenmcd/django-overextends/blob/5907bc94debd58acbddcbbc542472b9451475431/overextends/templatetags/overextends_tags.py#L35-L112
stephenmcd/django-overextends
overextends/templatetags/overextends_tags.py
OverExtendsNode.get_parent
def get_parent(self, context): """ Load the parent template using our own ``find_template``, which will cause its absolute path to not be used again. Then peek at the first node, and if its parent arg is the same as the current parent arg, we know circular inheritance is going to...
python
def get_parent(self, context): """ Load the parent template using our own ``find_template``, which will cause its absolute path to not be used again. Then peek at the first node, and if its parent arg is the same as the current parent arg, we know circular inheritance is going to...
[ "def", "get_parent", "(", "self", ",", "context", ")", ":", "parent", "=", "self", ".", "parent_name", ".", "resolve", "(", "context", ")", "# If parent is a template object, just return it.", "if", "hasattr", "(", "parent", ",", "\"render\"", ")", ":", "return"...
Load the parent template using our own ``find_template``, which will cause its absolute path to not be used again. Then peek at the first node, and if its parent arg is the same as the current parent arg, we know circular inheritance is going to occur, in which case we try and find the t...
[ "Load", "the", "parent", "template", "using", "our", "own", "find_template", "which", "will", "cause", "its", "absolute", "path", "to", "not", "be", "used", "again", ".", "Then", "peek", "at", "the", "first", "node", "and", "if", "its", "parent", "arg", ...
train
https://github.com/stephenmcd/django-overextends/blob/5907bc94debd58acbddcbbc542472b9451475431/overextends/templatetags/overextends_tags.py#L114-L132
NatLibFi/Skosify
skosify/cli.py
get_option_parser
def get_option_parser(defaults): """Create and return an OptionParser with the given defaults.""" # based on recipe from: # http://stackoverflow.com/questions/1880404/using-a-file-to-store-optparse-arguments # process command line parameters # e.g. skosify yso.owl -o yso-skos.rdf usage = "Usage...
python
def get_option_parser(defaults): """Create and return an OptionParser with the given defaults.""" # based on recipe from: # http://stackoverflow.com/questions/1880404/using-a-file-to-store-optparse-arguments # process command line parameters # e.g. skosify yso.owl -o yso-skos.rdf usage = "Usage...
[ "def", "get_option_parser", "(", "defaults", ")", ":", "# based on recipe from:", "# http://stackoverflow.com/questions/1880404/using-a-file-to-store-optparse-arguments", "# process command line parameters", "# e.g. skosify yso.owl -o yso-skos.rdf", "usage", "=", "\"Usage: %prog [options] vo...
Create and return an OptionParser with the given defaults.
[ "Create", "and", "return", "an", "OptionParser", "with", "the", "given", "defaults", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/cli.py#L15-L173
NatLibFi/Skosify
skosify/cli.py
main
def main(): """Read command line parameters and make a transform based on them.""" config = Config() # additional options for command line client only defaults = vars(config) defaults['to_format'] = None defaults['output'] = '-' defaults['log'] = None defaults['debug'] = False opt...
python
def main(): """Read command line parameters and make a transform based on them.""" config = Config() # additional options for command line client only defaults = vars(config) defaults['to_format'] = None defaults['output'] = '-' defaults['log'] = None defaults['debug'] = False opt...
[ "def", "main", "(", ")", ":", "config", "=", "Config", "(", ")", "# additional options for command line client only", "defaults", "=", "vars", "(", "config", ")", "defaults", "[", "'to_format'", "]", "=", "None", "defaults", "[", "'output'", "]", "=", "'-'", ...
Read command line parameters and make a transform based on them.
[ "Read", "command", "line", "parameters", "and", "make", "a", "transform", "based", "on", "them", "." ]
train
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/cli.py#L176-L221
decentfox/aioh2
aioh2/protocol.py
H2Protocol.set_handler
def set_handler(self, handler): """ Connect with a coroutine, which is scheduled when connection is made. This function will create a task, and when connection is closed, the task will be canceled. :param handler: :return: None """ if self._handler: ...
python
def set_handler(self, handler): """ Connect with a coroutine, which is scheduled when connection is made. This function will create a task, and when connection is closed, the task will be canceled. :param handler: :return: None """ if self._handler: ...
[ "def", "set_handler", "(", "self", ",", "handler", ")", ":", "if", "self", ".", "_handler", ":", "raise", "Exception", "(", "'Handler was already set'", ")", "if", "handler", ":", "self", ".", "_handler", "=", "async_task", "(", "handler", ",", "loop", "="...
Connect with a coroutine, which is scheduled when connection is made. This function will create a task, and when connection is closed, the task will be canceled. :param handler: :return: None
[ "Connect", "with", "a", "coroutine", "which", "is", "scheduled", "when", "connection", "is", "made", "." ]
train
https://github.com/decentfox/aioh2/blob/2f9b76161e99e32317083cd2ebd17ce2ed3e41ab/aioh2/protocol.py#L371-L383
decentfox/aioh2
aioh2/protocol.py
H2Protocol.start_request
def start_request(self, headers, *, end_stream=False): """ Start a request by sending given headers on a new stream, and return the ID of the new stream. This may block until the underlying transport becomes writable, and the number of concurrent outbound requests (open outbound...
python
def start_request(self, headers, *, end_stream=False): """ Start a request by sending given headers on a new stream, and return the ID of the new stream. This may block until the underlying transport becomes writable, and the number of concurrent outbound requests (open outbound...
[ "def", "start_request", "(", "self", ",", "headers", ",", "*", ",", "end_stream", "=", "False", ")", ":", "yield", "from", "_wait_for_events", "(", "self", ".", "_resumed", ",", "self", ".", "_stream_creatable", ")", "stream_id", "=", "self", ".", "_conn",...
Start a request by sending given headers on a new stream, and return the ID of the new stream. This may block until the underlying transport becomes writable, and the number of concurrent outbound requests (open outbound streams) is less than the value of peer config MAX_CONCURRENT_STRE...
[ "Start", "a", "request", "by", "sending", "given", "headers", "on", "a", "new", "stream", "and", "return", "the", "ID", "of", "the", "new", "stream", "." ]
train
https://github.com/decentfox/aioh2/blob/2f9b76161e99e32317083cd2ebd17ce2ed3e41ab/aioh2/protocol.py#L389-L413
decentfox/aioh2
aioh2/protocol.py
H2Protocol.start_response
def start_response(self, stream_id, headers, *, end_stream=False): """ Start a response by sending given headers on the given stream. This may block until the underlying transport becomes writable. :param stream_id: Which stream to send response on. :param headers: A list of ke...
python
def start_response(self, stream_id, headers, *, end_stream=False): """ Start a response by sending given headers on the given stream. This may block until the underlying transport becomes writable. :param stream_id: Which stream to send response on. :param headers: A list of ke...
[ "def", "start_response", "(", "self", ",", "stream_id", ",", "headers", ",", "*", ",", "end_stream", "=", "False", ")", ":", "yield", "from", "self", ".", "_resumed", ".", "wait", "(", ")", "self", ".", "_conn", ".", "send_headers", "(", "stream_id", "...
Start a response by sending given headers on the given stream. This may block until the underlying transport becomes writable. :param stream_id: Which stream to send response on. :param headers: A list of key-value tuples as headers. :param end_stream: To send a response without body, ...
[ "Start", "a", "response", "by", "sending", "given", "headers", "on", "the", "given", "stream", "." ]
train
https://github.com/decentfox/aioh2/blob/2f9b76161e99e32317083cd2ebd17ce2ed3e41ab/aioh2/protocol.py#L416-L429
decentfox/aioh2
aioh2/protocol.py
H2Protocol.send_data
def send_data(self, stream_id, data, *, end_stream=False): """ Send request or response body on the given stream. This will block until either whole data is sent, or the stream gets closed. Meanwhile, a paused underlying transport or a closed flow control window will also help w...
python
def send_data(self, stream_id, data, *, end_stream=False): """ Send request or response body on the given stream. This will block until either whole data is sent, or the stream gets closed. Meanwhile, a paused underlying transport or a closed flow control window will also help w...
[ "def", "send_data", "(", "self", ",", "stream_id", ",", "data", ",", "*", ",", "end_stream", "=", "False", ")", ":", "try", ":", "with", "(", "yield", "from", "self", ".", "_get_stream", "(", "stream_id", ")", ".", "wlock", ")", ":", "while", "True",...
Send request or response body on the given stream. This will block until either whole data is sent, or the stream gets closed. Meanwhile, a paused underlying transport or a closed flow control window will also help waiting. If the peer increase the flow control window, this method will ...
[ "Send", "request", "or", "response", "body", "on", "the", "given", "stream", "." ]
train
https://github.com/decentfox/aioh2/blob/2f9b76161e99e32317083cd2ebd17ce2ed3e41ab/aioh2/protocol.py#L432-L495
decentfox/aioh2
aioh2/protocol.py
H2Protocol.send_trailers
def send_trailers(self, stream_id, headers): """ Send trailers on the given stream, closing the stream locally. This may block until the underlying transport becomes writable, or other coroutines release the wlock on this stream. :param stream_id: Which stream to send trailers ...
python
def send_trailers(self, stream_id, headers): """ Send trailers on the given stream, closing the stream locally. This may block until the underlying transport becomes writable, or other coroutines release the wlock on this stream. :param stream_id: Which stream to send trailers ...
[ "def", "send_trailers", "(", "self", ",", "stream_id", ",", "headers", ")", ":", "with", "(", "yield", "from", "self", ".", "_get_stream", "(", "stream_id", ")", ".", "wlock", ")", ":", "yield", "from", "self", ".", "_resumed", ".", "wait", "(", ")", ...
Send trailers on the given stream, closing the stream locally. This may block until the underlying transport becomes writable, or other coroutines release the wlock on this stream. :param stream_id: Which stream to send trailers on. :param headers: A list of key-value tuples as trailer...
[ "Send", "trailers", "on", "the", "given", "stream", "closing", "the", "stream", "locally", "." ]
train
https://github.com/decentfox/aioh2/blob/2f9b76161e99e32317083cd2ebd17ce2ed3e41ab/aioh2/protocol.py#L498-L511
decentfox/aioh2
aioh2/protocol.py
H2Protocol.end_stream
def end_stream(self, stream_id): """ Close the given stream locally. This may block until the underlying transport becomes writable, or other coroutines release the wlock on this stream. :param stream_id: Which stream to close. """ with (yield from self._get_str...
python
def end_stream(self, stream_id): """ Close the given stream locally. This may block until the underlying transport becomes writable, or other coroutines release the wlock on this stream. :param stream_id: Which stream to close. """ with (yield from self._get_str...
[ "def", "end_stream", "(", "self", ",", "stream_id", ")", ":", "with", "(", "yield", "from", "self", ".", "_get_stream", "(", "stream_id", ")", ".", "wlock", ")", ":", "yield", "from", "self", ".", "_resumed", ".", "wait", "(", ")", "self", ".", "_con...
Close the given stream locally. This may block until the underlying transport becomes writable, or other coroutines release the wlock on this stream. :param stream_id: Which stream to close.
[ "Close", "the", "given", "stream", "locally", "." ]
train
https://github.com/decentfox/aioh2/blob/2f9b76161e99e32317083cd2ebd17ce2ed3e41ab/aioh2/protocol.py#L514-L526
decentfox/aioh2
aioh2/protocol.py
H2Protocol.read_stream
def read_stream(self, stream_id, size=None): """ Read data from the given stream. By default (`size=None`), this returns all data left in current HTTP/2 frame. In other words, default behavior is to receive frame by frame. If size is given a number above zero, method will try t...
python
def read_stream(self, stream_id, size=None): """ Read data from the given stream. By default (`size=None`), this returns all data left in current HTTP/2 frame. In other words, default behavior is to receive frame by frame. If size is given a number above zero, method will try t...
[ "def", "read_stream", "(", "self", ",", "stream_id", ",", "size", "=", "None", ")", ":", "rv", "=", "[", "]", "try", ":", "with", "(", "yield", "from", "self", ".", "_get_stream", "(", "stream_id", ")", ".", "rlock", ")", ":", "if", "size", "is", ...
Read data from the given stream. By default (`size=None`), this returns all data left in current HTTP/2 frame. In other words, default behavior is to receive frame by frame. If size is given a number above zero, method will try to return as much bytes as possible up to the given size, ...
[ "Read", "data", "from", "the", "given", "stream", "." ]
train
https://github.com/decentfox/aioh2/blob/2f9b76161e99e32317083cd2ebd17ce2ed3e41ab/aioh2/protocol.py#L561-L615
decentfox/aioh2
aioh2/protocol.py
H2Protocol.wait_functional
def wait_functional(self): """ Wait until the connection becomes functional. The connection is count functional if it was active within last few seconds (defined by `functional_timeout`), where a newly-made connection and received data indicate activeness. :return: Most...
python
def wait_functional(self): """ Wait until the connection becomes functional. The connection is count functional if it was active within last few seconds (defined by `functional_timeout`), where a newly-made connection and received data indicate activeness. :return: Most...
[ "def", "wait_functional", "(", "self", ")", ":", "while", "not", "self", ".", "_is_functional", "(", ")", ":", "self", ".", "_rtt", "=", "None", "self", ".", "_ping_index", "+=", "1", "self", ".", "_ping_time", "=", "self", ".", "_loop", ".", "time", ...
Wait until the connection becomes functional. The connection is count functional if it was active within last few seconds (defined by `functional_timeout`), where a newly-made connection and received data indicate activeness. :return: Most recently calculated round-trip time if any.
[ "Wait", "until", "the", "connection", "becomes", "functional", "." ]
train
https://github.com/decentfox/aioh2/blob/2f9b76161e99e32317083cd2ebd17ce2ed3e41ab/aioh2/protocol.py#L622-L643
decentfox/aioh2
aioh2/protocol.py
H2Protocol.reprioritize
def reprioritize(self, stream_id, depends_on=None, weight=16, exclusive=False): """ Update the priority status of an existing stream. :param stream_id: The stream ID of the stream being updated. :param depends_on: (optional) The ID of the stream that the stream now ...
python
def reprioritize(self, stream_id, depends_on=None, weight=16, exclusive=False): """ Update the priority status of an existing stream. :param stream_id: The stream ID of the stream being updated. :param depends_on: (optional) The ID of the stream that the stream now ...
[ "def", "reprioritize", "(", "self", ",", "stream_id", ",", "depends_on", "=", "None", ",", "weight", "=", "16", ",", "exclusive", "=", "False", ")", ":", "self", ".", "_priority", ".", "reprioritize", "(", "stream_id", ",", "depends_on", ",", "weight", "...
Update the priority status of an existing stream. :param stream_id: The stream ID of the stream being updated. :param depends_on: (optional) The ID of the stream that the stream now depends on. If ``None``, will be moved to depend on stream 0. :param weight: (optional) The new weigh...
[ "Update", "the", "priority", "status", "of", "an", "existing", "stream", "." ]
train
https://github.com/decentfox/aioh2/blob/2f9b76161e99e32317083cd2ebd17ce2ed3e41ab/aioh2/protocol.py#L645-L658
muccg/django-iprestrict
iprestrict/decorators.py
superuser_required
def superuser_required(view_func=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='admin:login'): """ Decorator for views that checks that the user is logged in and is a superuser member, redirecting to the login page if necessary. """ actual_decorator = user_passes_te...
python
def superuser_required(view_func=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='admin:login'): """ Decorator for views that checks that the user is logged in and is a superuser member, redirecting to the login page if necessary. """ actual_decorator = user_passes_te...
[ "def", "superuser_required", "(", "view_func", "=", "None", ",", "redirect_field_name", "=", "REDIRECT_FIELD_NAME", ",", "login_url", "=", "'admin:login'", ")", ":", "actual_decorator", "=", "user_passes_test", "(", "lambda", "u", ":", "u", ".", "is_active", "and"...
Decorator for views that checks that the user is logged in and is a superuser member, redirecting to the login page if necessary.
[ "Decorator", "for", "views", "that", "checks", "that", "the", "user", "is", "logged", "in", "and", "is", "a", "superuser", "member", "redirecting", "to", "the", "login", "page", "if", "necessary", "." ]
train
https://github.com/muccg/django-iprestrict/blob/f5ea013b7b856866c7164df146f1e205772677db/iprestrict/decorators.py#L7-L20
henriquebastos/django-aggregate-if
aggregate_if.py
SqlAggregate._condition_as_sql
def _condition_as_sql(self, qn, connection): ''' Return sql for condition. ''' def escape(value): if isinstance(value, bool): value = str(int(value)) if isinstance(value, six.string_types): # Escape params used with LIKE ...
python
def _condition_as_sql(self, qn, connection): ''' Return sql for condition. ''' def escape(value): if isinstance(value, bool): value = str(int(value)) if isinstance(value, six.string_types): # Escape params used with LIKE ...
[ "def", "_condition_as_sql", "(", "self", ",", "qn", ",", "connection", ")", ":", "def", "escape", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "bool", ")", ":", "value", "=", "str", "(", "int", "(", "value", ")", ")", "if", "isins...
Return sql for condition.
[ "Return", "sql", "for", "condition", "." ]
train
https://github.com/henriquebastos/django-aggregate-if/blob/588c1487bc88a8996d4ee9c2c9d50fa4a4484872/aggregate_if.py#L54-L75
karimbahgat/Pytess
pytess/tesselator.py
computeVoronoiDiagram
def computeVoronoiDiagram(points): """ Takes a list of point objects (which must have x and y fields). Returns a 3-tuple of: (1) a list of 2-tuples, which are the x,y coordinates of the Voronoi diagram vertices (2) a list of 3-tuples (a,b,c) which are the equations of ...
python
def computeVoronoiDiagram(points): """ Takes a list of point objects (which must have x and y fields). Returns a 3-tuple of: (1) a list of 2-tuples, which are the x,y coordinates of the Voronoi diagram vertices (2) a list of 3-tuples (a,b,c) which are the equations of ...
[ "def", "computeVoronoiDiagram", "(", "points", ")", ":", "siteList", "=", "SiteList", "(", "points", ")", "context", "=", "Context", "(", ")", "voronoi", "(", "siteList", ",", "context", ")", "return", "(", "context", ".", "vertices", ",", "context", ".", ...
Takes a list of point objects (which must have x and y fields). Returns a 3-tuple of: (1) a list of 2-tuples, which are the x,y coordinates of the Voronoi diagram vertices (2) a list of 3-tuples (a,b,c) which are the equations of the lines in the Voronoi dia...
[ "Takes", "a", "list", "of", "point", "objects", "(", "which", "must", "have", "x", "and", "y", "fields", ")", ".", "Returns", "a", "3", "-", "tuple", "of", ":" ]
train
https://github.com/karimbahgat/Pytess/blob/026d0c6bfc281361d850d9a44af1da6fed45b170/pytess/tesselator.py#L772-L788
karimbahgat/Pytess
pytess/tesselator.py
computeDelaunayTriangulation
def computeDelaunayTriangulation(points): """ Takes a list of point objects (which must have x and y fields). Returns a list of 3-tuples: the indices of the points that form a Delaunay triangle. """ siteList = SiteList(points) context = Context() context.triangulate = True voron...
python
def computeDelaunayTriangulation(points): """ Takes a list of point objects (which must have x and y fields). Returns a list of 3-tuples: the indices of the points that form a Delaunay triangle. """ siteList = SiteList(points) context = Context() context.triangulate = True voron...
[ "def", "computeDelaunayTriangulation", "(", "points", ")", ":", "siteList", "=", "SiteList", "(", "points", ")", "context", "=", "Context", "(", ")", "context", ".", "triangulate", "=", "True", "voronoi", "(", "siteList", ",", "context", ")", "return", "cont...
Takes a list of point objects (which must have x and y fields). Returns a list of 3-tuples: the indices of the points that form a Delaunay triangle.
[ "Takes", "a", "list", "of", "point", "objects", "(", "which", "must", "have", "x", "and", "y", "fields", ")", ".", "Returns", "a", "list", "of", "3", "-", "tuples", ":", "the", "indices", "of", "the", "points", "that", "form", "a", "Delaunay", "trian...
train
https://github.com/karimbahgat/Pytess/blob/026d0c6bfc281361d850d9a44af1da6fed45b170/pytess/tesselator.py#L791-L800
Exirel/pylint-json2html
pylint_json2html/__init__.py
build_messages_metrics
def build_messages_metrics(messages): """Build reports's metrics""" count_types = collections.Counter( line.get('type') or None for line in messages) count_modules = collections.Counter( line.get('module') or None for line in messages) count_symbols = collections.Counter(...
python
def build_messages_metrics(messages): """Build reports's metrics""" count_types = collections.Counter( line.get('type') or None for line in messages) count_modules = collections.Counter( line.get('module') or None for line in messages) count_symbols = collections.Counter(...
[ "def", "build_messages_metrics", "(", "messages", ")", ":", "count_types", "=", "collections", ".", "Counter", "(", "line", ".", "get", "(", "'type'", ")", "or", "None", "for", "line", "in", "messages", ")", "count_modules", "=", "collections", ".", "Counter...
Build reports's metrics
[ "Build", "reports", "s", "metrics" ]
train
https://github.com/Exirel/pylint-json2html/blob/7acdb4b7ea2f82a39a67d8ed3a43839c91cc423b/pylint_json2html/__init__.py#L26-L46
Exirel/pylint-json2html
pylint_json2html/__init__.py
build_messages_modules
def build_messages_modules(messages): """Build and yield sorted list of messages per module. :param list messages: List of dict of messages :return: Tuple of 2 values: first is the module info, second is the list of messages sorted by line number """ data = collections.defaultdict(list...
python
def build_messages_modules(messages): """Build and yield sorted list of messages per module. :param list messages: List of dict of messages :return: Tuple of 2 values: first is the module info, second is the list of messages sorted by line number """ data = collections.defaultdict(list...
[ "def", "build_messages_modules", "(", "messages", ")", ":", "data", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "line", "in", "messages", ":", "module_name", "=", "line", ".", "get", "(", "'module'", ")", "module_path", "=", "line", "....
Build and yield sorted list of messages per module. :param list messages: List of dict of messages :return: Tuple of 2 values: first is the module info, second is the list of messages sorted by line number
[ "Build", "and", "yield", "sorted", "list", "of", "messages", "per", "module", "." ]
train
https://github.com/Exirel/pylint-json2html/blob/7acdb4b7ea2f82a39a67d8ed3a43839c91cc423b/pylint_json2html/__init__.py#L49-L69
Exirel/pylint-json2html
pylint_json2html/__init__.py
stats_evaluation
def stats_evaluation(stats): """Generate an evaluation for the given pylint ``stats``.""" statement = stats.get('statement') error = stats.get('error', 0) warning = stats.get('warning', 0) refactor = stats.get('refactor', 0) convention = stats.get('convention', 0) if not statement or statem...
python
def stats_evaluation(stats): """Generate an evaluation for the given pylint ``stats``.""" statement = stats.get('statement') error = stats.get('error', 0) warning = stats.get('warning', 0) refactor = stats.get('refactor', 0) convention = stats.get('convention', 0) if not statement or statem...
[ "def", "stats_evaluation", "(", "stats", ")", ":", "statement", "=", "stats", ".", "get", "(", "'statement'", ")", "error", "=", "stats", ".", "get", "(", "'error'", ",", "0", ")", "warning", "=", "stats", ".", "get", "(", "'warning'", ",", "0", ")",...
Generate an evaluation for the given pylint ``stats``.
[ "Generate", "an", "evaluation", "for", "the", "given", "pylint", "stats", "." ]
train
https://github.com/Exirel/pylint-json2html/blob/7acdb4b7ea2f82a39a67d8ed3a43839c91cc423b/pylint_json2html/__init__.py#L72-L85
Exirel/pylint-json2html
pylint_json2html/__init__.py
build_command_parser
def build_command_parser(): """Build command parser using ``argparse`` module.""" parser = argparse.ArgumentParser( description='Transform Pylint JSON report to HTML') parser.add_argument( 'filename', metavar='FILENAME', type=argparse.FileType('r'), nargs='?', ...
python
def build_command_parser(): """Build command parser using ``argparse`` module.""" parser = argparse.ArgumentParser( description='Transform Pylint JSON report to HTML') parser.add_argument( 'filename', metavar='FILENAME', type=argparse.FileType('r'), nargs='?', ...
[ "def", "build_command_parser", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Transform Pylint JSON report to HTML'", ")", "parser", ".", "add_argument", "(", "'filename'", ",", "metavar", "=", "'FILENAME'", ",", "type", ...
Build command parser using ``argparse`` module.
[ "Build", "command", "parser", "using", "argparse", "module", "." ]
train
https://github.com/Exirel/pylint-json2html/blob/7acdb4b7ea2f82a39a67d8ed3a43839c91cc423b/pylint_json2html/__init__.py#L207-L233
Exirel/pylint-json2html
pylint_json2html/__init__.py
main
def main(): """Pylint JSON to HTML Main Entry Point""" parser = build_command_parser() options = parser.parse_args() file_pointer = options.filename input_format = options.input_format with file_pointer: json_data = json.load(file_pointer) if input_format == SIMPLE_JSON: re...
python
def main(): """Pylint JSON to HTML Main Entry Point""" parser = build_command_parser() options = parser.parse_args() file_pointer = options.filename input_format = options.input_format with file_pointer: json_data = json.load(file_pointer) if input_format == SIMPLE_JSON: re...
[ "def", "main", "(", ")", ":", "parser", "=", "build_command_parser", "(", ")", "options", "=", "parser", ".", "parse_args", "(", ")", "file_pointer", "=", "options", ".", "filename", "input_format", "=", "options", ".", "input_format", "with", "file_pointer", ...
Pylint JSON to HTML Main Entry Point
[ "Pylint", "JSON", "to", "HTML", "Main", "Entry", "Point" ]
train
https://github.com/Exirel/pylint-json2html/blob/7acdb4b7ea2f82a39a67d8ed3a43839c91cc423b/pylint_json2html/__init__.py#L236-L254
Exirel/pylint-json2html
pylint_json2html/__init__.py
Report.render
def render(self): """Render report to HTML""" template = self.get_template() return template.render( messages=self._messages, metrics=self.metrics, report=self)
python
def render(self): """Render report to HTML""" template = self.get_template() return template.render( messages=self._messages, metrics=self.metrics, report=self)
[ "def", "render", "(", "self", ")", ":", "template", "=", "self", ".", "get_template", "(", ")", "return", "template", ".", "render", "(", "messages", "=", "self", ".", "_messages", ",", "metrics", "=", "self", ".", "metrics", ",", "report", "=", "self"...
Render report to HTML
[ "Render", "report", "to", "HTML" ]
train
https://github.com/Exirel/pylint-json2html/blob/7acdb4b7ea2f82a39a67d8ed3a43839c91cc423b/pylint_json2html/__init__.py#L118-L124
Exirel/pylint-json2html
pylint_json2html/__init__.py
JsonExtendedReporter.handle_message
def handle_message(self, msg): """Store new message for later use. .. seealso:: :meth:`~JsonExtendedReporter.on_close` """ self._messages.append({ 'type': msg.category, 'module': msg.module, 'obj': msg.obj, 'line': msg.line, 'c...
python
def handle_message(self, msg): """Store new message for later use. .. seealso:: :meth:`~JsonExtendedReporter.on_close` """ self._messages.append({ 'type': msg.category, 'module': msg.module, 'obj': msg.obj, 'line': msg.line, 'c...
[ "def", "handle_message", "(", "self", ",", "msg", ")", ":", "self", ".", "_messages", ".", "append", "(", "{", "'type'", ":", "msg", ".", "category", ",", "'module'", ":", "msg", ".", "module", ",", "'obj'", ":", "msg", ".", "obj", ",", "'line'", "...
Store new message for later use. .. seealso:: :meth:`~JsonExtendedReporter.on_close`
[ "Store", "new", "message", "for", "later", "use", "." ]
train
https://github.com/Exirel/pylint-json2html/blob/7acdb4b7ea2f82a39a67d8ed3a43839c91cc423b/pylint_json2html/__init__.py#L157-L172
Exirel/pylint-json2html
pylint_json2html/__init__.py
JsonExtendedReporter.on_close
def on_close(self, stats, previous_stats): """Print the extended JSON report to reporter's output. :param dict stats: Metrics for the current pylint run :param dict previous_stats: Metrics for the previous pylint run """ reports = { 'messages': self._messages, ...
python
def on_close(self, stats, previous_stats): """Print the extended JSON report to reporter's output. :param dict stats: Metrics for the current pylint run :param dict previous_stats: Metrics for the previous pylint run """ reports = { 'messages': self._messages, ...
[ "def", "on_close", "(", "self", ",", "stats", ",", "previous_stats", ")", ":", "reports", "=", "{", "'messages'", ":", "self", ".", "_messages", ",", "'stats'", ":", "stats", ",", "'previous'", ":", "previous_stats", ",", "}", "print", "(", "json", ".", ...
Print the extended JSON report to reporter's output. :param dict stats: Metrics for the current pylint run :param dict previous_stats: Metrics for the previous pylint run
[ "Print", "the", "extended", "JSON", "report", "to", "reporter", "s", "output", "." ]
train
https://github.com/Exirel/pylint-json2html/blob/7acdb4b7ea2f82a39a67d8ed3a43839c91cc423b/pylint_json2html/__init__.py#L188-L199
karimbahgat/Pytess
pytess/main.py
triangulate
def triangulate(points): """ Connects an input list of xy tuples with lines forming a set of smallest possible Delauney triangles between them. Arguments: - **points**: A list of xy or xyz point tuples to triangulate. Returns: - A list of triangle polygons. If the input coordinate po...
python
def triangulate(points): """ Connects an input list of xy tuples with lines forming a set of smallest possible Delauney triangles between them. Arguments: - **points**: A list of xy or xyz point tuples to triangulate. Returns: - A list of triangle polygons. If the input coordinate po...
[ "def", "triangulate", "(", "points", ")", ":", "# Remove duplicate xy points bc that would make delauney fail, and must remember z (if any) for retrieving originals from index results", "seen", "=", "set", "(", ")", "uniqpoints", "=", "[", "p", "for", "p", "in", "points", "if...
Connects an input list of xy tuples with lines forming a set of smallest possible Delauney triangles between them. Arguments: - **points**: A list of xy or xyz point tuples to triangulate. Returns: - A list of triangle polygons. If the input coordinate points contained a third z value ...
[ "Connects", "an", "input", "list", "of", "xy", "tuples", "with", "lines", "forming", "a", "set", "of", "smallest", "possible", "Delauney", "triangles", "between", "them", "." ]
train
https://github.com/karimbahgat/Pytess/blob/026d0c6bfc281361d850d9a44af1da6fed45b170/pytess/main.py#L20-L46
karimbahgat/Pytess
pytess/main.py
voronoi
def voronoi(points, buffer_percent=100): """ Surrounds each point in an input list of xy tuples with a unique Voronoi polygon. Arguments: - **points**: A list of xy or xyz point tuples to triangulate. - **buffer_percent** (optional): Controls how much bigger than the original bbox...
python
def voronoi(points, buffer_percent=100): """ Surrounds each point in an input list of xy tuples with a unique Voronoi polygon. Arguments: - **points**: A list of xy or xyz point tuples to triangulate. - **buffer_percent** (optional): Controls how much bigger than the original bbox...
[ "def", "voronoi", "(", "points", ",", "buffer_percent", "=", "100", ")", ":", "# Remove duplicate xy points bc that would make delauney fail, and must remember z (if any) for retrieving originals from index results", "seen", "=", "set", "(", ")", "uniqpoints", "=", "[", "p", ...
Surrounds each point in an input list of xy tuples with a unique Voronoi polygon. Arguments: - **points**: A list of xy or xyz point tuples to triangulate. - **buffer_percent** (optional): Controls how much bigger than the original bbox of the input points to set the bbox of fake points, ...
[ "Surrounds", "each", "point", "in", "an", "input", "list", "of", "xy", "tuples", "with", "a", "unique", "Voronoi", "polygon", "." ]
train
https://github.com/karimbahgat/Pytess/blob/026d0c6bfc281361d850d9a44af1da6fed45b170/pytess/main.py#L48-L117
ecordell/pymacaroons
pymacaroons/utils.py
equals
def equals(val1, val2): """ Returns True if the two strings are equal, False otherwise. The time taken is independent of the number of characters that match. For the sake of simplicity, this function executes in constant time only when the two strings have the same length. It short-circuits when t...
python
def equals(val1, val2): """ Returns True if the two strings are equal, False otherwise. The time taken is independent of the number of characters that match. For the sake of simplicity, this function executes in constant time only when the two strings have the same length. It short-circuits when t...
[ "def", "equals", "(", "val1", ",", "val2", ")", ":", "if", "len", "(", "val1", ")", "!=", "len", "(", "val2", ")", ":", "return", "False", "result", "=", "0", "for", "x", ",", "y", "in", "zip", "(", "val1", ",", "val2", ")", ":", "result", "|...
Returns True if the two strings are equal, False otherwise. The time taken is independent of the number of characters that match. For the sake of simplicity, this function executes in constant time only when the two strings have the same length. It short-circuits when they have different lengths.
[ "Returns", "True", "if", "the", "two", "strings", "are", "equal", "False", "otherwise", "." ]
train
https://github.com/ecordell/pymacaroons/blob/c941614df15fe732ea432a62788e45410bcb868d/pymacaroons/utils.py#L80-L95
ecordell/pymacaroons
pymacaroons/serializers/binary_serializer.py
_encode_uvarint
def _encode_uvarint(data, n): ''' Encodes integer into variable-length format into data.''' if n < 0: raise ValueError('only support positive integer') while True: this_byte = n & 0x7f n >>= 7 if n == 0: data.append(this_byte) break data.append...
python
def _encode_uvarint(data, n): ''' Encodes integer into variable-length format into data.''' if n < 0: raise ValueError('only support positive integer') while True: this_byte = n & 0x7f n >>= 7 if n == 0: data.append(this_byte) break data.append...
[ "def", "_encode_uvarint", "(", "data", ",", "n", ")", ":", "if", "n", "<", "0", ":", "raise", "ValueError", "(", "'only support positive integer'", ")", "while", "True", ":", "this_byte", "=", "n", "&", "0x7f", "n", ">>=", "7", "if", "n", "==", "0", ...
Encodes integer into variable-length format into data.
[ "Encodes", "integer", "into", "variable", "-", "length", "format", "into", "data", "." ]
train
https://github.com/ecordell/pymacaroons/blob/c941614df15fe732ea432a62788e45410bcb868d/pymacaroons/serializers/binary_serializer.py#L301-L311
ecordell/pymacaroons
pymacaroons/serializers/binary_serializer.py
BinarySerializer._parse_section_v2
def _parse_section_v2(self, data): ''' Parses a sequence of packets in data. The sequence is terminated by a packet with a field type of EOS :param data bytes to be deserialized. :return: the rest of data and an array of packet V2 ''' from pymacaroons.exceptions import ...
python
def _parse_section_v2(self, data): ''' Parses a sequence of packets in data. The sequence is terminated by a packet with a field type of EOS :param data bytes to be deserialized. :return: the rest of data and an array of packet V2 ''' from pymacaroons.exceptions import ...
[ "def", "_parse_section_v2", "(", "self", ",", "data", ")", ":", "from", "pymacaroons", ".", "exceptions", "import", "MacaroonDeserializationException", "prev_field_type", "=", "-", "1", "packets", "=", "[", "]", "while", "True", ":", "if", "len", "(", "data", ...
Parses a sequence of packets in data. The sequence is terminated by a packet with a field type of EOS :param data bytes to be deserialized. :return: the rest of data and an array of packet V2
[ "Parses", "a", "sequence", "of", "packets", "in", "data", "." ]
train
https://github.com/ecordell/pymacaroons/blob/c941614df15fe732ea432a62788e45410bcb868d/pymacaroons/serializers/binary_serializer.py#L249-L272
ecordell/pymacaroons
pymacaroons/serializers/binary_serializer.py
BinarySerializer._parse_packet_v2
def _parse_packet_v2(self, data): ''' Parses a V2 data packet at the start of the given data. The format of a packet is as follows: field_type(varint) payload_len(varint) data[payload_len bytes] apart from EOS which has no payload_en or data (it's a single zero byte). ...
python
def _parse_packet_v2(self, data): ''' Parses a V2 data packet at the start of the given data. The format of a packet is as follows: field_type(varint) payload_len(varint) data[payload_len bytes] apart from EOS which has no payload_en or data (it's a single zero byte). ...
[ "def", "_parse_packet_v2", "(", "self", ",", "data", ")", ":", "from", "pymacaroons", ".", "exceptions", "import", "MacaroonDeserializationException", "ft", ",", "n", "=", "_decode_uvarint", "(", "data", ")", "data", "=", "data", "[", "n", ":", "]", "if", ...
Parses a V2 data packet at the start of the given data. The format of a packet is as follows: field_type(varint) payload_len(varint) data[payload_len bytes] apart from EOS which has no payload_en or data (it's a single zero byte). :param data: :return: rest of data, P...
[ "Parses", "a", "V2", "data", "packet", "at", "the", "start", "of", "the", "given", "data", "." ]
train
https://github.com/ecordell/pymacaroons/blob/c941614df15fe732ea432a62788e45410bcb868d/pymacaroons/serializers/binary_serializer.py#L274-L298
ecordell/pymacaroons
pymacaroons/macaroon.py
Macaroon.prepare_for_request
def prepare_for_request(self, discharge_macaroon): ''' Return a new discharge macaroon bound to the receiving macaroon's current signature so that it can be used in a request. This must be done before a discharge macaroon is sent to a server. :param discharge_macaroon: :return:...
python
def prepare_for_request(self, discharge_macaroon): ''' Return a new discharge macaroon bound to the receiving macaroon's current signature so that it can be used in a request. This must be done before a discharge macaroon is sent to a server. :param discharge_macaroon: :return:...
[ "def", "prepare_for_request", "(", "self", ",", "discharge_macaroon", ")", ":", "protected", "=", "discharge_macaroon", ".", "copy", "(", ")", "return", "HashSignaturesBinder", "(", "self", ")", ".", "bind", "(", "protected", ")" ]
Return a new discharge macaroon bound to the receiving macaroon's current signature so that it can be used in a request. This must be done before a discharge macaroon is sent to a server. :param discharge_macaroon: :return: bound discharge macaroon
[ "Return", "a", "new", "discharge", "macaroon", "bound", "to", "the", "receiving", "macaroon", "s", "current", "signature", "so", "that", "it", "can", "be", "used", "in", "a", "request", "." ]
train
https://github.com/ecordell/pymacaroons/blob/c941614df15fe732ea432a62788e45410bcb868d/pymacaroons/macaroon.py#L129-L139
ecordell/pymacaroons
pymacaroons/serializers/json_serializer.py
_caveat_v1_to_dict
def _caveat_v1_to_dict(c): ''' Return a caveat as a dictionary for export as the JSON macaroon v1 format. ''' serialized = {} if len(c.caveat_id) > 0: serialized['cid'] = c.caveat_id if c.verification_key_id: serialized['vid'] = utils.raw_urlsafe_b64encode( c.verifica...
python
def _caveat_v1_to_dict(c): ''' Return a caveat as a dictionary for export as the JSON macaroon v1 format. ''' serialized = {} if len(c.caveat_id) > 0: serialized['cid'] = c.caveat_id if c.verification_key_id: serialized['vid'] = utils.raw_urlsafe_b64encode( c.verifica...
[ "def", "_caveat_v1_to_dict", "(", "c", ")", ":", "serialized", "=", "{", "}", "if", "len", "(", "c", ".", "caveat_id", ")", ">", "0", ":", "serialized", "[", "'cid'", "]", "=", "c", ".", "caveat_id", "if", "c", ".", "verification_key_id", ":", "seria...
Return a caveat as a dictionary for export as the JSON macaroon v1 format.
[ "Return", "a", "caveat", "as", "a", "dictionary", "for", "export", "as", "the", "JSON", "macaroon", "v1", "format", "." ]
train
https://github.com/ecordell/pymacaroons/blob/c941614df15fe732ea432a62788e45410bcb868d/pymacaroons/serializers/json_serializer.py#L128-L140
ecordell/pymacaroons
pymacaroons/serializers/json_serializer.py
_caveat_v2_to_dict
def _caveat_v2_to_dict(c): ''' Return a caveat as a dictionary for export as the JSON macaroon v2 format. ''' serialized = {} if len(c.caveat_id_bytes) > 0: _add_json_binary_field(c.caveat_id_bytes, serialized, 'i') if c.verification_key_id: _add_json_binary_field(c.verification_...
python
def _caveat_v2_to_dict(c): ''' Return a caveat as a dictionary for export as the JSON macaroon v2 format. ''' serialized = {} if len(c.caveat_id_bytes) > 0: _add_json_binary_field(c.caveat_id_bytes, serialized, 'i') if c.verification_key_id: _add_json_binary_field(c.verification_...
[ "def", "_caveat_v2_to_dict", "(", "c", ")", ":", "serialized", "=", "{", "}", "if", "len", "(", "c", ".", "caveat_id_bytes", ")", ">", "0", ":", "_add_json_binary_field", "(", "c", ".", "caveat_id_bytes", ",", "serialized", ",", "'i'", ")", "if", "c", ...
Return a caveat as a dictionary for export as the JSON macaroon v2 format.
[ "Return", "a", "caveat", "as", "a", "dictionary", "for", "export", "as", "the", "JSON", "macaroon", "v2", "format", "." ]
train
https://github.com/ecordell/pymacaroons/blob/c941614df15fe732ea432a62788e45410bcb868d/pymacaroons/serializers/json_serializer.py#L143-L154
ecordell/pymacaroons
pymacaroons/serializers/json_serializer.py
_add_json_binary_field
def _add_json_binary_field(b, serialized, field): ''' Set the given field to the given val (a bytearray) in the serialized dictionary. If the value isn't valid utf-8, we base64 encode it and use field+"64" as the field name. ''' try: val = b.decode("utf-8") serialized[field] = v...
python
def _add_json_binary_field(b, serialized, field): ''' Set the given field to the given val (a bytearray) in the serialized dictionary. If the value isn't valid utf-8, we base64 encode it and use field+"64" as the field name. ''' try: val = b.decode("utf-8") serialized[field] = v...
[ "def", "_add_json_binary_field", "(", "b", ",", "serialized", ",", "field", ")", ":", "try", ":", "val", "=", "b", ".", "decode", "(", "\"utf-8\"", ")", "serialized", "[", "field", "]", "=", "val", "except", "UnicodeDecodeError", ":", "val", "=", "utils"...
Set the given field to the given val (a bytearray) in the serialized dictionary. If the value isn't valid utf-8, we base64 encode it and use field+"64" as the field name.
[ "Set", "the", "given", "field", "to", "the", "given", "val", "(", "a", "bytearray", ")", "in", "the", "serialized", "dictionary", "." ]
train
https://github.com/ecordell/pymacaroons/blob/c941614df15fe732ea432a62788e45410bcb868d/pymacaroons/serializers/json_serializer.py#L157-L169
ecordell/pymacaroons
pymacaroons/serializers/json_serializer.py
_read_json_binary_field
def _read_json_binary_field(deserialized, field): ''' Read the value of a JSON field that may be string or base64-encoded. ''' val = deserialized.get(field) if val is not None: return utils.convert_to_bytes(val) val = deserialized.get(field + '64') if val is None: return None ...
python
def _read_json_binary_field(deserialized, field): ''' Read the value of a JSON field that may be string or base64-encoded. ''' val = deserialized.get(field) if val is not None: return utils.convert_to_bytes(val) val = deserialized.get(field + '64') if val is None: return None ...
[ "def", "_read_json_binary_field", "(", "deserialized", ",", "field", ")", ":", "val", "=", "deserialized", ".", "get", "(", "field", ")", "if", "val", "is", "not", "None", ":", "return", "utils", ".", "convert_to_bytes", "(", "val", ")", "val", "=", "des...
Read the value of a JSON field that may be string or base64-encoded.
[ "Read", "the", "value", "of", "a", "JSON", "field", "that", "may", "be", "string", "or", "base64", "-", "encoded", "." ]
train
https://github.com/ecordell/pymacaroons/blob/c941614df15fe732ea432a62788e45410bcb868d/pymacaroons/serializers/json_serializer.py#L172-L181
ecordell/pymacaroons
pymacaroons/serializers/json_serializer.py
JsonSerializer.serialize
def serialize(self, m): '''Serialize the macaroon in JSON format indicated by the version field. @param macaroon the macaroon to serialize. @return JSON macaroon. ''' from pymacaroons import macaroon if m.version == macaroon.MACAROON_V1: return self._serializ...
python
def serialize(self, m): '''Serialize the macaroon in JSON format indicated by the version field. @param macaroon the macaroon to serialize. @return JSON macaroon. ''' from pymacaroons import macaroon if m.version == macaroon.MACAROON_V1: return self._serializ...
[ "def", "serialize", "(", "self", ",", "m", ")", ":", "from", "pymacaroons", "import", "macaroon", "if", "m", ".", "version", "==", "macaroon", ".", "MACAROON_V1", ":", "return", "self", ".", "_serialize_v1", "(", "m", ")", "return", "self", ".", "_serial...
Serialize the macaroon in JSON format indicated by the version field. @param macaroon the macaroon to serialize. @return JSON macaroon.
[ "Serialize", "the", "macaroon", "in", "JSON", "format", "indicated", "by", "the", "version", "field", "." ]
train
https://github.com/ecordell/pymacaroons/blob/c941614df15fe732ea432a62788e45410bcb868d/pymacaroons/serializers/json_serializer.py#L9-L18