repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
cmheisel/basecampreporting
src/basecampreporting/project.py
Project.milestones
def milestones(self): '''Array of all milestones''' if self.cache['milestones']: return self.cache['milestones'] milestone_xml = self.bc.list_milestones(self.id) milestones = [] for node in ET.fromstring(milestone_xml).findall("milestone"): milestones.append(Milestone...
python
def milestones(self): '''Array of all milestones''' if self.cache['milestones']: return self.cache['milestones'] milestone_xml = self.bc.list_milestones(self.id) milestones = [] for node in ET.fromstring(milestone_xml).findall("milestone"): milestones.append(Milestone...
[ "def", "milestones", "(", "self", ")", ":", "if", "self", ".", "cache", "[", "'milestones'", "]", ":", "return", "self", ".", "cache", "[", "'milestones'", "]", "milestone_xml", "=", "self", ".", "bc", ".", "list_milestones", "(", "self", ".", "id", ")...
Array of all milestones
[ "Array", "of", "all", "milestones" ]
train
https://github.com/cmheisel/basecampreporting/blob/88ecfc6e835608650ff6be23cbf2421d224c122b/src/basecampreporting/project.py#L167-L178
jwodder/txtble
txtble/util.py
to_lines
def to_lines(s): """ Like `str.splitlines()`, except that an empty string results in a one-element list and a trailing newline results in a trailing empty string (and all without re-implementing Python's changing line-splitting algorithm). >>> to_lines('') [''] >>> to_lines('\\n') [...
python
def to_lines(s): """ Like `str.splitlines()`, except that an empty string results in a one-element list and a trailing newline results in a trailing empty string (and all without re-implementing Python's changing line-splitting algorithm). >>> to_lines('') [''] >>> to_lines('\\n') [...
[ "def", "to_lines", "(", "s", ")", ":", "lines", "=", "s", ".", "splitlines", "(", "True", ")", "if", "not", "lines", ":", "return", "[", "''", "]", "if", "lines", "[", "-", "1", "]", ".", "splitlines", "(", ")", "!=", "[", "lines", "[", "-", ...
Like `str.splitlines()`, except that an empty string results in a one-element list and a trailing newline results in a trailing empty string (and all without re-implementing Python's changing line-splitting algorithm). >>> to_lines('') [''] >>> to_lines('\\n') ['', ''] >>> to_lines('foo...
[ "Like", "str", ".", "splitlines", "()", "except", "that", "an", "empty", "string", "results", "in", "a", "one", "-", "element", "list", "and", "a", "trailing", "newline", "results", "in", "a", "trailing", "empty", "string", "(", "and", "all", "without", ...
train
https://github.com/jwodder/txtble/blob/31d39ed6c15df13599c704a757cd36e1cd57cdd1/txtble/util.py#L34-L72
jwodder/txtble
txtble/util.py
with_color_stripped
def with_color_stripped(f): """ A function decorator for applying to `len` or imitators thereof that strips ANSI color sequences from a string before passing it on. If any color sequences are not followed by a reset sequence, an `UnterminatedColorError` is raised. """ @wraps(f) def colo...
python
def with_color_stripped(f): """ A function decorator for applying to `len` or imitators thereof that strips ANSI color sequences from a string before passing it on. If any color sequences are not followed by a reset sequence, an `UnterminatedColorError` is raised. """ @wraps(f) def colo...
[ "def", "with_color_stripped", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "colored_len", "(", "s", ")", ":", "s2", "=", "re", ".", "sub", "(", "COLOR_BEGIN_RGX", "+", "'(.*?)'", "+", "COLOR_END_RGX", ",", "lambda", "m", ":", "re", ".", ...
A function decorator for applying to `len` or imitators thereof that strips ANSI color sequences from a string before passing it on. If any color sequences are not followed by a reset sequence, an `UnterminatedColorError` is raised.
[ "A", "function", "decorator", "for", "applying", "to", "len", "or", "imitators", "thereof", "that", "strips", "ANSI", "color", "sequences", "from", "a", "string", "before", "passing", "it", "on", ".", "If", "any", "color", "sequences", "are", "not", "followe...
train
https://github.com/jwodder/txtble/blob/31d39ed6c15df13599c704a757cd36e1cd57cdd1/txtble/util.py#L94-L111
jwodder/txtble
txtble/util.py
carry_over_color
def carry_over_color(lines): """ Given a sequence of lines, for each line that contains a ANSI color escape sequence without a reset, add a reset to the end of that line and copy all colors in effect at the end of it to the beginning of the next line. """ lines2 = [] in_effect = '' for s...
python
def carry_over_color(lines): """ Given a sequence of lines, for each line that contains a ANSI color escape sequence without a reset, add a reset to the end of that line and copy all colors in effect at the end of it to the beginning of the next line. """ lines2 = [] in_effect = '' for s...
[ "def", "carry_over_color", "(", "lines", ")", ":", "lines2", "=", "[", "]", "in_effect", "=", "''", "for", "s", "in", "lines", ":", "s", "=", "in_effect", "+", "s", "in_effect", "=", "''", "m", "=", "re", ".", "search", "(", "COLOR_BEGIN_RGX", "+", ...
Given a sequence of lines, for each line that contains a ANSI color escape sequence without a reset, add a reset to the end of that line and copy all colors in effect at the end of it to the beginning of the next line.
[ "Given", "a", "sequence", "of", "lines", "for", "each", "line", "that", "contains", "a", "ANSI", "color", "escape", "sequence", "without", "a", "reset", "add", "a", "reset", "to", "the", "end", "of", "that", "line", "and", "copy", "all", "colors", "in", ...
train
https://github.com/jwodder/txtble/blob/31d39ed6c15df13599c704a757cd36e1cd57cdd1/txtble/util.py#L115-L131
jwodder/txtble
txtble/util.py
breakable_units
def breakable_units(s): """ Break a string into a list of substrings, breaking at each point that it is permissible for `wrap(..., break_long_words=True)` to break; i.e., _not_ breaking in the middle of ANSI color escape sequences. """ units = [] for run, color in zip( re.split('(' +...
python
def breakable_units(s): """ Break a string into a list of substrings, breaking at each point that it is permissible for `wrap(..., break_long_words=True)` to break; i.e., _not_ breaking in the middle of ANSI color escape sequences. """ units = [] for run, color in zip( re.split('(' +...
[ "def", "breakable_units", "(", "s", ")", ":", "units", "=", "[", "]", "for", "run", ",", "color", "in", "zip", "(", "re", ".", "split", "(", "'('", "+", "COLOR_BEGIN_RGX", "+", "'|'", "+", "COLOR_END_RGX", "+", "')'", ",", "s", ")", ",", "cycle", ...
Break a string into a list of substrings, breaking at each point that it is permissible for `wrap(..., break_long_words=True)` to break; i.e., _not_ breaking in the middle of ANSI color escape sequences.
[ "Break", "a", "string", "into", "a", "list", "of", "substrings", "breaking", "at", "each", "point", "that", "it", "is", "permissible", "for", "wrap", "(", "...", "break_long_words", "=", "True", ")", "to", "break", ";", "i", ".", "e", ".", "_not_", "br...
train
https://github.com/jwodder/txtble/blob/31d39ed6c15df13599c704a757cd36e1cd57cdd1/txtble/util.py#L199-L215
draperunner/fjlc
fjlc/main.py
LexiconClassifier.classify
def classify(self, tweets): """ Classify tweet or tweets :param tweets: String or array of strings to classify. :return: String or array of strings depicting sentiment. Sentiment can be POSITIVE, NEGATIVE or NEUTRAL. """ if type(tweets) == str: return self.cla...
python
def classify(self, tweets): """ Classify tweet or tweets :param tweets: String or array of strings to classify. :return: String or array of strings depicting sentiment. Sentiment can be POSITIVE, NEGATIVE or NEUTRAL. """ if type(tweets) == str: return self.cla...
[ "def", "classify", "(", "self", ",", "tweets", ")", ":", "if", "type", "(", "tweets", ")", "==", "str", ":", "return", "self", ".", "classifier", ".", "classify", "(", "tweets", ")", "return", "list", "(", "map", "(", "lambda", "tweet", ":", "self", ...
Classify tweet or tweets :param tweets: String or array of strings to classify. :return: String or array of strings depicting sentiment. Sentiment can be POSITIVE, NEGATIVE or NEUTRAL.
[ "Classify", "tweet", "or", "tweets", ":", "param", "tweets", ":", "String", "or", "array", "of", "strings", "to", "classify", ".", ":", "return", ":", "String", "or", "array", "of", "strings", "depicting", "sentiment", ".", "Sentiment", "can", "be", "POSIT...
train
https://github.com/draperunner/fjlc/blob/d2cc8cf1244984e7caf0bf95b11ed1677a94c994/fjlc/main.py#L78-L87
martijnvermaat/monoseq
monoseq/commands.py
_fasta_iter
def _fasta_iter(fasta): """ Given an open FASTA file, yield tuples of (`header`, `sequence`). """ # Adapted from Brent Pedersen. # http://www.biostars.org/p/710/#1412 groups = (group for _, group in itertools.groupby(fasta, lambda line: line.startswith('>'))) for group in group...
python
def _fasta_iter(fasta): """ Given an open FASTA file, yield tuples of (`header`, `sequence`). """ # Adapted from Brent Pedersen. # http://www.biostars.org/p/710/#1412 groups = (group for _, group in itertools.groupby(fasta, lambda line: line.startswith('>'))) for group in group...
[ "def", "_fasta_iter", "(", "fasta", ")", ":", "# Adapted from Brent Pedersen.", "# http://www.biostars.org/p/710/#1412", "groups", "=", "(", "group", "for", "_", ",", "group", "in", "itertools", ".", "groupby", "(", "fasta", ",", "lambda", "line", ":", "line", "...
Given an open FASTA file, yield tuples of (`header`, `sequence`).
[ "Given", "an", "open", "FASTA", "file", "yield", "tuples", "of", "(", "header", "sequence", ")", "." ]
train
https://github.com/martijnvermaat/monoseq/blob/02b92f6aa482ba169787a1a4bcad28372662dc36/monoseq/commands.py#L35-L46
martijnvermaat/monoseq
monoseq/commands.py
_bed_iter
def _bed_iter(bed): """ Given an open BED file, yield tuples of (`chrom`, `chrom_iter`) where `chrom_iter` yields tuples of (`start`, `stop`). """ records = (line.split()[:3] for line in bed if not (line.startswith('browser') or line.startswith('track'))) for chrom, chrom_iter in...
python
def _bed_iter(bed): """ Given an open BED file, yield tuples of (`chrom`, `chrom_iter`) where `chrom_iter` yields tuples of (`start`, `stop`). """ records = (line.split()[:3] for line in bed if not (line.startswith('browser') or line.startswith('track'))) for chrom, chrom_iter in...
[ "def", "_bed_iter", "(", "bed", ")", ":", "records", "=", "(", "line", ".", "split", "(", ")", "[", ":", "3", "]", "for", "line", "in", "bed", "if", "not", "(", "line", ".", "startswith", "(", "'browser'", ")", "or", "line", ".", "startswith", "(...
Given an open BED file, yield tuples of (`chrom`, `chrom_iter`) where `chrom_iter` yields tuples of (`start`, `stop`).
[ "Given", "an", "open", "BED", "file", "yield", "tuples", "of", "(", "chrom", "chrom_iter", ")", "where", "chrom_iter", "yields", "tuples", "of", "(", "start", "stop", ")", "." ]
train
https://github.com/martijnvermaat/monoseq/blob/02b92f6aa482ba169787a1a4bcad28372662dc36/monoseq/commands.py#L49-L59
martijnvermaat/monoseq
monoseq/commands.py
_pprint_fasta
def _pprint_fasta(fasta, annotations=None, annotation_file=None, block_length=10, blocks_per_line=6): """ Pretty-print each record in the FASTA file. """ annotations = annotations or [] # Annotations by chromosome. as_by_chrom = collections.defaultdict(lambda: [a for a in anno...
python
def _pprint_fasta(fasta, annotations=None, annotation_file=None, block_length=10, blocks_per_line=6): """ Pretty-print each record in the FASTA file. """ annotations = annotations or [] # Annotations by chromosome. as_by_chrom = collections.defaultdict(lambda: [a for a in anno...
[ "def", "_pprint_fasta", "(", "fasta", ",", "annotations", "=", "None", ",", "annotation_file", "=", "None", ",", "block_length", "=", "10", ",", "blocks_per_line", "=", "6", ")", ":", "annotations", "=", "annotations", "or", "[", "]", "# Annotations by chromos...
Pretty-print each record in the FASTA file.
[ "Pretty", "-", "print", "each", "record", "in", "the", "FASTA", "file", "." ]
train
https://github.com/martijnvermaat/monoseq/blob/02b92f6aa482ba169787a1a4bcad28372662dc36/monoseq/commands.py#L62-L81
martijnvermaat/monoseq
monoseq/commands.py
_pprint_line
def _pprint_line(line, annotations=None, annotation_file=None, block_length=10, blocks_per_line=6): """ Pretty-print one line. """ annotations = annotations or [] if annotation_file: # We just use the first chromosome defined in the BED file. _, chrom_iter = next(_b...
python
def _pprint_line(line, annotations=None, annotation_file=None, block_length=10, blocks_per_line=6): """ Pretty-print one line. """ annotations = annotations or [] if annotation_file: # We just use the first chromosome defined in the BED file. _, chrom_iter = next(_b...
[ "def", "_pprint_line", "(", "line", ",", "annotations", "=", "None", ",", "annotation_file", "=", "None", ",", "block_length", "=", "10", ",", "blocks_per_line", "=", "6", ")", ":", "annotations", "=", "annotations", "or", "[", "]", "if", "annotation_file", ...
Pretty-print one line.
[ "Pretty", "-", "print", "one", "line", "." ]
train
https://github.com/martijnvermaat/monoseq/blob/02b92f6aa482ba169787a1a4bcad28372662dc36/monoseq/commands.py#L84-L98
martijnvermaat/monoseq
monoseq/commands.py
pprint
def pprint(sequence_file, annotation=None, annotation_file=None, block_length=10, blocks_per_line=6): """ Pretty-print sequence(s) from a file. """ annotations = [] if annotation: annotations.append([(first - 1, last) for first, last in annotation]) try: # Peek to se...
python
def pprint(sequence_file, annotation=None, annotation_file=None, block_length=10, blocks_per_line=6): """ Pretty-print sequence(s) from a file. """ annotations = [] if annotation: annotations.append([(first - 1, last) for first, last in annotation]) try: # Peek to se...
[ "def", "pprint", "(", "sequence_file", ",", "annotation", "=", "None", ",", "annotation_file", "=", "None", ",", "block_length", "=", "10", ",", "blocks_per_line", "=", "6", ")", ":", "annotations", "=", "[", "]", "if", "annotation", ":", "annotations", "....
Pretty-print sequence(s) from a file.
[ "Pretty", "-", "print", "sequence", "(", "s", ")", "from", "a", "file", "." ]
train
https://github.com/martijnvermaat/monoseq/blob/02b92f6aa482ba169787a1a4bcad28372662dc36/monoseq/commands.py#L101-L126
martijnvermaat/monoseq
monoseq/commands.py
main
def main(): """ Command line interface. """ parser = argparse.ArgumentParser( description='monoseq: pretty-printing DNA and protein sequences', epilog='If INPUT is in FASTA format, each record is pretty-printed ' 'after printing its name and ANNOTATION (if supplied) is used by ' ...
python
def main(): """ Command line interface. """ parser = argparse.ArgumentParser( description='monoseq: pretty-printing DNA and protein sequences', epilog='If INPUT is in FASTA format, each record is pretty-printed ' 'after printing its name and ANNOTATION (if supplied) is used by ' ...
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'monoseq: pretty-printing DNA and protein sequences'", ",", "epilog", "=", "'If INPUT is in FASTA format, each record is pretty-printed '", "'after printing its name and ANNO...
Command line interface.
[ "Command", "line", "interface", "." ]
train
https://github.com/martijnvermaat/monoseq/blob/02b92f6aa482ba169787a1a4bcad28372662dc36/monoseq/commands.py#L129-L162
draperunner/fjlc
fjlc/utils/map_utils.py
normalize_map_between
def normalize_map_between(dictionary, norm_min, norm_max): """ Performs linear normalization of all values in Map between normMin and normMax :param: map Map to normalize values for :param: normMin Smallest normalized value :param: normMax Largest normalized value :return: A new map with do...
python
def normalize_map_between(dictionary, norm_min, norm_max): """ Performs linear normalization of all values in Map between normMin and normMax :param: map Map to normalize values for :param: normMin Smallest normalized value :param: normMax Largest normalized value :return: A new map with do...
[ "def", "normalize_map_between", "(", "dictionary", ",", "norm_min", ",", "norm_max", ")", ":", "if", "len", "(", "dictionary", ")", "<", "2", ":", "return", "{", "}", "values", "=", "list", "(", "dictionary", ".", "values", "(", ")", ")", "norm_range", ...
Performs linear normalization of all values in Map between normMin and normMax :param: map Map to normalize values for :param: normMin Smallest normalized value :param: normMax Largest normalized value :return: A new map with double values within [normMin, normMax]
[ "Performs", "linear", "normalization", "of", "all", "values", "in", "Map", "between", "normMin", "and", "normMax" ]
train
https://github.com/draperunner/fjlc/blob/d2cc8cf1244984e7caf0bf95b11ed1677a94c994/fjlc/utils/map_utils.py#L11-L34
draperunner/fjlc
fjlc/classifier/classifier_options.py
load_options
def load_options(file_name): """ Loads options from a JSON file. The file should contain general classifier options, intensifier words with their intensification values, negation words and stop words. @param file_name Name of file containing the options @throws IOException """ words = from_...
python
def load_options(file_name): """ Loads options from a JSON file. The file should contain general classifier options, intensifier words with their intensification values, negation words and stop words. @param file_name Name of file containing the options @throws IOException """ words = from_...
[ "def", "load_options", "(", "file_name", ")", ":", "words", "=", "from_json", "(", "read_entire_file_into_string", "(", "file_name", ")", ")", "global", "options", ",", "intensifiers", ",", "negators", ",", "stop_words", "options", "=", "words", "[", "\"options\...
Loads options from a JSON file. The file should contain general classifier options, intensifier words with their intensification values, negation words and stop words. @param file_name Name of file containing the options @throws IOException
[ "Loads", "options", "from", "a", "JSON", "file", ".", "The", "file", "should", "contain", "general", "classifier", "options", "intensifier", "words", "with", "their", "intensification", "values", "negation", "words", "and", "stop", "words", "." ]
train
https://github.com/draperunner/fjlc/blob/d2cc8cf1244984e7caf0bf95b11ed1677a94c994/fjlc/classifier/classifier_options.py#L65-L79
elapouya/python-textops
textops/base.py
activate_debug
def activate_debug(): """Activate debug logging on console This function is useful when playing with python-textops through a python console. It is not recommended to use this function in a real application : use standard logging functions instead. """ ch = logging.StreamHandler() ch.setLev...
python
def activate_debug(): """Activate debug logging on console This function is useful when playing with python-textops through a python console. It is not recommended to use this function in a real application : use standard logging functions instead. """ ch = logging.StreamHandler() ch.setLev...
[ "def", "activate_debug", "(", ")", ":", "ch", "=", "logging", ".", "StreamHandler", "(", ")", "ch", ".", "setLevel", "(", "logging", ".", "DEBUG", ")", "logger", ".", "addHandler", "(", "ch", ")", "logger", ".", "setLevel", "(", "logging", ".", "DEBUG"...
Activate debug logging on console This function is useful when playing with python-textops through a python console. It is not recommended to use this function in a real application : use standard logging functions instead.
[ "Activate", "debug", "logging", "on", "console" ]
train
https://github.com/elapouya/python-textops/blob/5c63b9074a1acd8dd108725f1b370f6684c941ef/textops/base.py#L23-L33
elapouya/python-textops
textops/base.py
add_textop
def add_textop(class_or_func): """Decorator to declare custom function or custom class as a new textops op the custom function/class will receive the whole raw input text at once. Examples: >>> @add_textop ... def repeat(text, n, *args,**kwargs): ... return text * n >>...
python
def add_textop(class_or_func): """Decorator to declare custom function or custom class as a new textops op the custom function/class will receive the whole raw input text at once. Examples: >>> @add_textop ... def repeat(text, n, *args,**kwargs): ... return text * n >>...
[ "def", "add_textop", "(", "class_or_func", ")", ":", "if", "isinstance", "(", "class_or_func", ",", "type", ")", ":", "op", "=", "class_or_func", "else", ":", "op", "=", "type", "(", "class_or_func", ".", "__name__", ",", "(", "TextOp", ",", ")", ",", ...
Decorator to declare custom function or custom class as a new textops op the custom function/class will receive the whole raw input text at once. Examples: >>> @add_textop ... def repeat(text, n, *args,**kwargs): ... return text * n >>> 'hello' | repeat(3) 'hellohe...
[ "Decorator", "to", "declare", "custom", "function", "or", "custom", "class", "as", "a", "new", "textops", "op" ]
train
https://github.com/elapouya/python-textops/blob/5c63b9074a1acd8dd108725f1b370f6684c941ef/textops/base.py#L563-L590
elapouya/python-textops
textops/base.py
add_textop_iter
def add_textop_iter(func): """Decorator to declare custom *ITER* function as a new textops op An *ITER* function is a function that will receive the input text as a *LIST* of lines. One have to iterate over this list and generate a result (it can be a list, a generator, a dict, a string, an int ...) ...
python
def add_textop_iter(func): """Decorator to declare custom *ITER* function as a new textops op An *ITER* function is a function that will receive the input text as a *LIST* of lines. One have to iterate over this list and generate a result (it can be a list, a generator, a dict, a string, an int ...) ...
[ "def", "add_textop_iter", "(", "func", ")", ":", "op", "=", "type", "(", "func", ".", "__name__", ",", "(", "WrapOpIter", ",", ")", ",", "{", "'fn'", ":", "staticmethod", "(", "func", ")", "}", ")", "setattr", "(", "textops", ".", "ops", ",", "func...
Decorator to declare custom *ITER* function as a new textops op An *ITER* function is a function that will receive the input text as a *LIST* of lines. One have to iterate over this list and generate a result (it can be a list, a generator, a dict, a string, an int ...) Examples: >>> @add_tex...
[ "Decorator", "to", "declare", "custom", "*", "ITER", "*", "function", "as", "a", "new", "textops", "op" ]
train
https://github.com/elapouya/python-textops/blob/5c63b9074a1acd8dd108725f1b370f6684c941ef/textops/base.py#L592-L627
elapouya/python-textops
textops/base.py
eformat
def eformat(format_str,lst,dct,defvalue='-'): """ Formats a list and a dictionary, manages unkown keys It works like :meth:`string.Formatter.vformat` except that it accepts a defvalue for not matching keys. Defvalue can be a callable that will receive the requested key as argument and return a string ...
python
def eformat(format_str,lst,dct,defvalue='-'): """ Formats a list and a dictionary, manages unkown keys It works like :meth:`string.Formatter.vformat` except that it accepts a defvalue for not matching keys. Defvalue can be a callable that will receive the requested key as argument and return a string ...
[ "def", "eformat", "(", "format_str", ",", "lst", ",", "dct", ",", "defvalue", "=", "'-'", ")", ":", "return", "vformat", "(", "format_str", ",", "DefaultList", "(", "defvalue", ",", "lst", ")", ",", "DefaultDict", "(", "defvalue", ",", "dct", ")", ")" ...
Formats a list and a dictionary, manages unkown keys It works like :meth:`string.Formatter.vformat` except that it accepts a defvalue for not matching keys. Defvalue can be a callable that will receive the requested key as argument and return a string Args: format_string (str): Same format string ...
[ "Formats", "a", "list", "and", "a", "dictionary", "manages", "unkown", "keys" ]
train
https://github.com/elapouya/python-textops/blob/5c63b9074a1acd8dd108725f1b370f6684c941ef/textops/base.py#L1035-L1058
elapouya/python-textops
textops/base.py
TextOp.je
def je(self): r"""Execute operations, returns a string ( '' if the result is None, join=''). This works like :attr:`j` except it returns an empty string if the execution result is None. Examples: >>> echo(None).je '' """ text = self._process() ...
python
def je(self): r"""Execute operations, returns a string ( '' if the result is None, join=''). This works like :attr:`j` except it returns an empty string if the execution result is None. Examples: >>> echo(None).je '' """ text = self._process() ...
[ "def", "je", "(", "self", ")", ":", "text", "=", "self", ".", "_process", "(", ")", "return", "self", ".", "make_string", "(", "text", ",", "join_str", "=", "''", ",", "return_if_none", "=", "''", ")" ]
r"""Execute operations, returns a string ( '' if the result is None, join=''). This works like :attr:`j` except it returns an empty string if the execution result is None. Examples: >>> echo(None).je ''
[ "r", "Execute", "operations", "returns", "a", "string", "(", "if", "the", "result", "is", "None", "join", "=", ")", "." ]
train
https://github.com/elapouya/python-textops/blob/5c63b9074a1acd8dd108725f1b370f6684c941ef/textops/base.py#L311-L323
elapouya/python-textops
textops/base.py
TextOp.op
def op(cls,text,*args,**kwargs): """ This method must be overriden in derived classes """ return cls.fn(text,*args,**kwargs)
python
def op(cls,text,*args,**kwargs): """ This method must be overriden in derived classes """ return cls.fn(text,*args,**kwargs)
[ "def", "op", "(", "cls", ",", "text", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "cls", ".", "fn", "(", "text", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
This method must be overriden in derived classes
[ "This", "method", "must", "be", "overriden", "in", "derived", "classes" ]
train
https://github.com/elapouya/python-textops/blob/5c63b9074a1acd8dd108725f1b370f6684c941ef/textops/base.py#L444-L446
uw-it-aca/uw-restclients
restclients/dao_implementation/__init__.py
get_timeout
def get_timeout(service): """ Returns either a custom timeout for the given service, or a default """ custom_timeout_key = "RESTCLIENTS_%s_TIMEOUT" % service.upper() if hasattr(settings, custom_timeout_key): return getattr(settings, custom_timeout_key) default_key = "RESTCLIENTS_DEFAULT_TIM...
python
def get_timeout(service): """ Returns either a custom timeout for the given service, or a default """ custom_timeout_key = "RESTCLIENTS_%s_TIMEOUT" % service.upper() if hasattr(settings, custom_timeout_key): return getattr(settings, custom_timeout_key) default_key = "RESTCLIENTS_DEFAULT_TIM...
[ "def", "get_timeout", "(", "service", ")", ":", "custom_timeout_key", "=", "\"RESTCLIENTS_%s_TIMEOUT\"", "%", "service", ".", "upper", "(", ")", "if", "hasattr", "(", "settings", ",", "custom_timeout_key", ")", ":", "return", "getattr", "(", "settings", ",", "...
Returns either a custom timeout for the given service, or a default
[ "Returns", "either", "a", "custom", "timeout", "for", "the", "given", "service", "or", "a", "default" ]
train
https://github.com/uw-it-aca/uw-restclients/blob/e12dcd32bf5296b6ebdf71798031594afb7852cb/restclients/dao_implementation/__init__.py#L6-L17
t184256/mutants
mutants/on_access_mutant.py
_delegate_or
def _delegate_or(smethname, func): """ Produce a method that calls either the existing method of the wrapped object with the same name or a special invocation if it's missing (see SPECIAL_METHODS in special_methods.py). Usage: OnAccessMutant(initial_object, callable_mutator) where: callable_mut...
python
def _delegate_or(smethname, func): """ Produce a method that calls either the existing method of the wrapped object with the same name or a special invocation if it's missing (see SPECIAL_METHODS in special_methods.py). Usage: OnAccessMutant(initial_object, callable_mutator) where: callable_mut...
[ "def", "_delegate_or", "(", "smethname", ",", "func", ")", ":", "def", "delegated", "(", "self", ",", "*", "a", ",", "*", "*", "kwa", ")", ":", "# Mutate the object before access", "wrapped", "=", "object", ".", "__getattribute__", "(", "self", ",", "'__wr...
Produce a method that calls either the existing method of the wrapped object with the same name or a special invocation if it's missing (see SPECIAL_METHODS in special_methods.py). Usage: OnAccessMutant(initial_object, callable_mutator) where: callable_mutator(wrapped_object) -> new_wrapped_object
[ "Produce", "a", "method", "that", "calls", "either", "the", "existing", "method", "of", "the", "wrapped", "object", "with", "the", "same", "name", "or", "a", "special", "invocation", "if", "it", "s", "missing", "(", "see", "SPECIAL_METHODS", "in", "special_m...
train
https://github.com/t184256/mutants/blob/efb53df88a4700297937b6e75235fd323bd18923/mutants/on_access_mutant.py#L32-L59
timstaley/voeventdb
voeventdb/server/restapi/v1/definitions.py
_list_class_vars
def _list_class_vars(cls, exclude=None): """ Return a dict of all 'regular' (i.e. not prefixed ``_``) class attributes. """ cvars = {k: v for k, v in vars(cls).items() if not k.startswith('_')} cvars = deepcopy(cvars) if exclude is not None: for e in exclude: cva...
python
def _list_class_vars(cls, exclude=None): """ Return a dict of all 'regular' (i.e. not prefixed ``_``) class attributes. """ cvars = {k: v for k, v in vars(cls).items() if not k.startswith('_')} cvars = deepcopy(cvars) if exclude is not None: for e in exclude: cva...
[ "def", "_list_class_vars", "(", "cls", ",", "exclude", "=", "None", ")", ":", "cvars", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "vars", "(", "cls", ")", ".", "items", "(", ")", "if", "not", "k", ".", "startswith", "(", "'_'", ")", ...
Return a dict of all 'regular' (i.e. not prefixed ``_``) class attributes.
[ "Return", "a", "dict", "of", "all", "regular", "(", "i", ".", "e", ".", "not", "prefixed", "_", ")", "class", "attributes", "." ]
train
https://github.com/timstaley/voeventdb/blob/e37b176d65fced4ca4f059109a95d6974bb8a091/voeventdb/server/restapi/v1/definitions.py#L4-L14
lapets/isqrt
isqrt/isqrt.py
isqrt
def isqrt(n): """ Returns the largest root such that root**2 <= n (root + 1)**2 > n. Credit goes to: https://gist.github.com/castle-bravo/e841684d6bad8e0598e31862a7afcfc7 http://stackoverflow.com/a/23279113/2738025 >>> isqrt(4) 2 >>> isqrt(16) 4 >>> list(map(isqrt, range(16...
python
def isqrt(n): """ Returns the largest root such that root**2 <= n (root + 1)**2 > n. Credit goes to: https://gist.github.com/castle-bravo/e841684d6bad8e0598e31862a7afcfc7 http://stackoverflow.com/a/23279113/2738025 >>> isqrt(4) 2 >>> isqrt(16) 4 >>> list(map(isqrt, range(16...
[ "def", "isqrt", "(", "n", ")", ":", "if", "n", "is", "None", "or", "type", "(", "n", ")", "is", "not", "int", "or", "n", "<", "0", ":", "raise", "ValueError", "(", "\"Input must be a non-negative integer.\"", ")", "try", ":", "# Attempt to use the native m...
Returns the largest root such that root**2 <= n (root + 1)**2 > n. Credit goes to: https://gist.github.com/castle-bravo/e841684d6bad8e0598e31862a7afcfc7 http://stackoverflow.com/a/23279113/2738025 >>> isqrt(4) 2 >>> isqrt(16) 4 >>> list(map(isqrt, range(16,26))) [4, 4, 4, 4, 4,...
[ "Returns", "the", "largest", "root", "such", "that", "root", "**", "2", "<", "=", "n", "(", "root", "+", "1", ")", "**", "2", ">", "n", "." ]
train
https://github.com/lapets/isqrt/blob/133a73659d1490726cdcfe42fe4621f4ec445801/isqrt/isqrt.py#L11-L53
inspirehep/inspire-utils
inspire_utils/logging.py
getStackTraceLogger
def getStackTraceLogger(*args, **kwargs): """Returns a :class:`StackTrace` logger that wraps a Python logger instance.""" logger = logging.getLogger(*args, **kwargs) return StackTraceLogger(logger)
python
def getStackTraceLogger(*args, **kwargs): """Returns a :class:`StackTrace` logger that wraps a Python logger instance.""" logger = logging.getLogger(*args, **kwargs) return StackTraceLogger(logger)
[ "def", "getStackTraceLogger", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "StackTraceLogger", "(", "logger", ")" ]
Returns a :class:`StackTrace` logger that wraps a Python logger instance.
[ "Returns", "a", ":", "class", ":", "StackTrace", "logger", "that", "wraps", "a", "Python", "logger", "instance", "." ]
train
https://github.com/inspirehep/inspire-utils/blob/b0b5983c58700735dfde75e4c8bd32834f2473d4/inspire_utils/logging.py#L45-L48
inspirehep/inspire-utils
inspire_utils/logging.py
StackTraceLogger.error
def error(self, message, *args, **kwargs): """Log error with stack trace and locals information. By default, enables stack trace information in logging messages, so that stacktrace and locals appear in Sentry. """ kwargs.setdefault('extra', {}).setdefault('stack', True) return s...
python
def error(self, message, *args, **kwargs): """Log error with stack trace and locals information. By default, enables stack trace information in logging messages, so that stacktrace and locals appear in Sentry. """ kwargs.setdefault('extra', {}).setdefault('stack', True) return s...
[ "def", "error", "(", "self", ",", "message", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'extra'", ",", "{", "}", ")", ".", "setdefault", "(", "'stack'", ",", "True", ")", "return", "self", ".", "logger",...
Log error with stack trace and locals information. By default, enables stack trace information in logging messages, so that stacktrace and locals appear in Sentry.
[ "Log", "error", "with", "stack", "trace", "and", "locals", "information", "." ]
train
https://github.com/inspirehep/inspire-utils/blob/b0b5983c58700735dfde75e4c8bd32834f2473d4/inspire_utils/logging.py#L36-L42
andycasey/sick
sick/models/interpolation.py
InterpolationModel._initialise_approximator
def _initialise_approximator(self, closest_point=None, wavelengths_required=None, rescale=True, **kwargs): """ Initialise a spectrum interpolator. """ if self._initialised and not kwargs.get("force", False): logger.debug("Ignoring call to re-initialise approximator b...
python
def _initialise_approximator(self, closest_point=None, wavelengths_required=None, rescale=True, **kwargs): """ Initialise a spectrum interpolator. """ if self._initialised and not kwargs.get("force", False): logger.debug("Ignoring call to re-initialise approximator b...
[ "def", "_initialise_approximator", "(", "self", ",", "closest_point", "=", "None", ",", "wavelengths_required", "=", "None", ",", "rescale", "=", "True", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_initialised", "and", "not", "kwargs", ".", "ge...
Initialise a spectrum interpolator.
[ "Initialise", "a", "spectrum", "interpolator", "." ]
train
https://github.com/andycasey/sick/blob/6c37686182794c4cafea45abf7062b30b789b1a2/sick/models/interpolation.py#L23-L109
The-Politico/politico-civic-ap-loader
aploader/management/commands/initialize_election_date.py
Command.get_division
def get_division(self, row): """ Gets the Division object for the given row of election results. """ # back out of Alaska county if ( row["level"] == geography.DivisionLevel.COUNTY and row["statename"] == "Alaska" ): print("Do not tak...
python
def get_division(self, row): """ Gets the Division object for the given row of election results. """ # back out of Alaska county if ( row["level"] == geography.DivisionLevel.COUNTY and row["statename"] == "Alaska" ): print("Do not tak...
[ "def", "get_division", "(", "self", ",", "row", ")", ":", "# back out of Alaska county", "if", "(", "row", "[", "\"level\"", "]", "==", "geography", ".", "DivisionLevel", ".", "COUNTY", "and", "row", "[", "\"statename\"", "]", "==", "\"Alaska\"", ")", ":", ...
Gets the Division object for the given row of election results.
[ "Gets", "the", "Division", "object", "for", "the", "given", "row", "of", "election", "results", "." ]
train
https://github.com/The-Politico/politico-civic-ap-loader/blob/4afeebb62da4b8f22da63711e7176bf4527bccfb/aploader/management/commands/initialize_election_date.py#L20-L51
The-Politico/politico-civic-ap-loader
aploader/management/commands/initialize_election_date.py
Command.get_office
def get_office(self, row, division): """ Gets the Office object for the given row of election results. Depends on knowing the division of the row of election results. """ AT_LARGE_STATES = ["AK", "DE", "MT", "ND", "SD", "VT", "WY"] if division.level.name not in [ ...
python
def get_office(self, row, division): """ Gets the Office object for the given row of election results. Depends on knowing the division of the row of election results. """ AT_LARGE_STATES = ["AK", "DE", "MT", "ND", "SD", "VT", "WY"] if division.level.name not in [ ...
[ "def", "get_office", "(", "self", ",", "row", ",", "division", ")", ":", "AT_LARGE_STATES", "=", "[", "\"AK\"", ",", "\"DE\"", ",", "\"MT\"", ",", "\"ND\"", ",", "\"SD\"", ",", "\"VT\"", ",", "\"WY\"", "]", "if", "division", ".", "level", ".", "name", ...
Gets the Office object for the given row of election results. Depends on knowing the division of the row of election results.
[ "Gets", "the", "Office", "object", "for", "the", "given", "row", "of", "election", "results", ".", "Depends", "on", "knowing", "the", "division", "of", "the", "row", "of", "election", "results", "." ]
train
https://github.com/The-Politico/politico-civic-ap-loader/blob/4afeebb62da4b8f22da63711e7176bf4527bccfb/aploader/management/commands/initialize_election_date.py#L53-L108
The-Politico/politico-civic-ap-loader
aploader/management/commands/initialize_election_date.py
Command.get_race
def get_race(self, row, division): """ Gets the Race object for the given row of election results. In order to get the race, we must know the office. This function will get the office as well. The only way to know if a Race is a special is based on the string of the `ra...
python
def get_race(self, row, division): """ Gets the Race object for the given row of election results. In order to get the race, we must know the office. This function will get the office as well. The only way to know if a Race is a special is based on the string of the `ra...
[ "def", "get_race", "(", "self", ",", "row", ",", "division", ")", ":", "office", "=", "self", ".", "get_office", "(", "row", ",", "division", ")", "try", ":", "return", "election", ".", "Race", ".", "objects", ".", "get", "(", "office", "=", "office"...
Gets the Race object for the given row of election results. In order to get the race, we must know the office. This function will get the office as well. The only way to know if a Race is a special is based on the string of the `racetype` field from the AP data.
[ "Gets", "the", "Race", "object", "for", "the", "given", "row", "of", "election", "results", "." ]
train
https://github.com/The-Politico/politico-civic-ap-loader/blob/4afeebb62da4b8f22da63711e7176bf4527bccfb/aploader/management/commands/initialize_election_date.py#L110-L142
The-Politico/politico-civic-ap-loader
aploader/management/commands/initialize_election_date.py
Command.get_election
def get_election(self, row, race): """ Gets the Election object for the given row of election results. Depends on knowing the Race object. If this is the presidential election, this will determine the Division attached to the election based on the row's statename. This ...
python
def get_election(self, row, race): """ Gets the Election object for the given row of election results. Depends on knowing the Race object. If this is the presidential election, this will determine the Division attached to the election based on the row's statename. This ...
[ "def", "get_election", "(", "self", ",", "row", ",", "race", ")", ":", "election_day", "=", "election", ".", "ElectionDay", ".", "objects", ".", "get", "(", "date", "=", "row", "[", "\"electiondate\"", "]", ")", "if", "row", "[", "\"racetypeid\"", "]", ...
Gets the Election object for the given row of election results. Depends on knowing the Race object. If this is the presidential election, this will determine the Division attached to the election based on the row's statename. This function depends on knowing the Race object from `get_r...
[ "Gets", "the", "Election", "object", "for", "the", "given", "row", "of", "election", "results", ".", "Depends", "on", "knowing", "the", "Race", "object", "." ]
train
https://github.com/The-Politico/politico-civic-ap-loader/blob/4afeebb62da4b8f22da63711e7176bf4527bccfb/aploader/management/commands/initialize_election_date.py#L144-L193
The-Politico/politico-civic-ap-loader
aploader/management/commands/initialize_election_date.py
Command.get_or_create_party
def get_or_create_party(self, row): """ Gets or creates the Party object based on AP code of the row of election data. All parties that aren't Democratic or Republican are aggregable. """ if row["party"] in ["Dem", "GOP"]: aggregable = False else: ...
python
def get_or_create_party(self, row): """ Gets or creates the Party object based on AP code of the row of election data. All parties that aren't Democratic or Republican are aggregable. """ if row["party"] in ["Dem", "GOP"]: aggregable = False else: ...
[ "def", "get_or_create_party", "(", "self", ",", "row", ")", ":", "if", "row", "[", "\"party\"", "]", "in", "[", "\"Dem\"", ",", "\"GOP\"", "]", ":", "aggregable", "=", "False", "else", ":", "aggregable", "=", "True", "defaults", "=", "{", "\"label\"", ...
Gets or creates the Party object based on AP code of the row of election data. All parties that aren't Democratic or Republican are aggregable.
[ "Gets", "or", "creates", "the", "Party", "object", "based", "on", "AP", "code", "of", "the", "row", "of", "election", "data", "." ]
train
https://github.com/The-Politico/politico-civic-ap-loader/blob/4afeebb62da4b8f22da63711e7176bf4527bccfb/aploader/management/commands/initialize_election_date.py#L195-L213
The-Politico/politico-civic-ap-loader
aploader/management/commands/initialize_election_date.py
Command.get_or_create_person
def get_or_create_person(self, row): """ Gets or creates the Person object for the given row of AP data. """ person, created = entity.Person.objects.get_or_create( first_name=row["first"], last_name=row["last"] ) return person
python
def get_or_create_person(self, row): """ Gets or creates the Person object for the given row of AP data. """ person, created = entity.Person.objects.get_or_create( first_name=row["first"], last_name=row["last"] ) return person
[ "def", "get_or_create_person", "(", "self", ",", "row", ")", ":", "person", ",", "created", "=", "entity", ".", "Person", ".", "objects", ".", "get_or_create", "(", "first_name", "=", "row", "[", "\"first\"", "]", ",", "last_name", "=", "row", "[", "\"la...
Gets or creates the Person object for the given row of AP data.
[ "Gets", "or", "creates", "the", "Person", "object", "for", "the", "given", "row", "of", "AP", "data", "." ]
train
https://github.com/The-Politico/politico-civic-ap-loader/blob/4afeebb62da4b8f22da63711e7176bf4527bccfb/aploader/management/commands/initialize_election_date.py#L215-L223
The-Politico/politico-civic-ap-loader
aploader/management/commands/initialize_election_date.py
Command.get_or_create_candidate
def get_or_create_candidate(self, row, party, race): """ Gets or creates the Candidate object for the given row of AP data. In order to tie with live data, this will synthesize the proper AP candidate id. This function also calls `get_or_create_person` to get a Person o...
python
def get_or_create_candidate(self, row, party, race): """ Gets or creates the Candidate object for the given row of AP data. In order to tie with live data, this will synthesize the proper AP candidate id. This function also calls `get_or_create_person` to get a Person o...
[ "def", "get_or_create_candidate", "(", "self", ",", "row", ",", "party", ",", "race", ")", ":", "person", "=", "self", ".", "get_or_create_person", "(", "row", ")", "id_components", "=", "row", "[", "\"id\"", "]", ".", "split", "(", "\"-\"", ")", "candid...
Gets or creates the Candidate object for the given row of AP data. In order to tie with live data, this will synthesize the proper AP candidate id. This function also calls `get_or_create_person` to get a Person object to pass to Django.
[ "Gets", "or", "creates", "the", "Candidate", "object", "for", "the", "given", "row", "of", "AP", "data", "." ]
train
https://github.com/The-Politico/politico-civic-ap-loader/blob/4afeebb62da4b8f22da63711e7176bf4527bccfb/aploader/management/commands/initialize_election_date.py#L225-L253
The-Politico/politico-civic-ap-loader
aploader/management/commands/initialize_election_date.py
Command.get_or_create_candidate_election
def get_or_create_candidate_election( self, row, election, candidate, party ): """ For a given election, this function updates or creates the CandidateElection object using the model method on the election. """ return election.update_or_create_candidate( c...
python
def get_or_create_candidate_election( self, row, election, candidate, party ): """ For a given election, this function updates or creates the CandidateElection object using the model method on the election. """ return election.update_or_create_candidate( c...
[ "def", "get_or_create_candidate_election", "(", "self", ",", "row", ",", "election", ",", "candidate", ",", "party", ")", ":", "return", "election", ".", "update_or_create_candidate", "(", "candidate", ",", "party", ".", "aggregate_candidates", ",", "row", "[", ...
For a given election, this function updates or creates the CandidateElection object using the model method on the election.
[ "For", "a", "given", "election", "this", "function", "updates", "or", "creates", "the", "CandidateElection", "object", "using", "the", "model", "method", "on", "the", "election", "." ]
train
https://github.com/The-Politico/politico-civic-ap-loader/blob/4afeebb62da4b8f22da63711e7176bf4527bccfb/aploader/management/commands/initialize_election_date.py#L255-L264
The-Politico/politico-civic-ap-loader
aploader/management/commands/initialize_election_date.py
Command.get_or_create_ap_election_meta
def get_or_create_ap_election_meta(self, row, election): """ Gets or creates the APElectionMeta object for the given row of AP data. """ APElectionMeta.objects.get_or_create( ap_election_id=row["raceid"], election=election )
python
def get_or_create_ap_election_meta(self, row, election): """ Gets or creates the APElectionMeta object for the given row of AP data. """ APElectionMeta.objects.get_or_create( ap_election_id=row["raceid"], election=election )
[ "def", "get_or_create_ap_election_meta", "(", "self", ",", "row", ",", "election", ")", ":", "APElectionMeta", ".", "objects", ".", "get_or_create", "(", "ap_election_id", "=", "row", "[", "\"raceid\"", "]", ",", "election", "=", "election", ")" ]
Gets or creates the APElectionMeta object for the given row of AP data.
[ "Gets", "or", "creates", "the", "APElectionMeta", "object", "for", "the", "given", "row", "of", "AP", "data", "." ]
train
https://github.com/The-Politico/politico-civic-ap-loader/blob/4afeebb62da4b8f22da63711e7176bf4527bccfb/aploader/management/commands/initialize_election_date.py#L266-L273
The-Politico/politico-civic-ap-loader
aploader/management/commands/initialize_election_date.py
Command.get_or_create_votes
def get_or_create_votes(self, row, division, candidate_election): """ Gets or creates the Vote object for the given row of AP data. """ vote.Votes.objects.get_or_create( division=division, count=row["votecount"], pct=row["votepct"], winning...
python
def get_or_create_votes(self, row, division, candidate_election): """ Gets or creates the Vote object for the given row of AP data. """ vote.Votes.objects.get_or_create( division=division, count=row["votecount"], pct=row["votepct"], winning...
[ "def", "get_or_create_votes", "(", "self", ",", "row", ",", "division", ",", "candidate_election", ")", ":", "vote", ".", "Votes", ".", "objects", ".", "get_or_create", "(", "division", "=", "division", ",", "count", "=", "row", "[", "\"votecount\"", "]", ...
Gets or creates the Vote object for the given row of AP data.
[ "Gets", "or", "creates", "the", "Vote", "object", "for", "the", "given", "row", "of", "AP", "data", "." ]
train
https://github.com/The-Politico/politico-civic-ap-loader/blob/4afeebb62da4b8f22da63711e7176bf4527bccfb/aploader/management/commands/initialize_election_date.py#L275-L286
The-Politico/politico-civic-ap-loader
aploader/management/commands/initialize_election_date.py
Command.process_row
def process_row(self, row): """ Processes a row of AP election data to determine what model objects need to be created. """ division = self.get_division(row) if not division: return None race = self.get_race(row, division) election = self.get_...
python
def process_row(self, row): """ Processes a row of AP election data to determine what model objects need to be created. """ division = self.get_division(row) if not division: return None race = self.get_race(row, division) election = self.get_...
[ "def", "process_row", "(", "self", ",", "row", ")", ":", "division", "=", "self", ".", "get_division", "(", "row", ")", "if", "not", "division", ":", "return", "None", "race", "=", "self", ".", "get_race", "(", "row", ",", "division", ")", "election", ...
Processes a row of AP election data to determine what model objects need to be created.
[ "Processes", "a", "row", "of", "AP", "election", "data", "to", "determine", "what", "model", "objects", "need", "to", "be", "created", "." ]
train
https://github.com/The-Politico/politico-civic-ap-loader/blob/4afeebb62da4b8f22da63711e7176bf4527bccfb/aploader/management/commands/initialize_election_date.py#L288-L309
The-Politico/politico-civic-ap-loader
aploader/management/commands/initialize_election_date.py
Command.handle
def handle(self, *args, **options): """ This management command gets data for a given election date from elex. Then, it loops through each row of the data and calls `process_row`. In order for this command to work, you must have bootstrapped all of the dependent apps: en...
python
def handle(self, *args, **options): """ This management command gets data for a given election date from elex. Then, it loops through each row of the data and calls `process_row`. In order for this command to work, you must have bootstrapped all of the dependent apps: en...
[ "def", "handle", "(", "self", ",", "*", "args", ",", "*", "*", "options", ")", ":", "self", ".", "senate_class", "=", "options", "[", "\"senate_class\"", "]", "writefile", "=", "open", "(", "\"bootstrap.json\"", ",", "\"w\"", ")", "elex_args", "=", "[", ...
This management command gets data for a given election date from elex. Then, it loops through each row of the data and calls `process_row`. In order for this command to work, you must have bootstrapped all of the dependent apps: entity, geography, government, election, vote, and...
[ "This", "management", "command", "gets", "data", "for", "a", "given", "election", "date", "from", "elex", ".", "Then", "it", "loops", "through", "each", "row", "of", "the", "data", "and", "calls", "process_row", "." ]
train
https://github.com/The-Politico/politico-civic-ap-loader/blob/4afeebb62da4b8f22da63711e7176bf4527bccfb/aploader/management/commands/initialize_election_date.py#L318-L374
chop-dbhi/varify-data-warehouse
vdw/samples/migrations/0026_delete_autocreated_batch_cohorts.py
Migration.forwards
def forwards(self, orm): "Write your forwards methods here." orm['samples.Cohort'].objects.filter(autocreated=True, batch__isnull=False).delete()
python
def forwards(self, orm): "Write your forwards methods here." orm['samples.Cohort'].objects.filter(autocreated=True, batch__isnull=False).delete()
[ "def", "forwards", "(", "self", ",", "orm", ")", ":", "orm", "[", "'samples.Cohort'", "]", ".", "objects", ".", "filter", "(", "autocreated", "=", "True", ",", "batch__isnull", "=", "False", ")", ".", "delete", "(", ")" ]
Write your forwards methods here.
[ "Write", "your", "forwards", "methods", "here", "." ]
train
https://github.com/chop-dbhi/varify-data-warehouse/blob/1600ee1bc5fae6c68fd03b23624467298570cca8/vdw/samples/migrations/0026_delete_autocreated_batch_cohorts.py#L9-L11
uw-it-aca/uw-restclients
restclients/trumba/account.py
add_editor
def add_editor(name, userid): """ :param name: a string representing the user's name :param userid: a string representing the user's UW NetID :return: True if request is successful, False otherwise. raise DataFailureException or a corresponding TrumbaException if the request failed or an error c...
python
def add_editor(name, userid): """ :param name: a string representing the user's name :param userid: a string representing the user's UW NetID :return: True if request is successful, False otherwise. raise DataFailureException or a corresponding TrumbaException if the request failed or an error c...
[ "def", "add_editor", "(", "name", ",", "userid", ")", ":", "url", "=", "_make_add_account_url", "(", "name", ",", "userid", ")", "return", "_process_resp", "(", "url", ",", "get_sea_resource", "(", "url", ")", ",", "_is_editor_added", ")" ]
:param name: a string representing the user's name :param userid: a string representing the user's UW NetID :return: True if request is successful, False otherwise. raise DataFailureException or a corresponding TrumbaException if the request failed or an error code has been returned.
[ ":", "param", "name", ":", "a", "string", "representing", "the", "user", "s", "name", ":", "param", "userid", ":", "a", "string", "representing", "the", "user", "s", "UW", "NetID", ":", "return", ":", "True", "if", "request", "is", "successful", "False",...
train
https://github.com/uw-it-aca/uw-restclients/blob/e12dcd32bf5296b6ebdf71798031594afb7852cb/restclients/trumba/account.py#L40-L52
uw-it-aca/uw-restclients
restclients/trumba/account.py
delete_editor
def delete_editor(userid): """ :param userid: a string representing the user's UW NetID :return: True if request is successful, False otherwise. raise DataFailureException or a corresponding TrumbaException if the request failed or an error code has been returned. """ url = _make_del_account...
python
def delete_editor(userid): """ :param userid: a string representing the user's UW NetID :return: True if request is successful, False otherwise. raise DataFailureException or a corresponding TrumbaException if the request failed or an error code has been returned. """ url = _make_del_account...
[ "def", "delete_editor", "(", "userid", ")", ":", "url", "=", "_make_del_account_url", "(", "userid", ")", "return", "_process_resp", "(", "url", ",", "get_sea_resource", "(", "url", ")", ",", "_is_editor_deleted", ")" ]
:param userid: a string representing the user's UW NetID :return: True if request is successful, False otherwise. raise DataFailureException or a corresponding TrumbaException if the request failed or an error code has been returned.
[ ":", "param", "userid", ":", "a", "string", "representing", "the", "user", "s", "UW", "NetID", ":", "return", ":", "True", "if", "request", "is", "successful", "False", "otherwise", ".", "raise", "DataFailureException", "or", "a", "corresponding", "TrumbaExcep...
train
https://github.com/uw-it-aca/uw-restclients/blob/e12dcd32bf5296b6ebdf71798031594afb7852cb/restclients/trumba/account.py#L63-L74
uw-it-aca/uw-restclients
restclients/trumba/account.py
set_bot_permissions
def set_bot_permissions(calendar_id, userid, level): """ :param calendar_id: an integer representing calendar ID :param userid: a string representing the user's UW NetID :param level: a string representing the permission level :return: True if request is successful, False otherwise. raise DataFa...
python
def set_bot_permissions(calendar_id, userid, level): """ :param calendar_id: an integer representing calendar ID :param userid: a string representing the user's UW NetID :param level: a string representing the permission level :return: True if request is successful, False otherwise. raise DataFa...
[ "def", "set_bot_permissions", "(", "calendar_id", ",", "userid", ",", "level", ")", ":", "url", "=", "_make_set_permissions_url", "(", "calendar_id", ",", "userid", ",", "level", ")", "return", "_process_resp", "(", "url", ",", "get_bot_resource", "(", "url", ...
:param calendar_id: an integer representing calendar ID :param userid: a string representing the user's UW NetID :param level: a string representing the permission level :return: True if request is successful, False otherwise. raise DataFailureException or a corresponding TrumbaException if the requ...
[ ":", "param", "calendar_id", ":", "an", "integer", "representing", "calendar", "ID", ":", "param", "userid", ":", "a", "string", "representing", "the", "user", "s", "UW", "NetID", ":", "param", "level", ":", "a", "string", "representing", "the", "permission"...
train
https://github.com/uw-it-aca/uw-restclients/blob/e12dcd32bf5296b6ebdf71798031594afb7852cb/restclients/trumba/account.py#L98-L112
uw-it-aca/uw-restclients
restclients/trumba/account.py
set_sea_permissions
def set_sea_permissions(calendar_id, userid, level): """ :param calendar_id: an integer representing calendar ID :param userid: a string representing the user's UW NetID :param level: a string representing the permission level :return: True if request is successful, False otherwise. raise DataFa...
python
def set_sea_permissions(calendar_id, userid, level): """ :param calendar_id: an integer representing calendar ID :param userid: a string representing the user's UW NetID :param level: a string representing the permission level :return: True if request is successful, False otherwise. raise DataFa...
[ "def", "set_sea_permissions", "(", "calendar_id", ",", "userid", ",", "level", ")", ":", "url", "=", "_make_set_permissions_url", "(", "calendar_id", ",", "userid", ",", "level", ")", "return", "_process_resp", "(", "url", ",", "get_sea_resource", "(", "url", ...
:param calendar_id: an integer representing calendar ID :param userid: a string representing the user's UW NetID :param level: a string representing the permission level :return: True if request is successful, False otherwise. raise DataFailureException or a corresponding TrumbaException if the requ...
[ ":", "param", "calendar_id", ":", "an", "integer", "representing", "calendar", "ID", ":", "param", "userid", ":", "a", "string", "representing", "the", "user", "s", "UW", "NetID", ":", "param", "level", ":", "a", "string", "representing", "the", "permission"...
train
https://github.com/uw-it-aca/uw-restclients/blob/e12dcd32bf5296b6ebdf71798031594afb7852cb/restclients/trumba/account.py#L127-L141
uw-it-aca/uw-restclients
restclients/trumba/account.py
set_tac_permissions
def set_tac_permissions(calendar_id, userid, level): """ :param calendar_id: an integer representing calendar ID :param userid: a string representing the user's UW NetID :param level: a string representing the permission level :return: True if request is successful, False otherwise. raise DataFa...
python
def set_tac_permissions(calendar_id, userid, level): """ :param calendar_id: an integer representing calendar ID :param userid: a string representing the user's UW NetID :param level: a string representing the permission level :return: True if request is successful, False otherwise. raise DataFa...
[ "def", "set_tac_permissions", "(", "calendar_id", ",", "userid", ",", "level", ")", ":", "url", "=", "_make_set_permissions_url", "(", "calendar_id", ",", "userid", ",", "level", ")", "return", "_process_resp", "(", "url", ",", "get_tac_resource", "(", "url", ...
:param calendar_id: an integer representing calendar ID :param userid: a string representing the user's UW NetID :param level: a string representing the permission level :return: True if request is successful, False otherwise. raise DataFailureException or a corresponding TrumbaException if the requ...
[ ":", "param", "calendar_id", ":", "an", "integer", "representing", "calendar", "ID", ":", "param", "userid", ":", "a", "string", "representing", "the", "user", "s", "UW", "NetID", ":", "param", "level", ":", "a", "string", "representing", "the", "permission"...
train
https://github.com/uw-it-aca/uw-restclients/blob/e12dcd32bf5296b6ebdf71798031594afb7852cb/restclients/trumba/account.py#L156-L170
uw-it-aca/uw-restclients
restclients/trumba/account.py
_process_resp
def _process_resp(request_id, response, is_success_func): """ :param request_id: campus url identifying the request :param response: the GET method response object :param is_success_func: the name of the function for verifying a success code :return: True if successful, False otherwise. ...
python
def _process_resp(request_id, response, is_success_func): """ :param request_id: campus url identifying the request :param response: the GET method response object :param is_success_func: the name of the function for verifying a success code :return: True if successful, False otherwise. ...
[ "def", "_process_resp", "(", "request_id", ",", "response", ",", "is_success_func", ")", ":", "if", "response", ".", "status", "!=", "200", ":", "raise", "DataFailureException", "(", "request_id", ",", "response", ".", "status", ",", "response", ".", "reason",...
:param request_id: campus url identifying the request :param response: the GET method response object :param is_success_func: the name of the function for verifying a success code :return: True if successful, False otherwise. raise DataFailureException or a corresponding TrumbaException if t...
[ ":", "param", "request_id", ":", "campus", "url", "identifying", "the", "request", ":", "param", "response", ":", "the", "GET", "method", "response", "object", ":", "param", "is_success_func", ":", "the", "name", "of", "the", "function", "for", "verifying", ...
train
https://github.com/uw-it-aca/uw-restclients/blob/e12dcd32bf5296b6ebdf71798031594afb7852cb/restclients/trumba/account.py#L173-L198
uw-it-aca/uw-restclients
restclients/trumba/account.py
_check_err
def _check_err(code, request_id): """ :param code: an integer value :param request_id: campus url identifying the request Check possible error code returned in the response body raise the corresponding TrumbaException """ if code == 3006: raise CalendarNotExist() elif code == 300...
python
def _check_err(code, request_id): """ :param code: an integer value :param request_id: campus url identifying the request Check possible error code returned in the response body raise the corresponding TrumbaException """ if code == 3006: raise CalendarNotExist() elif code == 300...
[ "def", "_check_err", "(", "code", ",", "request_id", ")", ":", "if", "code", "==", "3006", ":", "raise", "CalendarNotExist", "(", ")", "elif", "code", "==", "3007", ":", "raise", "CalendarOwnByDiffAccount", "(", ")", "elif", "code", "==", "3008", ":", "r...
:param code: an integer value :param request_id: campus url identifying the request Check possible error code returned in the response body raise the corresponding TrumbaException
[ ":", "param", "code", ":", "an", "integer", "value", ":", "param", "request_id", ":", "campus", "url", "identifying", "the", "request", "Check", "possible", "error", "code", "returned", "in", "the", "response", "body", "raise", "the", "corresponding", "TrumbaE...
train
https://github.com/uw-it-aca/uw-restclients/blob/e12dcd32bf5296b6ebdf71798031594afb7852cb/restclients/trumba/account.py#L225-L256
timstaley/voeventdb
voeventdb/server/bin/voeventdb_dump_tarball.py
handle_args
def handle_args(): """ Default values are defined here. """ default_database_name = dbconfig.testdb_corpus_url.database parser = argparse.ArgumentParser( prog=os.path.basename(__file__), # formatter_class=argparse.ArgumentDefaultsHelpFormatter, formatter_class=MyFormatter, ...
python
def handle_args(): """ Default values are defined here. """ default_database_name = dbconfig.testdb_corpus_url.database parser = argparse.ArgumentParser( prog=os.path.basename(__file__), # formatter_class=argparse.ArgumentDefaultsHelpFormatter, formatter_class=MyFormatter, ...
[ "def", "handle_args", "(", ")", ":", "default_database_name", "=", "dbconfig", ".", "testdb_corpus_url", ".", "database", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "os", ".", "path", ".", "basename", "(", "__file__", ")", ",", "# fo...
Default values are defined here.
[ "Default", "values", "are", "defined", "here", "." ]
train
https://github.com/timstaley/voeventdb/blob/e37b176d65fced4ca4f059109a95d6974bb8a091/voeventdb/server/bin/voeventdb_dump_tarball.py#L32-L97
chop-dbhi/varify-data-warehouse
vdw/variants/migrations/0009_rename_evs_maf_datafields.py
Migration.forwards
def forwards(self, orm): "Write your forwards methods here." fields = orm['avocado.DataField'].objects.filter(app_name='variants', model_name='evs', field_name__in=('all_maf', 'aa_maf', 'ea_maf')) for f in fields: f.field_name = f.field_name.replace('maf', 'af') ...
python
def forwards(self, orm): "Write your forwards methods here." fields = orm['avocado.DataField'].objects.filter(app_name='variants', model_name='evs', field_name__in=('all_maf', 'aa_maf', 'ea_maf')) for f in fields: f.field_name = f.field_name.replace('maf', 'af') ...
[ "def", "forwards", "(", "self", ",", "orm", ")", ":", "fields", "=", "orm", "[", "'avocado.DataField'", "]", ".", "objects", ".", "filter", "(", "app_name", "=", "'variants'", ",", "model_name", "=", "'evs'", ",", "field_name__in", "=", "(", "'all_maf'", ...
Write your forwards methods here.
[ "Write", "your", "forwards", "methods", "here", "." ]
train
https://github.com/chop-dbhi/varify-data-warehouse/blob/1600ee1bc5fae6c68fd03b23624467298570cca8/vdw/variants/migrations/0009_rename_evs_maf_datafields.py#L9-L15
nicholasbishop/shaderdef
tools/release.py
bump_minor_version
def bump_minor_version(): """Bump the minor version in version.py.""" version = load_version_as_list() print('current version: {}'.format(format_version_string(version))) version[-1] += 1 print('new version: {}'.format(format_version_string(version))) contents = "__version__ = '{}'\n".format(fo...
python
def bump_minor_version(): """Bump the minor version in version.py.""" version = load_version_as_list() print('current version: {}'.format(format_version_string(version))) version[-1] += 1 print('new version: {}'.format(format_version_string(version))) contents = "__version__ = '{}'\n".format(fo...
[ "def", "bump_minor_version", "(", ")", ":", "version", "=", "load_version_as_list", "(", ")", "print", "(", "'current version: {}'", ".", "format", "(", "format_version_string", "(", "version", ")", ")", ")", "version", "[", "-", "1", "]", "+=", "1", "print"...
Bump the minor version in version.py.
[ "Bump", "the", "minor", "version", "in", "version", ".", "py", "." ]
train
https://github.com/nicholasbishop/shaderdef/blob/b68a9faf4c7cfa61e32a2e49eb2cae2f2e2b1f78/tools/release.py#L27-L37
timstaley/voeventdb
voeventdb/server/restapi/v1/views.py
apiv1_root_view
def apiv1_root_view(): """ API root url. Shows a list of active endpoints. """ docs_url = current_app.config.get('DOCS_URL', 'http://' + request.host + '/docs') message = "Welcome to the voeventdb REST API, " \ "interface version '{}'.".format( ...
python
def apiv1_root_view(): """ API root url. Shows a list of active endpoints. """ docs_url = current_app.config.get('DOCS_URL', 'http://' + request.host + '/docs') message = "Welcome to the voeventdb REST API, " \ "interface version '{}'.".format( ...
[ "def", "apiv1_root_view", "(", ")", ":", "docs_url", "=", "current_app", ".", "config", ".", "get", "(", "'DOCS_URL'", ",", "'http://'", "+", "request", ".", "host", "+", "'/docs'", ")", "message", "=", "\"Welcome to the voeventdb REST API, \"", "\"interface versi...
API root url. Shows a list of active endpoints.
[ "API", "root", "url", ".", "Shows", "a", "list", "of", "active", "endpoints", "." ]
train
https://github.com/timstaley/voeventdb/blob/e37b176d65fced4ca4f059109a95d6974bb8a091/voeventdb/server/restapi/v1/views.py#L82-L105
timstaley/voeventdb
voeventdb/server/restapi/v1/views.py
packet_synopsis
def packet_synopsis(url_encoded_ivorn=None): """ Result: Nested dict providing key details, e.g.:: {"coords": [ { "dec": 10.9712, "error": 0.05, "ra": 233.7307, ...
python
def packet_synopsis(url_encoded_ivorn=None): """ Result: Nested dict providing key details, e.g.:: {"coords": [ { "dec": 10.9712, "error": 0.05, "ra": 233.7307, ...
[ "def", "packet_synopsis", "(", "url_encoded_ivorn", "=", "None", ")", ":", "ivorn", "=", "validate_ivorn", "(", "url_encoded_ivorn", ")", "voevent_row", "=", "db_session", ".", "query", "(", "Voevent", ")", ".", "filter", "(", "Voevent", ".", "ivorn", "==", ...
Result: Nested dict providing key details, e.g.:: {"coords": [ { "dec": 10.9712, "error": 0.05, "ra": 233.7307, "time": "2015-10-01T15:04:22.93...
[ "Result", ":", "Nested", "dict", "providing", "key", "details", "e", ".", "g", ".", "::" ]
train
https://github.com/timstaley/voeventdb/blob/e37b176d65fced4ca4f059109a95d6974bb8a091/voeventdb/server/restapi/v1/views.py#L298-L364
timstaley/voeventdb
voeventdb/server/restapi/v1/views.py
packet_xml
def packet_xml(url_encoded_ivorn=None): """ Returns the XML packet contents stored for a given IVORN. The required IVORN should be appended to the URL after ``/xml/`` in :ref:`URL-encoded <url-encoding>` form. """ # Handle Apache / Debug server difference... # Apache conf must include the s...
python
def packet_xml(url_encoded_ivorn=None): """ Returns the XML packet contents stored for a given IVORN. The required IVORN should be appended to the URL after ``/xml/`` in :ref:`URL-encoded <url-encoding>` form. """ # Handle Apache / Debug server difference... # Apache conf must include the s...
[ "def", "packet_xml", "(", "url_encoded_ivorn", "=", "None", ")", ":", "# Handle Apache / Debug server difference...", "# Apache conf must include the setting::", "# AllowEncodedSlashes NoDecode", "# otherwise urlencoded paths have", "# double-slashes ('//') replaced with single-slashes ('/...
Returns the XML packet contents stored for a given IVORN. The required IVORN should be appended to the URL after ``/xml/`` in :ref:`URL-encoded <url-encoding>` form.
[ "Returns", "the", "XML", "packet", "contents", "stored", "for", "a", "given", "IVORN", "." ]
train
https://github.com/timstaley/voeventdb/blob/e37b176d65fced4ca4f059109a95d6974bb8a091/voeventdb/server/restapi/v1/views.py#L369-L390
kxxoling/flask-decorators
flask_decorators/__init__.py
json_or_jsonp
def json_or_jsonp(func): """Wrap response in JSON or JSONP style""" @wraps(func) def _(*args, **kwargs): mimetype = 'application/javascript' callback = request.args.get('callback', None) if callback is None: content = func(*args, **kwargs) else: conte...
python
def json_or_jsonp(func): """Wrap response in JSON or JSONP style""" @wraps(func) def _(*args, **kwargs): mimetype = 'application/javascript' callback = request.args.get('callback', None) if callback is None: content = func(*args, **kwargs) else: conte...
[ "def", "json_or_jsonp", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "_", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "mimetype", "=", "'application/javascript'", "callback", "=", "request", ".", "args", ".", "get", "(", "'c...
Wrap response in JSON or JSONP style
[ "Wrap", "response", "in", "JSON", "or", "JSONP", "style" ]
train
https://github.com/kxxoling/flask-decorators/blob/e0bf4fc1a5260548063ef8b8adbb782151cd72cc/flask_decorators/__init__.py#L5-L17
kxxoling/flask-decorators
flask_decorators/__init__.py
add_response_headers
def add_response_headers(headers): """Add headers passed in to the response Usage: .. code::py @app.route('/') @add_response_headers({'X-Robots-Tag': 'noindex'}) def not_indexed(): # This will set ``X-Robots-Tag: noindex`` in the response headers return "Ch...
python
def add_response_headers(headers): """Add headers passed in to the response Usage: .. code::py @app.route('/') @add_response_headers({'X-Robots-Tag': 'noindex'}) def not_indexed(): # This will set ``X-Robots-Tag: noindex`` in the response headers return "Ch...
[ "def", "add_response_headers", "(", "headers", ")", ":", "def", "decorator", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "_", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "rsp", "=", "make_response", "(", "func", "(", "*",...
Add headers passed in to the response Usage: .. code::py @app.route('/') @add_response_headers({'X-Robots-Tag': 'noindex'}) def not_indexed(): # This will set ``X-Robots-Tag: noindex`` in the response headers return "Check my headers!"
[ "Add", "headers", "passed", "in", "to", "the", "response" ]
train
https://github.com/kxxoling/flask-decorators/blob/e0bf4fc1a5260548063ef8b8adbb782151cd72cc/flask_decorators/__init__.py#L20-L43
kxxoling/flask-decorators
flask_decorators/__init__.py
gen
def gen(mimetype): """``gen`` is a decorator factory function, you just need to set a mimetype before using:: @app.route('/') @gen('') def index(): pass A full demo for creating a image stream is available on `GitHub <https://github.com/kxxoling/flask-video-streamin...
python
def gen(mimetype): """``gen`` is a decorator factory function, you just need to set a mimetype before using:: @app.route('/') @gen('') def index(): pass A full demo for creating a image stream is available on `GitHub <https://github.com/kxxoling/flask-video-streamin...
[ "def", "gen", "(", "mimetype", ")", ":", "def", "streaming", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "@", "wraps", "(", "func", ")", "def", "_", "(", ")", ":", "return", "Response", "(", "func", "(", "*", "args", ",", ...
``gen`` is a decorator factory function, you just need to set a mimetype before using:: @app.route('/') @gen('') def index(): pass A full demo for creating a image stream is available on `GitHub <https://github.com/kxxoling/flask-video-streaming>`__ .
[ "gen", "is", "a", "decorator", "factory", "function", "you", "just", "need", "to", "set", "a", "mimetype", "before", "using", "::" ]
train
https://github.com/kxxoling/flask-decorators/blob/e0bf4fc1a5260548063ef8b8adbb782151cd72cc/flask_decorators/__init__.py#L46-L64
roll/interest-py
interest/middleware.py
Middleware.path
def path(self): """HTTP full path constraint. (read-only). """ path = self.__prefix if self is not self.over: path = self.over.path + path return path
python
def path(self): """HTTP full path constraint. (read-only). """ path = self.__prefix if self is not self.over: path = self.over.path + path return path
[ "def", "path", "(", "self", ")", ":", "path", "=", "self", ".", "__prefix", "if", "self", "is", "not", "self", ".", "over", ":", "path", "=", "self", ".", "over", ".", "path", "+", "path", "return", "path" ]
HTTP full path constraint. (read-only).
[ "HTTP", "full", "path", "constraint", ".", "(", "read", "-", "only", ")", "." ]
train
https://github.com/roll/interest-py/blob/e6e1def4f2999222aac2fb1d290ae94250673b89/interest/middleware.py#L146-L152
tailhook/magickpy
magickpy/util.py
wrap_ptr_class
def wrap_ptr_class(struct, constructor, destructor, classname=None): """Creates wrapper class for pointer to struct class which appropriately acquires and releases memory """ class WrapperClass(ctypes.c_void_p): def __init__(self, val=None): if val: super(WrapperCla...
python
def wrap_ptr_class(struct, constructor, destructor, classname=None): """Creates wrapper class for pointer to struct class which appropriately acquires and releases memory """ class WrapperClass(ctypes.c_void_p): def __init__(self, val=None): if val: super(WrapperCla...
[ "def", "wrap_ptr_class", "(", "struct", ",", "constructor", ",", "destructor", ",", "classname", "=", "None", ")", ":", "class", "WrapperClass", "(", "ctypes", ".", "c_void_p", ")", ":", "def", "__init__", "(", "self", ",", "val", "=", "None", ")", ":", ...
Creates wrapper class for pointer to struct class which appropriately acquires and releases memory
[ "Creates", "wrapper", "class", "for", "pointer", "to", "struct", "class", "which", "appropriately", "acquires", "and", "releases", "memory" ]
train
https://github.com/tailhook/magickpy/blob/fdfa37539a01dd187d3330726632888be6635f42/magickpy/util.py#L23-L54
liminspace/dju-common
dju_common/file.py
truncate_file
def truncate_file(f): """ Clear uploaded file and allow write to it. Only for not too big files!!! Also can clear simple opened file. Examples: truncate_file(request.FILES['file']) with open('/tmp/file', 'rb+') as f: truncate_file(f) """ if isinstance(f, InMemory...
python
def truncate_file(f): """ Clear uploaded file and allow write to it. Only for not too big files!!! Also can clear simple opened file. Examples: truncate_file(request.FILES['file']) with open('/tmp/file', 'rb+') as f: truncate_file(f) """ if isinstance(f, InMemory...
[ "def", "truncate_file", "(", "f", ")", ":", "if", "isinstance", "(", "f", ",", "InMemoryUploadedFile", ")", ":", "f", ".", "file", "=", "StringIO", "(", ")", "else", ":", "f", ".", "seek", "(", "0", ")", "f", ".", "truncate", "(", "0", ")" ]
Clear uploaded file and allow write to it. Only for not too big files!!! Also can clear simple opened file. Examples: truncate_file(request.FILES['file']) with open('/tmp/file', 'rb+') as f: truncate_file(f)
[ "Clear", "uploaded", "file", "and", "allow", "write", "to", "it", ".", "Only", "for", "not", "too", "big", "files!!!", "Also", "can", "clear", "simple", "opened", "file", ".", "Examples", ":", "truncate_file", "(", "request", ".", "FILES", "[", "file", "...
train
https://github.com/liminspace/dju-common/blob/c68860bb84d454a35e66275841c20f38375c2135/dju_common/file.py#L6-L21
liminspace/dju-common
dju_common/file.py
make_dirs_for_file_path
def make_dirs_for_file_path(file_path, mode=0o775): """ Make dirs for file file_path, if these dirs are not exist. """ dirname = os.path.dirname(file_path) if not os.path.exists(dirname): os.makedirs(dirname, mode=mode)
python
def make_dirs_for_file_path(file_path, mode=0o775): """ Make dirs for file file_path, if these dirs are not exist. """ dirname = os.path.dirname(file_path) if not os.path.exists(dirname): os.makedirs(dirname, mode=mode)
[ "def", "make_dirs_for_file_path", "(", "file_path", ",", "mode", "=", "0o775", ")", ":", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "file_path", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "dirname", ")", ":", "os", ".", "ma...
Make dirs for file file_path, if these dirs are not exist.
[ "Make", "dirs", "for", "file", "file_path", "if", "these", "dirs", "are", "not", "exist", "." ]
train
https://github.com/liminspace/dju-common/blob/c68860bb84d454a35e66275841c20f38375c2135/dju_common/file.py#L24-L30
uw-it-aca/uw-restclients
restclients/o365/license.py
License.set_user_licenses
def set_user_licenses(self, user, add=None, remove=None): """Implements: assignLicense https://msdn.microsoft.com/library/azure/ad/graph/api/functions-and-actions#assignLicense "add" is a dictionary of licence sku id's that reference an array of disabled plan id's add = { '...
python
def set_user_licenses(self, user, add=None, remove=None): """Implements: assignLicense https://msdn.microsoft.com/library/azure/ad/graph/api/functions-and-actions#assignLicense "add" is a dictionary of licence sku id's that reference an array of disabled plan id's add = { '...
[ "def", "set_user_licenses", "(", "self", ",", "user", ",", "add", "=", "None", ",", "remove", "=", "None", ")", ":", "# noqa", "url", "=", "'/users/%s/assignLicense'", "%", "(", "user", ")", "add_licenses", "=", "[", "]", "if", "add", ":", "for", "l", ...
Implements: assignLicense https://msdn.microsoft.com/library/azure/ad/graph/api/functions-and-actions#assignLicense "add" is a dictionary of licence sku id's that reference an array of disabled plan id's add = { '<license-sku-id>': ['<disabled-plan-id'>, ...] "remove" is an...
[ "Implements", ":", "assignLicense", "https", ":", "//", "msdn", ".", "microsoft", ".", "com", "/", "library", "/", "azure", "/", "ad", "/", "graph", "/", "api", "/", "functions", "-", "and", "-", "actions#assignLicense" ]
train
https://github.com/uw-it-aca/uw-restclients/blob/e12dcd32bf5296b6ebdf71798031594afb7852cb/restclients/o365/license.py#L32-L58
ByteInternet/amqpconsumer
amqpconsumer/events.py
EventConsumer.connect
def connect(self): """Connect to RabbitMQ, returning the connection handle. When the connection is established, the on_connection_open method will be invoked by pika. :rtype: pika.SelectConnection """ logger.debug('Connecting to %s', self._url) return pika.Selec...
python
def connect(self): """Connect to RabbitMQ, returning the connection handle. When the connection is established, the on_connection_open method will be invoked by pika. :rtype: pika.SelectConnection """ logger.debug('Connecting to %s', self._url) return pika.Selec...
[ "def", "connect", "(", "self", ")", ":", "logger", ".", "debug", "(", "'Connecting to %s'", ",", "self", ".", "_url", ")", "return", "pika", ".", "SelectConnection", "(", "pika", ".", "URLParameters", "(", "self", ".", "_url", ")", ",", "self", ".", "o...
Connect to RabbitMQ, returning the connection handle. When the connection is established, the on_connection_open method will be invoked by pika. :rtype: pika.SelectConnection
[ "Connect", "to", "RabbitMQ", "returning", "the", "connection", "handle", "." ]
train
https://github.com/ByteInternet/amqpconsumer/blob/144ab16b3fbba8ad30f8688ae1c58e3a6423b88b/amqpconsumer/events.py#L78-L89
ByteInternet/amqpconsumer
amqpconsumer/events.py
EventConsumer.on_connection_closed
def on_connection_closed(self, _, reply_code, reply_text): """Called by pika when the connection to RabbitMQ is closed unexpectedly. Since it is unexpected, we will reconnect to RabbitMQ if it disconnects. :param pika.connection.Connection _: The closed connection object :param...
python
def on_connection_closed(self, _, reply_code, reply_text): """Called by pika when the connection to RabbitMQ is closed unexpectedly. Since it is unexpected, we will reconnect to RabbitMQ if it disconnects. :param pika.connection.Connection _: The closed connection object :param...
[ "def", "on_connection_closed", "(", "self", ",", "_", ",", "reply_code", ",", "reply_text", ")", ":", "self", ".", "_channel", "=", "None", "if", "self", ".", "_closing", ":", "self", ".", "_connection", ".", "ioloop", ".", "stop", "(", ")", "else", ":...
Called by pika when the connection to RabbitMQ is closed unexpectedly. Since it is unexpected, we will reconnect to RabbitMQ if it disconnects. :param pika.connection.Connection _: The closed connection object :param int reply_code: The server provided reply_code if given :para...
[ "Called", "by", "pika", "when", "the", "connection", "to", "RabbitMQ", "is", "closed", "unexpectedly", "." ]
train
https://github.com/ByteInternet/amqpconsumer/blob/144ab16b3fbba8ad30f8688ae1c58e3a6423b88b/amqpconsumer/events.py#L110-L125
ByteInternet/amqpconsumer
amqpconsumer/events.py
EventConsumer.on_channel_open
def on_channel_open(self, channel): """Called by pika when the channel has been opened. The channel object is passed in so we can make use of it. Since the channel is now open, we'll start consuming. :param pika.channel.Channel channel: The channel object """ logger.deb...
python
def on_channel_open(self, channel): """Called by pika when the channel has been opened. The channel object is passed in so we can make use of it. Since the channel is now open, we'll start consuming. :param pika.channel.Channel channel: The channel object """ logger.deb...
[ "def", "on_channel_open", "(", "self", ",", "channel", ")", ":", "logger", ".", "debug", "(", "'Channel opened'", ")", "self", ".", "_channel", "=", "channel", "self", ".", "add_on_channel_close_callback", "(", ")", "self", ".", "setup_qos", "(", ")" ]
Called by pika when the channel has been opened. The channel object is passed in so we can make use of it. Since the channel is now open, we'll start consuming. :param pika.channel.Channel channel: The channel object
[ "Called", "by", "pika", "when", "the", "channel", "has", "been", "opened", "." ]
train
https://github.com/ByteInternet/amqpconsumer/blob/144ab16b3fbba8ad30f8688ae1c58e3a6423b88b/amqpconsumer/events.py#L142-L153
ByteInternet/amqpconsumer
amqpconsumer/events.py
EventConsumer.setup_exchange
def setup_exchange(self): """Declare the exchange When completed, the on_exchange_declareok method will be invoked by pika. """ logger.debug('Declaring exchange %s', self._exchange) self._channel.exchange_declare(self.on_exchange_declareok, ...
python
def setup_exchange(self): """Declare the exchange When completed, the on_exchange_declareok method will be invoked by pika. """ logger.debug('Declaring exchange %s', self._exchange) self._channel.exchange_declare(self.on_exchange_declareok, ...
[ "def", "setup_exchange", "(", "self", ")", ":", "logger", ".", "debug", "(", "'Declaring exchange %s'", ",", "self", ".", "_exchange", ")", "self", ".", "_channel", ".", "exchange_declare", "(", "self", ".", "on_exchange_declareok", ",", "self", ".", "_exchang...
Declare the exchange When completed, the on_exchange_declareok method will be invoked by pika.
[ "Declare", "the", "exchange" ]
train
https://github.com/ByteInternet/amqpconsumer/blob/144ab16b3fbba8ad30f8688ae1c58e3a6423b88b/amqpconsumer/events.py#L166-L175
ByteInternet/amqpconsumer
amqpconsumer/events.py
EventConsumer.setup_queue
def setup_queue(self): """Declare the queue When completed, the on_queue_declareok method will be invoked by pika. """ logger.debug("Declaring queue %s" % self._queue) self._channel.queue_declare(self.on_queue_declareok, self._queue, durable=True)
python
def setup_queue(self): """Declare the queue When completed, the on_queue_declareok method will be invoked by pika. """ logger.debug("Declaring queue %s" % self._queue) self._channel.queue_declare(self.on_queue_declareok, self._queue, durable=True)
[ "def", "setup_queue", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"Declaring queue %s\"", "%", "self", ".", "_queue", ")", "self", ".", "_channel", ".", "queue_declare", "(", "self", ".", "on_queue_declareok", ",", "self", ".", "_queue", ",", "du...
Declare the queue When completed, the on_queue_declareok method will be invoked by pika.
[ "Declare", "the", "queue" ]
train
https://github.com/ByteInternet/amqpconsumer/blob/144ab16b3fbba8ad30f8688ae1c58e3a6423b88b/amqpconsumer/events.py#L185-L191
ByteInternet/amqpconsumer
amqpconsumer/events.py
EventConsumer.on_queue_declareok
def on_queue_declareok(self, _): """Invoked by pika when queue is declared This method will start consuming or first bind the queue to the exchange if an exchange is provided. After binding, the on_bindok method will be invoked by pika. :param pika.frame.Method _: The Queue.De...
python
def on_queue_declareok(self, _): """Invoked by pika when queue is declared This method will start consuming or first bind the queue to the exchange if an exchange is provided. After binding, the on_bindok method will be invoked by pika. :param pika.frame.Method _: The Queue.De...
[ "def", "on_queue_declareok", "(", "self", ",", "_", ")", ":", "logger", ".", "debug", "(", "\"Binding %s to %s with %s\"", ",", "self", ".", "_exchange", ",", "self", ".", "_queue", ",", "self", ".", "_routing_key", ")", "if", "self", ".", "_exchange", ":"...
Invoked by pika when queue is declared This method will start consuming or first bind the queue to the exchange if an exchange is provided. After binding, the on_bindok method will be invoked by pika. :param pika.frame.Method _: The Queue.DeclareOk frame
[ "Invoked", "by", "pika", "when", "queue", "is", "declared" ]
train
https://github.com/ByteInternet/amqpconsumer/blob/144ab16b3fbba8ad30f8688ae1c58e3a6423b88b/amqpconsumer/events.py#L193-L207
ByteInternet/amqpconsumer
amqpconsumer/events.py
EventConsumer.on_consumer_cancelled
def on_consumer_cancelled(self, method_frame): """Invoked by pika when RabbitMQ sends a Basic.Cancel for a consumer receiving messages. :param pika.frame.Method method_frame: The Basic.Cancel frame """ logger.debug('Consumer was cancelled remotely, shutting down: %r', method_fra...
python
def on_consumer_cancelled(self, method_frame): """Invoked by pika when RabbitMQ sends a Basic.Cancel for a consumer receiving messages. :param pika.frame.Method method_frame: The Basic.Cancel frame """ logger.debug('Consumer was cancelled remotely, shutting down: %r', method_fra...
[ "def", "on_consumer_cancelled", "(", "self", ",", "method_frame", ")", ":", "logger", ".", "debug", "(", "'Consumer was cancelled remotely, shutting down: %r'", ",", "method_frame", ")", "if", "self", ".", "_channel", ":", "self", ".", "_channel", ".", "close", "(...
Invoked by pika when RabbitMQ sends a Basic.Cancel for a consumer receiving messages. :param pika.frame.Method method_frame: The Basic.Cancel frame
[ "Invoked", "by", "pika", "when", "RabbitMQ", "sends", "a", "Basic", ".", "Cancel", "for", "a", "consumer", "receiving", "messages", "." ]
train
https://github.com/ByteInternet/amqpconsumer/blob/144ab16b3fbba8ad30f8688ae1c58e3a6423b88b/amqpconsumer/events.py#L268-L276
ByteInternet/amqpconsumer
amqpconsumer/events.py
EventConsumer.on_message
def on_message(self, _, basic_deliver, properties, body): """Invoked by pika when a message is delivered from RabbitMQ. The channel is passed for your convenience. The basic_deliver object that is passed in carries the exchange, routing key, delivery tag and a redelivered flag for the m...
python
def on_message(self, _, basic_deliver, properties, body): """Invoked by pika when a message is delivered from RabbitMQ. The channel is passed for your convenience. The basic_deliver object that is passed in carries the exchange, routing key, delivery tag and a redelivered flag for the m...
[ "def", "on_message", "(", "self", ",", "_", ",", "basic_deliver", ",", "properties", ",", "body", ")", ":", "logger", ".", "debug", "(", "'Received message # %s from %s: %s'", ",", "basic_deliver", ".", "delivery_tag", ",", "properties", ".", "app_id", ",", "b...
Invoked by pika when a message is delivered from RabbitMQ. The channel is passed for your convenience. The basic_deliver object that is passed in carries the exchange, routing key, delivery tag and a redelivered flag for the message. The properties passed in is an instance of BasicPrope...
[ "Invoked", "by", "pika", "when", "a", "message", "is", "delivered", "from", "RabbitMQ", "." ]
train
https://github.com/ByteInternet/amqpconsumer/blob/144ab16b3fbba8ad30f8688ae1c58e3a6423b88b/amqpconsumer/events.py#L278-L304
ByteInternet/amqpconsumer
amqpconsumer/events.py
EventConsumer.acknowledge_message
def acknowledge_message(self, delivery_tag): """Acknowledge the message delivery from RabbitMQ. :param int delivery_tag: The delivery tag from the Basic.Deliver frame """ logger.debug('Acknowledging message %s', delivery_tag) self._channel.basic_ack(delivery_tag)
python
def acknowledge_message(self, delivery_tag): """Acknowledge the message delivery from RabbitMQ. :param int delivery_tag: The delivery tag from the Basic.Deliver frame """ logger.debug('Acknowledging message %s', delivery_tag) self._channel.basic_ack(delivery_tag)
[ "def", "acknowledge_message", "(", "self", ",", "delivery_tag", ")", ":", "logger", ".", "debug", "(", "'Acknowledging message %s'", ",", "delivery_tag", ")", "self", ".", "_channel", ".", "basic_ack", "(", "delivery_tag", ")" ]
Acknowledge the message delivery from RabbitMQ. :param int delivery_tag: The delivery tag from the Basic.Deliver frame
[ "Acknowledge", "the", "message", "delivery", "from", "RabbitMQ", "." ]
train
https://github.com/ByteInternet/amqpconsumer/blob/144ab16b3fbba8ad30f8688ae1c58e3a6423b88b/amqpconsumer/events.py#L306-L312
ByteInternet/amqpconsumer
amqpconsumer/events.py
EventConsumer.open_channel
def open_channel(self): """Open a new channel with RabbitMQ. When RabbitMQ responds that the channel is open, the on_channel_open callback will be invoked by pika. """ logger.debug('Creating new channel') self._connection.channel(on_open_callback=self.on_channel_open)
python
def open_channel(self): """Open a new channel with RabbitMQ. When RabbitMQ responds that the channel is open, the on_channel_open callback will be invoked by pika. """ logger.debug('Creating new channel') self._connection.channel(on_open_callback=self.on_channel_open)
[ "def", "open_channel", "(", "self", ")", ":", "logger", ".", "debug", "(", "'Creating new channel'", ")", "self", ".", "_connection", ".", "channel", "(", "on_open_callback", "=", "self", ".", "on_channel_open", ")" ]
Open a new channel with RabbitMQ. When RabbitMQ responds that the channel is open, the on_channel_open callback will be invoked by pika.
[ "Open", "a", "new", "channel", "with", "RabbitMQ", "." ]
train
https://github.com/ByteInternet/amqpconsumer/blob/144ab16b3fbba8ad30f8688ae1c58e3a6423b88b/amqpconsumer/events.py#L314-L321
ByteInternet/amqpconsumer
amqpconsumer/events.py
EventConsumer.stop
def stop(self): """Cleanly shutdown the connection to RabbitMQ by stopping the consumer with RabbitMQ. When RabbitMQ confirms the cancellation, on_cancelok will be invoked by pika, which will then closing the channel and connection. The IOLoop is started again, becuase this met...
python
def stop(self): """Cleanly shutdown the connection to RabbitMQ by stopping the consumer with RabbitMQ. When RabbitMQ confirms the cancellation, on_cancelok will be invoked by pika, which will then closing the channel and connection. The IOLoop is started again, becuase this met...
[ "def", "stop", "(", "self", ")", ":", "logger", ".", "debug", "(", "'Stopping'", ")", "self", ".", "_closing", "=", "True", "self", ".", "stop_consuming", "(", ")", "self", ".", "_connection", ".", "ioloop", ".", "start", "(", ")", "logger", ".", "de...
Cleanly shutdown the connection to RabbitMQ by stopping the consumer with RabbitMQ. When RabbitMQ confirms the cancellation, on_cancelok will be invoked by pika, which will then closing the channel and connection. The IOLoop is started again, becuase this method is invoked when ...
[ "Cleanly", "shutdown", "the", "connection", "to", "RabbitMQ", "by", "stopping", "the", "consumer", "with", "RabbitMQ", "." ]
train
https://github.com/ByteInternet/amqpconsumer/blob/144ab16b3fbba8ad30f8688ae1c58e3a6423b88b/amqpconsumer/events.py#L330-L347
ByteInternet/amqpconsumer
amqpconsumer/events.py
EventConsumer.stop_consuming
def stop_consuming(self): """Tell RabbitMQ that we would like to stop consuming.""" if self._channel: logger.debug('Sending a Basic.Cancel RPC command to RabbitMQ') self._channel.basic_cancel(self.on_cancelok, self._consumer_tag)
python
def stop_consuming(self): """Tell RabbitMQ that we would like to stop consuming.""" if self._channel: logger.debug('Sending a Basic.Cancel RPC command to RabbitMQ') self._channel.basic_cancel(self.on_cancelok, self._consumer_tag)
[ "def", "stop_consuming", "(", "self", ")", ":", "if", "self", ".", "_channel", ":", "logger", ".", "debug", "(", "'Sending a Basic.Cancel RPC command to RabbitMQ'", ")", "self", ".", "_channel", ".", "basic_cancel", "(", "self", ".", "on_cancelok", ",", "self", ...
Tell RabbitMQ that we would like to stop consuming.
[ "Tell", "RabbitMQ", "that", "we", "would", "like", "to", "stop", "consuming", "." ]
train
https://github.com/ByteInternet/amqpconsumer/blob/144ab16b3fbba8ad30f8688ae1c58e3a6423b88b/amqpconsumer/events.py#L349-L353
uw-it-aca/uw-restclients
restclients/o365/__init__.py
O365.get_resource
def get_resource(self, path, params=None): """ O365 GET method. Return representation of the requested resource. """ url = '%s%s' % (path, self._param_list(params)) headers = { 'Accept': 'application/json;odata=minimalmetadata' } response = O365_DAO()...
python
def get_resource(self, path, params=None): """ O365 GET method. Return representation of the requested resource. """ url = '%s%s' % (path, self._param_list(params)) headers = { 'Accept': 'application/json;odata=minimalmetadata' } response = O365_DAO()...
[ "def", "get_resource", "(", "self", ",", "path", ",", "params", "=", "None", ")", ":", "url", "=", "'%s%s'", "%", "(", "path", ",", "self", ".", "_param_list", "(", "params", ")", ")", "headers", "=", "{", "'Accept'", ":", "'application/json;odata=minima...
O365 GET method. Return representation of the requested resource.
[ "O365", "GET", "method", ".", "Return", "representation", "of", "the", "requested", "resource", "." ]
train
https://github.com/uw-it-aca/uw-restclients/blob/e12dcd32bf5296b6ebdf71798031594afb7852cb/restclients/o365/__init__.py#L33-L47
uw-it-aca/uw-restclients
restclients/o365/__init__.py
O365.post_resource
def post_resource(self, path, body=None, json=None): """ O365 POST method. """ url = '%s%s' % (path, self._param_list()) headers = { 'Accept': 'application/json;odata=minimalmetadata' } if json: headers['Content-Type'] = 'application/json'...
python
def post_resource(self, path, body=None, json=None): """ O365 POST method. """ url = '%s%s' % (path, self._param_list()) headers = { 'Accept': 'application/json;odata=minimalmetadata' } if json: headers['Content-Type'] = 'application/json'...
[ "def", "post_resource", "(", "self", ",", "path", ",", "body", "=", "None", ",", "json", "=", "None", ")", ":", "url", "=", "'%s%s'", "%", "(", "path", ",", "self", ".", "_param_list", "(", ")", ")", "headers", "=", "{", "'Accept'", ":", "'applicat...
O365 POST method.
[ "O365", "POST", "method", "." ]
train
https://github.com/uw-it-aca/uw-restclients/blob/e12dcd32bf5296b6ebdf71798031594afb7852cb/restclients/o365/__init__.py#L49-L68
uw-it-aca/uw-restclients
restclients/o365/__init__.py
O365.patch_resource
def patch_resource(self, path, body=None, json=None): """ O365 PATCH method. """ url = '%s%s' % (path, self._param_list()) headers = { 'Accept': 'application/json;odata=minimalmetadata' } if json: headers['Content-Type'] = 'application/jso...
python
def patch_resource(self, path, body=None, json=None): """ O365 PATCH method. """ url = '%s%s' % (path, self._param_list()) headers = { 'Accept': 'application/json;odata=minimalmetadata' } if json: headers['Content-Type'] = 'application/jso...
[ "def", "patch_resource", "(", "self", ",", "path", ",", "body", "=", "None", ",", "json", "=", "None", ")", ":", "url", "=", "'%s%s'", "%", "(", "path", ",", "self", ".", "_param_list", "(", ")", ")", "headers", "=", "{", "'Accept'", ":", "'applica...
O365 PATCH method.
[ "O365", "PATCH", "method", "." ]
train
https://github.com/uw-it-aca/uw-restclients/blob/e12dcd32bf5296b6ebdf71798031594afb7852cb/restclients/o365/__init__.py#L70-L89
JNRowe/upoints
upoints/gpx.py
_GpxElem.togpx
def togpx(self): """Generate a GPX waypoint element subtree. Returns: etree.Element: GPX element """ element = create_elem(self.__class__._elem_name, {'lat': str(self.latitude), 'lon': str(self.longitude)}) ...
python
def togpx(self): """Generate a GPX waypoint element subtree. Returns: etree.Element: GPX element """ element = create_elem(self.__class__._elem_name, {'lat': str(self.latitude), 'lon': str(self.longitude)}) ...
[ "def", "togpx", "(", "self", ")", ":", "element", "=", "create_elem", "(", "self", ".", "__class__", ".", "_elem_name", ",", "{", "'lat'", ":", "str", "(", "self", ".", "latitude", ")", ",", "'lon'", ":", "str", "(", "self", ".", "longitude", ")", ...
Generate a GPX waypoint element subtree. Returns: etree.Element: GPX element
[ "Generate", "a", "GPX", "waypoint", "element", "subtree", "." ]
train
https://github.com/JNRowe/upoints/blob/1e4b7a53ed2a06cd854523d54c36aabdccea3830/upoints/gpx.py#L90-L107
JNRowe/upoints
upoints/gpx.py
_SegWrap.distance
def distance(self, method='haversine'): """Calculate distances between locations in segments. Args: method (str): Method used to calculate distance Returns: list of list of float: Groups of distance between points in segments """ distance...
python
def distance(self, method='haversine'): """Calculate distances between locations in segments. Args: method (str): Method used to calculate distance Returns: list of list of float: Groups of distance between points in segments """ distance...
[ "def", "distance", "(", "self", ",", "method", "=", "'haversine'", ")", ":", "distances", "=", "[", "]", "for", "segment", "in", "self", ":", "if", "len", "(", "segment", ")", "<", "2", ":", "distances", ".", "append", "(", "[", "]", ")", "else", ...
Calculate distances between locations in segments. Args: method (str): Method used to calculate distance Returns: list of list of float: Groups of distance between points in segments
[ "Calculate", "distances", "between", "locations", "in", "segments", "." ]
train
https://github.com/JNRowe/upoints/blob/1e4b7a53ed2a06cd854523d54c36aabdccea3830/upoints/gpx.py#L124-L140
JNRowe/upoints
upoints/gpx.py
_SegWrap.bearing
def bearing(self, format='numeric'): """Calculate bearing between locations in segments. Args: format (str): Format of the bearing string to return Returns: list of list of float: Groups of bearings between points in segments """ bearings...
python
def bearing(self, format='numeric'): """Calculate bearing between locations in segments. Args: format (str): Format of the bearing string to return Returns: list of list of float: Groups of bearings between points in segments """ bearings...
[ "def", "bearing", "(", "self", ",", "format", "=", "'numeric'", ")", ":", "bearings", "=", "[", "]", "for", "segment", "in", "self", ":", "if", "len", "(", "segment", ")", "<", "2", ":", "bearings", ".", "append", "(", "[", "]", ")", "else", ":",...
Calculate bearing between locations in segments. Args: format (str): Format of the bearing string to return Returns: list of list of float: Groups of bearings between points in segments
[ "Calculate", "bearing", "between", "locations", "in", "segments", "." ]
train
https://github.com/JNRowe/upoints/blob/1e4b7a53ed2a06cd854523d54c36aabdccea3830/upoints/gpx.py#L142-L158
JNRowe/upoints
upoints/gpx.py
_SegWrap.final_bearing
def final_bearing(self, format='numeric'): """Calculate final bearing between locations in segments. Args: format (str): Format of the bearing string to return Returns: list of list of float: Groups of bearings between points in segments """ ...
python
def final_bearing(self, format='numeric'): """Calculate final bearing between locations in segments. Args: format (str): Format of the bearing string to return Returns: list of list of float: Groups of bearings between points in segments """ ...
[ "def", "final_bearing", "(", "self", ",", "format", "=", "'numeric'", ")", ":", "bearings", "=", "[", "]", "for", "segment", "in", "self", ":", "if", "len", "(", "segment", ")", "<", "2", ":", "bearings", ".", "append", "(", "[", "]", ")", "else", ...
Calculate final bearing between locations in segments. Args: format (str): Format of the bearing string to return Returns: list of list of float: Groups of bearings between points in segments
[ "Calculate", "final", "bearing", "between", "locations", "in", "segments", "." ]
train
https://github.com/JNRowe/upoints/blob/1e4b7a53ed2a06cd854523d54c36aabdccea3830/upoints/gpx.py#L160-L176
JNRowe/upoints
upoints/gpx.py
_SegWrap.inverse
def inverse(self): """Calculate the inverse geodesic between locations in segments. Returns: list of 2-tuple of float: Groups in bearing and distance between points in segments """ inverses = [] for segment in self: if len(segment) < 2: ...
python
def inverse(self): """Calculate the inverse geodesic between locations in segments. Returns: list of 2-tuple of float: Groups in bearing and distance between points in segments """ inverses = [] for segment in self: if len(segment) < 2: ...
[ "def", "inverse", "(", "self", ")", ":", "inverses", "=", "[", "]", "for", "segment", "in", "self", ":", "if", "len", "(", "segment", ")", "<", "2", ":", "inverses", ".", "append", "(", "[", "]", ")", "else", ":", "inverses", ".", "append", "(", ...
Calculate the inverse geodesic between locations in segments. Returns: list of 2-tuple of float: Groups in bearing and distance between points in segments
[ "Calculate", "the", "inverse", "geodesic", "between", "locations", "in", "segments", "." ]
train
https://github.com/JNRowe/upoints/blob/1e4b7a53ed2a06cd854523d54c36aabdccea3830/upoints/gpx.py#L178-L191
JNRowe/upoints
upoints/gpx.py
_SegWrap.midpoint
def midpoint(self): """Calculate the midpoint between locations in segments. Returns: list of Point: Groups of midpoint between points in segments """ midpoints = [] for segment in self: if len(segment) < 2: midpoints.append([]) ...
python
def midpoint(self): """Calculate the midpoint between locations in segments. Returns: list of Point: Groups of midpoint between points in segments """ midpoints = [] for segment in self: if len(segment) < 2: midpoints.append([]) ...
[ "def", "midpoint", "(", "self", ")", ":", "midpoints", "=", "[", "]", "for", "segment", "in", "self", ":", "if", "len", "(", "segment", ")", "<", "2", ":", "midpoints", ".", "append", "(", "[", "]", ")", "else", ":", "midpoints", ".", "append", "...
Calculate the midpoint between locations in segments. Returns: list of Point: Groups of midpoint between points in segments
[ "Calculate", "the", "midpoint", "between", "locations", "in", "segments", "." ]
train
https://github.com/JNRowe/upoints/blob/1e4b7a53ed2a06cd854523d54c36aabdccea3830/upoints/gpx.py#L193-L205
JNRowe/upoints
upoints/gpx.py
_SegWrap.range
def range(self, location, distance): """Test whether locations are within a given range of ``location``. Args: location (Point): Location to test range against distance (float): Distance to test location is within Returns: list of list of Point: Groups of po...
python
def range(self, location, distance): """Test whether locations are within a given range of ``location``. Args: location (Point): Location to test range against distance (float): Distance to test location is within Returns: list of list of Point: Groups of po...
[ "def", "range", "(", "self", ",", "location", ",", "distance", ")", ":", "return", "(", "segment", ".", "range", "(", "location", ",", "distance", ")", "for", "segment", "in", "self", ")" ]
Test whether locations are within a given range of ``location``. Args: location (Point): Location to test range against distance (float): Distance to test location is within Returns: list of list of Point: Groups of points in range per segment
[ "Test", "whether", "locations", "are", "within", "a", "given", "range", "of", "location", "." ]
train
https://github.com/JNRowe/upoints/blob/1e4b7a53ed2a06cd854523d54c36aabdccea3830/upoints/gpx.py#L207-L217
JNRowe/upoints
upoints/gpx.py
_SegWrap.destination
def destination(self, bearing, distance): """Calculate destination locations for given distance and bearings. Args: bearing (float): Bearing to move on in degrees distance (float): Distance in kilometres Returns: list of list of Point: Groups of points shift...
python
def destination(self, bearing, distance): """Calculate destination locations for given distance and bearings. Args: bearing (float): Bearing to move on in degrees distance (float): Distance in kilometres Returns: list of list of Point: Groups of points shift...
[ "def", "destination", "(", "self", ",", "bearing", ",", "distance", ")", ":", "return", "(", "segment", ".", "destination", "(", "bearing", ",", "distance", ")", "for", "segment", "in", "self", ")" ]
Calculate destination locations for given distance and bearings. Args: bearing (float): Bearing to move on in degrees distance (float): Distance in kilometres Returns: list of list of Point: Groups of points shifted by ``distance`` and ``bearing``
[ "Calculate", "destination", "locations", "for", "given", "distance", "and", "bearings", "." ]
train
https://github.com/JNRowe/upoints/blob/1e4b7a53ed2a06cd854523d54c36aabdccea3830/upoints/gpx.py#L219-L230
JNRowe/upoints
upoints/gpx.py
_SegWrap.sunrise
def sunrise(self, date=None, zenith=None): """Calculate sunrise times for locations. Args: date (datetime.date): Calculate rise or set for given date zenith (str): Calculate sunrise events, or end of twilight Returns: list of list of datetime.datetime: The ti...
python
def sunrise(self, date=None, zenith=None): """Calculate sunrise times for locations. Args: date (datetime.date): Calculate rise or set for given date zenith (str): Calculate sunrise events, or end of twilight Returns: list of list of datetime.datetime: The ti...
[ "def", "sunrise", "(", "self", ",", "date", "=", "None", ",", "zenith", "=", "None", ")", ":", "return", "(", "segment", ".", "sunrise", "(", "date", ",", "zenith", ")", "for", "segment", "in", "self", ")" ]
Calculate sunrise times for locations. Args: date (datetime.date): Calculate rise or set for given date zenith (str): Calculate sunrise events, or end of twilight Returns: list of list of datetime.datetime: The time for the sunrise for each point in e...
[ "Calculate", "sunrise", "times", "for", "locations", "." ]
train
https://github.com/JNRowe/upoints/blob/1e4b7a53ed2a06cd854523d54c36aabdccea3830/upoints/gpx.py#L233-L243
JNRowe/upoints
upoints/gpx.py
_SegWrap.sunset
def sunset(self, date=None, zenith=None): """Calculate sunset times for locations. Args: date (datetime.date): Calculate rise or set for given date zenith (str): Calculate sunset events, or start of twilight times Returns: list of list of datetime.datetime: ...
python
def sunset(self, date=None, zenith=None): """Calculate sunset times for locations. Args: date (datetime.date): Calculate rise or set for given date zenith (str): Calculate sunset events, or start of twilight times Returns: list of list of datetime.datetime: ...
[ "def", "sunset", "(", "self", ",", "date", "=", "None", ",", "zenith", "=", "None", ")", ":", "return", "(", "segment", ".", "sunset", "(", "date", ",", "zenith", ")", "for", "segment", "in", "self", ")" ]
Calculate sunset times for locations. Args: date (datetime.date): Calculate rise or set for given date zenith (str): Calculate sunset events, or start of twilight times Returns: list of list of datetime.datetime: The time for the sunset for each poin...
[ "Calculate", "sunset", "times", "for", "locations", "." ]
train
https://github.com/JNRowe/upoints/blob/1e4b7a53ed2a06cd854523d54c36aabdccea3830/upoints/gpx.py#L245-L256
JNRowe/upoints
upoints/gpx.py
_SegWrap.sun_events
def sun_events(self, date=None, zenith=None): """Calculate sunrise/sunset times for locations. Args: date (datetime.date): Calculate rise or set for given date zenith (str): Calculate rise/set events, or twilight times Returns: list of list of 2-tuple of dat...
python
def sun_events(self, date=None, zenith=None): """Calculate sunrise/sunset times for locations. Args: date (datetime.date): Calculate rise or set for given date zenith (str): Calculate rise/set events, or twilight times Returns: list of list of 2-tuple of dat...
[ "def", "sun_events", "(", "self", ",", "date", "=", "None", ",", "zenith", "=", "None", ")", ":", "return", "(", "segment", ".", "sun_events", "(", "date", ",", "zenith", ")", "for", "segment", "in", "self", ")" ]
Calculate sunrise/sunset times for locations. Args: date (datetime.date): Calculate rise or set for given date zenith (str): Calculate rise/set events, or twilight times Returns: list of list of 2-tuple of datetime.datetime: The time for the sunrise ...
[ "Calculate", "sunrise", "/", "sunset", "times", "for", "locations", "." ]
train
https://github.com/JNRowe/upoints/blob/1e4b7a53ed2a06cd854523d54c36aabdccea3830/upoints/gpx.py#L258-L269
JNRowe/upoints
upoints/gpx.py
_GpxMeta.togpx
def togpx(self): """Generate a GPX metadata element subtree. Returns: etree.Element: GPX metadata element """ metadata = create_elem('metadata') if self.name: metadata.append(create_elem('name', text=self.name)) if self.desc: metadata....
python
def togpx(self): """Generate a GPX metadata element subtree. Returns: etree.Element: GPX metadata element """ metadata = create_elem('metadata') if self.name: metadata.append(create_elem('name', text=self.name)) if self.desc: metadata....
[ "def", "togpx", "(", "self", ")", ":", "metadata", "=", "create_elem", "(", "'metadata'", ")", "if", "self", ".", "name", ":", "metadata", ".", "append", "(", "create_elem", "(", "'name'", ",", "text", "=", "self", ".", "name", ")", ")", "if", "self"...
Generate a GPX metadata element subtree. Returns: etree.Element: GPX metadata element
[ "Generate", "a", "GPX", "metadata", "element", "subtree", "." ]
train
https://github.com/JNRowe/upoints/blob/1e4b7a53ed2a06cd854523d54c36aabdccea3830/upoints/gpx.py#L329-L402
JNRowe/upoints
upoints/gpx.py
_GpxMeta.import_metadata
def import_metadata(self, elements): """Import information from GPX metadata. Args: elements (etree.Element): GPX metadata subtree """ metadata_elem = lambda name: etree.QName(GPX_NS, name) for child in elements.getchildren(): tag_ns, tag_name = child.ta...
python
def import_metadata(self, elements): """Import information from GPX metadata. Args: elements (etree.Element): GPX metadata subtree """ metadata_elem = lambda name: etree.QName(GPX_NS, name) for child in elements.getchildren(): tag_ns, tag_name = child.ta...
[ "def", "import_metadata", "(", "self", ",", "elements", ")", ":", "metadata_elem", "=", "lambda", "name", ":", "etree", ".", "QName", "(", "GPX_NS", ",", "name", ")", "for", "child", "in", "elements", ".", "getchildren", "(", ")", ":", "tag_ns", ",", "...
Import information from GPX metadata. Args: elements (etree.Element): GPX metadata subtree
[ "Import", "information", "from", "GPX", "metadata", "." ]
train
https://github.com/JNRowe/upoints/blob/1e4b7a53ed2a06cd854523d54c36aabdccea3830/upoints/gpx.py#L404-L447
JNRowe/upoints
upoints/gpx.py
Waypoints.import_locations
def import_locations(self, gpx_file): """Import GPX data files. ``import_locations()`` returns a list with :class:`~gpx.Waypoint` objects. It expects data files in GPX format, as specified in `GPX 1.1 Schema Documentation`_, which is XML such as:: <?xml version="1....
python
def import_locations(self, gpx_file): """Import GPX data files. ``import_locations()`` returns a list with :class:`~gpx.Waypoint` objects. It expects data files in GPX format, as specified in `GPX 1.1 Schema Documentation`_, which is XML such as:: <?xml version="1....
[ "def", "import_locations", "(", "self", ",", "gpx_file", ")", ":", "self", ".", "_gpx_file", "=", "gpx_file", "data", "=", "utils", ".", "prepare_xml_read", "(", "gpx_file", ",", "objectify", "=", "True", ")", "try", ":", "self", ".", "metadata", ".", "i...
Import GPX data files. ``import_locations()`` returns a list with :class:`~gpx.Waypoint` objects. It expects data files in GPX format, as specified in `GPX 1.1 Schema Documentation`_, which is XML such as:: <?xml version="1.0" encoding="utf-8" standalone="no"?> ...
[ "Import", "GPX", "data", "files", "." ]
train
https://github.com/JNRowe/upoints/blob/1e4b7a53ed2a06cd854523d54c36aabdccea3830/upoints/gpx.py#L478-L546
JNRowe/upoints
upoints/gpx.py
Waypoints.export_gpx_file
def export_gpx_file(self): """Generate GPX element tree from ``Waypoints`` object. Returns: etree.ElementTree: GPX element tree depicting ``Waypoints`` object """ gpx = create_elem('gpx', GPX_ELEM_ATTRIB) if not self.metadata.bounds: self.metadata.bounds ...
python
def export_gpx_file(self): """Generate GPX element tree from ``Waypoints`` object. Returns: etree.ElementTree: GPX element tree depicting ``Waypoints`` object """ gpx = create_elem('gpx', GPX_ELEM_ATTRIB) if not self.metadata.bounds: self.metadata.bounds ...
[ "def", "export_gpx_file", "(", "self", ")", ":", "gpx", "=", "create_elem", "(", "'gpx'", ",", "GPX_ELEM_ATTRIB", ")", "if", "not", "self", ".", "metadata", ".", "bounds", ":", "self", ".", "metadata", ".", "bounds", "=", "self", "[", ":", "]", "gpx", ...
Generate GPX element tree from ``Waypoints`` object. Returns: etree.ElementTree: GPX element tree depicting ``Waypoints`` object
[ "Generate", "GPX", "element", "tree", "from", "Waypoints", "object", "." ]
train
https://github.com/JNRowe/upoints/blob/1e4b7a53ed2a06cd854523d54c36aabdccea3830/upoints/gpx.py#L548-L561
JNRowe/upoints
upoints/gpx.py
Trackpoints.import_locations
def import_locations(self, gpx_file): """Import GPX data files. ``import_locations()`` returns a series of lists representing track segments with :class:`Trackpoint` objects as contents. It expects data files in GPX format, as specified in `GPX 1.1 Schema Documentation`_, which...
python
def import_locations(self, gpx_file): """Import GPX data files. ``import_locations()`` returns a series of lists representing track segments with :class:`Trackpoint` objects as contents. It expects data files in GPX format, as specified in `GPX 1.1 Schema Documentation`_, which...
[ "def", "import_locations", "(", "self", ",", "gpx_file", ")", ":", "self", ".", "_gpx_file", "=", "gpx_file", "data", "=", "utils", ".", "prepare_xml_read", "(", "gpx_file", ",", "objectify", "=", "True", ")", "try", ":", "self", ".", "metadata", ".", "i...
Import GPX data files. ``import_locations()`` returns a series of lists representing track segments with :class:`Trackpoint` objects as contents. It expects data files in GPX format, as specified in `GPX 1.1 Schema Documentation`_, which is XML such as:: <?xml version="1.0...
[ "Import", "GPX", "data", "files", "." ]
train
https://github.com/JNRowe/upoints/blob/1e4b7a53ed2a06cd854523d54c36aabdccea3830/upoints/gpx.py#L584-L658
JNRowe/upoints
upoints/gpx.py
Trackpoints.export_gpx_file
def export_gpx_file(self): """Generate GPX element tree from ``Trackpoints``. Returns: etree.ElementTree: GPX element tree depicting ``Trackpoints`` objects """ gpx = create_elem('gpx', GPX_ELEM_ATTRIB) if not self.metadata.bounds: self.me...
python
def export_gpx_file(self): """Generate GPX element tree from ``Trackpoints``. Returns: etree.ElementTree: GPX element tree depicting ``Trackpoints`` objects """ gpx = create_elem('gpx', GPX_ELEM_ATTRIB) if not self.metadata.bounds: self.me...
[ "def", "export_gpx_file", "(", "self", ")", ":", "gpx", "=", "create_elem", "(", "'gpx'", ",", "GPX_ELEM_ATTRIB", ")", "if", "not", "self", ".", "metadata", ".", "bounds", ":", "self", ".", "metadata", ".", "bounds", "=", "[", "j", "for", "i", "in", ...
Generate GPX element tree from ``Trackpoints``. Returns: etree.ElementTree: GPX element tree depicting ``Trackpoints`` objects
[ "Generate", "GPX", "element", "tree", "from", "Trackpoints", "." ]
train
https://github.com/JNRowe/upoints/blob/1e4b7a53ed2a06cd854523d54c36aabdccea3830/upoints/gpx.py#L660-L679
JNRowe/upoints
upoints/gpx.py
Routepoints.import_locations
def import_locations(self, gpx_file): """Import GPX data files. ``import_locations()`` returns a series of lists representing track segments with :class:`Routepoint` objects as contents. It expects data files in GPX format, as specified in `GPX 1.1 Schema Documentation`_, which...
python
def import_locations(self, gpx_file): """Import GPX data files. ``import_locations()`` returns a series of lists representing track segments with :class:`Routepoint` objects as contents. It expects data files in GPX format, as specified in `GPX 1.1 Schema Documentation`_, which...
[ "def", "import_locations", "(", "self", ",", "gpx_file", ")", ":", "self", ".", "_gpx_file", "=", "gpx_file", "data", "=", "utils", ".", "prepare_xml_read", "(", "gpx_file", ",", "objectify", "=", "True", ")", "try", ":", "self", ".", "metadata", ".", "i...
Import GPX data files. ``import_locations()`` returns a series of lists representing track segments with :class:`Routepoint` objects as contents. It expects data files in GPX format, as specified in `GPX 1.1 Schema Documentation`_, which is XML such as:: <?xml version="1.0...
[ "Import", "GPX", "data", "files", "." ]
train
https://github.com/JNRowe/upoints/blob/1e4b7a53ed2a06cd854523d54c36aabdccea3830/upoints/gpx.py#L702-L774
JNRowe/upoints
upoints/utils.py
repr_assist
def repr_assist(obj, remap=None): """Helper function to simplify ``__repr__`` methods. Args: obj: Object to pull argument values for remap (dict): Argument pairs to remap before output Returns: str: Self-documenting representation of ``value`` """ if not remap: rema...
python
def repr_assist(obj, remap=None): """Helper function to simplify ``__repr__`` methods. Args: obj: Object to pull argument values for remap (dict): Argument pairs to remap before output Returns: str: Self-documenting representation of ``value`` """ if not remap: rema...
[ "def", "repr_assist", "(", "obj", ",", "remap", "=", "None", ")", ":", "if", "not", "remap", ":", "remap", "=", "{", "}", "data", "=", "[", "]", "for", "arg", "in", "inspect", ".", "getargspec", "(", "getattr", "(", "obj", ".", "__class__", ",", ...
Helper function to simplify ``__repr__`` methods. Args: obj: Object to pull argument values for remap (dict): Argument pairs to remap before output Returns: str: Self-documenting representation of ``value``
[ "Helper", "function", "to", "simplify", "__repr__", "methods", "." ]
train
https://github.com/JNRowe/upoints/blob/1e4b7a53ed2a06cd854523d54c36aabdccea3830/upoints/utils.py#L127-L155
JNRowe/upoints
upoints/utils.py
prepare_read
def prepare_read(data, method='readlines', mode='r'): """Prepare various input types for parsing. Args: data (iter): Data to read method (str): Method to process data with mode (str): Custom mode to process with, if data is a file Returns: list: List suitable for parsing ...
python
def prepare_read(data, method='readlines', mode='r'): """Prepare various input types for parsing. Args: data (iter): Data to read method (str): Method to process data with mode (str): Custom mode to process with, if data is a file Returns: list: List suitable for parsing ...
[ "def", "prepare_read", "(", "data", ",", "method", "=", "'readlines'", ",", "mode", "=", "'r'", ")", ":", "if", "hasattr", "(", "data", ",", "'readlines'", ")", ":", "data", "=", "getattr", "(", "data", ",", "method", ")", "(", ")", "elif", "isinstan...
Prepare various input types for parsing. Args: data (iter): Data to read method (str): Method to process data with mode (str): Custom mode to process with, if data is a file Returns: list: List suitable for parsing Raises: TypeError: Invalid value for data
[ "Prepare", "various", "input", "types", "for", "parsing", "." ]
train
https://github.com/JNRowe/upoints/blob/1e4b7a53ed2a06cd854523d54c36aabdccea3830/upoints/utils.py#L158-L181
JNRowe/upoints
upoints/utils.py
prepare_csv_read
def prepare_csv_read(data, field_names, *args, **kwargs): """Prepare various input types for CSV parsing. Args: data (iter): Data to read field_names (tuple of str): Ordered names to assign to fields Returns: csv.DictReader: CSV reader suitable for parsing Raises: Type...
python
def prepare_csv_read(data, field_names, *args, **kwargs): """Prepare various input types for CSV parsing. Args: data (iter): Data to read field_names (tuple of str): Ordered names to assign to fields Returns: csv.DictReader: CSV reader suitable for parsing Raises: Type...
[ "def", "prepare_csv_read", "(", "data", ",", "field_names", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "hasattr", "(", "data", ",", "'readlines'", ")", "or", "isinstance", "(", "data", ",", "list", ")", ":", "pass", "elif", "isinstance"...
Prepare various input types for CSV parsing. Args: data (iter): Data to read field_names (tuple of str): Ordered names to assign to fields Returns: csv.DictReader: CSV reader suitable for parsing Raises: TypeError: Invalid value for data
[ "Prepare", "various", "input", "types", "for", "CSV", "parsing", "." ]
train
https://github.com/JNRowe/upoints/blob/1e4b7a53ed2a06cd854523d54c36aabdccea3830/upoints/utils.py#L184-L203
JNRowe/upoints
upoints/utils.py
prepare_xml_read
def prepare_xml_read(data, objectify=False): """Prepare various input types for XML parsing. Args: data (iter): Data to read objectify (bool): Parse using lxml's objectify data binding Returns: etree.ElementTree: Tree suitable for parsing Raises: TypeError: Invalid val...
python
def prepare_xml_read(data, objectify=False): """Prepare various input types for XML parsing. Args: data (iter): Data to read objectify (bool): Parse using lxml's objectify data binding Returns: etree.ElementTree: Tree suitable for parsing Raises: TypeError: Invalid val...
[ "def", "prepare_xml_read", "(", "data", ",", "objectify", "=", "False", ")", ":", "mod", "=", "_objectify", "if", "objectify", "else", "etree", "if", "hasattr", "(", "data", ",", "'readlines'", ")", ":", "data", "=", "mod", ".", "parse", "(", "data", "...
Prepare various input types for XML parsing. Args: data (iter): Data to read objectify (bool): Parse using lxml's objectify data binding Returns: etree.ElementTree: Tree suitable for parsing Raises: TypeError: Invalid value for data
[ "Prepare", "various", "input", "types", "for", "XML", "parsing", "." ]
train
https://github.com/JNRowe/upoints/blob/1e4b7a53ed2a06cd854523d54c36aabdccea3830/upoints/utils.py#L206-L228
JNRowe/upoints
upoints/utils.py
element_creator
def element_creator(namespace=None): """Create a simple namespace-aware objectify element creator. Args: namespace (str): Namespace to work in Returns: function: Namespace-aware element creator """ ELEMENT_MAKER = _objectify.ElementMaker(namespace=namespace, ...
python
def element_creator(namespace=None): """Create a simple namespace-aware objectify element creator. Args: namespace (str): Namespace to work in Returns: function: Namespace-aware element creator """ ELEMENT_MAKER = _objectify.ElementMaker(namespace=namespace, ...
[ "def", "element_creator", "(", "namespace", "=", "None", ")", ":", "ELEMENT_MAKER", "=", "_objectify", ".", "ElementMaker", "(", "namespace", "=", "namespace", ",", "annotate", "=", "False", ")", "def", "create_elem", "(", "tag", ",", "attr", "=", "None", ...
Create a simple namespace-aware objectify element creator. Args: namespace (str): Namespace to work in Returns: function: Namespace-aware element creator
[ "Create", "a", "simple", "namespace", "-", "aware", "objectify", "element", "creator", "." ]
train
https://github.com/JNRowe/upoints/blob/1e4b7a53ed2a06cd854523d54c36aabdccea3830/upoints/utils.py#L231-L262
JNRowe/upoints
upoints/utils.py
to_dms
def to_dms(angle, style='dms'): """Convert decimal angle to degrees, minutes and possibly seconds. Args: angle (float): Angle to convert style (str): Return fractional or whole minutes values Returns: tuple of int: Angle converted to degrees, minutes and possibly seconds Raise...
python
def to_dms(angle, style='dms'): """Convert decimal angle to degrees, minutes and possibly seconds. Args: angle (float): Angle to convert style (str): Return fractional or whole minutes values Returns: tuple of int: Angle converted to degrees, minutes and possibly seconds Raise...
[ "def", "to_dms", "(", "angle", ",", "style", "=", "'dms'", ")", ":", "sign", "=", "1", "if", "angle", ">=", "0", "else", "-", "1", "angle", "=", "abs", "(", "angle", ")", "*", "3600", "minutes", ",", "seconds", "=", "divmod", "(", "angle", ",", ...
Convert decimal angle to degrees, minutes and possibly seconds. Args: angle (float): Angle to convert style (str): Return fractional or whole minutes values Returns: tuple of int: Angle converted to degrees, minutes and possibly seconds Raises: ValueError: Unknown value fo...
[ "Convert", "decimal", "angle", "to", "degrees", "minutes", "and", "possibly", "seconds", "." ]
train
https://github.com/JNRowe/upoints/blob/1e4b7a53ed2a06cd854523d54c36aabdccea3830/upoints/utils.py#L268-L292