repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
yeraydiazdiaz/lunr.py
lunr/query.py
Query.term
def term(self, term, **kwargs): """Adds a term to the current query, creating a Clause and adds it to the list of clauses making up this Query. The term is not tokenized and used "as is". Any conversion to token or token-like strings should be performed before calling this method. For example: query.term(lunr.Tokenizer("foo bar")) Args: term (Token or iterable): Token or iterable of tokens to add. kwargs (dict): Additional properties to add to the Clause. """ if isinstance(term, (list, tuple)): for t in term: self.term(t, **kwargs) else: self.clause(str(term), **kwargs) return self
python
def term(self, term, **kwargs): """Adds a term to the current query, creating a Clause and adds it to the list of clauses making up this Query. The term is not tokenized and used "as is". Any conversion to token or token-like strings should be performed before calling this method. For example: query.term(lunr.Tokenizer("foo bar")) Args: term (Token or iterable): Token or iterable of tokens to add. kwargs (dict): Additional properties to add to the Clause. """ if isinstance(term, (list, tuple)): for t in term: self.term(t, **kwargs) else: self.clause(str(term), **kwargs) return self
[ "def", "term", "(", "self", ",", "term", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "term", ",", "(", "list", ",", "tuple", ")", ")", ":", "for", "t", "in", "term", ":", "self", ".", "term", "(", "t", ",", "*", "*", "kwargs", ")", "else", ":", "self", ".", "clause", "(", "str", "(", "term", ")", ",", "*", "*", "kwargs", ")", "return", "self" ]
Adds a term to the current query, creating a Clause and adds it to the list of clauses making up this Query. The term is not tokenized and used "as is". Any conversion to token or token-like strings should be performed before calling this method. For example: query.term(lunr.Tokenizer("foo bar")) Args: term (Token or iterable): Token or iterable of tokens to add. kwargs (dict): Additional properties to add to the Clause.
[ "Adds", "a", "term", "to", "the", "current", "query", "creating", "a", "Clause", "and", "adds", "it", "to", "the", "list", "of", "clauses", "making", "up", "this", "Query", "." ]
28ec3f6d4888295eed730211ee9617aa488d6ba3
https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/query.py#L76-L96
train
yeraydiazdiaz/lunr.py
lunr/query.py
Query.is_negated
def is_negated(self): """A negated query is one in which every clause has a presence of prohibited. These queries require some special processing to return the expected results. """ return all( clause.presence == QueryPresence.PROHIBITED for clause in self.clauses )
python
def is_negated(self): """A negated query is one in which every clause has a presence of prohibited. These queries require some special processing to return the expected results. """ return all( clause.presence == QueryPresence.PROHIBITED for clause in self.clauses )
[ "def", "is_negated", "(", "self", ")", ":", "return", "all", "(", "clause", ".", "presence", "==", "QueryPresence", ".", "PROHIBITED", "for", "clause", "in", "self", ".", "clauses", ")" ]
A negated query is one in which every clause has a presence of prohibited. These queries require some special processing to return the expected results.
[ "A", "negated", "query", "is", "one", "in", "which", "every", "clause", "has", "a", "presence", "of", "prohibited", ".", "These", "queries", "require", "some", "special", "processing", "to", "return", "the", "expected", "results", "." ]
28ec3f6d4888295eed730211ee9617aa488d6ba3
https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/query.py#L98-L105
train
philippWassibauer/templated-emails
templated_emails/utils.py
send_templated_email
def send_templated_email(recipients, template_path, context=None, from_email=settings.DEFAULT_FROM_EMAIL, fail_silently=False, extra_headers=None): """ recipients can be either a list of emails or a list of users, if it is users the system will change to the language that the user has set as theyr mother toungue """ recipient_pks = [r.pk for r in recipients if isinstance(r, get_user_model())] recipient_emails = [e for e in recipients if not isinstance(e, get_user_model())] send = _send_task.delay if use_celery else _send msg = send(recipient_pks, recipient_emails, template_path, context, from_email, fail_silently, extra_headers=extra_headers) return msg
python
def send_templated_email(recipients, template_path, context=None, from_email=settings.DEFAULT_FROM_EMAIL, fail_silently=False, extra_headers=None): """ recipients can be either a list of emails or a list of users, if it is users the system will change to the language that the user has set as theyr mother toungue """ recipient_pks = [r.pk for r in recipients if isinstance(r, get_user_model())] recipient_emails = [e for e in recipients if not isinstance(e, get_user_model())] send = _send_task.delay if use_celery else _send msg = send(recipient_pks, recipient_emails, template_path, context, from_email, fail_silently, extra_headers=extra_headers) return msg
[ "def", "send_templated_email", "(", "recipients", ",", "template_path", ",", "context", "=", "None", ",", "from_email", "=", "settings", ".", "DEFAULT_FROM_EMAIL", ",", "fail_silently", "=", "False", ",", "extra_headers", "=", "None", ")", ":", "recipient_pks", "=", "[", "r", ".", "pk", "for", "r", "in", "recipients", "if", "isinstance", "(", "r", ",", "get_user_model", "(", ")", ")", "]", "recipient_emails", "=", "[", "e", "for", "e", "in", "recipients", "if", "not", "isinstance", "(", "e", ",", "get_user_model", "(", ")", ")", "]", "send", "=", "_send_task", ".", "delay", "if", "use_celery", "else", "_send", "msg", "=", "send", "(", "recipient_pks", ",", "recipient_emails", ",", "template_path", ",", "context", ",", "from_email", ",", "fail_silently", ",", "extra_headers", "=", "extra_headers", ")", "return", "msg" ]
recipients can be either a list of emails or a list of users, if it is users the system will change to the language that the user has set as theyr mother toungue
[ "recipients", "can", "be", "either", "a", "list", "of", "emails", "or", "a", "list", "of", "users", "if", "it", "is", "users", "the", "system", "will", "change", "to", "the", "language", "that", "the", "user", "has", "set", "as", "theyr", "mother", "toungue" ]
9f011ba84b67f2e0f088dae2b0b072c377c6d183
https://github.com/philippWassibauer/templated-emails/blob/9f011ba84b67f2e0f088dae2b0b072c377c6d183/templated_emails/utils.py#L47-L61
train
wroberts/fsed
fsed/ahocorasick.py
remove_duplicates
def remove_duplicates(seq): ''' Removes duplicate boundary token characters from the given character iterable. Arguments: - `seq`: ''' last_boundary = False for char in seq: if char == '\x00': if not last_boundary: last_boundary = True yield char else: last_boundary = False yield char
python
def remove_duplicates(seq): ''' Removes duplicate boundary token characters from the given character iterable. Arguments: - `seq`: ''' last_boundary = False for char in seq: if char == '\x00': if not last_boundary: last_boundary = True yield char else: last_boundary = False yield char
[ "def", "remove_duplicates", "(", "seq", ")", ":", "last_boundary", "=", "False", "for", "char", "in", "seq", ":", "if", "char", "==", "'\\x00'", ":", "if", "not", "last_boundary", ":", "last_boundary", "=", "True", "yield", "char", "else", ":", "last_boundary", "=", "False", "yield", "char" ]
Removes duplicate boundary token characters from the given character iterable. Arguments: - `seq`:
[ "Removes", "duplicate", "boundary", "token", "characters", "from", "the", "given", "character", "iterable", "." ]
c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2
https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/ahocorasick.py#L455-L471
train
wroberts/fsed
fsed/ahocorasick.py
Trie.pretty_print_str
def pretty_print_str(self): ''' Create a string to pretty-print this trie to standard output. ''' retval = '' # dfs todo = [self.root] while todo: current = todo.pop() for char in reversed(sorted(current.keys())): todo.append(current[char]) indent = ' ' * (current.depth * 2) retval += indent + current.__unicode__() + '\n' return retval.rstrip('\n')
python
def pretty_print_str(self): ''' Create a string to pretty-print this trie to standard output. ''' retval = '' # dfs todo = [self.root] while todo: current = todo.pop() for char in reversed(sorted(current.keys())): todo.append(current[char]) indent = ' ' * (current.depth * 2) retval += indent + current.__unicode__() + '\n' return retval.rstrip('\n')
[ "def", "pretty_print_str", "(", "self", ")", ":", "retval", "=", "''", "# dfs", "todo", "=", "[", "self", ".", "root", "]", "while", "todo", ":", "current", "=", "todo", ".", "pop", "(", ")", "for", "char", "in", "reversed", "(", "sorted", "(", "current", ".", "keys", "(", ")", ")", ")", ":", "todo", ".", "append", "(", "current", "[", "char", "]", ")", "indent", "=", "' '", "*", "(", "current", ".", "depth", "*", "2", ")", "retval", "+=", "indent", "+", "current", ".", "__unicode__", "(", ")", "+", "'\\n'", "return", "retval", ".", "rstrip", "(", "'\\n'", ")" ]
Create a string to pretty-print this trie to standard output.
[ "Create", "a", "string", "to", "pretty", "-", "print", "this", "trie", "to", "standard", "output", "." ]
c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2
https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/ahocorasick.py#L147-L160
train
wroberts/fsed
fsed/ahocorasick.py
AhoCorasickTrie._reset_suffix_links
def _reset_suffix_links(self): ''' Reset all suffix links in all nodes in this trie. ''' self._suffix_links_set = False for current, _parent in self.dfs(): current.suffix = None current.dict_suffix = None current.longest_prefix = None
python
def _reset_suffix_links(self): ''' Reset all suffix links in all nodes in this trie. ''' self._suffix_links_set = False for current, _parent in self.dfs(): current.suffix = None current.dict_suffix = None current.longest_prefix = None
[ "def", "_reset_suffix_links", "(", "self", ")", ":", "self", ".", "_suffix_links_set", "=", "False", "for", "current", ",", "_parent", "in", "self", ".", "dfs", "(", ")", ":", "current", ".", "suffix", "=", "None", "current", ".", "dict_suffix", "=", "None", "current", ".", "longest_prefix", "=", "None" ]
Reset all suffix links in all nodes in this trie.
[ "Reset", "all", "suffix", "links", "in", "all", "nodes", "in", "this", "trie", "." ]
c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2
https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/ahocorasick.py#L185-L193
train
wroberts/fsed
fsed/ahocorasick.py
AhoCorasickTrie._set_suffix_links
def _set_suffix_links(self): ''' Sets all suffix links in all nodes in this trie. ''' self._suffix_links_set = True for current, parent in self.bfs(): # skip the root node if parent is None: continue current.longest_prefix = parent.longest_prefix if parent.has_value: current.longest_prefix = parent # the root doesn't get a suffix link # also, skip previously set suffix links if current.has_suffix: continue # current is not the root and has no suffix # set current's suffix to parent's suffix suffix = parent while True: if not suffix.has_suffix: current.suffix = self.root break else: suffix = suffix.suffix if current.uplink in suffix: current.suffix = suffix[current.uplink] break # now find the dict_suffix value suffix = current.suffix while not suffix.has_value and suffix.has_suffix: suffix = suffix.suffix if suffix.has_value: current.dict_suffix = suffix
python
def _set_suffix_links(self): ''' Sets all suffix links in all nodes in this trie. ''' self._suffix_links_set = True for current, parent in self.bfs(): # skip the root node if parent is None: continue current.longest_prefix = parent.longest_prefix if parent.has_value: current.longest_prefix = parent # the root doesn't get a suffix link # also, skip previously set suffix links if current.has_suffix: continue # current is not the root and has no suffix # set current's suffix to parent's suffix suffix = parent while True: if not suffix.has_suffix: current.suffix = self.root break else: suffix = suffix.suffix if current.uplink in suffix: current.suffix = suffix[current.uplink] break # now find the dict_suffix value suffix = current.suffix while not suffix.has_value and suffix.has_suffix: suffix = suffix.suffix if suffix.has_value: current.dict_suffix = suffix
[ "def", "_set_suffix_links", "(", "self", ")", ":", "self", ".", "_suffix_links_set", "=", "True", "for", "current", ",", "parent", "in", "self", ".", "bfs", "(", ")", ":", "# skip the root node", "if", "parent", "is", "None", ":", "continue", "current", ".", "longest_prefix", "=", "parent", ".", "longest_prefix", "if", "parent", ".", "has_value", ":", "current", ".", "longest_prefix", "=", "parent", "# the root doesn't get a suffix link", "# also, skip previously set suffix links", "if", "current", ".", "has_suffix", ":", "continue", "# current is not the root and has no suffix", "# set current's suffix to parent's suffix", "suffix", "=", "parent", "while", "True", ":", "if", "not", "suffix", ".", "has_suffix", ":", "current", ".", "suffix", "=", "self", ".", "root", "break", "else", ":", "suffix", "=", "suffix", ".", "suffix", "if", "current", ".", "uplink", "in", "suffix", ":", "current", ".", "suffix", "=", "suffix", "[", "current", ".", "uplink", "]", "break", "# now find the dict_suffix value", "suffix", "=", "current", ".", "suffix", "while", "not", "suffix", ".", "has_value", "and", "suffix", ".", "has_suffix", ":", "suffix", "=", "suffix", ".", "suffix", "if", "suffix", ".", "has_value", ":", "current", ".", "dict_suffix", "=", "suffix" ]
Sets all suffix links in all nodes in this trie.
[ "Sets", "all", "suffix", "links", "in", "all", "nodes", "in", "this", "trie", "." ]
c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2
https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/ahocorasick.py#L195-L228
train
wroberts/fsed
fsed/ahocorasick.py
AhoCorasickTrie.greedy_replace
def greedy_replace(self, seq): ''' Greedily matches strings in ``seq``, and replaces them with their node values. Arguments: - `seq`: an iterable of characters to perform search-and-replace on ''' if not self._suffix_links_set: self._set_suffix_links() # start at the root current = self.root buffered = '' outstr = '' for char in seq: while char not in current: if current.has_dict_suffix: current = current.dict_suffix outstr += buffered[:-current.depth] outstr += current.value buffered = '' current = self.root break elif current.has_suffix: current = current.suffix if current.depth: outstr += buffered[:-current.depth] buffered = buffered[-current.depth:] else: outstr += buffered buffered = '' break else: current = self.root outstr += buffered buffered = '' break if char in current: buffered += char current = current[char] if current.has_value: outstr += buffered[:-current.depth] outstr += current.value buffered = '' current = self.root else: assert current is self.root outstr += buffered + char buffered = '' if current.has_dict_suffix: current = current.dict_suffix outstr += buffered[:-current.depth] outstr += current.value else: outstr += buffered return outstr
python
def greedy_replace(self, seq): ''' Greedily matches strings in ``seq``, and replaces them with their node values. Arguments: - `seq`: an iterable of characters to perform search-and-replace on ''' if not self._suffix_links_set: self._set_suffix_links() # start at the root current = self.root buffered = '' outstr = '' for char in seq: while char not in current: if current.has_dict_suffix: current = current.dict_suffix outstr += buffered[:-current.depth] outstr += current.value buffered = '' current = self.root break elif current.has_suffix: current = current.suffix if current.depth: outstr += buffered[:-current.depth] buffered = buffered[-current.depth:] else: outstr += buffered buffered = '' break else: current = self.root outstr += buffered buffered = '' break if char in current: buffered += char current = current[char] if current.has_value: outstr += buffered[:-current.depth] outstr += current.value buffered = '' current = self.root else: assert current is self.root outstr += buffered + char buffered = '' if current.has_dict_suffix: current = current.dict_suffix outstr += buffered[:-current.depth] outstr += current.value else: outstr += buffered return outstr
[ "def", "greedy_replace", "(", "self", ",", "seq", ")", ":", "if", "not", "self", ".", "_suffix_links_set", ":", "self", ".", "_set_suffix_links", "(", ")", "# start at the root", "current", "=", "self", ".", "root", "buffered", "=", "''", "outstr", "=", "''", "for", "char", "in", "seq", ":", "while", "char", "not", "in", "current", ":", "if", "current", ".", "has_dict_suffix", ":", "current", "=", "current", ".", "dict_suffix", "outstr", "+=", "buffered", "[", ":", "-", "current", ".", "depth", "]", "outstr", "+=", "current", ".", "value", "buffered", "=", "''", "current", "=", "self", ".", "root", "break", "elif", "current", ".", "has_suffix", ":", "current", "=", "current", ".", "suffix", "if", "current", ".", "depth", ":", "outstr", "+=", "buffered", "[", ":", "-", "current", ".", "depth", "]", "buffered", "=", "buffered", "[", "-", "current", ".", "depth", ":", "]", "else", ":", "outstr", "+=", "buffered", "buffered", "=", "''", "break", "else", ":", "current", "=", "self", ".", "root", "outstr", "+=", "buffered", "buffered", "=", "''", "break", "if", "char", "in", "current", ":", "buffered", "+=", "char", "current", "=", "current", "[", "char", "]", "if", "current", ".", "has_value", ":", "outstr", "+=", "buffered", "[", ":", "-", "current", ".", "depth", "]", "outstr", "+=", "current", ".", "value", "buffered", "=", "''", "current", "=", "self", ".", "root", "else", ":", "assert", "current", "is", "self", ".", "root", "outstr", "+=", "buffered", "+", "char", "buffered", "=", "''", "if", "current", ".", "has_dict_suffix", ":", "current", "=", "current", ".", "dict_suffix", "outstr", "+=", "buffered", "[", ":", "-", "current", ".", "depth", "]", "outstr", "+=", "current", ".", "value", "else", ":", "outstr", "+=", "buffered", "return", "outstr" ]
Greedily matches strings in ``seq``, and replaces them with their node values. Arguments: - `seq`: an iterable of characters to perform search-and-replace on
[ "Greedily", "matches", "strings", "in", "seq", "and", "replaces", "them", "with", "their", "node", "values", "." ]
c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2
https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/ahocorasick.py#L340-L395
train
CiscoUcs/UcsPythonSDK
src/UcsSdk/UcsBase.py
_write_mo
def _write_mo(mo): """ Method to return string representation of a managed object. """ # from UcsBase import UcsUtils classNotFound = False if (UcsUtils.FindClassIdInMoMetaIgnoreCase(mo.classId) == None): classNotFound = True tabsize = 8 outstr = "\n" if classNotFound: outstr += "Managed Object\t\t\t:\t" + str(UcsUtils.WordU(mo.classId)) + "\n" else: outstr += "Managed Object\t\t\t:\t" + str(mo.propMoMeta.name) + "\n" outstr += "-" * len("Managed Object") + "\n" if (not classNotFound): for prop in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): propMeta = UcsUtils.GetUcsPropertyMeta(mo.propMoMeta.name, prop) if (propMeta.access == UcsPropertyMeta.Internal): continue val = mo.getattr(prop) # if val != None and val != "": outstr += str(prop).ljust(tabsize * 4) + ':' + str(val) + "\n" else: for prop in mo.__dict__: if (prop in ['classId', 'XtraProperty', 'handle', 'propMoMeta', 'dirtyMask', 'child']): continue val = mo.__dict__[prop] outstr += str(UcsUtils.WordU(prop)).ljust(tabsize * 4) + ':' + str(val) + "\n" if mo.__dict__.has_key('XtraProperty'): for xtraProp in mo.__dict__['XtraProperty']: outstr += '[X]' + str(UcsUtils.WordU(xtraProp)).ljust(tabsize * 4) + ':' + str( mo.__dict__['XtraProperty'][xtraProp]) + "\n" outstr += str("Ucs").ljust(tabsize * 4) + ':' + str(mo.handle._ucs) + "\n" outstr += "\n" return outstr
python
def _write_mo(mo): """ Method to return string representation of a managed object. """ # from UcsBase import UcsUtils classNotFound = False if (UcsUtils.FindClassIdInMoMetaIgnoreCase(mo.classId) == None): classNotFound = True tabsize = 8 outstr = "\n" if classNotFound: outstr += "Managed Object\t\t\t:\t" + str(UcsUtils.WordU(mo.classId)) + "\n" else: outstr += "Managed Object\t\t\t:\t" + str(mo.propMoMeta.name) + "\n" outstr += "-" * len("Managed Object") + "\n" if (not classNotFound): for prop in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): propMeta = UcsUtils.GetUcsPropertyMeta(mo.propMoMeta.name, prop) if (propMeta.access == UcsPropertyMeta.Internal): continue val = mo.getattr(prop) # if val != None and val != "": outstr += str(prop).ljust(tabsize * 4) + ':' + str(val) + "\n" else: for prop in mo.__dict__: if (prop in ['classId', 'XtraProperty', 'handle', 'propMoMeta', 'dirtyMask', 'child']): continue val = mo.__dict__[prop] outstr += str(UcsUtils.WordU(prop)).ljust(tabsize * 4) + ':' + str(val) + "\n" if mo.__dict__.has_key('XtraProperty'): for xtraProp in mo.__dict__['XtraProperty']: outstr += '[X]' + str(UcsUtils.WordU(xtraProp)).ljust(tabsize * 4) + ':' + str( mo.__dict__['XtraProperty'][xtraProp]) + "\n" outstr += str("Ucs").ljust(tabsize * 4) + ':' + str(mo.handle._ucs) + "\n" outstr += "\n" return outstr
[ "def", "_write_mo", "(", "mo", ")", ":", "# from UcsBase import UcsUtils", "classNotFound", "=", "False", "if", "(", "UcsUtils", ".", "FindClassIdInMoMetaIgnoreCase", "(", "mo", ".", "classId", ")", "==", "None", ")", ":", "classNotFound", "=", "True", "tabsize", "=", "8", "outstr", "=", "\"\\n\"", "if", "classNotFound", ":", "outstr", "+=", "\"Managed Object\\t\\t\\t:\\t\"", "+", "str", "(", "UcsUtils", ".", "WordU", "(", "mo", ".", "classId", ")", ")", "+", "\"\\n\"", "else", ":", "outstr", "+=", "\"Managed Object\\t\\t\\t:\\t\"", "+", "str", "(", "mo", ".", "propMoMeta", ".", "name", ")", "+", "\"\\n\"", "outstr", "+=", "\"-\"", "*", "len", "(", "\"Managed Object\"", ")", "+", "\"\\n\"", "if", "(", "not", "classNotFound", ")", ":", "for", "prop", "in", "UcsUtils", ".", "GetUcsPropertyMetaAttributeList", "(", "mo", ".", "propMoMeta", ".", "name", ")", ":", "propMeta", "=", "UcsUtils", ".", "GetUcsPropertyMeta", "(", "mo", ".", "propMoMeta", ".", "name", ",", "prop", ")", "if", "(", "propMeta", ".", "access", "==", "UcsPropertyMeta", ".", "Internal", ")", ":", "continue", "val", "=", "mo", ".", "getattr", "(", "prop", ")", "# if val != None and val != \"\":", "outstr", "+=", "str", "(", "prop", ")", ".", "ljust", "(", "tabsize", "*", "4", ")", "+", "':'", "+", "str", "(", "val", ")", "+", "\"\\n\"", "else", ":", "for", "prop", "in", "mo", ".", "__dict__", ":", "if", "(", "prop", "in", "[", "'classId'", ",", "'XtraProperty'", ",", "'handle'", ",", "'propMoMeta'", ",", "'dirtyMask'", ",", "'child'", "]", ")", ":", "continue", "val", "=", "mo", ".", "__dict__", "[", "prop", "]", "outstr", "+=", "str", "(", "UcsUtils", ".", "WordU", "(", "prop", ")", ")", ".", "ljust", "(", "tabsize", "*", "4", ")", "+", "':'", "+", "str", "(", "val", ")", "+", "\"\\n\"", "if", "mo", ".", "__dict__", ".", "has_key", "(", "'XtraProperty'", ")", ":", "for", "xtraProp", "in", "mo", ".", "__dict__", "[", "'XtraProperty'", "]", ":", "outstr", "+=", "'[X]'", "+", "str", "(", "UcsUtils", ".", "WordU", "(", "xtraProp", ")", ")", ".", "ljust", "(", "tabsize", "*", "4", ")", "+", "':'", "+", "str", "(", "mo", ".", "__dict__", "[", "'XtraProperty'", "]", "[", "xtraProp", "]", ")", "+", "\"\\n\"", "outstr", "+=", "str", "(", "\"Ucs\"", ")", ".", "ljust", "(", "tabsize", "*", "4", ")", "+", "':'", "+", "str", "(", "mo", ".", "handle", ".", "_ucs", ")", "+", "\"\\n\"", "outstr", "+=", "\"\\n\"", "return", "outstr" ]
Method to return string representation of a managed object.
[ "Method", "to", "return", "string", "representation", "of", "a", "managed", "object", "." ]
bf6b07d6abeacb922c92b198352eda4eb9e4629b
https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L932-L968
train
CiscoUcs/UcsPythonSDK
src/UcsSdk/UcsBase.py
WriteObject
def WriteObject(moList): """ Writes the managed object on the terminal in form of key value pairs. """ from Ucs import Dn from UcsHandle import UcsMoDiff tabsize = 8 if (isinstance(moList, _GenericMO) == True): print str(moList) elif (isinstance(moList, ExternalMethod) == True): if (hasattr(moList, "OutConfigs") == True): for child in moList.OutConfigs.GetChild(): if (isinstance(child, ManagedObject) == True): WriteObject(child) elif (isinstance(moList, ManagedObject) == True): print str(_write_mo(moList)) elif ((isinstance(moList, list) == True) and (len(moList) > 0)): if (isinstance(moList[0], UcsMoDiff)): print "Dn".ljust(tabsize * 10), "InputObject".ljust(tabsize * 4), "SideIndicator".ljust( tabsize * 3), "DiffProperty" print "--".ljust(tabsize * 10), "-----------".ljust(tabsize * 4), "-------------".ljust( tabsize * 3), "------------" for mo in moList: if (isinstance(mo, ManagedObject) == True): print str(_write_mo(mo)) elif (isinstance(mo, Dn) == True): print mo.getattr("value") elif (isinstance(mo, UcsMoDiff) == True): WriteMoDiff(mo)
python
def WriteObject(moList): """ Writes the managed object on the terminal in form of key value pairs. """ from Ucs import Dn from UcsHandle import UcsMoDiff tabsize = 8 if (isinstance(moList, _GenericMO) == True): print str(moList) elif (isinstance(moList, ExternalMethod) == True): if (hasattr(moList, "OutConfigs") == True): for child in moList.OutConfigs.GetChild(): if (isinstance(child, ManagedObject) == True): WriteObject(child) elif (isinstance(moList, ManagedObject) == True): print str(_write_mo(moList)) elif ((isinstance(moList, list) == True) and (len(moList) > 0)): if (isinstance(moList[0], UcsMoDiff)): print "Dn".ljust(tabsize * 10), "InputObject".ljust(tabsize * 4), "SideIndicator".ljust( tabsize * 3), "DiffProperty" print "--".ljust(tabsize * 10), "-----------".ljust(tabsize * 4), "-------------".ljust( tabsize * 3), "------------" for mo in moList: if (isinstance(mo, ManagedObject) == True): print str(_write_mo(mo)) elif (isinstance(mo, Dn) == True): print mo.getattr("value") elif (isinstance(mo, UcsMoDiff) == True): WriteMoDiff(mo)
[ "def", "WriteObject", "(", "moList", ")", ":", "from", "Ucs", "import", "Dn", "from", "UcsHandle", "import", "UcsMoDiff", "tabsize", "=", "8", "if", "(", "isinstance", "(", "moList", ",", "_GenericMO", ")", "==", "True", ")", ":", "print", "str", "(", "moList", ")", "elif", "(", "isinstance", "(", "moList", ",", "ExternalMethod", ")", "==", "True", ")", ":", "if", "(", "hasattr", "(", "moList", ",", "\"OutConfigs\"", ")", "==", "True", ")", ":", "for", "child", "in", "moList", ".", "OutConfigs", ".", "GetChild", "(", ")", ":", "if", "(", "isinstance", "(", "child", ",", "ManagedObject", ")", "==", "True", ")", ":", "WriteObject", "(", "child", ")", "elif", "(", "isinstance", "(", "moList", ",", "ManagedObject", ")", "==", "True", ")", ":", "print", "str", "(", "_write_mo", "(", "moList", ")", ")", "elif", "(", "(", "isinstance", "(", "moList", ",", "list", ")", "==", "True", ")", "and", "(", "len", "(", "moList", ")", ">", "0", ")", ")", ":", "if", "(", "isinstance", "(", "moList", "[", "0", "]", ",", "UcsMoDiff", ")", ")", ":", "print", "\"Dn\"", ".", "ljust", "(", "tabsize", "*", "10", ")", ",", "\"InputObject\"", ".", "ljust", "(", "tabsize", "*", "4", ")", ",", "\"SideIndicator\"", ".", "ljust", "(", "tabsize", "*", "3", ")", ",", "\"DiffProperty\"", "print", "\"--\"", ".", "ljust", "(", "tabsize", "*", "10", ")", ",", "\"-----------\"", ".", "ljust", "(", "tabsize", "*", "4", ")", ",", "\"-------------\"", ".", "ljust", "(", "tabsize", "*", "3", ")", ",", "\"------------\"", "for", "mo", "in", "moList", ":", "if", "(", "isinstance", "(", "mo", ",", "ManagedObject", ")", "==", "True", ")", ":", "print", "str", "(", "_write_mo", "(", "mo", ")", ")", "elif", "(", "isinstance", "(", "mo", ",", "Dn", ")", "==", "True", ")", ":", "print", "mo", ".", "getattr", "(", "\"value\"", ")", "elif", "(", "isinstance", "(", "mo", ",", "UcsMoDiff", ")", "==", "True", ")", ":", "WriteMoDiff", "(", "mo", ")" ]
Writes the managed object on the terminal in form of key value pairs.
[ "Writes", "the", "managed", "object", "on", "the", "terminal", "in", "form", "of", "key", "value", "pairs", "." ]
bf6b07d6abeacb922c92b198352eda4eb9e4629b
https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L978-L1005
train
CiscoUcs/UcsPythonSDK
src/UcsSdk/UcsBase.py
UcsBase.childWriteXml
def childWriteXml(self, w, option): """Method writes the xml representation for the object.""" ch = [] for c in self.child: ch.append(c.WriteXml(w, option)) return ch
python
def childWriteXml(self, w, option): """Method writes the xml representation for the object.""" ch = [] for c in self.child: ch.append(c.WriteXml(w, option)) return ch
[ "def", "childWriteXml", "(", "self", ",", "w", ",", "option", ")", ":", "ch", "=", "[", "]", "for", "c", "in", "self", ".", "child", ":", "ch", ".", "append", "(", "c", ".", "WriteXml", "(", "w", ",", "option", ")", ")", "return", "ch" ]
Method writes the xml representation for the object.
[ "Method", "writes", "the", "xml", "representation", "for", "the", "object", "." ]
bf6b07d6abeacb922c92b198352eda4eb9e4629b
https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L68-L73
train
CiscoUcs/UcsPythonSDK
src/UcsSdk/UcsBase.py
ManagedObject.setattr
def setattr(self, key, value): """ This method sets attribute of a Managed Object. """ if (UcsUtils.FindClassIdInMoMetaIgnoreCase(self.classId) != None): if (key in _ManagedObjectMeta[self.classId]): propMeta = UcsUtils.GetUcsPropertyMeta(self.classId, key) if (propMeta.ValidatePropertyValue(value) == False): # print "Validation Failure" return False if (propMeta.mask != None): self.dirtyMask |= propMeta.mask self.__dict__[key] = value else: self.__dict__['XtraProperty'][key] = value else: """ no such property """ self.__dict__['XtraProperty'][UcsUtils.WordU(key)] = value
python
def setattr(self, key, value): """ This method sets attribute of a Managed Object. """ if (UcsUtils.FindClassIdInMoMetaIgnoreCase(self.classId) != None): if (key in _ManagedObjectMeta[self.classId]): propMeta = UcsUtils.GetUcsPropertyMeta(self.classId, key) if (propMeta.ValidatePropertyValue(value) == False): # print "Validation Failure" return False if (propMeta.mask != None): self.dirtyMask |= propMeta.mask self.__dict__[key] = value else: self.__dict__['XtraProperty'][key] = value else: """ no such property """ self.__dict__['XtraProperty'][UcsUtils.WordU(key)] = value
[ "def", "setattr", "(", "self", ",", "key", ",", "value", ")", ":", "if", "(", "UcsUtils", ".", "FindClassIdInMoMetaIgnoreCase", "(", "self", ".", "classId", ")", "!=", "None", ")", ":", "if", "(", "key", "in", "_ManagedObjectMeta", "[", "self", ".", "classId", "]", ")", ":", "propMeta", "=", "UcsUtils", ".", "GetUcsPropertyMeta", "(", "self", ".", "classId", ",", "key", ")", "if", "(", "propMeta", ".", "ValidatePropertyValue", "(", "value", ")", "==", "False", ")", ":", "# print \"Validation Failure\"", "return", "False", "if", "(", "propMeta", ".", "mask", "!=", "None", ")", ":", "self", ".", "dirtyMask", "|=", "propMeta", ".", "mask", "self", ".", "__dict__", "[", "key", "]", "=", "value", "else", ":", "self", ".", "__dict__", "[", "'XtraProperty'", "]", "[", "key", "]", "=", "value", "else", ":", "\"\"\" no such property \"\"\"", "self", ".", "__dict__", "[", "'XtraProperty'", "]", "[", "UcsUtils", ".", "WordU", "(", "key", ")", "]", "=", "value" ]
This method sets attribute of a Managed Object.
[ "This", "method", "sets", "attribute", "of", "a", "Managed", "Object", "." ]
bf6b07d6abeacb922c92b198352eda4eb9e4629b
https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L200-L218
train
CiscoUcs/UcsPythonSDK
src/UcsSdk/UcsBase.py
ManagedObject.getattr
def getattr(self, key): """ This method gets attribute value of a Managed Object. """ if ((key == "classId") and (self.__dict__.has_key(key))): return self.__dict__[key] if UcsUtils.FindClassIdInMoMetaIgnoreCase(self.classId): if self.__dict__.has_key(key): if key in _ManagedObjectMeta[self.classId]: """ property exists """ return self.__dict__[key] else: if self.__dict__.has_key('XtraProperty'): if self.__dict__['XtraProperty'].has_key(key): return self.__dict__['XtraProperty'][UcsUtils.WordU(key)] else: raise AttributeError(key) else: # TODO: Add Warning/Error messages in Logger. print "No XtraProperty in mo:", self.classId, " key:", key else: """ property does not exist """ if self.__dict__['XtraProperty'].has_key(key): return self.__dict__['XtraProperty'][UcsUtils.WordU(key)] elif key == "Dn" or key == "Rn": return None else: raise AttributeError(key)
python
def getattr(self, key): """ This method gets attribute value of a Managed Object. """ if ((key == "classId") and (self.__dict__.has_key(key))): return self.__dict__[key] if UcsUtils.FindClassIdInMoMetaIgnoreCase(self.classId): if self.__dict__.has_key(key): if key in _ManagedObjectMeta[self.classId]: """ property exists """ return self.__dict__[key] else: if self.__dict__.has_key('XtraProperty'): if self.__dict__['XtraProperty'].has_key(key): return self.__dict__['XtraProperty'][UcsUtils.WordU(key)] else: raise AttributeError(key) else: # TODO: Add Warning/Error messages in Logger. print "No XtraProperty in mo:", self.classId, " key:", key else: """ property does not exist """ if self.__dict__['XtraProperty'].has_key(key): return self.__dict__['XtraProperty'][UcsUtils.WordU(key)] elif key == "Dn" or key == "Rn": return None else: raise AttributeError(key)
[ "def", "getattr", "(", "self", ",", "key", ")", ":", "if", "(", "(", "key", "==", "\"classId\"", ")", "and", "(", "self", ".", "__dict__", ".", "has_key", "(", "key", ")", ")", ")", ":", "return", "self", ".", "__dict__", "[", "key", "]", "if", "UcsUtils", ".", "FindClassIdInMoMetaIgnoreCase", "(", "self", ".", "classId", ")", ":", "if", "self", ".", "__dict__", ".", "has_key", "(", "key", ")", ":", "if", "key", "in", "_ManagedObjectMeta", "[", "self", ".", "classId", "]", ":", "\"\"\" property exists \"\"\"", "return", "self", ".", "__dict__", "[", "key", "]", "else", ":", "if", "self", ".", "__dict__", ".", "has_key", "(", "'XtraProperty'", ")", ":", "if", "self", ".", "__dict__", "[", "'XtraProperty'", "]", ".", "has_key", "(", "key", ")", ":", "return", "self", ".", "__dict__", "[", "'XtraProperty'", "]", "[", "UcsUtils", ".", "WordU", "(", "key", ")", "]", "else", ":", "raise", "AttributeError", "(", "key", ")", "else", ":", "# TODO: Add Warning/Error messages in Logger.", "print", "\"No XtraProperty in mo:\"", ",", "self", ".", "classId", ",", "\" key:\"", ",", "key", "else", ":", "\"\"\" property does not exist \"\"\"", "if", "self", ".", "__dict__", "[", "'XtraProperty'", "]", ".", "has_key", "(", "key", ")", ":", "return", "self", ".", "__dict__", "[", "'XtraProperty'", "]", "[", "UcsUtils", ".", "WordU", "(", "key", ")", "]", "elif", "key", "==", "\"Dn\"", "or", "key", "==", "\"Rn\"", ":", "return", "None", "else", ":", "raise", "AttributeError", "(", "key", ")" ]
This method gets attribute value of a Managed Object.
[ "This", "method", "gets", "attribute", "value", "of", "a", "Managed", "Object", "." ]
bf6b07d6abeacb922c92b198352eda4eb9e4629b
https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L230-L256
train
CiscoUcs/UcsPythonSDK
src/UcsSdk/UcsBase.py
ManagedObject.MarkDirty
def MarkDirty(self): """ This method marks the managed object dirty. """ if ((UcsUtils.FindClassIdInMoMetaIgnoreCase(self.classId) == None) and (not self.IsDirty())): self.dirtyMask = ManagedObject.DUMMYDIRTY else: self.dirtyMask = self.propMoMeta.mask
python
def MarkDirty(self): """ This method marks the managed object dirty. """ if ((UcsUtils.FindClassIdInMoMetaIgnoreCase(self.classId) == None) and (not self.IsDirty())): self.dirtyMask = ManagedObject.DUMMYDIRTY else: self.dirtyMask = self.propMoMeta.mask
[ "def", "MarkDirty", "(", "self", ")", ":", "if", "(", "(", "UcsUtils", ".", "FindClassIdInMoMetaIgnoreCase", "(", "self", ".", "classId", ")", "==", "None", ")", "and", "(", "not", "self", ".", "IsDirty", "(", ")", ")", ")", ":", "self", ".", "dirtyMask", "=", "ManagedObject", ".", "DUMMYDIRTY", "else", ":", "self", ".", "dirtyMask", "=", "self", ".", "propMoMeta", ".", "mask" ]
This method marks the managed object dirty.
[ "This", "method", "marks", "the", "managed", "object", "dirty", "." ]
bf6b07d6abeacb922c92b198352eda4eb9e4629b
https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L266-L271
train
CiscoUcs/UcsPythonSDK
src/UcsSdk/UcsBase.py
ManagedObject.MakeRn
def MakeRn(self): """ This method returns the Rn for a managed object. """ rnPattern = self.propMoMeta.rn for prop in re.findall("\[([^\]]*)\]", rnPattern): if prop in UcsUtils.GetUcsPropertyMetaAttributeList(self.classId): if (self.getattr(prop) != None): rnPattern = re.sub('\[%s\]' % prop, '%s' % self.getattr(prop), rnPattern) else: raise UcsValidationException('Property "%s" was None in MakeRn' % prop) # raise Exception('Property "%s" was None in MakeRn' %prop) else: raise UcsValidationException('Property "%s" was not found in MakeRn arguments' % prop) # raise Exception('Property "%s" was not found in MakeRn arguments' %prop) return rnPattern
python
def MakeRn(self): """ This method returns the Rn for a managed object. """ rnPattern = self.propMoMeta.rn for prop in re.findall("\[([^\]]*)\]", rnPattern): if prop in UcsUtils.GetUcsPropertyMetaAttributeList(self.classId): if (self.getattr(prop) != None): rnPattern = re.sub('\[%s\]' % prop, '%s' % self.getattr(prop), rnPattern) else: raise UcsValidationException('Property "%s" was None in MakeRn' % prop) # raise Exception('Property "%s" was None in MakeRn' %prop) else: raise UcsValidationException('Property "%s" was not found in MakeRn arguments' % prop) # raise Exception('Property "%s" was not found in MakeRn arguments' %prop) return rnPattern
[ "def", "MakeRn", "(", "self", ")", ":", "rnPattern", "=", "self", ".", "propMoMeta", ".", "rn", "for", "prop", "in", "re", ".", "findall", "(", "\"\\[([^\\]]*)\\]\"", ",", "rnPattern", ")", ":", "if", "prop", "in", "UcsUtils", ".", "GetUcsPropertyMetaAttributeList", "(", "self", ".", "classId", ")", ":", "if", "(", "self", ".", "getattr", "(", "prop", ")", "!=", "None", ")", ":", "rnPattern", "=", "re", ".", "sub", "(", "'\\[%s\\]'", "%", "prop", ",", "'%s'", "%", "self", ".", "getattr", "(", "prop", ")", ",", "rnPattern", ")", "else", ":", "raise", "UcsValidationException", "(", "'Property \"%s\" was None in MakeRn'", "%", "prop", ")", "# raise Exception('Property \"%s\" was None in MakeRn' %prop)", "else", ":", "raise", "UcsValidationException", "(", "'Property \"%s\" was not found in MakeRn arguments'", "%", "prop", ")", "# raise Exception('Property \"%s\" was not found in MakeRn arguments' %prop)", "return", "rnPattern" ]
This method returns the Rn for a managed object.
[ "This", "method", "returns", "the", "Rn", "for", "a", "managed", "object", "." ]
bf6b07d6abeacb922c92b198352eda4eb9e4629b
https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L277-L291
train
CiscoUcs/UcsPythonSDK
src/UcsSdk/UcsBase.py
ManagedObject.LoadFromXml
def LoadFromXml(self, node, handle): """ Method updates the object from the xml representation of the managed object. """ self.SetHandle(handle) if node.hasAttributes(): # attributes = node._get_attributes() # attCount = attributes._get_length() attributes = node.attributes attCount = len(attributes) for i in range(attCount): attNode = attributes.item(i) # attr = UcsUtils.WordU(attNode._get_name()) attr = UcsUtils.WordU(attNode.localName) if (UcsUtils.FindClassIdInMoMetaIgnoreCase(self.classId) != None): if (attr in UcsUtils.GetUcsPropertyMetaAttributeList(self.classId)): # self.setattr(attr, str(attNode.nodeValue)) self.setattr(attr, str(attNode.value)) else: # self.setattr(UcsUtils.WordU(attr), str(attNode.nodeValue)) self.setattr(UcsUtils.WordU(attr), str(attNode.value)) else: # self.setattr(UcsUtils.WordU(attr), str(attNode.nodeValue)) self.setattr(UcsUtils.WordU(attr), str(attNode.value)) if self.getattr("Rn") == None and self.getattr("Dn") != None: self.setattr("Rn", str(re.sub(r'^.*/', '', self.getattr("Dn")))) if (node.hasChildNodes()): # childList = node._get_childNodes() # childCount = childList._get_length() childList = node.childNodes childCount = len(childList) for i in range(childCount): childNode = childList.item(i) if (childNode.nodeType != Node.ELEMENT_NODE): continue if childNode.localName in self.propMoMeta.fieldNames: # .LoadFromXml(childNode, handle) pass # TODO: Need code analysis. # if childNode.localName in self.propMoMeta.childFieldNames: c = ManagedObject(UcsUtils.WordU(childNode.localName)) self.child.append(c) c.LoadFromXml(childNode, handle)
python
def LoadFromXml(self, node, handle): """ Method updates the object from the xml representation of the managed object. """ self.SetHandle(handle) if node.hasAttributes(): # attributes = node._get_attributes() # attCount = attributes._get_length() attributes = node.attributes attCount = len(attributes) for i in range(attCount): attNode = attributes.item(i) # attr = UcsUtils.WordU(attNode._get_name()) attr = UcsUtils.WordU(attNode.localName) if (UcsUtils.FindClassIdInMoMetaIgnoreCase(self.classId) != None): if (attr in UcsUtils.GetUcsPropertyMetaAttributeList(self.classId)): # self.setattr(attr, str(attNode.nodeValue)) self.setattr(attr, str(attNode.value)) else: # self.setattr(UcsUtils.WordU(attr), str(attNode.nodeValue)) self.setattr(UcsUtils.WordU(attr), str(attNode.value)) else: # self.setattr(UcsUtils.WordU(attr), str(attNode.nodeValue)) self.setattr(UcsUtils.WordU(attr), str(attNode.value)) if self.getattr("Rn") == None and self.getattr("Dn") != None: self.setattr("Rn", str(re.sub(r'^.*/', '', self.getattr("Dn")))) if (node.hasChildNodes()): # childList = node._get_childNodes() # childCount = childList._get_length() childList = node.childNodes childCount = len(childList) for i in range(childCount): childNode = childList.item(i) if (childNode.nodeType != Node.ELEMENT_NODE): continue if childNode.localName in self.propMoMeta.fieldNames: # .LoadFromXml(childNode, handle) pass # TODO: Need code analysis. # if childNode.localName in self.propMoMeta.childFieldNames: c = ManagedObject(UcsUtils.WordU(childNode.localName)) self.child.append(c) c.LoadFromXml(childNode, handle)
[ "def", "LoadFromXml", "(", "self", ",", "node", ",", "handle", ")", ":", "self", ".", "SetHandle", "(", "handle", ")", "if", "node", ".", "hasAttributes", "(", ")", ":", "# attributes = node._get_attributes()", "# attCount = attributes._get_length()", "attributes", "=", "node", ".", "attributes", "attCount", "=", "len", "(", "attributes", ")", "for", "i", "in", "range", "(", "attCount", ")", ":", "attNode", "=", "attributes", ".", "item", "(", "i", ")", "# attr = UcsUtils.WordU(attNode._get_name())", "attr", "=", "UcsUtils", ".", "WordU", "(", "attNode", ".", "localName", ")", "if", "(", "UcsUtils", ".", "FindClassIdInMoMetaIgnoreCase", "(", "self", ".", "classId", ")", "!=", "None", ")", ":", "if", "(", "attr", "in", "UcsUtils", ".", "GetUcsPropertyMetaAttributeList", "(", "self", ".", "classId", ")", ")", ":", "# self.setattr(attr, str(attNode.nodeValue))", "self", ".", "setattr", "(", "attr", ",", "str", "(", "attNode", ".", "value", ")", ")", "else", ":", "# self.setattr(UcsUtils.WordU(attr), str(attNode.nodeValue))", "self", ".", "setattr", "(", "UcsUtils", ".", "WordU", "(", "attr", ")", ",", "str", "(", "attNode", ".", "value", ")", ")", "else", ":", "# self.setattr(UcsUtils.WordU(attr), str(attNode.nodeValue))", "self", ".", "setattr", "(", "UcsUtils", ".", "WordU", "(", "attr", ")", ",", "str", "(", "attNode", ".", "value", ")", ")", "if", "self", ".", "getattr", "(", "\"Rn\"", ")", "==", "None", "and", "self", ".", "getattr", "(", "\"Dn\"", ")", "!=", "None", ":", "self", ".", "setattr", "(", "\"Rn\"", ",", "str", "(", "re", ".", "sub", "(", "r'^.*/'", ",", "''", ",", "self", ".", "getattr", "(", "\"Dn\"", ")", ")", ")", ")", "if", "(", "node", ".", "hasChildNodes", "(", ")", ")", ":", "# childList = node._get_childNodes()", "# childCount = childList._get_length()", "childList", "=", "node", ".", "childNodes", "childCount", "=", "len", "(", "childList", ")", "for", "i", "in", "range", "(", "childCount", ")", ":", "childNode", "=", "childList", ".", "item", "(", "i", ")", "if", "(", "childNode", ".", "nodeType", "!=", "Node", ".", "ELEMENT_NODE", ")", ":", "continue", "if", "childNode", ".", "localName", "in", "self", ".", "propMoMeta", ".", "fieldNames", ":", "# .LoadFromXml(childNode, handle)", "pass", "# TODO: Need code analysis.", "# if childNode.localName in self.propMoMeta.childFieldNames:", "c", "=", "ManagedObject", "(", "UcsUtils", ".", "WordU", "(", "childNode", ".", "localName", ")", ")", "self", ".", "child", ".", "append", "(", "c", ")", "c", ".", "LoadFromXml", "(", "childNode", ",", "handle", ")" ]
Method updates the object from the xml representation of the managed object.
[ "Method", "updates", "the", "object", "from", "the", "xml", "representation", "of", "the", "managed", "object", "." ]
bf6b07d6abeacb922c92b198352eda4eb9e4629b
https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L319-L362
train
CiscoUcs/UcsPythonSDK
src/UcsSdk/UcsBase.py
ExternalMethod.setattr
def setattr(self, key, value): """ This method sets the attribute of external method object. """ if key in _MethodFactoryMeta[self.classId]: self.__dict__[key] = value elif key == 'errorCode': self.errorCode = value elif key == 'errorDescr': self.errorDescr = value elif key == 'invocationResult': self.invocationResult = value elif key == 'response': self.response = value else: """ no such property """ # print "No such property ClassId: %s Property:%s" %(self.classId, key) return None
python
def setattr(self, key, value): """ This method sets the attribute of external method object. """ if key in _MethodFactoryMeta[self.classId]: self.__dict__[key] = value elif key == 'errorCode': self.errorCode = value elif key == 'errorDescr': self.errorDescr = value elif key == 'invocationResult': self.invocationResult = value elif key == 'response': self.response = value else: """ no such property """ # print "No such property ClassId: %s Property:%s" %(self.classId, key) return None
[ "def", "setattr", "(", "self", ",", "key", ",", "value", ")", ":", "if", "key", "in", "_MethodFactoryMeta", "[", "self", ".", "classId", "]", ":", "self", ".", "__dict__", "[", "key", "]", "=", "value", "elif", "key", "==", "'errorCode'", ":", "self", ".", "errorCode", "=", "value", "elif", "key", "==", "'errorDescr'", ":", "self", ".", "errorDescr", "=", "value", "elif", "key", "==", "'invocationResult'", ":", "self", ".", "invocationResult", "=", "value", "elif", "key", "==", "'response'", ":", "self", ".", "response", "=", "value", "else", ":", "\"\"\" no such property \"\"\"", "# print \"No such property ClassId: %s Property:%s\" %(self.classId, key)", "return", "None" ]
This method sets the attribute of external method object.
[ "This", "method", "sets", "the", "attribute", "of", "external", "method", "object", "." ]
bf6b07d6abeacb922c92b198352eda4eb9e4629b
https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L406-L421
train
CiscoUcs/UcsPythonSDK
src/UcsSdk/UcsBase.py
ExternalMethod.getattr
def getattr(self, key): """ This method gets the attribute value of external method object. """ if key in _MethodFactoryMeta[self.classId]: """ property exists """ return self.__dict__[key] else: """ property does not exist """ return None
python
def getattr(self, key): """ This method gets the attribute value of external method object. """ if key in _MethodFactoryMeta[self.classId]: """ property exists """ return self.__dict__[key] else: """ property does not exist """ return None
[ "def", "getattr", "(", "self", ",", "key", ")", ":", "if", "key", "in", "_MethodFactoryMeta", "[", "self", ".", "classId", "]", ":", "\"\"\" property exists \"\"\"", "return", "self", ".", "__dict__", "[", "key", "]", "else", ":", "\"\"\" property does not exist \"\"\"", "return", "None" ]
This method gets the attribute value of external method object.
[ "This", "method", "gets", "the", "attribute", "value", "of", "external", "method", "object", "." ]
bf6b07d6abeacb922c92b198352eda4eb9e4629b
https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L423-L430
train
CiscoUcs/UcsPythonSDK
src/UcsSdk/UcsBase.py
ExternalMethod.getErrorResponse
def getErrorResponse(self, errorCode, errorDescr): """ This methods sets error attributes of an external method object. """ self.errorCode = errorCode self.errorDescr = errorDescr self.response = "yes" return self
python
def getErrorResponse(self, errorCode, errorDescr): """ This methods sets error attributes of an external method object. """ self.errorCode = errorCode self.errorDescr = errorDescr self.response = "yes" return self
[ "def", "getErrorResponse", "(", "self", ",", "errorCode", ",", "errorDescr", ")", ":", "self", ".", "errorCode", "=", "errorCode", "self", ".", "errorDescr", "=", "errorDescr", "self", ".", "response", "=", "\"yes\"", "return", "self" ]
This methods sets error attributes of an external method object.
[ "This", "methods", "sets", "error", "attributes", "of", "an", "external", "method", "object", "." ]
bf6b07d6abeacb922c92b198352eda4eb9e4629b
https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L432-L437
train
CiscoUcs/UcsPythonSDK
src/UcsSdk/UcsBase.py
UcsUtils.GetUcsPropertyMeta
def GetUcsPropertyMeta(classId, key): """ Methods returns the property meta of the provided key for the given classId. """ if classId in _ManagedObjectMeta: if key in _ManagedObjectMeta[classId]: return _ManagedObjectMeta[classId][key] return None
python
def GetUcsPropertyMeta(classId, key): """ Methods returns the property meta of the provided key for the given classId. """ if classId in _ManagedObjectMeta: if key in _ManagedObjectMeta[classId]: return _ManagedObjectMeta[classId][key] return None
[ "def", "GetUcsPropertyMeta", "(", "classId", ",", "key", ")", ":", "if", "classId", "in", "_ManagedObjectMeta", ":", "if", "key", "in", "_ManagedObjectMeta", "[", "classId", "]", ":", "return", "_ManagedObjectMeta", "[", "classId", "]", "[", "key", "]", "return", "None" ]
Methods returns the property meta of the provided key for the given classId.
[ "Methods", "returns", "the", "property", "meta", "of", "the", "provided", "key", "for", "the", "given", "classId", "." ]
bf6b07d6abeacb922c92b198352eda4eb9e4629b
https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L518-L523
train
CiscoUcs/UcsPythonSDK
src/UcsSdk/UcsBase.py
UcsUtils.GetUcsMethodMeta
def GetUcsMethodMeta(classId, key): """ Methods returns the method meta of the ExternalMethod. """ if classId in _MethodFactoryMeta: if key in _MethodFactoryMeta[classId]: return _MethodFactoryMeta[classId][key] return None
python
def GetUcsMethodMeta(classId, key): """ Methods returns the method meta of the ExternalMethod. """ if classId in _MethodFactoryMeta: if key in _MethodFactoryMeta[classId]: return _MethodFactoryMeta[classId][key] return None
[ "def", "GetUcsMethodMeta", "(", "classId", ",", "key", ")", ":", "if", "classId", "in", "_MethodFactoryMeta", ":", "if", "key", "in", "_MethodFactoryMeta", "[", "classId", "]", ":", "return", "_MethodFactoryMeta", "[", "classId", "]", "[", "key", "]", "return", "None" ]
Methods returns the method meta of the ExternalMethod.
[ "Methods", "returns", "the", "method", "meta", "of", "the", "ExternalMethod", "." ]
bf6b07d6abeacb922c92b198352eda4eb9e4629b
https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L526-L531
train
CiscoUcs/UcsPythonSDK
src/UcsSdk/UcsBase.py
UcsUtils.GetUcsPropertyMetaAttributeList
def GetUcsPropertyMetaAttributeList(classId): """ Methods returns the class meta. """ if classId in _ManagedObjectMeta: attrList = _ManagedObjectMeta[classId].keys() attrList.remove("Meta") return attrList if classId in _MethodFactoryMeta: attrList = _MethodFactoryMeta[classId].keys() attrList.remove("Meta") return attrList # If the case of classId is not as in Meta nci = UcsUtils.FindClassIdInMoMetaIgnoreCase(classId) if (nci != None): attrList = _ManagedObjectMeta[nci].keys() attrList.remove("Meta") return attrList nci = UcsUtils.FindClassIdInMethodMetaIgnoreCase(classId) if (nci != None): attrList = _MethodFactoryMeta[nci].keys() attrList.remove("Meta") return attrList return None
python
def GetUcsPropertyMetaAttributeList(classId): """ Methods returns the class meta. """ if classId in _ManagedObjectMeta: attrList = _ManagedObjectMeta[classId].keys() attrList.remove("Meta") return attrList if classId in _MethodFactoryMeta: attrList = _MethodFactoryMeta[classId].keys() attrList.remove("Meta") return attrList # If the case of classId is not as in Meta nci = UcsUtils.FindClassIdInMoMetaIgnoreCase(classId) if (nci != None): attrList = _ManagedObjectMeta[nci].keys() attrList.remove("Meta") return attrList nci = UcsUtils.FindClassIdInMethodMetaIgnoreCase(classId) if (nci != None): attrList = _MethodFactoryMeta[nci].keys() attrList.remove("Meta") return attrList return None
[ "def", "GetUcsPropertyMetaAttributeList", "(", "classId", ")", ":", "if", "classId", "in", "_ManagedObjectMeta", ":", "attrList", "=", "_ManagedObjectMeta", "[", "classId", "]", ".", "keys", "(", ")", "attrList", ".", "remove", "(", "\"Meta\"", ")", "return", "attrList", "if", "classId", "in", "_MethodFactoryMeta", ":", "attrList", "=", "_MethodFactoryMeta", "[", "classId", "]", ".", "keys", "(", ")", "attrList", ".", "remove", "(", "\"Meta\"", ")", "return", "attrList", "# If the case of classId is not as in Meta", "nci", "=", "UcsUtils", ".", "FindClassIdInMoMetaIgnoreCase", "(", "classId", ")", "if", "(", "nci", "!=", "None", ")", ":", "attrList", "=", "_ManagedObjectMeta", "[", "nci", "]", ".", "keys", "(", ")", "attrList", ".", "remove", "(", "\"Meta\"", ")", "return", "attrList", "nci", "=", "UcsUtils", ".", "FindClassIdInMethodMetaIgnoreCase", "(", "classId", ")", "if", "(", "nci", "!=", "None", ")", ":", "attrList", "=", "_MethodFactoryMeta", "[", "nci", "]", ".", "keys", "(", ")", "attrList", ".", "remove", "(", "\"Meta\"", ")", "return", "attrList", "return", "None" ]
Methods returns the class meta.
[ "Methods", "returns", "the", "class", "meta", "." ]
bf6b07d6abeacb922c92b198352eda4eb9e4629b
https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L534-L558
train
CiscoUcs/UcsPythonSDK
src/UcsSdk/UcsBase.py
UcsUtils.IsPropertyInMetaIgnoreCase
def IsPropertyInMetaIgnoreCase(classId, key): """ Methods returns the property meta of the provided key for the given classId. Given key is case insensitive. """ if classId in _ManagedObjectMeta: for prop in _ManagedObjectMeta[classId]: if (prop.lower() == key.lower()): return _ManagedObjectMeta[classId][prop] if classId in _MethodFactoryMeta: for prop in _MethodFactoryMeta[classId]: if (prop.lower() == key.lower()): return _MethodFactoryMeta[classId][prop] return None
python
def IsPropertyInMetaIgnoreCase(classId, key): """ Methods returns the property meta of the provided key for the given classId. Given key is case insensitive. """ if classId in _ManagedObjectMeta: for prop in _ManagedObjectMeta[classId]: if (prop.lower() == key.lower()): return _ManagedObjectMeta[classId][prop] if classId in _MethodFactoryMeta: for prop in _MethodFactoryMeta[classId]: if (prop.lower() == key.lower()): return _MethodFactoryMeta[classId][prop] return None
[ "def", "IsPropertyInMetaIgnoreCase", "(", "classId", ",", "key", ")", ":", "if", "classId", "in", "_ManagedObjectMeta", ":", "for", "prop", "in", "_ManagedObjectMeta", "[", "classId", "]", ":", "if", "(", "prop", ".", "lower", "(", ")", "==", "key", ".", "lower", "(", ")", ")", ":", "return", "_ManagedObjectMeta", "[", "classId", "]", "[", "prop", "]", "if", "classId", "in", "_MethodFactoryMeta", ":", "for", "prop", "in", "_MethodFactoryMeta", "[", "classId", "]", ":", "if", "(", "prop", ".", "lower", "(", ")", "==", "key", ".", "lower", "(", ")", ")", ":", "return", "_MethodFactoryMeta", "[", "classId", "]", "[", "prop", "]", "return", "None" ]
Methods returns the property meta of the provided key for the given classId. Given key is case insensitive.
[ "Methods", "returns", "the", "property", "meta", "of", "the", "provided", "key", "for", "the", "given", "classId", ".", "Given", "key", "is", "case", "insensitive", "." ]
bf6b07d6abeacb922c92b198352eda4eb9e4629b
https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L561-L571
train
CiscoUcs/UcsPythonSDK
src/UcsSdk/UcsBase.py
UcsUtils.CheckRegistryKey
def CheckRegistryKey(javaKey): """ Method checks for the java in the registry entries. """ from _winreg import ConnectRegistry, HKEY_LOCAL_MACHINE, OpenKey, QueryValueEx path = None try: aReg = ConnectRegistry(None, HKEY_LOCAL_MACHINE) rk = OpenKey(aReg, javaKey) for i in range(1024): currentVersion = QueryValueEx(rk, "CurrentVersion") if currentVersion != None: key = OpenKey(rk, currentVersion[0]) if key != None: path = QueryValueEx(key, "JavaHome") return path[0] except Exception, err: # TODO: Add Warning/Error messages in Logger. WriteUcsWarning("Not able to access registry.") return None
python
def CheckRegistryKey(javaKey): """ Method checks for the java in the registry entries. """ from _winreg import ConnectRegistry, HKEY_LOCAL_MACHINE, OpenKey, QueryValueEx path = None try: aReg = ConnectRegistry(None, HKEY_LOCAL_MACHINE) rk = OpenKey(aReg, javaKey) for i in range(1024): currentVersion = QueryValueEx(rk, "CurrentVersion") if currentVersion != None: key = OpenKey(rk, currentVersion[0]) if key != None: path = QueryValueEx(key, "JavaHome") return path[0] except Exception, err: # TODO: Add Warning/Error messages in Logger. WriteUcsWarning("Not able to access registry.") return None
[ "def", "CheckRegistryKey", "(", "javaKey", ")", ":", "from", "_winreg", "import", "ConnectRegistry", ",", "HKEY_LOCAL_MACHINE", ",", "OpenKey", ",", "QueryValueEx", "path", "=", "None", "try", ":", "aReg", "=", "ConnectRegistry", "(", "None", ",", "HKEY_LOCAL_MACHINE", ")", "rk", "=", "OpenKey", "(", "aReg", ",", "javaKey", ")", "for", "i", "in", "range", "(", "1024", ")", ":", "currentVersion", "=", "QueryValueEx", "(", "rk", ",", "\"CurrentVersion\"", ")", "if", "currentVersion", "!=", "None", ":", "key", "=", "OpenKey", "(", "rk", ",", "currentVersion", "[", "0", "]", ")", "if", "key", "!=", "None", ":", "path", "=", "QueryValueEx", "(", "key", ",", "\"JavaHome\"", ")", "return", "path", "[", "0", "]", "except", "Exception", ",", "err", ":", "# TODO: Add Warning/Error messages in Logger.", "WriteUcsWarning", "(", "\"Not able to access registry.\"", ")", "return", "None" ]
Method checks for the java in the registry entries.
[ "Method", "checks", "for", "the", "java", "in", "the", "registry", "entries", "." ]
bf6b07d6abeacb922c92b198352eda4eb9e4629b
https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L654-L672
train
CiscoUcs/UcsPythonSDK
src/UcsSdk/UcsBase.py
UcsUtils.GetJavaInstallationPath
def GetJavaInstallationPath(): """ Method returns the java installation path in the windows or Linux environment. """ import os, platform # Get JavaPath for Ubuntu # if os.name == "posix": if platform.system() == "Linux": path = os.environ.get('JAVA_HOME') if not path: raise UcsValidationException( "Please make sure JAVA is installed and variable JAVA_HOME is set properly.") # raise Exception("Please make sure JAVA is installed and variable JAVA_HOME is set properly.") else: path = os.path.join(path, 'bin') path = os.path.join(path, 'javaws') if not os.path.exists(path): raise UcsValidationException("javaws is not installed on System.") # raise Exception("javaws is not installed on System.") else: return path # Get JavaPath for Windows # elif os.name == "nt": elif platform.system() == "Windows" or platform.system() == "Microsoft": path = os.environ.get('JAVA_HOME') if path == None: path = UcsUtils.CheckRegistryKey(r"SOFTWARE\\JavaSoft\\Java Runtime Environment\\") if path == None: # Check for 32 bit Java on 64 bit machine. path = UcsUtils.CheckRegistryKey(r"SOFTWARE\\Wow6432Node\\JavaSoft\\Java Runtime Environment") if not path: raise UcsValidationException("Please make sure JAVA is installed.") # raise Exception("Please make sure JAVA is installed.") else: path = os.path.join(path, 'bin') path = os.path.join(path, 'javaws.exe') if not os.path.exists(path): raise UcsValidationException("javaws.exe is not installed on System.") # raise Exception("javaws.exe is not installed on System.") else: return path
python
def GetJavaInstallationPath(): """ Method returns the java installation path in the windows or Linux environment. """ import os, platform # Get JavaPath for Ubuntu # if os.name == "posix": if platform.system() == "Linux": path = os.environ.get('JAVA_HOME') if not path: raise UcsValidationException( "Please make sure JAVA is installed and variable JAVA_HOME is set properly.") # raise Exception("Please make sure JAVA is installed and variable JAVA_HOME is set properly.") else: path = os.path.join(path, 'bin') path = os.path.join(path, 'javaws') if not os.path.exists(path): raise UcsValidationException("javaws is not installed on System.") # raise Exception("javaws is not installed on System.") else: return path # Get JavaPath for Windows # elif os.name == "nt": elif platform.system() == "Windows" or platform.system() == "Microsoft": path = os.environ.get('JAVA_HOME') if path == None: path = UcsUtils.CheckRegistryKey(r"SOFTWARE\\JavaSoft\\Java Runtime Environment\\") if path == None: # Check for 32 bit Java on 64 bit machine. path = UcsUtils.CheckRegistryKey(r"SOFTWARE\\Wow6432Node\\JavaSoft\\Java Runtime Environment") if not path: raise UcsValidationException("Please make sure JAVA is installed.") # raise Exception("Please make sure JAVA is installed.") else: path = os.path.join(path, 'bin') path = os.path.join(path, 'javaws.exe') if not os.path.exists(path): raise UcsValidationException("javaws.exe is not installed on System.") # raise Exception("javaws.exe is not installed on System.") else: return path
[ "def", "GetJavaInstallationPath", "(", ")", ":", "import", "os", ",", "platform", "# Get JavaPath for Ubuntu", "# if os.name == \"posix\":", "if", "platform", ".", "system", "(", ")", "==", "\"Linux\"", ":", "path", "=", "os", ".", "environ", ".", "get", "(", "'JAVA_HOME'", ")", "if", "not", "path", ":", "raise", "UcsValidationException", "(", "\"Please make sure JAVA is installed and variable JAVA_HOME is set properly.\"", ")", "# raise Exception(\"Please make sure JAVA is installed and variable JAVA_HOME is set properly.\")", "else", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'bin'", ")", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'javaws'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise", "UcsValidationException", "(", "\"javaws is not installed on System.\"", ")", "# raise Exception(\"javaws is not installed on System.\")", "else", ":", "return", "path", "# Get JavaPath for Windows", "# elif os.name == \"nt\":", "elif", "platform", ".", "system", "(", ")", "==", "\"Windows\"", "or", "platform", ".", "system", "(", ")", "==", "\"Microsoft\"", ":", "path", "=", "os", ".", "environ", ".", "get", "(", "'JAVA_HOME'", ")", "if", "path", "==", "None", ":", "path", "=", "UcsUtils", ".", "CheckRegistryKey", "(", "r\"SOFTWARE\\\\JavaSoft\\\\Java Runtime Environment\\\\\"", ")", "if", "path", "==", "None", ":", "# Check for 32 bit Java on 64 bit machine.", "path", "=", "UcsUtils", ".", "CheckRegistryKey", "(", "r\"SOFTWARE\\\\Wow6432Node\\\\JavaSoft\\\\Java Runtime Environment\"", ")", "if", "not", "path", ":", "raise", "UcsValidationException", "(", "\"Please make sure JAVA is installed.\"", ")", "# raise Exception(\"Please make sure JAVA is installed.\")", "else", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'bin'", ")", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'javaws.exe'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise", "UcsValidationException", "(", "\"javaws.exe is not installed on System.\"", ")", "# raise Exception(\"javaws.exe is not installed on System.\")", "else", ":", "return", "path" ]
Method returns the java installation path in the windows or Linux environment.
[ "Method", "returns", "the", "java", "installation", "path", "in", "the", "windows", "or", "Linux", "environment", "." ]
bf6b07d6abeacb922c92b198352eda4eb9e4629b
https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L675-L718
train
CiscoUcs/UcsPythonSDK
src/UcsSdk/UcsBase.py
UcsUtils.DownloadFile
def DownloadFile(hUcs, source, destination): """ Method provides the functionality to download file from the UCS. This method is used in BackupUcs and GetTechSupport to download the files from the Ucs. """ import urllib2 from sys import stdout from time import sleep httpAddress = "%s/%s" % (hUcs.Uri(), source) file_name = httpAddress.split('/')[-1] req = urllib2.Request(httpAddress) # send the new url with the cookie. req.add_header('Cookie', 'ucsm-cookie=%s' % (hUcs._cookie)) res = urllib2.urlopen(req) meta = res.info() file_size = int(meta.getheaders("Content-Length")[0]) print "Downloading: %s Bytes: %s" % (file_name, file_size) f = open(destination, 'wb') file_size_dl = 0 block_sz = 8192 while True: rBuffer = res.read(block_sz) if not rBuffer: break file_size_dl += len(rBuffer) f.write(rBuffer) status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size) status = status + chr(8) * (len(status) + 1) stdout.write("\r%s" % status) stdout.flush() # print status f.close()
python
def DownloadFile(hUcs, source, destination): """ Method provides the functionality to download file from the UCS. This method is used in BackupUcs and GetTechSupport to download the files from the Ucs. """ import urllib2 from sys import stdout from time import sleep httpAddress = "%s/%s" % (hUcs.Uri(), source) file_name = httpAddress.split('/')[-1] req = urllib2.Request(httpAddress) # send the new url with the cookie. req.add_header('Cookie', 'ucsm-cookie=%s' % (hUcs._cookie)) res = urllib2.urlopen(req) meta = res.info() file_size = int(meta.getheaders("Content-Length")[0]) print "Downloading: %s Bytes: %s" % (file_name, file_size) f = open(destination, 'wb') file_size_dl = 0 block_sz = 8192 while True: rBuffer = res.read(block_sz) if not rBuffer: break file_size_dl += len(rBuffer) f.write(rBuffer) status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size) status = status + chr(8) * (len(status) + 1) stdout.write("\r%s" % status) stdout.flush() # print status f.close()
[ "def", "DownloadFile", "(", "hUcs", ",", "source", ",", "destination", ")", ":", "import", "urllib2", "from", "sys", "import", "stdout", "from", "time", "import", "sleep", "httpAddress", "=", "\"%s/%s\"", "%", "(", "hUcs", ".", "Uri", "(", ")", ",", "source", ")", "file_name", "=", "httpAddress", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "req", "=", "urllib2", ".", "Request", "(", "httpAddress", ")", "# send the new url with the cookie.", "req", ".", "add_header", "(", "'Cookie'", ",", "'ucsm-cookie=%s'", "%", "(", "hUcs", ".", "_cookie", ")", ")", "res", "=", "urllib2", ".", "urlopen", "(", "req", ")", "meta", "=", "res", ".", "info", "(", ")", "file_size", "=", "int", "(", "meta", ".", "getheaders", "(", "\"Content-Length\"", ")", "[", "0", "]", ")", "print", "\"Downloading: %s Bytes: %s\"", "%", "(", "file_name", ",", "file_size", ")", "f", "=", "open", "(", "destination", ",", "'wb'", ")", "file_size_dl", "=", "0", "block_sz", "=", "8192", "while", "True", ":", "rBuffer", "=", "res", ".", "read", "(", "block_sz", ")", "if", "not", "rBuffer", ":", "break", "file_size_dl", "+=", "len", "(", "rBuffer", ")", "f", ".", "write", "(", "rBuffer", ")", "status", "=", "r\"%10d [%3.2f%%]\"", "%", "(", "file_size_dl", ",", "file_size_dl", "*", "100.", "/", "file_size", ")", "status", "=", "status", "+", "chr", "(", "8", ")", "*", "(", "len", "(", "status", ")", "+", "1", ")", "stdout", ".", "write", "(", "\"\\r%s\"", "%", "status", ")", "stdout", ".", "flush", "(", ")", "# print status", "f", ".", "close", "(", ")" ]
Method provides the functionality to download file from the UCS. This method is used in BackupUcs and GetTechSupport to download the files from the Ucs.
[ "Method", "provides", "the", "functionality", "to", "download", "file", "from", "the", "UCS", ".", "This", "method", "is", "used", "in", "BackupUcs", "and", "GetTechSupport", "to", "download", "the", "files", "from", "the", "Ucs", "." ]
bf6b07d6abeacb922c92b198352eda4eb9e4629b
https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L721-L757
train
CiscoUcs/UcsPythonSDK
src/UcsSdk/UcsBase.py
UcsUtils.GetSyncMoConfigFilePath
def GetSyncMoConfigFilePath(): """ Method returs the path of SyncMoConfig.xml file. """ return os.path.join(os.path.join(os.path.dirname(__file__), "resources"), "SyncMoConfig.xml")
python
def GetSyncMoConfigFilePath(): """ Method returs the path of SyncMoConfig.xml file. """ return os.path.join(os.path.join(os.path.dirname(__file__), "resources"), "SyncMoConfig.xml")
[ "def", "GetSyncMoConfigFilePath", "(", ")", ":", "return", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "\"resources\"", ")", ",", "\"SyncMoConfig.xml\"", ")" ]
Method returs the path of SyncMoConfig.xml file.
[ "Method", "returs", "the", "path", "of", "SyncMoConfig", ".", "xml", "file", "." ]
bf6b07d6abeacb922c92b198352eda4eb9e4629b
https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L760-L762
train
CiscoUcs/UcsPythonSDK
src/UcsSdk/UcsBase.py
UcsUtils.GetSyncMoConfig
def GetSyncMoConfig(ConfigDoc): """ Internal support method for SyncManagedObject. """ moConfigMap = {} configList = ConfigDoc.getElementsByTagName("mo") for moConfigNode in configList: classId = None noun = None version = None actionVersion = None action = None ignoreReason = None status = None excludeList = None if moConfigNode.hasAttribute("classid"): classId = moConfigNode.getAttribute("classid") if moConfigNode.hasAttribute("noun"): noun = moConfigNode.getAttribute("noun") if moConfigNode.hasAttribute("version"): version = moConfigNode.getAttribute("version") if moConfigNode.hasAttribute("actionVersion"): actionVersion = moConfigNode.getAttribute("actionVersion") if moConfigNode.hasAttribute("action"): action = moConfigNode.getAttribute("action") if moConfigNode.hasAttribute("ignoreReason"): ignoreReason = moConfigNode.getAttribute("ignoreReason") if moConfigNode.hasAttribute("status"): status = moConfigNode.getAttribute("status") if moConfigNode.hasAttribute("excludeList"): excludeList = moConfigNode.getAttribute("excludeList") # SyncMoConfig Object moConfig = None if classId: moConfig = SyncMoConfig(classId, noun, version, actionVersion, action, ignoreReason, status, excludeList) if moConfig: if classId in moConfigMap: moConfigMap[classId] = moConfig else: moConfigList = [] moConfigList.append(moConfig) moConfigMap[classId] = moConfigList return moConfigMap
python
def GetSyncMoConfig(ConfigDoc): """ Internal support method for SyncManagedObject. """ moConfigMap = {} configList = ConfigDoc.getElementsByTagName("mo") for moConfigNode in configList: classId = None noun = None version = None actionVersion = None action = None ignoreReason = None status = None excludeList = None if moConfigNode.hasAttribute("classid"): classId = moConfigNode.getAttribute("classid") if moConfigNode.hasAttribute("noun"): noun = moConfigNode.getAttribute("noun") if moConfigNode.hasAttribute("version"): version = moConfigNode.getAttribute("version") if moConfigNode.hasAttribute("actionVersion"): actionVersion = moConfigNode.getAttribute("actionVersion") if moConfigNode.hasAttribute("action"): action = moConfigNode.getAttribute("action") if moConfigNode.hasAttribute("ignoreReason"): ignoreReason = moConfigNode.getAttribute("ignoreReason") if moConfigNode.hasAttribute("status"): status = moConfigNode.getAttribute("status") if moConfigNode.hasAttribute("excludeList"): excludeList = moConfigNode.getAttribute("excludeList") # SyncMoConfig Object moConfig = None if classId: moConfig = SyncMoConfig(classId, noun, version, actionVersion, action, ignoreReason, status, excludeList) if moConfig: if classId in moConfigMap: moConfigMap[classId] = moConfig else: moConfigList = [] moConfigList.append(moConfig) moConfigMap[classId] = moConfigList return moConfigMap
[ "def", "GetSyncMoConfig", "(", "ConfigDoc", ")", ":", "moConfigMap", "=", "{", "}", "configList", "=", "ConfigDoc", ".", "getElementsByTagName", "(", "\"mo\"", ")", "for", "moConfigNode", "in", "configList", ":", "classId", "=", "None", "noun", "=", "None", "version", "=", "None", "actionVersion", "=", "None", "action", "=", "None", "ignoreReason", "=", "None", "status", "=", "None", "excludeList", "=", "None", "if", "moConfigNode", ".", "hasAttribute", "(", "\"classid\"", ")", ":", "classId", "=", "moConfigNode", ".", "getAttribute", "(", "\"classid\"", ")", "if", "moConfigNode", ".", "hasAttribute", "(", "\"noun\"", ")", ":", "noun", "=", "moConfigNode", ".", "getAttribute", "(", "\"noun\"", ")", "if", "moConfigNode", ".", "hasAttribute", "(", "\"version\"", ")", ":", "version", "=", "moConfigNode", ".", "getAttribute", "(", "\"version\"", ")", "if", "moConfigNode", ".", "hasAttribute", "(", "\"actionVersion\"", ")", ":", "actionVersion", "=", "moConfigNode", ".", "getAttribute", "(", "\"actionVersion\"", ")", "if", "moConfigNode", ".", "hasAttribute", "(", "\"action\"", ")", ":", "action", "=", "moConfigNode", ".", "getAttribute", "(", "\"action\"", ")", "if", "moConfigNode", ".", "hasAttribute", "(", "\"ignoreReason\"", ")", ":", "ignoreReason", "=", "moConfigNode", ".", "getAttribute", "(", "\"ignoreReason\"", ")", "if", "moConfigNode", ".", "hasAttribute", "(", "\"status\"", ")", ":", "status", "=", "moConfigNode", ".", "getAttribute", "(", "\"status\"", ")", "if", "moConfigNode", ".", "hasAttribute", "(", "\"excludeList\"", ")", ":", "excludeList", "=", "moConfigNode", ".", "getAttribute", "(", "\"excludeList\"", ")", "# SyncMoConfig Object", "moConfig", "=", "None", "if", "classId", ":", "moConfig", "=", "SyncMoConfig", "(", "classId", ",", "noun", ",", "version", ",", "actionVersion", ",", "action", ",", "ignoreReason", ",", "status", ",", "excludeList", ")", "if", "moConfig", ":", "if", "classId", "in", "moConfigMap", ":", "moConfigMap", "[", "classId", "]", "=", "moConfig", "else", ":", "moConfigList", "=", "[", "]", "moConfigList", ".", "append", "(", "moConfig", ")", "moConfigMap", "[", "classId", "]", "=", "moConfigList", "return", "moConfigMap" ]
Internal support method for SyncManagedObject.
[ "Internal", "support", "method", "for", "SyncManagedObject", "." ]
bf6b07d6abeacb922c92b198352eda4eb9e4629b
https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L765-L819
train
CiscoUcs/UcsPythonSDK
src/UcsSdk/UcsBase.py
UcsUtils.Expandkey
def Expandkey(key, clen): """ Internal method supporting encryption and decryption functionality. """ import sha from string import join from array import array blocks = (clen + 19) / 20 xkey = [] seed = key for i in xrange(blocks): seed = sha.new(key + seed).digest() xkey.append(seed) j = join(xkey, '') return array('L', j)
python
def Expandkey(key, clen): """ Internal method supporting encryption and decryption functionality. """ import sha from string import join from array import array blocks = (clen + 19) / 20 xkey = [] seed = key for i in xrange(blocks): seed = sha.new(key + seed).digest() xkey.append(seed) j = join(xkey, '') return array('L', j)
[ "def", "Expandkey", "(", "key", ",", "clen", ")", ":", "import", "sha", "from", "string", "import", "join", "from", "array", "import", "array", "blocks", "=", "(", "clen", "+", "19", ")", "/", "20", "xkey", "=", "[", "]", "seed", "=", "key", "for", "i", "in", "xrange", "(", "blocks", ")", ":", "seed", "=", "sha", ".", "new", "(", "key", "+", "seed", ")", ".", "digest", "(", ")", "xkey", ".", "append", "(", "seed", ")", "j", "=", "join", "(", "xkey", ",", "''", ")", "return", "array", "(", "'L'", ",", "j", ")" ]
Internal method supporting encryption and decryption functionality.
[ "Internal", "method", "supporting", "encryption", "and", "decryption", "functionality", "." ]
bf6b07d6abeacb922c92b198352eda4eb9e4629b
https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L829-L842
train
CiscoUcs/UcsPythonSDK
src/UcsSdk/UcsBase.py
UcsUtils.EncryptPassword
def EncryptPassword(password, key): """ Encrypts the password using the given key. """ from time import time from array import array import hmac import sha import os import base64 H = UcsUtils.GetShaHash uhash = H(','.join(str(x) for x in [`time()`, `os.getpid()`, `len(password)`, password, key]))[:16] k_enc, k_auth = H('enc' + key + uhash), H('auth' + key + uhash) n = len(password) passwordStream = array('L', password + '0000'[n & 3:]) xkey = UcsUtils.Expandkey(k_enc, n + 4) for i in xrange(len(passwordStream)): passwordStream[i] = passwordStream[i] ^ xkey[i] ct = uhash + passwordStream.tostring()[:n] auth = hmac.new(ct, k_auth, sha).digest() encryptStr = ct + auth[:8] encodedStr = base64.encodestring(encryptStr) encryptedPassword = encodedStr.rstrip('\n') return encryptedPassword
python
def EncryptPassword(password, key): """ Encrypts the password using the given key. """ from time import time from array import array import hmac import sha import os import base64 H = UcsUtils.GetShaHash uhash = H(','.join(str(x) for x in [`time()`, `os.getpid()`, `len(password)`, password, key]))[:16] k_enc, k_auth = H('enc' + key + uhash), H('auth' + key + uhash) n = len(password) passwordStream = array('L', password + '0000'[n & 3:]) xkey = UcsUtils.Expandkey(k_enc, n + 4) for i in xrange(len(passwordStream)): passwordStream[i] = passwordStream[i] ^ xkey[i] ct = uhash + passwordStream.tostring()[:n] auth = hmac.new(ct, k_auth, sha).digest() encryptStr = ct + auth[:8] encodedStr = base64.encodestring(encryptStr) encryptedPassword = encodedStr.rstrip('\n') return encryptedPassword
[ "def", "EncryptPassword", "(", "password", ",", "key", ")", ":", "from", "time", "import", "time", "from", "array", "import", "array", "import", "hmac", "import", "sha", "import", "os", "import", "base64", "H", "=", "UcsUtils", ".", "GetShaHash", "uhash", "=", "H", "(", "','", ".", "join", "(", "str", "(", "x", ")", "for", "x", "in", "[", "`time()`", ",", "`os.getpid()`", ",", "`len(password)`", ",", "password", ",", "key", "]", ")", ")", "[", ":", "16", "]", "k_enc", ",", "k_auth", "=", "H", "(", "'enc'", "+", "key", "+", "uhash", ")", ",", "H", "(", "'auth'", "+", "key", "+", "uhash", ")", "n", "=", "len", "(", "password", ")", "passwordStream", "=", "array", "(", "'L'", ",", "password", "+", "'0000'", "[", "n", "&", "3", ":", "]", ")", "xkey", "=", "UcsUtils", ".", "Expandkey", "(", "k_enc", ",", "n", "+", "4", ")", "for", "i", "in", "xrange", "(", "len", "(", "passwordStream", ")", ")", ":", "passwordStream", "[", "i", "]", "=", "passwordStream", "[", "i", "]", "^", "xkey", "[", "i", "]", "ct", "=", "uhash", "+", "passwordStream", ".", "tostring", "(", ")", "[", ":", "n", "]", "auth", "=", "hmac", ".", "new", "(", "ct", ",", "k_auth", ",", "sha", ")", ".", "digest", "(", ")", "encryptStr", "=", "ct", "+", "auth", "[", ":", "8", "]", "encodedStr", "=", "base64", ".", "encodestring", "(", "encryptStr", ")", "encryptedPassword", "=", "encodedStr", ".", "rstrip", "(", "'\\n'", ")", "return", "encryptedPassword" ]
Encrypts the password using the given key.
[ "Encrypts", "the", "password", "using", "the", "given", "key", "." ]
bf6b07d6abeacb922c92b198352eda4eb9e4629b
https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L845-L872
train
CiscoUcs/UcsPythonSDK
src/UcsSdk/UcsBase.py
UcsUtils.DecryptPassword
def DecryptPassword(cipher, key): """ Decrypts the password using the given key with which the password was encrypted first. """ import base64 import hmac import sha from array import array H = UcsUtils.GetShaHash cipher = cipher + "\n" cipher = base64.decodestring(cipher) n = len(cipher) - 16 - 8 uhash = cipher[:16] passwordStream = cipher[16:-8] + "0000"[n & 3:] auth = cipher[-8:] k_enc, k_auth = H('enc' + key + uhash), H('auth' + key + uhash) vauth = hmac.new(cipher[-8:], k_auth, sha).digest()[:8] passwordStream = array('L', passwordStream) xkey = UcsUtils.Expandkey(k_enc, n + 4) for i in xrange(len(passwordStream)): passwordStream[i] = passwordStream[i] ^ xkey[i] decryptedPassword = passwordStream.tostring()[:n] return decryptedPassword
python
def DecryptPassword(cipher, key): """ Decrypts the password using the given key with which the password was encrypted first. """ import base64 import hmac import sha from array import array H = UcsUtils.GetShaHash cipher = cipher + "\n" cipher = base64.decodestring(cipher) n = len(cipher) - 16 - 8 uhash = cipher[:16] passwordStream = cipher[16:-8] + "0000"[n & 3:] auth = cipher[-8:] k_enc, k_auth = H('enc' + key + uhash), H('auth' + key + uhash) vauth = hmac.new(cipher[-8:], k_auth, sha).digest()[:8] passwordStream = array('L', passwordStream) xkey = UcsUtils.Expandkey(k_enc, n + 4) for i in xrange(len(passwordStream)): passwordStream[i] = passwordStream[i] ^ xkey[i] decryptedPassword = passwordStream.tostring()[:n] return decryptedPassword
[ "def", "DecryptPassword", "(", "cipher", ",", "key", ")", ":", "import", "base64", "import", "hmac", "import", "sha", "from", "array", "import", "array", "H", "=", "UcsUtils", ".", "GetShaHash", "cipher", "=", "cipher", "+", "\"\\n\"", "cipher", "=", "base64", ".", "decodestring", "(", "cipher", ")", "n", "=", "len", "(", "cipher", ")", "-", "16", "-", "8", "uhash", "=", "cipher", "[", ":", "16", "]", "passwordStream", "=", "cipher", "[", "16", ":", "-", "8", "]", "+", "\"0000\"", "[", "n", "&", "3", ":", "]", "auth", "=", "cipher", "[", "-", "8", ":", "]", "k_enc", ",", "k_auth", "=", "H", "(", "'enc'", "+", "key", "+", "uhash", ")", ",", "H", "(", "'auth'", "+", "key", "+", "uhash", ")", "vauth", "=", "hmac", ".", "new", "(", "cipher", "[", "-", "8", ":", "]", ",", "k_auth", ",", "sha", ")", ".", "digest", "(", ")", "[", ":", "8", "]", "passwordStream", "=", "array", "(", "'L'", ",", "passwordStream", ")", "xkey", "=", "UcsUtils", ".", "Expandkey", "(", "k_enc", ",", "n", "+", "4", ")", "for", "i", "in", "xrange", "(", "len", "(", "passwordStream", ")", ")", ":", "passwordStream", "[", "i", "]", "=", "passwordStream", "[", "i", "]", "^", "xkey", "[", "i", "]", "decryptedPassword", "=", "passwordStream", ".", "tostring", "(", ")", "[", ":", "n", "]", "return", "decryptedPassword" ]
Decrypts the password using the given key with which the password was encrypted first.
[ "Decrypts", "the", "password", "using", "the", "given", "key", "with", "which", "the", "password", "was", "encrypted", "first", "." ]
bf6b07d6abeacb922c92b198352eda4eb9e4629b
https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L875-L902
train
CiscoUcs/UcsPythonSDK
src/UcsSdk/UcsBase.py
_GenericMO.LoadFromXml
def LoadFromXml(self, node): """ Method updates the object from the xml. """ import os self.classId = node.localName metaClassId = UcsUtils.FindClassIdInMoMetaIgnoreCase(self.classId) if metaClassId: self.classId = metaClassId if node.hasAttribute(NamingPropertyId.DN): self.dn = node.getAttribute(NamingPropertyId.DN) if self.dn: self.rn = os.path.basename(self.dn) # Write the attribute and value to dictionary properties, as it is . self.WriteToAttributes(node) # Run the LoadFromXml for each childNode recursively and populate child list too. if (node.hasChildNodes()): # childList = node._get_childNodes() # childCount = childList._get_length() childList = node.childNodes childCount = len(childList) for i in range(childCount): childNode = childList.item(i) if (childNode.nodeType != Node.ELEMENT_NODE): continue c = _GenericMO() self.child.append(c) c.LoadFromXml(childNode)
python
def LoadFromXml(self, node): """ Method updates the object from the xml. """ import os self.classId = node.localName metaClassId = UcsUtils.FindClassIdInMoMetaIgnoreCase(self.classId) if metaClassId: self.classId = metaClassId if node.hasAttribute(NamingPropertyId.DN): self.dn = node.getAttribute(NamingPropertyId.DN) if self.dn: self.rn = os.path.basename(self.dn) # Write the attribute and value to dictionary properties, as it is . self.WriteToAttributes(node) # Run the LoadFromXml for each childNode recursively and populate child list too. if (node.hasChildNodes()): # childList = node._get_childNodes() # childCount = childList._get_length() childList = node.childNodes childCount = len(childList) for i in range(childCount): childNode = childList.item(i) if (childNode.nodeType != Node.ELEMENT_NODE): continue c = _GenericMO() self.child.append(c) c.LoadFromXml(childNode)
[ "def", "LoadFromXml", "(", "self", ",", "node", ")", ":", "import", "os", "self", ".", "classId", "=", "node", ".", "localName", "metaClassId", "=", "UcsUtils", ".", "FindClassIdInMoMetaIgnoreCase", "(", "self", ".", "classId", ")", "if", "metaClassId", ":", "self", ".", "classId", "=", "metaClassId", "if", "node", ".", "hasAttribute", "(", "NamingPropertyId", ".", "DN", ")", ":", "self", ".", "dn", "=", "node", ".", "getAttribute", "(", "NamingPropertyId", ".", "DN", ")", "if", "self", ".", "dn", ":", "self", ".", "rn", "=", "os", ".", "path", ".", "basename", "(", "self", ".", "dn", ")", "# Write the attribute and value to dictionary properties, as it is .", "self", ".", "WriteToAttributes", "(", "node", ")", "# Run the LoadFromXml for each childNode recursively and populate child list too.", "if", "(", "node", ".", "hasChildNodes", "(", ")", ")", ":", "# childList = node._get_childNodes()", "# childCount = childList._get_length()", "childList", "=", "node", ".", "childNodes", "childCount", "=", "len", "(", "childList", ")", "for", "i", "in", "range", "(", "childCount", ")", ":", "childNode", "=", "childList", ".", "item", "(", "i", ")", "if", "(", "childNode", ".", "nodeType", "!=", "Node", ".", "ELEMENT_NODE", ")", ":", "continue", "c", "=", "_GenericMO", "(", ")", "self", ".", "child", ".", "append", "(", "c", ")", "c", ".", "LoadFromXml", "(", "childNode", ")" ]
Method updates the object from the xml.
[ "Method", "updates", "the", "object", "from", "the", "xml", "." ]
bf6b07d6abeacb922c92b198352eda4eb9e4629b
https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L1061-L1092
train
CiscoUcs/UcsPythonSDK
src/UcsSdk/UcsBase.py
_GenericMO.WriteXml
def WriteXml(self, w, option, elementName=None): """ Method writes the xml representation of the generic managed object. """ if elementName == None: x = w.createElement(self.classId) else: x = w.createElement(elementName) for prop in self.__dict__['properties']: x.setAttribute(UcsUtils.WordL(prop), self.__dict__['properties'][prop]) x_child = self.childWriteXml(w, option) for xc in x_child: if (xc != None): x.appendChild(xc) return x
python
def WriteXml(self, w, option, elementName=None): """ Method writes the xml representation of the generic managed object. """ if elementName == None: x = w.createElement(self.classId) else: x = w.createElement(elementName) for prop in self.__dict__['properties']: x.setAttribute(UcsUtils.WordL(prop), self.__dict__['properties'][prop]) x_child = self.childWriteXml(w, option) for xc in x_child: if (xc != None): x.appendChild(xc) return x
[ "def", "WriteXml", "(", "self", ",", "w", ",", "option", ",", "elementName", "=", "None", ")", ":", "if", "elementName", "==", "None", ":", "x", "=", "w", ".", "createElement", "(", "self", ".", "classId", ")", "else", ":", "x", "=", "w", ".", "createElement", "(", "elementName", ")", "for", "prop", "in", "self", ".", "__dict__", "[", "'properties'", "]", ":", "x", ".", "setAttribute", "(", "UcsUtils", ".", "WordL", "(", "prop", ")", ",", "self", ".", "__dict__", "[", "'properties'", "]", "[", "prop", "]", ")", "x_child", "=", "self", ".", "childWriteXml", "(", "w", ",", "option", ")", "for", "xc", "in", "x_child", ":", "if", "(", "xc", "!=", "None", ")", ":", "x", ".", "appendChild", "(", "xc", ")", "return", "x" ]
Method writes the xml representation of the generic managed object.
[ "Method", "writes", "the", "xml", "representation", "of", "the", "generic", "managed", "object", "." ]
bf6b07d6abeacb922c92b198352eda4eb9e4629b
https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L1094-L1107
train
CiscoUcs/UcsPythonSDK
src/UcsSdk/UcsBase.py
_GenericMO.ToManagedObject
def ToManagedObject(self): """ Method creates and returns an object of ManagedObject class using the classId and information from the Generic managed object. """ from Ucs import ClassFactory cln = UcsUtils.WordU(self.classId) mo = ClassFactory(cln) if mo and (isinstance(mo, ManagedObject) == True): metaClassId = UcsUtils.FindClassIdInMoMetaIgnoreCase(self.classId) for property in self.properties: if UcsUtils.WordU(property) in UcsUtils.GetUcsPropertyMetaAttributeList(metaClassId): mo.setattr(UcsUtils.WordU(property), self.properties[property]) else: # TODO: Add Warning/Error messages in Logger. WriteUcsWarning("Property %s Not Exist in MO %s" % (UcsUtils.WordU(property), metaClassId)) if len(self.child): for ch in self.child: moch = ch.ToManagedObject() mo.child.append(moch) return mo else: return None
python
def ToManagedObject(self): """ Method creates and returns an object of ManagedObject class using the classId and information from the Generic managed object. """ from Ucs import ClassFactory cln = UcsUtils.WordU(self.classId) mo = ClassFactory(cln) if mo and (isinstance(mo, ManagedObject) == True): metaClassId = UcsUtils.FindClassIdInMoMetaIgnoreCase(self.classId) for property in self.properties: if UcsUtils.WordU(property) in UcsUtils.GetUcsPropertyMetaAttributeList(metaClassId): mo.setattr(UcsUtils.WordU(property), self.properties[property]) else: # TODO: Add Warning/Error messages in Logger. WriteUcsWarning("Property %s Not Exist in MO %s" % (UcsUtils.WordU(property), metaClassId)) if len(self.child): for ch in self.child: moch = ch.ToManagedObject() mo.child.append(moch) return mo else: return None
[ "def", "ToManagedObject", "(", "self", ")", ":", "from", "Ucs", "import", "ClassFactory", "cln", "=", "UcsUtils", ".", "WordU", "(", "self", ".", "classId", ")", "mo", "=", "ClassFactory", "(", "cln", ")", "if", "mo", "and", "(", "isinstance", "(", "mo", ",", "ManagedObject", ")", "==", "True", ")", ":", "metaClassId", "=", "UcsUtils", ".", "FindClassIdInMoMetaIgnoreCase", "(", "self", ".", "classId", ")", "for", "property", "in", "self", ".", "properties", ":", "if", "UcsUtils", ".", "WordU", "(", "property", ")", "in", "UcsUtils", ".", "GetUcsPropertyMetaAttributeList", "(", "metaClassId", ")", ":", "mo", ".", "setattr", "(", "UcsUtils", ".", "WordU", "(", "property", ")", ",", "self", ".", "properties", "[", "property", "]", ")", "else", ":", "# TODO: Add Warning/Error messages in Logger.", "WriteUcsWarning", "(", "\"Property %s Not Exist in MO %s\"", "%", "(", "UcsUtils", ".", "WordU", "(", "property", ")", ",", "metaClassId", ")", ")", "if", "len", "(", "self", ".", "child", ")", ":", "for", "ch", "in", "self", ".", "child", ":", "moch", "=", "ch", ".", "ToManagedObject", "(", ")", "mo", ".", "child", ".", "append", "(", "moch", ")", "return", "mo", "else", ":", "return", "None" ]
Method creates and returns an object of ManagedObject class using the classId and information from the Generic managed object.
[ "Method", "creates", "and", "returns", "an", "object", "of", "ManagedObject", "class", "using", "the", "classId", "and", "information", "from", "the", "Generic", "managed", "object", "." ]
bf6b07d6abeacb922c92b198352eda4eb9e4629b
https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L1109-L1133
train
CiscoUcs/UcsPythonSDK
src/UcsSdk/UcsBase.py
_GenericMO.FromManagedObject
def FromManagedObject(self): """ Method creates and returns an object of _GenericMO class using the classId and other information from the managed object. """ import os if (isinstance(self.mo, ManagedObject) == True): self.classId = self.mo.classId if self.mo.getattr('Dn'): self.dn = self.mo.getattr('Dn') if self.mo.getattr('Rn'): self.rn = self.mo.getattr('Rn') elif self.dn: self.rn = os.path.basename(self.dn) for property in UcsUtils.GetUcsPropertyMetaAttributeList(self.mo.classId): self.properties[property] = self.mo.getattr(property) if len(self.mo.child): for ch in self.mo.child: if not ch.getattr('Dn'): _Dn = self.mo.getattr('Dn') + "/" + ch.getattr('Rn') ch.setattr('Dn', _Dn) gmo = _GenericMO(mo=ch) self.child.append(gmo)
python
def FromManagedObject(self): """ Method creates and returns an object of _GenericMO class using the classId and other information from the managed object. """ import os if (isinstance(self.mo, ManagedObject) == True): self.classId = self.mo.classId if self.mo.getattr('Dn'): self.dn = self.mo.getattr('Dn') if self.mo.getattr('Rn'): self.rn = self.mo.getattr('Rn') elif self.dn: self.rn = os.path.basename(self.dn) for property in UcsUtils.GetUcsPropertyMetaAttributeList(self.mo.classId): self.properties[property] = self.mo.getattr(property) if len(self.mo.child): for ch in self.mo.child: if not ch.getattr('Dn'): _Dn = self.mo.getattr('Dn') + "/" + ch.getattr('Rn') ch.setattr('Dn', _Dn) gmo = _GenericMO(mo=ch) self.child.append(gmo)
[ "def", "FromManagedObject", "(", "self", ")", ":", "import", "os", "if", "(", "isinstance", "(", "self", ".", "mo", ",", "ManagedObject", ")", "==", "True", ")", ":", "self", ".", "classId", "=", "self", ".", "mo", ".", "classId", "if", "self", ".", "mo", ".", "getattr", "(", "'Dn'", ")", ":", "self", ".", "dn", "=", "self", ".", "mo", ".", "getattr", "(", "'Dn'", ")", "if", "self", ".", "mo", ".", "getattr", "(", "'Rn'", ")", ":", "self", ".", "rn", "=", "self", ".", "mo", ".", "getattr", "(", "'Rn'", ")", "elif", "self", ".", "dn", ":", "self", ".", "rn", "=", "os", ".", "path", ".", "basename", "(", "self", ".", "dn", ")", "for", "property", "in", "UcsUtils", ".", "GetUcsPropertyMetaAttributeList", "(", "self", ".", "mo", ".", "classId", ")", ":", "self", ".", "properties", "[", "property", "]", "=", "self", ".", "mo", ".", "getattr", "(", "property", ")", "if", "len", "(", "self", ".", "mo", ".", "child", ")", ":", "for", "ch", "in", "self", ".", "mo", ".", "child", ":", "if", "not", "ch", ".", "getattr", "(", "'Dn'", ")", ":", "_Dn", "=", "self", ".", "mo", ".", "getattr", "(", "'Dn'", ")", "+", "\"/\"", "+", "ch", ".", "getattr", "(", "'Rn'", ")", "ch", ".", "setattr", "(", "'Dn'", ",", "_Dn", ")", "gmo", "=", "_GenericMO", "(", "mo", "=", "ch", ")", "self", ".", "child", ".", "append", "(", "gmo", ")" ]
Method creates and returns an object of _GenericMO class using the classId and other information from the managed object.
[ "Method", "creates", "and", "returns", "an", "object", "of", "_GenericMO", "class", "using", "the", "classId", "and", "other", "information", "from", "the", "managed", "object", "." ]
bf6b07d6abeacb922c92b198352eda4eb9e4629b
https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L1135-L1162
train
CiscoUcs/UcsPythonSDK
src/UcsSdk/UcsBase.py
_GenericMO.GetChildClassId
def GetChildClassId(self, classId): """ Method extracts and returns the child object list same as the given classId """ childList = [] for ch in self.child: if ch.classId.lower() == classId.lower(): childList.append(ch) return childList
python
def GetChildClassId(self, classId): """ Method extracts and returns the child object list same as the given classId """ childList = [] for ch in self.child: if ch.classId.lower() == classId.lower(): childList.append(ch) return childList
[ "def", "GetChildClassId", "(", "self", ",", "classId", ")", ":", "childList", "=", "[", "]", "for", "ch", "in", "self", ".", "child", ":", "if", "ch", ".", "classId", ".", "lower", "(", ")", "==", "classId", ".", "lower", "(", ")", ":", "childList", ".", "append", "(", "ch", ")", "return", "childList" ]
Method extracts and returns the child object list same as the given classId
[ "Method", "extracts", "and", "returns", "the", "child", "object", "list", "same", "as", "the", "given", "classId" ]
bf6b07d6abeacb922c92b198352eda4eb9e4629b
https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L1180-L1188
train
tehmaze/natural
natural/date.py
_total_seconds
def _total_seconds(t): ''' Takes a `datetime.timedelta` object and returns the delta in seconds. >>> _total_seconds(datetime.timedelta(23, 42, 123456)) 1987242 >>> _total_seconds(datetime.timedelta(23, 42, 654321)) 1987243 ''' return sum([ int(t.days * 86400 + t.seconds), int(round(t.microseconds / 1000000.0)) ])
python
def _total_seconds(t): ''' Takes a `datetime.timedelta` object and returns the delta in seconds. >>> _total_seconds(datetime.timedelta(23, 42, 123456)) 1987242 >>> _total_seconds(datetime.timedelta(23, 42, 654321)) 1987243 ''' return sum([ int(t.days * 86400 + t.seconds), int(round(t.microseconds / 1000000.0)) ])
[ "def", "_total_seconds", "(", "t", ")", ":", "return", "sum", "(", "[", "int", "(", "t", ".", "days", "*", "86400", "+", "t", ".", "seconds", ")", ",", "int", "(", "round", "(", "t", ".", "microseconds", "/", "1000000.0", ")", ")", "]", ")" ]
Takes a `datetime.timedelta` object and returns the delta in seconds. >>> _total_seconds(datetime.timedelta(23, 42, 123456)) 1987242 >>> _total_seconds(datetime.timedelta(23, 42, 654321)) 1987243
[ "Takes", "a", "datetime", ".", "timedelta", "object", "and", "returns", "the", "delta", "in", "seconds", "." ]
d7a1fc9de712f9bcf68884a80826a7977df356fb
https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/date.py#L41-L53
train
tehmaze/natural
natural/date.py
day
def day(t, now=None, format='%B %d'): ''' Date delta compared to ``t``. You can override ``now`` to specify what date to compare to. You can override the date format by supplying a ``format`` parameter. :param t: timestamp, :class:`datetime.date` or :class:`datetime.datetime` object :param now: default ``None``, optionally a :class:`datetime.datetime` object :param format: default ``'%B %d'`` >>> import time >>> print(day(time.time())) today >>> print(day(time.time() - 86400)) yesterday >>> print(day(time.time() - 604800)) last week >>> print(day(time.time() + 86400)) tomorrow >>> print(day(time.time() + 604800)) next week ''' t1 = _to_date(t) t2 = _to_date(now or datetime.datetime.now()) diff = t1 - t2 secs = _total_seconds(diff) days = abs(diff.days) if days == 0: return _('today') elif days == 1: if secs < 0: return _('yesterday') else: return _('tomorrow') elif days == 7: if secs < 0: return _('last week') else: return _('next week') else: return t1.strftime(format)
python
def day(t, now=None, format='%B %d'): ''' Date delta compared to ``t``. You can override ``now`` to specify what date to compare to. You can override the date format by supplying a ``format`` parameter. :param t: timestamp, :class:`datetime.date` or :class:`datetime.datetime` object :param now: default ``None``, optionally a :class:`datetime.datetime` object :param format: default ``'%B %d'`` >>> import time >>> print(day(time.time())) today >>> print(day(time.time() - 86400)) yesterday >>> print(day(time.time() - 604800)) last week >>> print(day(time.time() + 86400)) tomorrow >>> print(day(time.time() + 604800)) next week ''' t1 = _to_date(t) t2 = _to_date(now or datetime.datetime.now()) diff = t1 - t2 secs = _total_seconds(diff) days = abs(diff.days) if days == 0: return _('today') elif days == 1: if secs < 0: return _('yesterday') else: return _('tomorrow') elif days == 7: if secs < 0: return _('last week') else: return _('next week') else: return t1.strftime(format)
[ "def", "day", "(", "t", ",", "now", "=", "None", ",", "format", "=", "'%B %d'", ")", ":", "t1", "=", "_to_date", "(", "t", ")", "t2", "=", "_to_date", "(", "now", "or", "datetime", ".", "datetime", ".", "now", "(", ")", ")", "diff", "=", "t1", "-", "t2", "secs", "=", "_total_seconds", "(", "diff", ")", "days", "=", "abs", "(", "diff", ".", "days", ")", "if", "days", "==", "0", ":", "return", "_", "(", "'today'", ")", "elif", "days", "==", "1", ":", "if", "secs", "<", "0", ":", "return", "_", "(", "'yesterday'", ")", "else", ":", "return", "_", "(", "'tomorrow'", ")", "elif", "days", "==", "7", ":", "if", "secs", "<", "0", ":", "return", "_", "(", "'last week'", ")", "else", ":", "return", "_", "(", "'next week'", ")", "else", ":", "return", "t1", ".", "strftime", "(", "format", ")" ]
Date delta compared to ``t``. You can override ``now`` to specify what date to compare to. You can override the date format by supplying a ``format`` parameter. :param t: timestamp, :class:`datetime.date` or :class:`datetime.datetime` object :param now: default ``None``, optionally a :class:`datetime.datetime` object :param format: default ``'%B %d'`` >>> import time >>> print(day(time.time())) today >>> print(day(time.time() - 86400)) yesterday >>> print(day(time.time() - 604800)) last week >>> print(day(time.time() + 86400)) tomorrow >>> print(day(time.time() + 604800)) next week
[ "Date", "delta", "compared", "to", "t", ".", "You", "can", "override", "now", "to", "specify", "what", "date", "to", "compare", "to", "." ]
d7a1fc9de712f9bcf68884a80826a7977df356fb
https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/date.py#L266-L310
train
tehmaze/natural
natural/date.py
duration
def duration(t, now=None, precision=1, pad=', ', words=None, justnow=datetime.timedelta(seconds=10)): ''' Time delta compared to ``t``. You can override ``now`` to specify what time to compare to. :param t: timestamp, :class:`datetime.date` or :class:`datetime.datetime` object :param now: default ``None``, optionally a :class:`datetime.datetime` object :param precision: default ``1``, number of fragments to return :param words: default ``None``, allow words like "yesterday", if set to ``None`` this will be enabled if ``precision`` is set to ``1`` :param justnow: default ``datetime.timedelta(seconds=10)``, :class:`datetime.timedelta` object passed to :func:`delta` representing tolerance for considering argument ``t`` as meaning 'just now' >>> import time >>> from datetime import datetime >>> print(duration(time.time() + 1)) just now >>> print(duration(time.time() + 11)) 11 seconds from now >>> print(duration(time.time() - 1)) just now >>> print(duration(time.time() - 11)) 11 seconds ago >>> print(duration(time.time() - 3601)) an hour ago >>> print(duration(time.time() - 7201)) 2 hours ago >>> print(duration(time.time() - 1234567)) 2 weeks ago >>> print(duration(time.time() + 7200, precision=1)) 2 hours from now >>> print(duration(time.time() - 1234567, precision=3)) 2 weeks, 6 hours, 56 minutes ago >>> print(duration(datetime(2014, 9, 8), now=datetime(2014, 9, 9))) yesterday >>> print(duration(datetime(2014, 9, 7, 23), now=datetime(2014, 9, 9))) 1 day ago >>> print(duration(datetime(2014, 9, 10), now=datetime(2014, 9, 9))) tomorrow >>> print(duration(datetime(2014, 9, 11, 1), now=datetime(2014, 9, 9, 23))) 1 day from now ''' if words is None: words = precision == 1 t1 = _to_datetime(t) t2 = _to_datetime(now or datetime.datetime.now()) if t1 < t2: format = _('%s ago') else: format = _('%s from now') result, remains = delta(t1, t2, words=words, justnow=justnow) if result in ( _('just now'), _('yesterday'), _('tomorrow'), _('last week'), _('next week'), ): return result elif precision > 1 and remains: t3 = t2 - datetime.timedelta(seconds=remains) return pad.join([ result, duration(t2, t3, precision - 1, pad, words=False), ]) else: return format % (result,)
python
def duration(t, now=None, precision=1, pad=', ', words=None, justnow=datetime.timedelta(seconds=10)): ''' Time delta compared to ``t``. You can override ``now`` to specify what time to compare to. :param t: timestamp, :class:`datetime.date` or :class:`datetime.datetime` object :param now: default ``None``, optionally a :class:`datetime.datetime` object :param precision: default ``1``, number of fragments to return :param words: default ``None``, allow words like "yesterday", if set to ``None`` this will be enabled if ``precision`` is set to ``1`` :param justnow: default ``datetime.timedelta(seconds=10)``, :class:`datetime.timedelta` object passed to :func:`delta` representing tolerance for considering argument ``t`` as meaning 'just now' >>> import time >>> from datetime import datetime >>> print(duration(time.time() + 1)) just now >>> print(duration(time.time() + 11)) 11 seconds from now >>> print(duration(time.time() - 1)) just now >>> print(duration(time.time() - 11)) 11 seconds ago >>> print(duration(time.time() - 3601)) an hour ago >>> print(duration(time.time() - 7201)) 2 hours ago >>> print(duration(time.time() - 1234567)) 2 weeks ago >>> print(duration(time.time() + 7200, precision=1)) 2 hours from now >>> print(duration(time.time() - 1234567, precision=3)) 2 weeks, 6 hours, 56 minutes ago >>> print(duration(datetime(2014, 9, 8), now=datetime(2014, 9, 9))) yesterday >>> print(duration(datetime(2014, 9, 7, 23), now=datetime(2014, 9, 9))) 1 day ago >>> print(duration(datetime(2014, 9, 10), now=datetime(2014, 9, 9))) tomorrow >>> print(duration(datetime(2014, 9, 11, 1), now=datetime(2014, 9, 9, 23))) 1 day from now ''' if words is None: words = precision == 1 t1 = _to_datetime(t) t2 = _to_datetime(now or datetime.datetime.now()) if t1 < t2: format = _('%s ago') else: format = _('%s from now') result, remains = delta(t1, t2, words=words, justnow=justnow) if result in ( _('just now'), _('yesterday'), _('tomorrow'), _('last week'), _('next week'), ): return result elif precision > 1 and remains: t3 = t2 - datetime.timedelta(seconds=remains) return pad.join([ result, duration(t2, t3, precision - 1, pad, words=False), ]) else: return format % (result,)
[ "def", "duration", "(", "t", ",", "now", "=", "None", ",", "precision", "=", "1", ",", "pad", "=", "', '", ",", "words", "=", "None", ",", "justnow", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "10", ")", ")", ":", "if", "words", "is", "None", ":", "words", "=", "precision", "==", "1", "t1", "=", "_to_datetime", "(", "t", ")", "t2", "=", "_to_datetime", "(", "now", "or", "datetime", ".", "datetime", ".", "now", "(", ")", ")", "if", "t1", "<", "t2", ":", "format", "=", "_", "(", "'%s ago'", ")", "else", ":", "format", "=", "_", "(", "'%s from now'", ")", "result", ",", "remains", "=", "delta", "(", "t1", ",", "t2", ",", "words", "=", "words", ",", "justnow", "=", "justnow", ")", "if", "result", "in", "(", "_", "(", "'just now'", ")", ",", "_", "(", "'yesterday'", ")", ",", "_", "(", "'tomorrow'", ")", ",", "_", "(", "'last week'", ")", ",", "_", "(", "'next week'", ")", ",", ")", ":", "return", "result", "elif", "precision", ">", "1", "and", "remains", ":", "t3", "=", "t2", "-", "datetime", ".", "timedelta", "(", "seconds", "=", "remains", ")", "return", "pad", ".", "join", "(", "[", "result", ",", "duration", "(", "t2", ",", "t3", ",", "precision", "-", "1", ",", "pad", ",", "words", "=", "False", ")", ",", "]", ")", "else", ":", "return", "format", "%", "(", "result", ",", ")" ]
Time delta compared to ``t``. You can override ``now`` to specify what time to compare to. :param t: timestamp, :class:`datetime.date` or :class:`datetime.datetime` object :param now: default ``None``, optionally a :class:`datetime.datetime` object :param precision: default ``1``, number of fragments to return :param words: default ``None``, allow words like "yesterday", if set to ``None`` this will be enabled if ``precision`` is set to ``1`` :param justnow: default ``datetime.timedelta(seconds=10)``, :class:`datetime.timedelta` object passed to :func:`delta` representing tolerance for considering argument ``t`` as meaning 'just now' >>> import time >>> from datetime import datetime >>> print(duration(time.time() + 1)) just now >>> print(duration(time.time() + 11)) 11 seconds from now >>> print(duration(time.time() - 1)) just now >>> print(duration(time.time() - 11)) 11 seconds ago >>> print(duration(time.time() - 3601)) an hour ago >>> print(duration(time.time() - 7201)) 2 hours ago >>> print(duration(time.time() - 1234567)) 2 weeks ago >>> print(duration(time.time() + 7200, precision=1)) 2 hours from now >>> print(duration(time.time() - 1234567, precision=3)) 2 weeks, 6 hours, 56 minutes ago >>> print(duration(datetime(2014, 9, 8), now=datetime(2014, 9, 9))) yesterday >>> print(duration(datetime(2014, 9, 7, 23), now=datetime(2014, 9, 9))) 1 day ago >>> print(duration(datetime(2014, 9, 10), now=datetime(2014, 9, 9))) tomorrow >>> print(duration(datetime(2014, 9, 11, 1), now=datetime(2014, 9, 9, 23))) 1 day from now
[ "Time", "delta", "compared", "to", "t", ".", "You", "can", "override", "now", "to", "specify", "what", "time", "to", "compare", "to", "." ]
d7a1fc9de712f9bcf68884a80826a7977df356fb
https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/date.py#L313-L391
train
yeraydiazdiaz/lunr.py
lunr/index.py
Index.search
def search(self, query_string): """Performs a search against the index using lunr query syntax. Results will be returned sorted by their score, the most relevant results will be returned first. For more programmatic querying use `lunr.Index.query`. Args: query_string (str): A string to parse into a Query. Returns: dict: Results of executing the query. """ query = self.create_query() # TODO: should QueryParser be a method of query? should it return one? parser = QueryParser(query_string, query) parser.parse() return self.query(query)
python
def search(self, query_string): """Performs a search against the index using lunr query syntax. Results will be returned sorted by their score, the most relevant results will be returned first. For more programmatic querying use `lunr.Index.query`. Args: query_string (str): A string to parse into a Query. Returns: dict: Results of executing the query. """ query = self.create_query() # TODO: should QueryParser be a method of query? should it return one? parser = QueryParser(query_string, query) parser.parse() return self.query(query)
[ "def", "search", "(", "self", ",", "query_string", ")", ":", "query", "=", "self", ".", "create_query", "(", ")", "# TODO: should QueryParser be a method of query? should it return one?", "parser", "=", "QueryParser", "(", "query_string", ",", "query", ")", "parser", ".", "parse", "(", ")", "return", "self", ".", "query", "(", "query", ")" ]
Performs a search against the index using lunr query syntax. Results will be returned sorted by their score, the most relevant results will be returned first. For more programmatic querying use `lunr.Index.query`. Args: query_string (str): A string to parse into a Query. Returns: dict: Results of executing the query.
[ "Performs", "a", "search", "against", "the", "index", "using", "lunr", "query", "syntax", "." ]
28ec3f6d4888295eed730211ee9617aa488d6ba3
https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/index.py#L47-L65
train
yeraydiazdiaz/lunr.py
lunr/index.py
Index.create_query
def create_query(self, fields=None): """Convenience method to create a Query with the Index's fields. Args: fields (iterable, optional): The fields to include in the Query, defaults to the Index's `all_fields`. Returns: Query: With the specified fields or all the fields in the Index. """ if fields is None: return Query(self.fields) non_contained_fields = set(fields) - set(self.fields) if non_contained_fields: raise BaseLunrException( "Fields {} are not part of the index", non_contained_fields ) return Query(fields)
python
def create_query(self, fields=None): """Convenience method to create a Query with the Index's fields. Args: fields (iterable, optional): The fields to include in the Query, defaults to the Index's `all_fields`. Returns: Query: With the specified fields or all the fields in the Index. """ if fields is None: return Query(self.fields) non_contained_fields = set(fields) - set(self.fields) if non_contained_fields: raise BaseLunrException( "Fields {} are not part of the index", non_contained_fields ) return Query(fields)
[ "def", "create_query", "(", "self", ",", "fields", "=", "None", ")", ":", "if", "fields", "is", "None", ":", "return", "Query", "(", "self", ".", "fields", ")", "non_contained_fields", "=", "set", "(", "fields", ")", "-", "set", "(", "self", ".", "fields", ")", "if", "non_contained_fields", ":", "raise", "BaseLunrException", "(", "\"Fields {} are not part of the index\"", ",", "non_contained_fields", ")", "return", "Query", "(", "fields", ")" ]
Convenience method to create a Query with the Index's fields. Args: fields (iterable, optional): The fields to include in the Query, defaults to the Index's `all_fields`. Returns: Query: With the specified fields or all the fields in the Index.
[ "Convenience", "method", "to", "create", "a", "Query", "with", "the", "Index", "s", "fields", "." ]
28ec3f6d4888295eed730211ee9617aa488d6ba3
https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/index.py#L67-L86
train
yeraydiazdiaz/lunr.py
lunr/index.py
Index.load
def load(cls, serialized_index): """Load a serialized index""" from lunr import __TARGET_JS_VERSION__ if isinstance(serialized_index, basestring): serialized_index = json.loads(serialized_index) if serialized_index["version"] != __TARGET_JS_VERSION__: logger.warning( "Version mismatch when loading serialized index. " "Current version of lunr {} does not match that of serialized " "index {}".format(__TARGET_JS_VERSION__, serialized_index["version"]) ) field_vectors = { ref: Vector(elements) for ref, elements in serialized_index["fieldVectors"] } tokenset_builder = TokenSetBuilder() inverted_index = {} for term, posting in serialized_index["invertedIndex"]: tokenset_builder.insert(term) inverted_index[term] = posting tokenset_builder.finish() return Index( fields=serialized_index["fields"], field_vectors=field_vectors, inverted_index=inverted_index, token_set=tokenset_builder.root, pipeline=Pipeline.load(serialized_index["pipeline"]), )
python
def load(cls, serialized_index): """Load a serialized index""" from lunr import __TARGET_JS_VERSION__ if isinstance(serialized_index, basestring): serialized_index = json.loads(serialized_index) if serialized_index["version"] != __TARGET_JS_VERSION__: logger.warning( "Version mismatch when loading serialized index. " "Current version of lunr {} does not match that of serialized " "index {}".format(__TARGET_JS_VERSION__, serialized_index["version"]) ) field_vectors = { ref: Vector(elements) for ref, elements in serialized_index["fieldVectors"] } tokenset_builder = TokenSetBuilder() inverted_index = {} for term, posting in serialized_index["invertedIndex"]: tokenset_builder.insert(term) inverted_index[term] = posting tokenset_builder.finish() return Index( fields=serialized_index["fields"], field_vectors=field_vectors, inverted_index=inverted_index, token_set=tokenset_builder.root, pipeline=Pipeline.load(serialized_index["pipeline"]), )
[ "def", "load", "(", "cls", ",", "serialized_index", ")", ":", "from", "lunr", "import", "__TARGET_JS_VERSION__", "if", "isinstance", "(", "serialized_index", ",", "basestring", ")", ":", "serialized_index", "=", "json", ".", "loads", "(", "serialized_index", ")", "if", "serialized_index", "[", "\"version\"", "]", "!=", "__TARGET_JS_VERSION__", ":", "logger", ".", "warning", "(", "\"Version mismatch when loading serialized index. \"", "\"Current version of lunr {} does not match that of serialized \"", "\"index {}\"", ".", "format", "(", "__TARGET_JS_VERSION__", ",", "serialized_index", "[", "\"version\"", "]", ")", ")", "field_vectors", "=", "{", "ref", ":", "Vector", "(", "elements", ")", "for", "ref", ",", "elements", "in", "serialized_index", "[", "\"fieldVectors\"", "]", "}", "tokenset_builder", "=", "TokenSetBuilder", "(", ")", "inverted_index", "=", "{", "}", "for", "term", ",", "posting", "in", "serialized_index", "[", "\"invertedIndex\"", "]", ":", "tokenset_builder", ".", "insert", "(", "term", ")", "inverted_index", "[", "term", "]", "=", "posting", "tokenset_builder", ".", "finish", "(", ")", "return", "Index", "(", "fields", "=", "serialized_index", "[", "\"fields\"", "]", ",", "field_vectors", "=", "field_vectors", ",", "inverted_index", "=", "inverted_index", ",", "token_set", "=", "tokenset_builder", ".", "root", ",", "pipeline", "=", "Pipeline", ".", "load", "(", "serialized_index", "[", "\"pipeline\"", "]", ")", ",", ")" ]
Load a serialized index
[ "Load", "a", "serialized", "index" ]
28ec3f6d4888295eed730211ee9617aa488d6ba3
https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/index.py#L340-L372
train
CyberInt/celstash
celstash.py
configure
def configure(logstash_host=None, logstash_port=None, logdir=None): '''Configuration settings.''' if not (logstash_host or logstash_port or logdir): raise ValueError('you must specify at least one parameter') config.logstash.host = logstash_host or config.logstash.host config.logstash.port = logstash_port or config.logstash.port config.logdir = logdir or config.logdir create_logdir(config.logdir)
python
def configure(logstash_host=None, logstash_port=None, logdir=None): '''Configuration settings.''' if not (logstash_host or logstash_port or logdir): raise ValueError('you must specify at least one parameter') config.logstash.host = logstash_host or config.logstash.host config.logstash.port = logstash_port or config.logstash.port config.logdir = logdir or config.logdir create_logdir(config.logdir)
[ "def", "configure", "(", "logstash_host", "=", "None", ",", "logstash_port", "=", "None", ",", "logdir", "=", "None", ")", ":", "if", "not", "(", "logstash_host", "or", "logstash_port", "or", "logdir", ")", ":", "raise", "ValueError", "(", "'you must specify at least one parameter'", ")", "config", ".", "logstash", ".", "host", "=", "logstash_host", "or", "config", ".", "logstash", ".", "host", "config", ".", "logstash", ".", "port", "=", "logstash_port", "or", "config", ".", "logstash", ".", "port", "config", ".", "logdir", "=", "logdir", "or", "config", ".", "logdir", "create_logdir", "(", "config", ".", "logdir", ")" ]
Configuration settings.
[ "Configuration", "settings", "." ]
d22f2787e5a95a723bffd0a4c2ea3bb269a16c8e
https://github.com/CyberInt/celstash/blob/d22f2787e5a95a723bffd0a4c2ea3bb269a16c8e/celstash.py#L51-L61
train
CyberInt/celstash
celstash.py
new_logger
def new_logger(name): '''Return new logger which will log both to logstash and to file in JSON format. Log files are stored in <logdir>/name.json ''' log = get_task_logger(name) handler = logstash.LogstashHandler( config.logstash.host, config.logstash.port) log.addHandler(handler) create_logdir(config.logdir) handler = TimedRotatingFileHandler( '%s.json' % join(config.logdir, name), when='midnight', utc=True, ) handler.setFormatter(JSONFormatter()) log.addHandler(handler) return TaskCtxAdapter(log, {})
python
def new_logger(name): '''Return new logger which will log both to logstash and to file in JSON format. Log files are stored in <logdir>/name.json ''' log = get_task_logger(name) handler = logstash.LogstashHandler( config.logstash.host, config.logstash.port) log.addHandler(handler) create_logdir(config.logdir) handler = TimedRotatingFileHandler( '%s.json' % join(config.logdir, name), when='midnight', utc=True, ) handler.setFormatter(JSONFormatter()) log.addHandler(handler) return TaskCtxAdapter(log, {})
[ "def", "new_logger", "(", "name", ")", ":", "log", "=", "get_task_logger", "(", "name", ")", "handler", "=", "logstash", ".", "LogstashHandler", "(", "config", ".", "logstash", ".", "host", ",", "config", ".", "logstash", ".", "port", ")", "log", ".", "addHandler", "(", "handler", ")", "create_logdir", "(", "config", ".", "logdir", ")", "handler", "=", "TimedRotatingFileHandler", "(", "'%s.json'", "%", "join", "(", "config", ".", "logdir", ",", "name", ")", ",", "when", "=", "'midnight'", ",", "utc", "=", "True", ",", ")", "handler", ".", "setFormatter", "(", "JSONFormatter", "(", ")", ")", "log", ".", "addHandler", "(", "handler", ")", "return", "TaskCtxAdapter", "(", "log", ",", "{", "}", ")" ]
Return new logger which will log both to logstash and to file in JSON format. Log files are stored in <logdir>/name.json
[ "Return", "new", "logger", "which", "will", "log", "both", "to", "logstash", "and", "to", "file", "in", "JSON", "format", "." ]
d22f2787e5a95a723bffd0a4c2ea3bb269a16c8e
https://github.com/CyberInt/celstash/blob/d22f2787e5a95a723bffd0a4c2ea3bb269a16c8e/celstash.py#L69-L91
train
JensRantil/rewind
rewind/server/main.py
_zmq_socket_context
def _zmq_socket_context(context, socket_type, bind_endpoints): """A ZeroMQ socket context that both constructs a socket and closes it.""" socket = context.socket(socket_type) try: for endpoint in bind_endpoints: try: socket.bind(endpoint) except Exception: _logger.fatal("Could not bind to '%s'.", endpoint) raise yield socket finally: socket.close()
python
def _zmq_socket_context(context, socket_type, bind_endpoints): """A ZeroMQ socket context that both constructs a socket and closes it.""" socket = context.socket(socket_type) try: for endpoint in bind_endpoints: try: socket.bind(endpoint) except Exception: _logger.fatal("Could not bind to '%s'.", endpoint) raise yield socket finally: socket.close()
[ "def", "_zmq_socket_context", "(", "context", ",", "socket_type", ",", "bind_endpoints", ")", ":", "socket", "=", "context", ".", "socket", "(", "socket_type", ")", "try", ":", "for", "endpoint", "in", "bind_endpoints", ":", "try", ":", "socket", ".", "bind", "(", "endpoint", ")", "except", "Exception", ":", "_logger", ".", "fatal", "(", "\"Could not bind to '%s'.\"", ",", "endpoint", ")", "raise", "yield", "socket", "finally", ":", "socket", ".", "close", "(", ")" ]
A ZeroMQ socket context that both constructs a socket and closes it.
[ "A", "ZeroMQ", "socket", "context", "that", "both", "constructs", "a", "socket", "and", "closes", "it", "." ]
7f645d20186c1db55cfe53a0310c9fd6292f91ea
https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/main.py#L229-L241
train
JensRantil/rewind
rewind/server/main.py
_get_with_fallback
def _get_with_fallback(config, section, option, fallback): """Get a configuration value, using fallback for missing values. Parameters: config -- the configparser to try to extract the option value from. section -- the section to extract value from. option -- the name of the option to extract value from. fallback -- fallback value to return if no value was set in `config`. returns -- the config option value if it was set, else fallback. """ exists = (config.has_section(section) and config.has_option(section, option)) if not exists: return fallback else: return config.get(section, option)
python
def _get_with_fallback(config, section, option, fallback): """Get a configuration value, using fallback for missing values. Parameters: config -- the configparser to try to extract the option value from. section -- the section to extract value from. option -- the name of the option to extract value from. fallback -- fallback value to return if no value was set in `config`. returns -- the config option value if it was set, else fallback. """ exists = (config.has_section(section) and config.has_option(section, option)) if not exists: return fallback else: return config.get(section, option)
[ "def", "_get_with_fallback", "(", "config", ",", "section", ",", "option", ",", "fallback", ")", ":", "exists", "=", "(", "config", ".", "has_section", "(", "section", ")", "and", "config", ".", "has_option", "(", "section", ",", "option", ")", ")", "if", "not", "exists", ":", "return", "fallback", "else", ":", "return", "config", ".", "get", "(", "section", ",", "option", ")" ]
Get a configuration value, using fallback for missing values. Parameters: config -- the configparser to try to extract the option value from. section -- the section to extract value from. option -- the name of the option to extract value from. fallback -- fallback value to return if no value was set in `config`. returns -- the config option value if it was set, else fallback.
[ "Get", "a", "configuration", "value", "using", "fallback", "for", "missing", "values", "." ]
7f645d20186c1db55cfe53a0310c9fd6292f91ea
https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/main.py#L244-L262
train
JensRantil/rewind
rewind/server/main.py
run
def run(options, exit_codeword=None): """Actually execute the program. Calling this method can be done from tests to simulate executing the application from command line. Parameters: options -- `optionparser` from config file. exit_codeword -- an optional exit_message that will shut down Rewind. Used for testing. returns -- exit code for the application. Non-zero for errors. """ QUERY_ENDP_OPT = 'query-bind-endpoint' STREAM_ENDP_OPT = 'streaming-bind-endpoint' ZMQ_NTHREADS = "zmq-nthreads" if not options.has_section(config.DEFAULT_SECTION): msg = "Missing default section, `{0}`." fmsg = msg.format(config.DEFAULT_SECTION) raise config.ConfigurationError(fmsg) if not options.has_option(config.DEFAULT_SECTION, QUERY_ENDP_OPT): msg = "Missing (query) bind endpoint in option file: {0}:{1}" fmsg = msg.format(config.DEFAULT_SECTION, QUERY_ENDP_OPT) raise config.ConfigurationError(fmsg) queryendp = options.get(config.DEFAULT_SECTION, QUERY_ENDP_OPT).split(",") streamendp = _get_with_fallback(options, config.DEFAULT_SECTION, STREAM_ENDP_OPT, '').split(",") queryendp = filter(lambda x: x.strip(), queryendp) streamendp = filter(lambda x: x.strip(), streamendp) try: eventstore = config.construct_eventstore(options) except config.ConfigurationError as e: _logger.exception("Could instantiate event store from config file.") raise zmq_nthreads = _get_with_fallback(options, config.DEFAULT_SECTION, ZMQ_NTHREADS, '3') try: zmq_nthreads = int(zmq_nthreads) except ValueError: msg = "{0}:{1} must be an integer".format(config.DEFAULT_SECTION, ZMQ_NTHREADS) _logger.fatal(msg) return 1 with _zmq_context_context(zmq_nthreads) as context, \ _zmq_socket_context(context, zmq.REP, queryendp) as querysock, \ _zmq_socket_context(context, zmq.PUB, streamendp) as streamsock: # Executing the program in the context of ZeroMQ context as well as # ZeroMQ sockets. Using with here to make sure are correctly closing # things in the correct order, particularly also if we have an # exception or similar. runner = _RewindRunner(eventstore, querysock, streamsock, (exit_codeword.encode() if exit_codeword else None)) runner.run() return 0
python
def run(options, exit_codeword=None): """Actually execute the program. Calling this method can be done from tests to simulate executing the application from command line. Parameters: options -- `optionparser` from config file. exit_codeword -- an optional exit_message that will shut down Rewind. Used for testing. returns -- exit code for the application. Non-zero for errors. """ QUERY_ENDP_OPT = 'query-bind-endpoint' STREAM_ENDP_OPT = 'streaming-bind-endpoint' ZMQ_NTHREADS = "zmq-nthreads" if not options.has_section(config.DEFAULT_SECTION): msg = "Missing default section, `{0}`." fmsg = msg.format(config.DEFAULT_SECTION) raise config.ConfigurationError(fmsg) if not options.has_option(config.DEFAULT_SECTION, QUERY_ENDP_OPT): msg = "Missing (query) bind endpoint in option file: {0}:{1}" fmsg = msg.format(config.DEFAULT_SECTION, QUERY_ENDP_OPT) raise config.ConfigurationError(fmsg) queryendp = options.get(config.DEFAULT_SECTION, QUERY_ENDP_OPT).split(",") streamendp = _get_with_fallback(options, config.DEFAULT_SECTION, STREAM_ENDP_OPT, '').split(",") queryendp = filter(lambda x: x.strip(), queryendp) streamendp = filter(lambda x: x.strip(), streamendp) try: eventstore = config.construct_eventstore(options) except config.ConfigurationError as e: _logger.exception("Could instantiate event store from config file.") raise zmq_nthreads = _get_with_fallback(options, config.DEFAULT_SECTION, ZMQ_NTHREADS, '3') try: zmq_nthreads = int(zmq_nthreads) except ValueError: msg = "{0}:{1} must be an integer".format(config.DEFAULT_SECTION, ZMQ_NTHREADS) _logger.fatal(msg) return 1 with _zmq_context_context(zmq_nthreads) as context, \ _zmq_socket_context(context, zmq.REP, queryendp) as querysock, \ _zmq_socket_context(context, zmq.PUB, streamendp) as streamsock: # Executing the program in the context of ZeroMQ context as well as # ZeroMQ sockets. Using with here to make sure are correctly closing # things in the correct order, particularly also if we have an # exception or similar. runner = _RewindRunner(eventstore, querysock, streamsock, (exit_codeword.encode() if exit_codeword else None)) runner.run() return 0
[ "def", "run", "(", "options", ",", "exit_codeword", "=", "None", ")", ":", "QUERY_ENDP_OPT", "=", "'query-bind-endpoint'", "STREAM_ENDP_OPT", "=", "'streaming-bind-endpoint'", "ZMQ_NTHREADS", "=", "\"zmq-nthreads\"", "if", "not", "options", ".", "has_section", "(", "config", ".", "DEFAULT_SECTION", ")", ":", "msg", "=", "\"Missing default section, `{0}`.\"", "fmsg", "=", "msg", ".", "format", "(", "config", ".", "DEFAULT_SECTION", ")", "raise", "config", ".", "ConfigurationError", "(", "fmsg", ")", "if", "not", "options", ".", "has_option", "(", "config", ".", "DEFAULT_SECTION", ",", "QUERY_ENDP_OPT", ")", ":", "msg", "=", "\"Missing (query) bind endpoint in option file: {0}:{1}\"", "fmsg", "=", "msg", ".", "format", "(", "config", ".", "DEFAULT_SECTION", ",", "QUERY_ENDP_OPT", ")", "raise", "config", ".", "ConfigurationError", "(", "fmsg", ")", "queryendp", "=", "options", ".", "get", "(", "config", ".", "DEFAULT_SECTION", ",", "QUERY_ENDP_OPT", ")", ".", "split", "(", "\",\"", ")", "streamendp", "=", "_get_with_fallback", "(", "options", ",", "config", ".", "DEFAULT_SECTION", ",", "STREAM_ENDP_OPT", ",", "''", ")", ".", "split", "(", "\",\"", ")", "queryendp", "=", "filter", "(", "lambda", "x", ":", "x", ".", "strip", "(", ")", ",", "queryendp", ")", "streamendp", "=", "filter", "(", "lambda", "x", ":", "x", ".", "strip", "(", ")", ",", "streamendp", ")", "try", ":", "eventstore", "=", "config", ".", "construct_eventstore", "(", "options", ")", "except", "config", ".", "ConfigurationError", "as", "e", ":", "_logger", ".", "exception", "(", "\"Could instantiate event store from config file.\"", ")", "raise", "zmq_nthreads", "=", "_get_with_fallback", "(", "options", ",", "config", ".", "DEFAULT_SECTION", ",", "ZMQ_NTHREADS", ",", "'3'", ")", "try", ":", "zmq_nthreads", "=", "int", "(", "zmq_nthreads", ")", "except", "ValueError", ":", "msg", "=", "\"{0}:{1} must be an integer\"", ".", "format", "(", "config", ".", "DEFAULT_SECTION", ",", "ZMQ_NTHREADS", ")", "_logger", ".", "fatal", "(", "msg", ")", "return", "1", "with", "_zmq_context_context", "(", "zmq_nthreads", ")", "as", "context", ",", "_zmq_socket_context", "(", "context", ",", "zmq", ".", "REP", ",", "queryendp", ")", "as", "querysock", ",", "_zmq_socket_context", "(", "context", ",", "zmq", ".", "PUB", ",", "streamendp", ")", "as", "streamsock", ":", "# Executing the program in the context of ZeroMQ context as well as", "# ZeroMQ sockets. Using with here to make sure are correctly closing", "# things in the correct order, particularly also if we have an", "# exception or similar.", "runner", "=", "_RewindRunner", "(", "eventstore", ",", "querysock", ",", "streamsock", ",", "(", "exit_codeword", ".", "encode", "(", ")", "if", "exit_codeword", "else", "None", ")", ")", "runner", ".", "run", "(", ")", "return", "0" ]
Actually execute the program. Calling this method can be done from tests to simulate executing the application from command line. Parameters: options -- `optionparser` from config file. exit_codeword -- an optional exit_message that will shut down Rewind. Used for testing. returns -- exit code for the application. Non-zero for errors.
[ "Actually", "execute", "the", "program", "." ]
7f645d20186c1db55cfe53a0310c9fd6292f91ea
https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/main.py#L265-L330
train
JensRantil/rewind
rewind/server/main.py
main
def main(argv=None): """Entry point for Rewind. Parses input and calls run() for the real work. Parameters: argv -- sys.argv arguments. Can be set for testing purposes. returns -- the proposed exit code for the program. """ parser = argparse.ArgumentParser( description='Event storage and event proxy.', usage='%(prog)s <configfile>' ) parser.add_argument('--exit-codeword', metavar="MSG", dest="exit_message", default=None, help="An incoming message that makes" " Rewind quit. Used for testing.") parser.add_argument('configfile') args = argv if argv is not None else sys.argv[1:] args = parser.parse_args(args) config = configparser.SafeConfigParser() with open(args.configfile) as f: config.readfp(f) exitcode = run(config, args.exit_message) return exitcode
python
def main(argv=None): """Entry point for Rewind. Parses input and calls run() for the real work. Parameters: argv -- sys.argv arguments. Can be set for testing purposes. returns -- the proposed exit code for the program. """ parser = argparse.ArgumentParser( description='Event storage and event proxy.', usage='%(prog)s <configfile>' ) parser.add_argument('--exit-codeword', metavar="MSG", dest="exit_message", default=None, help="An incoming message that makes" " Rewind quit. Used for testing.") parser.add_argument('configfile') args = argv if argv is not None else sys.argv[1:] args = parser.parse_args(args) config = configparser.SafeConfigParser() with open(args.configfile) as f: config.readfp(f) exitcode = run(config, args.exit_message) return exitcode
[ "def", "main", "(", "argv", "=", "None", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Event storage and event proxy.'", ",", "usage", "=", "'%(prog)s <configfile>'", ")", "parser", ".", "add_argument", "(", "'--exit-codeword'", ",", "metavar", "=", "\"MSG\"", ",", "dest", "=", "\"exit_message\"", ",", "default", "=", "None", ",", "help", "=", "\"An incoming message that makes\"", "\" Rewind quit. Used for testing.\"", ")", "parser", ".", "add_argument", "(", "'configfile'", ")", "args", "=", "argv", "if", "argv", "is", "not", "None", "else", "sys", ".", "argv", "[", "1", ":", "]", "args", "=", "parser", ".", "parse_args", "(", "args", ")", "config", "=", "configparser", ".", "SafeConfigParser", "(", ")", "with", "open", "(", "args", ".", "configfile", ")", "as", "f", ":", "config", ".", "readfp", "(", "f", ")", "exitcode", "=", "run", "(", "config", ",", "args", ".", "exit_message", ")", "return", "exitcode" ]
Entry point for Rewind. Parses input and calls run() for the real work. Parameters: argv -- sys.argv arguments. Can be set for testing purposes. returns -- the proposed exit code for the program.
[ "Entry", "point", "for", "Rewind", "." ]
7f645d20186c1db55cfe53a0310c9fd6292f91ea
https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/main.py#L333-L361
train
JensRantil/rewind
rewind/server/main.py
_IdGenerator.generate
def generate(self): """Generate a new string and return it.""" key = self._propose_new_key() while self.key_exists(key): _logger.warning('Previous candidate was used.' ' Regenerating another...') key = self._propose_new_key() return key
python
def generate(self): """Generate a new string and return it.""" key = self._propose_new_key() while self.key_exists(key): _logger.warning('Previous candidate was used.' ' Regenerating another...') key = self._propose_new_key() return key
[ "def", "generate", "(", "self", ")", ":", "key", "=", "self", ".", "_propose_new_key", "(", ")", "while", "self", ".", "key_exists", "(", "key", ")", ":", "_logger", ".", "warning", "(", "'Previous candidate was used.'", "' Regenerating another...'", ")", "key", "=", "self", ".", "_propose_new_key", "(", ")", "return", "key" ]
Generate a new string and return it.
[ "Generate", "a", "new", "string", "and", "return", "it", "." ]
7f645d20186c1db55cfe53a0310c9fd6292f91ea
https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/main.py#L55-L62
train
JensRantil/rewind
rewind/server/main.py
_RewindRunner._handle_one_message
def _handle_one_message(self): """Handle one single incoming message on any socket. This is the inner loop of the main application loop. Returns True if further messages should be received, False otherwise (it should quit, that is). It is crucial that this class function always respond with a query_socket.sent() for every query_socket.recv() call. Otherwise, clients and/or server might be stuck in limbo. """ result = True requesttype = self.query_socket.recv() if requesttype == b"PUBLISH": self._handle_incoming_event() elif requesttype == b"QUERY": self._handle_event_query() elif (self.exit_message is not None and requesttype == self.exit_message): _logger.warn("Asked to quit through an exit message." "I'm quitting...") self.query_socket.send(b'QUIT') result = False else: _logger.warn("Could not identify request type: %s", requesttype) self._handle_unknown_command() return result
python
def _handle_one_message(self): """Handle one single incoming message on any socket. This is the inner loop of the main application loop. Returns True if further messages should be received, False otherwise (it should quit, that is). It is crucial that this class function always respond with a query_socket.sent() for every query_socket.recv() call. Otherwise, clients and/or server might be stuck in limbo. """ result = True requesttype = self.query_socket.recv() if requesttype == b"PUBLISH": self._handle_incoming_event() elif requesttype == b"QUERY": self._handle_event_query() elif (self.exit_message is not None and requesttype == self.exit_message): _logger.warn("Asked to quit through an exit message." "I'm quitting...") self.query_socket.send(b'QUIT') result = False else: _logger.warn("Could not identify request type: %s", requesttype) self._handle_unknown_command() return result
[ "def", "_handle_one_message", "(", "self", ")", ":", "result", "=", "True", "requesttype", "=", "self", ".", "query_socket", ".", "recv", "(", ")", "if", "requesttype", "==", "b\"PUBLISH\"", ":", "self", ".", "_handle_incoming_event", "(", ")", "elif", "requesttype", "==", "b\"QUERY\"", ":", "self", ".", "_handle_event_query", "(", ")", "elif", "(", "self", ".", "exit_message", "is", "not", "None", "and", "requesttype", "==", "self", ".", "exit_message", ")", ":", "_logger", ".", "warn", "(", "\"Asked to quit through an exit message.\"", "\"I'm quitting...\"", ")", "self", ".", "query_socket", ".", "send", "(", "b'QUIT'", ")", "result", "=", "False", "else", ":", "_logger", ".", "warn", "(", "\"Could not identify request type: %s\"", ",", "requesttype", ")", "self", ".", "_handle_unknown_command", "(", ")", "return", "result" ]
Handle one single incoming message on any socket. This is the inner loop of the main application loop. Returns True if further messages should be received, False otherwise (it should quit, that is). It is crucial that this class function always respond with a query_socket.sent() for every query_socket.recv() call. Otherwise, clients and/or server might be stuck in limbo.
[ "Handle", "one", "single", "incoming", "message", "on", "any", "socket", "." ]
7f645d20186c1db55cfe53a0310c9fd6292f91ea
https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/main.py#L98-L129
train
JensRantil/rewind
rewind/server/main.py
_RewindRunner._handle_unknown_command
def _handle_unknown_command(self): """Handle an unknown RES command. The function makes sure to recv all message parts and respond with an error. """ while self.query_socket.getsockopt(zmq.RCVMORE): # Making sure we 'empty' enveloped message. Otherwise, we can't # respond. self.query_socket.recv() self.query_socket.send(b"ERROR Unknown request type")
python
def _handle_unknown_command(self): """Handle an unknown RES command. The function makes sure to recv all message parts and respond with an error. """ while self.query_socket.getsockopt(zmq.RCVMORE): # Making sure we 'empty' enveloped message. Otherwise, we can't # respond. self.query_socket.recv() self.query_socket.send(b"ERROR Unknown request type")
[ "def", "_handle_unknown_command", "(", "self", ")", ":", "while", "self", ".", "query_socket", ".", "getsockopt", "(", "zmq", ".", "RCVMORE", ")", ":", "# Making sure we 'empty' enveloped message. Otherwise, we can't", "# respond.", "self", ".", "query_socket", ".", "recv", "(", ")", "self", ".", "query_socket", ".", "send", "(", "b\"ERROR Unknown request type\"", ")" ]
Handle an unknown RES command. The function makes sure to recv all message parts and respond with an error.
[ "Handle", "an", "unknown", "RES", "command", "." ]
7f645d20186c1db55cfe53a0310c9fd6292f91ea
https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/main.py#L131-L142
train
JensRantil/rewind
rewind/server/main.py
_RewindRunner._handle_event_query
def _handle_event_query(self): """Handle an incoming event query.""" assert self.query_socket.getsockopt(zmq.RCVMORE) fro = self.query_socket.recv().decode() assert self.query_socket.getsockopt(zmq.RCVMORE) to = self.query_socket.recv().decode() assert not self.query_socket.getsockopt(zmq.RCVMORE) _logger.debug("Incoming query: (from, to)=(%s, %s)", fro, to) try: events = self.eventstore.get_events(fro if fro else None, to if to else None) except eventstores.EventStore.EventKeyDoesNotExistError: _logger.exception("A client requested a key that does not" " exist:") self.query_socket.send(b"ERROR Key did not exist") return # Since we are using ZeroMQ enveloping we want to cap the # maximum number of messages that are send for each request. # Otherwise we might run out of memory for a lot of events. MAX_ELMNTS_PER_REQ = 100 events = itertools.islice(events, 0, MAX_ELMNTS_PER_REQ) events = list(events) if len(events) == MAX_ELMNTS_PER_REQ: # There are more elements, but we are capping the result for eventid, eventdata in events[:-1]: self.query_socket.send(eventid.encode(), zmq.SNDMORE) self.query_socket.send(eventdata, zmq.SNDMORE) lasteventid, lasteventdata = events[-1] self.query_socket.send(lasteventid.encode(), zmq.SNDMORE) self.query_socket.send(lasteventdata) else: # Sending all events. Ie., we are not capping for eventid, eventdata in events: self.query_socket.send(eventid.encode(), zmq.SNDMORE) self.query_socket.send(eventdata, zmq.SNDMORE) self.query_socket.send(b"END")
python
def _handle_event_query(self): """Handle an incoming event query.""" assert self.query_socket.getsockopt(zmq.RCVMORE) fro = self.query_socket.recv().decode() assert self.query_socket.getsockopt(zmq.RCVMORE) to = self.query_socket.recv().decode() assert not self.query_socket.getsockopt(zmq.RCVMORE) _logger.debug("Incoming query: (from, to)=(%s, %s)", fro, to) try: events = self.eventstore.get_events(fro if fro else None, to if to else None) except eventstores.EventStore.EventKeyDoesNotExistError: _logger.exception("A client requested a key that does not" " exist:") self.query_socket.send(b"ERROR Key did not exist") return # Since we are using ZeroMQ enveloping we want to cap the # maximum number of messages that are send for each request. # Otherwise we might run out of memory for a lot of events. MAX_ELMNTS_PER_REQ = 100 events = itertools.islice(events, 0, MAX_ELMNTS_PER_REQ) events = list(events) if len(events) == MAX_ELMNTS_PER_REQ: # There are more elements, but we are capping the result for eventid, eventdata in events[:-1]: self.query_socket.send(eventid.encode(), zmq.SNDMORE) self.query_socket.send(eventdata, zmq.SNDMORE) lasteventid, lasteventdata = events[-1] self.query_socket.send(lasteventid.encode(), zmq.SNDMORE) self.query_socket.send(lasteventdata) else: # Sending all events. Ie., we are not capping for eventid, eventdata in events: self.query_socket.send(eventid.encode(), zmq.SNDMORE) self.query_socket.send(eventdata, zmq.SNDMORE) self.query_socket.send(b"END")
[ "def", "_handle_event_query", "(", "self", ")", ":", "assert", "self", ".", "query_socket", ".", "getsockopt", "(", "zmq", ".", "RCVMORE", ")", "fro", "=", "self", ".", "query_socket", ".", "recv", "(", ")", ".", "decode", "(", ")", "assert", "self", ".", "query_socket", ".", "getsockopt", "(", "zmq", ".", "RCVMORE", ")", "to", "=", "self", ".", "query_socket", ".", "recv", "(", ")", ".", "decode", "(", ")", "assert", "not", "self", ".", "query_socket", ".", "getsockopt", "(", "zmq", ".", "RCVMORE", ")", "_logger", ".", "debug", "(", "\"Incoming query: (from, to)=(%s, %s)\"", ",", "fro", ",", "to", ")", "try", ":", "events", "=", "self", ".", "eventstore", ".", "get_events", "(", "fro", "if", "fro", "else", "None", ",", "to", "if", "to", "else", "None", ")", "except", "eventstores", ".", "EventStore", ".", "EventKeyDoesNotExistError", ":", "_logger", ".", "exception", "(", "\"A client requested a key that does not\"", "\" exist:\"", ")", "self", ".", "query_socket", ".", "send", "(", "b\"ERROR Key did not exist\"", ")", "return", "# Since we are using ZeroMQ enveloping we want to cap the", "# maximum number of messages that are send for each request.", "# Otherwise we might run out of memory for a lot of events.", "MAX_ELMNTS_PER_REQ", "=", "100", "events", "=", "itertools", ".", "islice", "(", "events", ",", "0", ",", "MAX_ELMNTS_PER_REQ", ")", "events", "=", "list", "(", "events", ")", "if", "len", "(", "events", ")", "==", "MAX_ELMNTS_PER_REQ", ":", "# There are more elements, but we are capping the result", "for", "eventid", ",", "eventdata", "in", "events", "[", ":", "-", "1", "]", ":", "self", ".", "query_socket", ".", "send", "(", "eventid", ".", "encode", "(", ")", ",", "zmq", ".", "SNDMORE", ")", "self", ".", "query_socket", ".", "send", "(", "eventdata", ",", "zmq", ".", "SNDMORE", ")", "lasteventid", ",", "lasteventdata", "=", "events", "[", "-", "1", "]", "self", ".", "query_socket", ".", "send", "(", "lasteventid", ".", "encode", "(", ")", ",", "zmq", ".", "SNDMORE", ")", "self", ".", "query_socket", ".", "send", "(", "lasteventdata", ")", "else", ":", "# Sending all events. Ie., we are not capping", "for", "eventid", ",", "eventdata", "in", "events", ":", "self", ".", "query_socket", ".", "send", "(", "eventid", ".", "encode", "(", ")", ",", "zmq", ".", "SNDMORE", ")", "self", ".", "query_socket", ".", "send", "(", "eventdata", ",", "zmq", ".", "SNDMORE", ")", "self", ".", "query_socket", ".", "send", "(", "b\"END\"", ")" ]
Handle an incoming event query.
[ "Handle", "an", "incoming", "event", "query", "." ]
7f645d20186c1db55cfe53a0310c9fd6292f91ea
https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/main.py#L144-L183
train
JensRantil/rewind
rewind/server/main.py
_RewindRunner._handle_incoming_event
def _handle_incoming_event(self): """Handle an incoming event. Returns True if further messages should be received, False otherwise (it should quit, that is). TODO: Move the content of this function into `_handle_one_message`. This class function does not simply handle incoming events. """ eventstr = self.query_socket.recv() newid = self.id_generator.generate() # Make sure newid is not part of our request vocabulary assert newid not in (b"QUERY", b"PUBLISH"), \ "Generated ID must not be part of req/rep vocabulary." assert not newid.startswith("ERROR"), \ "Generated ID must not be part of req/rep vocabulary." # Important this is done before forwarding to the streaming socket self.eventstore.add_event(newid, eventstr) self.streaming_socket.send(newid.encode(), zmq.SNDMORE) self.streaming_socket.send(self.oldid.encode(), zmq.SNDMORE) self.streaming_socket.send(eventstr) self.oldid = newid assert not self.query_socket.getsockopt(zmq.RCVMORE) self.query_socket.send(b"PUBLISHED")
python
def _handle_incoming_event(self): """Handle an incoming event. Returns True if further messages should be received, False otherwise (it should quit, that is). TODO: Move the content of this function into `_handle_one_message`. This class function does not simply handle incoming events. """ eventstr = self.query_socket.recv() newid = self.id_generator.generate() # Make sure newid is not part of our request vocabulary assert newid not in (b"QUERY", b"PUBLISH"), \ "Generated ID must not be part of req/rep vocabulary." assert not newid.startswith("ERROR"), \ "Generated ID must not be part of req/rep vocabulary." # Important this is done before forwarding to the streaming socket self.eventstore.add_event(newid, eventstr) self.streaming_socket.send(newid.encode(), zmq.SNDMORE) self.streaming_socket.send(self.oldid.encode(), zmq.SNDMORE) self.streaming_socket.send(eventstr) self.oldid = newid assert not self.query_socket.getsockopt(zmq.RCVMORE) self.query_socket.send(b"PUBLISHED")
[ "def", "_handle_incoming_event", "(", "self", ")", ":", "eventstr", "=", "self", ".", "query_socket", ".", "recv", "(", ")", "newid", "=", "self", ".", "id_generator", ".", "generate", "(", ")", "# Make sure newid is not part of our request vocabulary", "assert", "newid", "not", "in", "(", "b\"QUERY\"", ",", "b\"PUBLISH\"", ")", ",", "\"Generated ID must not be part of req/rep vocabulary.\"", "assert", "not", "newid", ".", "startswith", "(", "\"ERROR\"", ")", ",", "\"Generated ID must not be part of req/rep vocabulary.\"", "# Important this is done before forwarding to the streaming socket", "self", ".", "eventstore", ".", "add_event", "(", "newid", ",", "eventstr", ")", "self", ".", "streaming_socket", ".", "send", "(", "newid", ".", "encode", "(", ")", ",", "zmq", ".", "SNDMORE", ")", "self", ".", "streaming_socket", ".", "send", "(", "self", ".", "oldid", ".", "encode", "(", ")", ",", "zmq", ".", "SNDMORE", ")", "self", ".", "streaming_socket", ".", "send", "(", "eventstr", ")", "self", ".", "oldid", "=", "newid", "assert", "not", "self", ".", "query_socket", ".", "getsockopt", "(", "zmq", ".", "RCVMORE", ")", "self", ".", "query_socket", ".", "send", "(", "b\"PUBLISHED\"", ")" ]
Handle an incoming event. Returns True if further messages should be received, False otherwise (it should quit, that is). TODO: Move the content of this function into `_handle_one_message`. This class function does not simply handle incoming events.
[ "Handle", "an", "incoming", "event", "." ]
7f645d20186c1db55cfe53a0310c9fd6292f91ea
https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/main.py#L185-L215
train
yeraydiazdiaz/lunr.py
lunr/idf.py
idf
def idf(posting, document_count): """A function to calculate the inverse document frequency for a posting. This is shared between the builder and the index. """ documents_with_term = 0 for field_name in posting: if field_name == "_index": continue documents_with_term += len(posting[field_name].keys()) x = (document_count - documents_with_term + 0.5) / (documents_with_term + 0.5) return math.log(1 + abs(x))
python
def idf(posting, document_count): """A function to calculate the inverse document frequency for a posting. This is shared between the builder and the index. """ documents_with_term = 0 for field_name in posting: if field_name == "_index": continue documents_with_term += len(posting[field_name].keys()) x = (document_count - documents_with_term + 0.5) / (documents_with_term + 0.5) return math.log(1 + abs(x))
[ "def", "idf", "(", "posting", ",", "document_count", ")", ":", "documents_with_term", "=", "0", "for", "field_name", "in", "posting", ":", "if", "field_name", "==", "\"_index\"", ":", "continue", "documents_with_term", "+=", "len", "(", "posting", "[", "field_name", "]", ".", "keys", "(", ")", ")", "x", "=", "(", "document_count", "-", "documents_with_term", "+", "0.5", ")", "/", "(", "documents_with_term", "+", "0.5", ")", "return", "math", ".", "log", "(", "1", "+", "abs", "(", "x", ")", ")" ]
A function to calculate the inverse document frequency for a posting. This is shared between the builder and the index.
[ "A", "function", "to", "calculate", "the", "inverse", "document", "frequency", "for", "a", "posting", ".", "This", "is", "shared", "between", "the", "builder", "and", "the", "index", "." ]
28ec3f6d4888295eed730211ee9617aa488d6ba3
https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/idf.py#L6-L17
train
JensRantil/rewind
rewind/server/config.py
check_config_options
def check_config_options(_class, required_options, optional_options, options): """Helper method to check options. Arguments: _class -- the original class that takes received the options. required_options -- the options that are required. If they are not present, a ConfigurationError is raised. Given as a tuple. optional_options -- the options that are optional. Given options that are not present in `optional_options` nor in `required_options` will be logged as unrecognized. Given as a tuple. options -- a dictionary of given options. Raises: ConfigurationError -- if any required option is missing. """ for opt in required_options: if opt not in options: msg = "Required option missing: {0}" raise ConfigurationError(msg.format(opt)) for opt in options: if opt not in (required_options + optional_options): msg = "Unknown config option to `{0}`: {1}" _logger.warn(msg.format(_class, opt))
python
def check_config_options(_class, required_options, optional_options, options): """Helper method to check options. Arguments: _class -- the original class that takes received the options. required_options -- the options that are required. If they are not present, a ConfigurationError is raised. Given as a tuple. optional_options -- the options that are optional. Given options that are not present in `optional_options` nor in `required_options` will be logged as unrecognized. Given as a tuple. options -- a dictionary of given options. Raises: ConfigurationError -- if any required option is missing. """ for opt in required_options: if opt not in options: msg = "Required option missing: {0}" raise ConfigurationError(msg.format(opt)) for opt in options: if opt not in (required_options + optional_options): msg = "Unknown config option to `{0}`: {1}" _logger.warn(msg.format(_class, opt))
[ "def", "check_config_options", "(", "_class", ",", "required_options", ",", "optional_options", ",", "options", ")", ":", "for", "opt", "in", "required_options", ":", "if", "opt", "not", "in", "options", ":", "msg", "=", "\"Required option missing: {0}\"", "raise", "ConfigurationError", "(", "msg", ".", "format", "(", "opt", ")", ")", "for", "opt", "in", "options", ":", "if", "opt", "not", "in", "(", "required_options", "+", "optional_options", ")", ":", "msg", "=", "\"Unknown config option to `{0}`: {1}\"", "_logger", ".", "warn", "(", "msg", ".", "format", "(", "_class", ",", "opt", ")", ")" ]
Helper method to check options. Arguments: _class -- the original class that takes received the options. required_options -- the options that are required. If they are not present, a ConfigurationError is raised. Given as a tuple. optional_options -- the options that are optional. Given options that are not present in `optional_options` nor in `required_options` will be logged as unrecognized. Given as a tuple. options -- a dictionary of given options. Raises: ConfigurationError -- if any required option is missing.
[ "Helper", "method", "to", "check", "options", "." ]
7f645d20186c1db55cfe53a0310c9fd6292f91ea
https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/config.py#L123-L148
train
tehmaze/natural
natural/file.py
accessed
def accessed(filename): ''' Retrieve how long ago a file has been accessed. :param filename: name of the file >>> print accessed(__file__) # doctest: +SKIP just now ''' if isinstance(filename, file): filename = filename.name return duration(os.stat(filename)[stat.ST_ATIME])
python
def accessed(filename): ''' Retrieve how long ago a file has been accessed. :param filename: name of the file >>> print accessed(__file__) # doctest: +SKIP just now ''' if isinstance(filename, file): filename = filename.name return duration(os.stat(filename)[stat.ST_ATIME])
[ "def", "accessed", "(", "filename", ")", ":", "if", "isinstance", "(", "filename", ",", "file", ")", ":", "filename", "=", "filename", ".", "name", "return", "duration", "(", "os", ".", "stat", "(", "filename", ")", "[", "stat", ".", "ST_ATIME", "]", ")" ]
Retrieve how long ago a file has been accessed. :param filename: name of the file >>> print accessed(__file__) # doctest: +SKIP just now
[ "Retrieve", "how", "long", "ago", "a", "file", "has", "been", "accessed", "." ]
d7a1fc9de712f9bcf68884a80826a7977df356fb
https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/file.py#L7-L19
train
tehmaze/natural
natural/file.py
created
def created(filename): ''' Retrieve how long ago a file has been created. :param filename: name of the file >>> print created('/') # doctest: +SKIP 8 weeks ago ''' if isinstance(filename, file): filename = filename.name return duration(os.stat(filename)[stat.ST_CTIME])
python
def created(filename): ''' Retrieve how long ago a file has been created. :param filename: name of the file >>> print created('/') # doctest: +SKIP 8 weeks ago ''' if isinstance(filename, file): filename = filename.name return duration(os.stat(filename)[stat.ST_CTIME])
[ "def", "created", "(", "filename", ")", ":", "if", "isinstance", "(", "filename", ",", "file", ")", ":", "filename", "=", "filename", ".", "name", "return", "duration", "(", "os", ".", "stat", "(", "filename", ")", "[", "stat", ".", "ST_CTIME", "]", ")" ]
Retrieve how long ago a file has been created. :param filename: name of the file >>> print created('/') # doctest: +SKIP 8 weeks ago
[ "Retrieve", "how", "long", "ago", "a", "file", "has", "been", "created", "." ]
d7a1fc9de712f9bcf68884a80826a7977df356fb
https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/file.py#L22-L34
train
tehmaze/natural
natural/file.py
modified
def modified(filename): ''' Retrieve how long ago a file has been modified. :param filename: name of the file >>> print modified('/') # doctest: +SKIP 3 days ago ''' if isinstance(filename, file): filename = filename.name return duration(os.stat(filename)[stat.ST_MTIME])
python
def modified(filename): ''' Retrieve how long ago a file has been modified. :param filename: name of the file >>> print modified('/') # doctest: +SKIP 3 days ago ''' if isinstance(filename, file): filename = filename.name return duration(os.stat(filename)[stat.ST_MTIME])
[ "def", "modified", "(", "filename", ")", ":", "if", "isinstance", "(", "filename", ",", "file", ")", ":", "filename", "=", "filename", ".", "name", "return", "duration", "(", "os", ".", "stat", "(", "filename", ")", "[", "stat", ".", "ST_MTIME", "]", ")" ]
Retrieve how long ago a file has been modified. :param filename: name of the file >>> print modified('/') # doctest: +SKIP 3 days ago
[ "Retrieve", "how", "long", "ago", "a", "file", "has", "been", "modified", "." ]
d7a1fc9de712f9bcf68884a80826a7977df356fb
https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/file.py#L37-L49
train
tehmaze/natural
natural/file.py
size
def size(filename, format='decimal'): ''' Retrieve the size of a file. :param filename: name of the file >>> size('/etc/mime.types') # doctest: +SKIP 23.70 kB ''' if isinstance(filename, file): filename = filename.name return filesize(os.stat(filename)[stat.ST_SIZE], format)
python
def size(filename, format='decimal'): ''' Retrieve the size of a file. :param filename: name of the file >>> size('/etc/mime.types') # doctest: +SKIP 23.70 kB ''' if isinstance(filename, file): filename = filename.name return filesize(os.stat(filename)[stat.ST_SIZE], format)
[ "def", "size", "(", "filename", ",", "format", "=", "'decimal'", ")", ":", "if", "isinstance", "(", "filename", ",", "file", ")", ":", "filename", "=", "filename", ".", "name", "return", "filesize", "(", "os", ".", "stat", "(", "filename", ")", "[", "stat", ".", "ST_SIZE", "]", ",", "format", ")" ]
Retrieve the size of a file. :param filename: name of the file >>> size('/etc/mime.types') # doctest: +SKIP 23.70 kB
[ "Retrieve", "the", "size", "of", "a", "file", "." ]
d7a1fc9de712f9bcf68884a80826a7977df356fb
https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/file.py#L52-L65
train
mapeveri/django-endless-pagination-vue
endless_pagination/templatetags/endless.py
show_more
def show_more(context, label=None, loading=settings.LOADING): """Show the link to get the next page in a Twitter-like pagination. Usage:: {% show_more %} Alternatively you can override the label passed to the default template:: {% show_more "even more" %} You can override the loading text too:: {% show_more "even more" "working" %} Must be called after ``{% paginate objects %}``. """ # This template tag could raise a PaginationError: you have to call # *paginate* or *lazy_paginate* before including the showmore template. data = utils.get_data_from_context(context) page = data['page'] # show the template only if there is a next page if page.has_next(): request = context['request'] page_number = page.next_page_number() # Generate the querystring. querystring_key = data['querystring_key'] querystring = utils.get_querystring_for_page( request, page_number, querystring_key, default_number=data['default_number']) return { 'label': label, 'loading': loading, 'path': iri_to_uri(data['override_path'] or request.path), 'querystring': querystring, 'querystring_key': querystring_key, 'request': request, } # No next page, nothing to see. return {}
python
def show_more(context, label=None, loading=settings.LOADING): """Show the link to get the next page in a Twitter-like pagination. Usage:: {% show_more %} Alternatively you can override the label passed to the default template:: {% show_more "even more" %} You can override the loading text too:: {% show_more "even more" "working" %} Must be called after ``{% paginate objects %}``. """ # This template tag could raise a PaginationError: you have to call # *paginate* or *lazy_paginate* before including the showmore template. data = utils.get_data_from_context(context) page = data['page'] # show the template only if there is a next page if page.has_next(): request = context['request'] page_number = page.next_page_number() # Generate the querystring. querystring_key = data['querystring_key'] querystring = utils.get_querystring_for_page( request, page_number, querystring_key, default_number=data['default_number']) return { 'label': label, 'loading': loading, 'path': iri_to_uri(data['override_path'] or request.path), 'querystring': querystring, 'querystring_key': querystring_key, 'request': request, } # No next page, nothing to see. return {}
[ "def", "show_more", "(", "context", ",", "label", "=", "None", ",", "loading", "=", "settings", ".", "LOADING", ")", ":", "# This template tag could raise a PaginationError: you have to call", "# *paginate* or *lazy_paginate* before including the showmore template.", "data", "=", "utils", ".", "get_data_from_context", "(", "context", ")", "page", "=", "data", "[", "'page'", "]", "# show the template only if there is a next page", "if", "page", ".", "has_next", "(", ")", ":", "request", "=", "context", "[", "'request'", "]", "page_number", "=", "page", ".", "next_page_number", "(", ")", "# Generate the querystring.", "querystring_key", "=", "data", "[", "'querystring_key'", "]", "querystring", "=", "utils", ".", "get_querystring_for_page", "(", "request", ",", "page_number", ",", "querystring_key", ",", "default_number", "=", "data", "[", "'default_number'", "]", ")", "return", "{", "'label'", ":", "label", ",", "'loading'", ":", "loading", ",", "'path'", ":", "iri_to_uri", "(", "data", "[", "'override_path'", "]", "or", "request", ".", "path", ")", ",", "'querystring'", ":", "querystring", ",", "'querystring_key'", ":", "querystring_key", ",", "'request'", ":", "request", ",", "}", "# No next page, nothing to see.", "return", "{", "}" ]
Show the link to get the next page in a Twitter-like pagination. Usage:: {% show_more %} Alternatively you can override the label passed to the default template:: {% show_more "even more" %} You can override the loading text too:: {% show_more "even more" "working" %} Must be called after ``{% paginate objects %}``.
[ "Show", "the", "link", "to", "get", "the", "next", "page", "in", "a", "Twitter", "-", "like", "pagination", "." ]
3faa79a51b11d7ae0bd431abf8c38ecaf9180704
https://github.com/mapeveri/django-endless-pagination-vue/blob/3faa79a51b11d7ae0bd431abf8c38ecaf9180704/endless_pagination/templatetags/endless.py#L327-L366
train
mapeveri/django-endless-pagination-vue
endless_pagination/templatetags/endless.py
show_more_table
def show_more_table(context, label=None, loading=settings.LOADING): """Show the link to get the next page in a Twitter-like pagination in a template for table. Usage:: {% show_more_table %} Alternatively you can override the label passed to the default template:: {% show_more_table "even more" %} You can override the loading text too:: {% show_more_table "even more" "working" %} Must be called after ``{% paginate objects %}``. """ # This template tag could raise a PaginationError: you have to call # *paginate* or *lazy_paginate* before including the showmore template. return show_more(context, label, loading)
python
def show_more_table(context, label=None, loading=settings.LOADING): """Show the link to get the next page in a Twitter-like pagination in a template for table. Usage:: {% show_more_table %} Alternatively you can override the label passed to the default template:: {% show_more_table "even more" %} You can override the loading text too:: {% show_more_table "even more" "working" %} Must be called after ``{% paginate objects %}``. """ # This template tag could raise a PaginationError: you have to call # *paginate* or *lazy_paginate* before including the showmore template. return show_more(context, label, loading)
[ "def", "show_more_table", "(", "context", ",", "label", "=", "None", ",", "loading", "=", "settings", ".", "LOADING", ")", ":", "# This template tag could raise a PaginationError: you have to call", "# *paginate* or *lazy_paginate* before including the showmore template.", "return", "show_more", "(", "context", ",", "label", ",", "loading", ")" ]
Show the link to get the next page in a Twitter-like pagination in a template for table. Usage:: {% show_more_table %} Alternatively you can override the label passed to the default template:: {% show_more_table "even more" %} You can override the loading text too:: {% show_more_table "even more" "working" %} Must be called after ``{% paginate objects %}``.
[ "Show", "the", "link", "to", "get", "the", "next", "page", "in", "a", "Twitter", "-", "like", "pagination", "in", "a", "template", "for", "table", "." ]
3faa79a51b11d7ae0bd431abf8c38ecaf9180704
https://github.com/mapeveri/django-endless-pagination-vue/blob/3faa79a51b11d7ae0bd431abf8c38ecaf9180704/endless_pagination/templatetags/endless.py#L370-L391
train
yeraydiazdiaz/lunr.py
lunr/languages/trimmer.py
generate_trimmer
def generate_trimmer(word_characters): """Returns a trimmer function from a string of word characters. TODO: lunr-languages ships with lists of word characters for each language I haven't found an equivalent in Python, we may need to copy it. """ start_re = r"^[^{}]+".format(word_characters) end_re = r"[^{}]+$".format(word_characters) def trimmer(token, i=None, tokens=None): def trim(s, metadata=None): s = re.sub(start_re, "", s) s = re.sub(end_re, "", s) return s return token.update(trim) return trimmer
python
def generate_trimmer(word_characters): """Returns a trimmer function from a string of word characters. TODO: lunr-languages ships with lists of word characters for each language I haven't found an equivalent in Python, we may need to copy it. """ start_re = r"^[^{}]+".format(word_characters) end_re = r"[^{}]+$".format(word_characters) def trimmer(token, i=None, tokens=None): def trim(s, metadata=None): s = re.sub(start_re, "", s) s = re.sub(end_re, "", s) return s return token.update(trim) return trimmer
[ "def", "generate_trimmer", "(", "word_characters", ")", ":", "start_re", "=", "r\"^[^{}]+\"", ".", "format", "(", "word_characters", ")", "end_re", "=", "r\"[^{}]+$\"", ".", "format", "(", "word_characters", ")", "def", "trimmer", "(", "token", ",", "i", "=", "None", ",", "tokens", "=", "None", ")", ":", "def", "trim", "(", "s", ",", "metadata", "=", "None", ")", ":", "s", "=", "re", ".", "sub", "(", "start_re", ",", "\"\"", ",", "s", ")", "s", "=", "re", ".", "sub", "(", "end_re", ",", "\"\"", ",", "s", ")", "return", "s", "return", "token", ".", "update", "(", "trim", ")", "return", "trimmer" ]
Returns a trimmer function from a string of word characters. TODO: lunr-languages ships with lists of word characters for each language I haven't found an equivalent in Python, we may need to copy it.
[ "Returns", "a", "trimmer", "function", "from", "a", "string", "of", "word", "characters", "." ]
28ec3f6d4888295eed730211ee9617aa488d6ba3
https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/languages/trimmer.py#L6-L23
train
kevin-brown/drf-json-api
rest_framework_json_api/utils.py
camelcase
def camelcase(string): '''Return a string in lowerCamelCase Examples: "people" -> "people" "profile images" -> "profileImages" ''' out = slug(string).replace('-', ' ').title().replace(' ', '') return out[0].lower() + out[1:]
python
def camelcase(string): '''Return a string in lowerCamelCase Examples: "people" -> "people" "profile images" -> "profileImages" ''' out = slug(string).replace('-', ' ').title().replace(' ', '') return out[0].lower() + out[1:]
[ "def", "camelcase", "(", "string", ")", ":", "out", "=", "slug", "(", "string", ")", ".", "replace", "(", "'-'", ",", "' '", ")", ".", "title", "(", ")", ".", "replace", "(", "' '", ",", "''", ")", "return", "out", "[", "0", "]", ".", "lower", "(", ")", "+", "out", "[", "1", ":", "]" ]
Return a string in lowerCamelCase Examples: "people" -> "people" "profile images" -> "profileImages"
[ "Return", "a", "string", "in", "lowerCamelCase" ]
664643bd02c0d92eadbd1f8c9d8507adf0538df6
https://github.com/kevin-brown/drf-json-api/blob/664643bd02c0d92eadbd1f8c9d8507adf0538df6/rest_framework_json_api/utils.py#L69-L77
train
yeraydiazdiaz/lunr.py
lunr/vector.py
Vector.position_for_index
def position_for_index(self, index): """Calculates the position within the vector to insert a given index. This is used internally by insert and upsert. If there are duplicate indexes then the position is returned as if the value for that index were to be updated, but it is the callers responsibility to check whether there is a duplicate at that index """ if not self.elements: return 0 start = 0 end = int(len(self.elements) / 2) slice_length = end - start pivot_point = int(slice_length / 2) pivot_index = self.elements[pivot_point * 2] while slice_length > 1: if pivot_index < index: start = pivot_point elif pivot_index > index: end = pivot_point else: break slice_length = end - start pivot_point = start + int(slice_length / 2) pivot_index = self.elements[pivot_point * 2] if pivot_index == index: return pivot_point * 2 elif pivot_index > index: return pivot_point * 2 else: return (pivot_point + 1) * 2
python
def position_for_index(self, index): """Calculates the position within the vector to insert a given index. This is used internally by insert and upsert. If there are duplicate indexes then the position is returned as if the value for that index were to be updated, but it is the callers responsibility to check whether there is a duplicate at that index """ if not self.elements: return 0 start = 0 end = int(len(self.elements) / 2) slice_length = end - start pivot_point = int(slice_length / 2) pivot_index = self.elements[pivot_point * 2] while slice_length > 1: if pivot_index < index: start = pivot_point elif pivot_index > index: end = pivot_point else: break slice_length = end - start pivot_point = start + int(slice_length / 2) pivot_index = self.elements[pivot_point * 2] if pivot_index == index: return pivot_point * 2 elif pivot_index > index: return pivot_point * 2 else: return (pivot_point + 1) * 2
[ "def", "position_for_index", "(", "self", ",", "index", ")", ":", "if", "not", "self", ".", "elements", ":", "return", "0", "start", "=", "0", "end", "=", "int", "(", "len", "(", "self", ".", "elements", ")", "/", "2", ")", "slice_length", "=", "end", "-", "start", "pivot_point", "=", "int", "(", "slice_length", "/", "2", ")", "pivot_index", "=", "self", ".", "elements", "[", "pivot_point", "*", "2", "]", "while", "slice_length", ">", "1", ":", "if", "pivot_index", "<", "index", ":", "start", "=", "pivot_point", "elif", "pivot_index", ">", "index", ":", "end", "=", "pivot_point", "else", ":", "break", "slice_length", "=", "end", "-", "start", "pivot_point", "=", "start", "+", "int", "(", "slice_length", "/", "2", ")", "pivot_index", "=", "self", ".", "elements", "[", "pivot_point", "*", "2", "]", "if", "pivot_index", "==", "index", ":", "return", "pivot_point", "*", "2", "elif", "pivot_index", ">", "index", ":", "return", "pivot_point", "*", "2", "else", ":", "return", "(", "pivot_point", "+", "1", ")", "*", "2" ]
Calculates the position within the vector to insert a given index. This is used internally by insert and upsert. If there are duplicate indexes then the position is returned as if the value for that index were to be updated, but it is the callers responsibility to check whether there is a duplicate at that index
[ "Calculates", "the", "position", "within", "the", "vector", "to", "insert", "a", "given", "index", "." ]
28ec3f6d4888295eed730211ee9617aa488d6ba3
https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/vector.py#L37-L71
train
yeraydiazdiaz/lunr.py
lunr/vector.py
Vector.insert
def insert(self, insert_index, val): """Inserts an element at an index within the vector. Does not allow duplicates, will throw an error if there is already an entry for this index. """ def prevent_duplicates(index, val): raise BaseLunrException("Duplicate index") self.upsert(insert_index, val, prevent_duplicates)
python
def insert(self, insert_index, val): """Inserts an element at an index within the vector. Does not allow duplicates, will throw an error if there is already an entry for this index. """ def prevent_duplicates(index, val): raise BaseLunrException("Duplicate index") self.upsert(insert_index, val, prevent_duplicates)
[ "def", "insert", "(", "self", ",", "insert_index", ",", "val", ")", ":", "def", "prevent_duplicates", "(", "index", ",", "val", ")", ":", "raise", "BaseLunrException", "(", "\"Duplicate index\"", ")", "self", ".", "upsert", "(", "insert_index", ",", "val", ",", "prevent_duplicates", ")" ]
Inserts an element at an index within the vector. Does not allow duplicates, will throw an error if there is already an entry for this index.
[ "Inserts", "an", "element", "at", "an", "index", "within", "the", "vector", "." ]
28ec3f6d4888295eed730211ee9617aa488d6ba3
https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/vector.py#L73-L83
train
yeraydiazdiaz/lunr.py
lunr/vector.py
Vector.upsert
def upsert(self, insert_index, val, fn=None): """Inserts or updates an existing index within the vector. Args: - insert_index (int): The index at which the element should be inserted. - val (int|float): The value to be inserted into the vector. - fn (callable, optional): An optional callable taking two arguments, the current value and the passed value to generate the final inserted value at the position in case of collision. """ fn = fn or (lambda current, passed: passed) self._magnitude = 0 position = self.position_for_index(insert_index) if position < len(self.elements) and self.elements[position] == insert_index: self.elements[position + 1] = fn(self.elements[position + 1], val) else: self.elements.insert(position, val) self.elements.insert(position, insert_index)
python
def upsert(self, insert_index, val, fn=None): """Inserts or updates an existing index within the vector. Args: - insert_index (int): The index at which the element should be inserted. - val (int|float): The value to be inserted into the vector. - fn (callable, optional): An optional callable taking two arguments, the current value and the passed value to generate the final inserted value at the position in case of collision. """ fn = fn or (lambda current, passed: passed) self._magnitude = 0 position = self.position_for_index(insert_index) if position < len(self.elements) and self.elements[position] == insert_index: self.elements[position + 1] = fn(self.elements[position + 1], val) else: self.elements.insert(position, val) self.elements.insert(position, insert_index)
[ "def", "upsert", "(", "self", ",", "insert_index", ",", "val", ",", "fn", "=", "None", ")", ":", "fn", "=", "fn", "or", "(", "lambda", "current", ",", "passed", ":", "passed", ")", "self", ".", "_magnitude", "=", "0", "position", "=", "self", ".", "position_for_index", "(", "insert_index", ")", "if", "position", "<", "len", "(", "self", ".", "elements", ")", "and", "self", ".", "elements", "[", "position", "]", "==", "insert_index", ":", "self", ".", "elements", "[", "position", "+", "1", "]", "=", "fn", "(", "self", ".", "elements", "[", "position", "+", "1", "]", ",", "val", ")", "else", ":", "self", ".", "elements", ".", "insert", "(", "position", ",", "val", ")", "self", ".", "elements", ".", "insert", "(", "position", ",", "insert_index", ")" ]
Inserts or updates an existing index within the vector. Args: - insert_index (int): The index at which the element should be inserted. - val (int|float): The value to be inserted into the vector. - fn (callable, optional): An optional callable taking two arguments, the current value and the passed value to generate the final inserted value at the position in case of collision.
[ "Inserts", "or", "updates", "an", "existing", "index", "within", "the", "vector", "." ]
28ec3f6d4888295eed730211ee9617aa488d6ba3
https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/vector.py#L85-L103
train
yeraydiazdiaz/lunr.py
lunr/vector.py
Vector.to_list
def to_list(self): """Converts the vector to an array of the elements within the vector""" output = [] for i in range(1, len(self.elements), 2): output.append(self.elements[i]) return output
python
def to_list(self): """Converts the vector to an array of the elements within the vector""" output = [] for i in range(1, len(self.elements), 2): output.append(self.elements[i]) return output
[ "def", "to_list", "(", "self", ")", ":", "output", "=", "[", "]", "for", "i", "in", "range", "(", "1", ",", "len", "(", "self", ".", "elements", ")", ",", "2", ")", ":", "output", ".", "append", "(", "self", ".", "elements", "[", "i", "]", ")", "return", "output" ]
Converts the vector to an array of the elements within the vector
[ "Converts", "the", "vector", "to", "an", "array", "of", "the", "elements", "within", "the", "vector" ]
28ec3f6d4888295eed730211ee9617aa488d6ba3
https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/vector.py#L105-L110
train
yeraydiazdiaz/lunr.py
lunr/vector.py
Vector.dot
def dot(self, other): """Calculates the dot product of this vector and another vector.""" dot_product = 0 a = self.elements b = other.elements a_len = len(a) b_len = len(b) i = j = 0 while i < a_len and j < b_len: a_val = a[i] b_val = b[j] if a_val < b_val: i += 2 elif a_val > b_val: j += 2 else: dot_product += a[i + 1] * b[j + 1] i += 2 j += 2 return dot_product
python
def dot(self, other): """Calculates the dot product of this vector and another vector.""" dot_product = 0 a = self.elements b = other.elements a_len = len(a) b_len = len(b) i = j = 0 while i < a_len and j < b_len: a_val = a[i] b_val = b[j] if a_val < b_val: i += 2 elif a_val > b_val: j += 2 else: dot_product += a[i + 1] * b[j + 1] i += 2 j += 2 return dot_product
[ "def", "dot", "(", "self", ",", "other", ")", ":", "dot_product", "=", "0", "a", "=", "self", ".", "elements", "b", "=", "other", ".", "elements", "a_len", "=", "len", "(", "a", ")", "b_len", "=", "len", "(", "b", ")", "i", "=", "j", "=", "0", "while", "i", "<", "a_len", "and", "j", "<", "b_len", ":", "a_val", "=", "a", "[", "i", "]", "b_val", "=", "b", "[", "j", "]", "if", "a_val", "<", "b_val", ":", "i", "+=", "2", "elif", "a_val", ">", "b_val", ":", "j", "+=", "2", "else", ":", "dot_product", "+=", "a", "[", "i", "+", "1", "]", "*", "b", "[", "j", "+", "1", "]", "i", "+=", "2", "j", "+=", "2", "return", "dot_product" ]
Calculates the dot product of this vector and another vector.
[ "Calculates", "the", "dot", "product", "of", "this", "vector", "and", "another", "vector", "." ]
28ec3f6d4888295eed730211ee9617aa488d6ba3
https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/vector.py#L129-L150
train
yeraydiazdiaz/lunr.py
lunr/vector.py
Vector.similarity
def similarity(self, other): """Calculates the cosine similarity between this vector and another vector.""" if self.magnitude == 0 or other.magnitude == 0: return 0 return self.dot(other) / self.magnitude
python
def similarity(self, other): """Calculates the cosine similarity between this vector and another vector.""" if self.magnitude == 0 or other.magnitude == 0: return 0 return self.dot(other) / self.magnitude
[ "def", "similarity", "(", "self", ",", "other", ")", ":", "if", "self", ".", "magnitude", "==", "0", "or", "other", ".", "magnitude", "==", "0", ":", "return", "0", "return", "self", ".", "dot", "(", "other", ")", "/", "self", ".", "magnitude" ]
Calculates the cosine similarity between this vector and another vector.
[ "Calculates", "the", "cosine", "similarity", "between", "this", "vector", "and", "another", "vector", "." ]
28ec3f6d4888295eed730211ee9617aa488d6ba3
https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/vector.py#L152-L158
train
tehmaze/natural
natural/bank.py
bban_base10
def bban_base10(number): ''' Printable Basic Bank Account Number in base-10. :param number: string >>> bban_base10('01234567') '45670123' >>> bban_base10('ABCD') '10111213' ''' number = bban_compact(number) number = number[4:] + number[:4] return ''.join([str(IBAN_ALPHABET.index(char)) for char in number])
python
def bban_base10(number): ''' Printable Basic Bank Account Number in base-10. :param number: string >>> bban_base10('01234567') '45670123' >>> bban_base10('ABCD') '10111213' ''' number = bban_compact(number) number = number[4:] + number[:4] return ''.join([str(IBAN_ALPHABET.index(char)) for char in number])
[ "def", "bban_base10", "(", "number", ")", ":", "number", "=", "bban_compact", "(", "number", ")", "number", "=", "number", "[", "4", ":", "]", "+", "number", "[", ":", "4", "]", "return", "''", ".", "join", "(", "[", "str", "(", "IBAN_ALPHABET", ".", "index", "(", "char", ")", ")", "for", "char", "in", "number", "]", ")" ]
Printable Basic Bank Account Number in base-10. :param number: string >>> bban_base10('01234567') '45670123' >>> bban_base10('ABCD') '10111213'
[ "Printable", "Basic", "Bank", "Account", "Number", "in", "base", "-", "10", "." ]
d7a1fc9de712f9bcf68884a80826a7977df356fb
https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/bank.py#L21-L34
train
jaraco/jaraco.mongodb
jaraco/mongodb/uri.py
_add_scheme
def _add_scheme(): """ urllib.parse doesn't support the mongodb scheme, but it's easy to make it so. """ lists = [ urllib.parse.uses_relative, urllib.parse.uses_netloc, urllib.parse.uses_query, ] for l in lists: l.append('mongodb')
python
def _add_scheme(): """ urllib.parse doesn't support the mongodb scheme, but it's easy to make it so. """ lists = [ urllib.parse.uses_relative, urllib.parse.uses_netloc, urllib.parse.uses_query, ] for l in lists: l.append('mongodb')
[ "def", "_add_scheme", "(", ")", ":", "lists", "=", "[", "urllib", ".", "parse", ".", "uses_relative", ",", "urllib", ".", "parse", ".", "uses_netloc", ",", "urllib", ".", "parse", ".", "uses_query", ",", "]", "for", "l", "in", "lists", ":", "l", ".", "append", "(", "'mongodb'", ")" ]
urllib.parse doesn't support the mongodb scheme, but it's easy to make it so.
[ "urllib", ".", "parse", "doesn", "t", "support", "the", "mongodb", "scheme", "but", "it", "s", "easy", "to", "make", "it", "so", "." ]
280f17894941f4babf2e97db033dbb1fd2b9f705
https://github.com/jaraco/jaraco.mongodb/blob/280f17894941f4babf2e97db033dbb1fd2b9f705/jaraco/mongodb/uri.py#L7-L18
train
yeraydiazdiaz/lunr.py
lunr/builder.py
Builder.field
def field(self, field_name, boost=1, extractor=None): """Adds a field to the list of document fields that will be indexed. Every document being indexed should have this field. None values for this field in indexed documents will not cause errors but will limit the chance of that document being retrieved by searches. All fields should be added before adding documents to the index. Adding fields after a document has been indexed will have no effect on already indexed documents. Fields can be boosted at build time. This allows terms within that field to have more importance on search results. Use a field boost to specify that matches within one field are more important that other fields. Args: field_name (str): Name of the field to be added, must not include a forward slash '/'. boost (int): Optional boost factor to apply to field. extractor (callable): Optional function to extract a field from the document. Raises: ValueError: If the field name contains a `/`. """ if "/" in field_name: raise ValueError("Field {} contains illegal character `/`") self._fields[field_name] = Field(field_name, boost, extractor)
python
def field(self, field_name, boost=1, extractor=None): """Adds a field to the list of document fields that will be indexed. Every document being indexed should have this field. None values for this field in indexed documents will not cause errors but will limit the chance of that document being retrieved by searches. All fields should be added before adding documents to the index. Adding fields after a document has been indexed will have no effect on already indexed documents. Fields can be boosted at build time. This allows terms within that field to have more importance on search results. Use a field boost to specify that matches within one field are more important that other fields. Args: field_name (str): Name of the field to be added, must not include a forward slash '/'. boost (int): Optional boost factor to apply to field. extractor (callable): Optional function to extract a field from the document. Raises: ValueError: If the field name contains a `/`. """ if "/" in field_name: raise ValueError("Field {} contains illegal character `/`") self._fields[field_name] = Field(field_name, boost, extractor)
[ "def", "field", "(", "self", ",", "field_name", ",", "boost", "=", "1", ",", "extractor", "=", "None", ")", ":", "if", "\"/\"", "in", "field_name", ":", "raise", "ValueError", "(", "\"Field {} contains illegal character `/`\"", ")", "self", ".", "_fields", "[", "field_name", "]", "=", "Field", "(", "field_name", ",", "boost", ",", "extractor", ")" ]
Adds a field to the list of document fields that will be indexed. Every document being indexed should have this field. None values for this field in indexed documents will not cause errors but will limit the chance of that document being retrieved by searches. All fields should be added before adding documents to the index. Adding fields after a document has been indexed will have no effect on already indexed documents. Fields can be boosted at build time. This allows terms within that field to have more importance on search results. Use a field boost to specify that matches within one field are more important that other fields. Args: field_name (str): Name of the field to be added, must not include a forward slash '/'. boost (int): Optional boost factor to apply to field. extractor (callable): Optional function to extract a field from the document. Raises: ValueError: If the field name contains a `/`.
[ "Adds", "a", "field", "to", "the", "list", "of", "document", "fields", "that", "will", "be", "indexed", "." ]
28ec3f6d4888295eed730211ee9617aa488d6ba3
https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/builder.py#L69-L98
train
yeraydiazdiaz/lunr.py
lunr/builder.py
Builder.b
def b(self, number): """A parameter to tune the amount of field length normalisation that is applied when calculating relevance scores. A value of 0 will completely disable any normalisation and a value of 1 will fully normalise field lengths. The default is 0.75. Values of b will be clamped to the range 0 - 1. """ if number < 0: self._b = 0 elif number > 1: self._b = 1 else: self._b = number
python
def b(self, number): """A parameter to tune the amount of field length normalisation that is applied when calculating relevance scores. A value of 0 will completely disable any normalisation and a value of 1 will fully normalise field lengths. The default is 0.75. Values of b will be clamped to the range 0 - 1. """ if number < 0: self._b = 0 elif number > 1: self._b = 1 else: self._b = number
[ "def", "b", "(", "self", ",", "number", ")", ":", "if", "number", "<", "0", ":", "self", ".", "_b", "=", "0", "elif", "number", ">", "1", ":", "self", ".", "_b", "=", "1", "else", ":", "self", ".", "_b", "=", "number" ]
A parameter to tune the amount of field length normalisation that is applied when calculating relevance scores. A value of 0 will completely disable any normalisation and a value of 1 will fully normalise field lengths. The default is 0.75. Values of b will be clamped to the range 0 - 1.
[ "A", "parameter", "to", "tune", "the", "amount", "of", "field", "length", "normalisation", "that", "is", "applied", "when", "calculating", "relevance", "scores", "." ]
28ec3f6d4888295eed730211ee9617aa488d6ba3
https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/builder.py#L100-L113
train
yeraydiazdiaz/lunr.py
lunr/builder.py
Builder.add
def add(self, doc, attributes=None): """Adds a document to the index. Before adding documents to the index it should have been fully setup, with the document ref and all fields to index already having been specified. The document must have a field name as specified by the ref (by default this is 'id') and it should have all fields defined for indexing, though None values will not cause errors. Args: - doc (dict): The document to be added to the index. - attributes (dict, optional): A set of attributes corresponding to the document, currently a single `boost` -> int will be taken into account. """ doc_ref = str(doc[self._ref]) self._documents[doc_ref] = attributes or {} self.document_count += 1 for field_name, field in self._fields.items(): extractor = field.extractor field_value = doc[field_name] if extractor is None else extractor(doc) tokens = Tokenizer(field_value) terms = self.pipeline.run(tokens) field_ref = FieldRef(doc_ref, field_name) field_terms = defaultdict(int) # TODO: field_refs are casted to strings in JS, should we allow # FieldRef as keys? self.field_term_frequencies[str(field_ref)] = field_terms self.field_lengths[str(field_ref)] = len(terms) for term in terms: # TODO: term is a Token, should we allow Tokens as keys? term_key = str(term) field_terms[term_key] += 1 if term_key not in self.inverted_index: posting = {_field_name: {} for _field_name in self._fields} posting["_index"] = self.term_index self.term_index += 1 self.inverted_index[term_key] = posting if doc_ref not in self.inverted_index[term_key][field_name]: self.inverted_index[term_key][field_name][doc_ref] = defaultdict( list ) for metadata_key in self.metadata_whitelist: metadata = term.metadata[metadata_key] self.inverted_index[term_key][field_name][doc_ref][ metadata_key ].append(metadata)
python
def add(self, doc, attributes=None): """Adds a document to the index. Before adding documents to the index it should have been fully setup, with the document ref and all fields to index already having been specified. The document must have a field name as specified by the ref (by default this is 'id') and it should have all fields defined for indexing, though None values will not cause errors. Args: - doc (dict): The document to be added to the index. - attributes (dict, optional): A set of attributes corresponding to the document, currently a single `boost` -> int will be taken into account. """ doc_ref = str(doc[self._ref]) self._documents[doc_ref] = attributes or {} self.document_count += 1 for field_name, field in self._fields.items(): extractor = field.extractor field_value = doc[field_name] if extractor is None else extractor(doc) tokens = Tokenizer(field_value) terms = self.pipeline.run(tokens) field_ref = FieldRef(doc_ref, field_name) field_terms = defaultdict(int) # TODO: field_refs are casted to strings in JS, should we allow # FieldRef as keys? self.field_term_frequencies[str(field_ref)] = field_terms self.field_lengths[str(field_ref)] = len(terms) for term in terms: # TODO: term is a Token, should we allow Tokens as keys? term_key = str(term) field_terms[term_key] += 1 if term_key not in self.inverted_index: posting = {_field_name: {} for _field_name in self._fields} posting["_index"] = self.term_index self.term_index += 1 self.inverted_index[term_key] = posting if doc_ref not in self.inverted_index[term_key][field_name]: self.inverted_index[term_key][field_name][doc_ref] = defaultdict( list ) for metadata_key in self.metadata_whitelist: metadata = term.metadata[metadata_key] self.inverted_index[term_key][field_name][doc_ref][ metadata_key ].append(metadata)
[ "def", "add", "(", "self", ",", "doc", ",", "attributes", "=", "None", ")", ":", "doc_ref", "=", "str", "(", "doc", "[", "self", ".", "_ref", "]", ")", "self", ".", "_documents", "[", "doc_ref", "]", "=", "attributes", "or", "{", "}", "self", ".", "document_count", "+=", "1", "for", "field_name", ",", "field", "in", "self", ".", "_fields", ".", "items", "(", ")", ":", "extractor", "=", "field", ".", "extractor", "field_value", "=", "doc", "[", "field_name", "]", "if", "extractor", "is", "None", "else", "extractor", "(", "doc", ")", "tokens", "=", "Tokenizer", "(", "field_value", ")", "terms", "=", "self", ".", "pipeline", ".", "run", "(", "tokens", ")", "field_ref", "=", "FieldRef", "(", "doc_ref", ",", "field_name", ")", "field_terms", "=", "defaultdict", "(", "int", ")", "# TODO: field_refs are casted to strings in JS, should we allow", "# FieldRef as keys?", "self", ".", "field_term_frequencies", "[", "str", "(", "field_ref", ")", "]", "=", "field_terms", "self", ".", "field_lengths", "[", "str", "(", "field_ref", ")", "]", "=", "len", "(", "terms", ")", "for", "term", "in", "terms", ":", "# TODO: term is a Token, should we allow Tokens as keys?", "term_key", "=", "str", "(", "term", ")", "field_terms", "[", "term_key", "]", "+=", "1", "if", "term_key", "not", "in", "self", ".", "inverted_index", ":", "posting", "=", "{", "_field_name", ":", "{", "}", "for", "_field_name", "in", "self", ".", "_fields", "}", "posting", "[", "\"_index\"", "]", "=", "self", ".", "term_index", "self", ".", "term_index", "+=", "1", "self", ".", "inverted_index", "[", "term_key", "]", "=", "posting", "if", "doc_ref", "not", "in", "self", ".", "inverted_index", "[", "term_key", "]", "[", "field_name", "]", ":", "self", ".", "inverted_index", "[", "term_key", "]", "[", "field_name", "]", "[", "doc_ref", "]", "=", "defaultdict", "(", "list", ")", "for", "metadata_key", "in", "self", ".", "metadata_whitelist", ":", "metadata", "=", "term", ".", "metadata", "[", "metadata_key", "]", "self", ".", "inverted_index", "[", "term_key", "]", "[", "field_name", "]", "[", "doc_ref", "]", "[", "metadata_key", "]", ".", "append", "(", "metadata", ")" ]
Adds a document to the index. Before adding documents to the index it should have been fully setup, with the document ref and all fields to index already having been specified. The document must have a field name as specified by the ref (by default this is 'id') and it should have all fields defined for indexing, though None values will not cause errors. Args: - doc (dict): The document to be added to the index. - attributes (dict, optional): A set of attributes corresponding to the document, currently a single `boost` -> int will be taken into account.
[ "Adds", "a", "document", "to", "the", "index", "." ]
28ec3f6d4888295eed730211ee9617aa488d6ba3
https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/builder.py#L125-L179
train
yeraydiazdiaz/lunr.py
lunr/builder.py
Builder.build
def build(self): """Builds the index, creating an instance of `lunr.Index`. This completes the indexing process and should only be called once all documents have been added to the index. """ self._calculate_average_field_lengths() self._create_field_vectors() self._create_token_set() return Index( inverted_index=self.inverted_index, field_vectors=self.field_vectors, token_set=self.token_set, fields=list(self._fields.keys()), pipeline=self.search_pipeline, )
python
def build(self): """Builds the index, creating an instance of `lunr.Index`. This completes the indexing process and should only be called once all documents have been added to the index. """ self._calculate_average_field_lengths() self._create_field_vectors() self._create_token_set() return Index( inverted_index=self.inverted_index, field_vectors=self.field_vectors, token_set=self.token_set, fields=list(self._fields.keys()), pipeline=self.search_pipeline, )
[ "def", "build", "(", "self", ")", ":", "self", ".", "_calculate_average_field_lengths", "(", ")", "self", ".", "_create_field_vectors", "(", ")", "self", ".", "_create_token_set", "(", ")", "return", "Index", "(", "inverted_index", "=", "self", ".", "inverted_index", ",", "field_vectors", "=", "self", ".", "field_vectors", ",", "token_set", "=", "self", ".", "token_set", ",", "fields", "=", "list", "(", "self", ".", "_fields", ".", "keys", "(", ")", ")", ",", "pipeline", "=", "self", ".", "search_pipeline", ",", ")" ]
Builds the index, creating an instance of `lunr.Index`. This completes the indexing process and should only be called once all documents have been added to the index.
[ "Builds", "the", "index", "creating", "an", "instance", "of", "lunr", ".", "Index", "." ]
28ec3f6d4888295eed730211ee9617aa488d6ba3
https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/builder.py#L181-L197
train
yeraydiazdiaz/lunr.py
lunr/builder.py
Builder._create_token_set
def _create_token_set(self): """Creates a token set of all tokens in the index using `lunr.TokenSet` """ self.token_set = TokenSet.from_list(sorted(list(self.inverted_index.keys())))
python
def _create_token_set(self): """Creates a token set of all tokens in the index using `lunr.TokenSet` """ self.token_set = TokenSet.from_list(sorted(list(self.inverted_index.keys())))
[ "def", "_create_token_set", "(", "self", ")", ":", "self", ".", "token_set", "=", "TokenSet", ".", "from_list", "(", "sorted", "(", "list", "(", "self", ".", "inverted_index", ".", "keys", "(", ")", ")", ")", ")" ]
Creates a token set of all tokens in the index using `lunr.TokenSet`
[ "Creates", "a", "token", "set", "of", "all", "tokens", "in", "the", "index", "using", "lunr", ".", "TokenSet" ]
28ec3f6d4888295eed730211ee9617aa488d6ba3
https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/builder.py#L199-L202
train
yeraydiazdiaz/lunr.py
lunr/builder.py
Builder._calculate_average_field_lengths
def _calculate_average_field_lengths(self): """Calculates the average document length for this index""" accumulator = defaultdict(int) documents_with_field = defaultdict(int) for field_ref, length in self.field_lengths.items(): _field_ref = FieldRef.from_string(field_ref) field = _field_ref.field_name documents_with_field[field] += 1 accumulator[field] += length for field_name in self._fields: accumulator[field_name] /= documents_with_field[field_name] self.average_field_length = accumulator
python
def _calculate_average_field_lengths(self): """Calculates the average document length for this index""" accumulator = defaultdict(int) documents_with_field = defaultdict(int) for field_ref, length in self.field_lengths.items(): _field_ref = FieldRef.from_string(field_ref) field = _field_ref.field_name documents_with_field[field] += 1 accumulator[field] += length for field_name in self._fields: accumulator[field_name] /= documents_with_field[field_name] self.average_field_length = accumulator
[ "def", "_calculate_average_field_lengths", "(", "self", ")", ":", "accumulator", "=", "defaultdict", "(", "int", ")", "documents_with_field", "=", "defaultdict", "(", "int", ")", "for", "field_ref", ",", "length", "in", "self", ".", "field_lengths", ".", "items", "(", ")", ":", "_field_ref", "=", "FieldRef", ".", "from_string", "(", "field_ref", ")", "field", "=", "_field_ref", ".", "field_name", "documents_with_field", "[", "field", "]", "+=", "1", "accumulator", "[", "field", "]", "+=", "length", "for", "field_name", "in", "self", ".", "_fields", ":", "accumulator", "[", "field_name", "]", "/=", "documents_with_field", "[", "field_name", "]", "self", ".", "average_field_length", "=", "accumulator" ]
Calculates the average document length for this index
[ "Calculates", "the", "average", "document", "length", "for", "this", "index" ]
28ec3f6d4888295eed730211ee9617aa488d6ba3
https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/builder.py#L204-L219
train
yeraydiazdiaz/lunr.py
lunr/builder.py
Builder._create_field_vectors
def _create_field_vectors(self): """Builds a vector space model of every document using lunr.Vector.""" field_vectors = {} term_idf_cache = {} for field_ref, term_frequencies in self.field_term_frequencies.items(): _field_ref = FieldRef.from_string(field_ref) field_name = _field_ref.field_name field_length = self.field_lengths[field_ref] field_vector = Vector() field_boost = self._fields[field_name].boost doc_boost = self._documents[_field_ref.doc_ref].get("boost", 1) for term, tf in term_frequencies.items(): term_index = self.inverted_index[term]["_index"] if term not in term_idf_cache: idf = Idf(self.inverted_index[term], self.document_count) term_idf_cache[term] = idf else: idf = term_idf_cache[term] score = ( idf * ((self._k1 + 1) * tf) / ( self._k1 * ( 1 - self._b + self._b * (field_length / self.average_field_length[field_name]) ) + tf ) ) score *= field_boost score *= doc_boost score_with_precision = round(score, 3) field_vector.insert(term_index, score_with_precision) field_vectors[field_ref] = field_vector self.field_vectors = field_vectors
python
def _create_field_vectors(self): """Builds a vector space model of every document using lunr.Vector.""" field_vectors = {} term_idf_cache = {} for field_ref, term_frequencies in self.field_term_frequencies.items(): _field_ref = FieldRef.from_string(field_ref) field_name = _field_ref.field_name field_length = self.field_lengths[field_ref] field_vector = Vector() field_boost = self._fields[field_name].boost doc_boost = self._documents[_field_ref.doc_ref].get("boost", 1) for term, tf in term_frequencies.items(): term_index = self.inverted_index[term]["_index"] if term not in term_idf_cache: idf = Idf(self.inverted_index[term], self.document_count) term_idf_cache[term] = idf else: idf = term_idf_cache[term] score = ( idf * ((self._k1 + 1) * tf) / ( self._k1 * ( 1 - self._b + self._b * (field_length / self.average_field_length[field_name]) ) + tf ) ) score *= field_boost score *= doc_boost score_with_precision = round(score, 3) field_vector.insert(term_index, score_with_precision) field_vectors[field_ref] = field_vector self.field_vectors = field_vectors
[ "def", "_create_field_vectors", "(", "self", ")", ":", "field_vectors", "=", "{", "}", "term_idf_cache", "=", "{", "}", "for", "field_ref", ",", "term_frequencies", "in", "self", ".", "field_term_frequencies", ".", "items", "(", ")", ":", "_field_ref", "=", "FieldRef", ".", "from_string", "(", "field_ref", ")", "field_name", "=", "_field_ref", ".", "field_name", "field_length", "=", "self", ".", "field_lengths", "[", "field_ref", "]", "field_vector", "=", "Vector", "(", ")", "field_boost", "=", "self", ".", "_fields", "[", "field_name", "]", ".", "boost", "doc_boost", "=", "self", ".", "_documents", "[", "_field_ref", ".", "doc_ref", "]", ".", "get", "(", "\"boost\"", ",", "1", ")", "for", "term", ",", "tf", "in", "term_frequencies", ".", "items", "(", ")", ":", "term_index", "=", "self", ".", "inverted_index", "[", "term", "]", "[", "\"_index\"", "]", "if", "term", "not", "in", "term_idf_cache", ":", "idf", "=", "Idf", "(", "self", ".", "inverted_index", "[", "term", "]", ",", "self", ".", "document_count", ")", "term_idf_cache", "[", "term", "]", "=", "idf", "else", ":", "idf", "=", "term_idf_cache", "[", "term", "]", "score", "=", "(", "idf", "*", "(", "(", "self", ".", "_k1", "+", "1", ")", "*", "tf", ")", "/", "(", "self", ".", "_k1", "*", "(", "1", "-", "self", ".", "_b", "+", "self", ".", "_b", "*", "(", "field_length", "/", "self", ".", "average_field_length", "[", "field_name", "]", ")", ")", "+", "tf", ")", ")", "score", "*=", "field_boost", "score", "*=", "doc_boost", "score_with_precision", "=", "round", "(", "score", ",", "3", ")", "field_vector", ".", "insert", "(", "term_index", ",", "score_with_precision", ")", "field_vectors", "[", "field_ref", "]", "=", "field_vector", "self", ".", "field_vectors", "=", "field_vectors" ]
Builds a vector space model of every document using lunr.Vector.
[ "Builds", "a", "vector", "space", "model", "of", "every", "document", "using", "lunr", ".", "Vector", "." ]
28ec3f6d4888295eed730211ee9617aa488d6ba3
https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/builder.py#L221-L265
train
jaraco/jaraco.mongodb
jaraco/mongodb/sampling.py
estimate
def estimate(coll, filter={}, sample=1): """ Estimate the number of documents in the collection matching the filter. Sample may be a fixed number of documents to sample or a percentage of the total collection size. >>> coll = getfixture('bulky_collection') >>> estimate(coll) 100 >>> query = {"val": {"$gte": 50}} >>> val = estimate(coll, filter=query) >>> val > 0 True >>> val = estimate(coll, filter=query, sample=10) >>> val > 0 True >>> val = estimate(coll, filter=query, sample=.1) >>> val > 0 True """ total = coll.estimated_document_count() if not filter and sample == 1: return total if sample <= 1: sample *= total pipeline = list(builtins.filter(None, [ {'$sample': {'size': sample}} if sample < total else {}, {'$match': filter}, {'$count': 'matched'}, ])) docs = next(coll.aggregate(pipeline)) ratio = docs['matched'] / sample return int(total * ratio)
python
def estimate(coll, filter={}, sample=1): """ Estimate the number of documents in the collection matching the filter. Sample may be a fixed number of documents to sample or a percentage of the total collection size. >>> coll = getfixture('bulky_collection') >>> estimate(coll) 100 >>> query = {"val": {"$gte": 50}} >>> val = estimate(coll, filter=query) >>> val > 0 True >>> val = estimate(coll, filter=query, sample=10) >>> val > 0 True >>> val = estimate(coll, filter=query, sample=.1) >>> val > 0 True """ total = coll.estimated_document_count() if not filter and sample == 1: return total if sample <= 1: sample *= total pipeline = list(builtins.filter(None, [ {'$sample': {'size': sample}} if sample < total else {}, {'$match': filter}, {'$count': 'matched'}, ])) docs = next(coll.aggregate(pipeline)) ratio = docs['matched'] / sample return int(total * ratio)
[ "def", "estimate", "(", "coll", ",", "filter", "=", "{", "}", ",", "sample", "=", "1", ")", ":", "total", "=", "coll", ".", "estimated_document_count", "(", ")", "if", "not", "filter", "and", "sample", "==", "1", ":", "return", "total", "if", "sample", "<=", "1", ":", "sample", "*=", "total", "pipeline", "=", "list", "(", "builtins", ".", "filter", "(", "None", ",", "[", "{", "'$sample'", ":", "{", "'size'", ":", "sample", "}", "}", "if", "sample", "<", "total", "else", "{", "}", ",", "{", "'$match'", ":", "filter", "}", ",", "{", "'$count'", ":", "'matched'", "}", ",", "]", ")", ")", "docs", "=", "next", "(", "coll", ".", "aggregate", "(", "pipeline", ")", ")", "ratio", "=", "docs", "[", "'matched'", "]", "/", "sample", "return", "int", "(", "total", "*", "ratio", ")" ]
Estimate the number of documents in the collection matching the filter. Sample may be a fixed number of documents to sample or a percentage of the total collection size. >>> coll = getfixture('bulky_collection') >>> estimate(coll) 100 >>> query = {"val": {"$gte": 50}} >>> val = estimate(coll, filter=query) >>> val > 0 True >>> val = estimate(coll, filter=query, sample=10) >>> val > 0 True >>> val = estimate(coll, filter=query, sample=.1) >>> val > 0 True
[ "Estimate", "the", "number", "of", "documents", "in", "the", "collection", "matching", "the", "filter", "." ]
280f17894941f4babf2e97db033dbb1fd2b9f705
https://github.com/jaraco/jaraco.mongodb/blob/280f17894941f4babf2e97db033dbb1fd2b9f705/jaraco/mongodb/sampling.py#L6-L40
train
kevin-brown/drf-json-api
rest_framework_json_api/renderers.py
JsonApiMixin.render
def render(self, data, accepted_media_type=None, renderer_context=None): """Convert native data to JSON API Tries each of the methods in `wrappers`, using the first successful one, or raises `WrapperNotApplicable`. """ wrapper = None success = False for wrapper_name in self.wrappers: wrapper_method = getattr(self, wrapper_name) try: wrapper = wrapper_method(data, renderer_context) except WrapperNotApplicable: pass else: success = True break if not success: raise WrapperNotApplicable( 'No acceptable wrappers found for response.', data=data, renderer_context=renderer_context) renderer_context["indent"] = 4 return super(JsonApiMixin, self).render( data=wrapper, accepted_media_type=accepted_media_type, renderer_context=renderer_context)
python
def render(self, data, accepted_media_type=None, renderer_context=None): """Convert native data to JSON API Tries each of the methods in `wrappers`, using the first successful one, or raises `WrapperNotApplicable`. """ wrapper = None success = False for wrapper_name in self.wrappers: wrapper_method = getattr(self, wrapper_name) try: wrapper = wrapper_method(data, renderer_context) except WrapperNotApplicable: pass else: success = True break if not success: raise WrapperNotApplicable( 'No acceptable wrappers found for response.', data=data, renderer_context=renderer_context) renderer_context["indent"] = 4 return super(JsonApiMixin, self).render( data=wrapper, accepted_media_type=accepted_media_type, renderer_context=renderer_context)
[ "def", "render", "(", "self", ",", "data", ",", "accepted_media_type", "=", "None", ",", "renderer_context", "=", "None", ")", ":", "wrapper", "=", "None", "success", "=", "False", "for", "wrapper_name", "in", "self", ".", "wrappers", ":", "wrapper_method", "=", "getattr", "(", "self", ",", "wrapper_name", ")", "try", ":", "wrapper", "=", "wrapper_method", "(", "data", ",", "renderer_context", ")", "except", "WrapperNotApplicable", ":", "pass", "else", ":", "success", "=", "True", "break", "if", "not", "success", ":", "raise", "WrapperNotApplicable", "(", "'No acceptable wrappers found for response.'", ",", "data", "=", "data", ",", "renderer_context", "=", "renderer_context", ")", "renderer_context", "[", "\"indent\"", "]", "=", "4", "return", "super", "(", "JsonApiMixin", ",", "self", ")", ".", "render", "(", "data", "=", "wrapper", ",", "accepted_media_type", "=", "accepted_media_type", ",", "renderer_context", "=", "renderer_context", ")" ]
Convert native data to JSON API Tries each of the methods in `wrappers`, using the first successful one, or raises `WrapperNotApplicable`.
[ "Convert", "native", "data", "to", "JSON", "API" ]
664643bd02c0d92eadbd1f8c9d8507adf0538df6
https://github.com/kevin-brown/drf-json-api/blob/664643bd02c0d92eadbd1f8c9d8507adf0538df6/rest_framework_json_api/renderers.py#L47-L77
train
kevin-brown/drf-json-api
rest_framework_json_api/renderers.py
JsonApiMixin.wrap_parser_error
def wrap_parser_error(self, data, renderer_context): """ Convert parser errors to the JSON API Error format Parser errors have a status code of 400, like field errors, but have the same native format as generic errors. Also, the detail message is often specific to the input, so the error is listed as a 'detail' rather than a 'title'. """ response = renderer_context.get("response", None) status_code = response and response.status_code if status_code != 400: raise WrapperNotApplicable('Status code must be 400.') if list(data.keys()) != ['detail']: raise WrapperNotApplicable('Data must only have "detail" key.') # Probably a parser error, unless `detail` is a valid field view = renderer_context.get("view", None) model = self.model_from_obj(view) if 'detail' in model._meta.get_all_field_names(): raise WrapperNotApplicable() return self.wrap_error( data, renderer_context, keys_are_fields=False, issue_is_title=False)
python
def wrap_parser_error(self, data, renderer_context): """ Convert parser errors to the JSON API Error format Parser errors have a status code of 400, like field errors, but have the same native format as generic errors. Also, the detail message is often specific to the input, so the error is listed as a 'detail' rather than a 'title'. """ response = renderer_context.get("response", None) status_code = response and response.status_code if status_code != 400: raise WrapperNotApplicable('Status code must be 400.') if list(data.keys()) != ['detail']: raise WrapperNotApplicable('Data must only have "detail" key.') # Probably a parser error, unless `detail` is a valid field view = renderer_context.get("view", None) model = self.model_from_obj(view) if 'detail' in model._meta.get_all_field_names(): raise WrapperNotApplicable() return self.wrap_error( data, renderer_context, keys_are_fields=False, issue_is_title=False)
[ "def", "wrap_parser_error", "(", "self", ",", "data", ",", "renderer_context", ")", ":", "response", "=", "renderer_context", ".", "get", "(", "\"response\"", ",", "None", ")", "status_code", "=", "response", "and", "response", ".", "status_code", "if", "status_code", "!=", "400", ":", "raise", "WrapperNotApplicable", "(", "'Status code must be 400.'", ")", "if", "list", "(", "data", ".", "keys", "(", ")", ")", "!=", "[", "'detail'", "]", ":", "raise", "WrapperNotApplicable", "(", "'Data must only have \"detail\" key.'", ")", "# Probably a parser error, unless `detail` is a valid field", "view", "=", "renderer_context", ".", "get", "(", "\"view\"", ",", "None", ")", "model", "=", "self", ".", "model_from_obj", "(", "view", ")", "if", "'detail'", "in", "model", ".", "_meta", ".", "get_all_field_names", "(", ")", ":", "raise", "WrapperNotApplicable", "(", ")", "return", "self", ".", "wrap_error", "(", "data", ",", "renderer_context", ",", "keys_are_fields", "=", "False", ",", "issue_is_title", "=", "False", ")" ]
Convert parser errors to the JSON API Error format Parser errors have a status code of 400, like field errors, but have the same native format as generic errors. Also, the detail message is often specific to the input, so the error is listed as a 'detail' rather than a 'title'.
[ "Convert", "parser", "errors", "to", "the", "JSON", "API", "Error", "format" ]
664643bd02c0d92eadbd1f8c9d8507adf0538df6
https://github.com/kevin-brown/drf-json-api/blob/664643bd02c0d92eadbd1f8c9d8507adf0538df6/rest_framework_json_api/renderers.py#L91-L119
train
kevin-brown/drf-json-api
rest_framework_json_api/renderers.py
JsonApiMixin.wrap_field_error
def wrap_field_error(self, data, renderer_context): """ Convert field error native data to the JSON API Error format See the note about the JSON API Error format on `wrap_error`. The native format for field errors is a dictionary where the keys are field names (or 'non_field_errors' for additional errors) and the values are a list of error strings: { "min": [ "min must be greater than 0.", "min must be an even number." ], "max": ["max must be a positive number."], "non_field_errors": [ "Select either a range or an enumeration, not both."] } It is rendered into this JSON API error format: { "errors": [{ "status": "400", "path": "/min", "detail": "min must be greater than 0." },{ "status": "400", "path": "/min", "detail": "min must be an even number." },{ "status": "400", "path": "/max", "detail": "max must be a positive number." },{ "status": "400", "path": "/-", "detail": "Select either a range or an enumeration, not both." }] } """ response = renderer_context.get("response", None) status_code = response and response.status_code if status_code != 400: raise WrapperNotApplicable('Status code must be 400.') return self.wrap_error( data, renderer_context, keys_are_fields=True, issue_is_title=False)
python
def wrap_field_error(self, data, renderer_context): """ Convert field error native data to the JSON API Error format See the note about the JSON API Error format on `wrap_error`. The native format for field errors is a dictionary where the keys are field names (or 'non_field_errors' for additional errors) and the values are a list of error strings: { "min": [ "min must be greater than 0.", "min must be an even number." ], "max": ["max must be a positive number."], "non_field_errors": [ "Select either a range or an enumeration, not both."] } It is rendered into this JSON API error format: { "errors": [{ "status": "400", "path": "/min", "detail": "min must be greater than 0." },{ "status": "400", "path": "/min", "detail": "min must be an even number." },{ "status": "400", "path": "/max", "detail": "max must be a positive number." },{ "status": "400", "path": "/-", "detail": "Select either a range or an enumeration, not both." }] } """ response = renderer_context.get("response", None) status_code = response and response.status_code if status_code != 400: raise WrapperNotApplicable('Status code must be 400.') return self.wrap_error( data, renderer_context, keys_are_fields=True, issue_is_title=False)
[ "def", "wrap_field_error", "(", "self", ",", "data", ",", "renderer_context", ")", ":", "response", "=", "renderer_context", ".", "get", "(", "\"response\"", ",", "None", ")", "status_code", "=", "response", "and", "response", ".", "status_code", "if", "status_code", "!=", "400", ":", "raise", "WrapperNotApplicable", "(", "'Status code must be 400.'", ")", "return", "self", ".", "wrap_error", "(", "data", ",", "renderer_context", ",", "keys_are_fields", "=", "True", ",", "issue_is_title", "=", "False", ")" ]
Convert field error native data to the JSON API Error format See the note about the JSON API Error format on `wrap_error`. The native format for field errors is a dictionary where the keys are field names (or 'non_field_errors' for additional errors) and the values are a list of error strings: { "min": [ "min must be greater than 0.", "min must be an even number." ], "max": ["max must be a positive number."], "non_field_errors": [ "Select either a range or an enumeration, not both."] } It is rendered into this JSON API error format: { "errors": [{ "status": "400", "path": "/min", "detail": "min must be greater than 0." },{ "status": "400", "path": "/min", "detail": "min must be an even number." },{ "status": "400", "path": "/max", "detail": "max must be a positive number." },{ "status": "400", "path": "/-", "detail": "Select either a range or an enumeration, not both." }] }
[ "Convert", "field", "error", "native", "data", "to", "the", "JSON", "API", "Error", "format" ]
664643bd02c0d92eadbd1f8c9d8507adf0538df6
https://github.com/kevin-brown/drf-json-api/blob/664643bd02c0d92eadbd1f8c9d8507adf0538df6/rest_framework_json_api/renderers.py#L121-L169
train
kevin-brown/drf-json-api
rest_framework_json_api/renderers.py
JsonApiMixin.wrap_generic_error
def wrap_generic_error(self, data, renderer_context): """ Convert generic error native data using the JSON API Error format See the note about the JSON API Error format on `wrap_error`. The native format for errors that are not bad requests, such as authentication issues or missing content, is a dictionary with a 'detail' key and a string value: { "detail": "Authentication credentials were not provided." } This is rendered into this JSON API error format: { "errors": [{ "status": "403", "title": "Authentication credentials were not provided" }] } """ response = renderer_context.get("response", None) status_code = response and response.status_code is_error = ( status.is_client_error(status_code) or status.is_server_error(status_code) ) if not is_error: raise WrapperNotApplicable("Status code must be 4xx or 5xx.") return self.wrap_error( data, renderer_context, keys_are_fields=False, issue_is_title=True)
python
def wrap_generic_error(self, data, renderer_context): """ Convert generic error native data using the JSON API Error format See the note about the JSON API Error format on `wrap_error`. The native format for errors that are not bad requests, such as authentication issues or missing content, is a dictionary with a 'detail' key and a string value: { "detail": "Authentication credentials were not provided." } This is rendered into this JSON API error format: { "errors": [{ "status": "403", "title": "Authentication credentials were not provided" }] } """ response = renderer_context.get("response", None) status_code = response and response.status_code is_error = ( status.is_client_error(status_code) or status.is_server_error(status_code) ) if not is_error: raise WrapperNotApplicable("Status code must be 4xx or 5xx.") return self.wrap_error( data, renderer_context, keys_are_fields=False, issue_is_title=True)
[ "def", "wrap_generic_error", "(", "self", ",", "data", ",", "renderer_context", ")", ":", "response", "=", "renderer_context", ".", "get", "(", "\"response\"", ",", "None", ")", "status_code", "=", "response", "and", "response", ".", "status_code", "is_error", "=", "(", "status", ".", "is_client_error", "(", "status_code", ")", "or", "status", ".", "is_server_error", "(", "status_code", ")", ")", "if", "not", "is_error", ":", "raise", "WrapperNotApplicable", "(", "\"Status code must be 4xx or 5xx.\"", ")", "return", "self", ".", "wrap_error", "(", "data", ",", "renderer_context", ",", "keys_are_fields", "=", "False", ",", "issue_is_title", "=", "True", ")" ]
Convert generic error native data using the JSON API Error format See the note about the JSON API Error format on `wrap_error`. The native format for errors that are not bad requests, such as authentication issues or missing content, is a dictionary with a 'detail' key and a string value: { "detail": "Authentication credentials were not provided." } This is rendered into this JSON API error format: { "errors": [{ "status": "403", "title": "Authentication credentials were not provided" }] }
[ "Convert", "generic", "error", "native", "data", "using", "the", "JSON", "API", "Error", "format" ]
664643bd02c0d92eadbd1f8c9d8507adf0538df6
https://github.com/kevin-brown/drf-json-api/blob/664643bd02c0d92eadbd1f8c9d8507adf0538df6/rest_framework_json_api/renderers.py#L171-L204
train
kevin-brown/drf-json-api
rest_framework_json_api/renderers.py
JsonApiMixin.wrap_error
def wrap_error( self, data, renderer_context, keys_are_fields, issue_is_title): """Convert error native data to the JSON API Error format JSON API has a different format for errors, but Django REST Framework doesn't have a separate rendering path for errors. This results in some guesswork to determine if data is an error, what kind, and how to handle it. As of August 2014, there is not a consensus about the error format in JSON API. The format documentation defines an "errors" collection, and some possible fields for that collection, but without examples for common cases. If and when consensus is reached, this format will probably change. """ response = renderer_context.get("response", None) status_code = str(response and response.status_code) errors = [] for field, issues in data.items(): if isinstance(issues, six.string_types): issues = [issues] for issue in issues: error = self.dict_class() error["status"] = status_code if issue_is_title: error["title"] = issue else: error["detail"] = issue if keys_are_fields: if field in ('non_field_errors', NON_FIELD_ERRORS): error["path"] = '/-' else: error["path"] = '/' + field errors.append(error) wrapper = self.dict_class() wrapper["errors"] = errors return wrapper
python
def wrap_error( self, data, renderer_context, keys_are_fields, issue_is_title): """Convert error native data to the JSON API Error format JSON API has a different format for errors, but Django REST Framework doesn't have a separate rendering path for errors. This results in some guesswork to determine if data is an error, what kind, and how to handle it. As of August 2014, there is not a consensus about the error format in JSON API. The format documentation defines an "errors" collection, and some possible fields for that collection, but without examples for common cases. If and when consensus is reached, this format will probably change. """ response = renderer_context.get("response", None) status_code = str(response and response.status_code) errors = [] for field, issues in data.items(): if isinstance(issues, six.string_types): issues = [issues] for issue in issues: error = self.dict_class() error["status"] = status_code if issue_is_title: error["title"] = issue else: error["detail"] = issue if keys_are_fields: if field in ('non_field_errors', NON_FIELD_ERRORS): error["path"] = '/-' else: error["path"] = '/' + field errors.append(error) wrapper = self.dict_class() wrapper["errors"] = errors return wrapper
[ "def", "wrap_error", "(", "self", ",", "data", ",", "renderer_context", ",", "keys_are_fields", ",", "issue_is_title", ")", ":", "response", "=", "renderer_context", ".", "get", "(", "\"response\"", ",", "None", ")", "status_code", "=", "str", "(", "response", "and", "response", ".", "status_code", ")", "errors", "=", "[", "]", "for", "field", ",", "issues", "in", "data", ".", "items", "(", ")", ":", "if", "isinstance", "(", "issues", ",", "six", ".", "string_types", ")", ":", "issues", "=", "[", "issues", "]", "for", "issue", "in", "issues", ":", "error", "=", "self", ".", "dict_class", "(", ")", "error", "[", "\"status\"", "]", "=", "status_code", "if", "issue_is_title", ":", "error", "[", "\"title\"", "]", "=", "issue", "else", ":", "error", "[", "\"detail\"", "]", "=", "issue", "if", "keys_are_fields", ":", "if", "field", "in", "(", "'non_field_errors'", ",", "NON_FIELD_ERRORS", ")", ":", "error", "[", "\"path\"", "]", "=", "'/-'", "else", ":", "error", "[", "\"path\"", "]", "=", "'/'", "+", "field", "errors", ".", "append", "(", "error", ")", "wrapper", "=", "self", ".", "dict_class", "(", ")", "wrapper", "[", "\"errors\"", "]", "=", "errors", "return", "wrapper" ]
Convert error native data to the JSON API Error format JSON API has a different format for errors, but Django REST Framework doesn't have a separate rendering path for errors. This results in some guesswork to determine if data is an error, what kind, and how to handle it. As of August 2014, there is not a consensus about the error format in JSON API. The format documentation defines an "errors" collection, and some possible fields for that collection, but without examples for common cases. If and when consensus is reached, this format will probably change.
[ "Convert", "error", "native", "data", "to", "the", "JSON", "API", "Error", "format" ]
664643bd02c0d92eadbd1f8c9d8507adf0538df6
https://github.com/kevin-brown/drf-json-api/blob/664643bd02c0d92eadbd1f8c9d8507adf0538df6/rest_framework_json_api/renderers.py#L206-L247
train
kevin-brown/drf-json-api
rest_framework_json_api/renderers.py
JsonApiMixin.wrap_options
def wrap_options(self, data, renderer_context): '''Wrap OPTIONS data as JSON API meta value''' request = renderer_context.get("request", None) method = request and getattr(request, 'method') if method != 'OPTIONS': raise WrapperNotApplicable("Request method must be OPTIONS") wrapper = self.dict_class() wrapper["meta"] = data return wrapper
python
def wrap_options(self, data, renderer_context): '''Wrap OPTIONS data as JSON API meta value''' request = renderer_context.get("request", None) method = request and getattr(request, 'method') if method != 'OPTIONS': raise WrapperNotApplicable("Request method must be OPTIONS") wrapper = self.dict_class() wrapper["meta"] = data return wrapper
[ "def", "wrap_options", "(", "self", ",", "data", ",", "renderer_context", ")", ":", "request", "=", "renderer_context", ".", "get", "(", "\"request\"", ",", "None", ")", "method", "=", "request", "and", "getattr", "(", "request", ",", "'method'", ")", "if", "method", "!=", "'OPTIONS'", ":", "raise", "WrapperNotApplicable", "(", "\"Request method must be OPTIONS\"", ")", "wrapper", "=", "self", ".", "dict_class", "(", ")", "wrapper", "[", "\"meta\"", "]", "=", "data", "return", "wrapper" ]
Wrap OPTIONS data as JSON API meta value
[ "Wrap", "OPTIONS", "data", "as", "JSON", "API", "meta", "value" ]
664643bd02c0d92eadbd1f8c9d8507adf0538df6
https://github.com/kevin-brown/drf-json-api/blob/664643bd02c0d92eadbd1f8c9d8507adf0538df6/rest_framework_json_api/renderers.py#L249-L258
train
kevin-brown/drf-json-api
rest_framework_json_api/renderers.py
JsonApiMixin.wrap_paginated
def wrap_paginated(self, data, renderer_context): """Convert paginated data to JSON API with meta""" pagination_keys = ['count', 'next', 'previous', 'results'] for key in pagination_keys: if not (data and key in data): raise WrapperNotApplicable('Not paginated results') view = renderer_context.get("view", None) model = self.model_from_obj(view) resource_type = self.model_to_resource_type(model) try: from rest_framework.utils.serializer_helpers import ReturnList results = ReturnList( data["results"], serializer=data.serializer.fields["results"], ) except ImportError: results = data["results"] # Use default wrapper for results wrapper = self.wrap_default(results, renderer_context) # Add pagination metadata pagination = self.dict_class() pagination['previous'] = data['previous'] pagination['next'] = data['next'] pagination['count'] = data['count'] wrapper.setdefault('meta', self.dict_class()) wrapper['meta'].setdefault('pagination', self.dict_class()) wrapper['meta']['pagination'].setdefault( resource_type, self.dict_class()).update(pagination) return wrapper
python
def wrap_paginated(self, data, renderer_context): """Convert paginated data to JSON API with meta""" pagination_keys = ['count', 'next', 'previous', 'results'] for key in pagination_keys: if not (data and key in data): raise WrapperNotApplicable('Not paginated results') view = renderer_context.get("view", None) model = self.model_from_obj(view) resource_type = self.model_to_resource_type(model) try: from rest_framework.utils.serializer_helpers import ReturnList results = ReturnList( data["results"], serializer=data.serializer.fields["results"], ) except ImportError: results = data["results"] # Use default wrapper for results wrapper = self.wrap_default(results, renderer_context) # Add pagination metadata pagination = self.dict_class() pagination['previous'] = data['previous'] pagination['next'] = data['next'] pagination['count'] = data['count'] wrapper.setdefault('meta', self.dict_class()) wrapper['meta'].setdefault('pagination', self.dict_class()) wrapper['meta']['pagination'].setdefault( resource_type, self.dict_class()).update(pagination) return wrapper
[ "def", "wrap_paginated", "(", "self", ",", "data", ",", "renderer_context", ")", ":", "pagination_keys", "=", "[", "'count'", ",", "'next'", ",", "'previous'", ",", "'results'", "]", "for", "key", "in", "pagination_keys", ":", "if", "not", "(", "data", "and", "key", "in", "data", ")", ":", "raise", "WrapperNotApplicable", "(", "'Not paginated results'", ")", "view", "=", "renderer_context", ".", "get", "(", "\"view\"", ",", "None", ")", "model", "=", "self", ".", "model_from_obj", "(", "view", ")", "resource_type", "=", "self", ".", "model_to_resource_type", "(", "model", ")", "try", ":", "from", "rest_framework", ".", "utils", ".", "serializer_helpers", "import", "ReturnList", "results", "=", "ReturnList", "(", "data", "[", "\"results\"", "]", ",", "serializer", "=", "data", ".", "serializer", ".", "fields", "[", "\"results\"", "]", ",", ")", "except", "ImportError", ":", "results", "=", "data", "[", "\"results\"", "]", "# Use default wrapper for results", "wrapper", "=", "self", ".", "wrap_default", "(", "results", ",", "renderer_context", ")", "# Add pagination metadata", "pagination", "=", "self", ".", "dict_class", "(", ")", "pagination", "[", "'previous'", "]", "=", "data", "[", "'previous'", "]", "pagination", "[", "'next'", "]", "=", "data", "[", "'next'", "]", "pagination", "[", "'count'", "]", "=", "data", "[", "'count'", "]", "wrapper", ".", "setdefault", "(", "'meta'", ",", "self", ".", "dict_class", "(", ")", ")", "wrapper", "[", "'meta'", "]", ".", "setdefault", "(", "'pagination'", ",", "self", ".", "dict_class", "(", ")", ")", "wrapper", "[", "'meta'", "]", "[", "'pagination'", "]", ".", "setdefault", "(", "resource_type", ",", "self", ".", "dict_class", "(", ")", ")", ".", "update", "(", "pagination", ")", "return", "wrapper" ]
Convert paginated data to JSON API with meta
[ "Convert", "paginated", "data", "to", "JSON", "API", "with", "meta" ]
664643bd02c0d92eadbd1f8c9d8507adf0538df6
https://github.com/kevin-brown/drf-json-api/blob/664643bd02c0d92eadbd1f8c9d8507adf0538df6/rest_framework_json_api/renderers.py#L260-L298
train
kevin-brown/drf-json-api
rest_framework_json_api/renderers.py
JsonApiMixin.wrap_default
def wrap_default(self, data, renderer_context): """Convert native data to a JSON API resource collection This wrapper expects a standard DRF data object (a dict-like object with a `fields` dict-like attribute), or a list of such data objects. """ wrapper = self.dict_class() view = renderer_context.get("view", None) request = renderer_context.get("request", None) model = self.model_from_obj(view) resource_type = self.model_to_resource_type(model) if isinstance(data, list): many = True resources = data else: many = False resources = [data] items = [] links = self.dict_class() linked = self.dict_class() meta = self.dict_class() for resource in resources: converted = self.convert_resource(resource, data, request) item = converted.get('data', {}) linked_ids = converted.get('linked_ids', {}) if linked_ids: item["links"] = linked_ids items.append(item) links.update(converted.get('links', {})) linked = self.update_nested(linked, converted.get('linked', {})) meta.update(converted.get('meta', {})) if many: wrapper[resource_type] = items else: wrapper[resource_type] = items[0] if links: links = self.prepend_links_with_name(links, resource_type) wrapper["links"] = links if linked: wrapper["linked"] = linked if meta: wrapper["meta"] = meta return wrapper
python
def wrap_default(self, data, renderer_context): """Convert native data to a JSON API resource collection This wrapper expects a standard DRF data object (a dict-like object with a `fields` dict-like attribute), or a list of such data objects. """ wrapper = self.dict_class() view = renderer_context.get("view", None) request = renderer_context.get("request", None) model = self.model_from_obj(view) resource_type = self.model_to_resource_type(model) if isinstance(data, list): many = True resources = data else: many = False resources = [data] items = [] links = self.dict_class() linked = self.dict_class() meta = self.dict_class() for resource in resources: converted = self.convert_resource(resource, data, request) item = converted.get('data', {}) linked_ids = converted.get('linked_ids', {}) if linked_ids: item["links"] = linked_ids items.append(item) links.update(converted.get('links', {})) linked = self.update_nested(linked, converted.get('linked', {})) meta.update(converted.get('meta', {})) if many: wrapper[resource_type] = items else: wrapper[resource_type] = items[0] if links: links = self.prepend_links_with_name(links, resource_type) wrapper["links"] = links if linked: wrapper["linked"] = linked if meta: wrapper["meta"] = meta return wrapper
[ "def", "wrap_default", "(", "self", ",", "data", ",", "renderer_context", ")", ":", "wrapper", "=", "self", ".", "dict_class", "(", ")", "view", "=", "renderer_context", ".", "get", "(", "\"view\"", ",", "None", ")", "request", "=", "renderer_context", ".", "get", "(", "\"request\"", ",", "None", ")", "model", "=", "self", ".", "model_from_obj", "(", "view", ")", "resource_type", "=", "self", ".", "model_to_resource_type", "(", "model", ")", "if", "isinstance", "(", "data", ",", "list", ")", ":", "many", "=", "True", "resources", "=", "data", "else", ":", "many", "=", "False", "resources", "=", "[", "data", "]", "items", "=", "[", "]", "links", "=", "self", ".", "dict_class", "(", ")", "linked", "=", "self", ".", "dict_class", "(", ")", "meta", "=", "self", ".", "dict_class", "(", ")", "for", "resource", "in", "resources", ":", "converted", "=", "self", ".", "convert_resource", "(", "resource", ",", "data", ",", "request", ")", "item", "=", "converted", ".", "get", "(", "'data'", ",", "{", "}", ")", "linked_ids", "=", "converted", ".", "get", "(", "'linked_ids'", ",", "{", "}", ")", "if", "linked_ids", ":", "item", "[", "\"links\"", "]", "=", "linked_ids", "items", ".", "append", "(", "item", ")", "links", ".", "update", "(", "converted", ".", "get", "(", "'links'", ",", "{", "}", ")", ")", "linked", "=", "self", ".", "update_nested", "(", "linked", ",", "converted", ".", "get", "(", "'linked'", ",", "{", "}", ")", ")", "meta", ".", "update", "(", "converted", ".", "get", "(", "'meta'", ",", "{", "}", ")", ")", "if", "many", ":", "wrapper", "[", "resource_type", "]", "=", "items", "else", ":", "wrapper", "[", "resource_type", "]", "=", "items", "[", "0", "]", "if", "links", ":", "links", "=", "self", ".", "prepend_links_with_name", "(", "links", ",", "resource_type", ")", "wrapper", "[", "\"links\"", "]", "=", "links", "if", "linked", ":", "wrapper", "[", "\"linked\"", "]", "=", "linked", "if", "meta", ":", "wrapper", "[", "\"meta\"", "]", "=", "meta", "return", "wrapper" ]
Convert native data to a JSON API resource collection This wrapper expects a standard DRF data object (a dict-like object with a `fields` dict-like attribute), or a list of such data objects.
[ "Convert", "native", "data", "to", "a", "JSON", "API", "resource", "collection" ]
664643bd02c0d92eadbd1f8c9d8507adf0538df6
https://github.com/kevin-brown/drf-json-api/blob/664643bd02c0d92eadbd1f8c9d8507adf0538df6/rest_framework_json_api/renderers.py#L300-L355
train
jaraco/jaraco.mongodb
jaraco/mongodb/sessions.py
Session.acquire_lock
def acquire_lock(self): """ Acquire the lock. Blocks indefinitely until lock is available unless `lock_timeout` was supplied. If the lock_timeout elapses, raises LockTimeout. """ # first ensure that a record exists for this session id try: self.collection.insert_one(dict(_id=self.id)) except pymongo.errors.DuplicateKeyError: pass unlocked_spec = dict(_id=self.id, locked=None) lock_timer = ( timers.Timer.after(self.lock_timeout) if self.lock_timeout else timers.NeverExpires() ) while not lock_timer.expired(): locked_spec = {'$set': dict(locked=datetime.datetime.utcnow())} res = self.collection.update_one(unlocked_spec, locked_spec) if res.raw_result['updatedExisting']: # we have the lock break time.sleep(0.1) else: raise LockTimeout(f"Timeout acquiring lock for {self.id}") self.locked = True
python
def acquire_lock(self): """ Acquire the lock. Blocks indefinitely until lock is available unless `lock_timeout` was supplied. If the lock_timeout elapses, raises LockTimeout. """ # first ensure that a record exists for this session id try: self.collection.insert_one(dict(_id=self.id)) except pymongo.errors.DuplicateKeyError: pass unlocked_spec = dict(_id=self.id, locked=None) lock_timer = ( timers.Timer.after(self.lock_timeout) if self.lock_timeout else timers.NeverExpires() ) while not lock_timer.expired(): locked_spec = {'$set': dict(locked=datetime.datetime.utcnow())} res = self.collection.update_one(unlocked_spec, locked_spec) if res.raw_result['updatedExisting']: # we have the lock break time.sleep(0.1) else: raise LockTimeout(f"Timeout acquiring lock for {self.id}") self.locked = True
[ "def", "acquire_lock", "(", "self", ")", ":", "# first ensure that a record exists for this session id", "try", ":", "self", ".", "collection", ".", "insert_one", "(", "dict", "(", "_id", "=", "self", ".", "id", ")", ")", "except", "pymongo", ".", "errors", ".", "DuplicateKeyError", ":", "pass", "unlocked_spec", "=", "dict", "(", "_id", "=", "self", ".", "id", ",", "locked", "=", "None", ")", "lock_timer", "=", "(", "timers", ".", "Timer", ".", "after", "(", "self", ".", "lock_timeout", ")", "if", "self", ".", "lock_timeout", "else", "timers", ".", "NeverExpires", "(", ")", ")", "while", "not", "lock_timer", ".", "expired", "(", ")", ":", "locked_spec", "=", "{", "'$set'", ":", "dict", "(", "locked", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ")", "}", "res", "=", "self", ".", "collection", ".", "update_one", "(", "unlocked_spec", ",", "locked_spec", ")", "if", "res", ".", "raw_result", "[", "'updatedExisting'", "]", ":", "# we have the lock", "break", "time", ".", "sleep", "(", "0.1", ")", "else", ":", "raise", "LockTimeout", "(", "f\"Timeout acquiring lock for {self.id}\"", ")", "self", ".", "locked", "=", "True" ]
Acquire the lock. Blocks indefinitely until lock is available unless `lock_timeout` was supplied. If the lock_timeout elapses, raises LockTimeout.
[ "Acquire", "the", "lock", ".", "Blocks", "indefinitely", "until", "lock", "is", "available", "unless", "lock_timeout", "was", "supplied", ".", "If", "the", "lock_timeout", "elapses", "raises", "LockTimeout", "." ]
280f17894941f4babf2e97db033dbb1fd2b9f705
https://github.com/jaraco/jaraco.mongodb/blob/280f17894941f4babf2e97db033dbb1fd2b9f705/jaraco/mongodb/sessions.py#L172-L198
train
CiscoUcs/UcsPythonSDK
src/UcsSdk/utils/management.py
BootDeviceHelper.set_boot_device
def set_boot_device(self, device, persistent=False): """Set the boot device for the node. Set the boot device to use on next reboot of the node. :param device: the boot device, one of :mod:`ironic.common.boot_devices`. :param persistent: Boolean value. True if the boot device will persist to all future boots, False if not. Default: False. Ignored by this driver. :raises: UcsOperationError if it UCS Manager reports any error. """ operation = "set_boot_device" try: self.sp_manager.create_boot_policy() self.sp_manager.set_boot_device(device) except UcsException as ex: raise exception.UcsOperationError(operation=operation, error=ex)
python
def set_boot_device(self, device, persistent=False): """Set the boot device for the node. Set the boot device to use on next reboot of the node. :param device: the boot device, one of :mod:`ironic.common.boot_devices`. :param persistent: Boolean value. True if the boot device will persist to all future boots, False if not. Default: False. Ignored by this driver. :raises: UcsOperationError if it UCS Manager reports any error. """ operation = "set_boot_device" try: self.sp_manager.create_boot_policy() self.sp_manager.set_boot_device(device) except UcsException as ex: raise exception.UcsOperationError(operation=operation, error=ex)
[ "def", "set_boot_device", "(", "self", ",", "device", ",", "persistent", "=", "False", ")", ":", "operation", "=", "\"set_boot_device\"", "try", ":", "self", ".", "sp_manager", ".", "create_boot_policy", "(", ")", "self", ".", "sp_manager", ".", "set_boot_device", "(", "device", ")", "except", "UcsException", "as", "ex", ":", "raise", "exception", ".", "UcsOperationError", "(", "operation", "=", "operation", ",", "error", "=", "ex", ")" ]
Set the boot device for the node. Set the boot device to use on next reboot of the node. :param device: the boot device, one of :mod:`ironic.common.boot_devices`. :param persistent: Boolean value. True if the boot device will persist to all future boots, False if not. Default: False. Ignored by this driver. :raises: UcsOperationError if it UCS Manager reports any error.
[ "Set", "the", "boot", "device", "for", "the", "node", "." ]
bf6b07d6abeacb922c92b198352eda4eb9e4629b
https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/utils/management.py#L39-L57
train
CiscoUcs/UcsPythonSDK
src/UcsSdk/utils/management.py
BootDeviceHelper.get_boot_device
def get_boot_device(self): """Get the current boot device for the node. Provides the current boot device of the node. Be aware that not all drivers support this. :raises: InvalidParameterValue if any connection parameters are incorrect. :raises: MissingParameterValue if a required parameter is missing :returns: a dictionary containing: :boot_device: the boot device, one of :mod:`ironic.common.boot_devices` or None if it is unknown. :persistent: Whether the boot device will persist to all future boots or not, None if it is unknown. """ operation = 'get_boot_device' try: boot_device = self.sp_manager.get_boot_device() return boot_device except UcsException as ex: print(_("Cisco client exception: %(msg)s."), {'msg': ex}) raise exception.UcsOperationError(operation=operation, error=ex)
python
def get_boot_device(self): """Get the current boot device for the node. Provides the current boot device of the node. Be aware that not all drivers support this. :raises: InvalidParameterValue if any connection parameters are incorrect. :raises: MissingParameterValue if a required parameter is missing :returns: a dictionary containing: :boot_device: the boot device, one of :mod:`ironic.common.boot_devices` or None if it is unknown. :persistent: Whether the boot device will persist to all future boots or not, None if it is unknown. """ operation = 'get_boot_device' try: boot_device = self.sp_manager.get_boot_device() return boot_device except UcsException as ex: print(_("Cisco client exception: %(msg)s."), {'msg': ex}) raise exception.UcsOperationError(operation=operation, error=ex)
[ "def", "get_boot_device", "(", "self", ")", ":", "operation", "=", "'get_boot_device'", "try", ":", "boot_device", "=", "self", ".", "sp_manager", ".", "get_boot_device", "(", ")", "return", "boot_device", "except", "UcsException", "as", "ex", ":", "print", "(", "_", "(", "\"Cisco client exception: %(msg)s.\"", ")", ",", "{", "'msg'", ":", "ex", "}", ")", "raise", "exception", ".", "UcsOperationError", "(", "operation", "=", "operation", ",", "error", "=", "ex", ")" ]
Get the current boot device for the node. Provides the current boot device of the node. Be aware that not all drivers support this. :raises: InvalidParameterValue if any connection parameters are incorrect. :raises: MissingParameterValue if a required parameter is missing :returns: a dictionary containing: :boot_device: the boot device, one of :mod:`ironic.common.boot_devices` or None if it is unknown. :persistent: Whether the boot device will persist to all future boots or not, None if it is unknown.
[ "Get", "the", "current", "boot", "device", "for", "the", "node", "." ]
bf6b07d6abeacb922c92b198352eda4eb9e4629b
https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/utils/management.py#L59-L81
train
yeraydiazdiaz/lunr.py
lunr/__main__.py
lunr
def lunr(ref, fields, documents, languages=None): """A convenience function to configure and construct a lunr.Index. Args: ref (str): The key in the documents to be used a the reference. fields (list): A list of strings defining fields in the documents to index. Optionally a list of dictionaries with three keys: `field_name` defining the document's field, `boost` an integer defining a boost to be applied to the field, and `extractor` a callable taking the document as a single argument and returning a string located in the document in a particular way. documents (list): The list of dictonaries representing the documents to index. Optionally a 2-tuple of dicts, the first one being the document and the second the associated attributes to it. languages (str or list, optional): The languages to use if using NLTK language support, ignored if NLTK is not available. Returns: Index: The populated Index ready to search against. """ if languages is not None and lang.LANGUAGE_SUPPORT: if isinstance(languages, basestring): languages = [languages] unsupported_languages = set(languages) - set(lang.SUPPORTED_LANGUAGES) if unsupported_languages: raise RuntimeError( "The specified languages {} are not supported, " "please choose one of {}".format( ", ".join(unsupported_languages), ", ".join(lang.SUPPORTED_LANGUAGES.keys()), ) ) builder = lang.get_nltk_builder(languages) else: builder = Builder() builder.pipeline.add(trimmer, stop_word_filter, stemmer) builder.search_pipeline.add(stemmer) builder.ref(ref) for field in fields: if isinstance(field, dict): builder.field(**field) else: builder.field(field) for document in documents: if isinstance(document, (tuple, list)): builder.add(document[0], attributes=document[1]) else: builder.add(document) return builder.build()
python
def lunr(ref, fields, documents, languages=None): """A convenience function to configure and construct a lunr.Index. Args: ref (str): The key in the documents to be used a the reference. fields (list): A list of strings defining fields in the documents to index. Optionally a list of dictionaries with three keys: `field_name` defining the document's field, `boost` an integer defining a boost to be applied to the field, and `extractor` a callable taking the document as a single argument and returning a string located in the document in a particular way. documents (list): The list of dictonaries representing the documents to index. Optionally a 2-tuple of dicts, the first one being the document and the second the associated attributes to it. languages (str or list, optional): The languages to use if using NLTK language support, ignored if NLTK is not available. Returns: Index: The populated Index ready to search against. """ if languages is not None and lang.LANGUAGE_SUPPORT: if isinstance(languages, basestring): languages = [languages] unsupported_languages = set(languages) - set(lang.SUPPORTED_LANGUAGES) if unsupported_languages: raise RuntimeError( "The specified languages {} are not supported, " "please choose one of {}".format( ", ".join(unsupported_languages), ", ".join(lang.SUPPORTED_LANGUAGES.keys()), ) ) builder = lang.get_nltk_builder(languages) else: builder = Builder() builder.pipeline.add(trimmer, stop_word_filter, stemmer) builder.search_pipeline.add(stemmer) builder.ref(ref) for field in fields: if isinstance(field, dict): builder.field(**field) else: builder.field(field) for document in documents: if isinstance(document, (tuple, list)): builder.add(document[0], attributes=document[1]) else: builder.add(document) return builder.build()
[ "def", "lunr", "(", "ref", ",", "fields", ",", "documents", ",", "languages", "=", "None", ")", ":", "if", "languages", "is", "not", "None", "and", "lang", ".", "LANGUAGE_SUPPORT", ":", "if", "isinstance", "(", "languages", ",", "basestring", ")", ":", "languages", "=", "[", "languages", "]", "unsupported_languages", "=", "set", "(", "languages", ")", "-", "set", "(", "lang", ".", "SUPPORTED_LANGUAGES", ")", "if", "unsupported_languages", ":", "raise", "RuntimeError", "(", "\"The specified languages {} are not supported, \"", "\"please choose one of {}\"", ".", "format", "(", "\", \"", ".", "join", "(", "unsupported_languages", ")", ",", "\", \"", ".", "join", "(", "lang", ".", "SUPPORTED_LANGUAGES", ".", "keys", "(", ")", ")", ",", ")", ")", "builder", "=", "lang", ".", "get_nltk_builder", "(", "languages", ")", "else", ":", "builder", "=", "Builder", "(", ")", "builder", ".", "pipeline", ".", "add", "(", "trimmer", ",", "stop_word_filter", ",", "stemmer", ")", "builder", ".", "search_pipeline", ".", "add", "(", "stemmer", ")", "builder", ".", "ref", "(", "ref", ")", "for", "field", "in", "fields", ":", "if", "isinstance", "(", "field", ",", "dict", ")", ":", "builder", ".", "field", "(", "*", "*", "field", ")", "else", ":", "builder", ".", "field", "(", "field", ")", "for", "document", "in", "documents", ":", "if", "isinstance", "(", "document", ",", "(", "tuple", ",", "list", ")", ")", ":", "builder", ".", "add", "(", "document", "[", "0", "]", ",", "attributes", "=", "document", "[", "1", "]", ")", "else", ":", "builder", ".", "add", "(", "document", ")", "return", "builder", ".", "build", "(", ")" ]
A convenience function to configure and construct a lunr.Index. Args: ref (str): The key in the documents to be used a the reference. fields (list): A list of strings defining fields in the documents to index. Optionally a list of dictionaries with three keys: `field_name` defining the document's field, `boost` an integer defining a boost to be applied to the field, and `extractor` a callable taking the document as a single argument and returning a string located in the document in a particular way. documents (list): The list of dictonaries representing the documents to index. Optionally a 2-tuple of dicts, the first one being the document and the second the associated attributes to it. languages (str or list, optional): The languages to use if using NLTK language support, ignored if NLTK is not available. Returns: Index: The populated Index ready to search against.
[ "A", "convenience", "function", "to", "configure", "and", "construct", "a", "lunr", ".", "Index", "." ]
28ec3f6d4888295eed730211ee9617aa488d6ba3
https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/__main__.py#L13-L65
train
JensRantil/rewind
rewind/server/eventstores.py
SQLiteEventStore.from_config
def from_config(_config, **options): """Instantiate an SQLite event store from config. Parameters: _config -- the configuration file options read from file(s). Not used. **options -- various options given to the specific event store. Shall not be used with this event store. Warning will be logged for every extra non-recognized option. The only required key to this function is 'path'. returns -- a newly instantiated `SQLiteEventStore`. """ expected_args = ('path',) rconfig.check_config_options("SQLiteEventStore", expected_args, tuple(), options) return SQLiteEventStore(options['path'])
python
def from_config(_config, **options): """Instantiate an SQLite event store from config. Parameters: _config -- the configuration file options read from file(s). Not used. **options -- various options given to the specific event store. Shall not be used with this event store. Warning will be logged for every extra non-recognized option. The only required key to this function is 'path'. returns -- a newly instantiated `SQLiteEventStore`. """ expected_args = ('path',) rconfig.check_config_options("SQLiteEventStore", expected_args, tuple(), options) return SQLiteEventStore(options['path'])
[ "def", "from_config", "(", "_config", ",", "*", "*", "options", ")", ":", "expected_args", "=", "(", "'path'", ",", ")", "rconfig", ".", "check_config_options", "(", "\"SQLiteEventStore\"", ",", "expected_args", ",", "tuple", "(", ")", ",", "options", ")", "return", "SQLiteEventStore", "(", "options", "[", "'path'", "]", ")" ]
Instantiate an SQLite event store from config. Parameters: _config -- the configuration file options read from file(s). Not used. **options -- various options given to the specific event store. Shall not be used with this event store. Warning will be logged for every extra non-recognized option. The only required key to this function is 'path'. returns -- a newly instantiated `SQLiteEventStore`.
[ "Instantiate", "an", "SQLite", "event", "store", "from", "config", "." ]
7f645d20186c1db55cfe53a0310c9fd6292f91ea
https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/eventstores.py#L407-L424
train
JensRantil/rewind
rewind/server/eventstores.py
SQLiteEventStore.key_exists
def key_exists(self, key): """Check whether a key exists in the event store. Returns True if it does, False otherwise. """ assert isinstance(key, str) cursor = self.conn.cursor() with contextlib.closing(cursor): cursor.execute('SELECT COUNT(*) FROM events WHERE uuid=?', (key,)) res = cursor.fetchone() count = res[0] if count == 0: return False else: assert count in (0, 1), \ "Duplicate event ids detected: {0}".format(count) return True
python
def key_exists(self, key): """Check whether a key exists in the event store. Returns True if it does, False otherwise. """ assert isinstance(key, str) cursor = self.conn.cursor() with contextlib.closing(cursor): cursor.execute('SELECT COUNT(*) FROM events WHERE uuid=?', (key,)) res = cursor.fetchone() count = res[0] if count == 0: return False else: assert count in (0, 1), \ "Duplicate event ids detected: {0}".format(count) return True
[ "def", "key_exists", "(", "self", ",", "key", ")", ":", "assert", "isinstance", "(", "key", ",", "str", ")", "cursor", "=", "self", ".", "conn", ".", "cursor", "(", ")", "with", "contextlib", ".", "closing", "(", "cursor", ")", ":", "cursor", ".", "execute", "(", "'SELECT COUNT(*) FROM events WHERE uuid=?'", ",", "(", "key", ",", ")", ")", "res", "=", "cursor", ".", "fetchone", "(", ")", "count", "=", "res", "[", "0", "]", "if", "count", "==", "0", ":", "return", "False", "else", ":", "assert", "count", "in", "(", "0", ",", "1", ")", ",", "\"Duplicate event ids detected: {0}\"", ".", "format", "(", "count", ")", "return", "True" ]
Check whether a key exists in the event store. Returns True if it does, False otherwise.
[ "Check", "whether", "a", "key", "exists", "in", "the", "event", "store", "." ]
7f645d20186c1db55cfe53a0310c9fd6292f91ea
https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/eventstores.py#L483-L500
train
JensRantil/rewind
rewind/server/eventstores.py
SQLiteEventStore.count
def count(self): """Return the number of events in the db.""" cursor = self.conn.cursor() with contextlib.closing(cursor): cursor.execute('SELECT COUNT(*) FROM events') res = cursor.fetchone() return res[0]
python
def count(self): """Return the number of events in the db.""" cursor = self.conn.cursor() with contextlib.closing(cursor): cursor.execute('SELECT COUNT(*) FROM events') res = cursor.fetchone() return res[0]
[ "def", "count", "(", "self", ")", ":", "cursor", "=", "self", ".", "conn", ".", "cursor", "(", ")", "with", "contextlib", ".", "closing", "(", "cursor", ")", ":", "cursor", ".", "execute", "(", "'SELECT COUNT(*) FROM events'", ")", "res", "=", "cursor", ".", "fetchone", "(", ")", "return", "res", "[", "0", "]" ]
Return the number of events in the db.
[ "Return", "the", "number", "of", "events", "in", "the", "db", "." ]
7f645d20186c1db55cfe53a0310c9fd6292f91ea
https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/eventstores.py#L502-L508
train
JensRantil/rewind
rewind/server/eventstores.py
SQLiteEventStore.close
def close(self): """Close the event store. Important to close to not have any file descriptor leakages. """ if self.conn: self.conn.close() self.conn = None fname = os.path.basename(self._path) checksum_persister = _get_checksum_persister(self._path) hasher = _initialize_hasher(self._path) with contextlib.closing(checksum_persister): checksum_persister[fname] = hasher.hexdigest()
python
def close(self): """Close the event store. Important to close to not have any file descriptor leakages. """ if self.conn: self.conn.close() self.conn = None fname = os.path.basename(self._path) checksum_persister = _get_checksum_persister(self._path) hasher = _initialize_hasher(self._path) with contextlib.closing(checksum_persister): checksum_persister[fname] = hasher.hexdigest()
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "conn", ":", "self", ".", "conn", ".", "close", "(", ")", "self", ".", "conn", "=", "None", "fname", "=", "os", ".", "path", ".", "basename", "(", "self", ".", "_path", ")", "checksum_persister", "=", "_get_checksum_persister", "(", "self", ".", "_path", ")", "hasher", "=", "_initialize_hasher", "(", "self", ".", "_path", ")", "with", "contextlib", ".", "closing", "(", "checksum_persister", ")", ":", "checksum_persister", "[", "fname", "]", "=", "hasher", ".", "hexdigest", "(", ")" ]
Close the event store. Important to close to not have any file descriptor leakages.
[ "Close", "the", "event", "store", "." ]
7f645d20186c1db55cfe53a0310c9fd6292f91ea
https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/eventstores.py#L510-L524
train
JensRantil/rewind
rewind/server/eventstores.py
LogEventStore.from_config
def from_config(config, **options): """Instantiate an `LogEventStore` from config. Parameters: _config -- the configuration file options read from file(s). **options -- various options given to the specific event store. Shall not be used with this event store. Warning will be logged for every extra non-recognized option. The only required key to this function is 'path'. returns -- a newly instantiated `LogEventStore`. """ expected_args = ('path',) rconfig.check_config_options("LogEventStore", expected_args, tuple(), options) return LogEventStore(options['path'])
python
def from_config(config, **options): """Instantiate an `LogEventStore` from config. Parameters: _config -- the configuration file options read from file(s). **options -- various options given to the specific event store. Shall not be used with this event store. Warning will be logged for every extra non-recognized option. The only required key to this function is 'path'. returns -- a newly instantiated `LogEventStore`. """ expected_args = ('path',) rconfig.check_config_options("LogEventStore", expected_args, tuple(), options) return LogEventStore(options['path'])
[ "def", "from_config", "(", "config", ",", "*", "*", "options", ")", ":", "expected_args", "=", "(", "'path'", ",", ")", "rconfig", ".", "check_config_options", "(", "\"LogEventStore\"", ",", "expected_args", ",", "tuple", "(", ")", ",", "options", ")", "return", "LogEventStore", "(", "options", "[", "'path'", "]", ")" ]
Instantiate an `LogEventStore` from config. Parameters: _config -- the configuration file options read from file(s). **options -- various options given to the specific event store. Shall not be used with this event store. Warning will be logged for every extra non-recognized option. The only required key to this function is 'path'. returns -- a newly instantiated `LogEventStore`.
[ "Instantiate", "an", "LogEventStore", "from", "config", "." ]
7f645d20186c1db55cfe53a0310c9fd6292f91ea
https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/eventstores.py#L549-L565
train
JensRantil/rewind
rewind/server/eventstores.py
LogEventStore.key_exists
def key_exists(self, key): """Check if key has previously been added to this store. This function makes a linear search through the log file and is very slow. Returns True if the event has previously been added, False otherwise. """ assert isinstance(key, str) self._close() try: return self._unsafe_key_exists(key) finally: self._open()
python
def key_exists(self, key): """Check if key has previously been added to this store. This function makes a linear search through the log file and is very slow. Returns True if the event has previously been added, False otherwise. """ assert isinstance(key, str) self._close() try: return self._unsafe_key_exists(key) finally: self._open()
[ "def", "key_exists", "(", "self", ",", "key", ")", ":", "assert", "isinstance", "(", "key", ",", "str", ")", "self", ".", "_close", "(", ")", "try", ":", "return", "self", ".", "_unsafe_key_exists", "(", "key", ")", "finally", ":", "self", ".", "_open", "(", ")" ]
Check if key has previously been added to this store. This function makes a linear search through the log file and is very slow. Returns True if the event has previously been added, False otherwise.
[ "Check", "if", "key", "has", "previously", "been", "added", "to", "this", "store", "." ]
7f645d20186c1db55cfe53a0310c9fd6292f91ea
https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/eventstores.py#L656-L670
train
JensRantil/rewind
rewind/server/eventstores.py
LogEventStore.close
def close(self): """Persist a checksum and close the file.""" fname = os.path.basename(self._path) checksum_persister = _get_checksum_persister(self._path) with contextlib.closing(checksum_persister): checksum_persister[fname] = self._hasher.hexdigest() self._close()
python
def close(self): """Persist a checksum and close the file.""" fname = os.path.basename(self._path) checksum_persister = _get_checksum_persister(self._path) with contextlib.closing(checksum_persister): checksum_persister[fname] = self._hasher.hexdigest() self._close()
[ "def", "close", "(", "self", ")", ":", "fname", "=", "os", ".", "path", ".", "basename", "(", "self", ".", "_path", ")", "checksum_persister", "=", "_get_checksum_persister", "(", "self", ".", "_path", ")", "with", "contextlib", ".", "closing", "(", "checksum_persister", ")", ":", "checksum_persister", "[", "fname", "]", "=", "self", ".", "_hasher", ".", "hexdigest", "(", ")", "self", ".", "_close", "(", ")" ]
Persist a checksum and close the file.
[ "Persist", "a", "checksum", "and", "close", "the", "file", "." ]
7f645d20186c1db55cfe53a0310c9fd6292f91ea
https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/eventstores.py#L672-L679
train
JensRantil/rewind
rewind/server/eventstores.py
RotatedEventStore.from_config
def from_config(config, **options): """Instantiate an `RotatedEventStore` from config. Parameters: _config -- the configuration file options read from file(s). **options -- various options given to the specific event store. Shall not be used with this event store. Warning will be logged for every extra non-recognized option. The only required key to this function is 'path'. returns -- a newly instantiated `RotatedEventStore`. """ expected_args = ('prefix', 'realclass') for arg in expected_args: if arg not in options: msg = "Required option missing: {0}" raise rconfig.ConfigurationError(msg.format(arg)) # Not logging unrecognized options here, because they might be used # by the real event store instantiated below. classpath = options['realclass'] classpath_pieces = classpath.split('.') classname = classpath_pieces[-1] modulepath = '.'.join(classpath_pieces[0:-1]) module = importlib.import_module(modulepath) estore_class = getattr(module, classname) return RotatedEventStore(lambda fname: estore_class(fname), options['path'], options['prefix'])
python
def from_config(config, **options): """Instantiate an `RotatedEventStore` from config. Parameters: _config -- the configuration file options read from file(s). **options -- various options given to the specific event store. Shall not be used with this event store. Warning will be logged for every extra non-recognized option. The only required key to this function is 'path'. returns -- a newly instantiated `RotatedEventStore`. """ expected_args = ('prefix', 'realclass') for arg in expected_args: if arg not in options: msg = "Required option missing: {0}" raise rconfig.ConfigurationError(msg.format(arg)) # Not logging unrecognized options here, because they might be used # by the real event store instantiated below. classpath = options['realclass'] classpath_pieces = classpath.split('.') classname = classpath_pieces[-1] modulepath = '.'.join(classpath_pieces[0:-1]) module = importlib.import_module(modulepath) estore_class = getattr(module, classname) return RotatedEventStore(lambda fname: estore_class(fname), options['path'], options['prefix'])
[ "def", "from_config", "(", "config", ",", "*", "*", "options", ")", ":", "expected_args", "=", "(", "'prefix'", ",", "'realclass'", ")", "for", "arg", "in", "expected_args", ":", "if", "arg", "not", "in", "options", ":", "msg", "=", "\"Required option missing: {0}\"", "raise", "rconfig", ".", "ConfigurationError", "(", "msg", ".", "format", "(", "arg", ")", ")", "# Not logging unrecognized options here, because they might be used", "# by the real event store instantiated below.", "classpath", "=", "options", "[", "'realclass'", "]", "classpath_pieces", "=", "classpath", ".", "split", "(", "'.'", ")", "classname", "=", "classpath_pieces", "[", "-", "1", "]", "modulepath", "=", "'.'", ".", "join", "(", "classpath_pieces", "[", "0", ":", "-", "1", "]", ")", "module", "=", "importlib", ".", "import_module", "(", "modulepath", ")", "estore_class", "=", "getattr", "(", "module", ",", "classname", ")", "return", "RotatedEventStore", "(", "lambda", "fname", ":", "estore_class", "(", "fname", ")", ",", "options", "[", "'path'", "]", ",", "options", "[", "'prefix'", "]", ")" ]
Instantiate an `RotatedEventStore` from config. Parameters: _config -- the configuration file options read from file(s). **options -- various options given to the specific event store. Shall not be used with this event store. Warning will be logged for every extra non-recognized option. The only required key to this function is 'path'. returns -- a newly instantiated `RotatedEventStore`.
[ "Instantiate", "an", "RotatedEventStore", "from", "config", "." ]
7f645d20186c1db55cfe53a0310c9fd6292f91ea
https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/eventstores.py#L711-L740
train
JensRantil/rewind
rewind/server/eventstores.py
RotatedEventStore._construct_filename
def _construct_filename(self, batchno): """Construct a filename for a database. Parameters: batchno -- batch number for the rotated database. Returns the constructed path as a string. """ return os.path.join(self.dirpath, "{0}.{1}".format(self.prefix, batchno))
python
def _construct_filename(self, batchno): """Construct a filename for a database. Parameters: batchno -- batch number for the rotated database. Returns the constructed path as a string. """ return os.path.join(self.dirpath, "{0}.{1}".format(self.prefix, batchno))
[ "def", "_construct_filename", "(", "self", ",", "batchno", ")", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "dirpath", ",", "\"{0}.{1}\"", ".", "format", "(", "self", ".", "prefix", ",", "batchno", ")", ")" ]
Construct a filename for a database. Parameters: batchno -- batch number for the rotated database. Returns the constructed path as a string.
[ "Construct", "a", "filename", "for", "a", "database", "." ]
7f645d20186c1db55cfe53a0310c9fd6292f91ea
https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/eventstores.py#L773-L783
train