id
int32
0
252k
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
251,400
etscrivner/nose-perfdump
perfdump/plugin.py
PerfDumpPlugin.report
def report(self, stream): """Displays the slowest tests""" self.db.commit() stream.writeln() self.draw_header(stream, "10 SLOWEST SETUPS") self.display_slowest_setups(stream) stream.writeln() self.draw_header(stream, "10 SLOWEST TESTS") self.display_slowest_tests(stream) stream.writeln() if self.html_output_file: HtmlReport.write(self.html_output_file)
python
def report(self, stream): """Displays the slowest tests""" self.db.commit() stream.writeln() self.draw_header(stream, "10 SLOWEST SETUPS") self.display_slowest_setups(stream) stream.writeln() self.draw_header(stream, "10 SLOWEST TESTS") self.display_slowest_tests(stream) stream.writeln() if self.html_output_file: HtmlReport.write(self.html_output_file)
[ "def", "report", "(", "self", ",", "stream", ")", ":", "self", ".", "db", ".", "commit", "(", ")", "stream", ".", "writeln", "(", ")", "self", ".", "draw_header", "(", "stream", ",", "\"10 SLOWEST SETUPS\"", ")", "self", ".", "display_slowest_setups", "(", "stream", ")", "stream", ".", "writeln", "(", ")", "self", ".", "draw_header", "(", "stream", ",", "\"10 SLOWEST TESTS\"", ")", "self", ".", "display_slowest_tests", "(", "stream", ")", "stream", ".", "writeln", "(", ")", "if", "self", ".", "html_output_file", ":", "HtmlReport", ".", "write", "(", "self", ".", "html_output_file", ")" ]
Displays the slowest tests
[ "Displays", "the", "slowest", "tests" ]
a203a68495d30346fab43fb903cb60cd29b17d49
https://github.com/etscrivner/nose-perfdump/blob/a203a68495d30346fab43fb903cb60cd29b17d49/perfdump/plugin.py#L130-L144
251,401
etscrivner/nose-perfdump
perfdump/plugin.py
PerfDumpPlugin.draw_header
def draw_header(self, stream, header): """Draw header with underline""" stream.writeln('=' * (len(header) + 4)) stream.writeln('| ' + header + ' |') stream.writeln('=' * (len(header) + 4)) stream.writeln()
python
def draw_header(self, stream, header): """Draw header with underline""" stream.writeln('=' * (len(header) + 4)) stream.writeln('| ' + header + ' |') stream.writeln('=' * (len(header) + 4)) stream.writeln()
[ "def", "draw_header", "(", "self", ",", "stream", ",", "header", ")", ":", "stream", ".", "writeln", "(", "'='", "*", "(", "len", "(", "header", ")", "+", "4", ")", ")", "stream", ".", "writeln", "(", "'| '", "+", "header", "+", "' |'", ")", "stream", ".", "writeln", "(", "'='", "*", "(", "len", "(", "header", ")", "+", "4", ")", ")", "stream", ".", "writeln", "(", ")" ]
Draw header with underline
[ "Draw", "header", "with", "underline" ]
a203a68495d30346fab43fb903cb60cd29b17d49
https://github.com/etscrivner/nose-perfdump/blob/a203a68495d30346fab43fb903cb60cd29b17d49/perfdump/plugin.py#L146-L151
251,402
klingtnet/sblgntparser
sblgntparser/model.py
Text.find
def find(self, sought, view='lemma'): ''' Returns a word instance for the hit if the "sought" word is found in the text. Per default the "lemma" view of the words is compared. You can specify the desired view with the optional "view" option. ''' hits = [] for sentence in self._sentences: hits += sentence.find(sought, view) return hits
python
def find(self, sought, view='lemma'): ''' Returns a word instance for the hit if the "sought" word is found in the text. Per default the "lemma" view of the words is compared. You can specify the desired view with the optional "view" option. ''' hits = [] for sentence in self._sentences: hits += sentence.find(sought, view) return hits
[ "def", "find", "(", "self", ",", "sought", ",", "view", "=", "'lemma'", ")", ":", "hits", "=", "[", "]", "for", "sentence", "in", "self", ".", "_sentences", ":", "hits", "+=", "sentence", ".", "find", "(", "sought", ",", "view", ")", "return", "hits" ]
Returns a word instance for the hit if the "sought" word is found in the text. Per default the "lemma" view of the words is compared. You can specify the desired view with the optional "view" option.
[ "Returns", "a", "word", "instance", "for", "the", "hit", "if", "the", "sought", "word", "is", "found", "in", "the", "text", ".", "Per", "default", "the", "lemma", "view", "of", "the", "words", "is", "compared", ".", "You", "can", "specify", "the", "desired", "view", "with", "the", "optional", "view", "option", "." ]
535931a833203e5d9065072ec988c575b493d67f
https://github.com/klingtnet/sblgntparser/blob/535931a833203e5d9065072ec988c575b493d67f/sblgntparser/model.py#L28-L37
251,403
klingtnet/sblgntparser
sblgntparser/model.py
Sentence.find
def find(self, sought, view='lemma'): ''' Returns a word instance for the hit if the "sought" word is found in the sentence. Per default the "lemma" view of the words is compared. You can specify the desired view with the optional "view" option. ''' for word in self.wordlist: if sought == word.views[view]: yield word
python
def find(self, sought, view='lemma'): ''' Returns a word instance for the hit if the "sought" word is found in the sentence. Per default the "lemma" view of the words is compared. You can specify the desired view with the optional "view" option. ''' for word in self.wordlist: if sought == word.views[view]: yield word
[ "def", "find", "(", "self", ",", "sought", ",", "view", "=", "'lemma'", ")", ":", "for", "word", "in", "self", ".", "wordlist", ":", "if", "sought", "==", "word", ".", "views", "[", "view", "]", ":", "yield", "word" ]
Returns a word instance for the hit if the "sought" word is found in the sentence. Per default the "lemma" view of the words is compared. You can specify the desired view with the optional "view" option.
[ "Returns", "a", "word", "instance", "for", "the", "hit", "if", "the", "sought", "word", "is", "found", "in", "the", "sentence", ".", "Per", "default", "the", "lemma", "view", "of", "the", "words", "is", "compared", ".", "You", "can", "specify", "the", "desired", "view", "with", "the", "optional", "view", "option", "." ]
535931a833203e5d9065072ec988c575b493d67f
https://github.com/klingtnet/sblgntparser/blob/535931a833203e5d9065072ec988c575b493d67f/sblgntparser/model.py#L63-L71
251,404
klingtnet/sblgntparser
sblgntparser/model.py
Sentence.word
def word(self, position): ''' Returns the word instance at the given position in the sentence, None if not found. ''' if 0 <= position < len(self.wordlist): return self.wordlist[position] else: log.warn('position "{}" is not in sentence of length "{}"!'.format(position, len(self.wordlist))) raise IndexError()
python
def word(self, position): ''' Returns the word instance at the given position in the sentence, None if not found. ''' if 0 <= position < len(self.wordlist): return self.wordlist[position] else: log.warn('position "{}" is not in sentence of length "{}"!'.format(position, len(self.wordlist))) raise IndexError()
[ "def", "word", "(", "self", ",", "position", ")", ":", "if", "0", "<=", "position", "<", "len", "(", "self", ".", "wordlist", ")", ":", "return", "self", ".", "wordlist", "[", "position", "]", "else", ":", "log", ".", "warn", "(", "'position \"{}\" is not in sentence of length \"{}\"!'", ".", "format", "(", "position", ",", "len", "(", "self", ".", "wordlist", ")", ")", ")", "raise", "IndexError", "(", ")" ]
Returns the word instance at the given position in the sentence, None if not found.
[ "Returns", "the", "word", "instance", "at", "the", "given", "position", "in", "the", "sentence", "None", "if", "not", "found", "." ]
535931a833203e5d9065072ec988c575b493d67f
https://github.com/klingtnet/sblgntparser/blob/535931a833203e5d9065072ec988c575b493d67f/sblgntparser/model.py#L79-L87
251,405
klingtnet/sblgntparser
sblgntparser/model.py
Word.neighbors
def neighbors(self): ''' Returns the left and right neighbors as Word instance. If the word is the first one in the sentence only the right neighbor is returned and vice versa. ''' if len(self._sentence) == 1: return { 'left': None, 'right': None } else: p = self._position if -1 < p < len(self._sentence): if 0 == self._position: return { 'left': None, 'right': self._sentence.word(p+1) } elif 0 < self._position < len(self._sentence) - 1: return { 'left': self._sentence.word(p-1), 'right': self._sentence.word(p+1) } else: return { 'left': self._sentence.word(p-1), 'right': None } else: raise IndexError()
python
def neighbors(self): ''' Returns the left and right neighbors as Word instance. If the word is the first one in the sentence only the right neighbor is returned and vice versa. ''' if len(self._sentence) == 1: return { 'left': None, 'right': None } else: p = self._position if -1 < p < len(self._sentence): if 0 == self._position: return { 'left': None, 'right': self._sentence.word(p+1) } elif 0 < self._position < len(self._sentence) - 1: return { 'left': self._sentence.word(p-1), 'right': self._sentence.word(p+1) } else: return { 'left': self._sentence.word(p-1), 'right': None } else: raise IndexError()
[ "def", "neighbors", "(", "self", ")", ":", "if", "len", "(", "self", ".", "_sentence", ")", "==", "1", ":", "return", "{", "'left'", ":", "None", ",", "'right'", ":", "None", "}", "else", ":", "p", "=", "self", ".", "_position", "if", "-", "1", "<", "p", "<", "len", "(", "self", ".", "_sentence", ")", ":", "if", "0", "==", "self", ".", "_position", ":", "return", "{", "'left'", ":", "None", ",", "'right'", ":", "self", ".", "_sentence", ".", "word", "(", "p", "+", "1", ")", "}", "elif", "0", "<", "self", ".", "_position", "<", "len", "(", "self", ".", "_sentence", ")", "-", "1", ":", "return", "{", "'left'", ":", "self", ".", "_sentence", ".", "word", "(", "p", "-", "1", ")", ",", "'right'", ":", "self", ".", "_sentence", ".", "word", "(", "p", "+", "1", ")", "}", "else", ":", "return", "{", "'left'", ":", "self", ".", "_sentence", ".", "word", "(", "p", "-", "1", ")", ",", "'right'", ":", "None", "}", "else", ":", "raise", "IndexError", "(", ")" ]
Returns the left and right neighbors as Word instance. If the word is the first one in the sentence only the right neighbor is returned and vice versa.
[ "Returns", "the", "left", "and", "right", "neighbors", "as", "Word", "instance", ".", "If", "the", "word", "is", "the", "first", "one", "in", "the", "sentence", "only", "the", "right", "neighbor", "is", "returned", "and", "vice", "versa", "." ]
535931a833203e5d9065072ec988c575b493d67f
https://github.com/klingtnet/sblgntparser/blob/535931a833203e5d9065072ec988c575b493d67f/sblgntparser/model.py#L139-L168
251,406
breuleux/hrepr
hrepr/__init__.py
HRepr.stdrepr_iterable
def stdrepr_iterable(self, obj, *, cls=None, before=None, after=None): """ Helper function to represent iterables. StdHRepr calls this on lists, tuples, sets and frozensets, but NOT on iterables in general. This method may be called to produce custom representations. Arguments: obj (iterable): The iterable to represent. cls (optional): The class name for the representation. If None, stdrepr will use ``'hrepr-' + obj.__class__.___name__`` before (optional): A string or a Tag to prepend to the elements. after (optional): A string or a Tag to append to the elements. """ if cls is None: cls = f'hrepr-{obj.__class__.__name__}' children = [self(a) for a in obj] return self.titled_box((before, after), children, 'h', 'h')[cls]
python
def stdrepr_iterable(self, obj, *, cls=None, before=None, after=None): """ Helper function to represent iterables. StdHRepr calls this on lists, tuples, sets and frozensets, but NOT on iterables in general. This method may be called to produce custom representations. Arguments: obj (iterable): The iterable to represent. cls (optional): The class name for the representation. If None, stdrepr will use ``'hrepr-' + obj.__class__.___name__`` before (optional): A string or a Tag to prepend to the elements. after (optional): A string or a Tag to append to the elements. """ if cls is None: cls = f'hrepr-{obj.__class__.__name__}' children = [self(a) for a in obj] return self.titled_box((before, after), children, 'h', 'h')[cls]
[ "def", "stdrepr_iterable", "(", "self", ",", "obj", ",", "*", ",", "cls", "=", "None", ",", "before", "=", "None", ",", "after", "=", "None", ")", ":", "if", "cls", "is", "None", ":", "cls", "=", "f'hrepr-{obj.__class__.__name__}'", "children", "=", "[", "self", "(", "a", ")", "for", "a", "in", "obj", "]", "return", "self", ".", "titled_box", "(", "(", "before", ",", "after", ")", ",", "children", ",", "'h'", ",", "'h'", ")", "[", "cls", "]" ]
Helper function to represent iterables. StdHRepr calls this on lists, tuples, sets and frozensets, but NOT on iterables in general. This method may be called to produce custom representations. Arguments: obj (iterable): The iterable to represent. cls (optional): The class name for the representation. If None, stdrepr will use ``'hrepr-' + obj.__class__.___name__`` before (optional): A string or a Tag to prepend to the elements. after (optional): A string or a Tag to append to the elements.
[ "Helper", "function", "to", "represent", "iterables", ".", "StdHRepr", "calls", "this", "on", "lists", "tuples", "sets", "and", "frozensets", "but", "NOT", "on", "iterables", "in", "general", ".", "This", "method", "may", "be", "called", "to", "produce", "custom", "representations", "." ]
a411395d31ac7c8c071d174e63a093751aa5997b
https://github.com/breuleux/hrepr/blob/a411395d31ac7c8c071d174e63a093751aa5997b/hrepr/__init__.py#L258-L275
251,407
breuleux/hrepr
hrepr/__init__.py
HRepr.stdrepr_object
def stdrepr_object(self, title, elements, *, cls=None, short=False, quote_string_keys=False, delimiter=None): """ Helper function to represent objects. Arguments: title: A title string displayed above the box containing the elements, or a pair of two strings that will be displayed left and right (e.g. a pair of brackets). elements: A list of (key, value) pairs, which will be displayed in a table in the order given. cls: A class to give to the result. short: Whether to use short or long form. Short form displays the elements as ``k=v``, appended horizontally. The alternative is a table, with associations stacked vertically. quote_string_keys: If True, string keys will be displayed with quotes around them. Default is False. delimiter: The character to use to separate key and value. By default '↦' if quote_string_keys is True. """ H = self.H if delimiter is None and quote_string_keys is True: delimiter = ' ↦ ' def wrap(x): if not quote_string_keys and isinstance(x, str): return x else: return self(x) if short: contents = [] for k, v in elements: kv = H.div['hrepr-object-kvpair']( wrap(k), delimiter or '', self(v) ) contents.append(kv) else: t = H.table()['hrepr-object-table'] for k, v in elements: tr = H.tr(H.td(wrap(k))) if delimiter is not None: tr = tr(H.td['hrepr-delimiter'](delimiter)) tr = tr(H.td(self(v))) # t = t(H.tr(H.td(wrap(k)), H.td(self(v)))) t = t(tr) contents = [t] title_brackets = isinstance(title, tuple) and len(title) == 2 horizontal = short or title_brackets rval = self.titled_box(title, contents, 'h' if title_brackets else 'v', 'h' if short else 'v') if cls: rval = rval[cls] return rval
python
def stdrepr_object(self, title, elements, *, cls=None, short=False, quote_string_keys=False, delimiter=None): """ Helper function to represent objects. Arguments: title: A title string displayed above the box containing the elements, or a pair of two strings that will be displayed left and right (e.g. a pair of brackets). elements: A list of (key, value) pairs, which will be displayed in a table in the order given. cls: A class to give to the result. short: Whether to use short or long form. Short form displays the elements as ``k=v``, appended horizontally. The alternative is a table, with associations stacked vertically. quote_string_keys: If True, string keys will be displayed with quotes around them. Default is False. delimiter: The character to use to separate key and value. By default '↦' if quote_string_keys is True. """ H = self.H if delimiter is None and quote_string_keys is True: delimiter = ' ↦ ' def wrap(x): if not quote_string_keys and isinstance(x, str): return x else: return self(x) if short: contents = [] for k, v in elements: kv = H.div['hrepr-object-kvpair']( wrap(k), delimiter or '', self(v) ) contents.append(kv) else: t = H.table()['hrepr-object-table'] for k, v in elements: tr = H.tr(H.td(wrap(k))) if delimiter is not None: tr = tr(H.td['hrepr-delimiter'](delimiter)) tr = tr(H.td(self(v))) # t = t(H.tr(H.td(wrap(k)), H.td(self(v)))) t = t(tr) contents = [t] title_brackets = isinstance(title, tuple) and len(title) == 2 horizontal = short or title_brackets rval = self.titled_box(title, contents, 'h' if title_brackets else 'v', 'h' if short else 'v') if cls: rval = rval[cls] return rval
[ "def", "stdrepr_object", "(", "self", ",", "title", ",", "elements", ",", "*", ",", "cls", "=", "None", ",", "short", "=", "False", ",", "quote_string_keys", "=", "False", ",", "delimiter", "=", "None", ")", ":", "H", "=", "self", ".", "H", "if", "delimiter", "is", "None", "and", "quote_string_keys", "is", "True", ":", "delimiter", "=", "' ↦ '", "def", "wrap", "(", "x", ")", ":", "if", "not", "quote_string_keys", "and", "isinstance", "(", "x", ",", "str", ")", ":", "return", "x", "else", ":", "return", "self", "(", "x", ")", "if", "short", ":", "contents", "=", "[", "]", "for", "k", ",", "v", "in", "elements", ":", "kv", "=", "H", ".", "div", "[", "'hrepr-object-kvpair'", "]", "(", "wrap", "(", "k", ")", ",", "delimiter", "or", "''", ",", "self", "(", "v", ")", ")", "contents", ".", "append", "(", "kv", ")", "else", ":", "t", "=", "H", ".", "table", "(", ")", "[", "'hrepr-object-table'", "]", "for", "k", ",", "v", "in", "elements", ":", "tr", "=", "H", ".", "tr", "(", "H", ".", "td", "(", "wrap", "(", "k", ")", ")", ")", "if", "delimiter", "is", "not", "None", ":", "tr", "=", "tr", "(", "H", ".", "td", "[", "'hrepr-delimiter'", "]", "(", "delimiter", ")", ")", "tr", "=", "tr", "(", "H", ".", "td", "(", "self", "(", "v", ")", ")", ")", "# t = t(H.tr(H.td(wrap(k)), H.td(self(v))))", "t", "=", "t", "(", "tr", ")", "contents", "=", "[", "t", "]", "title_brackets", "=", "isinstance", "(", "title", ",", "tuple", ")", "and", "len", "(", "title", ")", "==", "2", "horizontal", "=", "short", "or", "title_brackets", "rval", "=", "self", ".", "titled_box", "(", "title", ",", "contents", ",", "'h'", "if", "title_brackets", "else", "'v'", ",", "'h'", "if", "short", "else", "'v'", ")", "if", "cls", ":", "rval", "=", "rval", "[", "cls", "]", "return", "rval" ]
Helper function to represent objects. Arguments: title: A title string displayed above the box containing the elements, or a pair of two strings that will be displayed left and right (e.g. a pair of brackets). elements: A list of (key, value) pairs, which will be displayed in a table in the order given. cls: A class to give to the result. short: Whether to use short or long form. Short form displays the elements as ``k=v``, appended horizontally. The alternative is a table, with associations stacked vertically. quote_string_keys: If True, string keys will be displayed with quotes around them. Default is False. delimiter: The character to use to separate key and value. By default '↦' if quote_string_keys is True.
[ "Helper", "function", "to", "represent", "objects", "." ]
a411395d31ac7c8c071d174e63a093751aa5997b
https://github.com/breuleux/hrepr/blob/a411395d31ac7c8c071d174e63a093751aa5997b/hrepr/__init__.py#L277-L340
251,408
qzmfranklin/easyshell
easycompleter/fs.py
find_matches
def find_matches(text): r"""Find matching files for text. For this completer to function in Unix systems, the readline module must not treat \ and / as delimiters. """ path = os.path.expanduser(text) if os.path.isdir(path) and not path.endswith('/'): return [ text + '/' ] pattern = path + '*' is_implicit_cwd = not (path.startswith('/') or path.startswith('./')) if is_implicit_cwd: pattern = './' + pattern rawlist = glob.glob(pattern) ret = [] for fname in rawlist: if is_implicit_cwd: fname = fname[2:] if os.path.isdir(fname): ret.append(fname + '/') else: ret.append(fname) return ret
python
def find_matches(text): r"""Find matching files for text. For this completer to function in Unix systems, the readline module must not treat \ and / as delimiters. """ path = os.path.expanduser(text) if os.path.isdir(path) and not path.endswith('/'): return [ text + '/' ] pattern = path + '*' is_implicit_cwd = not (path.startswith('/') or path.startswith('./')) if is_implicit_cwd: pattern = './' + pattern rawlist = glob.glob(pattern) ret = [] for fname in rawlist: if is_implicit_cwd: fname = fname[2:] if os.path.isdir(fname): ret.append(fname + '/') else: ret.append(fname) return ret
[ "def", "find_matches", "(", "text", ")", ":", "path", "=", "os", ".", "path", ".", "expanduser", "(", "text", ")", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", "and", "not", "path", ".", "endswith", "(", "'/'", ")", ":", "return", "[", "text", "+", "'/'", "]", "pattern", "=", "path", "+", "'*'", "is_implicit_cwd", "=", "not", "(", "path", ".", "startswith", "(", "'/'", ")", "or", "path", ".", "startswith", "(", "'./'", ")", ")", "if", "is_implicit_cwd", ":", "pattern", "=", "'./'", "+", "pattern", "rawlist", "=", "glob", ".", "glob", "(", "pattern", ")", "ret", "=", "[", "]", "for", "fname", "in", "rawlist", ":", "if", "is_implicit_cwd", ":", "fname", "=", "fname", "[", "2", ":", "]", "if", "os", ".", "path", ".", "isdir", "(", "fname", ")", ":", "ret", ".", "append", "(", "fname", "+", "'/'", ")", "else", ":", "ret", ".", "append", "(", "fname", ")", "return", "ret" ]
r"""Find matching files for text. For this completer to function in Unix systems, the readline module must not treat \ and / as delimiters.
[ "r", "Find", "matching", "files", "for", "text", "." ]
00c2e90e7767d32e7e127fc8c6875845aa308295
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easycompleter/fs.py#L4-L27
251,409
FujiMakoto/IPS-Vagrant
ips_vagrant/commands/mysql/__init__.py
cli
def cli(ctx, dname, site): """ Launches a MySQL CLI session for the database of the specified IPS installation. """ assert isinstance(ctx, Context) log = logging.getLogger('ipsv.mysql') dname = domain_parse(dname).hostname domain = Session.query(Domain).filter(Domain.name == dname).first() # No such domain if not domain: click.secho('No such domain: {dn}'.format(dn=dname), fg='red', bold=True, err=True) return site_name = site site = Site.get(domain, site_name) # No such site if not site: click.secho('No such site: {site}'.format(site=site_name), fg='red', bold=True, err=True) return # Connect to the MySQL database and exit log.info('Connecting to MySQL database: {db}'.format(db=site.db_name)) log.debug('MySQL host: {host}'.format(host=site.db_host)) log.debug('MySQL username: {user}'.format(user=site.db_user)) log.debug('MySQL password: {pwd}'.format(pwd=site.db_pass)) os.execl( '/usr/bin/mysql', '/usr/bin/mysql', '--database={db}'.format(db=site.db_name), '--user={user}'.format(user=site.db_user), '--password={pwd}'.format(pwd=site.db_pass) )
python
def cli(ctx, dname, site): """ Launches a MySQL CLI session for the database of the specified IPS installation. """ assert isinstance(ctx, Context) log = logging.getLogger('ipsv.mysql') dname = domain_parse(dname).hostname domain = Session.query(Domain).filter(Domain.name == dname).first() # No such domain if not domain: click.secho('No such domain: {dn}'.format(dn=dname), fg='red', bold=True, err=True) return site_name = site site = Site.get(domain, site_name) # No such site if not site: click.secho('No such site: {site}'.format(site=site_name), fg='red', bold=True, err=True) return # Connect to the MySQL database and exit log.info('Connecting to MySQL database: {db}'.format(db=site.db_name)) log.debug('MySQL host: {host}'.format(host=site.db_host)) log.debug('MySQL username: {user}'.format(user=site.db_user)) log.debug('MySQL password: {pwd}'.format(pwd=site.db_pass)) os.execl( '/usr/bin/mysql', '/usr/bin/mysql', '--database={db}'.format(db=site.db_name), '--user={user}'.format(user=site.db_user), '--password={pwd}'.format(pwd=site.db_pass) )
[ "def", "cli", "(", "ctx", ",", "dname", ",", "site", ")", ":", "assert", "isinstance", "(", "ctx", ",", "Context", ")", "log", "=", "logging", ".", "getLogger", "(", "'ipsv.mysql'", ")", "dname", "=", "domain_parse", "(", "dname", ")", ".", "hostname", "domain", "=", "Session", ".", "query", "(", "Domain", ")", ".", "filter", "(", "Domain", ".", "name", "==", "dname", ")", ".", "first", "(", ")", "# No such domain", "if", "not", "domain", ":", "click", ".", "secho", "(", "'No such domain: {dn}'", ".", "format", "(", "dn", "=", "dname", ")", ",", "fg", "=", "'red'", ",", "bold", "=", "True", ",", "err", "=", "True", ")", "return", "site_name", "=", "site", "site", "=", "Site", ".", "get", "(", "domain", ",", "site_name", ")", "# No such site", "if", "not", "site", ":", "click", ".", "secho", "(", "'No such site: {site}'", ".", "format", "(", "site", "=", "site_name", ")", ",", "fg", "=", "'red'", ",", "bold", "=", "True", ",", "err", "=", "True", ")", "return", "# Connect to the MySQL database and exit", "log", ".", "info", "(", "'Connecting to MySQL database: {db}'", ".", "format", "(", "db", "=", "site", ".", "db_name", ")", ")", "log", ".", "debug", "(", "'MySQL host: {host}'", ".", "format", "(", "host", "=", "site", ".", "db_host", ")", ")", "log", ".", "debug", "(", "'MySQL username: {user}'", ".", "format", "(", "user", "=", "site", ".", "db_user", ")", ")", "log", ".", "debug", "(", "'MySQL password: {pwd}'", ".", "format", "(", "pwd", "=", "site", ".", "db_pass", ")", ")", "os", ".", "execl", "(", "'/usr/bin/mysql'", ",", "'/usr/bin/mysql'", ",", "'--database={db}'", ".", "format", "(", "db", "=", "site", ".", "db_name", ")", ",", "'--user={user}'", ".", "format", "(", "user", "=", "site", ".", "db_user", ")", ",", "'--password={pwd}'", ".", "format", "(", "pwd", "=", "site", ".", "db_pass", ")", ")" ]
Launches a MySQL CLI session for the database of the specified IPS installation.
[ "Launches", "a", "MySQL", "CLI", "session", "for", "the", "database", "of", "the", "specified", "IPS", "installation", "." ]
7b1d6d095034dd8befb026d9315ecc6494d52269
https://github.com/FujiMakoto/IPS-Vagrant/blob/7b1d6d095034dd8befb026d9315ecc6494d52269/ips_vagrant/commands/mysql/__init__.py#L14-L49
251,410
ramrod-project/database-brain
schema/brain/telemetry/reads.py
target_query
def target_query(plugin, port, location): """ prepared ReQL for target """ return ((r.row[PLUGIN_NAME_KEY] == plugin) & (r.row[PORT_FIELD] == port) & (r.row[LOCATION_FIELD] == location))
python
def target_query(plugin, port, location): """ prepared ReQL for target """ return ((r.row[PLUGIN_NAME_KEY] == plugin) & (r.row[PORT_FIELD] == port) & (r.row[LOCATION_FIELD] == location))
[ "def", "target_query", "(", "plugin", ",", "port", ",", "location", ")", ":", "return", "(", "(", "r", ".", "row", "[", "PLUGIN_NAME_KEY", "]", "==", "plugin", ")", "&", "(", "r", ".", "row", "[", "PORT_FIELD", "]", "==", "port", ")", "&", "(", "r", ".", "row", "[", "LOCATION_FIELD", "]", "==", "location", ")", ")" ]
prepared ReQL for target
[ "prepared", "ReQL", "for", "target" ]
b024cb44f34cabb9d80af38271ddb65c25767083
https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/telemetry/reads.py#L10-L16
251,411
eallik/spinoff
spinoff/util/python.py
enums
def enums(*names): """Returns a set of `EnumValue` objects with specified names and optionally orders. Values in an enumeration must have unique names and be either all ordered or all unordered. """ if len(names) != len(list(set(names))): raise TypeError("Names in an enumeration must be unique") item_types = set(True if isinstance(x, tuple) else False for x in names) if len(item_types) == 2: raise TypeError("Mixing of ordered and unordered enumeration items is not allowed") else: is_ordered = item_types.pop() is True if not is_ordered: names = [(None, x) for x in names] return [EnumValue(name, order) for order, name in names]
python
def enums(*names): """Returns a set of `EnumValue` objects with specified names and optionally orders. Values in an enumeration must have unique names and be either all ordered or all unordered. """ if len(names) != len(list(set(names))): raise TypeError("Names in an enumeration must be unique") item_types = set(True if isinstance(x, tuple) else False for x in names) if len(item_types) == 2: raise TypeError("Mixing of ordered and unordered enumeration items is not allowed") else: is_ordered = item_types.pop() is True if not is_ordered: names = [(None, x) for x in names] return [EnumValue(name, order) for order, name in names]
[ "def", "enums", "(", "*", "names", ")", ":", "if", "len", "(", "names", ")", "!=", "len", "(", "list", "(", "set", "(", "names", ")", ")", ")", ":", "raise", "TypeError", "(", "\"Names in an enumeration must be unique\"", ")", "item_types", "=", "set", "(", "True", "if", "isinstance", "(", "x", ",", "tuple", ")", "else", "False", "for", "x", "in", "names", ")", "if", "len", "(", "item_types", ")", "==", "2", ":", "raise", "TypeError", "(", "\"Mixing of ordered and unordered enumeration items is not allowed\"", ")", "else", ":", "is_ordered", "=", "item_types", ".", "pop", "(", ")", "is", "True", "if", "not", "is_ordered", ":", "names", "=", "[", "(", "None", ",", "x", ")", "for", "x", "in", "names", "]", "return", "[", "EnumValue", "(", "name", ",", "order", ")", "for", "order", ",", "name", "in", "names", "]" ]
Returns a set of `EnumValue` objects with specified names and optionally orders. Values in an enumeration must have unique names and be either all ordered or all unordered.
[ "Returns", "a", "set", "of", "EnumValue", "objects", "with", "specified", "names", "and", "optionally", "orders", "." ]
06b00d6b86c7422c9cb8f9a4b2915906e92b7d52
https://github.com/eallik/spinoff/blob/06b00d6b86c7422c9cb8f9a4b2915906e92b7d52/spinoff/util/python.py#L45-L61
251,412
looplab/skal
skal/core.py
SkalApp.run
def run(self, args=None): """Applicatin starting point. This will run the associated method/function/module or print a help list if it's an unknown keyword or the syntax is incorrect. Keyword arguments: args -- Custom application arguments (default sys.argv) """ # TODO: Add tests to how command line arguments are passed in raw_args = self.__parser.parse_args(args=args) args = vars(raw_args) cmd = args.pop('cmd') if hasattr(cmd, '__call__'): cmd(**args)
python
def run(self, args=None): """Applicatin starting point. This will run the associated method/function/module or print a help list if it's an unknown keyword or the syntax is incorrect. Keyword arguments: args -- Custom application arguments (default sys.argv) """ # TODO: Add tests to how command line arguments are passed in raw_args = self.__parser.parse_args(args=args) args = vars(raw_args) cmd = args.pop('cmd') if hasattr(cmd, '__call__'): cmd(**args)
[ "def", "run", "(", "self", ",", "args", "=", "None", ")", ":", "# TODO: Add tests to how command line arguments are passed in", "raw_args", "=", "self", ".", "__parser", ".", "parse_args", "(", "args", "=", "args", ")", "args", "=", "vars", "(", "raw_args", ")", "cmd", "=", "args", ".", "pop", "(", "'cmd'", ")", "if", "hasattr", "(", "cmd", ",", "'__call__'", ")", ":", "cmd", "(", "*", "*", "args", ")" ]
Applicatin starting point. This will run the associated method/function/module or print a help list if it's an unknown keyword or the syntax is incorrect. Keyword arguments: args -- Custom application arguments (default sys.argv)
[ "Applicatin", "starting", "point", "." ]
af2ce460d9addd07ad2459125511308cfa7cdb44
https://github.com/looplab/skal/blob/af2ce460d9addd07ad2459125511308cfa7cdb44/skal/core.py#L108-L123
251,413
fordhurley/s3url
s3url/time.py
to_seconds
def to_seconds(string): """ Converts a human readable time string into seconds. Accepts: - 's': seconds - 'm': minutes - 'h': hours - 'd': days Examples: >>> to_seconds('1m30s') 90 >>> to_seconds('5m') 300 >>> to_seconds('1h') 3600 >>> to_seconds('1h30m') 5400 >>> to_seconds('3d') 259200 >>> to_seconds('42x') Traceback (most recent call last): ... ValueError """ units = { 's': 1, 'm': 60, 'h': 60 * 60, 'd': 60 * 60 * 24 } match = re.search(r'(?:(?P<d>\d+)d)?(?:(?P<h>\d+)h)?(?:(?P<m>\d+)m)?(?:(?P<s>\d+)s)?', string) if not match or not any(match.groups()): raise ValueError total = 0 for unit, seconds in units.iteritems(): if match.group(unit) is not None: total += int(match.group(unit)) * seconds return total
python
def to_seconds(string): """ Converts a human readable time string into seconds. Accepts: - 's': seconds - 'm': minutes - 'h': hours - 'd': days Examples: >>> to_seconds('1m30s') 90 >>> to_seconds('5m') 300 >>> to_seconds('1h') 3600 >>> to_seconds('1h30m') 5400 >>> to_seconds('3d') 259200 >>> to_seconds('42x') Traceback (most recent call last): ... ValueError """ units = { 's': 1, 'm': 60, 'h': 60 * 60, 'd': 60 * 60 * 24 } match = re.search(r'(?:(?P<d>\d+)d)?(?:(?P<h>\d+)h)?(?:(?P<m>\d+)m)?(?:(?P<s>\d+)s)?', string) if not match or not any(match.groups()): raise ValueError total = 0 for unit, seconds in units.iteritems(): if match.group(unit) is not None: total += int(match.group(unit)) * seconds return total
[ "def", "to_seconds", "(", "string", ")", ":", "units", "=", "{", "'s'", ":", "1", ",", "'m'", ":", "60", ",", "'h'", ":", "60", "*", "60", ",", "'d'", ":", "60", "*", "60", "*", "24", "}", "match", "=", "re", ".", "search", "(", "r'(?:(?P<d>\\d+)d)?(?:(?P<h>\\d+)h)?(?:(?P<m>\\d+)m)?(?:(?P<s>\\d+)s)?'", ",", "string", ")", "if", "not", "match", "or", "not", "any", "(", "match", ".", "groups", "(", ")", ")", ":", "raise", "ValueError", "total", "=", "0", "for", "unit", ",", "seconds", "in", "units", ".", "iteritems", "(", ")", ":", "if", "match", ".", "group", "(", "unit", ")", "is", "not", "None", ":", "total", "+=", "int", "(", "match", ".", "group", "(", "unit", ")", ")", "*", "seconds", "return", "total" ]
Converts a human readable time string into seconds. Accepts: - 's': seconds - 'm': minutes - 'h': hours - 'd': days Examples: >>> to_seconds('1m30s') 90 >>> to_seconds('5m') 300 >>> to_seconds('1h') 3600 >>> to_seconds('1h30m') 5400 >>> to_seconds('3d') 259200 >>> to_seconds('42x') Traceback (most recent call last): ... ValueError
[ "Converts", "a", "human", "readable", "time", "string", "into", "seconds", "." ]
a9e932308ee1bc70a4626ff0a28575cd6927ea33
https://github.com/fordhurley/s3url/blob/a9e932308ee1bc70a4626ff0a28575cd6927ea33/s3url/time.py#L11-L55
251,414
KelSolaar/Oncilla
oncilla/slice_reStructuredText.py
slice_reStructuredText
def slice_reStructuredText(input, output): """ Slices given reStructuredText file. :param input: ReStructuredText file to slice. :type input: unicode :param output: Directory to output sliced reStructuredText files. :type output: unicode :return: Definition success. :rtype: bool """ LOGGER.info("{0} | Slicing '{1}' file!".format(slice_reStructuredText.__name__, input)) file = File(input) file.cache() slices = OrderedDict() for i, line in enumerate(file.content): search = re.search(r"^\.\. \.(\w+)", line) if search: slices[search.groups()[0]] = i + SLICE_ATTRIBUTE_INDENT index = 0 for slice, slice_start in slices.iteritems(): slice_file = File(os.path.join(output, "{0}.{1}".format(slice, OUTPUT_FILES_EXTENSION))) LOGGER.info("{0} | Outputing '{1}' file!".format(slice_reStructuredText.__name__, slice_file.path)) slice_end = index < (len(slices.values()) - 1) and slices.values()[index + 1] - SLICE_ATTRIBUTE_INDENT or \ len(file.content) for i in range(slice_start, slice_end): skip_line = False for item in CONTENT_DELETION: if re.search(item, file.content[i]): LOGGER.info("{0} | Skipping Line '{1}' with '{2}' content!".format(slice_reStructuredText.__name__, i, item)) skip_line = True break if skip_line: continue line = file.content[i] for pattern, value in STATEMENT_SUBSTITUTE.iteritems(): line = re.sub(pattern, value, line) search = re.search(r"- `[\w ]+`_ \(([\w\.]+)\)", line) if search: LOGGER.info("{0} | Updating Line '{1}' link: '{2}'!".format(slice_reStructuredText.__name__, i, search.groups()[0])) line = "- :ref:`{0}`\n".format(search.groups()[0]) slice_file.content.append(line) slice_file.write() index += 1 return True
python
def slice_reStructuredText(input, output): """ Slices given reStructuredText file. :param input: ReStructuredText file to slice. :type input: unicode :param output: Directory to output sliced reStructuredText files. :type output: unicode :return: Definition success. :rtype: bool """ LOGGER.info("{0} | Slicing '{1}' file!".format(slice_reStructuredText.__name__, input)) file = File(input) file.cache() slices = OrderedDict() for i, line in enumerate(file.content): search = re.search(r"^\.\. \.(\w+)", line) if search: slices[search.groups()[0]] = i + SLICE_ATTRIBUTE_INDENT index = 0 for slice, slice_start in slices.iteritems(): slice_file = File(os.path.join(output, "{0}.{1}".format(slice, OUTPUT_FILES_EXTENSION))) LOGGER.info("{0} | Outputing '{1}' file!".format(slice_reStructuredText.__name__, slice_file.path)) slice_end = index < (len(slices.values()) - 1) and slices.values()[index + 1] - SLICE_ATTRIBUTE_INDENT or \ len(file.content) for i in range(slice_start, slice_end): skip_line = False for item in CONTENT_DELETION: if re.search(item, file.content[i]): LOGGER.info("{0} | Skipping Line '{1}' with '{2}' content!".format(slice_reStructuredText.__name__, i, item)) skip_line = True break if skip_line: continue line = file.content[i] for pattern, value in STATEMENT_SUBSTITUTE.iteritems(): line = re.sub(pattern, value, line) search = re.search(r"- `[\w ]+`_ \(([\w\.]+)\)", line) if search: LOGGER.info("{0} | Updating Line '{1}' link: '{2}'!".format(slice_reStructuredText.__name__, i, search.groups()[0])) line = "- :ref:`{0}`\n".format(search.groups()[0]) slice_file.content.append(line) slice_file.write() index += 1 return True
[ "def", "slice_reStructuredText", "(", "input", ",", "output", ")", ":", "LOGGER", ".", "info", "(", "\"{0} | Slicing '{1}' file!\"", ".", "format", "(", "slice_reStructuredText", ".", "__name__", ",", "input", ")", ")", "file", "=", "File", "(", "input", ")", "file", ".", "cache", "(", ")", "slices", "=", "OrderedDict", "(", ")", "for", "i", ",", "line", "in", "enumerate", "(", "file", ".", "content", ")", ":", "search", "=", "re", ".", "search", "(", "r\"^\\.\\. \\.(\\w+)\"", ",", "line", ")", "if", "search", ":", "slices", "[", "search", ".", "groups", "(", ")", "[", "0", "]", "]", "=", "i", "+", "SLICE_ATTRIBUTE_INDENT", "index", "=", "0", "for", "slice", ",", "slice_start", "in", "slices", ".", "iteritems", "(", ")", ":", "slice_file", "=", "File", "(", "os", ".", "path", ".", "join", "(", "output", ",", "\"{0}.{1}\"", ".", "format", "(", "slice", ",", "OUTPUT_FILES_EXTENSION", ")", ")", ")", "LOGGER", ".", "info", "(", "\"{0} | Outputing '{1}' file!\"", ".", "format", "(", "slice_reStructuredText", ".", "__name__", ",", "slice_file", ".", "path", ")", ")", "slice_end", "=", "index", "<", "(", "len", "(", "slices", ".", "values", "(", ")", ")", "-", "1", ")", "and", "slices", ".", "values", "(", ")", "[", "index", "+", "1", "]", "-", "SLICE_ATTRIBUTE_INDENT", "or", "len", "(", "file", ".", "content", ")", "for", "i", "in", "range", "(", "slice_start", ",", "slice_end", ")", ":", "skip_line", "=", "False", "for", "item", "in", "CONTENT_DELETION", ":", "if", "re", ".", "search", "(", "item", ",", "file", ".", "content", "[", "i", "]", ")", ":", "LOGGER", ".", "info", "(", "\"{0} | Skipping Line '{1}' with '{2}' content!\"", ".", "format", "(", "slice_reStructuredText", ".", "__name__", ",", "i", ",", "item", ")", ")", "skip_line", "=", "True", "break", "if", "skip_line", ":", "continue", "line", "=", "file", ".", "content", "[", "i", "]", "for", "pattern", ",", "value", "in", "STATEMENT_SUBSTITUTE", ".", "iteritems", "(", ")", ":", "line", "=", "re", ".", "sub", "(", "pattern", ",", "value", ",", "line", ")", "search", "=", "re", ".", "search", "(", "r\"- `[\\w ]+`_ \\(([\\w\\.]+)\\)\"", ",", "line", ")", "if", "search", ":", "LOGGER", ".", "info", "(", "\"{0} | Updating Line '{1}' link: '{2}'!\"", ".", "format", "(", "slice_reStructuredText", ".", "__name__", ",", "i", ",", "search", ".", "groups", "(", ")", "[", "0", "]", ")", ")", "line", "=", "\"- :ref:`{0}`\\n\"", ".", "format", "(", "search", ".", "groups", "(", ")", "[", "0", "]", ")", "slice_file", ".", "content", ".", "append", "(", "line", ")", "slice_file", ".", "write", "(", ")", "index", "+=", "1", "return", "True" ]
Slices given reStructuredText file. :param input: ReStructuredText file to slice. :type input: unicode :param output: Directory to output sliced reStructuredText files. :type output: unicode :return: Definition success. :rtype: bool
[ "Slices", "given", "reStructuredText", "file", "." ]
2b4db3704cf2c22a09a207681cb041fff555a994
https://github.com/KelSolaar/Oncilla/blob/2b4db3704cf2c22a09a207681cb041fff555a994/oncilla/slice_reStructuredText.py#L61-L118
251,415
FujiMakoto/IPS-Vagrant
ips_vagrant/scrapers/licenses.py
Licenses.get
def get(self): """ Fetch all licenses associated with our account @rtype: list of LicenseMeta """ response = requests.get(self.URL, cookies=self.cookiejar) self.log.debug('Response code: %s', response.status_code) if response.status_code != 200: raise HtmlParserError soup = BeautifulSoup(response.text, "html.parser") com_pattern = re.compile('\((.+)\)') package_list = soup.find('ul', {'id': 'package_list'}) package_items = package_list.find_all('li') licenses = [] for item in package_items: div = item.find('div', {'class': 'product_info'}) a = div.find('a') licenses.append( LicenseMeta( div.find('span', {'class': 'desc'}).text, a.get('href'), com_pattern.search(a.text).group(1) ) ) return licenses
python
def get(self): """ Fetch all licenses associated with our account @rtype: list of LicenseMeta """ response = requests.get(self.URL, cookies=self.cookiejar) self.log.debug('Response code: %s', response.status_code) if response.status_code != 200: raise HtmlParserError soup = BeautifulSoup(response.text, "html.parser") com_pattern = re.compile('\((.+)\)') package_list = soup.find('ul', {'id': 'package_list'}) package_items = package_list.find_all('li') licenses = [] for item in package_items: div = item.find('div', {'class': 'product_info'}) a = div.find('a') licenses.append( LicenseMeta( div.find('span', {'class': 'desc'}).text, a.get('href'), com_pattern.search(a.text).group(1) ) ) return licenses
[ "def", "get", "(", "self", ")", ":", "response", "=", "requests", ".", "get", "(", "self", ".", "URL", ",", "cookies", "=", "self", ".", "cookiejar", ")", "self", ".", "log", ".", "debug", "(", "'Response code: %s'", ",", "response", ".", "status_code", ")", "if", "response", ".", "status_code", "!=", "200", ":", "raise", "HtmlParserError", "soup", "=", "BeautifulSoup", "(", "response", ".", "text", ",", "\"html.parser\"", ")", "com_pattern", "=", "re", ".", "compile", "(", "'\\((.+)\\)'", ")", "package_list", "=", "soup", ".", "find", "(", "'ul'", ",", "{", "'id'", ":", "'package_list'", "}", ")", "package_items", "=", "package_list", ".", "find_all", "(", "'li'", ")", "licenses", "=", "[", "]", "for", "item", "in", "package_items", ":", "div", "=", "item", ".", "find", "(", "'div'", ",", "{", "'class'", ":", "'product_info'", "}", ")", "a", "=", "div", ".", "find", "(", "'a'", ")", "licenses", ".", "append", "(", "LicenseMeta", "(", "div", ".", "find", "(", "'span'", ",", "{", "'class'", ":", "'desc'", "}", ")", ".", "text", ",", "a", ".", "get", "(", "'href'", ")", ",", "com_pattern", ".", "search", "(", "a", ".", "text", ")", ".", "group", "(", "1", ")", ")", ")", "return", "licenses" ]
Fetch all licenses associated with our account @rtype: list of LicenseMeta
[ "Fetch", "all", "licenses", "associated", "with", "our", "account" ]
7b1d6d095034dd8befb026d9315ecc6494d52269
https://github.com/FujiMakoto/IPS-Vagrant/blob/7b1d6d095034dd8befb026d9315ecc6494d52269/ips_vagrant/scrapers/licenses.py#L22-L50
251,416
uw-it-aca/uw-restclients-sdbmyuw
uw_sdbmyuw/__init__.py
get_app_status
def get_app_status(system_key): """ Get Undergraduate application status @return ApplicationStatus object @InvalidSystemKey if system_key is not valid """ if invalid_system_key(system_key): raise InvalidSystemKey( "Invalid system key in get_app_status({})".format(system_key)) url = get_appstatus_url(system_key) response = DAO.getURL(url, {}) response_data = str(response.data) if response.status != 200: raise DataFailureException(url, response.status, response_data) if len(response.data) == 0: is_cached = (type(response) == restclients_core.models.MockHttp) raise Exception( "{} Unexpected Response Data: {}, from cache: {}".format( url, response_data, str(is_cached))) status = parse_statuses(response_data) return status
python
def get_app_status(system_key): """ Get Undergraduate application status @return ApplicationStatus object @InvalidSystemKey if system_key is not valid """ if invalid_system_key(system_key): raise InvalidSystemKey( "Invalid system key in get_app_status({})".format(system_key)) url = get_appstatus_url(system_key) response = DAO.getURL(url, {}) response_data = str(response.data) if response.status != 200: raise DataFailureException(url, response.status, response_data) if len(response.data) == 0: is_cached = (type(response) == restclients_core.models.MockHttp) raise Exception( "{} Unexpected Response Data: {}, from cache: {}".format( url, response_data, str(is_cached))) status = parse_statuses(response_data) return status
[ "def", "get_app_status", "(", "system_key", ")", ":", "if", "invalid_system_key", "(", "system_key", ")", ":", "raise", "InvalidSystemKey", "(", "\"Invalid system key in get_app_status({})\"", ".", "format", "(", "system_key", ")", ")", "url", "=", "get_appstatus_url", "(", "system_key", ")", "response", "=", "DAO", ".", "getURL", "(", "url", ",", "{", "}", ")", "response_data", "=", "str", "(", "response", ".", "data", ")", "if", "response", ".", "status", "!=", "200", ":", "raise", "DataFailureException", "(", "url", ",", "response", ".", "status", ",", "response_data", ")", "if", "len", "(", "response", ".", "data", ")", "==", "0", ":", "is_cached", "=", "(", "type", "(", "response", ")", "==", "restclients_core", ".", "models", ".", "MockHttp", ")", "raise", "Exception", "(", "\"{} Unexpected Response Data: {}, from cache: {}\"", ".", "format", "(", "url", ",", "response_data", ",", "str", "(", "is_cached", ")", ")", ")", "status", "=", "parse_statuses", "(", "response_data", ")", "return", "status" ]
Get Undergraduate application status @return ApplicationStatus object @InvalidSystemKey if system_key is not valid
[ "Get", "Undergraduate", "application", "status" ]
b54317f8bcff1fd226a91e085fd6fe59757db07c
https://github.com/uw-it-aca/uw-restclients-sdbmyuw/blob/b54317f8bcff1fd226a91e085fd6fe59757db07c/uw_sdbmyuw/__init__.py#L17-L40
251,417
fedora-infra/fmn.lib
fmn/lib/hinting.py
hint
def hint(invertible=True, callable=None, **hints): """ A decorator that can optionally hang datanommer hints on a rule. """ def wrapper(fn): # Hang hints on fn. fn.hints = hints fn.hinting_invertible = invertible fn.hinting_callable = callable return fn return wrapper
python
def hint(invertible=True, callable=None, **hints): """ A decorator that can optionally hang datanommer hints on a rule. """ def wrapper(fn): # Hang hints on fn. fn.hints = hints fn.hinting_invertible = invertible fn.hinting_callable = callable return fn return wrapper
[ "def", "hint", "(", "invertible", "=", "True", ",", "callable", "=", "None", ",", "*", "*", "hints", ")", ":", "def", "wrapper", "(", "fn", ")", ":", "# Hang hints on fn.", "fn", ".", "hints", "=", "hints", "fn", ".", "hinting_invertible", "=", "invertible", "fn", ".", "hinting_callable", "=", "callable", "return", "fn", "return", "wrapper" ]
A decorator that can optionally hang datanommer hints on a rule.
[ "A", "decorator", "that", "can", "optionally", "hang", "datanommer", "hints", "on", "a", "rule", "." ]
3120725556153d07c1809530f0fadcf250439110
https://github.com/fedora-infra/fmn.lib/blob/3120725556153d07c1809530f0fadcf250439110/fmn/lib/hinting.py#L25-L35
251,418
fedora-infra/fmn.lib
fmn/lib/hinting.py
gather_hinting
def gather_hinting(config, rules, valid_paths): """ Construct hint arguments for datanommer from a list of rules. """ hinting = collections.defaultdict(list) for rule in rules: root, name = rule.code_path.split(':', 1) info = valid_paths[root][name] if info['hints-callable']: # Call the callable hint to get its values result = info['hints-callable'](config=config, **rule.arguments) # If the rule is inverted, but the hint is not invertible, then # there is no hinting we can provide. Carry on. if rule.negated and not info['hints-invertible']: continue for key, values in result.items(): # Negate the hint if necessary key = 'not_' + key if rule.negated else key hinting[key].extend(values) # Then, finish off with all the other ordinary, non-callable hints for key, value in info['datanommer-hints'].items(): # If the rule is inverted, but the hint is not invertible, then # there is no hinting we can provide. Carry on. if rule.negated and not info['hints-invertible']: continue # Otherwise, construct the inverse hint if necessary key = 'not_' + key if rule.negated else key # And tack it on. hinting[key] += value log.debug('gathered hinting %r', hinting) return hinting
python
def gather_hinting(config, rules, valid_paths): """ Construct hint arguments for datanommer from a list of rules. """ hinting = collections.defaultdict(list) for rule in rules: root, name = rule.code_path.split(':', 1) info = valid_paths[root][name] if info['hints-callable']: # Call the callable hint to get its values result = info['hints-callable'](config=config, **rule.arguments) # If the rule is inverted, but the hint is not invertible, then # there is no hinting we can provide. Carry on. if rule.negated and not info['hints-invertible']: continue for key, values in result.items(): # Negate the hint if necessary key = 'not_' + key if rule.negated else key hinting[key].extend(values) # Then, finish off with all the other ordinary, non-callable hints for key, value in info['datanommer-hints'].items(): # If the rule is inverted, but the hint is not invertible, then # there is no hinting we can provide. Carry on. if rule.negated and not info['hints-invertible']: continue # Otherwise, construct the inverse hint if necessary key = 'not_' + key if rule.negated else key # And tack it on. hinting[key] += value log.debug('gathered hinting %r', hinting) return hinting
[ "def", "gather_hinting", "(", "config", ",", "rules", ",", "valid_paths", ")", ":", "hinting", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "rule", "in", "rules", ":", "root", ",", "name", "=", "rule", ".", "code_path", ".", "split", "(", "':'", ",", "1", ")", "info", "=", "valid_paths", "[", "root", "]", "[", "name", "]", "if", "info", "[", "'hints-callable'", "]", ":", "# Call the callable hint to get its values", "result", "=", "info", "[", "'hints-callable'", "]", "(", "config", "=", "config", ",", "*", "*", "rule", ".", "arguments", ")", "# If the rule is inverted, but the hint is not invertible, then", "# there is no hinting we can provide. Carry on.", "if", "rule", ".", "negated", "and", "not", "info", "[", "'hints-invertible'", "]", ":", "continue", "for", "key", ",", "values", "in", "result", ".", "items", "(", ")", ":", "# Negate the hint if necessary", "key", "=", "'not_'", "+", "key", "if", "rule", ".", "negated", "else", "key", "hinting", "[", "key", "]", ".", "extend", "(", "values", ")", "# Then, finish off with all the other ordinary, non-callable hints", "for", "key", ",", "value", "in", "info", "[", "'datanommer-hints'", "]", ".", "items", "(", ")", ":", "# If the rule is inverted, but the hint is not invertible, then", "# there is no hinting we can provide. Carry on.", "if", "rule", ".", "negated", "and", "not", "info", "[", "'hints-invertible'", "]", ":", "continue", "# Otherwise, construct the inverse hint if necessary", "key", "=", "'not_'", "+", "key", "if", "rule", ".", "negated", "else", "key", "# And tack it on.", "hinting", "[", "key", "]", "+=", "value", "log", ".", "debug", "(", "'gathered hinting %r'", ",", "hinting", ")", "return", "hinting" ]
Construct hint arguments for datanommer from a list of rules.
[ "Construct", "hint", "arguments", "for", "datanommer", "from", "a", "list", "of", "rules", "." ]
3120725556153d07c1809530f0fadcf250439110
https://github.com/fedora-infra/fmn.lib/blob/3120725556153d07c1809530f0fadcf250439110/fmn/lib/hinting.py#L43-L81
251,419
roedesh/django-xfeed
xfeed/templatetags/xfeed_tags.py
generate_feed_list
def generate_feed_list(feed, amount=None, list_class=None, li_class=None, list_type='ul'): """Generates a HTML list with items from a feed :param feed: The feed to generate the list from. :type feed: Feed :param amount: The amount of items to show. :type amount: int :param ul_class: The <ul> or <ol> class to use. :type ul_class: str :param li_class: The <li> class to use. :type li_class: str :param list_type: The list type to use. Defaults to 'ul' :type list_type: str :raises: ValueError """ if feed.feed_type == 'twitter': ret = ['<%s class="%s">' % (list_type, list_class or 'tweet-list')] tweets = feed.tweets.all() if amount: if not int(amount): raise ValueError('Amount must be a number') tweets = tweets[:amount] for t in tweets: ret.append( '<li class="%s">' '<div class="tweet-profile-picture">' '<img src="%s" alt="Twitter profile picture of %s" width="48" height="48" /></div>' '<div class="tweet-body">%s</div></li>' % (li_class or 'tweet', t.profile_image_url, t.from_user_name, t.text)) if feed.feed_type == 'rss': ret = ['<%s class="%s">' % (list_type, list_class or 'rss-list')] rss_items = feed.rss_items.all() if amount: if not int(amount): raise ValueError('Amount must be a number') rss_items = rss_items[:amount] for t in rss_items: ret.append( '<li class="%s">' '<div class="rss-item-body">%s</div></li>' % (li_class or 'rss-item', t.description)) ret.append('</%s>' % list_type) return ''.join(ret)
python
def generate_feed_list(feed, amount=None, list_class=None, li_class=None, list_type='ul'): """Generates a HTML list with items from a feed :param feed: The feed to generate the list from. :type feed: Feed :param amount: The amount of items to show. :type amount: int :param ul_class: The <ul> or <ol> class to use. :type ul_class: str :param li_class: The <li> class to use. :type li_class: str :param list_type: The list type to use. Defaults to 'ul' :type list_type: str :raises: ValueError """ if feed.feed_type == 'twitter': ret = ['<%s class="%s">' % (list_type, list_class or 'tweet-list')] tweets = feed.tweets.all() if amount: if not int(amount): raise ValueError('Amount must be a number') tweets = tweets[:amount] for t in tweets: ret.append( '<li class="%s">' '<div class="tweet-profile-picture">' '<img src="%s" alt="Twitter profile picture of %s" width="48" height="48" /></div>' '<div class="tweet-body">%s</div></li>' % (li_class or 'tweet', t.profile_image_url, t.from_user_name, t.text)) if feed.feed_type == 'rss': ret = ['<%s class="%s">' % (list_type, list_class or 'rss-list')] rss_items = feed.rss_items.all() if amount: if not int(amount): raise ValueError('Amount must be a number') rss_items = rss_items[:amount] for t in rss_items: ret.append( '<li class="%s">' '<div class="rss-item-body">%s</div></li>' % (li_class or 'rss-item', t.description)) ret.append('</%s>' % list_type) return ''.join(ret)
[ "def", "generate_feed_list", "(", "feed", ",", "amount", "=", "None", ",", "list_class", "=", "None", ",", "li_class", "=", "None", ",", "list_type", "=", "'ul'", ")", ":", "if", "feed", ".", "feed_type", "==", "'twitter'", ":", "ret", "=", "[", "'<%s class=\"%s\">'", "%", "(", "list_type", ",", "list_class", "or", "'tweet-list'", ")", "]", "tweets", "=", "feed", ".", "tweets", ".", "all", "(", ")", "if", "amount", ":", "if", "not", "int", "(", "amount", ")", ":", "raise", "ValueError", "(", "'Amount must be a number'", ")", "tweets", "=", "tweets", "[", ":", "amount", "]", "for", "t", "in", "tweets", ":", "ret", ".", "append", "(", "'<li class=\"%s\">'", "'<div class=\"tweet-profile-picture\">'", "'<img src=\"%s\" alt=\"Twitter profile picture of %s\" width=\"48\" height=\"48\" /></div>'", "'<div class=\"tweet-body\">%s</div></li>'", "%", "(", "li_class", "or", "'tweet'", ",", "t", ".", "profile_image_url", ",", "t", ".", "from_user_name", ",", "t", ".", "text", ")", ")", "if", "feed", ".", "feed_type", "==", "'rss'", ":", "ret", "=", "[", "'<%s class=\"%s\">'", "%", "(", "list_type", ",", "list_class", "or", "'rss-list'", ")", "]", "rss_items", "=", "feed", ".", "rss_items", ".", "all", "(", ")", "if", "amount", ":", "if", "not", "int", "(", "amount", ")", ":", "raise", "ValueError", "(", "'Amount must be a number'", ")", "rss_items", "=", "rss_items", "[", ":", "amount", "]", "for", "t", "in", "rss_items", ":", "ret", ".", "append", "(", "'<li class=\"%s\">'", "'<div class=\"rss-item-body\">%s</div></li>'", "%", "(", "li_class", "or", "'rss-item'", ",", "t", ".", "description", ")", ")", "ret", ".", "append", "(", "'</%s>'", "%", "list_type", ")", "return", "''", ".", "join", "(", "ret", ")" ]
Generates a HTML list with items from a feed :param feed: The feed to generate the list from. :type feed: Feed :param amount: The amount of items to show. :type amount: int :param ul_class: The <ul> or <ol> class to use. :type ul_class: str :param li_class: The <li> class to use. :type li_class: str :param list_type: The list type to use. Defaults to 'ul' :type list_type: str :raises: ValueError
[ "Generates", "a", "HTML", "list", "with", "items", "from", "a", "feed" ]
e4f1e4a6e476c06ea461e4c4c12e98230a61bdfc
https://github.com/roedesh/django-xfeed/blob/e4f1e4a6e476c06ea461e4c4c12e98230a61bdfc/xfeed/templatetags/xfeed_tags.py#L6-L47
251,420
dstufft/storages
storages/core.py
chunks
def chunks(f, chunk_size=None): """ Read the file and yield chucks of ``chunk_size`` bytes. """ if not chunk_size: chunk_size = 64 * 2 ** 10 if hasattr(f, "seek"): f.seek(0) while True: data = f.read(chunk_size) if not data: break yield data
python
def chunks(f, chunk_size=None): """ Read the file and yield chucks of ``chunk_size`` bytes. """ if not chunk_size: chunk_size = 64 * 2 ** 10 if hasattr(f, "seek"): f.seek(0) while True: data = f.read(chunk_size) if not data: break yield data
[ "def", "chunks", "(", "f", ",", "chunk_size", "=", "None", ")", ":", "if", "not", "chunk_size", ":", "chunk_size", "=", "64", "*", "2", "**", "10", "if", "hasattr", "(", "f", ",", "\"seek\"", ")", ":", "f", ".", "seek", "(", "0", ")", "while", "True", ":", "data", "=", "f", ".", "read", "(", "chunk_size", ")", "if", "not", "data", ":", "break", "yield", "data" ]
Read the file and yield chucks of ``chunk_size`` bytes.
[ "Read", "the", "file", "and", "yield", "chucks", "of", "chunk_size", "bytes", "." ]
0d893afc1db32cd83eaf8e2ad4ed51b37933d5f0
https://github.com/dstufft/storages/blob/0d893afc1db32cd83eaf8e2ad4ed51b37933d5f0/storages/core.py#L20-L34
251,421
dstufft/storages
storages/core.py
Storage.save
def save(self, name, content): """ Saves new content to the file specified by name. The content should be a proper File object, ready to be read from the beginning. """ # Get the proper name for the file, as it will actually be saved. if name is None: name = content.name name = self.get_available_name(name) name = self._save(name, content) # Store filenames with forward slashes, even on Windows return name.replace("\\", "/")
python
def save(self, name, content): """ Saves new content to the file specified by name. The content should be a proper File object, ready to be read from the beginning. """ # Get the proper name for the file, as it will actually be saved. if name is None: name = content.name name = self.get_available_name(name) name = self._save(name, content) # Store filenames with forward slashes, even on Windows return name.replace("\\", "/")
[ "def", "save", "(", "self", ",", "name", ",", "content", ")", ":", "# Get the proper name for the file, as it will actually be saved.", "if", "name", "is", "None", ":", "name", "=", "content", ".", "name", "name", "=", "self", ".", "get_available_name", "(", "name", ")", "name", "=", "self", ".", "_save", "(", "name", ",", "content", ")", "# Store filenames with forward slashes, even on Windows", "return", "name", ".", "replace", "(", "\"\\\\\"", ",", "\"/\"", ")" ]
Saves new content to the file specified by name. The content should be a proper File object, ready to be read from the beginning.
[ "Saves", "new", "content", "to", "the", "file", "specified", "by", "name", ".", "The", "content", "should", "be", "a", "proper", "File", "object", "ready", "to", "be", "read", "from", "the", "beginning", "." ]
0d893afc1db32cd83eaf8e2ad4ed51b37933d5f0
https://github.com/dstufft/storages/blob/0d893afc1db32cd83eaf8e2ad4ed51b37933d5f0/storages/core.py#L55-L68
251,422
anti1869/sunhead
src/sunhead/cli/banners.py
print_banner
def print_banner(filename: str, template: str = DEFAULT_BANNER_TEMPLATE) -> None: """ Print text file to output. :param filename: Which file to print. :param template: Format string which specified banner arrangement. :return: Does not return anything """ if not os.path.isfile(filename): logger.warning("Can't find logo banner at %s", filename) return with open(filename, "r") as f: banner = f.read() formatted_banner = template.format(banner) print(formatted_banner)
python
def print_banner(filename: str, template: str = DEFAULT_BANNER_TEMPLATE) -> None: """ Print text file to output. :param filename: Which file to print. :param template: Format string which specified banner arrangement. :return: Does not return anything """ if not os.path.isfile(filename): logger.warning("Can't find logo banner at %s", filename) return with open(filename, "r") as f: banner = f.read() formatted_banner = template.format(banner) print(formatted_banner)
[ "def", "print_banner", "(", "filename", ":", "str", ",", "template", ":", "str", "=", "DEFAULT_BANNER_TEMPLATE", ")", "->", "None", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "logger", ".", "warning", "(", "\"Can't find logo banner at %s\"", ",", "filename", ")", "return", "with", "open", "(", "filename", ",", "\"r\"", ")", "as", "f", ":", "banner", "=", "f", ".", "read", "(", ")", "formatted_banner", "=", "template", ".", "format", "(", "banner", ")", "print", "(", "formatted_banner", ")" ]
Print text file to output. :param filename: Which file to print. :param template: Format string which specified banner arrangement. :return: Does not return anything
[ "Print", "text", "file", "to", "output", "." ]
5117ec797a38eb82d955241d20547d125efe80f3
https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/cli/banners.py#L15-L31
251,423
dossier/dossier.fc
python/dossier/fc/dump.py
repr_feature
def repr_feature(feature, max_keys=100, indent=8, lexigraphic=False): ''' generate a pretty-printed string for a feature Currently implemented: * StringCounter @max_keys: truncate long counters @indent: indent multi-line displays by this many spaces @lexigraphic: instead of sorting counters by count (default), sort keys lexigraphically ''' if isinstance(feature, (str, bytes)): try: ustr = feature.decode('utf8') return ustr except: # failure to decode, not actually utf8, other binary data return repr(feature) if isinstance(feature, StringCounter): return repr_stringcounter(feature, max_keys, indent, lexigraphic) elif isinstance(feature, unicode): return feature else: return repr(feature) assert False, 'internal logic failure, no branch taken'
python
def repr_feature(feature, max_keys=100, indent=8, lexigraphic=False): ''' generate a pretty-printed string for a feature Currently implemented: * StringCounter @max_keys: truncate long counters @indent: indent multi-line displays by this many spaces @lexigraphic: instead of sorting counters by count (default), sort keys lexigraphically ''' if isinstance(feature, (str, bytes)): try: ustr = feature.decode('utf8') return ustr except: # failure to decode, not actually utf8, other binary data return repr(feature) if isinstance(feature, StringCounter): return repr_stringcounter(feature, max_keys, indent, lexigraphic) elif isinstance(feature, unicode): return feature else: return repr(feature) assert False, 'internal logic failure, no branch taken'
[ "def", "repr_feature", "(", "feature", ",", "max_keys", "=", "100", ",", "indent", "=", "8", ",", "lexigraphic", "=", "False", ")", ":", "if", "isinstance", "(", "feature", ",", "(", "str", ",", "bytes", ")", ")", ":", "try", ":", "ustr", "=", "feature", ".", "decode", "(", "'utf8'", ")", "return", "ustr", "except", ":", "# failure to decode, not actually utf8, other binary data", "return", "repr", "(", "feature", ")", "if", "isinstance", "(", "feature", ",", "StringCounter", ")", ":", "return", "repr_stringcounter", "(", "feature", ",", "max_keys", ",", "indent", ",", "lexigraphic", ")", "elif", "isinstance", "(", "feature", ",", "unicode", ")", ":", "return", "feature", "else", ":", "return", "repr", "(", "feature", ")", "assert", "False", ",", "'internal logic failure, no branch taken'" ]
generate a pretty-printed string for a feature Currently implemented: * StringCounter @max_keys: truncate long counters @indent: indent multi-line displays by this many spaces @lexigraphic: instead of sorting counters by count (default), sort keys lexigraphically
[ "generate", "a", "pretty", "-", "printed", "string", "for", "a", "feature" ]
3e969d0cb2592fc06afc1c849d2b22283450b5e2
https://github.com/dossier/dossier.fc/blob/3e969d0cb2592fc06afc1c849d2b22283450b5e2/python/dossier/fc/dump.py#L18-L47
251,424
dossier/dossier.fc
python/dossier/fc/dump.py
only_specific_multisets
def only_specific_multisets(ent, multisets_to_show): ''' returns a pretty-printed string for specific features in a FeatureCollection ''' out_str = [] for mset_name in multisets_to_show: for key, count in ent[mset_name].items(): out_str.append( '%s - %d: %s' % (mset_name, count, key) ) return '\n'.join(out_str)
python
def only_specific_multisets(ent, multisets_to_show): ''' returns a pretty-printed string for specific features in a FeatureCollection ''' out_str = [] for mset_name in multisets_to_show: for key, count in ent[mset_name].items(): out_str.append( '%s - %d: %s' % (mset_name, count, key) ) return '\n'.join(out_str)
[ "def", "only_specific_multisets", "(", "ent", ",", "multisets_to_show", ")", ":", "out_str", "=", "[", "]", "for", "mset_name", "in", "multisets_to_show", ":", "for", "key", ",", "count", "in", "ent", "[", "mset_name", "]", ".", "items", "(", ")", ":", "out_str", ".", "append", "(", "'%s - %d: %s'", "%", "(", "mset_name", ",", "count", ",", "key", ")", ")", "return", "'\\n'", ".", "join", "(", "out_str", ")" ]
returns a pretty-printed string for specific features in a FeatureCollection
[ "returns", "a", "pretty", "-", "printed", "string", "for", "specific", "features", "in", "a", "FeatureCollection" ]
3e969d0cb2592fc06afc1c849d2b22283450b5e2
https://github.com/dossier/dossier.fc/blob/3e969d0cb2592fc06afc1c849d2b22283450b5e2/python/dossier/fc/dump.py#L132-L140
251,425
lambdalisue/tolerance
src/tolerance/decorators.py
tolerate
def tolerate(substitute=None, exceptions=None, switch=DEFAULT_TOLERATE_SWITCH): """ A function decorator which makes a function fail silently To disable fail silently in a decorated function, specify ``fail_silently=False``. To disable fail silenlty in decorated functions globally, specify ``tolerate.disabled``. Parameters ---------- fn : function A function which will be decorated. substitute : function or returning value A function used instead of :attr:`fn` or returning value when :attr:`fn` failed. exceptions : list of exceptions or None A list of exception classes or None. If exceptions is specified, ignore exceptions only listed in this parameter and raise exception if the exception is not listed. switch : string, list/tuple, dict, function or None A switch function which determine whether silent the function failar. The function receive ``*args`` and ``**kwargs`` which will specified to :attr:`fn` and should return status (bool), args, and kwargs. If the function return ``False`` then agggressive decorated function worked as normal function (raise exception when there is exception). Default switch function is generated by :func:`argument_switch_generator` with ``argument_switch_generator('fail_silently')`` so if ``fail_silently=False`` is specified to the function, the function works as noramlly. **From Version 0.1.1**, when switch is specified as non functional value, :func:`argument_switch_generator` will be called with switch as arguments. If string is specified, the switch generator will be called as ``argument_switch_generator(switch)``. If list or tuple is specified, the switch generator will be called as ``argument_switch_generator(*switch)``. If dict is specified, the switch generator will be called as ``argument_switch_generator(**switch)``. Returns ------- function A decorated function Examples -------- >>> # >>> # use tolerate as a function wrapper >>> # >>> parse_int = tolerate()(int) >>> parse_int(0) 0 >>> parse_int("0") 0 >>> parse_int("zero") is None True >>> # >>> # use tolerate as a function decorator (PIP-318) >>> # >>> @tolerate(lambda x: x) ... def prefer_int(x): ... return int(x) >>> prefer_int(0) 0 >>> prefer_int("0") 0 >>> prefer_int("zero") 'zero' >>> # >>> # filter exceptions be ignored >>> # >>> @tolerate(exceptions=(KeyError, ValueError)) ... def force_int(x): ... string_numbers = { ... 'zero': 0, ... 'one': 1, ... 'two': 2, ... 'three': 3, ... 'four': 4, ... 'five': 5, ... 'six': 6, ... 'seven': 7, ... 'eight': 8, ... 'nine': 9 ... } ... if isinstance(x, (int, float)): ... return int(x) ... elif isinstance(x, str): ... if x in string_numbers: ... return string_numbers[x] ... elif x in ('ten', 'hundred', 'thousand'): ... raise KeyError ... raise ValueError ... else: ... raise AttributeError >>> force_int('zero') 0 >>> force_int('ten') is None # KeyError True >>> force_int('foo') is None # ValueError True >>> force_int(object) # AttributeError Traceback (most recent call last): ... AttributeError >>> # >>> # disable tolerance by passing `fail_silently=False` >>> # >>> force_int('ten', fail_silently=False) # KeyError Traceback (most recent call last): ... KeyError >>> # >>> # disable tolerance globally by setting `tolerate.disabled=True` >>> # >>> tolerate.disabled = True >>> force_int('foo') # ValueError Traceback (most recent call last): ... ValueError >>> tolerate.disabled = False # rollback >>> # >>> # Features from Version 0.1.1 >>> # >>> # specify switch as a string >>> parse_int_string = tolerate(switch='patient')(int) >>> parse_int_string('zero') is None True >>> parse_int_string('zero', patient=False) Traceback (most recent call last): ... ValueError: ... >>> # specify switch as a list >>> parse_int_list = tolerate(switch=['fail_silently', False])(int) >>> parse_int_list('zero') Traceback (most recent call last): ... ValueError: ... >>> parse_int_string('zero', fail_silently=True) is None True >>> # specify switch as a dict >>> parse_int_dict = tolerate(switch={'argument_name': 'aggressive', ... 'reverse': True})(int) >>> parse_int_dict('zero') is None True >>> parse_int_dict('zero', aggressive=False) is None True >>> parse_int_dict('zero', aggressive=True) is None Traceback (most recent call last): ... ValueError: ... """ def decorator(fn): @wraps(fn) def inner(*args, **kwargs): if getattr(tolerate, 'disabled', False): # the function has disabled so call normally. return fn(*args, **kwargs) if switch is not None: status, args, kwargs = switch(*args, **kwargs) if not status: # the switch function return `False` so call noramlly. return fn(*args, **kwargs) try: return fn(*args, **kwargs) except: e = sys.exc_info()[1] if exceptions is None or e.__class__ in exceptions: if _is_callable(substitute): return substitute(*args, **kwargs) return substitute raise e return inner if switch: # create argument switch if switch is string or list or dict if isinstance(switch, basestring): switch = argument_switch_generator(switch) elif isinstance(switch, (list, tuple)): switch = argument_switch_generator(*switch) elif isinstance(switch, dict): switch = argument_switch_generator(**switch) return decorator
python
def tolerate(substitute=None, exceptions=None, switch=DEFAULT_TOLERATE_SWITCH): """ A function decorator which makes a function fail silently To disable fail silently in a decorated function, specify ``fail_silently=False``. To disable fail silenlty in decorated functions globally, specify ``tolerate.disabled``. Parameters ---------- fn : function A function which will be decorated. substitute : function or returning value A function used instead of :attr:`fn` or returning value when :attr:`fn` failed. exceptions : list of exceptions or None A list of exception classes or None. If exceptions is specified, ignore exceptions only listed in this parameter and raise exception if the exception is not listed. switch : string, list/tuple, dict, function or None A switch function which determine whether silent the function failar. The function receive ``*args`` and ``**kwargs`` which will specified to :attr:`fn` and should return status (bool), args, and kwargs. If the function return ``False`` then agggressive decorated function worked as normal function (raise exception when there is exception). Default switch function is generated by :func:`argument_switch_generator` with ``argument_switch_generator('fail_silently')`` so if ``fail_silently=False`` is specified to the function, the function works as noramlly. **From Version 0.1.1**, when switch is specified as non functional value, :func:`argument_switch_generator` will be called with switch as arguments. If string is specified, the switch generator will be called as ``argument_switch_generator(switch)``. If list or tuple is specified, the switch generator will be called as ``argument_switch_generator(*switch)``. If dict is specified, the switch generator will be called as ``argument_switch_generator(**switch)``. Returns ------- function A decorated function Examples -------- >>> # >>> # use tolerate as a function wrapper >>> # >>> parse_int = tolerate()(int) >>> parse_int(0) 0 >>> parse_int("0") 0 >>> parse_int("zero") is None True >>> # >>> # use tolerate as a function decorator (PIP-318) >>> # >>> @tolerate(lambda x: x) ... def prefer_int(x): ... return int(x) >>> prefer_int(0) 0 >>> prefer_int("0") 0 >>> prefer_int("zero") 'zero' >>> # >>> # filter exceptions be ignored >>> # >>> @tolerate(exceptions=(KeyError, ValueError)) ... def force_int(x): ... string_numbers = { ... 'zero': 0, ... 'one': 1, ... 'two': 2, ... 'three': 3, ... 'four': 4, ... 'five': 5, ... 'six': 6, ... 'seven': 7, ... 'eight': 8, ... 'nine': 9 ... } ... if isinstance(x, (int, float)): ... return int(x) ... elif isinstance(x, str): ... if x in string_numbers: ... return string_numbers[x] ... elif x in ('ten', 'hundred', 'thousand'): ... raise KeyError ... raise ValueError ... else: ... raise AttributeError >>> force_int('zero') 0 >>> force_int('ten') is None # KeyError True >>> force_int('foo') is None # ValueError True >>> force_int(object) # AttributeError Traceback (most recent call last): ... AttributeError >>> # >>> # disable tolerance by passing `fail_silently=False` >>> # >>> force_int('ten', fail_silently=False) # KeyError Traceback (most recent call last): ... KeyError >>> # >>> # disable tolerance globally by setting `tolerate.disabled=True` >>> # >>> tolerate.disabled = True >>> force_int('foo') # ValueError Traceback (most recent call last): ... ValueError >>> tolerate.disabled = False # rollback >>> # >>> # Features from Version 0.1.1 >>> # >>> # specify switch as a string >>> parse_int_string = tolerate(switch='patient')(int) >>> parse_int_string('zero') is None True >>> parse_int_string('zero', patient=False) Traceback (most recent call last): ... ValueError: ... >>> # specify switch as a list >>> parse_int_list = tolerate(switch=['fail_silently', False])(int) >>> parse_int_list('zero') Traceback (most recent call last): ... ValueError: ... >>> parse_int_string('zero', fail_silently=True) is None True >>> # specify switch as a dict >>> parse_int_dict = tolerate(switch={'argument_name': 'aggressive', ... 'reverse': True})(int) >>> parse_int_dict('zero') is None True >>> parse_int_dict('zero', aggressive=False) is None True >>> parse_int_dict('zero', aggressive=True) is None Traceback (most recent call last): ... ValueError: ... """ def decorator(fn): @wraps(fn) def inner(*args, **kwargs): if getattr(tolerate, 'disabled', False): # the function has disabled so call normally. return fn(*args, **kwargs) if switch is not None: status, args, kwargs = switch(*args, **kwargs) if not status: # the switch function return `False` so call noramlly. return fn(*args, **kwargs) try: return fn(*args, **kwargs) except: e = sys.exc_info()[1] if exceptions is None or e.__class__ in exceptions: if _is_callable(substitute): return substitute(*args, **kwargs) return substitute raise e return inner if switch: # create argument switch if switch is string or list or dict if isinstance(switch, basestring): switch = argument_switch_generator(switch) elif isinstance(switch, (list, tuple)): switch = argument_switch_generator(*switch) elif isinstance(switch, dict): switch = argument_switch_generator(**switch) return decorator
[ "def", "tolerate", "(", "substitute", "=", "None", ",", "exceptions", "=", "None", ",", "switch", "=", "DEFAULT_TOLERATE_SWITCH", ")", ":", "def", "decorator", "(", "fn", ")", ":", "@", "wraps", "(", "fn", ")", "def", "inner", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "getattr", "(", "tolerate", ",", "'disabled'", ",", "False", ")", ":", "# the function has disabled so call normally.", "return", "fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "switch", "is", "not", "None", ":", "status", ",", "args", ",", "kwargs", "=", "switch", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "not", "status", ":", "# the switch function return `False` so call noramlly.", "return", "fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", "try", ":", "return", "fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", ":", "e", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "if", "exceptions", "is", "None", "or", "e", ".", "__class__", "in", "exceptions", ":", "if", "_is_callable", "(", "substitute", ")", ":", "return", "substitute", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "substitute", "raise", "e", "return", "inner", "if", "switch", ":", "# create argument switch if switch is string or list or dict", "if", "isinstance", "(", "switch", ",", "basestring", ")", ":", "switch", "=", "argument_switch_generator", "(", "switch", ")", "elif", "isinstance", "(", "switch", ",", "(", "list", ",", "tuple", ")", ")", ":", "switch", "=", "argument_switch_generator", "(", "*", "switch", ")", "elif", "isinstance", "(", "switch", ",", "dict", ")", ":", "switch", "=", "argument_switch_generator", "(", "*", "*", "switch", ")", "return", "decorator" ]
A function decorator which makes a function fail silently To disable fail silently in a decorated function, specify ``fail_silently=False``. To disable fail silenlty in decorated functions globally, specify ``tolerate.disabled``. Parameters ---------- fn : function A function which will be decorated. substitute : function or returning value A function used instead of :attr:`fn` or returning value when :attr:`fn` failed. exceptions : list of exceptions or None A list of exception classes or None. If exceptions is specified, ignore exceptions only listed in this parameter and raise exception if the exception is not listed. switch : string, list/tuple, dict, function or None A switch function which determine whether silent the function failar. The function receive ``*args`` and ``**kwargs`` which will specified to :attr:`fn` and should return status (bool), args, and kwargs. If the function return ``False`` then agggressive decorated function worked as normal function (raise exception when there is exception). Default switch function is generated by :func:`argument_switch_generator` with ``argument_switch_generator('fail_silently')`` so if ``fail_silently=False`` is specified to the function, the function works as noramlly. **From Version 0.1.1**, when switch is specified as non functional value, :func:`argument_switch_generator` will be called with switch as arguments. If string is specified, the switch generator will be called as ``argument_switch_generator(switch)``. If list or tuple is specified, the switch generator will be called as ``argument_switch_generator(*switch)``. If dict is specified, the switch generator will be called as ``argument_switch_generator(**switch)``. Returns ------- function A decorated function Examples -------- >>> # >>> # use tolerate as a function wrapper >>> # >>> parse_int = tolerate()(int) >>> parse_int(0) 0 >>> parse_int("0") 0 >>> parse_int("zero") is None True >>> # >>> # use tolerate as a function decorator (PIP-318) >>> # >>> @tolerate(lambda x: x) ... def prefer_int(x): ... return int(x) >>> prefer_int(0) 0 >>> prefer_int("0") 0 >>> prefer_int("zero") 'zero' >>> # >>> # filter exceptions be ignored >>> # >>> @tolerate(exceptions=(KeyError, ValueError)) ... def force_int(x): ... string_numbers = { ... 'zero': 0, ... 'one': 1, ... 'two': 2, ... 'three': 3, ... 'four': 4, ... 'five': 5, ... 'six': 6, ... 'seven': 7, ... 'eight': 8, ... 'nine': 9 ... } ... if isinstance(x, (int, float)): ... return int(x) ... elif isinstance(x, str): ... if x in string_numbers: ... return string_numbers[x] ... elif x in ('ten', 'hundred', 'thousand'): ... raise KeyError ... raise ValueError ... else: ... raise AttributeError >>> force_int('zero') 0 >>> force_int('ten') is None # KeyError True >>> force_int('foo') is None # ValueError True >>> force_int(object) # AttributeError Traceback (most recent call last): ... AttributeError >>> # >>> # disable tolerance by passing `fail_silently=False` >>> # >>> force_int('ten', fail_silently=False) # KeyError Traceback (most recent call last): ... KeyError >>> # >>> # disable tolerance globally by setting `tolerate.disabled=True` >>> # >>> tolerate.disabled = True >>> force_int('foo') # ValueError Traceback (most recent call last): ... ValueError >>> tolerate.disabled = False # rollback >>> # >>> # Features from Version 0.1.1 >>> # >>> # specify switch as a string >>> parse_int_string = tolerate(switch='patient')(int) >>> parse_int_string('zero') is None True >>> parse_int_string('zero', patient=False) Traceback (most recent call last): ... ValueError: ... >>> # specify switch as a list >>> parse_int_list = tolerate(switch=['fail_silently', False])(int) >>> parse_int_list('zero') Traceback (most recent call last): ... ValueError: ... >>> parse_int_string('zero', fail_silently=True) is None True >>> # specify switch as a dict >>> parse_int_dict = tolerate(switch={'argument_name': 'aggressive', ... 'reverse': True})(int) >>> parse_int_dict('zero') is None True >>> parse_int_dict('zero', aggressive=False) is None True >>> parse_int_dict('zero', aggressive=True) is None Traceback (most recent call last): ... ValueError: ...
[ "A", "function", "decorator", "which", "makes", "a", "function", "fail", "silently" ]
e332622d78b1f8066098cc768af4ed12ccb4153d
https://github.com/lambdalisue/tolerance/blob/e332622d78b1f8066098cc768af4ed12ccb4153d/src/tolerance/decorators.py#L15-L201
251,426
soasme/rio-client
rio_client/transports/requests.py
RequestsTransport.emit
def emit(self, action, payload): """Emit action with payload via `requests.post`.""" url = self.get_emit_api(action) headers = { 'User-Agent': 'rio/%s' % VERSION, 'X-Rio-Protocol': '1', } args = dict( url=url, json=payload, headers=headers, timeout=self.timeout, ) resp = requests.post(**args) data = resp.json() is_success = resp.status_code == 200 result = dict( is_success=is_success, message=data['message'], ) if result['is_success']: result.update( event_uuid=data['event']['uuid'], task_id=data['task']['id'], ) return result
python
def emit(self, action, payload): """Emit action with payload via `requests.post`.""" url = self.get_emit_api(action) headers = { 'User-Agent': 'rio/%s' % VERSION, 'X-Rio-Protocol': '1', } args = dict( url=url, json=payload, headers=headers, timeout=self.timeout, ) resp = requests.post(**args) data = resp.json() is_success = resp.status_code == 200 result = dict( is_success=is_success, message=data['message'], ) if result['is_success']: result.update( event_uuid=data['event']['uuid'], task_id=data['task']['id'], ) return result
[ "def", "emit", "(", "self", ",", "action", ",", "payload", ")", ":", "url", "=", "self", ".", "get_emit_api", "(", "action", ")", "headers", "=", "{", "'User-Agent'", ":", "'rio/%s'", "%", "VERSION", ",", "'X-Rio-Protocol'", ":", "'1'", ",", "}", "args", "=", "dict", "(", "url", "=", "url", ",", "json", "=", "payload", ",", "headers", "=", "headers", ",", "timeout", "=", "self", ".", "timeout", ",", ")", "resp", "=", "requests", ".", "post", "(", "*", "*", "args", ")", "data", "=", "resp", ".", "json", "(", ")", "is_success", "=", "resp", ".", "status_code", "==", "200", "result", "=", "dict", "(", "is_success", "=", "is_success", ",", "message", "=", "data", "[", "'message'", "]", ",", ")", "if", "result", "[", "'is_success'", "]", ":", "result", ".", "update", "(", "event_uuid", "=", "data", "[", "'event'", "]", "[", "'uuid'", "]", ",", "task_id", "=", "data", "[", "'task'", "]", "[", "'id'", "]", ",", ")", "return", "result" ]
Emit action with payload via `requests.post`.
[ "Emit", "action", "with", "payload", "via", "requests", ".", "post", "." ]
c6d684c6f9deea5b43f2b05bcaf40714c48b5619
https://github.com/soasme/rio-client/blob/c6d684c6f9deea5b43f2b05bcaf40714c48b5619/rio_client/transports/requests.py#L25-L50
251,427
tsileo/globster
lazy_regex.py
LazyRegex._compile_and_collapse
def _compile_and_collapse(self): """Actually compile the requested regex""" self._real_regex = self._real_re_compile(*self._regex_args, **self._regex_kwargs) for attr in self._regex_attributes_to_copy: setattr(self, attr, getattr(self._real_regex, attr))
python
def _compile_and_collapse(self): """Actually compile the requested regex""" self._real_regex = self._real_re_compile(*self._regex_args, **self._regex_kwargs) for attr in self._regex_attributes_to_copy: setattr(self, attr, getattr(self._real_regex, attr))
[ "def", "_compile_and_collapse", "(", "self", ")", ":", "self", ".", "_real_regex", "=", "self", ".", "_real_re_compile", "(", "*", "self", ".", "_regex_args", ",", "*", "*", "self", ".", "_regex_kwargs", ")", "for", "attr", "in", "self", ".", "_regex_attributes_to_copy", ":", "setattr", "(", "self", ",", "attr", ",", "getattr", "(", "self", ".", "_real_regex", ",", "attr", ")", ")" ]
Actually compile the requested regex
[ "Actually", "compile", "the", "requested", "regex" ]
9628bce60207b150d39b409cddc3fadb34e70841
https://github.com/tsileo/globster/blob/9628bce60207b150d39b409cddc3fadb34e70841/lazy_regex.py#L60-L65
251,428
jfjlaros/memoise
memoise/memoise.py
_get_params
def _get_params(func, *args, **kwargs): """Turn an argument list into a dictionary. :arg function func: A function. :arg list *args: Positional arguments of `func`. :arg dict **kwargs: Keyword arguments of `func`. :returns dict: Dictionary representation of `args` and `kwargs`. """ params = dict(zip(func.func_code.co_varnames[:len(args)], args)) if func.func_defaults: params.update(dict(zip( func.func_code.co_varnames[-len(func.func_defaults):], func.func_defaults))) params.update(kwargs) return params
python
def _get_params(func, *args, **kwargs): """Turn an argument list into a dictionary. :arg function func: A function. :arg list *args: Positional arguments of `func`. :arg dict **kwargs: Keyword arguments of `func`. :returns dict: Dictionary representation of `args` and `kwargs`. """ params = dict(zip(func.func_code.co_varnames[:len(args)], args)) if func.func_defaults: params.update(dict(zip( func.func_code.co_varnames[-len(func.func_defaults):], func.func_defaults))) params.update(kwargs) return params
[ "def", "_get_params", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "params", "=", "dict", "(", "zip", "(", "func", ".", "func_code", ".", "co_varnames", "[", ":", "len", "(", "args", ")", "]", ",", "args", ")", ")", "if", "func", ".", "func_defaults", ":", "params", ".", "update", "(", "dict", "(", "zip", "(", "func", ".", "func_code", ".", "co_varnames", "[", "-", "len", "(", "func", ".", "func_defaults", ")", ":", "]", ",", "func", ".", "func_defaults", ")", ")", ")", "params", ".", "update", "(", "kwargs", ")", "return", "params" ]
Turn an argument list into a dictionary. :arg function func: A function. :arg list *args: Positional arguments of `func`. :arg dict **kwargs: Keyword arguments of `func`. :returns dict: Dictionary representation of `args` and `kwargs`.
[ "Turn", "an", "argument", "list", "into", "a", "dictionary", "." ]
65c834c2a778a39742827b0627e4792637096fec
https://github.com/jfjlaros/memoise/blob/65c834c2a778a39742827b0627e4792637096fec/memoise/memoise.py#L6-L22
251,429
refinery29/chassis
chassis/services/dependency_injection/__init__.py
_check_type
def _check_type(name, obj, expected_type): """ Raise a TypeError if object is not of expected type """ if not isinstance(obj, expected_type): raise TypeError( '"%s" must be an a %s' % (name, expected_type.__name__) )
python
def _check_type(name, obj, expected_type): """ Raise a TypeError if object is not of expected type """ if not isinstance(obj, expected_type): raise TypeError( '"%s" must be an a %s' % (name, expected_type.__name__) )
[ "def", "_check_type", "(", "name", ",", "obj", ",", "expected_type", ")", ":", "if", "not", "isinstance", "(", "obj", ",", "expected_type", ")", ":", "raise", "TypeError", "(", "'\"%s\" must be an a %s'", "%", "(", "name", ",", "expected_type", ".", "__name__", ")", ")" ]
Raise a TypeError if object is not of expected type
[ "Raise", "a", "TypeError", "if", "object", "is", "not", "of", "expected", "type" ]
1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192
https://github.com/refinery29/chassis/blob/1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192/chassis/services/dependency_injection/__init__.py#L27-L32
251,430
refinery29/chassis
chassis/services/dependency_injection/__init__.py
_import_module
def _import_module(module_name): """ Imports the module dynamically _import_module('foo.bar') calls: __import__('foo.bar', globals(), locals(), ['bar', ], 0) """ fromlist = [] dot_position = module_name.rfind('.') if dot_position > -1: fromlist.append( module_name[dot_position+1:len(module_name)] ) # Import module module = __import__(module_name, globals(), locals(), fromlist, 0) return module
python
def _import_module(module_name): """ Imports the module dynamically _import_module('foo.bar') calls: __import__('foo.bar', globals(), locals(), ['bar', ], 0) """ fromlist = [] dot_position = module_name.rfind('.') if dot_position > -1: fromlist.append( module_name[dot_position+1:len(module_name)] ) # Import module module = __import__(module_name, globals(), locals(), fromlist, 0) return module
[ "def", "_import_module", "(", "module_name", ")", ":", "fromlist", "=", "[", "]", "dot_position", "=", "module_name", ".", "rfind", "(", "'.'", ")", "if", "dot_position", ">", "-", "1", ":", "fromlist", ".", "append", "(", "module_name", "[", "dot_position", "+", "1", ":", "len", "(", "module_name", ")", "]", ")", "# Import module", "module", "=", "__import__", "(", "module_name", ",", "globals", "(", ")", ",", "locals", "(", ")", ",", "fromlist", ",", "0", ")", "return", "module" ]
Imports the module dynamically _import_module('foo.bar') calls: __import__('foo.bar', globals(), locals(), ['bar', ], 0)
[ "Imports", "the", "module", "dynamically" ]
1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192
https://github.com/refinery29/chassis/blob/1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192/chassis/services/dependency_injection/__init__.py#L35-L56
251,431
refinery29/chassis
chassis/services/dependency_injection/__init__.py
ServiceFactory.create
def create(self, module_name, class_name, args=None, kwargs=None, factory_method=None, factory_args=None, factory_kwargs=None, static=False, calls=None): """ Initializes an instance of the service """ if args is None: args = [] if kwargs is None: kwargs = {} if factory_args is None: factory_args = [] if factory_kwargs is None: factory_kwargs = {} if static is None: static = False # Verify _verify_create_args(module_name, class_name, static) # Import module = _import_module(module_name) # Instantiate service_obj = self._instantiate(module, class_name, args, kwargs, static) # Factory? if factory_method is not None: service_obj = self._handle_factory_method(service_obj, factory_method, factory_args, factory_kwargs) # Extra Calls if calls is not None and isinstance(calls, list): self._handle_calls(service_obj, calls) # Return return service_obj
python
def create(self, module_name, class_name, args=None, kwargs=None, factory_method=None, factory_args=None, factory_kwargs=None, static=False, calls=None): """ Initializes an instance of the service """ if args is None: args = [] if kwargs is None: kwargs = {} if factory_args is None: factory_args = [] if factory_kwargs is None: factory_kwargs = {} if static is None: static = False # Verify _verify_create_args(module_name, class_name, static) # Import module = _import_module(module_name) # Instantiate service_obj = self._instantiate(module, class_name, args, kwargs, static) # Factory? if factory_method is not None: service_obj = self._handle_factory_method(service_obj, factory_method, factory_args, factory_kwargs) # Extra Calls if calls is not None and isinstance(calls, list): self._handle_calls(service_obj, calls) # Return return service_obj
[ "def", "create", "(", "self", ",", "module_name", ",", "class_name", ",", "args", "=", "None", ",", "kwargs", "=", "None", ",", "factory_method", "=", "None", ",", "factory_args", "=", "None", ",", "factory_kwargs", "=", "None", ",", "static", "=", "False", ",", "calls", "=", "None", ")", ":", "if", "args", "is", "None", ":", "args", "=", "[", "]", "if", "kwargs", "is", "None", ":", "kwargs", "=", "{", "}", "if", "factory_args", "is", "None", ":", "factory_args", "=", "[", "]", "if", "factory_kwargs", "is", "None", ":", "factory_kwargs", "=", "{", "}", "if", "static", "is", "None", ":", "static", "=", "False", "# Verify", "_verify_create_args", "(", "module_name", ",", "class_name", ",", "static", ")", "# Import", "module", "=", "_import_module", "(", "module_name", ")", "# Instantiate", "service_obj", "=", "self", ".", "_instantiate", "(", "module", ",", "class_name", ",", "args", ",", "kwargs", ",", "static", ")", "# Factory?", "if", "factory_method", "is", "not", "None", ":", "service_obj", "=", "self", ".", "_handle_factory_method", "(", "service_obj", ",", "factory_method", ",", "factory_args", ",", "factory_kwargs", ")", "# Extra Calls", "if", "calls", "is", "not", "None", "and", "isinstance", "(", "calls", ",", "list", ")", ":", "self", ".", "_handle_calls", "(", "service_obj", ",", "calls", ")", "# Return", "return", "service_obj" ]
Initializes an instance of the service
[ "Initializes", "an", "instance", "of", "the", "service" ]
1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192
https://github.com/refinery29/chassis/blob/1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192/chassis/services/dependency_injection/__init__.py#L86-L122
251,432
refinery29/chassis
chassis/services/dependency_injection/__init__.py
ServiceFactory.create_from_dict
def create_from_dict(self, dictionary): """ Initializes an instance from a dictionary blueprint """ # Defaults args = [] kwargs = {} factory_method = None factory_args = [] factory_kwargs = {} static = False calls = None # Check dictionary for arguments if 'args' in dictionary: args = dictionary['args'] if 'kwargs' in dictionary: kwargs = dictionary['kwargs'] if 'factory-method' in dictionary: factory_method = dictionary['factory-method'] if 'factory-args' in dictionary: factory_args = dictionary['factory-args'] if 'factory-kwargs' in dictionary: factory_kwargs = dictionary['factory-kwargs'] if 'static' in dictionary: static = dictionary['static'] if 'calls' in dictionary: calls = dictionary['calls'] return self.create( dictionary['module'], dictionary['class'], args=args, kwargs=kwargs, factory_method=factory_method, factory_args=factory_args, factory_kwargs=factory_kwargs, static=static, calls=calls )
python
def create_from_dict(self, dictionary): """ Initializes an instance from a dictionary blueprint """ # Defaults args = [] kwargs = {} factory_method = None factory_args = [] factory_kwargs = {} static = False calls = None # Check dictionary for arguments if 'args' in dictionary: args = dictionary['args'] if 'kwargs' in dictionary: kwargs = dictionary['kwargs'] if 'factory-method' in dictionary: factory_method = dictionary['factory-method'] if 'factory-args' in dictionary: factory_args = dictionary['factory-args'] if 'factory-kwargs' in dictionary: factory_kwargs = dictionary['factory-kwargs'] if 'static' in dictionary: static = dictionary['static'] if 'calls' in dictionary: calls = dictionary['calls'] return self.create( dictionary['module'], dictionary['class'], args=args, kwargs=kwargs, factory_method=factory_method, factory_args=factory_args, factory_kwargs=factory_kwargs, static=static, calls=calls )
[ "def", "create_from_dict", "(", "self", ",", "dictionary", ")", ":", "# Defaults", "args", "=", "[", "]", "kwargs", "=", "{", "}", "factory_method", "=", "None", "factory_args", "=", "[", "]", "factory_kwargs", "=", "{", "}", "static", "=", "False", "calls", "=", "None", "# Check dictionary for arguments", "if", "'args'", "in", "dictionary", ":", "args", "=", "dictionary", "[", "'args'", "]", "if", "'kwargs'", "in", "dictionary", ":", "kwargs", "=", "dictionary", "[", "'kwargs'", "]", "if", "'factory-method'", "in", "dictionary", ":", "factory_method", "=", "dictionary", "[", "'factory-method'", "]", "if", "'factory-args'", "in", "dictionary", ":", "factory_args", "=", "dictionary", "[", "'factory-args'", "]", "if", "'factory-kwargs'", "in", "dictionary", ":", "factory_kwargs", "=", "dictionary", "[", "'factory-kwargs'", "]", "if", "'static'", "in", "dictionary", ":", "static", "=", "dictionary", "[", "'static'", "]", "if", "'calls'", "in", "dictionary", ":", "calls", "=", "dictionary", "[", "'calls'", "]", "return", "self", ".", "create", "(", "dictionary", "[", "'module'", "]", ",", "dictionary", "[", "'class'", "]", ",", "args", "=", "args", ",", "kwargs", "=", "kwargs", ",", "factory_method", "=", "factory_method", ",", "factory_args", "=", "factory_args", ",", "factory_kwargs", "=", "factory_kwargs", ",", "static", "=", "static", ",", "calls", "=", "calls", ")" ]
Initializes an instance from a dictionary blueprint
[ "Initializes", "an", "instance", "from", "a", "dictionary", "blueprint" ]
1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192
https://github.com/refinery29/chassis/blob/1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192/chassis/services/dependency_injection/__init__.py#L124-L167
251,433
refinery29/chassis
chassis/services/dependency_injection/__init__.py
ServiceFactory.get_instantiated_service
def get_instantiated_service(self, name): """ Get instantiated service by name """ if name not in self.instantiated_services: raise UninstantiatedServiceException return self.instantiated_services[name]
python
def get_instantiated_service(self, name): """ Get instantiated service by name """ if name not in self.instantiated_services: raise UninstantiatedServiceException return self.instantiated_services[name]
[ "def", "get_instantiated_service", "(", "self", ",", "name", ")", ":", "if", "name", "not", "in", "self", ".", "instantiated_services", ":", "raise", "UninstantiatedServiceException", "return", "self", ".", "instantiated_services", "[", "name", "]" ]
Get instantiated service by name
[ "Get", "instantiated", "service", "by", "name" ]
1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192
https://github.com/refinery29/chassis/blob/1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192/chassis/services/dependency_injection/__init__.py#L177-L181
251,434
refinery29/chassis
chassis/services/dependency_injection/__init__.py
ServiceFactory._replace_service_arg
def _replace_service_arg(self, name, index, args): """ Replace index in list with service """ args[index] = self.get_instantiated_service(name)
python
def _replace_service_arg(self, name, index, args): """ Replace index in list with service """ args[index] = self.get_instantiated_service(name)
[ "def", "_replace_service_arg", "(", "self", ",", "name", ",", "index", ",", "args", ")", ":", "args", "[", "index", "]", "=", "self", ".", "get_instantiated_service", "(", "name", ")" ]
Replace index in list with service
[ "Replace", "index", "in", "list", "with", "service" ]
1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192
https://github.com/refinery29/chassis/blob/1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192/chassis/services/dependency_injection/__init__.py#L183-L185
251,435
refinery29/chassis
chassis/services/dependency_injection/__init__.py
ServiceFactory._replace_scalars_in_args
def _replace_scalars_in_args(self, args): """ Replace scalars in arguments list """ _check_type('args', args, list) new_args = [] for arg in args: if isinstance(arg, list): to_append = self._replace_scalars_in_args(arg) elif isinstance(arg, dict): to_append = self._replace_scalars_in_kwargs(arg) elif isinstance(arg, string_types): to_append = self._replace_scalar(arg) else: to_append = arg new_args.append(to_append) return new_args
python
def _replace_scalars_in_args(self, args): """ Replace scalars in arguments list """ _check_type('args', args, list) new_args = [] for arg in args: if isinstance(arg, list): to_append = self._replace_scalars_in_args(arg) elif isinstance(arg, dict): to_append = self._replace_scalars_in_kwargs(arg) elif isinstance(arg, string_types): to_append = self._replace_scalar(arg) else: to_append = arg new_args.append(to_append) return new_args
[ "def", "_replace_scalars_in_args", "(", "self", ",", "args", ")", ":", "_check_type", "(", "'args'", ",", "args", ",", "list", ")", "new_args", "=", "[", "]", "for", "arg", "in", "args", ":", "if", "isinstance", "(", "arg", ",", "list", ")", ":", "to_append", "=", "self", ".", "_replace_scalars_in_args", "(", "arg", ")", "elif", "isinstance", "(", "arg", ",", "dict", ")", ":", "to_append", "=", "self", ".", "_replace_scalars_in_kwargs", "(", "arg", ")", "elif", "isinstance", "(", "arg", ",", "string_types", ")", ":", "to_append", "=", "self", ".", "_replace_scalar", "(", "arg", ")", "else", ":", "to_append", "=", "arg", "new_args", ".", "append", "(", "to_append", ")", "return", "new_args" ]
Replace scalars in arguments list
[ "Replace", "scalars", "in", "arguments", "list" ]
1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192
https://github.com/refinery29/chassis/blob/1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192/chassis/services/dependency_injection/__init__.py#L191-L205
251,436
refinery29/chassis
chassis/services/dependency_injection/__init__.py
ServiceFactory._replace_scalars_in_kwargs
def _replace_scalars_in_kwargs(self, kwargs): """ Replace scalars in keyed arguments dictionary """ _check_type('kwargs', kwargs, dict) new_kwargs = {} for (name, value) in iteritems(kwargs): if isinstance(value, list): new_kwargs[name] = self._replace_scalars_in_args(value) elif isinstance(value, dict): new_kwargs[name] = self._replace_scalars_in_kwargs(value) elif isinstance(value, string_types): new_kwargs[name] = self._replace_scalar(value) else: new_kwargs[name] = value return new_kwargs
python
def _replace_scalars_in_kwargs(self, kwargs): """ Replace scalars in keyed arguments dictionary """ _check_type('kwargs', kwargs, dict) new_kwargs = {} for (name, value) in iteritems(kwargs): if isinstance(value, list): new_kwargs[name] = self._replace_scalars_in_args(value) elif isinstance(value, dict): new_kwargs[name] = self._replace_scalars_in_kwargs(value) elif isinstance(value, string_types): new_kwargs[name] = self._replace_scalar(value) else: new_kwargs[name] = value return new_kwargs
[ "def", "_replace_scalars_in_kwargs", "(", "self", ",", "kwargs", ")", ":", "_check_type", "(", "'kwargs'", ",", "kwargs", ",", "dict", ")", "new_kwargs", "=", "{", "}", "for", "(", "name", ",", "value", ")", "in", "iteritems", "(", "kwargs", ")", ":", "if", "isinstance", "(", "value", ",", "list", ")", ":", "new_kwargs", "[", "name", "]", "=", "self", ".", "_replace_scalars_in_args", "(", "value", ")", "elif", "isinstance", "(", "value", ",", "dict", ")", ":", "new_kwargs", "[", "name", "]", "=", "self", ".", "_replace_scalars_in_kwargs", "(", "value", ")", "elif", "isinstance", "(", "value", ",", "string_types", ")", ":", "new_kwargs", "[", "name", "]", "=", "self", ".", "_replace_scalar", "(", "value", ")", "else", ":", "new_kwargs", "[", "name", "]", "=", "value", "return", "new_kwargs" ]
Replace scalars in keyed arguments dictionary
[ "Replace", "scalars", "in", "keyed", "arguments", "dictionary" ]
1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192
https://github.com/refinery29/chassis/blob/1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192/chassis/services/dependency_injection/__init__.py#L207-L221
251,437
refinery29/chassis
chassis/services/dependency_injection/__init__.py
ServiceFactory._replace_services_in_args
def _replace_services_in_args(self, args): """ Replace service references in arguments list """ _check_type('args', args, list) new_args = [] for arg in args: if isinstance(arg, list): new_args.append(self._replace_services_in_args(arg)) elif isinstance(arg, dict): new_args.append(self._replace_services_in_kwargs(arg)) elif isinstance(arg, string_types): new_args.append(self._replace_service(arg)) else: new_args.append(arg) return new_args
python
def _replace_services_in_args(self, args): """ Replace service references in arguments list """ _check_type('args', args, list) new_args = [] for arg in args: if isinstance(arg, list): new_args.append(self._replace_services_in_args(arg)) elif isinstance(arg, dict): new_args.append(self._replace_services_in_kwargs(arg)) elif isinstance(arg, string_types): new_args.append(self._replace_service(arg)) else: new_args.append(arg) return new_args
[ "def", "_replace_services_in_args", "(", "self", ",", "args", ")", ":", "_check_type", "(", "'args'", ",", "args", ",", "list", ")", "new_args", "=", "[", "]", "for", "arg", "in", "args", ":", "if", "isinstance", "(", "arg", ",", "list", ")", ":", "new_args", ".", "append", "(", "self", ".", "_replace_services_in_args", "(", "arg", ")", ")", "elif", "isinstance", "(", "arg", ",", "dict", ")", ":", "new_args", ".", "append", "(", "self", ".", "_replace_services_in_kwargs", "(", "arg", ")", ")", "elif", "isinstance", "(", "arg", ",", "string_types", ")", ":", "new_args", ".", "append", "(", "self", ".", "_replace_service", "(", "arg", ")", ")", "else", ":", "new_args", ".", "append", "(", "arg", ")", "return", "new_args" ]
Replace service references in arguments list
[ "Replace", "service", "references", "in", "arguments", "list" ]
1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192
https://github.com/refinery29/chassis/blob/1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192/chassis/services/dependency_injection/__init__.py#L223-L237
251,438
refinery29/chassis
chassis/services/dependency_injection/__init__.py
ServiceFactory._replace_services_in_kwargs
def _replace_services_in_kwargs(self, kwargs): """ Replace service references in keyed arguments dictionary """ _check_type('kwargs', kwargs, dict) new_kwargs = {} for (name, value) in iteritems(kwargs): if isinstance(value, list): new_kwargs[name] = self._replace_services_in_args(value) elif isinstance(value, dict): new_kwargs[name] = self._replace_services_in_kwargs(value) elif isinstance(value, string_types): new_kwargs[name] = self._replace_service(value) else: new_kwargs[name] = value return new_kwargs
python
def _replace_services_in_kwargs(self, kwargs): """ Replace service references in keyed arguments dictionary """ _check_type('kwargs', kwargs, dict) new_kwargs = {} for (name, value) in iteritems(kwargs): if isinstance(value, list): new_kwargs[name] = self._replace_services_in_args(value) elif isinstance(value, dict): new_kwargs[name] = self._replace_services_in_kwargs(value) elif isinstance(value, string_types): new_kwargs[name] = self._replace_service(value) else: new_kwargs[name] = value return new_kwargs
[ "def", "_replace_services_in_kwargs", "(", "self", ",", "kwargs", ")", ":", "_check_type", "(", "'kwargs'", ",", "kwargs", ",", "dict", ")", "new_kwargs", "=", "{", "}", "for", "(", "name", ",", "value", ")", "in", "iteritems", "(", "kwargs", ")", ":", "if", "isinstance", "(", "value", ",", "list", ")", ":", "new_kwargs", "[", "name", "]", "=", "self", ".", "_replace_services_in_args", "(", "value", ")", "elif", "isinstance", "(", "value", ",", "dict", ")", ":", "new_kwargs", "[", "name", "]", "=", "self", ".", "_replace_services_in_kwargs", "(", "value", ")", "elif", "isinstance", "(", "value", ",", "string_types", ")", ":", "new_kwargs", "[", "name", "]", "=", "self", ".", "_replace_service", "(", "value", ")", "else", ":", "new_kwargs", "[", "name", "]", "=", "value", "return", "new_kwargs" ]
Replace service references in keyed arguments dictionary
[ "Replace", "service", "references", "in", "keyed", "arguments", "dictionary" ]
1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192
https://github.com/refinery29/chassis/blob/1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192/chassis/services/dependency_injection/__init__.py#L239-L253
251,439
refinery29/chassis
chassis/services/dependency_injection/__init__.py
ServiceFactory.get_scalar_value
def get_scalar_value(self, name): """ Get scalar value by name """ if name not in self.scalars: raise InvalidServiceConfiguration( 'Invalid Service Argument Scalar "%s" (not found)' % name ) new_value = self.scalars.get(name) return new_value
python
def get_scalar_value(self, name): """ Get scalar value by name """ if name not in self.scalars: raise InvalidServiceConfiguration( 'Invalid Service Argument Scalar "%s" (not found)' % name ) new_value = self.scalars.get(name) return new_value
[ "def", "get_scalar_value", "(", "self", ",", "name", ")", ":", "if", "name", "not", "in", "self", ".", "scalars", ":", "raise", "InvalidServiceConfiguration", "(", "'Invalid Service Argument Scalar \"%s\" (not found)'", "%", "name", ")", "new_value", "=", "self", ".", "scalars", ".", "get", "(", "name", ")", "return", "new_value" ]
Get scalar value by name
[ "Get", "scalar", "value", "by", "name" ]
1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192
https://github.com/refinery29/chassis/blob/1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192/chassis/services/dependency_injection/__init__.py#L255-L262
251,440
refinery29/chassis
chassis/services/dependency_injection/__init__.py
ServiceFactory._replace_scalar
def _replace_scalar(self, scalar): """ Replace scalar name with scalar value """ if not is_arg_scalar(scalar): return scalar name = scalar[1:] return self.get_scalar_value(name)
python
def _replace_scalar(self, scalar): """ Replace scalar name with scalar value """ if not is_arg_scalar(scalar): return scalar name = scalar[1:] return self.get_scalar_value(name)
[ "def", "_replace_scalar", "(", "self", ",", "scalar", ")", ":", "if", "not", "is_arg_scalar", "(", "scalar", ")", ":", "return", "scalar", "name", "=", "scalar", "[", "1", ":", "]", "return", "self", ".", "get_scalar_value", "(", "name", ")" ]
Replace scalar name with scalar value
[ "Replace", "scalar", "name", "with", "scalar", "value" ]
1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192
https://github.com/refinery29/chassis/blob/1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192/chassis/services/dependency_injection/__init__.py#L264-L269
251,441
refinery29/chassis
chassis/services/dependency_injection/__init__.py
ServiceFactory._instantiate
def _instantiate(self, module, class_name, args=None, kwargs=None, static=None): """ Instantiates a class if provided """ if args is None: args = [] if kwargs is None: kwargs = {} if static is None: static = False _check_type('args', args, list) _check_type('kwargs', kwargs, dict) if static and class_name is None: return module if static and class_name is not None: return getattr(module, class_name) service_obj = getattr(module, class_name) # Replace scalars args = self._replace_scalars_in_args(args) kwargs = self._replace_scalars_in_kwargs(kwargs) # Replace service references args = self._replace_services_in_args(args) kwargs = self._replace_services_in_kwargs(kwargs) # Instantiate object return service_obj(*args, **kwargs)
python
def _instantiate(self, module, class_name, args=None, kwargs=None, static=None): """ Instantiates a class if provided """ if args is None: args = [] if kwargs is None: kwargs = {} if static is None: static = False _check_type('args', args, list) _check_type('kwargs', kwargs, dict) if static and class_name is None: return module if static and class_name is not None: return getattr(module, class_name) service_obj = getattr(module, class_name) # Replace scalars args = self._replace_scalars_in_args(args) kwargs = self._replace_scalars_in_kwargs(kwargs) # Replace service references args = self._replace_services_in_args(args) kwargs = self._replace_services_in_kwargs(kwargs) # Instantiate object return service_obj(*args, **kwargs)
[ "def", "_instantiate", "(", "self", ",", "module", ",", "class_name", ",", "args", "=", "None", ",", "kwargs", "=", "None", ",", "static", "=", "None", ")", ":", "if", "args", "is", "None", ":", "args", "=", "[", "]", "if", "kwargs", "is", "None", ":", "kwargs", "=", "{", "}", "if", "static", "is", "None", ":", "static", "=", "False", "_check_type", "(", "'args'", ",", "args", ",", "list", ")", "_check_type", "(", "'kwargs'", ",", "kwargs", ",", "dict", ")", "if", "static", "and", "class_name", "is", "None", ":", "return", "module", "if", "static", "and", "class_name", "is", "not", "None", ":", "return", "getattr", "(", "module", ",", "class_name", ")", "service_obj", "=", "getattr", "(", "module", ",", "class_name", ")", "# Replace scalars", "args", "=", "self", ".", "_replace_scalars_in_args", "(", "args", ")", "kwargs", "=", "self", ".", "_replace_scalars_in_kwargs", "(", "kwargs", ")", "# Replace service references", "args", "=", "self", ".", "_replace_services_in_args", "(", "args", ")", "kwargs", "=", "self", ".", "_replace_services_in_kwargs", "(", "kwargs", ")", "# Instantiate object", "return", "service_obj", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Instantiates a class if provided
[ "Instantiates", "a", "class", "if", "provided" ]
1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192
https://github.com/refinery29/chassis/blob/1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192/chassis/services/dependency_injection/__init__.py#L277-L307
251,442
refinery29/chassis
chassis/services/dependency_injection/__init__.py
ServiceFactory._handle_factory_method
def _handle_factory_method(self, service_obj, method_name, args=None, kwargs=None): """" Returns an object returned from a factory method """ if args is None: args = [] if kwargs is None: kwargs = {} _check_type('args', args, list) _check_type('kwargs', kwargs, dict) # Replace args new_args = self._replace_scalars_in_args(args) new_kwargs = self._replace_scalars_in_kwargs(kwargs) return getattr(service_obj, method_name)(*new_args, **new_kwargs)
python
def _handle_factory_method(self, service_obj, method_name, args=None, kwargs=None): """" Returns an object returned from a factory method """ if args is None: args = [] if kwargs is None: kwargs = {} _check_type('args', args, list) _check_type('kwargs', kwargs, dict) # Replace args new_args = self._replace_scalars_in_args(args) new_kwargs = self._replace_scalars_in_kwargs(kwargs) return getattr(service_obj, method_name)(*new_args, **new_kwargs)
[ "def", "_handle_factory_method", "(", "self", ",", "service_obj", ",", "method_name", ",", "args", "=", "None", ",", "kwargs", "=", "None", ")", ":", "if", "args", "is", "None", ":", "args", "=", "[", "]", "if", "kwargs", "is", "None", ":", "kwargs", "=", "{", "}", "_check_type", "(", "'args'", ",", "args", ",", "list", ")", "_check_type", "(", "'kwargs'", ",", "kwargs", ",", "dict", ")", "# Replace args", "new_args", "=", "self", ".", "_replace_scalars_in_args", "(", "args", ")", "new_kwargs", "=", "self", ".", "_replace_scalars_in_kwargs", "(", "kwargs", ")", "return", "getattr", "(", "service_obj", ",", "method_name", ")", "(", "*", "new_args", ",", "*", "*", "new_kwargs", ")" ]
Returns an object returned from a factory method
[ "Returns", "an", "object", "returned", "from", "a", "factory", "method" ]
1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192
https://github.com/refinery29/chassis/blob/1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192/chassis/services/dependency_injection/__init__.py#L309-L324
251,443
refinery29/chassis
chassis/services/dependency_injection/__init__.py
ServiceFactory._handle_calls
def _handle_calls(self, service_obj, calls): """ Performs method calls on service object """ for call in calls: method = call.get('method') args = call.get('args', []) kwargs = call.get('kwargs', {}) _check_type('args', args, list) _check_type('kwargs', kwargs, dict) if method is None: raise InvalidServiceConfiguration( 'Service call must define a method.' ) new_args = self._replace_scalars_in_args(args) new_kwargs = self._replace_scalars_in_kwargs(kwargs) getattr(service_obj, method)(*new_args, **new_kwargs)
python
def _handle_calls(self, service_obj, calls): """ Performs method calls on service object """ for call in calls: method = call.get('method') args = call.get('args', []) kwargs = call.get('kwargs', {}) _check_type('args', args, list) _check_type('kwargs', kwargs, dict) if method is None: raise InvalidServiceConfiguration( 'Service call must define a method.' ) new_args = self._replace_scalars_in_args(args) new_kwargs = self._replace_scalars_in_kwargs(kwargs) getattr(service_obj, method)(*new_args, **new_kwargs)
[ "def", "_handle_calls", "(", "self", ",", "service_obj", ",", "calls", ")", ":", "for", "call", "in", "calls", ":", "method", "=", "call", ".", "get", "(", "'method'", ")", "args", "=", "call", ".", "get", "(", "'args'", ",", "[", "]", ")", "kwargs", "=", "call", ".", "get", "(", "'kwargs'", ",", "{", "}", ")", "_check_type", "(", "'args'", ",", "args", ",", "list", ")", "_check_type", "(", "'kwargs'", ",", "kwargs", ",", "dict", ")", "if", "method", "is", "None", ":", "raise", "InvalidServiceConfiguration", "(", "'Service call must define a method.'", ")", "new_args", "=", "self", ".", "_replace_scalars_in_args", "(", "args", ")", "new_kwargs", "=", "self", ".", "_replace_scalars_in_kwargs", "(", "kwargs", ")", "getattr", "(", "service_obj", ",", "method", ")", "(", "*", "new_args", ",", "*", "*", "new_kwargs", ")" ]
Performs method calls on service object
[ "Performs", "method", "calls", "on", "service", "object" ]
1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192
https://github.com/refinery29/chassis/blob/1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192/chassis/services/dependency_injection/__init__.py#L326-L344
251,444
breuleux/hrepr
hrepr/h.py
Tag._repr_html_
def _repr_html_(self): """ Jupyter Notebook hook to print this element as HTML. """ nbreset = f'<style>{css_nbreset}</style>' resources = ''.join(map(str, self.resources)) return f'<div>{nbreset}{resources}<div class="hrepr">{self}</div></div>'
python
def _repr_html_(self): """ Jupyter Notebook hook to print this element as HTML. """ nbreset = f'<style>{css_nbreset}</style>' resources = ''.join(map(str, self.resources)) return f'<div>{nbreset}{resources}<div class="hrepr">{self}</div></div>'
[ "def", "_repr_html_", "(", "self", ")", ":", "nbreset", "=", "f'<style>{css_nbreset}</style>'", "resources", "=", "''", ".", "join", "(", "map", "(", "str", ",", "self", ".", "resources", ")", ")", "return", "f'<div>{nbreset}{resources}<div class=\"hrepr\">{self}</div></div>'" ]
Jupyter Notebook hook to print this element as HTML.
[ "Jupyter", "Notebook", "hook", "to", "print", "this", "element", "as", "HTML", "." ]
a411395d31ac7c8c071d174e63a093751aa5997b
https://github.com/breuleux/hrepr/blob/a411395d31ac7c8c071d174e63a093751aa5997b/hrepr/h.py#L143-L149
251,445
rackerlabs/rackspace-python-neutronclient
neutronclient/neutron/client.py
make_client
def make_client(instance): """Returns an neutron client.""" neutron_client = utils.get_client_class( API_NAME, instance._api_version[API_NAME], API_VERSIONS, ) instance.initialize() url = instance._url url = url.rstrip("/") client = neutron_client(username=instance._username, project_name=instance._project_name, password=instance._password, region_name=instance._region_name, auth_url=instance._auth_url, endpoint_url=url, endpoint_type=instance._endpoint_type, token=instance._token, auth_strategy=instance._auth_strategy, insecure=instance._insecure, ca_cert=instance._ca_cert, retries=instance._retries, raise_errors=instance._raise_errors, session=instance._session, auth=instance._auth) return client
python
def make_client(instance): """Returns an neutron client.""" neutron_client = utils.get_client_class( API_NAME, instance._api_version[API_NAME], API_VERSIONS, ) instance.initialize() url = instance._url url = url.rstrip("/") client = neutron_client(username=instance._username, project_name=instance._project_name, password=instance._password, region_name=instance._region_name, auth_url=instance._auth_url, endpoint_url=url, endpoint_type=instance._endpoint_type, token=instance._token, auth_strategy=instance._auth_strategy, insecure=instance._insecure, ca_cert=instance._ca_cert, retries=instance._retries, raise_errors=instance._raise_errors, session=instance._session, auth=instance._auth) return client
[ "def", "make_client", "(", "instance", ")", ":", "neutron_client", "=", "utils", ".", "get_client_class", "(", "API_NAME", ",", "instance", ".", "_api_version", "[", "API_NAME", "]", ",", "API_VERSIONS", ",", ")", "instance", ".", "initialize", "(", ")", "url", "=", "instance", ".", "_url", "url", "=", "url", ".", "rstrip", "(", "\"/\"", ")", "client", "=", "neutron_client", "(", "username", "=", "instance", ".", "_username", ",", "project_name", "=", "instance", ".", "_project_name", ",", "password", "=", "instance", ".", "_password", ",", "region_name", "=", "instance", ".", "_region_name", ",", "auth_url", "=", "instance", ".", "_auth_url", ",", "endpoint_url", "=", "url", ",", "endpoint_type", "=", "instance", ".", "_endpoint_type", ",", "token", "=", "instance", ".", "_token", ",", "auth_strategy", "=", "instance", ".", "_auth_strategy", ",", "insecure", "=", "instance", ".", "_insecure", ",", "ca_cert", "=", "instance", ".", "_ca_cert", ",", "retries", "=", "instance", ".", "_retries", ",", "raise_errors", "=", "instance", ".", "_raise_errors", ",", "session", "=", "instance", ".", "_session", ",", "auth", "=", "instance", ".", "_auth", ")", "return", "client" ]
Returns an neutron client.
[ "Returns", "an", "neutron", "client", "." ]
5a5009a8fe078e3aa1d582176669f1b28ab26bef
https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/neutron/client.py#L27-L52
251,446
rackerlabs/rackspace-python-neutronclient
neutronclient/neutron/client.py
Client
def Client(api_version, *args, **kwargs): """Return an neutron client. @param api_version: only 2.0 is supported now """ neutron_client = utils.get_client_class( API_NAME, api_version, API_VERSIONS, ) return neutron_client(*args, **kwargs)
python
def Client(api_version, *args, **kwargs): """Return an neutron client. @param api_version: only 2.0 is supported now """ neutron_client = utils.get_client_class( API_NAME, api_version, API_VERSIONS, ) return neutron_client(*args, **kwargs)
[ "def", "Client", "(", "api_version", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "neutron_client", "=", "utils", ".", "get_client_class", "(", "API_NAME", ",", "api_version", ",", "API_VERSIONS", ",", ")", "return", "neutron_client", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Return an neutron client. @param api_version: only 2.0 is supported now
[ "Return", "an", "neutron", "client", "." ]
5a5009a8fe078e3aa1d582176669f1b28ab26bef
https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/neutron/client.py#L55-L65
251,447
kcolford/txt2boil
txt2boil/cmi.py
AbstractCMI._getSuperFunc
def _getSuperFunc(self, s, func): """Return the the super function.""" return getattr(super(self.cls(), s), func.__name__)
python
def _getSuperFunc(self, s, func): """Return the the super function.""" return getattr(super(self.cls(), s), func.__name__)
[ "def", "_getSuperFunc", "(", "self", ",", "s", ",", "func", ")", ":", "return", "getattr", "(", "super", "(", "self", ".", "cls", "(", ")", ",", "s", ")", ",", "func", ".", "__name__", ")" ]
Return the the super function.
[ "Return", "the", "the", "super", "function", "." ]
853a47bb8db27c0224531f24dfd02839c983d027
https://github.com/kcolford/txt2boil/blob/853a47bb8db27c0224531f24dfd02839c983d027/txt2boil/cmi.py#L72-L75
251,448
abalkin/tz
pavement.py
_doc_make
def _doc_make(*make_args): """Run make in sphinx' docs directory. :return: exit code """ if sys.platform == 'win32': # Windows make_cmd = ['make.bat'] else: # Linux, Mac OS X, and others make_cmd = ['make'] make_cmd.extend(make_args) # Account for a stupid Python "bug" on Windows: # <http://bugs.python.org/issue15533> with cwd(DOCS_DIRECTORY): retcode = subprocess.call(make_cmd) return retcode
python
def _doc_make(*make_args): """Run make in sphinx' docs directory. :return: exit code """ if sys.platform == 'win32': # Windows make_cmd = ['make.bat'] else: # Linux, Mac OS X, and others make_cmd = ['make'] make_cmd.extend(make_args) # Account for a stupid Python "bug" on Windows: # <http://bugs.python.org/issue15533> with cwd(DOCS_DIRECTORY): retcode = subprocess.call(make_cmd) return retcode
[ "def", "_doc_make", "(", "*", "make_args", ")", ":", "if", "sys", ".", "platform", "==", "'win32'", ":", "# Windows", "make_cmd", "=", "[", "'make.bat'", "]", "else", ":", "# Linux, Mac OS X, and others", "make_cmd", "=", "[", "'make'", "]", "make_cmd", ".", "extend", "(", "make_args", ")", "# Account for a stupid Python \"bug\" on Windows:", "# <http://bugs.python.org/issue15533>", "with", "cwd", "(", "DOCS_DIRECTORY", ")", ":", "retcode", "=", "subprocess", ".", "call", "(", "make_cmd", ")", "return", "retcode" ]
Run make in sphinx' docs directory. :return: exit code
[ "Run", "make", "in", "sphinx", "docs", "directory", "." ]
f25fca6afbf1abd46fd7aeb978282823c7dab5ab
https://github.com/abalkin/tz/blob/f25fca6afbf1abd46fd7aeb978282823c7dab5ab/pavement.py#L69-L86
251,449
abalkin/tz
pavement.py
coverage
def coverage(): """Run tests and show test coverage report.""" try: import pytest_cov # NOQA except ImportError: print_failure_message( 'Install the pytest coverage plugin to use this task, ' "i.e., `pip install pytest-cov'.") raise SystemExit(1) import pytest pytest.main(PYTEST_FLAGS + [ '--cov', CODE_DIRECTORY, '--cov-report', 'term-missing', '--junit-xml', 'test-report.xml', TESTS_DIRECTORY])
python
def coverage(): """Run tests and show test coverage report.""" try: import pytest_cov # NOQA except ImportError: print_failure_message( 'Install the pytest coverage plugin to use this task, ' "i.e., `pip install pytest-cov'.") raise SystemExit(1) import pytest pytest.main(PYTEST_FLAGS + [ '--cov', CODE_DIRECTORY, '--cov-report', 'term-missing', '--junit-xml', 'test-report.xml', TESTS_DIRECTORY])
[ "def", "coverage", "(", ")", ":", "try", ":", "import", "pytest_cov", "# NOQA", "except", "ImportError", ":", "print_failure_message", "(", "'Install the pytest coverage plugin to use this task, '", "\"i.e., `pip install pytest-cov'.\"", ")", "raise", "SystemExit", "(", "1", ")", "import", "pytest", "pytest", ".", "main", "(", "PYTEST_FLAGS", "+", "[", "'--cov'", ",", "CODE_DIRECTORY", ",", "'--cov-report'", ",", "'term-missing'", ",", "'--junit-xml'", ",", "'test-report.xml'", ",", "TESTS_DIRECTORY", "]", ")" ]
Run tests and show test coverage report.
[ "Run", "tests", "and", "show", "test", "coverage", "report", "." ]
f25fca6afbf1abd46fd7aeb978282823c7dab5ab
https://github.com/abalkin/tz/blob/f25fca6afbf1abd46fd7aeb978282823c7dab5ab/pavement.py#L148-L162
251,450
abalkin/tz
pavement.py
doc_watch
def doc_watch(): """Watch for changes in the docs and rebuild HTML docs when changed.""" try: from watchdog.events import FileSystemEventHandler from watchdog.observers import Observer except ImportError: print_failure_message('Install the watchdog package to use this task, ' "i.e., `pip install watchdog'.") raise SystemExit(1) class RebuildDocsEventHandler(FileSystemEventHandler): def __init__(self, base_paths): self.base_paths = base_paths def dispatch(self, event): """Dispatches events to the appropriate methods. :param event: The event object representing the file system event. :type event: :class:`watchdog.events.FileSystemEvent` """ for base_path in self.base_paths: if event.src_path.endswith(base_path): super(RebuildDocsEventHandler, self).dispatch(event) # We found one that matches. We're done. return def on_modified(self, event): print_failure_message('Modification detected. Rebuilding docs.') # # Strip off the path prefix. # import os # if event.src_path[len(os.getcwd()) + 1:].startswith( # CODE_DIRECTORY): # # sphinx-build doesn't always pick up changes on code files, # # even though they are used to generate the documentation. As # # a workaround, just clean before building. doc_html() print_success_message('Docs have been rebuilt.') print_success_message( 'Watching for changes in project files, press Ctrl-C to cancel...') handler = RebuildDocsEventHandler(get_project_files()) observer = Observer() observer.schedule(handler, path='.', recursive=True) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join()
python
def doc_watch(): """Watch for changes in the docs and rebuild HTML docs when changed.""" try: from watchdog.events import FileSystemEventHandler from watchdog.observers import Observer except ImportError: print_failure_message('Install the watchdog package to use this task, ' "i.e., `pip install watchdog'.") raise SystemExit(1) class RebuildDocsEventHandler(FileSystemEventHandler): def __init__(self, base_paths): self.base_paths = base_paths def dispatch(self, event): """Dispatches events to the appropriate methods. :param event: The event object representing the file system event. :type event: :class:`watchdog.events.FileSystemEvent` """ for base_path in self.base_paths: if event.src_path.endswith(base_path): super(RebuildDocsEventHandler, self).dispatch(event) # We found one that matches. We're done. return def on_modified(self, event): print_failure_message('Modification detected. Rebuilding docs.') # # Strip off the path prefix. # import os # if event.src_path[len(os.getcwd()) + 1:].startswith( # CODE_DIRECTORY): # # sphinx-build doesn't always pick up changes on code files, # # even though they are used to generate the documentation. As # # a workaround, just clean before building. doc_html() print_success_message('Docs have been rebuilt.') print_success_message( 'Watching for changes in project files, press Ctrl-C to cancel...') handler = RebuildDocsEventHandler(get_project_files()) observer = Observer() observer.schedule(handler, path='.', recursive=True) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join()
[ "def", "doc_watch", "(", ")", ":", "try", ":", "from", "watchdog", ".", "events", "import", "FileSystemEventHandler", "from", "watchdog", ".", "observers", "import", "Observer", "except", "ImportError", ":", "print_failure_message", "(", "'Install the watchdog package to use this task, '", "\"i.e., `pip install watchdog'.\"", ")", "raise", "SystemExit", "(", "1", ")", "class", "RebuildDocsEventHandler", "(", "FileSystemEventHandler", ")", ":", "def", "__init__", "(", "self", ",", "base_paths", ")", ":", "self", ".", "base_paths", "=", "base_paths", "def", "dispatch", "(", "self", ",", "event", ")", ":", "\"\"\"Dispatches events to the appropriate methods.\n :param event: The event object representing the file system event.\n :type event: :class:`watchdog.events.FileSystemEvent`\n \"\"\"", "for", "base_path", "in", "self", ".", "base_paths", ":", "if", "event", ".", "src_path", ".", "endswith", "(", "base_path", ")", ":", "super", "(", "RebuildDocsEventHandler", ",", "self", ")", ".", "dispatch", "(", "event", ")", "# We found one that matches. We're done.", "return", "def", "on_modified", "(", "self", ",", "event", ")", ":", "print_failure_message", "(", "'Modification detected. Rebuilding docs.'", ")", "# # Strip off the path prefix.", "# import os", "# if event.src_path[len(os.getcwd()) + 1:].startswith(", "# CODE_DIRECTORY):", "# # sphinx-build doesn't always pick up changes on code files,", "# # even though they are used to generate the documentation. As", "# # a workaround, just clean before building.", "doc_html", "(", ")", "print_success_message", "(", "'Docs have been rebuilt.'", ")", "print_success_message", "(", "'Watching for changes in project files, press Ctrl-C to cancel...'", ")", "handler", "=", "RebuildDocsEventHandler", "(", "get_project_files", "(", ")", ")", "observer", "=", "Observer", "(", ")", "observer", ".", "schedule", "(", "handler", ",", "path", "=", "'.'", ",", "recursive", "=", "True", ")", "observer", ".", "start", "(", ")", "try", ":", "while", "True", ":", "time", ".", "sleep", "(", "1", ")", "except", "KeyboardInterrupt", ":", "observer", ".", "stop", "(", ")", "observer", ".", "join", "(", ")" ]
Watch for changes in the docs and rebuild HTML docs when changed.
[ "Watch", "for", "changes", "in", "the", "docs", "and", "rebuild", "HTML", "docs", "when", "changed", "." ]
f25fca6afbf1abd46fd7aeb978282823c7dab5ab
https://github.com/abalkin/tz/blob/f25fca6afbf1abd46fd7aeb978282823c7dab5ab/pavement.py#L166-L214
251,451
abalkin/tz
pavement.py
doc_open
def doc_open(): """Build the HTML docs and open them in a web browser.""" doc_index = os.path.join(DOCS_DIRECTORY, 'build', 'html', 'index.html') if sys.platform == 'darwin': # Mac OS X subprocess.check_call(['open', doc_index]) elif sys.platform == 'win32': # Windows subprocess.check_call(['start', doc_index], shell=True) elif sys.platform == 'linux2': # All freedesktop-compatible desktops subprocess.check_call(['xdg-open', doc_index]) else: print_failure_message( "Unsupported platform. Please open `{0}' manually.".format( doc_index))
python
def doc_open(): """Build the HTML docs and open them in a web browser.""" doc_index = os.path.join(DOCS_DIRECTORY, 'build', 'html', 'index.html') if sys.platform == 'darwin': # Mac OS X subprocess.check_call(['open', doc_index]) elif sys.platform == 'win32': # Windows subprocess.check_call(['start', doc_index], shell=True) elif sys.platform == 'linux2': # All freedesktop-compatible desktops subprocess.check_call(['xdg-open', doc_index]) else: print_failure_message( "Unsupported platform. Please open `{0}' manually.".format( doc_index))
[ "def", "doc_open", "(", ")", ":", "doc_index", "=", "os", ".", "path", ".", "join", "(", "DOCS_DIRECTORY", ",", "'build'", ",", "'html'", ",", "'index.html'", ")", "if", "sys", ".", "platform", "==", "'darwin'", ":", "# Mac OS X", "subprocess", ".", "check_call", "(", "[", "'open'", ",", "doc_index", "]", ")", "elif", "sys", ".", "platform", "==", "'win32'", ":", "# Windows", "subprocess", ".", "check_call", "(", "[", "'start'", ",", "doc_index", "]", ",", "shell", "=", "True", ")", "elif", "sys", ".", "platform", "==", "'linux2'", ":", "# All freedesktop-compatible desktops", "subprocess", ".", "check_call", "(", "[", "'xdg-open'", ",", "doc_index", "]", ")", "else", ":", "print_failure_message", "(", "\"Unsupported platform. Please open `{0}' manually.\"", ".", "format", "(", "doc_index", ")", ")" ]
Build the HTML docs and open them in a web browser.
[ "Build", "the", "HTML", "docs", "and", "open", "them", "in", "a", "web", "browser", "." ]
f25fca6afbf1abd46fd7aeb978282823c7dab5ab
https://github.com/abalkin/tz/blob/f25fca6afbf1abd46fd7aeb978282823c7dab5ab/pavement.py#L219-L234
251,452
abalkin/tz
pavement.py
get_tasks
def get_tasks(): """Get all paver-defined tasks.""" from paver.tasks import environment for tsk in environment.get_tasks(): print(tsk.shortname)
python
def get_tasks(): """Get all paver-defined tasks.""" from paver.tasks import environment for tsk in environment.get_tasks(): print(tsk.shortname)
[ "def", "get_tasks", "(", ")", ":", "from", "paver", ".", "tasks", "import", "environment", "for", "tsk", "in", "environment", ".", "get_tasks", "(", ")", ":", "print", "(", "tsk", ".", "shortname", ")" ]
Get all paver-defined tasks.
[ "Get", "all", "paver", "-", "defined", "tasks", "." ]
f25fca6afbf1abd46fd7aeb978282823c7dab5ab
https://github.com/abalkin/tz/blob/f25fca6afbf1abd46fd7aeb978282823c7dab5ab/pavement.py#L238-L242
251,453
dr4ke616/pinky
twisted/plugins/node.py
NodeServiceMaker.makeService
def makeService(self, options): """ Construct a Node Server """ return NodeService( port=options['port'], host=options['host'], broker_host=options['broker_host'], broker_port=options['broker_port'], debug=options['debug'] )
python
def makeService(self, options): """ Construct a Node Server """ return NodeService( port=options['port'], host=options['host'], broker_host=options['broker_host'], broker_port=options['broker_port'], debug=options['debug'] )
[ "def", "makeService", "(", "self", ",", "options", ")", ":", "return", "NodeService", "(", "port", "=", "options", "[", "'port'", "]", ",", "host", "=", "options", "[", "'host'", "]", ",", "broker_host", "=", "options", "[", "'broker_host'", "]", ",", "broker_port", "=", "options", "[", "'broker_port'", "]", ",", "debug", "=", "options", "[", "'debug'", "]", ")" ]
Construct a Node Server
[ "Construct", "a", "Node", "Server" ]
35c165f5a1d410be467621f3152df1dbf458622a
https://github.com/dr4ke616/pinky/blob/35c165f5a1d410be467621f3152df1dbf458622a/twisted/plugins/node.py#L29-L38
251,454
KnowledgeLinks/rdfframework
rdfframework/rml/processor.py
Processor.add_to_triplestore
def add_to_triplestore(self, output): """Method attempts to add output to Blazegraph RDF Triplestore""" if len(output) > 0: result = self.ext_conn.load_data(data=output.serialize(), datatype='rdf')
python
def add_to_triplestore(self, output): """Method attempts to add output to Blazegraph RDF Triplestore""" if len(output) > 0: result = self.ext_conn.load_data(data=output.serialize(), datatype='rdf')
[ "def", "add_to_triplestore", "(", "self", ",", "output", ")", ":", "if", "len", "(", "output", ")", ">", "0", ":", "result", "=", "self", ".", "ext_conn", ".", "load_data", "(", "data", "=", "output", ".", "serialize", "(", ")", ",", "datatype", "=", "'rdf'", ")" ]
Method attempts to add output to Blazegraph RDF Triplestore
[ "Method", "attempts", "to", "add", "output", "to", "Blazegraph", "RDF", "Triplestore" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rml/processor.py#L397-L401
251,455
KnowledgeLinks/rdfframework
rdfframework/rml/processor.py
Processor.generate_term
def generate_term(self, **kwargs): """Method generates a rdflib.Term based on kwargs""" term_map = kwargs.pop('term_map') if hasattr(term_map, "termType") and\ term_map.termType == NS_MGR.rr.BlankNode.rdflib: return rdflib.BNode() if not hasattr(term_map, 'datatype'): term_map.datatype = NS_MGR.xsd.anyURI.rdflib if hasattr(term_map, "template") and term_map.template is not None: template_vars = kwargs template_vars.update(self.constants) # Call any functions to generate values for key, value in template_vars.items(): if hasattr(value, "__call__"): template_vars[key] = value() raw_value = term_map.template.format(**template_vars) if term_map.datatype == NS_MGR.xsd.anyURI.rdflib: return rdflib.URIRef(raw_value) return rdflib.Literal(raw_value, datatype=term_map.datatype) if term_map.reference is not None: # Each child will have different mechanisms for referencing the # source based return self.__generate_reference__(term_map, **kwargs)
python
def generate_term(self, **kwargs): """Method generates a rdflib.Term based on kwargs""" term_map = kwargs.pop('term_map') if hasattr(term_map, "termType") and\ term_map.termType == NS_MGR.rr.BlankNode.rdflib: return rdflib.BNode() if not hasattr(term_map, 'datatype'): term_map.datatype = NS_MGR.xsd.anyURI.rdflib if hasattr(term_map, "template") and term_map.template is not None: template_vars = kwargs template_vars.update(self.constants) # Call any functions to generate values for key, value in template_vars.items(): if hasattr(value, "__call__"): template_vars[key] = value() raw_value = term_map.template.format(**template_vars) if term_map.datatype == NS_MGR.xsd.anyURI.rdflib: return rdflib.URIRef(raw_value) return rdflib.Literal(raw_value, datatype=term_map.datatype) if term_map.reference is not None: # Each child will have different mechanisms for referencing the # source based return self.__generate_reference__(term_map, **kwargs)
[ "def", "generate_term", "(", "self", ",", "*", "*", "kwargs", ")", ":", "term_map", "=", "kwargs", ".", "pop", "(", "'term_map'", ")", "if", "hasattr", "(", "term_map", ",", "\"termType\"", ")", "and", "term_map", ".", "termType", "==", "NS_MGR", ".", "rr", ".", "BlankNode", ".", "rdflib", ":", "return", "rdflib", ".", "BNode", "(", ")", "if", "not", "hasattr", "(", "term_map", ",", "'datatype'", ")", ":", "term_map", ".", "datatype", "=", "NS_MGR", ".", "xsd", ".", "anyURI", ".", "rdflib", "if", "hasattr", "(", "term_map", ",", "\"template\"", ")", "and", "term_map", ".", "template", "is", "not", "None", ":", "template_vars", "=", "kwargs", "template_vars", ".", "update", "(", "self", ".", "constants", ")", "# Call any functions to generate values", "for", "key", ",", "value", "in", "template_vars", ".", "items", "(", ")", ":", "if", "hasattr", "(", "value", ",", "\"__call__\"", ")", ":", "template_vars", "[", "key", "]", "=", "value", "(", ")", "raw_value", "=", "term_map", ".", "template", ".", "format", "(", "*", "*", "template_vars", ")", "if", "term_map", ".", "datatype", "==", "NS_MGR", ".", "xsd", ".", "anyURI", ".", "rdflib", ":", "return", "rdflib", ".", "URIRef", "(", "raw_value", ")", "return", "rdflib", ".", "Literal", "(", "raw_value", ",", "datatype", "=", "term_map", ".", "datatype", ")", "if", "term_map", ".", "reference", "is", "not", "None", ":", "# Each child will have different mechanisms for referencing the", "# source based", "return", "self", ".", "__generate_reference__", "(", "term_map", ",", "*", "*", "kwargs", ")" ]
Method generates a rdflib.Term based on kwargs
[ "Method", "generates", "a", "rdflib", ".", "Term", "based", "on", "kwargs" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rml/processor.py#L403-L426
251,456
KnowledgeLinks/rdfframework
rdfframework/rml/processor.py
Processor.run
def run(self, **kwargs): """Run method iterates through triple maps and calls the execute method""" if 'timestamp' not in kwargs: kwargs['timestamp'] = datetime.datetime.utcnow().isoformat() if 'version' not in kwargs: kwargs['version'] = "Not Defined" #bibcat.__version__ # log.debug("kwargs: %s", pprint.pformat({k:v for k, v in kwargs.items() # if k != "dataset"})) # log.debug("parents: %s", self.parents) for map_key, triple_map in self.triple_maps.items(): if map_key not in self.parents: self.execute(triple_map, **kwargs)
python
def run(self, **kwargs): """Run method iterates through triple maps and calls the execute method""" if 'timestamp' not in kwargs: kwargs['timestamp'] = datetime.datetime.utcnow().isoformat() if 'version' not in kwargs: kwargs['version'] = "Not Defined" #bibcat.__version__ # log.debug("kwargs: %s", pprint.pformat({k:v for k, v in kwargs.items() # if k != "dataset"})) # log.debug("parents: %s", self.parents) for map_key, triple_map in self.triple_maps.items(): if map_key not in self.parents: self.execute(triple_map, **kwargs)
[ "def", "run", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "'timestamp'", "not", "in", "kwargs", ":", "kwargs", "[", "'timestamp'", "]", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ".", "isoformat", "(", ")", "if", "'version'", "not", "in", "kwargs", ":", "kwargs", "[", "'version'", "]", "=", "\"Not Defined\"", "#bibcat.__version__", "# log.debug(\"kwargs: %s\", pprint.pformat({k:v for k, v in kwargs.items()", "# if k != \"dataset\"}))", "# log.debug(\"parents: %s\", self.parents)", "for", "map_key", ",", "triple_map", "in", "self", ".", "triple_maps", ".", "items", "(", ")", ":", "if", "map_key", "not", "in", "self", ".", "parents", ":", "self", ".", "execute", "(", "triple_map", ",", "*", "*", "kwargs", ")" ]
Run method iterates through triple maps and calls the execute method
[ "Run", "method", "iterates", "through", "triple", "maps", "and", "calls", "the", "execute", "method" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rml/processor.py#L432-L444
251,457
KnowledgeLinks/rdfframework
rdfframework/rml/processor.py
Processor.set_context
def set_context(self): """ Reads throught the namespaces in the RML and generates a context for json+ld output when compared to the RdfNsManager namespaces """ results = self.rml.query(""" SELECT ?o { { ?s rr:class ?o } UNION { ?s rr:predicate ?o } }""") namespaces = [Uri(row[0]).value[0] for row in results if isinstance(row[0], rdflib.URIRef)] self.context = {ns[0]: ns[1] for ns in namespaces if ns[0]}
python
def set_context(self): """ Reads throught the namespaces in the RML and generates a context for json+ld output when compared to the RdfNsManager namespaces """ results = self.rml.query(""" SELECT ?o { { ?s rr:class ?o } UNION { ?s rr:predicate ?o } }""") namespaces = [Uri(row[0]).value[0] for row in results if isinstance(row[0], rdflib.URIRef)] self.context = {ns[0]: ns[1] for ns in namespaces if ns[0]}
[ "def", "set_context", "(", "self", ")", ":", "results", "=", "self", ".", "rml", ".", "query", "(", "\"\"\"\n SELECT ?o {\n {\n ?s rr:class ?o\n } UNION {\n ?s rr:predicate ?o\n }\n }\"\"\"", ")", "namespaces", "=", "[", "Uri", "(", "row", "[", "0", "]", ")", ".", "value", "[", "0", "]", "for", "row", "in", "results", "if", "isinstance", "(", "row", "[", "0", "]", ",", "rdflib", ".", "URIRef", ")", "]", "self", ".", "context", "=", "{", "ns", "[", "0", "]", ":", "ns", "[", "1", "]", "for", "ns", "in", "namespaces", "if", "ns", "[", "0", "]", "}" ]
Reads throught the namespaces in the RML and generates a context for json+ld output when compared to the RdfNsManager namespaces
[ "Reads", "throught", "the", "namespaces", "in", "the", "RML", "and", "generates", "a", "context", "for", "json", "+", "ld", "output", "when", "compared", "to", "the", "RdfNsManager", "namespaces" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rml/processor.py#L446-L462
251,458
KnowledgeLinks/rdfframework
rdfframework/rml/processor.py
Processor.json_ld
def json_ld(self, output, **kwargs): """ Returns the json-ld formated result """ raw_json_ld = output.serialize(format='json-ld', context=self.context).decode() # if there are fields that should be returned as arrays convert all # non-array fields to an array if not self.array_fields: return raw_json_ld json_data = json.loads(raw_json_ld) for i, item in enumerate(json_data['@graph']): if item.get("@type") in self.array_fields: test_flds = self.array_fields[item['@type']] for key, val in item.items(): if key in test_flds and not isinstance(val, list): json_data['@graph'][i][key] = [val] # print(json.dumps(json_data, indent=4)) return json.dumps(json_data, indent=4)
python
def json_ld(self, output, **kwargs): """ Returns the json-ld formated result """ raw_json_ld = output.serialize(format='json-ld', context=self.context).decode() # if there are fields that should be returned as arrays convert all # non-array fields to an array if not self.array_fields: return raw_json_ld json_data = json.loads(raw_json_ld) for i, item in enumerate(json_data['@graph']): if item.get("@type") in self.array_fields: test_flds = self.array_fields[item['@type']] for key, val in item.items(): if key in test_flds and not isinstance(val, list): json_data['@graph'][i][key] = [val] # print(json.dumps(json_data, indent=4)) return json.dumps(json_data, indent=4)
[ "def", "json_ld", "(", "self", ",", "output", ",", "*", "*", "kwargs", ")", ":", "raw_json_ld", "=", "output", ".", "serialize", "(", "format", "=", "'json-ld'", ",", "context", "=", "self", ".", "context", ")", ".", "decode", "(", ")", "# if there are fields that should be returned as arrays convert all", "# non-array fields to an array", "if", "not", "self", ".", "array_fields", ":", "return", "raw_json_ld", "json_data", "=", "json", ".", "loads", "(", "raw_json_ld", ")", "for", "i", ",", "item", "in", "enumerate", "(", "json_data", "[", "'@graph'", "]", ")", ":", "if", "item", ".", "get", "(", "\"@type\"", ")", "in", "self", ".", "array_fields", ":", "test_flds", "=", "self", ".", "array_fields", "[", "item", "[", "'@type'", "]", "]", "for", "key", ",", "val", "in", "item", ".", "items", "(", ")", ":", "if", "key", "in", "test_flds", "and", "not", "isinstance", "(", "val", ",", "list", ")", ":", "json_data", "[", "'@graph'", "]", "[", "i", "]", "[", "key", "]", "=", "[", "val", "]", "# print(json.dumps(json_data, indent=4))", "return", "json", ".", "dumps", "(", "json_data", ",", "indent", "=", "4", ")" ]
Returns the json-ld formated result
[ "Returns", "the", "json", "-", "ld", "formated", "result" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rml/processor.py#L501-L519
251,459
KnowledgeLinks/rdfframework
rdfframework/rml/processor.py
CSVRowProcessor.execute
def execute(self, triple_map, output, **kwargs): """Method executes mapping between CSV source and output RDF args: triple_map(SimpleNamespace): Triple Map """ subject = self.generate_term(term_map=triple_map.subjectMap, **kwargs) start_size = len(output) all_subjects = [] for pred_obj_map in triple_map.predicateObjectMap: predicate = pred_obj_map.predicate if pred_obj_map.template is not None: object_ = self.generate_term(term_map=pred_obj_map, **kwargs) if len(str(object)) > 0: output.add(( subject, predicate, object_)) if pred_obj_map.parentTriplesMap is not None: self.__handle_parents__( parent_map=pred_obj_map.parentTriplesMap, subject=subject, predicate=predicate, **kwargs) if pred_obj_map.reference is not None: object_ = self.generate_term(term_map=pred_obj_map, **kwargs) if object_ and len(str(object_)) > 0: output.add((subject, predicate, object_)) if pred_obj_map.constant is not None: output.add((subject, predicate, pred_obj_map.constant)) finish_size = len(output) if finish_size > start_size: output.add((subject, NS_MGR.rdf.type.rdflib, triple_map.subjectMap.class_)) all_subjects.append(subject) return all_subjects
python
def execute(self, triple_map, output, **kwargs): """Method executes mapping between CSV source and output RDF args: triple_map(SimpleNamespace): Triple Map """ subject = self.generate_term(term_map=triple_map.subjectMap, **kwargs) start_size = len(output) all_subjects = [] for pred_obj_map in triple_map.predicateObjectMap: predicate = pred_obj_map.predicate if pred_obj_map.template is not None: object_ = self.generate_term(term_map=pred_obj_map, **kwargs) if len(str(object)) > 0: output.add(( subject, predicate, object_)) if pred_obj_map.parentTriplesMap is not None: self.__handle_parents__( parent_map=pred_obj_map.parentTriplesMap, subject=subject, predicate=predicate, **kwargs) if pred_obj_map.reference is not None: object_ = self.generate_term(term_map=pred_obj_map, **kwargs) if object_ and len(str(object_)) > 0: output.add((subject, predicate, object_)) if pred_obj_map.constant is not None: output.add((subject, predicate, pred_obj_map.constant)) finish_size = len(output) if finish_size > start_size: output.add((subject, NS_MGR.rdf.type.rdflib, triple_map.subjectMap.class_)) all_subjects.append(subject) return all_subjects
[ "def", "execute", "(", "self", ",", "triple_map", ",", "output", ",", "*", "*", "kwargs", ")", ":", "subject", "=", "self", ".", "generate_term", "(", "term_map", "=", "triple_map", ".", "subjectMap", ",", "*", "*", "kwargs", ")", "start_size", "=", "len", "(", "output", ")", "all_subjects", "=", "[", "]", "for", "pred_obj_map", "in", "triple_map", ".", "predicateObjectMap", ":", "predicate", "=", "pred_obj_map", ".", "predicate", "if", "pred_obj_map", ".", "template", "is", "not", "None", ":", "object_", "=", "self", ".", "generate_term", "(", "term_map", "=", "pred_obj_map", ",", "*", "*", "kwargs", ")", "if", "len", "(", "str", "(", "object", ")", ")", ">", "0", ":", "output", ".", "add", "(", "(", "subject", ",", "predicate", ",", "object_", ")", ")", "if", "pred_obj_map", ".", "parentTriplesMap", "is", "not", "None", ":", "self", ".", "__handle_parents__", "(", "parent_map", "=", "pred_obj_map", ".", "parentTriplesMap", ",", "subject", "=", "subject", ",", "predicate", "=", "predicate", ",", "*", "*", "kwargs", ")", "if", "pred_obj_map", ".", "reference", "is", "not", "None", ":", "object_", "=", "self", ".", "generate_term", "(", "term_map", "=", "pred_obj_map", ",", "*", "*", "kwargs", ")", "if", "object_", "and", "len", "(", "str", "(", "object_", ")", ")", ">", "0", ":", "output", ".", "add", "(", "(", "subject", ",", "predicate", ",", "object_", ")", ")", "if", "pred_obj_map", ".", "constant", "is", "not", "None", ":", "output", ".", "add", "(", "(", "subject", ",", "predicate", ",", "pred_obj_map", ".", "constant", ")", ")", "finish_size", "=", "len", "(", "output", ")", "if", "finish_size", ">", "start_size", ":", "output", ".", "add", "(", "(", "subject", ",", "NS_MGR", ".", "rdf", ".", "type", ".", "rdflib", ",", "triple_map", ".", "subjectMap", ".", "class_", ")", ")", "all_subjects", ".", "append", "(", "subject", ")", "return", "all_subjects" ]
Method executes mapping between CSV source and output RDF args: triple_map(SimpleNamespace): Triple Map
[ "Method", "executes", "mapping", "between", "CSV", "source", "and", "output", "RDF" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rml/processor.py#L586-L626
251,460
KnowledgeLinks/rdfframework
rdfframework/rml/processor.py
CSVRowProcessor.run
def run(self, row, **kwargs): """Methods takes a row and depending if a dict or list, runs RML rules. Args: ----- row(Dict, List): Row from CSV Reader """ self.source = row kwargs['output'] = self.__graph__() super(CSVRowProcessor, self).run(**kwargs) return kwargs['output']
python
def run(self, row, **kwargs): """Methods takes a row and depending if a dict or list, runs RML rules. Args: ----- row(Dict, List): Row from CSV Reader """ self.source = row kwargs['output'] = self.__graph__() super(CSVRowProcessor, self).run(**kwargs) return kwargs['output']
[ "def", "run", "(", "self", ",", "row", ",", "*", "*", "kwargs", ")", ":", "self", ".", "source", "=", "row", "kwargs", "[", "'output'", "]", "=", "self", ".", "__graph__", "(", ")", "super", "(", "CSVRowProcessor", ",", "self", ")", ".", "run", "(", "*", "*", "kwargs", ")", "return", "kwargs", "[", "'output'", "]" ]
Methods takes a row and depending if a dict or list, runs RML rules. Args: ----- row(Dict, List): Row from CSV Reader
[ "Methods", "takes", "a", "row", "and", "depending", "if", "a", "dict", "or", "list", "runs", "RML", "rules", "." ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rml/processor.py#L630-L641
251,461
KnowledgeLinks/rdfframework
rdfframework/rml/processor.py
JSONProcessor.execute
def execute(self, triple_map, output, **kwargs): """Method executes mapping between JSON source and output RDF Args: ----- triple_map: SimpleNamespace """ subjects = [] logical_src_iterator = str(triple_map.logicalSource.iterator) json_object = kwargs.get('obj', self.source) # Removes '.' as a generic iterator, replace with '@' if logical_src_iterator == ".": results = [None,] else: json_path_exp = jsonpath_ng.parse(logical_src_iterator) results = [r.value for r in json_path_exp.find(json_object)][0] for row in results: subject = self.generate_term(term_map=triple_map.subjectMap, **kwargs) for pred_obj_map in triple_map.predicateObjectMap: predicate = pred_obj_map.predicate if pred_obj_map.template is not None: output.add(( subject, predicate, self.generate_term(term_map=pred_obj_map, **kwargs))) if pred_obj_map.parentTriplesMap is not None: self.__handle_parents__( output, parent_map=pred_obj_map.parentTriplesMap, subject=subject, predicate=predicate, obj=row, **kwargs) if pred_obj_map.reference is not None: ref_exp = jsonpath_ng.parse(str(pred_obj_map.reference)) found_objects = [r.value for r in ref_exp.find(row)] for obj in found_objects: if rdflib.term._is_valid_uri(obj): rdf_obj = rdflib.URIRef(str(obj)) else: rdf_obj = rdflib.Literal(str(obj)) output.add((subject, predicate, rdf_obj)) if pred_obj_map.constant is not None: output.add((subject, predicate, pred_obj_map.constant)) subjects.append(subject) return subjects
python
def execute(self, triple_map, output, **kwargs): """Method executes mapping between JSON source and output RDF Args: ----- triple_map: SimpleNamespace """ subjects = [] logical_src_iterator = str(triple_map.logicalSource.iterator) json_object = kwargs.get('obj', self.source) # Removes '.' as a generic iterator, replace with '@' if logical_src_iterator == ".": results = [None,] else: json_path_exp = jsonpath_ng.parse(logical_src_iterator) results = [r.value for r in json_path_exp.find(json_object)][0] for row in results: subject = self.generate_term(term_map=triple_map.subjectMap, **kwargs) for pred_obj_map in triple_map.predicateObjectMap: predicate = pred_obj_map.predicate if pred_obj_map.template is not None: output.add(( subject, predicate, self.generate_term(term_map=pred_obj_map, **kwargs))) if pred_obj_map.parentTriplesMap is not None: self.__handle_parents__( output, parent_map=pred_obj_map.parentTriplesMap, subject=subject, predicate=predicate, obj=row, **kwargs) if pred_obj_map.reference is not None: ref_exp = jsonpath_ng.parse(str(pred_obj_map.reference)) found_objects = [r.value for r in ref_exp.find(row)] for obj in found_objects: if rdflib.term._is_valid_uri(obj): rdf_obj = rdflib.URIRef(str(obj)) else: rdf_obj = rdflib.Literal(str(obj)) output.add((subject, predicate, rdf_obj)) if pred_obj_map.constant is not None: output.add((subject, predicate, pred_obj_map.constant)) subjects.append(subject) return subjects
[ "def", "execute", "(", "self", ",", "triple_map", ",", "output", ",", "*", "*", "kwargs", ")", ":", "subjects", "=", "[", "]", "logical_src_iterator", "=", "str", "(", "triple_map", ".", "logicalSource", ".", "iterator", ")", "json_object", "=", "kwargs", ".", "get", "(", "'obj'", ",", "self", ".", "source", ")", "# Removes '.' as a generic iterator, replace with '@'", "if", "logical_src_iterator", "==", "\".\"", ":", "results", "=", "[", "None", ",", "]", "else", ":", "json_path_exp", "=", "jsonpath_ng", ".", "parse", "(", "logical_src_iterator", ")", "results", "=", "[", "r", ".", "value", "for", "r", "in", "json_path_exp", ".", "find", "(", "json_object", ")", "]", "[", "0", "]", "for", "row", "in", "results", ":", "subject", "=", "self", ".", "generate_term", "(", "term_map", "=", "triple_map", ".", "subjectMap", ",", "*", "*", "kwargs", ")", "for", "pred_obj_map", "in", "triple_map", ".", "predicateObjectMap", ":", "predicate", "=", "pred_obj_map", ".", "predicate", "if", "pred_obj_map", ".", "template", "is", "not", "None", ":", "output", ".", "add", "(", "(", "subject", ",", "predicate", ",", "self", ".", "generate_term", "(", "term_map", "=", "pred_obj_map", ",", "*", "*", "kwargs", ")", ")", ")", "if", "pred_obj_map", ".", "parentTriplesMap", "is", "not", "None", ":", "self", ".", "__handle_parents__", "(", "output", ",", "parent_map", "=", "pred_obj_map", ".", "parentTriplesMap", ",", "subject", "=", "subject", ",", "predicate", "=", "predicate", ",", "obj", "=", "row", ",", "*", "*", "kwargs", ")", "if", "pred_obj_map", ".", "reference", "is", "not", "None", ":", "ref_exp", "=", "jsonpath_ng", ".", "parse", "(", "str", "(", "pred_obj_map", ".", "reference", ")", ")", "found_objects", "=", "[", "r", ".", "value", "for", "r", "in", "ref_exp", ".", "find", "(", "row", ")", "]", "for", "obj", "in", "found_objects", ":", "if", "rdflib", ".", "term", ".", "_is_valid_uri", "(", "obj", ")", ":", "rdf_obj", "=", "rdflib", ".", "URIRef", "(", "str", "(", "obj", ")", ")", "else", ":", "rdf_obj", "=", "rdflib", ".", "Literal", "(", "str", "(", "obj", ")", ")", "output", ".", "add", "(", "(", "subject", ",", "predicate", ",", "rdf_obj", ")", ")", "if", "pred_obj_map", ".", "constant", "is", "not", "None", ":", "output", ".", "add", "(", "(", "subject", ",", "predicate", ",", "pred_obj_map", ".", "constant", ")", ")", "subjects", ".", "append", "(", "subject", ")", "return", "subjects" ]
Method executes mapping between JSON source and output RDF Args: ----- triple_map: SimpleNamespace
[ "Method", "executes", "mapping", "between", "JSON", "source", "and", "output", "RDF" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rml/processor.py#L685-L736
251,462
KnowledgeLinks/rdfframework
rdfframework/rml/processor.py
JSONProcessor.run
def run(self, source, **kwargs): """Method takes a JSON source and any keywords and transforms from JSON to Lean BIBFRAME 2.0 triples Args: ---- source: str, dict """ kwargs['output'] = self.__graph__() if isinstance(source, str): import json source = json.loads(source) self.source = source super(JSONProcessor, self).run(**kwargs) self.output = kwargs['output'] return output
python
def run(self, source, **kwargs): """Method takes a JSON source and any keywords and transforms from JSON to Lean BIBFRAME 2.0 triples Args: ---- source: str, dict """ kwargs['output'] = self.__graph__() if isinstance(source, str): import json source = json.loads(source) self.source = source super(JSONProcessor, self).run(**kwargs) self.output = kwargs['output'] return output
[ "def", "run", "(", "self", ",", "source", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'output'", "]", "=", "self", ".", "__graph__", "(", ")", "if", "isinstance", "(", "source", ",", "str", ")", ":", "import", "json", "source", "=", "json", ".", "loads", "(", "source", ")", "self", ".", "source", "=", "source", "super", "(", "JSONProcessor", ",", "self", ")", ".", "run", "(", "*", "*", "kwargs", ")", "self", ".", "output", "=", "kwargs", "[", "'output'", "]", "return", "output" ]
Method takes a JSON source and any keywords and transforms from JSON to Lean BIBFRAME 2.0 triples Args: ---- source: str, dict
[ "Method", "takes", "a", "JSON", "source", "and", "any", "keywords", "and", "transforms", "from", "JSON", "to", "Lean", "BIBFRAME", "2", ".", "0", "triples" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rml/processor.py#L738-L754
251,463
KnowledgeLinks/rdfframework
rdfframework/rml/processor.py
XMLProcessor.execute
def execute(self, triple_map, output, **kwargs): """Method executes mapping between source Args: ----- triple_map: SimpleNamespace, Triple Map """ subjects = [] found_elements = self.source.xpath( str(triple_map.logicalSource.iterator), namespaces=self.xml_ns) for element in found_elements: subject = self.generate_term(term_map=triple_map.subjectMap, element=element, **kwargs) start = len(output) for row in triple_map.predicateObjectMap: predicate = row.predicate if row.template is not None: obj_ = self.generate_term(term_map=row, **kwargs) output.add((subject, predicate, obj_)) if row.parentTriplesMap is not None: self.__handle_parents__( output, parent_map=row.parentTriplesMap, subject=subject, predicate=predicate, **kwargs) new_subjects = self.__reference_handler__( output, predicate_obj_map=row, element=element, subject=subject) subjects.extend(new_subjects) if row.constant is not None: output.add((subject, predicate, row.constant)) if start < len(output): if triple_map.subjectMap.class_ is not None: output.add((subject, NS_MGR.rdf.type.rdflib, triple_map.subjectMap.class_)) subjects.append(subject) return subjects
python
def execute(self, triple_map, output, **kwargs): """Method executes mapping between source Args: ----- triple_map: SimpleNamespace, Triple Map """ subjects = [] found_elements = self.source.xpath( str(triple_map.logicalSource.iterator), namespaces=self.xml_ns) for element in found_elements: subject = self.generate_term(term_map=triple_map.subjectMap, element=element, **kwargs) start = len(output) for row in triple_map.predicateObjectMap: predicate = row.predicate if row.template is not None: obj_ = self.generate_term(term_map=row, **kwargs) output.add((subject, predicate, obj_)) if row.parentTriplesMap is not None: self.__handle_parents__( output, parent_map=row.parentTriplesMap, subject=subject, predicate=predicate, **kwargs) new_subjects = self.__reference_handler__( output, predicate_obj_map=row, element=element, subject=subject) subjects.extend(new_subjects) if row.constant is not None: output.add((subject, predicate, row.constant)) if start < len(output): if triple_map.subjectMap.class_ is not None: output.add((subject, NS_MGR.rdf.type.rdflib, triple_map.subjectMap.class_)) subjects.append(subject) return subjects
[ "def", "execute", "(", "self", ",", "triple_map", ",", "output", ",", "*", "*", "kwargs", ")", ":", "subjects", "=", "[", "]", "found_elements", "=", "self", ".", "source", ".", "xpath", "(", "str", "(", "triple_map", ".", "logicalSource", ".", "iterator", ")", ",", "namespaces", "=", "self", ".", "xml_ns", ")", "for", "element", "in", "found_elements", ":", "subject", "=", "self", ".", "generate_term", "(", "term_map", "=", "triple_map", ".", "subjectMap", ",", "element", "=", "element", ",", "*", "*", "kwargs", ")", "start", "=", "len", "(", "output", ")", "for", "row", "in", "triple_map", ".", "predicateObjectMap", ":", "predicate", "=", "row", ".", "predicate", "if", "row", ".", "template", "is", "not", "None", ":", "obj_", "=", "self", ".", "generate_term", "(", "term_map", "=", "row", ",", "*", "*", "kwargs", ")", "output", ".", "add", "(", "(", "subject", ",", "predicate", ",", "obj_", ")", ")", "if", "row", ".", "parentTriplesMap", "is", "not", "None", ":", "self", ".", "__handle_parents__", "(", "output", ",", "parent_map", "=", "row", ".", "parentTriplesMap", ",", "subject", "=", "subject", ",", "predicate", "=", "predicate", ",", "*", "*", "kwargs", ")", "new_subjects", "=", "self", ".", "__reference_handler__", "(", "output", ",", "predicate_obj_map", "=", "row", ",", "element", "=", "element", ",", "subject", "=", "subject", ")", "subjects", ".", "extend", "(", "new_subjects", ")", "if", "row", ".", "constant", "is", "not", "None", ":", "output", ".", "add", "(", "(", "subject", ",", "predicate", ",", "row", ".", "constant", ")", ")", "if", "start", "<", "len", "(", "output", ")", ":", "if", "triple_map", ".", "subjectMap", ".", "class_", "is", "not", "None", ":", "output", ".", "add", "(", "(", "subject", ",", "NS_MGR", ".", "rdf", ".", "type", ".", "rdflib", ",", "triple_map", ".", "subjectMap", ".", "class_", ")", ")", "subjects", ".", "append", "(", "subject", ")", "return", "subjects" ]
Method executes mapping between source Args: ----- triple_map: SimpleNamespace, Triple Map
[ "Method", "executes", "mapping", "between", "source" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rml/processor.py#L846-L890
251,464
KnowledgeLinks/rdfframework
rdfframework/rml/processor.py
XMLProcessor.run
def run(self, xml, **kwargs): """Method takes either an etree.ElementTree or raw XML text as the first argument. Args: xml(etree.ElementTree or text """ kwargs['output'] = self.__graph__() if isinstance(xml, str): try: self.source = etree.XML(xml) except ValueError: try: self.source = etree.XML(xml.encode()) except: raise ValueError("Cannot run error {}".format(sys.exc_info()[0])) else: self.source = xml super(XMLProcessor, self).run(**kwargs) self.output = kwargs['output'] return kwargs['output']
python
def run(self, xml, **kwargs): """Method takes either an etree.ElementTree or raw XML text as the first argument. Args: xml(etree.ElementTree or text """ kwargs['output'] = self.__graph__() if isinstance(xml, str): try: self.source = etree.XML(xml) except ValueError: try: self.source = etree.XML(xml.encode()) except: raise ValueError("Cannot run error {}".format(sys.exc_info()[0])) else: self.source = xml super(XMLProcessor, self).run(**kwargs) self.output = kwargs['output'] return kwargs['output']
[ "def", "run", "(", "self", ",", "xml", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'output'", "]", "=", "self", ".", "__graph__", "(", ")", "if", "isinstance", "(", "xml", ",", "str", ")", ":", "try", ":", "self", ".", "source", "=", "etree", ".", "XML", "(", "xml", ")", "except", "ValueError", ":", "try", ":", "self", ".", "source", "=", "etree", ".", "XML", "(", "xml", ".", "encode", "(", ")", ")", "except", ":", "raise", "ValueError", "(", "\"Cannot run error {}\"", ".", "format", "(", "sys", ".", "exc_info", "(", ")", "[", "0", "]", ")", ")", "else", ":", "self", ".", "source", "=", "xml", "super", "(", "XMLProcessor", ",", "self", ")", ".", "run", "(", "*", "*", "kwargs", ")", "self", ".", "output", "=", "kwargs", "[", "'output'", "]", "return", "kwargs", "[", "'output'", "]" ]
Method takes either an etree.ElementTree or raw XML text as the first argument. Args: xml(etree.ElementTree or text
[ "Method", "takes", "either", "an", "etree", ".", "ElementTree", "or", "raw", "XML", "text", "as", "the", "first", "argument", "." ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rml/processor.py#L894-L914
251,465
KnowledgeLinks/rdfframework
rdfframework/rml/processor.py
SPARQLBatchProcessor.execute
def execute(self, triple_map, output, **kwargs): """Method iterates through triple map's predicate object maps and processes query. Args: triple_map(SimpleNamespace): Triple Map """ sparql = PREFIX + triple_map.logicalSource.query.format( **kwargs) bindings = self.__get_bindings__(sparql) iterator = str(triple_map.logicalSource.iterator) for binding in bindings: entity_dict = binding.get(iterator) if isinstance(entity_dict, rdflib.term.Node): entity = entity_dict elif isinstance(entity_dict, dict): raw_value = entity_dict.get('value') if entity_dict.get('type').startswith('bnode'): entity = rdflib.BNode(raw_value) else: entity = rdflib.URIRef(raw_value) if triple_map.subjectMap.class_ is not None: output.add( (entity, rdflib.RDF.type, triple_map.subjectMap.class_)) sparql_query = self.__construct_compound_query__( triple_map).format(**kwargs) properties = self.__get_bindings__(sparql_query) for pred_obj_map in triple_map.predicateObjectMap: predicate = pred_obj_map.predicate if pred_obj_map.constant is not None: output.add( (entity, predicate, pred_obj_map.constant)) continue if "#" in str(predicate): key = str(predicate).split("#")[-1] else: key = str(predicate).split("/")[-1] for property_ in properties: if key in property_.keys(): info = {"about": property_.get(key)} object_ = __get_object__(info) output.add((entity, predicate, object_))
python
def execute(self, triple_map, output, **kwargs): """Method iterates through triple map's predicate object maps and processes query. Args: triple_map(SimpleNamespace): Triple Map """ sparql = PREFIX + triple_map.logicalSource.query.format( **kwargs) bindings = self.__get_bindings__(sparql) iterator = str(triple_map.logicalSource.iterator) for binding in bindings: entity_dict = binding.get(iterator) if isinstance(entity_dict, rdflib.term.Node): entity = entity_dict elif isinstance(entity_dict, dict): raw_value = entity_dict.get('value') if entity_dict.get('type').startswith('bnode'): entity = rdflib.BNode(raw_value) else: entity = rdflib.URIRef(raw_value) if triple_map.subjectMap.class_ is not None: output.add( (entity, rdflib.RDF.type, triple_map.subjectMap.class_)) sparql_query = self.__construct_compound_query__( triple_map).format(**kwargs) properties = self.__get_bindings__(sparql_query) for pred_obj_map in triple_map.predicateObjectMap: predicate = pred_obj_map.predicate if pred_obj_map.constant is not None: output.add( (entity, predicate, pred_obj_map.constant)) continue if "#" in str(predicate): key = str(predicate).split("#")[-1] else: key = str(predicate).split("/")[-1] for property_ in properties: if key in property_.keys(): info = {"about": property_.get(key)} object_ = __get_object__(info) output.add((entity, predicate, object_))
[ "def", "execute", "(", "self", ",", "triple_map", ",", "output", ",", "*", "*", "kwargs", ")", ":", "sparql", "=", "PREFIX", "+", "triple_map", ".", "logicalSource", ".", "query", ".", "format", "(", "*", "*", "kwargs", ")", "bindings", "=", "self", ".", "__get_bindings__", "(", "sparql", ")", "iterator", "=", "str", "(", "triple_map", ".", "logicalSource", ".", "iterator", ")", "for", "binding", "in", "bindings", ":", "entity_dict", "=", "binding", ".", "get", "(", "iterator", ")", "if", "isinstance", "(", "entity_dict", ",", "rdflib", ".", "term", ".", "Node", ")", ":", "entity", "=", "entity_dict", "elif", "isinstance", "(", "entity_dict", ",", "dict", ")", ":", "raw_value", "=", "entity_dict", ".", "get", "(", "'value'", ")", "if", "entity_dict", ".", "get", "(", "'type'", ")", ".", "startswith", "(", "'bnode'", ")", ":", "entity", "=", "rdflib", ".", "BNode", "(", "raw_value", ")", "else", ":", "entity", "=", "rdflib", ".", "URIRef", "(", "raw_value", ")", "if", "triple_map", ".", "subjectMap", ".", "class_", "is", "not", "None", ":", "output", ".", "add", "(", "(", "entity", ",", "rdflib", ".", "RDF", ".", "type", ",", "triple_map", ".", "subjectMap", ".", "class_", ")", ")", "sparql_query", "=", "self", ".", "__construct_compound_query__", "(", "triple_map", ")", ".", "format", "(", "*", "*", "kwargs", ")", "properties", "=", "self", ".", "__get_bindings__", "(", "sparql_query", ")", "for", "pred_obj_map", "in", "triple_map", ".", "predicateObjectMap", ":", "predicate", "=", "pred_obj_map", ".", "predicate", "if", "pred_obj_map", ".", "constant", "is", "not", "None", ":", "output", ".", "add", "(", "(", "entity", ",", "predicate", ",", "pred_obj_map", ".", "constant", ")", ")", "continue", "if", "\"#\"", "in", "str", "(", "predicate", ")", ":", "key", "=", "str", "(", "predicate", ")", ".", "split", "(", "\"#\"", ")", "[", "-", "1", "]", "else", ":", "key", "=", "str", "(", "predicate", ")", ".", "split", "(", "\"/\"", ")", "[", "-", "1", "]", "for", "property_", "in", "properties", ":", "if", "key", "in", "property_", ".", "keys", "(", ")", ":", "info", "=", "{", "\"about\"", ":", "property_", ".", "get", "(", "key", ")", "}", "object_", "=", "__get_object__", "(", "info", ")", "output", ".", "add", "(", "(", "entity", ",", "predicate", ",", "object_", ")", ")" ]
Method iterates through triple map's predicate object maps and processes query. Args: triple_map(SimpleNamespace): Triple Map
[ "Method", "iterates", "through", "triple", "map", "s", "predicate", "object", "maps", "and", "processes", "query", "." ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rml/processor.py#L1191-L1236
251,466
eallik/spinoff
spinoff/actor/ref.py
Ref.send
def send(self, message, _sender=None): """Sends a message to the actor represented by this `Ref`.""" if not _sender: context = get_context() if context: _sender = context.ref if self._cell: if not self._cell.stopped: self._cell.receive(message, _sender) return else: self._cell = None if not self.is_local: if self.uri.node != self.node.nid: self.node.send_message(message, remote_ref=self, sender=_sender) else: self._cell = self.node.guardian.lookup_cell(self.uri) self.is_local = True self._cell.receive(message, _sender) else: if self.node and self.node.guardian: cell = self.node.guardian.lookup_cell(self.uri) if cell: cell.receive(message, _sender) # do NOT set self._cell--it will never be unset and will cause a memleak return if ('_watched', ANY) == message: message[1].send(('terminated', self), _sender=self) elif (message == ('terminated', ANY) or message == ('_unwatched', ANY) or message == ('_node_down', ANY) or message == '_stop' or message == '_kill' or message == '__done'): pass else: Events.log(DeadLetter(self, message, _sender))
python
def send(self, message, _sender=None): """Sends a message to the actor represented by this `Ref`.""" if not _sender: context = get_context() if context: _sender = context.ref if self._cell: if not self._cell.stopped: self._cell.receive(message, _sender) return else: self._cell = None if not self.is_local: if self.uri.node != self.node.nid: self.node.send_message(message, remote_ref=self, sender=_sender) else: self._cell = self.node.guardian.lookup_cell(self.uri) self.is_local = True self._cell.receive(message, _sender) else: if self.node and self.node.guardian: cell = self.node.guardian.lookup_cell(self.uri) if cell: cell.receive(message, _sender) # do NOT set self._cell--it will never be unset and will cause a memleak return if ('_watched', ANY) == message: message[1].send(('terminated', self), _sender=self) elif (message == ('terminated', ANY) or message == ('_unwatched', ANY) or message == ('_node_down', ANY) or message == '_stop' or message == '_kill' or message == '__done'): pass else: Events.log(DeadLetter(self, message, _sender))
[ "def", "send", "(", "self", ",", "message", ",", "_sender", "=", "None", ")", ":", "if", "not", "_sender", ":", "context", "=", "get_context", "(", ")", "if", "context", ":", "_sender", "=", "context", ".", "ref", "if", "self", ".", "_cell", ":", "if", "not", "self", ".", "_cell", ".", "stopped", ":", "self", ".", "_cell", ".", "receive", "(", "message", ",", "_sender", ")", "return", "else", ":", "self", ".", "_cell", "=", "None", "if", "not", "self", ".", "is_local", ":", "if", "self", ".", "uri", ".", "node", "!=", "self", ".", "node", ".", "nid", ":", "self", ".", "node", ".", "send_message", "(", "message", ",", "remote_ref", "=", "self", ",", "sender", "=", "_sender", ")", "else", ":", "self", ".", "_cell", "=", "self", ".", "node", ".", "guardian", ".", "lookup_cell", "(", "self", ".", "uri", ")", "self", ".", "is_local", "=", "True", "self", ".", "_cell", ".", "receive", "(", "message", ",", "_sender", ")", "else", ":", "if", "self", ".", "node", "and", "self", ".", "node", ".", "guardian", ":", "cell", "=", "self", ".", "node", ".", "guardian", ".", "lookup_cell", "(", "self", ".", "uri", ")", "if", "cell", ":", "cell", ".", "receive", "(", "message", ",", "_sender", ")", "# do NOT set self._cell--it will never be unset and will cause a memleak", "return", "if", "(", "'_watched'", ",", "ANY", ")", "==", "message", ":", "message", "[", "1", "]", ".", "send", "(", "(", "'terminated'", ",", "self", ")", ",", "_sender", "=", "self", ")", "elif", "(", "message", "==", "(", "'terminated'", ",", "ANY", ")", "or", "message", "==", "(", "'_unwatched'", ",", "ANY", ")", "or", "message", "==", "(", "'_node_down'", ",", "ANY", ")", "or", "message", "==", "'_stop'", "or", "message", "==", "'_kill'", "or", "message", "==", "'__done'", ")", ":", "pass", "else", ":", "Events", ".", "log", "(", "DeadLetter", "(", "self", ",", "message", ",", "_sender", ")", ")" ]
Sends a message to the actor represented by this `Ref`.
[ "Sends", "a", "message", "to", "the", "actor", "represented", "by", "this", "Ref", "." ]
06b00d6b86c7422c9cb8f9a4b2915906e92b7d52
https://github.com/eallik/spinoff/blob/06b00d6b86c7422c9cb8f9a4b2915906e92b7d52/spinoff/actor/ref.py#L139-L170
251,467
tBaxter/tango-comments
build/lib/tango_comments/forms.py
CommentSecurityForm.security_errors
def security_errors(self): """Return just those errors associated with security""" errors = ErrorDict() for f in ["honeypot", "timestamp", "security_hash"]: if f in self.errors: errors[f] = self.errors[f] return errors
python
def security_errors(self): """Return just those errors associated with security""" errors = ErrorDict() for f in ["honeypot", "timestamp", "security_hash"]: if f in self.errors: errors[f] = self.errors[f] return errors
[ "def", "security_errors", "(", "self", ")", ":", "errors", "=", "ErrorDict", "(", ")", "for", "f", "in", "[", "\"honeypot\"", ",", "\"timestamp\"", ",", "\"security_hash\"", "]", ":", "if", "f", "in", "self", ".", "errors", ":", "errors", "[", "f", "]", "=", "self", ".", "errors", "[", "f", "]", "return", "errors" ]
Return just those errors associated with security
[ "Return", "just", "those", "errors", "associated", "with", "security" ]
1fd335c6fc9e81bba158e42e1483f1a149622ab4
https://github.com/tBaxter/tango-comments/blob/1fd335c6fc9e81bba158e42e1483f1a149622ab4/build/lib/tango_comments/forms.py#L34-L40
251,468
tBaxter/tango-comments
build/lib/tango_comments/forms.py
CommentSecurityForm.clean_security_hash
def clean_security_hash(self): """Check the security hash.""" security_hash_dict = { 'content_type': self.data.get("content_type", ""), 'object_pk': self.data.get("object_pk", ""), 'timestamp': self.data.get("timestamp", ""), } expected_hash = self.generate_security_hash(**security_hash_dict) actual_hash = self.cleaned_data["security_hash"] if not constant_time_compare(expected_hash, actual_hash): raise forms.ValidationError("Security hash check failed.") return actual_hash
python
def clean_security_hash(self): """Check the security hash.""" security_hash_dict = { 'content_type': self.data.get("content_type", ""), 'object_pk': self.data.get("object_pk", ""), 'timestamp': self.data.get("timestamp", ""), } expected_hash = self.generate_security_hash(**security_hash_dict) actual_hash = self.cleaned_data["security_hash"] if not constant_time_compare(expected_hash, actual_hash): raise forms.ValidationError("Security hash check failed.") return actual_hash
[ "def", "clean_security_hash", "(", "self", ")", ":", "security_hash_dict", "=", "{", "'content_type'", ":", "self", ".", "data", ".", "get", "(", "\"content_type\"", ",", "\"\"", ")", ",", "'object_pk'", ":", "self", ".", "data", ".", "get", "(", "\"object_pk\"", ",", "\"\"", ")", ",", "'timestamp'", ":", "self", ".", "data", ".", "get", "(", "\"timestamp\"", ",", "\"\"", ")", ",", "}", "expected_hash", "=", "self", ".", "generate_security_hash", "(", "*", "*", "security_hash_dict", ")", "actual_hash", "=", "self", ".", "cleaned_data", "[", "\"security_hash\"", "]", "if", "not", "constant_time_compare", "(", "expected_hash", ",", "actual_hash", ")", ":", "raise", "forms", ".", "ValidationError", "(", "\"Security hash check failed.\"", ")", "return", "actual_hash" ]
Check the security hash.
[ "Check", "the", "security", "hash", "." ]
1fd335c6fc9e81bba158e42e1483f1a149622ab4
https://github.com/tBaxter/tango-comments/blob/1fd335c6fc9e81bba158e42e1483f1a149622ab4/build/lib/tango_comments/forms.py#L42-L53
251,469
tBaxter/tango-comments
build/lib/tango_comments/forms.py
CommentSecurityForm.generate_security_data
def generate_security_data(self): """Generate a dict of security data for "initial" data.""" timestamp = int(time.time()) security_dict = { 'content_type': str(self.target_object._meta), 'object_pk': str(self.target_object._get_pk_val()), 'timestamp': str(timestamp), 'security_hash': self.initial_security_hash(timestamp), } return security_dict
python
def generate_security_data(self): """Generate a dict of security data for "initial" data.""" timestamp = int(time.time()) security_dict = { 'content_type': str(self.target_object._meta), 'object_pk': str(self.target_object._get_pk_val()), 'timestamp': str(timestamp), 'security_hash': self.initial_security_hash(timestamp), } return security_dict
[ "def", "generate_security_data", "(", "self", ")", ":", "timestamp", "=", "int", "(", "time", ".", "time", "(", ")", ")", "security_dict", "=", "{", "'content_type'", ":", "str", "(", "self", ".", "target_object", ".", "_meta", ")", ",", "'object_pk'", ":", "str", "(", "self", ".", "target_object", ".", "_get_pk_val", "(", ")", ")", ",", "'timestamp'", ":", "str", "(", "timestamp", ")", ",", "'security_hash'", ":", "self", ".", "initial_security_hash", "(", "timestamp", ")", ",", "}", "return", "security_dict" ]
Generate a dict of security data for "initial" data.
[ "Generate", "a", "dict", "of", "security", "data", "for", "initial", "data", "." ]
1fd335c6fc9e81bba158e42e1483f1a149622ab4
https://github.com/tBaxter/tango-comments/blob/1fd335c6fc9e81bba158e42e1483f1a149622ab4/build/lib/tango_comments/forms.py#L62-L71
251,470
tBaxter/tango-comments
build/lib/tango_comments/forms.py
CommentSecurityForm.generate_security_hash
def generate_security_hash(self, content_type, object_pk, timestamp): """ Generate a HMAC security hash from the provided info. """ info = (content_type, object_pk, timestamp) key_salt = "django.contrib.forms.CommentSecurityForm" value = "-".join(info) return salted_hmac(key_salt, value).hexdigest()
python
def generate_security_hash(self, content_type, object_pk, timestamp): """ Generate a HMAC security hash from the provided info. """ info = (content_type, object_pk, timestamp) key_salt = "django.contrib.forms.CommentSecurityForm" value = "-".join(info) return salted_hmac(key_salt, value).hexdigest()
[ "def", "generate_security_hash", "(", "self", ",", "content_type", ",", "object_pk", ",", "timestamp", ")", ":", "info", "=", "(", "content_type", ",", "object_pk", ",", "timestamp", ")", "key_salt", "=", "\"django.contrib.forms.CommentSecurityForm\"", "value", "=", "\"-\"", ".", "join", "(", "info", ")", "return", "salted_hmac", "(", "key_salt", ",", "value", ")", ".", "hexdigest", "(", ")" ]
Generate a HMAC security hash from the provided info.
[ "Generate", "a", "HMAC", "security", "hash", "from", "the", "provided", "info", "." ]
1fd335c6fc9e81bba158e42e1483f1a149622ab4
https://github.com/tBaxter/tango-comments/blob/1fd335c6fc9e81bba158e42e1483f1a149622ab4/build/lib/tango_comments/forms.py#L86-L93
251,471
tBaxter/tango-comments
build/lib/tango_comments/forms.py
CommentDetailsForm.get_comment_create_data
def get_comment_create_data(self): """ Returns the dict of data to be used to create a comment. Subclasses in custom comment apps that override get_comment_model can override this method to add extra fields onto a custom comment model. """ user_model = get_user_model() return dict( content_type=ContentType.objects.get_for_model(self.target_object), object_pk=force_text(self.target_object._get_pk_val()), text=self.cleaned_data["text"], user=user_model.objects.latest('id'), post_date=timezone.now(), site_id=settings.SITE_ID, is_public=True, is_removed=False, )
python
def get_comment_create_data(self): """ Returns the dict of data to be used to create a comment. Subclasses in custom comment apps that override get_comment_model can override this method to add extra fields onto a custom comment model. """ user_model = get_user_model() return dict( content_type=ContentType.objects.get_for_model(self.target_object), object_pk=force_text(self.target_object._get_pk_val()), text=self.cleaned_data["text"], user=user_model.objects.latest('id'), post_date=timezone.now(), site_id=settings.SITE_ID, is_public=True, is_removed=False, )
[ "def", "get_comment_create_data", "(", "self", ")", ":", "user_model", "=", "get_user_model", "(", ")", "return", "dict", "(", "content_type", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "self", ".", "target_object", ")", ",", "object_pk", "=", "force_text", "(", "self", ".", "target_object", ".", "_get_pk_val", "(", ")", ")", ",", "text", "=", "self", ".", "cleaned_data", "[", "\"text\"", "]", ",", "user", "=", "user_model", ".", "objects", ".", "latest", "(", "'id'", ")", ",", "post_date", "=", "timezone", ".", "now", "(", ")", ",", "site_id", "=", "settings", ".", "SITE_ID", ",", "is_public", "=", "True", ",", "is_removed", "=", "False", ",", ")" ]
Returns the dict of data to be used to create a comment. Subclasses in custom comment apps that override get_comment_model can override this method to add extra fields onto a custom comment model.
[ "Returns", "the", "dict", "of", "data", "to", "be", "used", "to", "create", "a", "comment", ".", "Subclasses", "in", "custom", "comment", "apps", "that", "override", "get_comment_model", "can", "override", "this", "method", "to", "add", "extra", "fields", "onto", "a", "custom", "comment", "model", "." ]
1fd335c6fc9e81bba158e42e1483f1a149622ab4
https://github.com/tBaxter/tango-comments/blob/1fd335c6fc9e81bba158e42e1483f1a149622ab4/build/lib/tango_comments/forms.py#L136-L152
251,472
tBaxter/tango-comments
build/lib/tango_comments/forms.py
CommentDetailsForm.clean_comment
def clean_comment(self): """ If COMMENTS_ALLOW_PROFANITIES is False, check that the comment doesn't contain anything in PROFANITIES_LIST. """ comment = self.cleaned_data["text"] if settings.COMMENTS_ALLOW_PROFANITIES is False: bad_words = [w for w in settings.PROFANITIES_LIST if w in comment.lower()] if bad_words: raise forms.ValidationError(ungettext( "Watch your mouth! The word %s is not allowed here.", "Watch your mouth! The words %s are not allowed here.", len(bad_words)) % get_text_list( ['"%s%s%s"' % (i[0], '-'*(len(i)-2), i[-1]) for i in bad_words], ugettext('and'))) return comment
python
def clean_comment(self): """ If COMMENTS_ALLOW_PROFANITIES is False, check that the comment doesn't contain anything in PROFANITIES_LIST. """ comment = self.cleaned_data["text"] if settings.COMMENTS_ALLOW_PROFANITIES is False: bad_words = [w for w in settings.PROFANITIES_LIST if w in comment.lower()] if bad_words: raise forms.ValidationError(ungettext( "Watch your mouth! The word %s is not allowed here.", "Watch your mouth! The words %s are not allowed here.", len(bad_words)) % get_text_list( ['"%s%s%s"' % (i[0], '-'*(len(i)-2), i[-1]) for i in bad_words], ugettext('and'))) return comment
[ "def", "clean_comment", "(", "self", ")", ":", "comment", "=", "self", ".", "cleaned_data", "[", "\"text\"", "]", "if", "settings", ".", "COMMENTS_ALLOW_PROFANITIES", "is", "False", ":", "bad_words", "=", "[", "w", "for", "w", "in", "settings", ".", "PROFANITIES_LIST", "if", "w", "in", "comment", ".", "lower", "(", ")", "]", "if", "bad_words", ":", "raise", "forms", ".", "ValidationError", "(", "ungettext", "(", "\"Watch your mouth! The word %s is not allowed here.\"", ",", "\"Watch your mouth! The words %s are not allowed here.\"", ",", "len", "(", "bad_words", ")", ")", "%", "get_text_list", "(", "[", "'\"%s%s%s\"'", "%", "(", "i", "[", "0", "]", ",", "'-'", "*", "(", "len", "(", "i", ")", "-", "2", ")", ",", "i", "[", "-", "1", "]", ")", "for", "i", "in", "bad_words", "]", ",", "ugettext", "(", "'and'", ")", ")", ")", "return", "comment" ]
If COMMENTS_ALLOW_PROFANITIES is False, check that the comment doesn't contain anything in PROFANITIES_LIST.
[ "If", "COMMENTS_ALLOW_PROFANITIES", "is", "False", "check", "that", "the", "comment", "doesn", "t", "contain", "anything", "in", "PROFANITIES_LIST", "." ]
1fd335c6fc9e81bba158e42e1483f1a149622ab4
https://github.com/tBaxter/tango-comments/blob/1fd335c6fc9e81bba158e42e1483f1a149622ab4/build/lib/tango_comments/forms.py#L171-L186
251,473
tBaxter/tango-comments
build/lib/tango_comments/forms.py
CommentForm.clean_honeypot
def clean_honeypot(self): """Check that nothing's been entered into the honeypot.""" value = self.cleaned_data["honeypot"] if value: raise forms.ValidationError(self.fields["honeypot"].label) return value
python
def clean_honeypot(self): """Check that nothing's been entered into the honeypot.""" value = self.cleaned_data["honeypot"] if value: raise forms.ValidationError(self.fields["honeypot"].label) return value
[ "def", "clean_honeypot", "(", "self", ")", ":", "value", "=", "self", ".", "cleaned_data", "[", "\"honeypot\"", "]", "if", "value", ":", "raise", "forms", ".", "ValidationError", "(", "self", ".", "fields", "[", "\"honeypot\"", "]", ".", "label", ")", "return", "value" ]
Check that nothing's been entered into the honeypot.
[ "Check", "that", "nothing", "s", "been", "entered", "into", "the", "honeypot", "." ]
1fd335c6fc9e81bba158e42e1483f1a149622ab4
https://github.com/tBaxter/tango-comments/blob/1fd335c6fc9e81bba158e42e1483f1a149622ab4/build/lib/tango_comments/forms.py#L195-L200
251,474
refinery29/chassis
chassis/util/decorators.py
include_original
def include_original(dec): """Decorate decorators so they include a copy of the original function.""" def meta_decorator(method): """Yo dawg, I heard you like decorators...""" # pylint: disable=protected-access decorator = dec(method) decorator._original = method return decorator return meta_decorator
python
def include_original(dec): """Decorate decorators so they include a copy of the original function.""" def meta_decorator(method): """Yo dawg, I heard you like decorators...""" # pylint: disable=protected-access decorator = dec(method) decorator._original = method return decorator return meta_decorator
[ "def", "include_original", "(", "dec", ")", ":", "def", "meta_decorator", "(", "method", ")", ":", "\"\"\"Yo dawg, I heard you like decorators...\"\"\"", "# pylint: disable=protected-access", "decorator", "=", "dec", "(", "method", ")", "decorator", ".", "_original", "=", "method", "return", "decorator", "return", "meta_decorator" ]
Decorate decorators so they include a copy of the original function.
[ "Decorate", "decorators", "so", "they", "include", "a", "copy", "of", "the", "original", "function", "." ]
1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192
https://github.com/refinery29/chassis/blob/1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192/chassis/util/decorators.py#L4-L12
251,475
kderynski/blade-netconf-python-client
build/lib/bnclient/bnclient.py
bnclient.sendhello
def sendhello(self): try: # send hello cli_hello_msg = "<hello>\n" +\ " <capabilities>\n" +\ " <capability>urn:ietf:params:netconf:base:1.0</capability>\n" +\ " </capabilities>\n" +\ "</hello>\n" self._cParams.set('cli_hello', cli_hello_msg) self._hConn.sendmsg(cli_hello_msg) # recv hello ser_hello_msg = self._hConn.recvmsg() self._cParams.set('ser_hello', ser_hello_msg) except: print 'BNClient: Call sendhello fail' sys.exit() """ end of function exchgcaps """
python
def sendhello(self): try: # send hello cli_hello_msg = "<hello>\n" +\ " <capabilities>\n" +\ " <capability>urn:ietf:params:netconf:base:1.0</capability>\n" +\ " </capabilities>\n" +\ "</hello>\n" self._cParams.set('cli_hello', cli_hello_msg) self._hConn.sendmsg(cli_hello_msg) # recv hello ser_hello_msg = self._hConn.recvmsg() self._cParams.set('ser_hello', ser_hello_msg) except: print 'BNClient: Call sendhello fail' sys.exit() """ end of function exchgcaps """
[ "def", "sendhello", "(", "self", ")", ":", "try", ":", "# send hello\r", "cli_hello_msg", "=", "\"<hello>\\n\"", "+", "\" <capabilities>\\n\"", "+", "\" <capability>urn:ietf:params:netconf:base:1.0</capability>\\n\"", "+", "\" </capabilities>\\n\"", "+", "\"</hello>\\n\"", "self", ".", "_cParams", ".", "set", "(", "'cli_hello'", ",", "cli_hello_msg", ")", "self", ".", "_hConn", ".", "sendmsg", "(", "cli_hello_msg", ")", "# recv hello\r", "ser_hello_msg", "=", "self", ".", "_hConn", ".", "recvmsg", "(", ")", "self", ".", "_cParams", ".", "set", "(", "'ser_hello'", ",", "ser_hello_msg", ")", "except", ":", "print", "'BNClient: Call sendhello fail'", "sys", ".", "exit", "(", ")" ]
end of function exchgcaps
[ "end", "of", "function", "exchgcaps" ]
87396921a1c75f1093adf4bb7b13428ee368b2b7
https://github.com/kderynski/blade-netconf-python-client/blob/87396921a1c75f1093adf4bb7b13428ee368b2b7/build/lib/bnclient/bnclient.py#L88-L106
251,476
kderynski/blade-netconf-python-client
build/lib/bnclient/bnclient.py
bnclient.sendrpc
def sendrpc(self, argv=[]): self._aArgv += argv _operation = '' try: self._cParams.parser(self._aArgv, self._dOptions) # set rpc operation handler while self._cParams.get('operation') not in rpc.operations.keys(): self._cParams.set('operation', raw_input("Enter RPC Operation:\n%s:" % rpc.operations.keys())) _operation = self._cParams.get('operation') self._hRpcOper = rpc.operations[_operation](opts=self._dOptions) # input missing operation parameters self._hRpcOper.fill(params=self._cParams.get()) send_msg = self._hRpcOper.readmsg(self._cParams.get()) self._cParams.set('messageid', self._cParams.get('messageid')+1) self._hConn.sendmsg(send_msg) self._cParams.set('sendmsg', send_msg) recv_msg = self._hConn.recvmsg() self._cParams.set('recvmsg', recv_msg) self._hRpcOper.parsemsg(self._cParams.get()) self._hRpcOper.writemsg(self._cParams.get()) # reset operation params self._cParams.reset() except: if _operation != 'close-session': print 'BNClient: Call sendrpc%s fail' % (' <'+_operation+'>' if len(_operation) else '') sys.exit() """ end of function exchgmsg """
python
def sendrpc(self, argv=[]): self._aArgv += argv _operation = '' try: self._cParams.parser(self._aArgv, self._dOptions) # set rpc operation handler while self._cParams.get('operation') not in rpc.operations.keys(): self._cParams.set('operation', raw_input("Enter RPC Operation:\n%s:" % rpc.operations.keys())) _operation = self._cParams.get('operation') self._hRpcOper = rpc.operations[_operation](opts=self._dOptions) # input missing operation parameters self._hRpcOper.fill(params=self._cParams.get()) send_msg = self._hRpcOper.readmsg(self._cParams.get()) self._cParams.set('messageid', self._cParams.get('messageid')+1) self._hConn.sendmsg(send_msg) self._cParams.set('sendmsg', send_msg) recv_msg = self._hConn.recvmsg() self._cParams.set('recvmsg', recv_msg) self._hRpcOper.parsemsg(self._cParams.get()) self._hRpcOper.writemsg(self._cParams.get()) # reset operation params self._cParams.reset() except: if _operation != 'close-session': print 'BNClient: Call sendrpc%s fail' % (' <'+_operation+'>' if len(_operation) else '') sys.exit() """ end of function exchgmsg """
[ "def", "sendrpc", "(", "self", ",", "argv", "=", "[", "]", ")", ":", "self", ".", "_aArgv", "+=", "argv", "_operation", "=", "''", "try", ":", "self", ".", "_cParams", ".", "parser", "(", "self", ".", "_aArgv", ",", "self", ".", "_dOptions", ")", "# set rpc operation handler\r", "while", "self", ".", "_cParams", ".", "get", "(", "'operation'", ")", "not", "in", "rpc", ".", "operations", ".", "keys", "(", ")", ":", "self", ".", "_cParams", ".", "set", "(", "'operation'", ",", "raw_input", "(", "\"Enter RPC Operation:\\n%s:\"", "%", "rpc", ".", "operations", ".", "keys", "(", ")", ")", ")", "_operation", "=", "self", ".", "_cParams", ".", "get", "(", "'operation'", ")", "self", ".", "_hRpcOper", "=", "rpc", ".", "operations", "[", "_operation", "]", "(", "opts", "=", "self", ".", "_dOptions", ")", "# input missing operation parameters\r", "self", ".", "_hRpcOper", ".", "fill", "(", "params", "=", "self", ".", "_cParams", ".", "get", "(", ")", ")", "send_msg", "=", "self", ".", "_hRpcOper", ".", "readmsg", "(", "self", ".", "_cParams", ".", "get", "(", ")", ")", "self", ".", "_cParams", ".", "set", "(", "'messageid'", ",", "self", ".", "_cParams", ".", "get", "(", "'messageid'", ")", "+", "1", ")", "self", ".", "_hConn", ".", "sendmsg", "(", "send_msg", ")", "self", ".", "_cParams", ".", "set", "(", "'sendmsg'", ",", "send_msg", ")", "recv_msg", "=", "self", ".", "_hConn", ".", "recvmsg", "(", ")", "self", ".", "_cParams", ".", "set", "(", "'recvmsg'", ",", "recv_msg", ")", "self", ".", "_hRpcOper", ".", "parsemsg", "(", "self", ".", "_cParams", ".", "get", "(", ")", ")", "self", ".", "_hRpcOper", ".", "writemsg", "(", "self", ".", "_cParams", ".", "get", "(", ")", ")", "# reset operation params\r", "self", ".", "_cParams", ".", "reset", "(", ")", "except", ":", "if", "_operation", "!=", "'close-session'", ":", "print", "'BNClient: Call sendrpc%s fail'", "%", "(", "' <'", "+", "_operation", "+", "'>'", "if", "len", "(", "_operation", ")", "else", "''", ")", "sys", ".", "exit", "(", ")" ]
end of function exchgmsg
[ "end", "of", "function", "exchgmsg" ]
87396921a1c75f1093adf4bb7b13428ee368b2b7
https://github.com/kderynski/blade-netconf-python-client/blob/87396921a1c75f1093adf4bb7b13428ee368b2b7/build/lib/bnclient/bnclient.py#L109-L141
251,477
carlitux/turboengine
src/turboengine/__init__.py
register_templatetags
def register_templatetags(): """ Register templatetags defined in settings as basic templatetags """ from turboengine.conf import settings from google.appengine.ext.webapp import template for python_file in settings.TEMPLATE_PATH: template.register_template_library(python_file)
python
def register_templatetags(): """ Register templatetags defined in settings as basic templatetags """ from turboengine.conf import settings from google.appengine.ext.webapp import template for python_file in settings.TEMPLATE_PATH: template.register_template_library(python_file)
[ "def", "register_templatetags", "(", ")", ":", "from", "turboengine", ".", "conf", "import", "settings", "from", "google", ".", "appengine", ".", "ext", ".", "webapp", "import", "template", "for", "python_file", "in", "settings", ".", "TEMPLATE_PATH", ":", "template", ".", "register_template_library", "(", "python_file", ")" ]
Register templatetags defined in settings as basic templatetags
[ "Register", "templatetags", "defined", "in", "settings", "as", "basic", "templatetags" ]
627b6dbc400d8c16e2ff7e17afd01915371ea287
https://github.com/carlitux/turboengine/blob/627b6dbc400d8c16e2ff7e17afd01915371ea287/src/turboengine/__init__.py#L28-L33
251,478
cirruscluster/cirruscluster
cirruscluster/ext/ansible/inventory/__init__.py
Inventory.get_hosts
def get_hosts(self, pattern="all"): """ find all host names matching a pattern string, taking into account any inventory restrictions or applied subsets. """ # process patterns if isinstance(pattern, list): pattern = ';'.join(pattern) patterns = pattern.replace(";",":").split(":") hosts = self._get_hosts(patterns) # exclude hosts not in a subset, if defined if self._subset: subset = self._get_hosts(self._subset) hosts.intersection_update(subset) # exclude hosts mentioned in any restriction (ex: failed hosts) if self._restriction is not None: hosts = [ h for h in hosts if h.name in self._restriction ] if self._also_restriction is not None: hosts = [ h for h in hosts if h.name in self._also_restriction ] return sorted(hosts, key=lambda x: x.name)
python
def get_hosts(self, pattern="all"): """ find all host names matching a pattern string, taking into account any inventory restrictions or applied subsets. """ # process patterns if isinstance(pattern, list): pattern = ';'.join(pattern) patterns = pattern.replace(";",":").split(":") hosts = self._get_hosts(patterns) # exclude hosts not in a subset, if defined if self._subset: subset = self._get_hosts(self._subset) hosts.intersection_update(subset) # exclude hosts mentioned in any restriction (ex: failed hosts) if self._restriction is not None: hosts = [ h for h in hosts if h.name in self._restriction ] if self._also_restriction is not None: hosts = [ h for h in hosts if h.name in self._also_restriction ] return sorted(hosts, key=lambda x: x.name)
[ "def", "get_hosts", "(", "self", ",", "pattern", "=", "\"all\"", ")", ":", "# process patterns", "if", "isinstance", "(", "pattern", ",", "list", ")", ":", "pattern", "=", "';'", ".", "join", "(", "pattern", ")", "patterns", "=", "pattern", ".", "replace", "(", "\";\"", ",", "\":\"", ")", ".", "split", "(", "\":\"", ")", "hosts", "=", "self", ".", "_get_hosts", "(", "patterns", ")", "# exclude hosts not in a subset, if defined", "if", "self", ".", "_subset", ":", "subset", "=", "self", ".", "_get_hosts", "(", "self", ".", "_subset", ")", "hosts", ".", "intersection_update", "(", "subset", ")", "# exclude hosts mentioned in any restriction (ex: failed hosts)", "if", "self", ".", "_restriction", "is", "not", "None", ":", "hosts", "=", "[", "h", "for", "h", "in", "hosts", "if", "h", ".", "name", "in", "self", ".", "_restriction", "]", "if", "self", ".", "_also_restriction", "is", "not", "None", ":", "hosts", "=", "[", "h", "for", "h", "in", "hosts", "if", "h", ".", "name", "in", "self", ".", "_also_restriction", "]", "return", "sorted", "(", "hosts", ",", "key", "=", "lambda", "x", ":", "x", ".", "name", ")" ]
find all host names matching a pattern string, taking into account any inventory restrictions or applied subsets.
[ "find", "all", "host", "names", "matching", "a", "pattern", "string", "taking", "into", "account", "any", "inventory", "restrictions", "or", "applied", "subsets", "." ]
977409929dd81322d886425cdced10608117d5d7
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/inventory/__init__.py#L101-L124
251,479
cirruscluster/cirruscluster
cirruscluster/ext/ansible/inventory/__init__.py
Inventory._get_hosts
def _get_hosts(self, patterns): """ finds hosts that match a list of patterns. Handles negative matches as well as intersection matches. """ hosts = set() for p in patterns: if p.startswith("!"): # Discard excluded hosts hosts.difference_update(self.__get_hosts(p)) elif p.startswith("&"): # Only leave the intersected hosts hosts.intersection_update(self.__get_hosts(p)) else: # Get all hosts from both patterns hosts.update(self.__get_hosts(p)) return hosts
python
def _get_hosts(self, patterns): """ finds hosts that match a list of patterns. Handles negative matches as well as intersection matches. """ hosts = set() for p in patterns: if p.startswith("!"): # Discard excluded hosts hosts.difference_update(self.__get_hosts(p)) elif p.startswith("&"): # Only leave the intersected hosts hosts.intersection_update(self.__get_hosts(p)) else: # Get all hosts from both patterns hosts.update(self.__get_hosts(p)) return hosts
[ "def", "_get_hosts", "(", "self", ",", "patterns", ")", ":", "hosts", "=", "set", "(", ")", "for", "p", "in", "patterns", ":", "if", "p", ".", "startswith", "(", "\"!\"", ")", ":", "# Discard excluded hosts", "hosts", ".", "difference_update", "(", "self", ".", "__get_hosts", "(", "p", ")", ")", "elif", "p", ".", "startswith", "(", "\"&\"", ")", ":", "# Only leave the intersected hosts", "hosts", ".", "intersection_update", "(", "self", ".", "__get_hosts", "(", "p", ")", ")", "else", ":", "# Get all hosts from both patterns", "hosts", ".", "update", "(", "self", ".", "__get_hosts", "(", "p", ")", ")", "return", "hosts" ]
finds hosts that match a list of patterns. Handles negative matches as well as intersection matches.
[ "finds", "hosts", "that", "match", "a", "list", "of", "patterns", ".", "Handles", "negative", "matches", "as", "well", "as", "intersection", "matches", "." ]
977409929dd81322d886425cdced10608117d5d7
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/inventory/__init__.py#L126-L143
251,480
cirruscluster/cirruscluster
cirruscluster/ext/ansible/inventory/__init__.py
Inventory.__get_hosts
def __get_hosts(self, pattern): """ finds hosts that postively match a particular pattern. Does not take into account negative matches. """ (name, enumeration_details) = self._enumeration_info(pattern) hpat = self._hosts_in_unenumerated_pattern(name) hpat = sorted(hpat, key=lambda x: x.name) return set(self._apply_ranges(pattern, hpat))
python
def __get_hosts(self, pattern): """ finds hosts that postively match a particular pattern. Does not take into account negative matches. """ (name, enumeration_details) = self._enumeration_info(pattern) hpat = self._hosts_in_unenumerated_pattern(name) hpat = sorted(hpat, key=lambda x: x.name) return set(self._apply_ranges(pattern, hpat))
[ "def", "__get_hosts", "(", "self", ",", "pattern", ")", ":", "(", "name", ",", "enumeration_details", ")", "=", "self", ".", "_enumeration_info", "(", "pattern", ")", "hpat", "=", "self", ".", "_hosts_in_unenumerated_pattern", "(", "name", ")", "hpat", "=", "sorted", "(", "hpat", ",", "key", "=", "lambda", "x", ":", "x", ".", "name", ")", "return", "set", "(", "self", ".", "_apply_ranges", "(", "pattern", ",", "hpat", ")", ")" ]
finds hosts that postively match a particular pattern. Does not take into account negative matches.
[ "finds", "hosts", "that", "postively", "match", "a", "particular", "pattern", ".", "Does", "not", "take", "into", "account", "negative", "matches", "." ]
977409929dd81322d886425cdced10608117d5d7
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/inventory/__init__.py#L145-L155
251,481
cirruscluster/cirruscluster
cirruscluster/ext/ansible/inventory/__init__.py
Inventory._hosts_in_unenumerated_pattern
def _hosts_in_unenumerated_pattern(self, pattern): """ Get all host names matching the pattern """ hosts = {} # ignore any negative checks here, this is handled elsewhere pattern = pattern.replace("!","").replace("&", "") groups = self.get_groups() for group in groups: for host in group.get_hosts(): if pattern == 'all' or self._match(group.name, pattern) or self._match(host.name, pattern): hosts[host.name] = host return sorted(hosts.values(), key=lambda x: x.name)
python
def _hosts_in_unenumerated_pattern(self, pattern): """ Get all host names matching the pattern """ hosts = {} # ignore any negative checks here, this is handled elsewhere pattern = pattern.replace("!","").replace("&", "") groups = self.get_groups() for group in groups: for host in group.get_hosts(): if pattern == 'all' or self._match(group.name, pattern) or self._match(host.name, pattern): hosts[host.name] = host return sorted(hosts.values(), key=lambda x: x.name)
[ "def", "_hosts_in_unenumerated_pattern", "(", "self", ",", "pattern", ")", ":", "hosts", "=", "{", "}", "# ignore any negative checks here, this is handled elsewhere", "pattern", "=", "pattern", ".", "replace", "(", "\"!\"", ",", "\"\"", ")", ".", "replace", "(", "\"&\"", ",", "\"\"", ")", "groups", "=", "self", ".", "get_groups", "(", ")", "for", "group", "in", "groups", ":", "for", "host", "in", "group", ".", "get_hosts", "(", ")", ":", "if", "pattern", "==", "'all'", "or", "self", ".", "_match", "(", "group", ".", "name", ",", "pattern", ")", "or", "self", ".", "_match", "(", "host", ".", "name", ",", "pattern", ")", ":", "hosts", "[", "host", ".", "name", "]", "=", "host", "return", "sorted", "(", "hosts", ".", "values", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", ".", "name", ")" ]
Get all host names matching the pattern
[ "Get", "all", "host", "names", "matching", "the", "pattern" ]
977409929dd81322d886425cdced10608117d5d7
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/inventory/__init__.py#L196-L208
251,482
cirruscluster/cirruscluster
cirruscluster/ext/ansible/inventory/__init__.py
Inventory.restrict_to
def restrict_to(self, restriction): """ Restrict list operations to the hosts given in restriction. This is used to exclude failed hosts in main playbook code, don't use this for other reasons. """ if type(restriction) != list: restriction = [ restriction ] self._restriction = restriction
python
def restrict_to(self, restriction): """ Restrict list operations to the hosts given in restriction. This is used to exclude failed hosts in main playbook code, don't use this for other reasons. """ if type(restriction) != list: restriction = [ restriction ] self._restriction = restriction
[ "def", "restrict_to", "(", "self", ",", "restriction", ")", ":", "if", "type", "(", "restriction", ")", "!=", "list", ":", "restriction", "=", "[", "restriction", "]", "self", ".", "_restriction", "=", "restriction" ]
Restrict list operations to the hosts given in restriction. This is used to exclude failed hosts in main playbook code, don't use this for other reasons.
[ "Restrict", "list", "operations", "to", "the", "hosts", "given", "in", "restriction", ".", "This", "is", "used", "to", "exclude", "failed", "hosts", "in", "main", "playbook", "code", "don", "t", "use", "this", "for", "other", "reasons", "." ]
977409929dd81322d886425cdced10608117d5d7
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/inventory/__init__.py#L305-L313
251,483
cirruscluster/cirruscluster
cirruscluster/ext/ansible/inventory/__init__.py
Inventory.also_restrict_to
def also_restrict_to(self, restriction): """ Works like restict_to but offers an additional restriction. Playbooks use this to implement serial behavior. """ if type(restriction) != list: restriction = [ restriction ] self._also_restriction = restriction
python
def also_restrict_to(self, restriction): """ Works like restict_to but offers an additional restriction. Playbooks use this to implement serial behavior. """ if type(restriction) != list: restriction = [ restriction ] self._also_restriction = restriction
[ "def", "also_restrict_to", "(", "self", ",", "restriction", ")", ":", "if", "type", "(", "restriction", ")", "!=", "list", ":", "restriction", "=", "[", "restriction", "]", "self", ".", "_also_restriction", "=", "restriction" ]
Works like restict_to but offers an additional restriction. Playbooks use this to implement serial behavior.
[ "Works", "like", "restict_to", "but", "offers", "an", "additional", "restriction", ".", "Playbooks", "use", "this", "to", "implement", "serial", "behavior", "." ]
977409929dd81322d886425cdced10608117d5d7
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/inventory/__init__.py#L315-L322
251,484
cirruscluster/cirruscluster
cirruscluster/ext/ansible/inventory/__init__.py
Inventory.is_file
def is_file(self): """ did inventory come from a file? """ if not isinstance(self.host_list, basestring): return False return os.path.exists(self.host_list)
python
def is_file(self): """ did inventory come from a file? """ if not isinstance(self.host_list, basestring): return False return os.path.exists(self.host_list)
[ "def", "is_file", "(", "self", ")", ":", "if", "not", "isinstance", "(", "self", ".", "host_list", ",", "basestring", ")", ":", "return", "False", "return", "os", ".", "path", ".", "exists", "(", "self", ".", "host_list", ")" ]
did inventory come from a file?
[ "did", "inventory", "come", "from", "a", "file?" ]
977409929dd81322d886425cdced10608117d5d7
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/inventory/__init__.py#L345-L349
251,485
jkenlooper/chill
src/chill/shortcodes.py
register
def register(tag, end_tag=None): """ Decorator for registering shortcode functions. """ def register_function(function): tagmap[tag] = {'func': function, 'endtag': end_tag} if end_tag: tagmap['endtags'].append(end_tag) return function return register_function
python
def register(tag, end_tag=None): """ Decorator for registering shortcode functions. """ def register_function(function): tagmap[tag] = {'func': function, 'endtag': end_tag} if end_tag: tagmap['endtags'].append(end_tag) return function return register_function
[ "def", "register", "(", "tag", ",", "end_tag", "=", "None", ")", ":", "def", "register_function", "(", "function", ")", ":", "tagmap", "[", "tag", "]", "=", "{", "'func'", ":", "function", ",", "'endtag'", ":", "end_tag", "}", "if", "end_tag", ":", "tagmap", "[", "'endtags'", "]", ".", "append", "(", "end_tag", ")", "return", "function", "return", "register_function" ]
Decorator for registering shortcode functions.
[ "Decorator", "for", "registering", "shortcode", "functions", "." ]
35360c17c2a3b769ecb5406c6dabcf4cc70bd76f
https://github.com/jkenlooper/chill/blob/35360c17c2a3b769ecb5406c6dabcf4cc70bd76f/src/chill/shortcodes.py#L63-L72
251,486
tempodb/tempodb-python
tempodb/temporal/validate.py
check_time_param
def check_time_param(t): """Check whether a string sent in matches the ISO8601 format. If a Datetime object is passed instead, it will be converted into an ISO8601 compliant string. :param t: the datetime to check :type t: string or Datetime :rtype: string""" if type(t) is str: if not ISO.match(t): raise ValueError('Date string "%s" does not match ISO8601 format' % (t)) return t else: return t.isoformat()
python
def check_time_param(t): """Check whether a string sent in matches the ISO8601 format. If a Datetime object is passed instead, it will be converted into an ISO8601 compliant string. :param t: the datetime to check :type t: string or Datetime :rtype: string""" if type(t) is str: if not ISO.match(t): raise ValueError('Date string "%s" does not match ISO8601 format' % (t)) return t else: return t.isoformat()
[ "def", "check_time_param", "(", "t", ")", ":", "if", "type", "(", "t", ")", "is", "str", ":", "if", "not", "ISO", ".", "match", "(", "t", ")", ":", "raise", "ValueError", "(", "'Date string \"%s\" does not match ISO8601 format'", "%", "(", "t", ")", ")", "return", "t", "else", ":", "return", "t", ".", "isoformat", "(", ")" ]
Check whether a string sent in matches the ISO8601 format. If a Datetime object is passed instead, it will be converted into an ISO8601 compliant string. :param t: the datetime to check :type t: string or Datetime :rtype: string
[ "Check", "whether", "a", "string", "sent", "in", "matches", "the", "ISO8601", "format", ".", "If", "a", "Datetime", "object", "is", "passed", "instead", "it", "will", "be", "converted", "into", "an", "ISO8601", "compliant", "string", "." ]
8ce45231bd728c6c97ef799cf0f1513ea3a9a7d3
https://github.com/tempodb/tempodb-python/blob/8ce45231bd728c6c97ef799cf0f1513ea3a9a7d3/tempodb/temporal/validate.py#L11-L26
251,487
tempodb/tempodb-python
tempodb/temporal/validate.py
convert_iso_stamp
def convert_iso_stamp(t, tz=None): """Convert a string in ISO8601 form into a Datetime object. This is mainly used for converting timestamps sent from the TempoDB API, which are assumed to be correct. :param string t: the timestamp to convert :rtype: Datetime object""" if t is None: return None dt = dateutil.parser.parse(t) if tz is not None: timezone = pytz.timezone(tz) if dt.tzinfo is None: dt = timezone.localize(dt) return dt
python
def convert_iso_stamp(t, tz=None): """Convert a string in ISO8601 form into a Datetime object. This is mainly used for converting timestamps sent from the TempoDB API, which are assumed to be correct. :param string t: the timestamp to convert :rtype: Datetime object""" if t is None: return None dt = dateutil.parser.parse(t) if tz is not None: timezone = pytz.timezone(tz) if dt.tzinfo is None: dt = timezone.localize(dt) return dt
[ "def", "convert_iso_stamp", "(", "t", ",", "tz", "=", "None", ")", ":", "if", "t", "is", "None", ":", "return", "None", "dt", "=", "dateutil", ".", "parser", ".", "parse", "(", "t", ")", "if", "tz", "is", "not", "None", ":", "timezone", "=", "pytz", ".", "timezone", "(", "tz", ")", "if", "dt", ".", "tzinfo", "is", "None", ":", "dt", "=", "timezone", ".", "localize", "(", "dt", ")", "return", "dt" ]
Convert a string in ISO8601 form into a Datetime object. This is mainly used for converting timestamps sent from the TempoDB API, which are assumed to be correct. :param string t: the timestamp to convert :rtype: Datetime object
[ "Convert", "a", "string", "in", "ISO8601", "form", "into", "a", "Datetime", "object", ".", "This", "is", "mainly", "used", "for", "converting", "timestamps", "sent", "from", "the", "TempoDB", "API", "which", "are", "assumed", "to", "be", "correct", "." ]
8ce45231bd728c6c97ef799cf0f1513ea3a9a7d3
https://github.com/tempodb/tempodb-python/blob/8ce45231bd728c6c97ef799cf0f1513ea3a9a7d3/tempodb/temporal/validate.py#L29-L45
251,488
shaypal5/utilitime
utilitime/weekday/weekday.py
next_weekday
def next_weekday(weekday): """Returns the name of the weekday after the given weekday name.""" ix = WEEKDAYS.index(weekday) if ix == len(WEEKDAYS)-1: return WEEKDAYS[0] return WEEKDAYS[ix+1]
python
def next_weekday(weekday): """Returns the name of the weekday after the given weekday name.""" ix = WEEKDAYS.index(weekday) if ix == len(WEEKDAYS)-1: return WEEKDAYS[0] return WEEKDAYS[ix+1]
[ "def", "next_weekday", "(", "weekday", ")", ":", "ix", "=", "WEEKDAYS", ".", "index", "(", "weekday", ")", "if", "ix", "==", "len", "(", "WEEKDAYS", ")", "-", "1", ":", "return", "WEEKDAYS", "[", "0", "]", "return", "WEEKDAYS", "[", "ix", "+", "1", "]" ]
Returns the name of the weekday after the given weekday name.
[ "Returns", "the", "name", "of", "the", "weekday", "after", "the", "given", "weekday", "name", "." ]
554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609
https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/weekday/weekday.py#L12-L17
251,489
shaypal5/utilitime
utilitime/weekday/weekday.py
prev_weekday
def prev_weekday(weekday): """Returns the name of the weekday before the given weekday name.""" ix = WEEKDAYS.index(weekday) if ix == 0: return WEEKDAYS[len(WEEKDAYS)-1] return WEEKDAYS[ix-1]
python
def prev_weekday(weekday): """Returns the name of the weekday before the given weekday name.""" ix = WEEKDAYS.index(weekday) if ix == 0: return WEEKDAYS[len(WEEKDAYS)-1] return WEEKDAYS[ix-1]
[ "def", "prev_weekday", "(", "weekday", ")", ":", "ix", "=", "WEEKDAYS", ".", "index", "(", "weekday", ")", "if", "ix", "==", "0", ":", "return", "WEEKDAYS", "[", "len", "(", "WEEKDAYS", ")", "-", "1", "]", "return", "WEEKDAYS", "[", "ix", "-", "1", "]" ]
Returns the name of the weekday before the given weekday name.
[ "Returns", "the", "name", "of", "the", "weekday", "before", "the", "given", "weekday", "name", "." ]
554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609
https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/weekday/weekday.py#L20-L25
251,490
shaypal5/utilitime
utilitime/weekday/weekday.py
workdays
def workdays(first_day=None): """Returns a list of workday names. Arguments --------- first_day : str, default None The first day of the five-day work week. If not given, 'Monday' is used. Returns ------- list A list of workday names. """ if first_day is None: first_day = 'Monday' ix = _lower_weekdays().index(first_day.lower()) return _double_weekdays()[ix:ix+5]
python
def workdays(first_day=None): """Returns a list of workday names. Arguments --------- first_day : str, default None The first day of the five-day work week. If not given, 'Monday' is used. Returns ------- list A list of workday names. """ if first_day is None: first_day = 'Monday' ix = _lower_weekdays().index(first_day.lower()) return _double_weekdays()[ix:ix+5]
[ "def", "workdays", "(", "first_day", "=", "None", ")", ":", "if", "first_day", "is", "None", ":", "first_day", "=", "'Monday'", "ix", "=", "_lower_weekdays", "(", ")", ".", "index", "(", "first_day", ".", "lower", "(", ")", ")", "return", "_double_weekdays", "(", ")", "[", "ix", ":", "ix", "+", "5", "]" ]
Returns a list of workday names. Arguments --------- first_day : str, default None The first day of the five-day work week. If not given, 'Monday' is used. Returns ------- list A list of workday names.
[ "Returns", "a", "list", "of", "workday", "names", "." ]
554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609
https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/weekday/weekday.py#L38-L55
251,491
shaypal5/utilitime
utilitime/weekday/weekday.py
weekdays
def weekdays(first_day=None): """Returns a list of weekday names. Arguments --------- first_day : str, default None The first day of the week. If not given, 'Monday' is used. Returns ------- list A list of weekday names. """ if first_day is None: first_day = 'Monday' ix = _lower_weekdays().index(first_day.lower()) return _double_weekdays()[ix:ix+7]
python
def weekdays(first_day=None): """Returns a list of weekday names. Arguments --------- first_day : str, default None The first day of the week. If not given, 'Monday' is used. Returns ------- list A list of weekday names. """ if first_day is None: first_day = 'Monday' ix = _lower_weekdays().index(first_day.lower()) return _double_weekdays()[ix:ix+7]
[ "def", "weekdays", "(", "first_day", "=", "None", ")", ":", "if", "first_day", "is", "None", ":", "first_day", "=", "'Monday'", "ix", "=", "_lower_weekdays", "(", ")", ".", "index", "(", "first_day", ".", "lower", "(", ")", ")", "return", "_double_weekdays", "(", ")", "[", "ix", ":", "ix", "+", "7", "]" ]
Returns a list of weekday names. Arguments --------- first_day : str, default None The first day of the week. If not given, 'Monday' is used. Returns ------- list A list of weekday names.
[ "Returns", "a", "list", "of", "weekday", "names", "." ]
554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609
https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/weekday/weekday.py#L58-L74
251,492
jmgilman/Neolib
neolib/quests/KitchenQuest.py
KitchenQuest.buyQuestItems
def buyQuestItems(self): """ Attempts to buy all quest items, returns result Returns bool - True if successful, otherwise False """ for item in self.items: us = UserShopFront(self.usr, item.owner, item.id, str(item.price)) us.loadInventory() if not item.name in us.inventory: return False if not us.inventory[item.name].buy(): return False return True
python
def buyQuestItems(self): """ Attempts to buy all quest items, returns result Returns bool - True if successful, otherwise False """ for item in self.items: us = UserShopFront(self.usr, item.owner, item.id, str(item.price)) us.loadInventory() if not item.name in us.inventory: return False if not us.inventory[item.name].buy(): return False return True
[ "def", "buyQuestItems", "(", "self", ")", ":", "for", "item", "in", "self", ".", "items", ":", "us", "=", "UserShopFront", "(", "self", ".", "usr", ",", "item", ".", "owner", ",", "item", ".", "id", ",", "str", "(", "item", ".", "price", ")", ")", "us", ".", "loadInventory", "(", ")", "if", "not", "item", ".", "name", "in", "us", ".", "inventory", ":", "return", "False", "if", "not", "us", ".", "inventory", "[", "item", ".", "name", "]", ".", "buy", "(", ")", ":", "return", "False", "return", "True" ]
Attempts to buy all quest items, returns result Returns bool - True if successful, otherwise False
[ "Attempts", "to", "buy", "all", "quest", "items", "returns", "result", "Returns", "bool", "-", "True", "if", "successful", "otherwise", "False" ]
228fafeaed0f3195676137732384a14820ae285c
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/quests/KitchenQuest.py#L155-L171
251,493
jmgilman/Neolib
neolib/quests/KitchenQuest.py
KitchenQuest.submitQuest
def submitQuest(self): """ Submits the active quest, returns result Returns bool - True if successful, otherwise False """ form = pg.form(action="kitchen2.phtml") pg = form.submit() if "Woohoo" in pg.content: try: self.prize = pg.find(text = "The Chef waves his hands, and you may collect your prize...").parent.parent.find_all("b")[-1].text except Exception: logging.getLogger("neolib.quest").exception("Failed to parse kitchen quest prize", {'pg': pg}) raise parseException return True else: logging.getLogger("neolib.quest").info("Failed to complete kitchen quest", {'pg': pg}) return False
python
def submitQuest(self): """ Submits the active quest, returns result Returns bool - True if successful, otherwise False """ form = pg.form(action="kitchen2.phtml") pg = form.submit() if "Woohoo" in pg.content: try: self.prize = pg.find(text = "The Chef waves his hands, and you may collect your prize...").parent.parent.find_all("b")[-1].text except Exception: logging.getLogger("neolib.quest").exception("Failed to parse kitchen quest prize", {'pg': pg}) raise parseException return True else: logging.getLogger("neolib.quest").info("Failed to complete kitchen quest", {'pg': pg}) return False
[ "def", "submitQuest", "(", "self", ")", ":", "form", "=", "pg", ".", "form", "(", "action", "=", "\"kitchen2.phtml\"", ")", "pg", "=", "form", ".", "submit", "(", ")", "if", "\"Woohoo\"", "in", "pg", ".", "content", ":", "try", ":", "self", ".", "prize", "=", "pg", ".", "find", "(", "text", "=", "\"The Chef waves his hands, and you may collect your prize...\"", ")", ".", "parent", ".", "parent", ".", "find_all", "(", "\"b\"", ")", "[", "-", "1", "]", ".", "text", "except", "Exception", ":", "logging", ".", "getLogger", "(", "\"neolib.quest\"", ")", ".", "exception", "(", "\"Failed to parse kitchen quest prize\"", ",", "{", "'pg'", ":", "pg", "}", ")", "raise", "parseException", "return", "True", "else", ":", "logging", ".", "getLogger", "(", "\"neolib.quest\"", ")", ".", "info", "(", "\"Failed to complete kitchen quest\"", ",", "{", "'pg'", ":", "pg", "}", ")", "return", "False" ]
Submits the active quest, returns result Returns bool - True if successful, otherwise False
[ "Submits", "the", "active", "quest", "returns", "result", "Returns", "bool", "-", "True", "if", "successful", "otherwise", "False" ]
228fafeaed0f3195676137732384a14820ae285c
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/quests/KitchenQuest.py#L173-L193
251,494
JHowell45/helium-cli
helium/__init__.py
youtube
def youtube(no_controls, no_autoplay, store, store_name, youtube_url): """Convert a Youtube URL so that works correctly with Helium. This command is used for converting the URL for a Youtube video that is part of a playlist so that Helium recognises it as a playlist and when the video ends it correctly moves onto the next video in the playlist. :param youtube_url: the URL of the playlist youtube video. :type youtube_url: str """ old_url_colour = 'blue' new_url_colour = 'green' echo('Format --> {0}: {1}'.format( style('Original URL/Stored Title', fg=old_url_colour), style('New URL', fg=new_url_colour) )) for url in youtube_url: new_url = convert_youtube_url(url, no_controls, no_autoplay) if store: if store_name is not None: url = store_name store_data({url: new_url}) echo('{}: {}'.format( style(url, fg=old_url_colour), style(new_url, fg=new_url_colour) ))
python
def youtube(no_controls, no_autoplay, store, store_name, youtube_url): """Convert a Youtube URL so that works correctly with Helium. This command is used for converting the URL for a Youtube video that is part of a playlist so that Helium recognises it as a playlist and when the video ends it correctly moves onto the next video in the playlist. :param youtube_url: the URL of the playlist youtube video. :type youtube_url: str """ old_url_colour = 'blue' new_url_colour = 'green' echo('Format --> {0}: {1}'.format( style('Original URL/Stored Title', fg=old_url_colour), style('New URL', fg=new_url_colour) )) for url in youtube_url: new_url = convert_youtube_url(url, no_controls, no_autoplay) if store: if store_name is not None: url = store_name store_data({url: new_url}) echo('{}: {}'.format( style(url, fg=old_url_colour), style(new_url, fg=new_url_colour) ))
[ "def", "youtube", "(", "no_controls", ",", "no_autoplay", ",", "store", ",", "store_name", ",", "youtube_url", ")", ":", "old_url_colour", "=", "'blue'", "new_url_colour", "=", "'green'", "echo", "(", "'Format --> {0}: {1}'", ".", "format", "(", "style", "(", "'Original URL/Stored Title'", ",", "fg", "=", "old_url_colour", ")", ",", "style", "(", "'New URL'", ",", "fg", "=", "new_url_colour", ")", ")", ")", "for", "url", "in", "youtube_url", ":", "new_url", "=", "convert_youtube_url", "(", "url", ",", "no_controls", ",", "no_autoplay", ")", "if", "store", ":", "if", "store_name", "is", "not", "None", ":", "url", "=", "store_name", "store_data", "(", "{", "url", ":", "new_url", "}", ")", "echo", "(", "'{}: {}'", ".", "format", "(", "style", "(", "url", ",", "fg", "=", "old_url_colour", ")", ",", "style", "(", "new_url", ",", "fg", "=", "new_url_colour", ")", ")", ")" ]
Convert a Youtube URL so that works correctly with Helium. This command is used for converting the URL for a Youtube video that is part of a playlist so that Helium recognises it as a playlist and when the video ends it correctly moves onto the next video in the playlist. :param youtube_url: the URL of the playlist youtube video. :type youtube_url: str
[ "Convert", "a", "Youtube", "URL", "so", "that", "works", "correctly", "with", "Helium", "." ]
8decc2f410a17314440eeed411a4b19dd4b4e780
https://github.com/JHowell45/helium-cli/blob/8decc2f410a17314440eeed411a4b19dd4b4e780/helium/__init__.py#L53-L78
251,495
JHowell45/helium-cli
helium/__init__.py
list
def list(): """Use this function to display all of the stored URLs. This command is used for displaying all of the URLs and their names from the stored list. """ for name, url in get_all_data().items(): echo('{}: {}'.format( style(name, fg='blue'), style(url, fg='green') ))
python
def list(): """Use this function to display all of the stored URLs. This command is used for displaying all of the URLs and their names from the stored list. """ for name, url in get_all_data().items(): echo('{}: {}'.format( style(name, fg='blue'), style(url, fg='green') ))
[ "def", "list", "(", ")", ":", "for", "name", ",", "url", "in", "get_all_data", "(", ")", ".", "items", "(", ")", ":", "echo", "(", "'{}: {}'", ".", "format", "(", "style", "(", "name", ",", "fg", "=", "'blue'", ")", ",", "style", "(", "url", ",", "fg", "=", "'green'", ")", ")", ")" ]
Use this function to display all of the stored URLs. This command is used for displaying all of the URLs and their names from the stored list.
[ "Use", "this", "function", "to", "display", "all", "of", "the", "stored", "URLs", "." ]
8decc2f410a17314440eeed411a4b19dd4b4e780
https://github.com/JHowell45/helium-cli/blob/8decc2f410a17314440eeed411a4b19dd4b4e780/helium/__init__.py#L94-L104
251,496
anti1869/sunhead
src/sunhead/utils.py
get_class_by_path
def get_class_by_path(class_path: str, is_module: Optional[bool] = False) -> type: """ Get class by its name within a package structure. :param class_path: E.g. brandt.some.module.ClassName :param is_module: Whether last item is module rather than class name :return: Class ready to be instantiated. """ if is_module: try: backend_module = importlib.import_module(class_path) except ImportError: logger.warning("Can't import backend with name `%s`", class_path) raise else: return backend_module module_name, class_name = class_path.rsplit('.', 1) try: backend_module = importlib.import_module(module_name) except ImportError: logger.error("Can't import backend with name `%s`", module_name) raise try: backend_class = getattr(backend_module, class_name) except AttributeError: logger.error("Can't get backend class `%s` from `%s`", class_name, module_name) raise return backend_class
python
def get_class_by_path(class_path: str, is_module: Optional[bool] = False) -> type: """ Get class by its name within a package structure. :param class_path: E.g. brandt.some.module.ClassName :param is_module: Whether last item is module rather than class name :return: Class ready to be instantiated. """ if is_module: try: backend_module = importlib.import_module(class_path) except ImportError: logger.warning("Can't import backend with name `%s`", class_path) raise else: return backend_module module_name, class_name = class_path.rsplit('.', 1) try: backend_module = importlib.import_module(module_name) except ImportError: logger.error("Can't import backend with name `%s`", module_name) raise try: backend_class = getattr(backend_module, class_name) except AttributeError: logger.error("Can't get backend class `%s` from `%s`", class_name, module_name) raise return backend_class
[ "def", "get_class_by_path", "(", "class_path", ":", "str", ",", "is_module", ":", "Optional", "[", "bool", "]", "=", "False", ")", "->", "type", ":", "if", "is_module", ":", "try", ":", "backend_module", "=", "importlib", ".", "import_module", "(", "class_path", ")", "except", "ImportError", ":", "logger", ".", "warning", "(", "\"Can't import backend with name `%s`\"", ",", "class_path", ")", "raise", "else", ":", "return", "backend_module", "module_name", ",", "class_name", "=", "class_path", ".", "rsplit", "(", "'.'", ",", "1", ")", "try", ":", "backend_module", "=", "importlib", ".", "import_module", "(", "module_name", ")", "except", "ImportError", ":", "logger", ".", "error", "(", "\"Can't import backend with name `%s`\"", ",", "module_name", ")", "raise", "try", ":", "backend_class", "=", "getattr", "(", "backend_module", ",", "class_name", ")", "except", "AttributeError", ":", "logger", ".", "error", "(", "\"Can't get backend class `%s` from `%s`\"", ",", "class_name", ",", "module_name", ")", "raise", "return", "backend_class" ]
Get class by its name within a package structure. :param class_path: E.g. brandt.some.module.ClassName :param is_module: Whether last item is module rather than class name :return: Class ready to be instantiated.
[ "Get", "class", "by", "its", "name", "within", "a", "package", "structure", "." ]
5117ec797a38eb82d955241d20547d125efe80f3
https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/utils.py#L26-L58
251,497
anti1869/sunhead
src/sunhead/utils.py
get_submodule_list
def get_submodule_list(package_path: str) -> Tuple[ModuleDescription, ...]: """Get list of submodules for some package by its path. E.g ``pkg.subpackage``""" pkg = importlib.import_module(package_path) subs = ( ModuleDescription( name=modname, path="{}.{}".format(package_path, modname), is_package=ispkg ) for importer, modname, ispkg in pkgutil.iter_modules(pkg.__path__) ) result = tuple(subs) return result
python
def get_submodule_list(package_path: str) -> Tuple[ModuleDescription, ...]: """Get list of submodules for some package by its path. E.g ``pkg.subpackage``""" pkg = importlib.import_module(package_path) subs = ( ModuleDescription( name=modname, path="{}.{}".format(package_path, modname), is_package=ispkg ) for importer, modname, ispkg in pkgutil.iter_modules(pkg.__path__) ) result = tuple(subs) return result
[ "def", "get_submodule_list", "(", "package_path", ":", "str", ")", "->", "Tuple", "[", "ModuleDescription", ",", "...", "]", ":", "pkg", "=", "importlib", ".", "import_module", "(", "package_path", ")", "subs", "=", "(", "ModuleDescription", "(", "name", "=", "modname", ",", "path", "=", "\"{}.{}\"", ".", "format", "(", "package_path", ",", "modname", ")", ",", "is_package", "=", "ispkg", ")", "for", "importer", ",", "modname", ",", "ispkg", "in", "pkgutil", ".", "iter_modules", "(", "pkg", ".", "__path__", ")", ")", "result", "=", "tuple", "(", "subs", ")", "return", "result" ]
Get list of submodules for some package by its path. E.g ``pkg.subpackage``
[ "Get", "list", "of", "submodules", "for", "some", "package", "by", "its", "path", ".", "E", ".", "g", "pkg", ".", "subpackage" ]
5117ec797a38eb82d955241d20547d125efe80f3
https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/utils.py#L61-L73
251,498
anti1869/sunhead
src/sunhead/utils.py
choices_from_enum
def choices_from_enum(source: Enum) -> Tuple[Tuple[Any, str], ...]: """ Makes tuple to use in Django's Fields ``choices`` attribute. Enum members names will be titles for the choices. :param source: Enum to process. :return: Tuple to put into ``choices`` """ result = tuple((s.value, s.name.title()) for s in source) return result
python
def choices_from_enum(source: Enum) -> Tuple[Tuple[Any, str], ...]: """ Makes tuple to use in Django's Fields ``choices`` attribute. Enum members names will be titles for the choices. :param source: Enum to process. :return: Tuple to put into ``choices`` """ result = tuple((s.value, s.name.title()) for s in source) return result
[ "def", "choices_from_enum", "(", "source", ":", "Enum", ")", "->", "Tuple", "[", "Tuple", "[", "Any", ",", "str", "]", ",", "...", "]", ":", "result", "=", "tuple", "(", "(", "s", ".", "value", ",", "s", ".", "name", ".", "title", "(", ")", ")", "for", "s", "in", "source", ")", "return", "result" ]
Makes tuple to use in Django's Fields ``choices`` attribute. Enum members names will be titles for the choices. :param source: Enum to process. :return: Tuple to put into ``choices``
[ "Makes", "tuple", "to", "use", "in", "Django", "s", "Fields", "choices", "attribute", ".", "Enum", "members", "names", "will", "be", "titles", "for", "the", "choices", "." ]
5117ec797a38eb82d955241d20547d125efe80f3
https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/utils.py#L135-L144
251,499
EventTeam/beliefs
src/beliefs/cells/dicts.py
DictCell.is_contradictory
def is_contradictory(self, other): """ Returns True if the two DictCells are unmergeable. """ if not isinstance(other, DictCell): raise Exception("Incomparable") for key, val in self: if key in other.__dict__['p'] \ and val.is_contradictory(other.__dict__['p'][key]): return True return False
python
def is_contradictory(self, other): """ Returns True if the two DictCells are unmergeable. """ if not isinstance(other, DictCell): raise Exception("Incomparable") for key, val in self: if key in other.__dict__['p'] \ and val.is_contradictory(other.__dict__['p'][key]): return True return False
[ "def", "is_contradictory", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "DictCell", ")", ":", "raise", "Exception", "(", "\"Incomparable\"", ")", "for", "key", ",", "val", "in", "self", ":", "if", "key", "in", "other", ".", "__dict__", "[", "'p'", "]", "and", "val", ".", "is_contradictory", "(", "other", ".", "__dict__", "[", "'p'", "]", "[", "key", "]", ")", ":", "return", "True", "return", "False" ]
Returns True if the two DictCells are unmergeable.
[ "Returns", "True", "if", "the", "two", "DictCells", "are", "unmergeable", "." ]
c07d22b61bebeede74a72800030dde770bf64208
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/dicts.py#L132-L140