id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
241,900
asphalt-framework/asphalt-redis
asphalt/redis/component.py
RedisComponent.configure_client
def configure_client( cls, address: Union[str, Tuple[str, int], Path] = 'localhost', port: int = 6379, db: int = 0, password: str = None, ssl: Union[bool, str, SSLContext] = False, **client_args) -> Dict[str, Any]: """ Configure a Redis client. :param address: IP address, host name or path to a UNIX socket :param port: port number to connect to (ignored for UNIX sockets) :param db: database number to connect to :param password: password used if the server requires authentication :param ssl: one of the following: * ``False`` to disable SSL * ``True`` to enable SSL using the default context * an :class:`~ssl.SSLContext` instance * a ``module:varname`` reference to an :class:`~ssl.SSLContext` instance * name of an :class:`~ssl.SSLContext` resource :param client_args: extra keyword arguments passed to :func:`~aioredis.create_redis_pool` """ assert check_argument_types() if isinstance(address, str) and not address.startswith('/'): address = (address, port) elif isinstance(address, Path): address = str(address) client_args.update({ 'address': address, 'db': db, 'password': password, 'ssl': resolve_reference(ssl) }) return client_args
python
def configure_client( cls, address: Union[str, Tuple[str, int], Path] = 'localhost', port: int = 6379, db: int = 0, password: str = None, ssl: Union[bool, str, SSLContext] = False, **client_args) -> Dict[str, Any]: """ Configure a Redis client. :param address: IP address, host name or path to a UNIX socket :param port: port number to connect to (ignored for UNIX sockets) :param db: database number to connect to :param password: password used if the server requires authentication :param ssl: one of the following: * ``False`` to disable SSL * ``True`` to enable SSL using the default context * an :class:`~ssl.SSLContext` instance * a ``module:varname`` reference to an :class:`~ssl.SSLContext` instance * name of an :class:`~ssl.SSLContext` resource :param client_args: extra keyword arguments passed to :func:`~aioredis.create_redis_pool` """ assert check_argument_types() if isinstance(address, str) and not address.startswith('/'): address = (address, port) elif isinstance(address, Path): address = str(address) client_args.update({ 'address': address, 'db': db, 'password': password, 'ssl': resolve_reference(ssl) }) return client_args
[ "def", "configure_client", "(", "cls", ",", "address", ":", "Union", "[", "str", ",", "Tuple", "[", "str", ",", "int", "]", ",", "Path", "]", "=", "'localhost'", ",", "port", ":", "int", "=", "6379", ",", "db", ":", "int", "=", "0", ",", "password", ":", "str", "=", "None", ",", "ssl", ":", "Union", "[", "bool", ",", "str", ",", "SSLContext", "]", "=", "False", ",", "*", "*", "client_args", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "assert", "check_argument_types", "(", ")", "if", "isinstance", "(", "address", ",", "str", ")", "and", "not", "address", ".", "startswith", "(", "'/'", ")", ":", "address", "=", "(", "address", ",", "port", ")", "elif", "isinstance", "(", "address", ",", "Path", ")", ":", "address", "=", "str", "(", "address", ")", "client_args", ".", "update", "(", "{", "'address'", ":", "address", ",", "'db'", ":", "db", ",", "'password'", ":", "password", ",", "'ssl'", ":", "resolve_reference", "(", "ssl", ")", "}", ")", "return", "client_args" ]
Configure a Redis client. :param address: IP address, host name or path to a UNIX socket :param port: port number to connect to (ignored for UNIX sockets) :param db: database number to connect to :param password: password used if the server requires authentication :param ssl: one of the following: * ``False`` to disable SSL * ``True`` to enable SSL using the default context * an :class:`~ssl.SSLContext` instance * a ``module:varname`` reference to an :class:`~ssl.SSLContext` instance * name of an :class:`~ssl.SSLContext` resource :param client_args: extra keyword arguments passed to :func:`~aioredis.create_redis_pool`
[ "Configure", "a", "Redis", "client", "." ]
ac4d01f77d55f225fb3c0e950c38bd4100916331
https://github.com/asphalt-framework/asphalt-redis/blob/ac4d01f77d55f225fb3c0e950c38bd4100916331/asphalt/redis/component.py#L46-L79
241,901
LeonardMH/namealizer
namealizer/namealizer.py
format_word_list_mixedcase
def format_word_list_mixedcase(word_list): """ Given a list of words, this function returns a new list where the words follow mixed case convention. As a reminder this is mixedCase. :param word_list: list, a list of words :return: list, a list of words where the words are mixed case """ to_return, first_word = list(), True for word in word_list: if first_word: to_return.append(word.lower()) first_word = False else: to_return.append(word.capitalize()) return to_return
python
def format_word_list_mixedcase(word_list): """ Given a list of words, this function returns a new list where the words follow mixed case convention. As a reminder this is mixedCase. :param word_list: list, a list of words :return: list, a list of words where the words are mixed case """ to_return, first_word = list(), True for word in word_list: if first_word: to_return.append(word.lower()) first_word = False else: to_return.append(word.capitalize()) return to_return
[ "def", "format_word_list_mixedcase", "(", "word_list", ")", ":", "to_return", ",", "first_word", "=", "list", "(", ")", ",", "True", "for", "word", "in", "word_list", ":", "if", "first_word", ":", "to_return", ".", "append", "(", "word", ".", "lower", "(", ")", ")", "first_word", "=", "False", "else", ":", "to_return", ".", "append", "(", "word", ".", "capitalize", "(", ")", ")", "return", "to_return" ]
Given a list of words, this function returns a new list where the words follow mixed case convention. As a reminder this is mixedCase. :param word_list: list, a list of words :return: list, a list of words where the words are mixed case
[ "Given", "a", "list", "of", "words", "this", "function", "returns", "a", "new", "list", "where", "the", "words", "follow", "mixed", "case", "convention", "." ]
ef09492fb4565b692fda329dc02b8c4364f1cc0a
https://github.com/LeonardMH/namealizer/blob/ef09492fb4565b692fda329dc02b8c4364f1cc0a/namealizer/namealizer.py#L106-L123
241,902
LeonardMH/namealizer
namealizer/namealizer.py
format_string
def format_string(string_to_format, wordstyle="lowercase", separator=" "): """ Takes an un-formatted string and returns it in the desired format Acceptable formats are defined in the function_map dictionary. """ # first split the string up into its constituent words words = string_to_format.split(" ") # format the individual words function_map = { "lowercase": format_word_list_lowercase, "uppercase": format_word_list_uppercase, "capitalize": format_word_list_capitalize, "mixedcase": format_word_list_mixedcase } try: words = function_map[wordstyle](words) except KeyError: msg = "Passed in an invalid wordstyle, allowed styles are {}" raise InvalidWordStyleError(msg.format(function_map.keys())) # now add in the separator and return return str(separator).join(words)
python
def format_string(string_to_format, wordstyle="lowercase", separator=" "): """ Takes an un-formatted string and returns it in the desired format Acceptable formats are defined in the function_map dictionary. """ # first split the string up into its constituent words words = string_to_format.split(" ") # format the individual words function_map = { "lowercase": format_word_list_lowercase, "uppercase": format_word_list_uppercase, "capitalize": format_word_list_capitalize, "mixedcase": format_word_list_mixedcase } try: words = function_map[wordstyle](words) except KeyError: msg = "Passed in an invalid wordstyle, allowed styles are {}" raise InvalidWordStyleError(msg.format(function_map.keys())) # now add in the separator and return return str(separator).join(words)
[ "def", "format_string", "(", "string_to_format", ",", "wordstyle", "=", "\"lowercase\"", ",", "separator", "=", "\" \"", ")", ":", "# first split the string up into its constituent words", "words", "=", "string_to_format", ".", "split", "(", "\" \"", ")", "# format the individual words", "function_map", "=", "{", "\"lowercase\"", ":", "format_word_list_lowercase", ",", "\"uppercase\"", ":", "format_word_list_uppercase", ",", "\"capitalize\"", ":", "format_word_list_capitalize", ",", "\"mixedcase\"", ":", "format_word_list_mixedcase", "}", "try", ":", "words", "=", "function_map", "[", "wordstyle", "]", "(", "words", ")", "except", "KeyError", ":", "msg", "=", "\"Passed in an invalid wordstyle, allowed styles are {}\"", "raise", "InvalidWordStyleError", "(", "msg", ".", "format", "(", "function_map", ".", "keys", "(", ")", ")", ")", "# now add in the separator and return", "return", "str", "(", "separator", ")", ".", "join", "(", "words", ")" ]
Takes an un-formatted string and returns it in the desired format Acceptable formats are defined in the function_map dictionary.
[ "Takes", "an", "un", "-", "formatted", "string", "and", "returns", "it", "in", "the", "desired", "format", "Acceptable", "formats", "are", "defined", "in", "the", "function_map", "dictionary", "." ]
ef09492fb4565b692fda329dc02b8c4364f1cc0a
https://github.com/LeonardMH/namealizer/blob/ef09492fb4565b692fda329dc02b8c4364f1cc0a/namealizer/namealizer.py#L126-L149
241,903
LeonardMH/namealizer
namealizer/namealizer.py
get_random_word
def get_random_word(dictionary, starting_letter=None): """ Takes the dictionary to read from and returns a random word optionally accepts a starting letter """ if starting_letter is None: starting_letter = random.choice(list(dictionary.keys())) try: to_return = random.choice(dictionary[starting_letter]) except KeyError: msg = "Dictionary does not contain a word starting with '{}'" raise NoWordForLetter(msg.format(starting_letter)) return to_return
python
def get_random_word(dictionary, starting_letter=None): """ Takes the dictionary to read from and returns a random word optionally accepts a starting letter """ if starting_letter is None: starting_letter = random.choice(list(dictionary.keys())) try: to_return = random.choice(dictionary[starting_letter]) except KeyError: msg = "Dictionary does not contain a word starting with '{}'" raise NoWordForLetter(msg.format(starting_letter)) return to_return
[ "def", "get_random_word", "(", "dictionary", ",", "starting_letter", "=", "None", ")", ":", "if", "starting_letter", "is", "None", ":", "starting_letter", "=", "random", ".", "choice", "(", "list", "(", "dictionary", ".", "keys", "(", ")", ")", ")", "try", ":", "to_return", "=", "random", ".", "choice", "(", "dictionary", "[", "starting_letter", "]", ")", "except", "KeyError", ":", "msg", "=", "\"Dictionary does not contain a word starting with '{}'\"", "raise", "NoWordForLetter", "(", "msg", ".", "format", "(", "starting_letter", ")", ")", "return", "to_return" ]
Takes the dictionary to read from and returns a random word optionally accepts a starting letter
[ "Takes", "the", "dictionary", "to", "read", "from", "and", "returns", "a", "random", "word", "optionally", "accepts", "a", "starting", "letter" ]
ef09492fb4565b692fda329dc02b8c4364f1cc0a
https://github.com/LeonardMH/namealizer/blob/ef09492fb4565b692fda329dc02b8c4364f1cc0a/namealizer/namealizer.py#L152-L166
241,904
LeonardMH/namealizer
namealizer/namealizer.py
import_dictionary
def import_dictionary(dictionary): """ Function used to import the dictionary file into memory opened_file should be an already opened dictionary file :raises DictionaryNotFoundError if dictionary can't be loaded """ def load_into_dictionary(dictionary_file): """create the dictionary to hold the words""" to_return = dict() for line in dictionary_file: try: to_return[line[0].lower()].append(line.strip().lower()) except KeyError: to_return[line[0].lower()] = [line.strip().lower()] return to_return try: with open(dictionary) as dictionary_file: to_return = load_into_dictionary(dictionary_file) except TypeError: to_return = load_into_dictionary(dictionary) except IOError: message = "Could not find the dictionary at {}".format(dictionary) raise DictionaryNotFoundError(message) return to_return
python
def import_dictionary(dictionary): """ Function used to import the dictionary file into memory opened_file should be an already opened dictionary file :raises DictionaryNotFoundError if dictionary can't be loaded """ def load_into_dictionary(dictionary_file): """create the dictionary to hold the words""" to_return = dict() for line in dictionary_file: try: to_return[line[0].lower()].append(line.strip().lower()) except KeyError: to_return[line[0].lower()] = [line.strip().lower()] return to_return try: with open(dictionary) as dictionary_file: to_return = load_into_dictionary(dictionary_file) except TypeError: to_return = load_into_dictionary(dictionary) except IOError: message = "Could not find the dictionary at {}".format(dictionary) raise DictionaryNotFoundError(message) return to_return
[ "def", "import_dictionary", "(", "dictionary", ")", ":", "def", "load_into_dictionary", "(", "dictionary_file", ")", ":", "\"\"\"create the dictionary to hold the words\"\"\"", "to_return", "=", "dict", "(", ")", "for", "line", "in", "dictionary_file", ":", "try", ":", "to_return", "[", "line", "[", "0", "]", ".", "lower", "(", ")", "]", ".", "append", "(", "line", ".", "strip", "(", ")", ".", "lower", "(", ")", ")", "except", "KeyError", ":", "to_return", "[", "line", "[", "0", "]", ".", "lower", "(", ")", "]", "=", "[", "line", ".", "strip", "(", ")", ".", "lower", "(", ")", "]", "return", "to_return", "try", ":", "with", "open", "(", "dictionary", ")", "as", "dictionary_file", ":", "to_return", "=", "load_into_dictionary", "(", "dictionary_file", ")", "except", "TypeError", ":", "to_return", "=", "load_into_dictionary", "(", "dictionary", ")", "except", "IOError", ":", "message", "=", "\"Could not find the dictionary at {}\"", ".", "format", "(", "dictionary", ")", "raise", "DictionaryNotFoundError", "(", "message", ")", "return", "to_return" ]
Function used to import the dictionary file into memory opened_file should be an already opened dictionary file :raises DictionaryNotFoundError if dictionary can't be loaded
[ "Function", "used", "to", "import", "the", "dictionary", "file", "into", "memory", "opened_file", "should", "be", "an", "already", "opened", "dictionary", "file" ]
ef09492fb4565b692fda329dc02b8c4364f1cc0a
https://github.com/LeonardMH/namealizer/blob/ef09492fb4565b692fda329dc02b8c4364f1cc0a/namealizer/namealizer.py#L169-L198
241,905
LeonardMH/namealizer
namealizer/namealizer.py
string_for_count
def string_for_count(dictionary, count): """Create a random string of N=`count` words""" string_to_print = "" if count is not None: if count == 0: return "" ranger = count else: ranger = 2 for index in range(ranger): string_to_print += "{} ".format(get_random_word(dictionary)) return string_to_print.strip()
python
def string_for_count(dictionary, count): """Create a random string of N=`count` words""" string_to_print = "" if count is not None: if count == 0: return "" ranger = count else: ranger = 2 for index in range(ranger): string_to_print += "{} ".format(get_random_word(dictionary)) return string_to_print.strip()
[ "def", "string_for_count", "(", "dictionary", ",", "count", ")", ":", "string_to_print", "=", "\"\"", "if", "count", "is", "not", "None", ":", "if", "count", "==", "0", ":", "return", "\"\"", "ranger", "=", "count", "else", ":", "ranger", "=", "2", "for", "index", "in", "range", "(", "ranger", ")", ":", "string_to_print", "+=", "\"{} \"", ".", "format", "(", "get_random_word", "(", "dictionary", ")", ")", "return", "string_to_print", ".", "strip", "(", ")" ]
Create a random string of N=`count` words
[ "Create", "a", "random", "string", "of", "N", "=", "count", "words" ]
ef09492fb4565b692fda329dc02b8c4364f1cc0a
https://github.com/LeonardMH/namealizer/blob/ef09492fb4565b692fda329dc02b8c4364f1cc0a/namealizer/namealizer.py#L211-L223
241,906
LeonardMH/namealizer
namealizer/namealizer.py
generate_seed
def generate_seed(seed): """Generate seed for random number generator""" if seed is None: random.seed() seed = random.randint(0, sys.maxsize) random.seed(a=seed) return seed
python
def generate_seed(seed): """Generate seed for random number generator""" if seed is None: random.seed() seed = random.randint(0, sys.maxsize) random.seed(a=seed) return seed
[ "def", "generate_seed", "(", "seed", ")", ":", "if", "seed", "is", "None", ":", "random", ".", "seed", "(", ")", "seed", "=", "random", ".", "randint", "(", "0", ",", "sys", ".", "maxsize", ")", "random", ".", "seed", "(", "a", "=", "seed", ")", "return", "seed" ]
Generate seed for random number generator
[ "Generate", "seed", "for", "random", "number", "generator" ]
ef09492fb4565b692fda329dc02b8c4364f1cc0a
https://github.com/LeonardMH/namealizer/blob/ef09492fb4565b692fda329dc02b8c4364f1cc0a/namealizer/namealizer.py#L226-L233
241,907
LeonardMH/namealizer
namealizer/namealizer.py
main
def main(dictionary='dictionaries/all_en_US.dict', count=None, initials=None, seed=None, wordstyle='lowercase', separator=' '): """Main processing function for namealizer""" generate_seed(seed) # attempt to read in the given dictionary dictionary = import_dictionary(dictionary) # if count and initials are both set, let the user know what's up if count and initials: msg = "--count and --initials are mutually exclusive, using initials" logging.info(msg) if initials is not None: string_to_print = string_for_initials(dictionary, initials) else: string_to_print = string_for_count(dictionary, count) return format_string(string_to_print, wordstyle, separator)
python
def main(dictionary='dictionaries/all_en_US.dict', count=None, initials=None, seed=None, wordstyle='lowercase', separator=' '): """Main processing function for namealizer""" generate_seed(seed) # attempt to read in the given dictionary dictionary = import_dictionary(dictionary) # if count and initials are both set, let the user know what's up if count and initials: msg = "--count and --initials are mutually exclusive, using initials" logging.info(msg) if initials is not None: string_to_print = string_for_initials(dictionary, initials) else: string_to_print = string_for_count(dictionary, count) return format_string(string_to_print, wordstyle, separator)
[ "def", "main", "(", "dictionary", "=", "'dictionaries/all_en_US.dict'", ",", "count", "=", "None", ",", "initials", "=", "None", ",", "seed", "=", "None", ",", "wordstyle", "=", "'lowercase'", ",", "separator", "=", "' '", ")", ":", "generate_seed", "(", "seed", ")", "# attempt to read in the given dictionary", "dictionary", "=", "import_dictionary", "(", "dictionary", ")", "# if count and initials are both set, let the user know what's up", "if", "count", "and", "initials", ":", "msg", "=", "\"--count and --initials are mutually exclusive, using initials\"", "logging", ".", "info", "(", "msg", ")", "if", "initials", "is", "not", "None", ":", "string_to_print", "=", "string_for_initials", "(", "dictionary", ",", "initials", ")", "else", ":", "string_to_print", "=", "string_for_count", "(", "dictionary", ",", "count", ")", "return", "format_string", "(", "string_to_print", ",", "wordstyle", ",", "separator", ")" ]
Main processing function for namealizer
[ "Main", "processing", "function", "for", "namealizer" ]
ef09492fb4565b692fda329dc02b8c4364f1cc0a
https://github.com/LeonardMH/namealizer/blob/ef09492fb4565b692fda329dc02b8c4364f1cc0a/namealizer/namealizer.py#L236-L254
241,908
LeonardMH/namealizer
namealizer/namealizer.py
create_parser
def create_parser(): """Creates the Namespace object to be used by the rest of the tool""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-d', '--dictionary', nargs='?', default='dictionaries/all_en_US.dict', help='Specify a non-default word dictionary to use.') parser.add_argument('-c', '--count', help='Specify the number of words to return.', type=int) parser.add_argument('-i', '--initials', type=str, help='String of letters used to form the word list') parser.add_argument('-s', '--seed', help='Specify the seed to use for the random number ' 'generator. Using the same seed without changing ' 'other settings will give repeatable results.', type=int) parser.add_argument('-ws', '--wordstyle', nargs='?', default='lowercase', type=str, help='Specify how to style the individual words. ' 'Default is lowercase.') parser.add_argument('-sep', '--separator', nargs='?', default=' ', type=str, help='How to separate words. Default is space.') return parser.parse_args()
python
def create_parser(): """Creates the Namespace object to be used by the rest of the tool""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-d', '--dictionary', nargs='?', default='dictionaries/all_en_US.dict', help='Specify a non-default word dictionary to use.') parser.add_argument('-c', '--count', help='Specify the number of words to return.', type=int) parser.add_argument('-i', '--initials', type=str, help='String of letters used to form the word list') parser.add_argument('-s', '--seed', help='Specify the seed to use for the random number ' 'generator. Using the same seed without changing ' 'other settings will give repeatable results.', type=int) parser.add_argument('-ws', '--wordstyle', nargs='?', default='lowercase', type=str, help='Specify how to style the individual words. ' 'Default is lowercase.') parser.add_argument('-sep', '--separator', nargs='?', default=' ', type=str, help='How to separate words. Default is space.') return parser.parse_args()
[ "def", "create_parser", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "__doc__", ")", "parser", ".", "add_argument", "(", "'-d'", ",", "'--dictionary'", ",", "nargs", "=", "'?'", ",", "default", "=", "'dictionaries/all_en_US.dict'", ",", "help", "=", "'Specify a non-default word dictionary to use.'", ")", "parser", ".", "add_argument", "(", "'-c'", ",", "'--count'", ",", "help", "=", "'Specify the number of words to return.'", ",", "type", "=", "int", ")", "parser", ".", "add_argument", "(", "'-i'", ",", "'--initials'", ",", "type", "=", "str", ",", "help", "=", "'String of letters used to form the word list'", ")", "parser", ".", "add_argument", "(", "'-s'", ",", "'--seed'", ",", "help", "=", "'Specify the seed to use for the random number '", "'generator. Using the same seed without changing '", "'other settings will give repeatable results.'", ",", "type", "=", "int", ")", "parser", ".", "add_argument", "(", "'-ws'", ",", "'--wordstyle'", ",", "nargs", "=", "'?'", ",", "default", "=", "'lowercase'", ",", "type", "=", "str", ",", "help", "=", "'Specify how to style the individual words. '", "'Default is lowercase.'", ")", "parser", ".", "add_argument", "(", "'-sep'", ",", "'--separator'", ",", "nargs", "=", "'?'", ",", "default", "=", "' '", ",", "type", "=", "str", ",", "help", "=", "'How to separate words. Default is space.'", ")", "return", "parser", ".", "parse_args", "(", ")" ]
Creates the Namespace object to be used by the rest of the tool
[ "Creates", "the", "Namespace", "object", "to", "be", "used", "by", "the", "rest", "of", "the", "tool" ]
ef09492fb4565b692fda329dc02b8c4364f1cc0a
https://github.com/LeonardMH/namealizer/blob/ef09492fb4565b692fda329dc02b8c4364f1cc0a/namealizer/namealizer.py#L257-L288
241,909
Akay7/nosql2django
nosql2django/parser_mapper.py
ParserMapper.save_to_db
def save_to_db(model_text_id, parsed_values): """save to db and return saved object""" Model = apps.get_model(model_text_id) # normalise values and separate to m2m, simple simple_fields = {} many2many_fields = {} for field, value in parsed_values.items(): if (Model._meta.get_field( field).get_internal_type() == 'ManyToManyField'): many2many_fields[field] = value elif (Model._meta.get_field( field).get_internal_type() == 'DateTimeField'): simple_fields[field] = time_parser.parse(value) else: simple_fields[field] = value # ToDo: add unique identify parameter to field # ToDo: allow unique identify m2m field model, created = Model.objects.get_or_create(**simple_fields) for field, value in many2many_fields.items(): setattr(model, field, value) model.save() return model
python
def save_to_db(model_text_id, parsed_values): """save to db and return saved object""" Model = apps.get_model(model_text_id) # normalise values and separate to m2m, simple simple_fields = {} many2many_fields = {} for field, value in parsed_values.items(): if (Model._meta.get_field( field).get_internal_type() == 'ManyToManyField'): many2many_fields[field] = value elif (Model._meta.get_field( field).get_internal_type() == 'DateTimeField'): simple_fields[field] = time_parser.parse(value) else: simple_fields[field] = value # ToDo: add unique identify parameter to field # ToDo: allow unique identify m2m field model, created = Model.objects.get_or_create(**simple_fields) for field, value in many2many_fields.items(): setattr(model, field, value) model.save() return model
[ "def", "save_to_db", "(", "model_text_id", ",", "parsed_values", ")", ":", "Model", "=", "apps", ".", "get_model", "(", "model_text_id", ")", "# normalise values and separate to m2m, simple", "simple_fields", "=", "{", "}", "many2many_fields", "=", "{", "}", "for", "field", ",", "value", "in", "parsed_values", ".", "items", "(", ")", ":", "if", "(", "Model", ".", "_meta", ".", "get_field", "(", "field", ")", ".", "get_internal_type", "(", ")", "==", "'ManyToManyField'", ")", ":", "many2many_fields", "[", "field", "]", "=", "value", "elif", "(", "Model", ".", "_meta", ".", "get_field", "(", "field", ")", ".", "get_internal_type", "(", ")", "==", "'DateTimeField'", ")", ":", "simple_fields", "[", "field", "]", "=", "time_parser", ".", "parse", "(", "value", ")", "else", ":", "simple_fields", "[", "field", "]", "=", "value", "# ToDo: add unique identify parameter to field", "# ToDo: allow unique identify m2m field", "model", ",", "created", "=", "Model", ".", "objects", ".", "get_or_create", "(", "*", "*", "simple_fields", ")", "for", "field", ",", "value", "in", "many2many_fields", ".", "items", "(", ")", ":", "setattr", "(", "model", ",", "field", ",", "value", ")", "model", ".", "save", "(", ")", "return", "model" ]
save to db and return saved object
[ "save", "to", "db", "and", "return", "saved", "object" ]
f33af832d4d0d652bd730471d1ce6a717700d1e7
https://github.com/Akay7/nosql2django/blob/f33af832d4d0d652bd730471d1ce6a717700d1e7/nosql2django/parser_mapper.py#L27-L53
241,910
TkTech/pytextql
pytextql/util.py
grouper
def grouper(iterable, n): """ Slice up `iterable` into iterables of `n` items. :param iterable: Iterable to splice. :param n: Number of items per slice. :returns: iterable of iterables """ it = iter(iterable) while True: chunk = itertools.islice(it, n) try: first = next(chunk) except StopIteration: return yield itertools.chain([first], chunk)
python
def grouper(iterable, n): """ Slice up `iterable` into iterables of `n` items. :param iterable: Iterable to splice. :param n: Number of items per slice. :returns: iterable of iterables """ it = iter(iterable) while True: chunk = itertools.islice(it, n) try: first = next(chunk) except StopIteration: return yield itertools.chain([first], chunk)
[ "def", "grouper", "(", "iterable", ",", "n", ")", ":", "it", "=", "iter", "(", "iterable", ")", "while", "True", ":", "chunk", "=", "itertools", ".", "islice", "(", "it", ",", "n", ")", "try", ":", "first", "=", "next", "(", "chunk", ")", "except", "StopIteration", ":", "return", "yield", "itertools", ".", "chain", "(", "[", "first", "]", ",", "chunk", ")" ]
Slice up `iterable` into iterables of `n` items. :param iterable: Iterable to splice. :param n: Number of items per slice. :returns: iterable of iterables
[ "Slice", "up", "iterable", "into", "iterables", "of", "n", "items", "." ]
e054a7a4df7262deaca49bdbf748c00acf011b51
https://github.com/TkTech/pytextql/blob/e054a7a4df7262deaca49bdbf748c00acf011b51/pytextql/util.py#L6-L22
241,911
GMadorell/abris
abris_transform/transformations/transformer.py
Transformer.prepare
def prepare(self, dataframe): """ Takes the already cleaned dataframe, splits it into train and test and returns the train and test as numpy arrays. If the problem is supervised, the target column will be that last one of the returned arrays. """ mapping = DataFrameMapCreator().get_mapping_from_config(self.__config) self.__mapper = DataFrameMapper(mapping) train, test = split_dataframe_train_test(dataframe, self.__config.get_option_parameter("split", "train_percentage")) return self.__get_correct_return_parameters(train, test)
python
def prepare(self, dataframe): """ Takes the already cleaned dataframe, splits it into train and test and returns the train and test as numpy arrays. If the problem is supervised, the target column will be that last one of the returned arrays. """ mapping = DataFrameMapCreator().get_mapping_from_config(self.__config) self.__mapper = DataFrameMapper(mapping) train, test = split_dataframe_train_test(dataframe, self.__config.get_option_parameter("split", "train_percentage")) return self.__get_correct_return_parameters(train, test)
[ "def", "prepare", "(", "self", ",", "dataframe", ")", ":", "mapping", "=", "DataFrameMapCreator", "(", ")", ".", "get_mapping_from_config", "(", "self", ".", "__config", ")", "self", ".", "__mapper", "=", "DataFrameMapper", "(", "mapping", ")", "train", ",", "test", "=", "split_dataframe_train_test", "(", "dataframe", ",", "self", ".", "__config", ".", "get_option_parameter", "(", "\"split\"", ",", "\"train_percentage\"", ")", ")", "return", "self", ".", "__get_correct_return_parameters", "(", "train", ",", "test", ")" ]
Takes the already cleaned dataframe, splits it into train and test and returns the train and test as numpy arrays. If the problem is supervised, the target column will be that last one of the returned arrays.
[ "Takes", "the", "already", "cleaned", "dataframe", "splits", "it", "into", "train", "and", "test", "and", "returns", "the", "train", "and", "test", "as", "numpy", "arrays", ".", "If", "the", "problem", "is", "supervised", "the", "target", "column", "will", "be", "that", "last", "one", "of", "the", "returned", "arrays", "." ]
0d8ab7ec506835a45fae6935d129f5d7e6937bb2
https://github.com/GMadorell/abris/blob/0d8ab7ec506835a45fae6935d129f5d7e6937bb2/abris_transform/transformations/transformer.py#L24-L34
241,912
GMadorell/abris
abris_transform/transformations/transformer.py
Transformer.__add_target_data
def __add_target_data(self, transformed_data, original_data): """ Picks up the target data from the original_data and appends it as a column to the transformed_data. Both arguments are expected to be np.array's. """ model = self.__config.get_data_model() target_feature = model.find_target_feature() name = target_feature.get_name() if target_feature.is_categorical(): target_row = original_data[name] target = self.__label_encoder_adapter.transform(target_row) else: target = original_data[name].values.astype(type_name_to_data_type("float")) target = target[..., None] return np.hstack((transformed_data, target))
python
def __add_target_data(self, transformed_data, original_data): """ Picks up the target data from the original_data and appends it as a column to the transformed_data. Both arguments are expected to be np.array's. """ model = self.__config.get_data_model() target_feature = model.find_target_feature() name = target_feature.get_name() if target_feature.is_categorical(): target_row = original_data[name] target = self.__label_encoder_adapter.transform(target_row) else: target = original_data[name].values.astype(type_name_to_data_type("float")) target = target[..., None] return np.hstack((transformed_data, target))
[ "def", "__add_target_data", "(", "self", ",", "transformed_data", ",", "original_data", ")", ":", "model", "=", "self", ".", "__config", ".", "get_data_model", "(", ")", "target_feature", "=", "model", ".", "find_target_feature", "(", ")", "name", "=", "target_feature", ".", "get_name", "(", ")", "if", "target_feature", ".", "is_categorical", "(", ")", ":", "target_row", "=", "original_data", "[", "name", "]", "target", "=", "self", ".", "__label_encoder_adapter", ".", "transform", "(", "target_row", ")", "else", ":", "target", "=", "original_data", "[", "name", "]", ".", "values", ".", "astype", "(", "type_name_to_data_type", "(", "\"float\"", ")", ")", "target", "=", "target", "[", "...", ",", "None", "]", "return", "np", ".", "hstack", "(", "(", "transformed_data", ",", "target", ")", ")" ]
Picks up the target data from the original_data and appends it as a column to the transformed_data. Both arguments are expected to be np.array's.
[ "Picks", "up", "the", "target", "data", "from", "the", "original_data", "and", "appends", "it", "as", "a", "column", "to", "the", "transformed_data", ".", "Both", "arguments", "are", "expected", "to", "be", "np", ".", "array", "s", "." ]
0d8ab7ec506835a45fae6935d129f5d7e6937bb2
https://github.com/GMadorell/abris/blob/0d8ab7ec506835a45fae6935d129f5d7e6937bb2/abris_transform/transformations/transformer.py#L48-L66
241,913
psychopenguin/limesurvey
limesurvey/limesurvey.py
set_params
def set_params(method, params): """Set params to query limesurvey""" data = {'method': method, 'params': params, 'id': str(uuid4())} return json.dumps(data)
python
def set_params(method, params): """Set params to query limesurvey""" data = {'method': method, 'params': params, 'id': str(uuid4())} return json.dumps(data)
[ "def", "set_params", "(", "method", ",", "params", ")", ":", "data", "=", "{", "'method'", ":", "method", ",", "'params'", ":", "params", ",", "'id'", ":", "str", "(", "uuid4", "(", ")", ")", "}", "return", "json", ".", "dumps", "(", "data", ")" ]
Set params to query limesurvey
[ "Set", "params", "to", "query", "limesurvey" ]
7df459a603315198f286b160638c1a330e66fa94
https://github.com/psychopenguin/limesurvey/blob/7df459a603315198f286b160638c1a330e66fa94/limesurvey/limesurvey.py#L11-L14
241,914
psychopenguin/limesurvey
limesurvey/limesurvey.py
list_surveys
def list_surveys(session): """retrieve a list of surveys from current user""" params = {'sUser': session['user'], 'sSessionKey': session['token']} data = set_params('list_surveys', params) req = requests.post(session['url'], data=data, headers=headers) return req.text
python
def list_surveys(session): """retrieve a list of surveys from current user""" params = {'sUser': session['user'], 'sSessionKey': session['token']} data = set_params('list_surveys', params) req = requests.post(session['url'], data=data, headers=headers) return req.text
[ "def", "list_surveys", "(", "session", ")", ":", "params", "=", "{", "'sUser'", ":", "session", "[", "'user'", "]", ",", "'sSessionKey'", ":", "session", "[", "'token'", "]", "}", "data", "=", "set_params", "(", "'list_surveys'", ",", "params", ")", "req", "=", "requests", ".", "post", "(", "session", "[", "'url'", "]", ",", "data", "=", "data", ",", "headers", "=", "headers", ")", "return", "req", ".", "text" ]
retrieve a list of surveys from current user
[ "retrieve", "a", "list", "of", "surveys", "from", "current", "user" ]
7df459a603315198f286b160638c1a330e66fa94
https://github.com/psychopenguin/limesurvey/blob/7df459a603315198f286b160638c1a330e66fa94/limesurvey/limesurvey.py#L31-L36
241,915
Huong-nt/flask-rak
flask_rak/models.py
audio.stop
def stop(self): """Send signal to stop the current stream playback""" self._response['shouldEndSession'] = True self._response['action']['audio']['interface'] = 'stop' self._response['action']['audio']['sources'] = [] return self
python
def stop(self): """Send signal to stop the current stream playback""" self._response['shouldEndSession'] = True self._response['action']['audio']['interface'] = 'stop' self._response['action']['audio']['sources'] = [] return self
[ "def", "stop", "(", "self", ")", ":", "self", ".", "_response", "[", "'shouldEndSession'", "]", "=", "True", "self", ".", "_response", "[", "'action'", "]", "[", "'audio'", "]", "[", "'interface'", "]", "=", "'stop'", "self", ".", "_response", "[", "'action'", "]", "[", "'audio'", "]", "[", "'sources'", "]", "=", "[", "]", "return", "self" ]
Send signal to stop the current stream playback
[ "Send", "signal", "to", "stop", "the", "current", "stream", "playback" ]
ffe16b0fc3d49e83c1d220c445ce14632219f69d
https://github.com/Huong-nt/flask-rak/blob/ffe16b0fc3d49e83c1d220c445ce14632219f69d/flask_rak/models.py#L163-L168
241,916
onespacemedia/cms-redirects
redirects/models.py
Redirect.sub_path
def sub_path(self, path): """ If this redirect is a regular expression, it will return a rewritten version of `path`; otherwise returns the `new_path`. """ if not self.regular_expression: return self.new_path return re.sub(self.old_path, self.new_path, path)
python
def sub_path(self, path): """ If this redirect is a regular expression, it will return a rewritten version of `path`; otherwise returns the `new_path`. """ if not self.regular_expression: return self.new_path return re.sub(self.old_path, self.new_path, path)
[ "def", "sub_path", "(", "self", ",", "path", ")", ":", "if", "not", "self", ".", "regular_expression", ":", "return", "self", ".", "new_path", "return", "re", ".", "sub", "(", "self", ".", "old_path", ",", "self", ".", "new_path", ",", "path", ")" ]
If this redirect is a regular expression, it will return a rewritten version of `path`; otherwise returns the `new_path`.
[ "If", "this", "redirect", "is", "a", "regular", "expression", "it", "will", "return", "a", "rewritten", "version", "of", "path", ";", "otherwise", "returns", "the", "new_path", "." ]
9a412dbd4fdac016fbe0ac7bf6773868169cb148
https://github.com/onespacemedia/cms-redirects/blob/9a412dbd4fdac016fbe0ac7bf6773868169cb148/redirects/models.py#L52-L57
241,917
konture/CloeePy
cloeepy/logger.py
Logger._set_formatter
def _set_formatter(self): """ Inspects config and sets the name of the formatter to either "json" or "text" as instance attr. If not present in config, default is "text" """ if hasattr(self._config, "formatter") and self._config.formatter == "json": self._formatter = "json" else: self._formatter = "text"
python
def _set_formatter(self): """ Inspects config and sets the name of the formatter to either "json" or "text" as instance attr. If not present in config, default is "text" """ if hasattr(self._config, "formatter") and self._config.formatter == "json": self._formatter = "json" else: self._formatter = "text"
[ "def", "_set_formatter", "(", "self", ")", ":", "if", "hasattr", "(", "self", ".", "_config", ",", "\"formatter\"", ")", "and", "self", ".", "_config", ".", "formatter", "==", "\"json\"", ":", "self", ".", "_formatter", "=", "\"json\"", "else", ":", "self", ".", "_formatter", "=", "\"text\"" ]
Inspects config and sets the name of the formatter to either "json" or "text" as instance attr. If not present in config, default is "text"
[ "Inspects", "config", "and", "sets", "the", "name", "of", "the", "formatter", "to", "either", "json", "or", "text", "as", "instance", "attr", ".", "If", "not", "present", "in", "config", "default", "is", "text" ]
dcb21284d2df405d92ac6868ea7215792c9323b9
https://github.com/konture/CloeePy/blob/dcb21284d2df405d92ac6868ea7215792c9323b9/cloeepy/logger.py#L49-L57
241,918
konture/CloeePy
cloeepy/logger.py
Logger._set_log_level
def _set_log_level(self): """ Inspects config and sets the log level as instance attr. If not present in config, default is "INFO". """ # set log level on logger log_level = "INFO" if hasattr(self._config, "level") and self._config.level.upper() in ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]: log_level = self._config.level.upper() self._log_level = log_level
python
def _set_log_level(self): """ Inspects config and sets the log level as instance attr. If not present in config, default is "INFO". """ # set log level on logger log_level = "INFO" if hasattr(self._config, "level") and self._config.level.upper() in ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]: log_level = self._config.level.upper() self._log_level = log_level
[ "def", "_set_log_level", "(", "self", ")", ":", "# set log level on logger", "log_level", "=", "\"INFO\"", "if", "hasattr", "(", "self", ".", "_config", ",", "\"level\"", ")", "and", "self", ".", "_config", ".", "level", ".", "upper", "(", ")", "in", "[", "\"DEBUG\"", ",", "\"INFO\"", ",", "\"WARNING\"", ",", "\"ERROR\"", ",", "\"CRITICAL\"", "]", ":", "log_level", "=", "self", ".", "_config", ".", "level", ".", "upper", "(", ")", "self", ".", "_log_level", "=", "log_level" ]
Inspects config and sets the log level as instance attr. If not present in config, default is "INFO".
[ "Inspects", "config", "and", "sets", "the", "log", "level", "as", "instance", "attr", ".", "If", "not", "present", "in", "config", "default", "is", "INFO", "." ]
dcb21284d2df405d92ac6868ea7215792c9323b9
https://github.com/konture/CloeePy/blob/dcb21284d2df405d92ac6868ea7215792c9323b9/cloeepy/logger.py#L59-L68
241,919
konture/CloeePy
cloeepy/logger.py
Logger._set_framework_logger
def _set_framework_logger(self): """ Creates a logger with default formatting for internal use by the CloeePy framework and its plugins. User may configure customer fields on their logger, but the framework would not know how to incorporate those custom fields, and by design of the logging pkg authors, the program would error out. """ formatter = None if self._formatter == "json": formatter = CustomJsonFormatter(self.default_json_fmt) else: formatter = logging.Formatter(self.default_text_fmt) self._logger = logging.getLogger("CloeePyFramework") logHandler = logging.StreamHandler() logHandler.setFormatter(formatter) self._logger.addHandler(logHandler) self._logger.setLevel(self._log_level)
python
def _set_framework_logger(self): """ Creates a logger with default formatting for internal use by the CloeePy framework and its plugins. User may configure customer fields on their logger, but the framework would not know how to incorporate those custom fields, and by design of the logging pkg authors, the program would error out. """ formatter = None if self._formatter == "json": formatter = CustomJsonFormatter(self.default_json_fmt) else: formatter = logging.Formatter(self.default_text_fmt) self._logger = logging.getLogger("CloeePyFramework") logHandler = logging.StreamHandler() logHandler.setFormatter(formatter) self._logger.addHandler(logHandler) self._logger.setLevel(self._log_level)
[ "def", "_set_framework_logger", "(", "self", ")", ":", "formatter", "=", "None", "if", "self", ".", "_formatter", "==", "\"json\"", ":", "formatter", "=", "CustomJsonFormatter", "(", "self", ".", "default_json_fmt", ")", "else", ":", "formatter", "=", "logging", ".", "Formatter", "(", "self", ".", "default_text_fmt", ")", "self", ".", "_logger", "=", "logging", ".", "getLogger", "(", "\"CloeePyFramework\"", ")", "logHandler", "=", "logging", ".", "StreamHandler", "(", ")", "logHandler", ".", "setFormatter", "(", "formatter", ")", "self", ".", "_logger", ".", "addHandler", "(", "logHandler", ")", "self", ".", "_logger", ".", "setLevel", "(", "self", ".", "_log_level", ")" ]
Creates a logger with default formatting for internal use by the CloeePy framework and its plugins. User may configure customer fields on their logger, but the framework would not know how to incorporate those custom fields, and by design of the logging pkg authors, the program would error out.
[ "Creates", "a", "logger", "with", "default", "formatting", "for", "internal", "use", "by", "the", "CloeePy", "framework", "and", "its", "plugins", ".", "User", "may", "configure", "customer", "fields", "on", "their", "logger", "but", "the", "framework", "would", "not", "know", "how", "to", "incorporate", "those", "custom", "fields", "and", "by", "design", "of", "the", "logging", "pkg", "authors", "the", "program", "would", "error", "out", "." ]
dcb21284d2df405d92ac6868ea7215792c9323b9
https://github.com/konture/CloeePy/blob/dcb21284d2df405d92ac6868ea7215792c9323b9/cloeepy/logger.py#L70-L88
241,920
konture/CloeePy
cloeepy/logger.py
Logger._set_application_logger
def _set_application_logger(self): """ Creates a logger intended for use by applications using CloeePy. This logger is fully configurable by the user and can include custom fields """ formatter = None if self._formatter == "json": if hasattr(self._config, "formatString"): formatter = CustomJsonFormatter(self._config.formatString) else: formatter = CustomJsonFormatter(self.default_json_fmt) else: if hasattr(self._config, "formatString"): formatter = logging.Formatter(self._config.formatString) else: formatter = logging.Formatter(self.default_txt_fmt) # get logging.Logger instance and set formatter self.logger = logging.getLogger('CloeePyApplication') logHandler = logging.StreamHandler() logHandler.setFormatter(formatter) self.logger.addHandler(logHandler) self.logger.setLevel(self._log_level)
python
def _set_application_logger(self): """ Creates a logger intended for use by applications using CloeePy. This logger is fully configurable by the user and can include custom fields """ formatter = None if self._formatter == "json": if hasattr(self._config, "formatString"): formatter = CustomJsonFormatter(self._config.formatString) else: formatter = CustomJsonFormatter(self.default_json_fmt) else: if hasattr(self._config, "formatString"): formatter = logging.Formatter(self._config.formatString) else: formatter = logging.Formatter(self.default_txt_fmt) # get logging.Logger instance and set formatter self.logger = logging.getLogger('CloeePyApplication') logHandler = logging.StreamHandler() logHandler.setFormatter(formatter) self.logger.addHandler(logHandler) self.logger.setLevel(self._log_level)
[ "def", "_set_application_logger", "(", "self", ")", ":", "formatter", "=", "None", "if", "self", ".", "_formatter", "==", "\"json\"", ":", "if", "hasattr", "(", "self", ".", "_config", ",", "\"formatString\"", ")", ":", "formatter", "=", "CustomJsonFormatter", "(", "self", ".", "_config", ".", "formatString", ")", "else", ":", "formatter", "=", "CustomJsonFormatter", "(", "self", ".", "default_json_fmt", ")", "else", ":", "if", "hasattr", "(", "self", ".", "_config", ",", "\"formatString\"", ")", ":", "formatter", "=", "logging", ".", "Formatter", "(", "self", ".", "_config", ".", "formatString", ")", "else", ":", "formatter", "=", "logging", ".", "Formatter", "(", "self", ".", "default_txt_fmt", ")", "# get logging.Logger instance and set formatter", "self", ".", "logger", "=", "logging", ".", "getLogger", "(", "'CloeePyApplication'", ")", "logHandler", "=", "logging", ".", "StreamHandler", "(", ")", "logHandler", ".", "setFormatter", "(", "formatter", ")", "self", ".", "logger", ".", "addHandler", "(", "logHandler", ")", "self", ".", "logger", ".", "setLevel", "(", "self", ".", "_log_level", ")" ]
Creates a logger intended for use by applications using CloeePy. This logger is fully configurable by the user and can include custom fields
[ "Creates", "a", "logger", "intended", "for", "use", "by", "applications", "using", "CloeePy", ".", "This", "logger", "is", "fully", "configurable", "by", "the", "user", "and", "can", "include", "custom", "fields" ]
dcb21284d2df405d92ac6868ea7215792c9323b9
https://github.com/konture/CloeePy/blob/dcb21284d2df405d92ac6868ea7215792c9323b9/cloeepy/logger.py#L90-L112
241,921
PonteIneptique/collatinus-python
pycollatinus/parser.py
Parser.lisFichierLexique
def lisFichierLexique(self, filepath): """ Lecture des lemmes, et enregistrement de leurs radicaux :param filepath: Chemin du fichier à charger :type filepath: str """ orig = int(filepath.endswith("ext.la")) lignes = lignesFichier(filepath) for ligne in lignes: self.parse_lemme(ligne, orig)
python
def lisFichierLexique(self, filepath): """ Lecture des lemmes, et enregistrement de leurs radicaux :param filepath: Chemin du fichier à charger :type filepath: str """ orig = int(filepath.endswith("ext.la")) lignes = lignesFichier(filepath) for ligne in lignes: self.parse_lemme(ligne, orig)
[ "def", "lisFichierLexique", "(", "self", ",", "filepath", ")", ":", "orig", "=", "int", "(", "filepath", ".", "endswith", "(", "\"ext.la\"", ")", ")", "lignes", "=", "lignesFichier", "(", "filepath", ")", "for", "ligne", "in", "lignes", ":", "self", ".", "parse_lemme", "(", "ligne", ",", "orig", ")" ]
Lecture des lemmes, et enregistrement de leurs radicaux :param filepath: Chemin du fichier à charger :type filepath: str
[ "Lecture", "des", "lemmes", "et", "enregistrement", "de", "leurs", "radicaux" ]
fca37b0b77bc60f47d3c24ab42f6d0bdca6ba0f5
https://github.com/PonteIneptique/collatinus-python/blob/fca37b0b77bc60f47d3c24ab42f6d0bdca6ba0f5/pycollatinus/parser.py#L104-L113
241,922
PonteIneptique/collatinus-python
pycollatinus/parser.py
Parser.register_modele
def register_modele(self, modele: Modele): """ Register a modele onto the lemmatizer :param modele: Modele to register """ self.lemmatiseur._modeles[modele.gr()] = modele
python
def register_modele(self, modele: Modele): """ Register a modele onto the lemmatizer :param modele: Modele to register """ self.lemmatiseur._modeles[modele.gr()] = modele
[ "def", "register_modele", "(", "self", ",", "modele", ":", "Modele", ")", ":", "self", ".", "lemmatiseur", ".", "_modeles", "[", "modele", ".", "gr", "(", ")", "]", "=", "modele" ]
Register a modele onto the lemmatizer :param modele: Modele to register
[ "Register", "a", "modele", "onto", "the", "lemmatizer" ]
fca37b0b77bc60f47d3c24ab42f6d0bdca6ba0f5
https://github.com/PonteIneptique/collatinus-python/blob/fca37b0b77bc60f47d3c24ab42f6d0bdca6ba0f5/pycollatinus/parser.py#L226-L231
241,923
PonteIneptique/collatinus-python
pycollatinus/parser.py
Parser._register_lemme
def _register_lemme(self, lemma): """ Register a lemma into the Lemmatiseur :param lemma: Lemma to register :return: """ if lemma.cle() not in self.lemmatiseur._lemmes: self.ajRadicaux(lemma) self.lemmatiseur._lemmes[lemma.cle()] = lemma
python
def _register_lemme(self, lemma): """ Register a lemma into the Lemmatiseur :param lemma: Lemma to register :return: """ if lemma.cle() not in self.lemmatiseur._lemmes: self.ajRadicaux(lemma) self.lemmatiseur._lemmes[lemma.cle()] = lemma
[ "def", "_register_lemme", "(", "self", ",", "lemma", ")", ":", "if", "lemma", ".", "cle", "(", ")", "not", "in", "self", ".", "lemmatiseur", ".", "_lemmes", ":", "self", ".", "ajRadicaux", "(", "lemma", ")", "self", ".", "lemmatiseur", ".", "_lemmes", "[", "lemma", ".", "cle", "(", ")", "]", "=", "lemma" ]
Register a lemma into the Lemmatiseur :param lemma: Lemma to register :return:
[ "Register", "a", "lemma", "into", "the", "Lemmatiseur" ]
fca37b0b77bc60f47d3c24ab42f6d0bdca6ba0f5
https://github.com/PonteIneptique/collatinus-python/blob/fca37b0b77bc60f47d3c24ab42f6d0bdca6ba0f5/pycollatinus/parser.py#L362-L370
241,924
PonteIneptique/collatinus-python
pycollatinus/parser.py
Parser.parse_irreg
def parse_irreg(self, l): """ Constructeur de la classe Irreg. :param l: Ligne de chargement des irréguliers :type l: str """ ecl = l.split(':') grq = ecl[0] exclusif = False if grq.endswith("*"): grq = grq[:-1] exclusif = True return Irreg( graphie_accentuee=grq, graphie=atone(grq), exclusif=exclusif, morphos=listeI(ecl[2]), lemme=self.lemmatiseur.lemme(ecl[1]), parent=self.lemmatiseur )
python
def parse_irreg(self, l): """ Constructeur de la classe Irreg. :param l: Ligne de chargement des irréguliers :type l: str """ ecl = l.split(':') grq = ecl[0] exclusif = False if grq.endswith("*"): grq = grq[:-1] exclusif = True return Irreg( graphie_accentuee=grq, graphie=atone(grq), exclusif=exclusif, morphos=listeI(ecl[2]), lemme=self.lemmatiseur.lemme(ecl[1]), parent=self.lemmatiseur )
[ "def", "parse_irreg", "(", "self", ",", "l", ")", ":", "ecl", "=", "l", ".", "split", "(", "':'", ")", "grq", "=", "ecl", "[", "0", "]", "exclusif", "=", "False", "if", "grq", ".", "endswith", "(", "\"*\"", ")", ":", "grq", "=", "grq", "[", ":", "-", "1", "]", "exclusif", "=", "True", "return", "Irreg", "(", "graphie_accentuee", "=", "grq", ",", "graphie", "=", "atone", "(", "grq", ")", ",", "exclusif", "=", "exclusif", ",", "morphos", "=", "listeI", "(", "ecl", "[", "2", "]", ")", ",", "lemme", "=", "self", ".", "lemmatiseur", ".", "lemme", "(", "ecl", "[", "1", "]", ")", ",", "parent", "=", "self", ".", "lemmatiseur", ")" ]
Constructeur de la classe Irreg. :param l: Ligne de chargement des irréguliers :type l: str
[ "Constructeur", "de", "la", "classe", "Irreg", "." ]
fca37b0b77bc60f47d3c24ab42f6d0bdca6ba0f5
https://github.com/PonteIneptique/collatinus-python/blob/fca37b0b77bc60f47d3c24ab42f6d0bdca6ba0f5/pycollatinus/parser.py#L456-L474
241,925
mayfield/shellish
shellish/eventing.py
Eventer.add_listener
def add_listener(self, event, callback, single=False, priority=1): """ Add a callback to an event list so it will be run at this event's firing. If single is True, the event is auto-removed after the first invocation. Priority can be used to jump ahead or behind other callback invocations.""" event_stack = self._events[event] event_stack.append({ "callback": callback, "single": single, "priority": priority }) event_stack.sort(key=lambda x: x['priority'])
python
def add_listener(self, event, callback, single=False, priority=1): """ Add a callback to an event list so it will be run at this event's firing. If single is True, the event is auto-removed after the first invocation. Priority can be used to jump ahead or behind other callback invocations.""" event_stack = self._events[event] event_stack.append({ "callback": callback, "single": single, "priority": priority }) event_stack.sort(key=lambda x: x['priority'])
[ "def", "add_listener", "(", "self", ",", "event", ",", "callback", ",", "single", "=", "False", ",", "priority", "=", "1", ")", ":", "event_stack", "=", "self", ".", "_events", "[", "event", "]", "event_stack", ".", "append", "(", "{", "\"callback\"", ":", "callback", ",", "\"single\"", ":", "single", ",", "\"priority\"", ":", "priority", "}", ")", "event_stack", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", "[", "'priority'", "]", ")" ]
Add a callback to an event list so it will be run at this event's firing. If single is True, the event is auto-removed after the first invocation. Priority can be used to jump ahead or behind other callback invocations.
[ "Add", "a", "callback", "to", "an", "event", "list", "so", "it", "will", "be", "run", "at", "this", "event", "s", "firing", ".", "If", "single", "is", "True", "the", "event", "is", "auto", "-", "removed", "after", "the", "first", "invocation", ".", "Priority", "can", "be", "used", "to", "jump", "ahead", "or", "behind", "other", "callback", "invocations", "." ]
df0f0e4612d138c34d8cb99b66ab5b8e47f1414a
https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/eventing.py#L20-L31
241,926
mayfield/shellish
shellish/eventing.py
Eventer.remove_listener
def remove_listener(self, event, callback, single=None, priority=None): """ Remove the event listener matching the same signature used for adding it. This will remove AT MOST one entry meeting the signature requirements. """ event_stack = self._events[event] for x in event_stack: if x['callback'] == callback and \ (single is None or x['single'] == single) and \ (priority is None or x['priority'] == priority): event_stack.remove(x) break else: raise KeyError('Listener not found for "%s": %s' % (event, callback))
python
def remove_listener(self, event, callback, single=None, priority=None): """ Remove the event listener matching the same signature used for adding it. This will remove AT MOST one entry meeting the signature requirements. """ event_stack = self._events[event] for x in event_stack: if x['callback'] == callback and \ (single is None or x['single'] == single) and \ (priority is None or x['priority'] == priority): event_stack.remove(x) break else: raise KeyError('Listener not found for "%s": %s' % (event, callback))
[ "def", "remove_listener", "(", "self", ",", "event", ",", "callback", ",", "single", "=", "None", ",", "priority", "=", "None", ")", ":", "event_stack", "=", "self", ".", "_events", "[", "event", "]", "for", "x", "in", "event_stack", ":", "if", "x", "[", "'callback'", "]", "==", "callback", "and", "(", "single", "is", "None", "or", "x", "[", "'single'", "]", "==", "single", ")", "and", "(", "priority", "is", "None", "or", "x", "[", "'priority'", "]", "==", "priority", ")", ":", "event_stack", ".", "remove", "(", "x", ")", "break", "else", ":", "raise", "KeyError", "(", "'Listener not found for \"%s\": %s'", "%", "(", "event", ",", "callback", ")", ")" ]
Remove the event listener matching the same signature used for adding it. This will remove AT MOST one entry meeting the signature requirements.
[ "Remove", "the", "event", "listener", "matching", "the", "same", "signature", "used", "for", "adding", "it", ".", "This", "will", "remove", "AT", "MOST", "one", "entry", "meeting", "the", "signature", "requirements", "." ]
df0f0e4612d138c34d8cb99b66ab5b8e47f1414a
https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/eventing.py#L33-L46
241,927
mayfield/shellish
shellish/eventing.py
Eventer.fire_event
def fire_event(self, event, *args, **kwargs): """ Execute the listeners for this event passing any arguments along. """ remove = [] event_stack = self._events[event] for x in event_stack: x['callback'](*args, **kwargs) if x['single']: remove.append(x) for x in remove: event_stack.remove(x)
python
def fire_event(self, event, *args, **kwargs): """ Execute the listeners for this event passing any arguments along. """ remove = [] event_stack = self._events[event] for x in event_stack: x['callback'](*args, **kwargs) if x['single']: remove.append(x) for x in remove: event_stack.remove(x)
[ "def", "fire_event", "(", "self", ",", "event", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "remove", "=", "[", "]", "event_stack", "=", "self", ".", "_events", "[", "event", "]", "for", "x", "in", "event_stack", ":", "x", "[", "'callback'", "]", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "x", "[", "'single'", "]", ":", "remove", ".", "append", "(", "x", ")", "for", "x", "in", "remove", ":", "event_stack", ".", "remove", "(", "x", ")" ]
Execute the listeners for this event passing any arguments along.
[ "Execute", "the", "listeners", "for", "this", "event", "passing", "any", "arguments", "along", "." ]
df0f0e4612d138c34d8cb99b66ab5b8e47f1414a
https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/eventing.py#L48-L58
241,928
MacHu-GWU/angora-project
angora/gadget/pytimer.py
Timer.stop
def stop(self): """Save last elapse time to self.records. """ self.elapse = time.clock() - self.st self.records.append(self.elapse)
python
def stop(self): """Save last elapse time to self.records. """ self.elapse = time.clock() - self.st self.records.append(self.elapse)
[ "def", "stop", "(", "self", ")", ":", "self", ".", "elapse", "=", "time", ".", "clock", "(", ")", "-", "self", ".", "st", "self", ".", "records", ".", "append", "(", "self", ".", "elapse", ")" ]
Save last elapse time to self.records.
[ "Save", "last", "elapse", "time", "to", "self", ".", "records", "." ]
689a60da51cd88680ddbe26e28dbe81e6b01d275
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/gadget/pytimer.py#L46-L50
241,929
MacHu-GWU/angora-project
angora/gadget/pytimer.py
Timer.display_all
def display_all(self): """Print detailed information. """ print( ("total elapse %0.6f seconds, last elapse %0.6f seconds, " "took %s times measurement") % ( self.total_elapse, self.elapse, len(self.records)))
python
def display_all(self): """Print detailed information. """ print( ("total elapse %0.6f seconds, last elapse %0.6f seconds, " "took %s times measurement") % ( self.total_elapse, self.elapse, len(self.records)))
[ "def", "display_all", "(", "self", ")", ":", "print", "(", "(", "\"total elapse %0.6f seconds, last elapse %0.6f seconds, \"", "\"took %s times measurement\"", ")", "%", "(", "self", ".", "total_elapse", ",", "self", ".", "elapse", ",", "len", "(", "self", ".", "records", ")", ")", ")" ]
Print detailed information.
[ "Print", "detailed", "information", "." ]
689a60da51cd88680ddbe26e28dbe81e6b01d275
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/gadget/pytimer.py#L69-L74
241,930
silenc3r/dikicli
dikicli/core.py
_parse_cached
def _parse_cached(html_dump): """Parse html string from cached html files. Parameters ---------- html_dump : string HTML content Returns ------- translations : list Translations list. """ soup = BeautifulSoup(html_dump, "html.parser") translations = [] for trans in soup.find_all("div", class_="translation"): word = tuple(t.get_text() for t in trans.select("div.word > h2")) trans_list = [] for part in trans.find_all("div", class_="part-of-speech"): pn = part.find("p", class_="part-name") if pn: pn = pn.get_text().strip("[]") meanings = [] for meaning in part.find_all("div", class_="meaning"): m = [mn.get_text() for mn in meaning.select("li > span")] examples = [] for e in meaning.find_all("p"): examples.append([ex.get_text() for ex in e.find_all("span")]) meanings.append(Meaning(m, examples)) trans_list.append(PartOfSpeech(pn, meanings)) translations.append(Translation(word, trans_list)) return translations
python
def _parse_cached(html_dump): """Parse html string from cached html files. Parameters ---------- html_dump : string HTML content Returns ------- translations : list Translations list. """ soup = BeautifulSoup(html_dump, "html.parser") translations = [] for trans in soup.find_all("div", class_="translation"): word = tuple(t.get_text() for t in trans.select("div.word > h2")) trans_list = [] for part in trans.find_all("div", class_="part-of-speech"): pn = part.find("p", class_="part-name") if pn: pn = pn.get_text().strip("[]") meanings = [] for meaning in part.find_all("div", class_="meaning"): m = [mn.get_text() for mn in meaning.select("li > span")] examples = [] for e in meaning.find_all("p"): examples.append([ex.get_text() for ex in e.find_all("span")]) meanings.append(Meaning(m, examples)) trans_list.append(PartOfSpeech(pn, meanings)) translations.append(Translation(word, trans_list)) return translations
[ "def", "_parse_cached", "(", "html_dump", ")", ":", "soup", "=", "BeautifulSoup", "(", "html_dump", ",", "\"html.parser\"", ")", "translations", "=", "[", "]", "for", "trans", "in", "soup", ".", "find_all", "(", "\"div\"", ",", "class_", "=", "\"translation\"", ")", ":", "word", "=", "tuple", "(", "t", ".", "get_text", "(", ")", "for", "t", "in", "trans", ".", "select", "(", "\"div.word > h2\"", ")", ")", "trans_list", "=", "[", "]", "for", "part", "in", "trans", ".", "find_all", "(", "\"div\"", ",", "class_", "=", "\"part-of-speech\"", ")", ":", "pn", "=", "part", ".", "find", "(", "\"p\"", ",", "class_", "=", "\"part-name\"", ")", "if", "pn", ":", "pn", "=", "pn", ".", "get_text", "(", ")", ".", "strip", "(", "\"[]\"", ")", "meanings", "=", "[", "]", "for", "meaning", "in", "part", ".", "find_all", "(", "\"div\"", ",", "class_", "=", "\"meaning\"", ")", ":", "m", "=", "[", "mn", ".", "get_text", "(", ")", "for", "mn", "in", "meaning", ".", "select", "(", "\"li > span\"", ")", "]", "examples", "=", "[", "]", "for", "e", "in", "meaning", ".", "find_all", "(", "\"p\"", ")", ":", "examples", ".", "append", "(", "[", "ex", ".", "get_text", "(", ")", "for", "ex", "in", "e", ".", "find_all", "(", "\"span\"", ")", "]", ")", "meanings", ".", "append", "(", "Meaning", "(", "m", ",", "examples", ")", ")", "trans_list", ".", "append", "(", "PartOfSpeech", "(", "pn", ",", "meanings", ")", ")", "translations", ".", "append", "(", "Translation", "(", "word", ",", "trans_list", ")", ")", "return", "translations" ]
Parse html string from cached html files. Parameters ---------- html_dump : string HTML content Returns ------- translations : list Translations list.
[ "Parse", "html", "string", "from", "cached", "html", "files", "." ]
53721cdf75db04e2edca5ed3f99beae7c079d980
https://github.com/silenc3r/dikicli/blob/53721cdf75db04e2edca5ed3f99beae7c079d980/dikicli/core.py#L205-L236
241,931
silenc3r/dikicli
dikicli/core.py
_cache_lookup
def _cache_lookup(word, data_dir, native=False): """Checks if word is in cache. Parameters ---------- word : str Word to check in cache. data_dir : pathlib.Path Cache directory location. Returns ------- translation : str or None Translation of given word. """ trans_dir = "translations" if native: trans_dir += "_native" logger.debug("Cache lookup: %s", word) filename = data_dir.joinpath(trans_dir, "{}.html".format(word)) if filename.is_file(): with open(filename, mode="r") as f: logger.debug("Cache found: %s", word) # TODO: not sure if we should parse data here translation = _parse_cached(f.read()) return translation logger.debug("Cache miss: %s", word) return None
python
def _cache_lookup(word, data_dir, native=False): """Checks if word is in cache. Parameters ---------- word : str Word to check in cache. data_dir : pathlib.Path Cache directory location. Returns ------- translation : str or None Translation of given word. """ trans_dir = "translations" if native: trans_dir += "_native" logger.debug("Cache lookup: %s", word) filename = data_dir.joinpath(trans_dir, "{}.html".format(word)) if filename.is_file(): with open(filename, mode="r") as f: logger.debug("Cache found: %s", word) # TODO: not sure if we should parse data here translation = _parse_cached(f.read()) return translation logger.debug("Cache miss: %s", word) return None
[ "def", "_cache_lookup", "(", "word", ",", "data_dir", ",", "native", "=", "False", ")", ":", "trans_dir", "=", "\"translations\"", "if", "native", ":", "trans_dir", "+=", "\"_native\"", "logger", ".", "debug", "(", "\"Cache lookup: %s\"", ",", "word", ")", "filename", "=", "data_dir", ".", "joinpath", "(", "trans_dir", ",", "\"{}.html\"", ".", "format", "(", "word", ")", ")", "if", "filename", ".", "is_file", "(", ")", ":", "with", "open", "(", "filename", ",", "mode", "=", "\"r\"", ")", "as", "f", ":", "logger", ".", "debug", "(", "\"Cache found: %s\"", ",", "word", ")", "# TODO: not sure if we should parse data here", "translation", "=", "_parse_cached", "(", "f", ".", "read", "(", ")", ")", "return", "translation", "logger", ".", "debug", "(", "\"Cache miss: %s\"", ",", "word", ")", "return", "None" ]
Checks if word is in cache. Parameters ---------- word : str Word to check in cache. data_dir : pathlib.Path Cache directory location. Returns ------- translation : str or None Translation of given word.
[ "Checks", "if", "word", "is", "in", "cache", "." ]
53721cdf75db04e2edca5ed3f99beae7c079d980
https://github.com/silenc3r/dikicli/blob/53721cdf75db04e2edca5ed3f99beae7c079d980/dikicli/core.py#L239-L266
241,932
silenc3r/dikicli
dikicli/core.py
_get_words
def _get_words(data_dir): """Get list of words from history file. Parameters ---------- data_dir : pathlib.Path Directory where data is saved. Returns ------- word_list : list of str List of words. """ words_file = data_dir.joinpath("words.txt") word_list = [] if not words_file.is_file(): return word_list with open(words_file, mode="r") as f: for l in f: line = l.rstrip() word_list.append(line) return word_list
python
def _get_words(data_dir): """Get list of words from history file. Parameters ---------- data_dir : pathlib.Path Directory where data is saved. Returns ------- word_list : list of str List of words. """ words_file = data_dir.joinpath("words.txt") word_list = [] if not words_file.is_file(): return word_list with open(words_file, mode="r") as f: for l in f: line = l.rstrip() word_list.append(line) return word_list
[ "def", "_get_words", "(", "data_dir", ")", ":", "words_file", "=", "data_dir", ".", "joinpath", "(", "\"words.txt\"", ")", "word_list", "=", "[", "]", "if", "not", "words_file", ".", "is_file", "(", ")", ":", "return", "word_list", "with", "open", "(", "words_file", ",", "mode", "=", "\"r\"", ")", "as", "f", ":", "for", "l", "in", "f", ":", "line", "=", "l", ".", "rstrip", "(", ")", "word_list", ".", "append", "(", "line", ")", "return", "word_list" ]
Get list of words from history file. Parameters ---------- data_dir : pathlib.Path Directory where data is saved. Returns ------- word_list : list of str List of words.
[ "Get", "list", "of", "words", "from", "history", "file", "." ]
53721cdf75db04e2edca5ed3f99beae7c079d980
https://github.com/silenc3r/dikicli/blob/53721cdf75db04e2edca5ed3f99beae7c079d980/dikicli/core.py#L269-L290
241,933
silenc3r/dikicli
dikicli/core.py
_save_to_history
def _save_to_history(word, data_dir): """Write word to history file. Parameters ---------- word : str Word to save to history. data_dir : pathlib.Path Directory where history file should be saved. data_dir and it's parent directories will be created if needed. """ if not data_dir.exists(): logger.debug("Creating DATA DIR: %s", data_dir.as_posix()) data_dir.mkdir(parents=True) if word not in _get_words(data_dir): with open(data_dir.joinpath("words.txt"), mode="a+") as f: logger.debug("Adding to history: %s", word) f.write(word + "\n")
python
def _save_to_history(word, data_dir): """Write word to history file. Parameters ---------- word : str Word to save to history. data_dir : pathlib.Path Directory where history file should be saved. data_dir and it's parent directories will be created if needed. """ if not data_dir.exists(): logger.debug("Creating DATA DIR: %s", data_dir.as_posix()) data_dir.mkdir(parents=True) if word not in _get_words(data_dir): with open(data_dir.joinpath("words.txt"), mode="a+") as f: logger.debug("Adding to history: %s", word) f.write(word + "\n")
[ "def", "_save_to_history", "(", "word", ",", "data_dir", ")", ":", "if", "not", "data_dir", ".", "exists", "(", ")", ":", "logger", ".", "debug", "(", "\"Creating DATA DIR: %s\"", ",", "data_dir", ".", "as_posix", "(", ")", ")", "data_dir", ".", "mkdir", "(", "parents", "=", "True", ")", "if", "word", "not", "in", "_get_words", "(", "data_dir", ")", ":", "with", "open", "(", "data_dir", ".", "joinpath", "(", "\"words.txt\"", ")", ",", "mode", "=", "\"a+\"", ")", "as", "f", ":", "logger", ".", "debug", "(", "\"Adding to history: %s\"", ",", "word", ")", "f", ".", "write", "(", "word", "+", "\"\\n\"", ")" ]
Write word to history file. Parameters ---------- word : str Word to save to history. data_dir : pathlib.Path Directory where history file should be saved. data_dir and it's parent directories will be created if needed.
[ "Write", "word", "to", "history", "file", "." ]
53721cdf75db04e2edca5ed3f99beae7c079d980
https://github.com/silenc3r/dikicli/blob/53721cdf75db04e2edca5ed3f99beae7c079d980/dikicli/core.py#L293-L311
241,934
silenc3r/dikicli
dikicli/core.py
_create_html_file_content
def _create_html_file_content(translations): """Create html string out of translation dict. Parameters ---------- tralnslations : dict Dictionary of word translations. Returns ------- str: html string of translation """ content = [] for i1, t in enumerate(translations): if i1 > 0: content.append("<br>") content.append('<div class="translation">') content.append('<div class="word">') for w in t.word: content.append("<h2>{word}</h2>".format(word=w)) content.append("</div>") # end `word` for i2, t2 in enumerate(t.parts_of_speech): if i2 > 0: content.append("<br>") content.append('<div class="part-of-speech">') if t2.part is not None: content.append('<p class="part-name">[{part}]</p>'.format(part=t2.part)) content.append("<ol>") for m in t2.meanings: content.append('<div class="meaning">') mng = ["<strong><li>"] for i3, mn in enumerate(m.meaning): if i3 > 0: mng.append(", ") mng.append("<span>{meaning}</span>".format(meaning=mn)) mng.append("</li></strong>") content.append("".join(mng)) content.append('<div class="examples">') for e in m.examples: exmpl = "<p><span>{ex}</span>".format(ex=e[0]) if e[1]: exmpl += "<br><span>{tr}</span>".format(tr=e[1]) exmpl += "</p>" content.append(exmpl) content.append("</div>") # end `examples` content.append("</div>") # end `meaning` content.append("</ol>") content.append("</div>") # end `part-of-speech` content.append("</div>") # end `translation` return "\n".join(content)
python
def _create_html_file_content(translations): """Create html string out of translation dict. Parameters ---------- tralnslations : dict Dictionary of word translations. Returns ------- str: html string of translation """ content = [] for i1, t in enumerate(translations): if i1 > 0: content.append("<br>") content.append('<div class="translation">') content.append('<div class="word">') for w in t.word: content.append("<h2>{word}</h2>".format(word=w)) content.append("</div>") # end `word` for i2, t2 in enumerate(t.parts_of_speech): if i2 > 0: content.append("<br>") content.append('<div class="part-of-speech">') if t2.part is not None: content.append('<p class="part-name">[{part}]</p>'.format(part=t2.part)) content.append("<ol>") for m in t2.meanings: content.append('<div class="meaning">') mng = ["<strong><li>"] for i3, mn in enumerate(m.meaning): if i3 > 0: mng.append(", ") mng.append("<span>{meaning}</span>".format(meaning=mn)) mng.append("</li></strong>") content.append("".join(mng)) content.append('<div class="examples">') for e in m.examples: exmpl = "<p><span>{ex}</span>".format(ex=e[0]) if e[1]: exmpl += "<br><span>{tr}</span>".format(tr=e[1]) exmpl += "</p>" content.append(exmpl) content.append("</div>") # end `examples` content.append("</div>") # end `meaning` content.append("</ol>") content.append("</div>") # end `part-of-speech` content.append("</div>") # end `translation` return "\n".join(content)
[ "def", "_create_html_file_content", "(", "translations", ")", ":", "content", "=", "[", "]", "for", "i1", ",", "t", "in", "enumerate", "(", "translations", ")", ":", "if", "i1", ">", "0", ":", "content", ".", "append", "(", "\"<br>\"", ")", "content", ".", "append", "(", "'<div class=\"translation\">'", ")", "content", ".", "append", "(", "'<div class=\"word\">'", ")", "for", "w", "in", "t", ".", "word", ":", "content", ".", "append", "(", "\"<h2>{word}</h2>\"", ".", "format", "(", "word", "=", "w", ")", ")", "content", ".", "append", "(", "\"</div>\"", ")", "# end `word`", "for", "i2", ",", "t2", "in", "enumerate", "(", "t", ".", "parts_of_speech", ")", ":", "if", "i2", ">", "0", ":", "content", ".", "append", "(", "\"<br>\"", ")", "content", ".", "append", "(", "'<div class=\"part-of-speech\">'", ")", "if", "t2", ".", "part", "is", "not", "None", ":", "content", ".", "append", "(", "'<p class=\"part-name\">[{part}]</p>'", ".", "format", "(", "part", "=", "t2", ".", "part", ")", ")", "content", ".", "append", "(", "\"<ol>\"", ")", "for", "m", "in", "t2", ".", "meanings", ":", "content", ".", "append", "(", "'<div class=\"meaning\">'", ")", "mng", "=", "[", "\"<strong><li>\"", "]", "for", "i3", ",", "mn", "in", "enumerate", "(", "m", ".", "meaning", ")", ":", "if", "i3", ">", "0", ":", "mng", ".", "append", "(", "\", \"", ")", "mng", ".", "append", "(", "\"<span>{meaning}</span>\"", ".", "format", "(", "meaning", "=", "mn", ")", ")", "mng", ".", "append", "(", "\"</li></strong>\"", ")", "content", ".", "append", "(", "\"\"", ".", "join", "(", "mng", ")", ")", "content", ".", "append", "(", "'<div class=\"examples\">'", ")", "for", "e", "in", "m", ".", "examples", ":", "exmpl", "=", "\"<p><span>{ex}</span>\"", ".", "format", "(", "ex", "=", "e", "[", "0", "]", ")", "if", "e", "[", "1", "]", ":", "exmpl", "+=", "\"<br><span>{tr}</span>\"", ".", "format", "(", "tr", "=", "e", "[", "1", "]", ")", "exmpl", "+=", "\"</p>\"", "content", ".", "append", "(", "exmpl", ")", "content", ".", "append", "(", "\"</div>\"", ")", "# end `examples`", "content", ".", "append", "(", "\"</div>\"", ")", "# end `meaning`", "content", ".", "append", "(", "\"</ol>\"", ")", "content", ".", "append", "(", "\"</div>\"", ")", "# end `part-of-speech`", "content", ".", "append", "(", "\"</div>\"", ")", "# end `translation`", "return", "\"\\n\"", ".", "join", "(", "content", ")" ]
Create html string out of translation dict. Parameters ---------- tralnslations : dict Dictionary of word translations. Returns ------- str: html string of translation
[ "Create", "html", "string", "out", "of", "translation", "dict", "." ]
53721cdf75db04e2edca5ed3f99beae7c079d980
https://github.com/silenc3r/dikicli/blob/53721cdf75db04e2edca5ed3f99beae7c079d980/dikicli/core.py#L314-L364
241,935
silenc3r/dikicli
dikicli/core.py
_write_html_file
def _write_html_file(word, translations, data_dir, native=False): """Create html file of word translations. Parameters ---------- word : str Word that was translated. tralnslations : dict Dictionary of word translations. data_dir : pathlib.Path Location where html files are saved. """ content_str = _create_html_file_content(translations) html_string = HTML_TEMPLATE.replace("{% word %}", word) html_string = html_string.replace("{% content %}", content_str) trans_dir = "translations" if native: trans_dir += "_native" translations_dir = data_dir.joinpath(trans_dir) fname = translations_dir.joinpath("{word}.html".format(word=word)) save_file(fname, html_string, mk_parents=True)
python
def _write_html_file(word, translations, data_dir, native=False): """Create html file of word translations. Parameters ---------- word : str Word that was translated. tralnslations : dict Dictionary of word translations. data_dir : pathlib.Path Location where html files are saved. """ content_str = _create_html_file_content(translations) html_string = HTML_TEMPLATE.replace("{% word %}", word) html_string = html_string.replace("{% content %}", content_str) trans_dir = "translations" if native: trans_dir += "_native" translations_dir = data_dir.joinpath(trans_dir) fname = translations_dir.joinpath("{word}.html".format(word=word)) save_file(fname, html_string, mk_parents=True)
[ "def", "_write_html_file", "(", "word", ",", "translations", ",", "data_dir", ",", "native", "=", "False", ")", ":", "content_str", "=", "_create_html_file_content", "(", "translations", ")", "html_string", "=", "HTML_TEMPLATE", ".", "replace", "(", "\"{% word %}\"", ",", "word", ")", "html_string", "=", "html_string", ".", "replace", "(", "\"{% content %}\"", ",", "content_str", ")", "trans_dir", "=", "\"translations\"", "if", "native", ":", "trans_dir", "+=", "\"_native\"", "translations_dir", "=", "data_dir", ".", "joinpath", "(", "trans_dir", ")", "fname", "=", "translations_dir", ".", "joinpath", "(", "\"{word}.html\"", ".", "format", "(", "word", "=", "word", ")", ")", "save_file", "(", "fname", ",", "html_string", ",", "mk_parents", "=", "True", ")" ]
Create html file of word translations. Parameters ---------- word : str Word that was translated. tralnslations : dict Dictionary of word translations. data_dir : pathlib.Path Location where html files are saved.
[ "Create", "html", "file", "of", "word", "translations", "." ]
53721cdf75db04e2edca5ed3f99beae7c079d980
https://github.com/silenc3r/dikicli/blob/53721cdf75db04e2edca5ed3f99beae7c079d980/dikicli/core.py#L367-L388
241,936
silenc3r/dikicli
dikicli/core.py
_create_index_content
def _create_index_content(words): """Create html string of index file. Parameters ---------- words : list of str List of cached words. Returns ------- str html string. """ content = ["<h1>Index</h1>", "<ul>"] for word in words: content.append( '<li><a href="translations/{word}.html">{word}</a></li>'.format(word=word) ) content.append("</ul>") if not words: content.append("<i>Nothing to see here ...yet!</i>") return "\n".join(content)
python
def _create_index_content(words): """Create html string of index file. Parameters ---------- words : list of str List of cached words. Returns ------- str html string. """ content = ["<h1>Index</h1>", "<ul>"] for word in words: content.append( '<li><a href="translations/{word}.html">{word}</a></li>'.format(word=word) ) content.append("</ul>") if not words: content.append("<i>Nothing to see here ...yet!</i>") return "\n".join(content)
[ "def", "_create_index_content", "(", "words", ")", ":", "content", "=", "[", "\"<h1>Index</h1>\"", ",", "\"<ul>\"", "]", "for", "word", "in", "words", ":", "content", ".", "append", "(", "'<li><a href=\"translations/{word}.html\">{word}</a></li>'", ".", "format", "(", "word", "=", "word", ")", ")", "content", ".", "append", "(", "\"</ul>\"", ")", "if", "not", "words", ":", "content", ".", "append", "(", "\"<i>Nothing to see here ...yet!</i>\"", ")", "return", "\"\\n\"", ".", "join", "(", "content", ")" ]
Create html string of index file. Parameters ---------- words : list of str List of cached words. Returns ------- str html string.
[ "Create", "html", "string", "of", "index", "file", "." ]
53721cdf75db04e2edca5ed3f99beae7c079d980
https://github.com/silenc3r/dikicli/blob/53721cdf75db04e2edca5ed3f99beae7c079d980/dikicli/core.py#L391-L414
241,937
silenc3r/dikicli
dikicli/core.py
_write_index_file
def _write_index_file(data_dir): """Create index file of cached translations. Parameters ---------- data_dir : pathlib.Path Cache directory location. """ cached_words = [ w for w in _get_words(data_dir) if data_dir.joinpath("translations/{}.html".format(w)).is_file() ] content_str = _create_index_content(cached_words) html_string = HTML_TEMPLATE.replace("{% word %}", "Index") html_string = html_string.replace("{% content %}", content_str) filename = data_dir.joinpath("index.html") save_file(filename, html_string, mk_parents=True)
python
def _write_index_file(data_dir): """Create index file of cached translations. Parameters ---------- data_dir : pathlib.Path Cache directory location. """ cached_words = [ w for w in _get_words(data_dir) if data_dir.joinpath("translations/{}.html".format(w)).is_file() ] content_str = _create_index_content(cached_words) html_string = HTML_TEMPLATE.replace("{% word %}", "Index") html_string = html_string.replace("{% content %}", content_str) filename = data_dir.joinpath("index.html") save_file(filename, html_string, mk_parents=True)
[ "def", "_write_index_file", "(", "data_dir", ")", ":", "cached_words", "=", "[", "w", "for", "w", "in", "_get_words", "(", "data_dir", ")", "if", "data_dir", ".", "joinpath", "(", "\"translations/{}.html\"", ".", "format", "(", "w", ")", ")", ".", "is_file", "(", ")", "]", "content_str", "=", "_create_index_content", "(", "cached_words", ")", "html_string", "=", "HTML_TEMPLATE", ".", "replace", "(", "\"{% word %}\"", ",", "\"Index\"", ")", "html_string", "=", "html_string", ".", "replace", "(", "\"{% content %}\"", ",", "content_str", ")", "filename", "=", "data_dir", ".", "joinpath", "(", "\"index.html\"", ")", "save_file", "(", "filename", ",", "html_string", ",", "mk_parents", "=", "True", ")" ]
Create index file of cached translations. Parameters ---------- data_dir : pathlib.Path Cache directory location.
[ "Create", "index", "file", "of", "cached", "translations", "." ]
53721cdf75db04e2edca5ed3f99beae7c079d980
https://github.com/silenc3r/dikicli/blob/53721cdf75db04e2edca5ed3f99beae7c079d980/dikicli/core.py#L417-L436
241,938
silenc3r/dikicli
dikicli/core.py
save_file
def save_file(filename, data, mk_parents=True): """Save file to disk. Paramaters ---------- filename : pathlib.Path Path to the file. data : str File contents. mk_parents : bool, optional If to create parent directories. """ parent = filename.parent if not parent.exists() and mk_parents: logger.debug("Creating directory: %s", parent.as_posix()) parent.mkdir(parents=True) with open(filename, mode="w") as f: logger.debug("Saving file: %s", filename.as_posix()) f.write(data)
python
def save_file(filename, data, mk_parents=True): """Save file to disk. Paramaters ---------- filename : pathlib.Path Path to the file. data : str File contents. mk_parents : bool, optional If to create parent directories. """ parent = filename.parent if not parent.exists() and mk_parents: logger.debug("Creating directory: %s", parent.as_posix()) parent.mkdir(parents=True) with open(filename, mode="w") as f: logger.debug("Saving file: %s", filename.as_posix()) f.write(data)
[ "def", "save_file", "(", "filename", ",", "data", ",", "mk_parents", "=", "True", ")", ":", "parent", "=", "filename", ".", "parent", "if", "not", "parent", ".", "exists", "(", ")", "and", "mk_parents", ":", "logger", ".", "debug", "(", "\"Creating directory: %s\"", ",", "parent", ".", "as_posix", "(", ")", ")", "parent", ".", "mkdir", "(", "parents", "=", "True", ")", "with", "open", "(", "filename", ",", "mode", "=", "\"w\"", ")", "as", "f", ":", "logger", ".", "debug", "(", "\"Saving file: %s\"", ",", "filename", ".", "as_posix", "(", ")", ")", "f", ".", "write", "(", "data", ")" ]
Save file to disk. Paramaters ---------- filename : pathlib.Path Path to the file. data : str File contents. mk_parents : bool, optional If to create parent directories.
[ "Save", "file", "to", "disk", "." ]
53721cdf75db04e2edca5ed3f99beae7c079d980
https://github.com/silenc3r/dikicli/blob/53721cdf75db04e2edca5ed3f99beae7c079d980/dikicli/core.py#L439-L457
241,939
silenc3r/dikicli
dikicli/core.py
_lookup_online
def _lookup_online(word): """Look up word on diki.pl. Parameters ---------- word : str Word too look up. Returns ------- str website HTML content. """ URL = "https://www.diki.pl/{word}" HEADERS = { "User-Agent": ( "Mozilla/5.0 (compatible, MSIE 11, Windows NT 6.3; " "Trident/7.0; rv:11.0) like Gecko" ) } logger.debug("Looking up online: %s", word) quoted_word = urllib.parse.quote(word) req = urllib.request.Request(URL.format(word=quoted_word), headers=HEADERS) with urllib.request.urlopen(req) as response: html_string = response.read().decode() return html.unescape(html_string)
python
def _lookup_online(word): """Look up word on diki.pl. Parameters ---------- word : str Word too look up. Returns ------- str website HTML content. """ URL = "https://www.diki.pl/{word}" HEADERS = { "User-Agent": ( "Mozilla/5.0 (compatible, MSIE 11, Windows NT 6.3; " "Trident/7.0; rv:11.0) like Gecko" ) } logger.debug("Looking up online: %s", word) quoted_word = urllib.parse.quote(word) req = urllib.request.Request(URL.format(word=quoted_word), headers=HEADERS) with urllib.request.urlopen(req) as response: html_string = response.read().decode() return html.unescape(html_string)
[ "def", "_lookup_online", "(", "word", ")", ":", "URL", "=", "\"https://www.diki.pl/{word}\"", "HEADERS", "=", "{", "\"User-Agent\"", ":", "(", "\"Mozilla/5.0 (compatible, MSIE 11, Windows NT 6.3; \"", "\"Trident/7.0; rv:11.0) like Gecko\"", ")", "}", "logger", ".", "debug", "(", "\"Looking up online: %s\"", ",", "word", ")", "quoted_word", "=", "urllib", ".", "parse", ".", "quote", "(", "word", ")", "req", "=", "urllib", ".", "request", ".", "Request", "(", "URL", ".", "format", "(", "word", "=", "quoted_word", ")", ",", "headers", "=", "HEADERS", ")", "with", "urllib", ".", "request", ".", "urlopen", "(", "req", ")", "as", "response", ":", "html_string", "=", "response", ".", "read", "(", ")", ".", "decode", "(", ")", "return", "html", ".", "unescape", "(", "html_string", ")" ]
Look up word on diki.pl. Parameters ---------- word : str Word too look up. Returns ------- str website HTML content.
[ "Look", "up", "word", "on", "diki", ".", "pl", "." ]
53721cdf75db04e2edca5ed3f99beae7c079d980
https://github.com/silenc3r/dikicli/blob/53721cdf75db04e2edca5ed3f99beae7c079d980/dikicli/core.py#L460-L487
241,940
silenc3r/dikicli
dikicli/core.py
translate
def translate(word, config, use_cache=True, to_eng=False): """Translate a word. Parameters ---------- word : str Word to translate. config : Config Configuration settings. use_cache : bool, optional Wheter to use cache. to_eng : bool, optional Translate from Polish to English. Returns ------- translation Translation of a word. Raises ------ WordNotFound If word can't be found. """ translation = None data_dir = Path(config["data dir"]) if use_cache: logger.debug("Checking cache: %s", word) translation = _cache_lookup(word, data_dir, native=to_eng) if translation: return translation html_dump = _lookup_online(word) try: translation = _parse_html(html_dump, native=to_eng) except WordNotFound as exn: logger.error(str(exn)) raise exn _write_html_file(word, translation, data_dir, native=to_eng) if not to_eng: _save_to_history(word, data_dir) _write_index_file(data_dir) return translation
python
def translate(word, config, use_cache=True, to_eng=False): """Translate a word. Parameters ---------- word : str Word to translate. config : Config Configuration settings. use_cache : bool, optional Wheter to use cache. to_eng : bool, optional Translate from Polish to English. Returns ------- translation Translation of a word. Raises ------ WordNotFound If word can't be found. """ translation = None data_dir = Path(config["data dir"]) if use_cache: logger.debug("Checking cache: %s", word) translation = _cache_lookup(word, data_dir, native=to_eng) if translation: return translation html_dump = _lookup_online(word) try: translation = _parse_html(html_dump, native=to_eng) except WordNotFound as exn: logger.error(str(exn)) raise exn _write_html_file(word, translation, data_dir, native=to_eng) if not to_eng: _save_to_history(word, data_dir) _write_index_file(data_dir) return translation
[ "def", "translate", "(", "word", ",", "config", ",", "use_cache", "=", "True", ",", "to_eng", "=", "False", ")", ":", "translation", "=", "None", "data_dir", "=", "Path", "(", "config", "[", "\"data dir\"", "]", ")", "if", "use_cache", ":", "logger", ".", "debug", "(", "\"Checking cache: %s\"", ",", "word", ")", "translation", "=", "_cache_lookup", "(", "word", ",", "data_dir", ",", "native", "=", "to_eng", ")", "if", "translation", ":", "return", "translation", "html_dump", "=", "_lookup_online", "(", "word", ")", "try", ":", "translation", "=", "_parse_html", "(", "html_dump", ",", "native", "=", "to_eng", ")", "except", "WordNotFound", "as", "exn", ":", "logger", ".", "error", "(", "str", "(", "exn", ")", ")", "raise", "exn", "_write_html_file", "(", "word", ",", "translation", ",", "data_dir", ",", "native", "=", "to_eng", ")", "if", "not", "to_eng", ":", "_save_to_history", "(", "word", ",", "data_dir", ")", "_write_index_file", "(", "data_dir", ")", "return", "translation" ]
Translate a word. Parameters ---------- word : str Word to translate. config : Config Configuration settings. use_cache : bool, optional Wheter to use cache. to_eng : bool, optional Translate from Polish to English. Returns ------- translation Translation of a word. Raises ------ WordNotFound If word can't be found.
[ "Translate", "a", "word", "." ]
53721cdf75db04e2edca5ed3f99beae7c079d980
https://github.com/silenc3r/dikicli/blob/53721cdf75db04e2edca5ed3f99beae7c079d980/dikicli/core.py#L490-L537
241,941
silenc3r/dikicli
dikicli/core.py
display_index
def display_index(config): """Open index in web browser. Parameters ---------- config : Config Configuration settings. Raises ------ FileNotFoundError If index file doesn't exist. """ browser = config["web browser"].lower() data_dir = Path(config["data dir"]) if browser in webbrowser._browsers: b = webbrowser.get(browser) else: if browser != "default": logger.warning( "Couldn't find '%s' browser. Falling back to default.", browser ) b = webbrowser.get() index_file = data_dir.joinpath("index.html") if not index_file.exists(): logger.error("File doesn't exist: %s", index_file.as_posix()) raise FileNotFoundError("Index file doesn't exist") else: logger.info("Opening %s in '%s'", index_file.as_posix(), b.name) b.open(index_file.as_uri())
python
def display_index(config): """Open index in web browser. Parameters ---------- config : Config Configuration settings. Raises ------ FileNotFoundError If index file doesn't exist. """ browser = config["web browser"].lower() data_dir = Path(config["data dir"]) if browser in webbrowser._browsers: b = webbrowser.get(browser) else: if browser != "default": logger.warning( "Couldn't find '%s' browser. Falling back to default.", browser ) b = webbrowser.get() index_file = data_dir.joinpath("index.html") if not index_file.exists(): logger.error("File doesn't exist: %s", index_file.as_posix()) raise FileNotFoundError("Index file doesn't exist") else: logger.info("Opening %s in '%s'", index_file.as_posix(), b.name) b.open(index_file.as_uri())
[ "def", "display_index", "(", "config", ")", ":", "browser", "=", "config", "[", "\"web browser\"", "]", ".", "lower", "(", ")", "data_dir", "=", "Path", "(", "config", "[", "\"data dir\"", "]", ")", "if", "browser", "in", "webbrowser", ".", "_browsers", ":", "b", "=", "webbrowser", ".", "get", "(", "browser", ")", "else", ":", "if", "browser", "!=", "\"default\"", ":", "logger", ".", "warning", "(", "\"Couldn't find '%s' browser. Falling back to default.\"", ",", "browser", ")", "b", "=", "webbrowser", ".", "get", "(", ")", "index_file", "=", "data_dir", ".", "joinpath", "(", "\"index.html\"", ")", "if", "not", "index_file", ".", "exists", "(", ")", ":", "logger", ".", "error", "(", "\"File doesn't exist: %s\"", ",", "index_file", ".", "as_posix", "(", ")", ")", "raise", "FileNotFoundError", "(", "\"Index file doesn't exist\"", ")", "else", ":", "logger", ".", "info", "(", "\"Opening %s in '%s'\"", ",", "index_file", ".", "as_posix", "(", ")", ",", "b", ".", "name", ")", "b", ".", "open", "(", "index_file", ".", "as_uri", "(", ")", ")" ]
Open index in web browser. Parameters ---------- config : Config Configuration settings. Raises ------ FileNotFoundError If index file doesn't exist.
[ "Open", "index", "in", "web", "browser", "." ]
53721cdf75db04e2edca5ed3f99beae7c079d980
https://github.com/silenc3r/dikicli/blob/53721cdf75db04e2edca5ed3f99beae7c079d980/dikicli/core.py#L540-L569
241,942
silenc3r/dikicli
dikicli/core.py
wrap_text
def wrap_text(translations, linewrap=0): """Pretty print translations. If linewrap is set to 0 disble line wrapping. Parameters ---------- translations : list List of word translations. linewrap : int Maximum line length before wrapping. """ # pylint: disable=too-many-locals def wrap(text, width=linewrap, findent=0, sindent=0, bold=False): if width == 0: text = " " * findent + text else: text = textwrap.fill( text, width=width, initial_indent=" " * findent, subsequent_indent=" " * sindent, ) # don't use bold when stdout is pipe or redirect if bold and sys.stdout.isatty(): text = "\033[0;1m" + text + "\033[0m" return text indent = 5 result = [] for i1, trans in enumerate(translations): if i1 > 0: result.append("\n") for w in trans.word: result.append(wrap(w, bold=True)) for i2, t in enumerate(trans.parts_of_speech): if i2 > 0: result.append("") if t.part: result.append("[{part}]".format(part=t.part)) for i3, m in enumerate(t.meanings, 1): if i3 > 1: result.append("") meaning = "{index:>3}. {meanings}".format( index=i3, meanings=", ".join(m.meaning) ) result.append(wrap(meaning, sindent=indent, bold=True)) eindent = indent + 1 for e in m.examples: result.append("") result.append(wrap(e[0], findent=eindent, sindent=eindent)) if len(e) == 2 and e[1]: result.append(wrap(e[1], findent=eindent, sindent=eindent + 1)) return "\n".join(result)
python
def wrap_text(translations, linewrap=0): """Pretty print translations. If linewrap is set to 0 disble line wrapping. Parameters ---------- translations : list List of word translations. linewrap : int Maximum line length before wrapping. """ # pylint: disable=too-many-locals def wrap(text, width=linewrap, findent=0, sindent=0, bold=False): if width == 0: text = " " * findent + text else: text = textwrap.fill( text, width=width, initial_indent=" " * findent, subsequent_indent=" " * sindent, ) # don't use bold when stdout is pipe or redirect if bold and sys.stdout.isatty(): text = "\033[0;1m" + text + "\033[0m" return text indent = 5 result = [] for i1, trans in enumerate(translations): if i1 > 0: result.append("\n") for w in trans.word: result.append(wrap(w, bold=True)) for i2, t in enumerate(trans.parts_of_speech): if i2 > 0: result.append("") if t.part: result.append("[{part}]".format(part=t.part)) for i3, m in enumerate(t.meanings, 1): if i3 > 1: result.append("") meaning = "{index:>3}. {meanings}".format( index=i3, meanings=", ".join(m.meaning) ) result.append(wrap(meaning, sindent=indent, bold=True)) eindent = indent + 1 for e in m.examples: result.append("") result.append(wrap(e[0], findent=eindent, sindent=eindent)) if len(e) == 2 and e[1]: result.append(wrap(e[1], findent=eindent, sindent=eindent + 1)) return "\n".join(result)
[ "def", "wrap_text", "(", "translations", ",", "linewrap", "=", "0", ")", ":", "# pylint: disable=too-many-locals", "def", "wrap", "(", "text", ",", "width", "=", "linewrap", ",", "findent", "=", "0", ",", "sindent", "=", "0", ",", "bold", "=", "False", ")", ":", "if", "width", "==", "0", ":", "text", "=", "\" \"", "*", "findent", "+", "text", "else", ":", "text", "=", "textwrap", ".", "fill", "(", "text", ",", "width", "=", "width", ",", "initial_indent", "=", "\" \"", "*", "findent", ",", "subsequent_indent", "=", "\" \"", "*", "sindent", ",", ")", "# don't use bold when stdout is pipe or redirect", "if", "bold", "and", "sys", ".", "stdout", ".", "isatty", "(", ")", ":", "text", "=", "\"\\033[0;1m\"", "+", "text", "+", "\"\\033[0m\"", "return", "text", "indent", "=", "5", "result", "=", "[", "]", "for", "i1", ",", "trans", "in", "enumerate", "(", "translations", ")", ":", "if", "i1", ">", "0", ":", "result", ".", "append", "(", "\"\\n\"", ")", "for", "w", "in", "trans", ".", "word", ":", "result", ".", "append", "(", "wrap", "(", "w", ",", "bold", "=", "True", ")", ")", "for", "i2", ",", "t", "in", "enumerate", "(", "trans", ".", "parts_of_speech", ")", ":", "if", "i2", ">", "0", ":", "result", ".", "append", "(", "\"\"", ")", "if", "t", ".", "part", ":", "result", ".", "append", "(", "\"[{part}]\"", ".", "format", "(", "part", "=", "t", ".", "part", ")", ")", "for", "i3", ",", "m", "in", "enumerate", "(", "t", ".", "meanings", ",", "1", ")", ":", "if", "i3", ">", "1", ":", "result", ".", "append", "(", "\"\"", ")", "meaning", "=", "\"{index:>3}. {meanings}\"", ".", "format", "(", "index", "=", "i3", ",", "meanings", "=", "\", \"", ".", "join", "(", "m", ".", "meaning", ")", ")", "result", ".", "append", "(", "wrap", "(", "meaning", ",", "sindent", "=", "indent", ",", "bold", "=", "True", ")", ")", "eindent", "=", "indent", "+", "1", "for", "e", "in", "m", ".", "examples", ":", "result", ".", "append", "(", "\"\"", ")", "result", ".", "append", "(", "wrap", "(", "e", "[", "0", "]", ",", "findent", "=", "eindent", ",", "sindent", "=", "eindent", ")", ")", "if", "len", "(", "e", ")", "==", "2", "and", "e", "[", "1", "]", ":", "result", ".", "append", "(", "wrap", "(", "e", "[", "1", "]", ",", "findent", "=", "eindent", ",", "sindent", "=", "eindent", "+", "1", ")", ")", "return", "\"\\n\"", ".", "join", "(", "result", ")" ]
Pretty print translations. If linewrap is set to 0 disble line wrapping. Parameters ---------- translations : list List of word translations. linewrap : int Maximum line length before wrapping.
[ "Pretty", "print", "translations", "." ]
53721cdf75db04e2edca5ed3f99beae7c079d980
https://github.com/silenc3r/dikicli/blob/53721cdf75db04e2edca5ed3f99beae7c079d980/dikicli/core.py#L572-L626
241,943
silenc3r/dikicli
dikicli/core.py
Config.read_config
def read_config(self): """ Read config from a file. Invalid config values will be discarded and defaults used in their place. """ _config = self.config["dikicli"] # TODO: what if file doesn't exist? if self.config_file.is_file(): logger.debug("Reading config file: %s", self.config_file.as_posix()) with open(self.config_file, mode="r") as f: self.config.read_file(f) # DIKI_DATA_DIR should always take precedence if it's set if "DIKI_DATA_DIR" in os.environ: _config["data dir"] = DATA_DIR.as_posix() w = _config.get("linewrap") try: w = int(w) if w < 0: raise ValueError() except ValueError: logger.warning("Config: Invalid linewrap value. Using default.") _config["linewrap"] = self.default_config["linewrap"] c = _config.get("colors") if c.lower() not in ["yes", "no", "true", "false"]: logger.warning("Config: Invalid colors value. Using default.") _config["colors"] = self.default_config["colors"]
python
def read_config(self): """ Read config from a file. Invalid config values will be discarded and defaults used in their place. """ _config = self.config["dikicli"] # TODO: what if file doesn't exist? if self.config_file.is_file(): logger.debug("Reading config file: %s", self.config_file.as_posix()) with open(self.config_file, mode="r") as f: self.config.read_file(f) # DIKI_DATA_DIR should always take precedence if it's set if "DIKI_DATA_DIR" in os.environ: _config["data dir"] = DATA_DIR.as_posix() w = _config.get("linewrap") try: w = int(w) if w < 0: raise ValueError() except ValueError: logger.warning("Config: Invalid linewrap value. Using default.") _config["linewrap"] = self.default_config["linewrap"] c = _config.get("colors") if c.lower() not in ["yes", "no", "true", "false"]: logger.warning("Config: Invalid colors value. Using default.") _config["colors"] = self.default_config["colors"]
[ "def", "read_config", "(", "self", ")", ":", "_config", "=", "self", ".", "config", "[", "\"dikicli\"", "]", "# TODO: what if file doesn't exist?", "if", "self", ".", "config_file", ".", "is_file", "(", ")", ":", "logger", ".", "debug", "(", "\"Reading config file: %s\"", ",", "self", ".", "config_file", ".", "as_posix", "(", ")", ")", "with", "open", "(", "self", ".", "config_file", ",", "mode", "=", "\"r\"", ")", "as", "f", ":", "self", ".", "config", ".", "read_file", "(", "f", ")", "# DIKI_DATA_DIR should always take precedence if it's set", "if", "\"DIKI_DATA_DIR\"", "in", "os", ".", "environ", ":", "_config", "[", "\"data dir\"", "]", "=", "DATA_DIR", ".", "as_posix", "(", ")", "w", "=", "_config", ".", "get", "(", "\"linewrap\"", ")", "try", ":", "w", "=", "int", "(", "w", ")", "if", "w", "<", "0", ":", "raise", "ValueError", "(", ")", "except", "ValueError", ":", "logger", ".", "warning", "(", "\"Config: Invalid linewrap value. Using default.\"", ")", "_config", "[", "\"linewrap\"", "]", "=", "self", ".", "default_config", "[", "\"linewrap\"", "]", "c", "=", "_config", ".", "get", "(", "\"colors\"", ")", "if", "c", ".", "lower", "(", ")", "not", "in", "[", "\"yes\"", ",", "\"no\"", ",", "\"true\"", ",", "\"false\"", "]", ":", "logger", ".", "warning", "(", "\"Config: Invalid colors value. Using default.\"", ")", "_config", "[", "\"colors\"", "]", "=", "self", ".", "default_config", "[", "\"colors\"", "]" ]
Read config from a file. Invalid config values will be discarded and defaults used in their place.
[ "Read", "config", "from", "a", "file", "." ]
53721cdf75db04e2edca5ed3f99beae7c079d980
https://github.com/silenc3r/dikicli/blob/53721cdf75db04e2edca5ed3f99beae7c079d980/dikicli/core.py#L71-L101
241,944
silenc3r/dikicli
dikicli/core.py
Config.create_default_config
def create_default_config(self): """Write default config file to disk. Backs up existing configuration file. Returns ------- filename : string Path to config file. """ filename = self.config_file.as_posix() logger.info("Creating default config file: %s", filename) config_dir = self.config_file.parent if not config_dir.exists(): config_dir.mkdir(parents=True) if self.config_file.is_file(): backup = filename + ".old" logger.info("Saving config file backup at: %s", backup) shutil.copy(filename, backup) with open(self.config_file, mode="w") as f: config_string = CONFIG_TEMPLATE.format( data_dir=self.default_config["data dir"], linewrap=self.default_config["linewrap"], colors=self.default_config["colors"], browser=self.default_config["web browser"], ) f.write(config_string) return filename
python
def create_default_config(self): """Write default config file to disk. Backs up existing configuration file. Returns ------- filename : string Path to config file. """ filename = self.config_file.as_posix() logger.info("Creating default config file: %s", filename) config_dir = self.config_file.parent if not config_dir.exists(): config_dir.mkdir(parents=True) if self.config_file.is_file(): backup = filename + ".old" logger.info("Saving config file backup at: %s", backup) shutil.copy(filename, backup) with open(self.config_file, mode="w") as f: config_string = CONFIG_TEMPLATE.format( data_dir=self.default_config["data dir"], linewrap=self.default_config["linewrap"], colors=self.default_config["colors"], browser=self.default_config["web browser"], ) f.write(config_string) return filename
[ "def", "create_default_config", "(", "self", ")", ":", "filename", "=", "self", ".", "config_file", ".", "as_posix", "(", ")", "logger", ".", "info", "(", "\"Creating default config file: %s\"", ",", "filename", ")", "config_dir", "=", "self", ".", "config_file", ".", "parent", "if", "not", "config_dir", ".", "exists", "(", ")", ":", "config_dir", ".", "mkdir", "(", "parents", "=", "True", ")", "if", "self", ".", "config_file", ".", "is_file", "(", ")", ":", "backup", "=", "filename", "+", "\".old\"", "logger", ".", "info", "(", "\"Saving config file backup at: %s\"", ",", "backup", ")", "shutil", ".", "copy", "(", "filename", ",", "backup", ")", "with", "open", "(", "self", ".", "config_file", ",", "mode", "=", "\"w\"", ")", "as", "f", ":", "config_string", "=", "CONFIG_TEMPLATE", ".", "format", "(", "data_dir", "=", "self", ".", "default_config", "[", "\"data dir\"", "]", ",", "linewrap", "=", "self", ".", "default_config", "[", "\"linewrap\"", "]", ",", "colors", "=", "self", ".", "default_config", "[", "\"colors\"", "]", ",", "browser", "=", "self", ".", "default_config", "[", "\"web browser\"", "]", ",", ")", "f", ".", "write", "(", "config_string", ")", "return", "filename" ]
Write default config file to disk. Backs up existing configuration file. Returns ------- filename : string Path to config file.
[ "Write", "default", "config", "file", "to", "disk", "." ]
53721cdf75db04e2edca5ed3f99beae7c079d980
https://github.com/silenc3r/dikicli/blob/53721cdf75db04e2edca5ed3f99beae7c079d980/dikicli/core.py#L103-L130
241,945
DaveMcEwan/ndim
ndim_arc.py
arc_length
def arc_length(start_a=[0.0], end_a=[0.0], radius=0.0): '''Return Euclidean length of arc. ''' assert isinstance(start_a, list) assert isinstance(end_a, list) l_angle = len(start_a) assert l_angle > 0 assert l_angle == len(end_a) for i in start_a: assert isinstance(i, float) assert abs(i) <= 2*pi for i in end_a: assert isinstance(i, float) assert abs(i) <= 2*pi assert isinstance(radius, float) # Allow negative radius full = pi * radius*2 diff = angle_diff(start_a, end_a, True) vec = [full * abs(d)/(2*pi) for d in diff] return sqrt(sum([v**2 for v in vec]))
python
def arc_length(start_a=[0.0], end_a=[0.0], radius=0.0): '''Return Euclidean length of arc. ''' assert isinstance(start_a, list) assert isinstance(end_a, list) l_angle = len(start_a) assert l_angle > 0 assert l_angle == len(end_a) for i in start_a: assert isinstance(i, float) assert abs(i) <= 2*pi for i in end_a: assert isinstance(i, float) assert abs(i) <= 2*pi assert isinstance(radius, float) # Allow negative radius full = pi * radius*2 diff = angle_diff(start_a, end_a, True) vec = [full * abs(d)/(2*pi) for d in diff] return sqrt(sum([v**2 for v in vec]))
[ "def", "arc_length", "(", "start_a", "=", "[", "0.0", "]", ",", "end_a", "=", "[", "0.0", "]", ",", "radius", "=", "0.0", ")", ":", "assert", "isinstance", "(", "start_a", ",", "list", ")", "assert", "isinstance", "(", "end_a", ",", "list", ")", "l_angle", "=", "len", "(", "start_a", ")", "assert", "l_angle", ">", "0", "assert", "l_angle", "==", "len", "(", "end_a", ")", "for", "i", "in", "start_a", ":", "assert", "isinstance", "(", "i", ",", "float", ")", "assert", "abs", "(", "i", ")", "<=", "2", "*", "pi", "for", "i", "in", "end_a", ":", "assert", "isinstance", "(", "i", ",", "float", ")", "assert", "abs", "(", "i", ")", "<=", "2", "*", "pi", "assert", "isinstance", "(", "radius", ",", "float", ")", "# Allow negative radius", "full", "=", "pi", "*", "radius", "*", "2", "diff", "=", "angle_diff", "(", "start_a", ",", "end_a", ",", "True", ")", "vec", "=", "[", "full", "*", "abs", "(", "d", ")", "/", "(", "2", "*", "pi", ")", "for", "d", "in", "diff", "]", "return", "sqrt", "(", "sum", "(", "[", "v", "**", "2", "for", "v", "in", "vec", "]", ")", ")" ]
Return Euclidean length of arc.
[ "Return", "Euclidean", "length", "of", "arc", "." ]
f1ea023d3e597160fc1e9e11921de07af659f9d2
https://github.com/DaveMcEwan/ndim/blob/f1ea023d3e597160fc1e9e11921de07af659f9d2/ndim_arc.py#L41-L61
241,946
alexkreimer/django-pagination
pagination/templatetags/pagination_tags.py
do_autopaginate
def do_autopaginate(parser, token): """ Splits the arguments to the autopaginate tag and formats them correctly. """ split = token.split_contents() as_index = None context_var = None for i, bit in enumerate(split): if bit == 'as': as_index = i break if as_index is not None: try: context_var = split[as_index + 1] except IndexError: raise template.TemplateSyntaxError("Context variable assignment " + "must take the form of {%% %r object.example_set.all ... as " + "context_var_name %%}" % split[0]) del split[as_index:as_index + 2] if len(split) == 2: return AutoPaginateNode(split[1]) elif len(split) == 3: return AutoPaginateNode(split[1], paginate_by=split[2], context_var=context_var) elif len(split) == 4: try: orphans = int(split[3]) except ValueError: raise template.TemplateSyntaxError(u'Got %s, but expected integer.' % split[3]) return AutoPaginateNode(split[1], paginate_by=split[2], orphans=orphans, context_var=context_var) else: raise template.TemplateSyntaxError('%r tag takes one required ' + 'argument and one optional argument' % split[0])
python
def do_autopaginate(parser, token): """ Splits the arguments to the autopaginate tag and formats them correctly. """ split = token.split_contents() as_index = None context_var = None for i, bit in enumerate(split): if bit == 'as': as_index = i break if as_index is not None: try: context_var = split[as_index + 1] except IndexError: raise template.TemplateSyntaxError("Context variable assignment " + "must take the form of {%% %r object.example_set.all ... as " + "context_var_name %%}" % split[0]) del split[as_index:as_index + 2] if len(split) == 2: return AutoPaginateNode(split[1]) elif len(split) == 3: return AutoPaginateNode(split[1], paginate_by=split[2], context_var=context_var) elif len(split) == 4: try: orphans = int(split[3]) except ValueError: raise template.TemplateSyntaxError(u'Got %s, but expected integer.' % split[3]) return AutoPaginateNode(split[1], paginate_by=split[2], orphans=orphans, context_var=context_var) else: raise template.TemplateSyntaxError('%r tag takes one required ' + 'argument and one optional argument' % split[0])
[ "def", "do_autopaginate", "(", "parser", ",", "token", ")", ":", "split", "=", "token", ".", "split_contents", "(", ")", "as_index", "=", "None", "context_var", "=", "None", "for", "i", ",", "bit", "in", "enumerate", "(", "split", ")", ":", "if", "bit", "==", "'as'", ":", "as_index", "=", "i", "break", "if", "as_index", "is", "not", "None", ":", "try", ":", "context_var", "=", "split", "[", "as_index", "+", "1", "]", "except", "IndexError", ":", "raise", "template", ".", "TemplateSyntaxError", "(", "\"Context variable assignment \"", "+", "\"must take the form of {%% %r object.example_set.all ... as \"", "+", "\"context_var_name %%}\"", "%", "split", "[", "0", "]", ")", "del", "split", "[", "as_index", ":", "as_index", "+", "2", "]", "if", "len", "(", "split", ")", "==", "2", ":", "return", "AutoPaginateNode", "(", "split", "[", "1", "]", ")", "elif", "len", "(", "split", ")", "==", "3", ":", "return", "AutoPaginateNode", "(", "split", "[", "1", "]", ",", "paginate_by", "=", "split", "[", "2", "]", ",", "context_var", "=", "context_var", ")", "elif", "len", "(", "split", ")", "==", "4", ":", "try", ":", "orphans", "=", "int", "(", "split", "[", "3", "]", ")", "except", "ValueError", ":", "raise", "template", ".", "TemplateSyntaxError", "(", "u'Got %s, but expected integer.'", "%", "split", "[", "3", "]", ")", "return", "AutoPaginateNode", "(", "split", "[", "1", "]", ",", "paginate_by", "=", "split", "[", "2", "]", ",", "orphans", "=", "orphans", ",", "context_var", "=", "context_var", ")", "else", ":", "raise", "template", ".", "TemplateSyntaxError", "(", "'%r tag takes one required '", "+", "'argument and one optional argument'", "%", "split", "[", "0", "]", ")" ]
Splits the arguments to the autopaginate tag and formats them correctly.
[ "Splits", "the", "arguments", "to", "the", "autopaginate", "tag", "and", "formats", "them", "correctly", "." ]
428e6b2277ed663fea7ce1a7006974d9f28d3ee5
https://github.com/alexkreimer/django-pagination/blob/428e6b2277ed663fea7ce1a7006974d9f28d3ee5/pagination/templatetags/pagination_tags.py#L19-L53
241,947
mayfield/shellish
shellish/command/__init__.py
linebuffered_stdout
def linebuffered_stdout(): """ Always line buffer stdout so pipes and redirects are CLI friendly. """ if sys.stdout.line_buffering: return sys.stdout orig = sys.stdout new = type(orig)(orig.buffer, encoding=orig.encoding, errors=orig.errors, line_buffering=True) new.mode = orig.mode return new
python
def linebuffered_stdout(): """ Always line buffer stdout so pipes and redirects are CLI friendly. """ if sys.stdout.line_buffering: return sys.stdout orig = sys.stdout new = type(orig)(orig.buffer, encoding=orig.encoding, errors=orig.errors, line_buffering=True) new.mode = orig.mode return new
[ "def", "linebuffered_stdout", "(", ")", ":", "if", "sys", ".", "stdout", ".", "line_buffering", ":", "return", "sys", ".", "stdout", "orig", "=", "sys", ".", "stdout", "new", "=", "type", "(", "orig", ")", "(", "orig", ".", "buffer", ",", "encoding", "=", "orig", ".", "encoding", ",", "errors", "=", "orig", ".", "errors", ",", "line_buffering", "=", "True", ")", "new", ".", "mode", "=", "orig", ".", "mode", "return", "new" ]
Always line buffer stdout so pipes and redirects are CLI friendly.
[ "Always", "line", "buffer", "stdout", "so", "pipes", "and", "redirects", "are", "CLI", "friendly", "." ]
df0f0e4612d138c34d8cb99b66ab5b8e47f1414a
https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/command/__init__.py#L6-L14
241,948
mayfield/shellish
shellish/command/__init__.py
ignore_broken_pipe
def ignore_broken_pipe(): """ If a shellish program has redirected stdio it is subject to erroneous "ignored" exceptions during the interpretor shutdown. This essentially beats the interpretor to the punch by closing them early and ignoring any broken pipe exceptions. """ for f in sys.stdin, sys.stdout, sys.stderr: try: f.close() except BrokenPipeError: pass
python
def ignore_broken_pipe(): """ If a shellish program has redirected stdio it is subject to erroneous "ignored" exceptions during the interpretor shutdown. This essentially beats the interpretor to the punch by closing them early and ignoring any broken pipe exceptions. """ for f in sys.stdin, sys.stdout, sys.stderr: try: f.close() except BrokenPipeError: pass
[ "def", "ignore_broken_pipe", "(", ")", ":", "for", "f", "in", "sys", ".", "stdin", ",", "sys", ".", "stdout", ",", "sys", ".", "stderr", ":", "try", ":", "f", ".", "close", "(", ")", "except", "BrokenPipeError", ":", "pass" ]
If a shellish program has redirected stdio it is subject to erroneous "ignored" exceptions during the interpretor shutdown. This essentially beats the interpretor to the punch by closing them early and ignoring any broken pipe exceptions.
[ "If", "a", "shellish", "program", "has", "redirected", "stdio", "it", "is", "subject", "to", "erroneous", "ignored", "exceptions", "during", "the", "interpretor", "shutdown", ".", "This", "essentially", "beats", "the", "interpretor", "to", "the", "punch", "by", "closing", "them", "early", "and", "ignoring", "any", "broken", "pipe", "exceptions", "." ]
df0f0e4612d138c34d8cb99b66ab5b8e47f1414a
https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/command/__init__.py#L19-L28
241,949
TAPPGuild/flask-bitjws
flask_bitjws.py
get_last_nonce
def get_last_nonce(app, key, nonce): """ This method is only an example! Replace it with a real nonce database. :param str key: the public key the nonce belongs to :param int nonce: the latest nonce """ if not hasattr(app, 'example_nonce_db'): # store nonces as a pair {key: lastnonce} app.example_nonce_db = {} if not key in app.example_nonce_db: app.example_nonce_db[key] = nonce return 0 else: oldnonce = copy.copy(app.example_nonce_db[key]) app.example_nonce_db[key] = nonce return oldnonce
python
def get_last_nonce(app, key, nonce): """ This method is only an example! Replace it with a real nonce database. :param str key: the public key the nonce belongs to :param int nonce: the latest nonce """ if not hasattr(app, 'example_nonce_db'): # store nonces as a pair {key: lastnonce} app.example_nonce_db = {} if not key in app.example_nonce_db: app.example_nonce_db[key] = nonce return 0 else: oldnonce = copy.copy(app.example_nonce_db[key]) app.example_nonce_db[key] = nonce return oldnonce
[ "def", "get_last_nonce", "(", "app", ",", "key", ",", "nonce", ")", ":", "if", "not", "hasattr", "(", "app", ",", "'example_nonce_db'", ")", ":", "# store nonces as a pair {key: lastnonce}", "app", ".", "example_nonce_db", "=", "{", "}", "if", "not", "key", "in", "app", ".", "example_nonce_db", ":", "app", ".", "example_nonce_db", "[", "key", "]", "=", "nonce", "return", "0", "else", ":", "oldnonce", "=", "copy", ".", "copy", "(", "app", ".", "example_nonce_db", "[", "key", "]", ")", "app", ".", "example_nonce_db", "[", "key", "]", "=", "nonce", "return", "oldnonce" ]
This method is only an example! Replace it with a real nonce database. :param str key: the public key the nonce belongs to :param int nonce: the latest nonce
[ "This", "method", "is", "only", "an", "example!", "Replace", "it", "with", "a", "real", "nonce", "database", "." ]
8f71b048a2d23c704ab1a84c3ee2f05914bb8347
https://github.com/TAPPGuild/flask-bitjws/blob/8f71b048a2d23c704ab1a84c3ee2f05914bb8347/flask_bitjws.py#L16-L32
241,950
TAPPGuild/flask-bitjws
flask_bitjws.py
get_user_by_key
def get_user_by_key(app, key): """ This method is only an example! Replace it with a real user database. :param str key: the public key the user belongs to """ if not hasattr(app, 'example_user_db'): app.example_user_db = {} if key in app.example_user_db: return app.example_user_db[key] return None
python
def get_user_by_key(app, key): """ This method is only an example! Replace it with a real user database. :param str key: the public key the user belongs to """ if not hasattr(app, 'example_user_db'): app.example_user_db = {} if key in app.example_user_db: return app.example_user_db[key] return None
[ "def", "get_user_by_key", "(", "app", ",", "key", ")", ":", "if", "not", "hasattr", "(", "app", ",", "'example_user_db'", ")", ":", "app", ".", "example_user_db", "=", "{", "}", "if", "key", "in", "app", ".", "example_user_db", ":", "return", "app", ".", "example_user_db", "[", "key", "]", "return", "None" ]
This method is only an example! Replace it with a real user database. :param str key: the public key the user belongs to
[ "This", "method", "is", "only", "an", "example!", "Replace", "it", "with", "a", "real", "user", "database", "." ]
8f71b048a2d23c704ab1a84c3ee2f05914bb8347
https://github.com/TAPPGuild/flask-bitjws/blob/8f71b048a2d23c704ab1a84c3ee2f05914bb8347/flask_bitjws.py#L35-L46
241,951
TAPPGuild/flask-bitjws
flask_bitjws.py
load_jws_from_request
def load_jws_from_request(req): """ This function performs almost entirely bitjws authentication tasks. If valid bitjws message and signature headers are found, then the request will be assigned 'jws_header' and 'jws_payload' attributes. :param req: The flask request to load the jwt claim set from. """ current_app.logger.info("loading request with headers: %s" % req.headers) if (("content-type" in req.headers and "application/jose" in req.headers['content-type']) or ("Content-Type" in req.headers and "application/jose" in req.headers['Content-Type'])): path = urlparse.urlsplit(req.url).path for rule in current_app.url_map.iter_rules(): if path == rule.rule and req.method in rule.methods: dedata = req.get_data().decode('utf8') bp = current_app.bitjws.basepath req.jws_header, req.jws_payload = \ bitjws.validate_deserialize(dedata, requrl=bp + rule.rule) break
python
def load_jws_from_request(req): """ This function performs almost entirely bitjws authentication tasks. If valid bitjws message and signature headers are found, then the request will be assigned 'jws_header' and 'jws_payload' attributes. :param req: The flask request to load the jwt claim set from. """ current_app.logger.info("loading request with headers: %s" % req.headers) if (("content-type" in req.headers and "application/jose" in req.headers['content-type']) or ("Content-Type" in req.headers and "application/jose" in req.headers['Content-Type'])): path = urlparse.urlsplit(req.url).path for rule in current_app.url_map.iter_rules(): if path == rule.rule and req.method in rule.methods: dedata = req.get_data().decode('utf8') bp = current_app.bitjws.basepath req.jws_header, req.jws_payload = \ bitjws.validate_deserialize(dedata, requrl=bp + rule.rule) break
[ "def", "load_jws_from_request", "(", "req", ")", ":", "current_app", ".", "logger", ".", "info", "(", "\"loading request with headers: %s\"", "%", "req", ".", "headers", ")", "if", "(", "(", "\"content-type\"", "in", "req", ".", "headers", "and", "\"application/jose\"", "in", "req", ".", "headers", "[", "'content-type'", "]", ")", "or", "(", "\"Content-Type\"", "in", "req", ".", "headers", "and", "\"application/jose\"", "in", "req", ".", "headers", "[", "'Content-Type'", "]", ")", ")", ":", "path", "=", "urlparse", ".", "urlsplit", "(", "req", ".", "url", ")", ".", "path", "for", "rule", "in", "current_app", ".", "url_map", ".", "iter_rules", "(", ")", ":", "if", "path", "==", "rule", ".", "rule", "and", "req", ".", "method", "in", "rule", ".", "methods", ":", "dedata", "=", "req", ".", "get_data", "(", ")", ".", "decode", "(", "'utf8'", ")", "bp", "=", "current_app", ".", "bitjws", ".", "basepath", "req", ".", "jws_header", ",", "req", ".", "jws_payload", "=", "bitjws", ".", "validate_deserialize", "(", "dedata", ",", "requrl", "=", "bp", "+", "rule", ".", "rule", ")", "break" ]
This function performs almost entirely bitjws authentication tasks. If valid bitjws message and signature headers are found, then the request will be assigned 'jws_header' and 'jws_payload' attributes. :param req: The flask request to load the jwt claim set from.
[ "This", "function", "performs", "almost", "entirely", "bitjws", "authentication", "tasks", ".", "If", "valid", "bitjws", "message", "and", "signature", "headers", "are", "found", "then", "the", "request", "will", "be", "assigned", "jws_header", "and", "jws_payload", "attributes", "." ]
8f71b048a2d23c704ab1a84c3ee2f05914bb8347
https://github.com/TAPPGuild/flask-bitjws/blob/8f71b048a2d23c704ab1a84c3ee2f05914bb8347/flask_bitjws.py#L52-L72
241,952
TAPPGuild/flask-bitjws
flask_bitjws.py
load_user_from_request
def load_user_from_request(req): """ Just like the Flask.login load_user_from_request If you need to customize the user loading from your database, the FlaskBitjws.get_user_by_key method is the one to modify. :param req: The flask request to load a user based on. """ load_jws_from_request(req) if not hasattr(req, 'jws_header') or req.jws_header is None or not \ 'iat' in req.jws_payload: current_app.logger.info("invalid jws request.") return None ln = current_app.bitjws.get_last_nonce(current_app, req.jws_header['kid'], req.jws_payload['iat']) if (ln is None or 'iat' not in req.jws_payload or req.jws_payload['iat'] * 1000 <= ln): current_app.logger.info("invalid nonce. lastnonce: %s" % ln) return None rawu = current_app.bitjws.get_user_by_key(current_app, req.jws_header['kid']) if rawu is None: return None current_app.logger.info("logging in user: %s" % rawu) return FlaskUser(rawu)
python
def load_user_from_request(req): """ Just like the Flask.login load_user_from_request If you need to customize the user loading from your database, the FlaskBitjws.get_user_by_key method is the one to modify. :param req: The flask request to load a user based on. """ load_jws_from_request(req) if not hasattr(req, 'jws_header') or req.jws_header is None or not \ 'iat' in req.jws_payload: current_app.logger.info("invalid jws request.") return None ln = current_app.bitjws.get_last_nonce(current_app, req.jws_header['kid'], req.jws_payload['iat']) if (ln is None or 'iat' not in req.jws_payload or req.jws_payload['iat'] * 1000 <= ln): current_app.logger.info("invalid nonce. lastnonce: %s" % ln) return None rawu = current_app.bitjws.get_user_by_key(current_app, req.jws_header['kid']) if rawu is None: return None current_app.logger.info("logging in user: %s" % rawu) return FlaskUser(rawu)
[ "def", "load_user_from_request", "(", "req", ")", ":", "load_jws_from_request", "(", "req", ")", "if", "not", "hasattr", "(", "req", ",", "'jws_header'", ")", "or", "req", ".", "jws_header", "is", "None", "or", "not", "'iat'", "in", "req", ".", "jws_payload", ":", "current_app", ".", "logger", ".", "info", "(", "\"invalid jws request.\"", ")", "return", "None", "ln", "=", "current_app", ".", "bitjws", ".", "get_last_nonce", "(", "current_app", ",", "req", ".", "jws_header", "[", "'kid'", "]", ",", "req", ".", "jws_payload", "[", "'iat'", "]", ")", "if", "(", "ln", "is", "None", "or", "'iat'", "not", "in", "req", ".", "jws_payload", "or", "req", ".", "jws_payload", "[", "'iat'", "]", "*", "1000", "<=", "ln", ")", ":", "current_app", ".", "logger", ".", "info", "(", "\"invalid nonce. lastnonce: %s\"", "%", "ln", ")", "return", "None", "rawu", "=", "current_app", ".", "bitjws", ".", "get_user_by_key", "(", "current_app", ",", "req", ".", "jws_header", "[", "'kid'", "]", ")", "if", "rawu", "is", "None", ":", "return", "None", "current_app", ".", "logger", ".", "info", "(", "\"logging in user: %s\"", "%", "rawu", ")", "return", "FlaskUser", "(", "rawu", ")" ]
Just like the Flask.login load_user_from_request If you need to customize the user loading from your database, the FlaskBitjws.get_user_by_key method is the one to modify. :param req: The flask request to load a user based on.
[ "Just", "like", "the", "Flask", ".", "login", "load_user_from_request" ]
8f71b048a2d23c704ab1a84c3ee2f05914bb8347
https://github.com/TAPPGuild/flask-bitjws/blob/8f71b048a2d23c704ab1a84c3ee2f05914bb8347/flask_bitjws.py#L75-L104
241,953
mgbarrero/xbob.db.atvskeystroke
xbob/db/atvskeystroke/driver.py
dumplist
def dumplist(args): """Dumps lists of files based on your criteria""" from .query import Database db = Database() r = db.objects( protocol=args.protocol, purposes=args.purpose, model_ids=(args.client,), groups=args.group, classes=args.sclass ) output = sys.stdout if args.selftest: from bob.db.utils import null output = null() for f in r: output.write('%s\n' % (f.make_path(args.directory, args.extension),)) return 0
python
def dumplist(args): """Dumps lists of files based on your criteria""" from .query import Database db = Database() r = db.objects( protocol=args.protocol, purposes=args.purpose, model_ids=(args.client,), groups=args.group, classes=args.sclass ) output = sys.stdout if args.selftest: from bob.db.utils import null output = null() for f in r: output.write('%s\n' % (f.make_path(args.directory, args.extension),)) return 0
[ "def", "dumplist", "(", "args", ")", ":", "from", ".", "query", "import", "Database", "db", "=", "Database", "(", ")", "r", "=", "db", ".", "objects", "(", "protocol", "=", "args", ".", "protocol", ",", "purposes", "=", "args", ".", "purpose", ",", "model_ids", "=", "(", "args", ".", "client", ",", ")", ",", "groups", "=", "args", ".", "group", ",", "classes", "=", "args", ".", "sclass", ")", "output", "=", "sys", ".", "stdout", "if", "args", ".", "selftest", ":", "from", "bob", ".", "db", ".", "utils", "import", "null", "output", "=", "null", "(", ")", "for", "f", "in", "r", ":", "output", ".", "write", "(", "'%s\\n'", "%", "(", "f", ".", "make_path", "(", "args", ".", "directory", ",", "args", ".", "extension", ")", ",", ")", ")", "return", "0" ]
Dumps lists of files based on your criteria
[ "Dumps", "lists", "of", "files", "based", "on", "your", "criteria" ]
b7358a73e21757b43334df7c89ba057b377ca704
https://github.com/mgbarrero/xbob.db.atvskeystroke/blob/b7358a73e21757b43334df7c89ba057b377ca704/xbob/db/atvskeystroke/driver.py#L23-L45
241,954
mgbarrero/xbob.db.atvskeystroke
xbob/db/atvskeystroke/driver.py
checkfiles
def checkfiles(args): """Checks existence of files based on your criteria""" from .query import Database db = Database() r = db.objects() # go through all files, check if they are available on the filesystem good = [] bad = [] for f in r: if os.path.exists(f.make_path(args.directory, args.extension)): good.append(f) else: bad.append(f) # report output = sys.stdout if args.selftest: from bob.db.utils import null output = null() if bad: for f in bad: output.write('Cannot find file "%s"\n' % (f.make_path(args.directory, args.extension),)) output.write('%d files (out of %d) were not found at "%s"\n' % \ (len(bad), len(r), args.directory)) return 0
python
def checkfiles(args): """Checks existence of files based on your criteria""" from .query import Database db = Database() r = db.objects() # go through all files, check if they are available on the filesystem good = [] bad = [] for f in r: if os.path.exists(f.make_path(args.directory, args.extension)): good.append(f) else: bad.append(f) # report output = sys.stdout if args.selftest: from bob.db.utils import null output = null() if bad: for f in bad: output.write('Cannot find file "%s"\n' % (f.make_path(args.directory, args.extension),)) output.write('%d files (out of %d) were not found at "%s"\n' % \ (len(bad), len(r), args.directory)) return 0
[ "def", "checkfiles", "(", "args", ")", ":", "from", ".", "query", "import", "Database", "db", "=", "Database", "(", ")", "r", "=", "db", ".", "objects", "(", ")", "# go through all files, check if they are available on the filesystem", "good", "=", "[", "]", "bad", "=", "[", "]", "for", "f", "in", "r", ":", "if", "os", ".", "path", ".", "exists", "(", "f", ".", "make_path", "(", "args", ".", "directory", ",", "args", ".", "extension", ")", ")", ":", "good", ".", "append", "(", "f", ")", "else", ":", "bad", ".", "append", "(", "f", ")", "# report", "output", "=", "sys", ".", "stdout", "if", "args", ".", "selftest", ":", "from", "bob", ".", "db", ".", "utils", "import", "null", "output", "=", "null", "(", ")", "if", "bad", ":", "for", "f", "in", "bad", ":", "output", ".", "write", "(", "'Cannot find file \"%s\"\\n'", "%", "(", "f", ".", "make_path", "(", "args", ".", "directory", ",", "args", ".", "extension", ")", ",", ")", ")", "output", ".", "write", "(", "'%d files (out of %d) were not found at \"%s\"\\n'", "%", "(", "len", "(", "bad", ")", ",", "len", "(", "r", ")", ",", "args", ".", "directory", ")", ")", "return", "0" ]
Checks existence of files based on your criteria
[ "Checks", "existence", "of", "files", "based", "on", "your", "criteria" ]
b7358a73e21757b43334df7c89ba057b377ca704
https://github.com/mgbarrero/xbob.db.atvskeystroke/blob/b7358a73e21757b43334df7c89ba057b377ca704/xbob/db/atvskeystroke/driver.py#L47-L76
241,955
mgbarrero/xbob.db.atvskeystroke
xbob/db/atvskeystroke/driver.py
reverse
def reverse(args): """Returns a list of file database identifiers given the path stems""" from .query import Database db = Database() output = sys.stdout if args.selftest: from bob.db.utils import null output = null() r = db.reverse(args.path) for f in r: output.write('%d\n' % f.id) if not r: return 1 return 0
python
def reverse(args): """Returns a list of file database identifiers given the path stems""" from .query import Database db = Database() output = sys.stdout if args.selftest: from bob.db.utils import null output = null() r = db.reverse(args.path) for f in r: output.write('%d\n' % f.id) if not r: return 1 return 0
[ "def", "reverse", "(", "args", ")", ":", "from", ".", "query", "import", "Database", "db", "=", "Database", "(", ")", "output", "=", "sys", ".", "stdout", "if", "args", ".", "selftest", ":", "from", "bob", ".", "db", ".", "utils", "import", "null", "output", "=", "null", "(", ")", "r", "=", "db", ".", "reverse", "(", "args", ".", "path", ")", "for", "f", "in", "r", ":", "output", ".", "write", "(", "'%d\\n'", "%", "f", ".", "id", ")", "if", "not", "r", ":", "return", "1", "return", "0" ]
Returns a list of file database identifiers given the path stems
[ "Returns", "a", "list", "of", "file", "database", "identifiers", "given", "the", "path", "stems" ]
b7358a73e21757b43334df7c89ba057b377ca704
https://github.com/mgbarrero/xbob.db.atvskeystroke/blob/b7358a73e21757b43334df7c89ba057b377ca704/xbob/db/atvskeystroke/driver.py#L78-L94
241,956
mgbarrero/xbob.db.atvskeystroke
xbob/db/atvskeystroke/driver.py
path
def path(args): """Returns a list of fully formed paths or stems given some file id""" from .query import Database db = Database() output = sys.stdout if args.selftest: from bob.db.utils import null output = null() r = db.paths(args.id, prefix=args.directory, suffix=args.extension) for path in r: output.write('%s\n' % path) if not r: return 1 return 0
python
def path(args): """Returns a list of fully formed paths or stems given some file id""" from .query import Database db = Database() output = sys.stdout if args.selftest: from bob.db.utils import null output = null() r = db.paths(args.id, prefix=args.directory, suffix=args.extension) for path in r: output.write('%s\n' % path) if not r: return 1 return 0
[ "def", "path", "(", "args", ")", ":", "from", ".", "query", "import", "Database", "db", "=", "Database", "(", ")", "output", "=", "sys", ".", "stdout", "if", "args", ".", "selftest", ":", "from", "bob", ".", "db", ".", "utils", "import", "null", "output", "=", "null", "(", ")", "r", "=", "db", ".", "paths", "(", "args", ".", "id", ",", "prefix", "=", "args", ".", "directory", ",", "suffix", "=", "args", ".", "extension", ")", "for", "path", "in", "r", ":", "output", ".", "write", "(", "'%s\\n'", "%", "path", ")", "if", "not", "r", ":", "return", "1", "return", "0" ]
Returns a list of fully formed paths or stems given some file id
[ "Returns", "a", "list", "of", "fully", "formed", "paths", "or", "stems", "given", "some", "file", "id" ]
b7358a73e21757b43334df7c89ba057b377ca704
https://github.com/mgbarrero/xbob.db.atvskeystroke/blob/b7358a73e21757b43334df7c89ba057b377ca704/xbob/db/atvskeystroke/driver.py#L96-L112
241,957
timeyyy/apptools
peasoup/restart.py
Restarter.app_restart
def app_restart(cls): ''' Restart a frozen esky app Can also restart if the program is being run as a script passes restarted as an argument to the restarted app ''' logging.debug('In restarter') executable = sys.executable.split(os.sep)[-1] if os.name == 'nt': logging.info('executable is is %s' % executable) # restart works here when testing compiled version only if executable != 'python.exe': boot_strap_path = cls.esky_bootstrap_path() bootstrap_file = os.path.join(boot_strap_path, executable) logging.info('Bootstrap file for restart: %s' % bootstrap_file) subprocess.Popen( [os.path.join(bootstrap_file, bootstrap_file), 'restarted'])
python
def app_restart(cls): ''' Restart a frozen esky app Can also restart if the program is being run as a script passes restarted as an argument to the restarted app ''' logging.debug('In restarter') executable = sys.executable.split(os.sep)[-1] if os.name == 'nt': logging.info('executable is is %s' % executable) # restart works here when testing compiled version only if executable != 'python.exe': boot_strap_path = cls.esky_bootstrap_path() bootstrap_file = os.path.join(boot_strap_path, executable) logging.info('Bootstrap file for restart: %s' % bootstrap_file) subprocess.Popen( [os.path.join(bootstrap_file, bootstrap_file), 'restarted'])
[ "def", "app_restart", "(", "cls", ")", ":", "logging", ".", "debug", "(", "'In restarter'", ")", "executable", "=", "sys", ".", "executable", ".", "split", "(", "os", ".", "sep", ")", "[", "-", "1", "]", "if", "os", ".", "name", "==", "'nt'", ":", "logging", ".", "info", "(", "'executable is is %s'", "%", "executable", ")", "# restart works here when testing compiled version only", "if", "executable", "!=", "'python.exe'", ":", "boot_strap_path", "=", "cls", ".", "esky_bootstrap_path", "(", ")", "bootstrap_file", "=", "os", ".", "path", ".", "join", "(", "boot_strap_path", ",", "executable", ")", "logging", ".", "info", "(", "'Bootstrap file for restart: %s'", "%", "bootstrap_file", ")", "subprocess", ".", "Popen", "(", "[", "os", ".", "path", ".", "join", "(", "bootstrap_file", ",", "bootstrap_file", ")", ",", "'restarted'", "]", ")" ]
Restart a frozen esky app Can also restart if the program is being run as a script passes restarted as an argument to the restarted app
[ "Restart", "a", "frozen", "esky", "app", "Can", "also", "restart", "if", "the", "program", "is", "being", "run", "as", "a", "script", "passes", "restarted", "as", "an", "argument", "to", "the", "restarted", "app" ]
d3c0f324b0c2689c35f5601348276f4efd6cb240
https://github.com/timeyyy/apptools/blob/d3c0f324b0c2689c35f5601348276f4efd6cb240/peasoup/restart.py#L20-L37
241,958
unitedstack/steth
stetho/agent/drivers/iperf.py
IPerfDriver.start_client
def start_client(self, host, port=5001, protocol='TCP', timeout=5, parallel=None, bandwidth=None): """iperf -D -c host -t 60 """ cmd = ['iperf', '-c', host, '-p', str(port), '-t', str(timeout)] if not (protocol, 'UDP'): cmd.append('-u') if parallel: cmd.extend(['-P', str(parallel)]) if bandwidth: cmd.extend(['-b', '%sM' % bandwidth]) stdcode, stdout, stderr = utils.execute_wait(cmd) if (not stdcode) or (not stderr): out_dict = stdout.split('\n') if not out_dict[-1]: out_dict.pop() out_data = out_dict[-1].split() data = dict() data['Bandwidth'] = out_data[-2] + ' ' + out_data[-1] data['Transfer'] = out_data[-4] + ' ' + out_data[-3] data['Interval'] = out_data[-6] return data raise Exception('Start iperf failed, please check on the node.')
python
def start_client(self, host, port=5001, protocol='TCP', timeout=5, parallel=None, bandwidth=None): """iperf -D -c host -t 60 """ cmd = ['iperf', '-c', host, '-p', str(port), '-t', str(timeout)] if not (protocol, 'UDP'): cmd.append('-u') if parallel: cmd.extend(['-P', str(parallel)]) if bandwidth: cmd.extend(['-b', '%sM' % bandwidth]) stdcode, stdout, stderr = utils.execute_wait(cmd) if (not stdcode) or (not stderr): out_dict = stdout.split('\n') if not out_dict[-1]: out_dict.pop() out_data = out_dict[-1].split() data = dict() data['Bandwidth'] = out_data[-2] + ' ' + out_data[-1] data['Transfer'] = out_data[-4] + ' ' + out_data[-3] data['Interval'] = out_data[-6] return data raise Exception('Start iperf failed, please check on the node.')
[ "def", "start_client", "(", "self", ",", "host", ",", "port", "=", "5001", ",", "protocol", "=", "'TCP'", ",", "timeout", "=", "5", ",", "parallel", "=", "None", ",", "bandwidth", "=", "None", ")", ":", "cmd", "=", "[", "'iperf'", ",", "'-c'", ",", "host", ",", "'-p'", ",", "str", "(", "port", ")", ",", "'-t'", ",", "str", "(", "timeout", ")", "]", "if", "not", "(", "protocol", ",", "'UDP'", ")", ":", "cmd", ".", "append", "(", "'-u'", ")", "if", "parallel", ":", "cmd", ".", "extend", "(", "[", "'-P'", ",", "str", "(", "parallel", ")", "]", ")", "if", "bandwidth", ":", "cmd", ".", "extend", "(", "[", "'-b'", ",", "'%sM'", "%", "bandwidth", "]", ")", "stdcode", ",", "stdout", ",", "stderr", "=", "utils", ".", "execute_wait", "(", "cmd", ")", "if", "(", "not", "stdcode", ")", "or", "(", "not", "stderr", ")", ":", "out_dict", "=", "stdout", ".", "split", "(", "'\\n'", ")", "if", "not", "out_dict", "[", "-", "1", "]", ":", "out_dict", ".", "pop", "(", ")", "out_data", "=", "out_dict", "[", "-", "1", "]", ".", "split", "(", ")", "data", "=", "dict", "(", ")", "data", "[", "'Bandwidth'", "]", "=", "out_data", "[", "-", "2", "]", "+", "' '", "+", "out_data", "[", "-", "1", "]", "data", "[", "'Transfer'", "]", "=", "out_data", "[", "-", "4", "]", "+", "' '", "+", "out_data", "[", "-", "3", "]", "data", "[", "'Interval'", "]", "=", "out_data", "[", "-", "6", "]", "return", "data", "raise", "Exception", "(", "'Start iperf failed, please check on the node.'", ")" ]
iperf -D -c host -t 60
[ "iperf", "-", "D", "-", "c", "host", "-", "t", "60" ]
955884ceebf3bdc474c93cc5cf555e67d16458f1
https://github.com/unitedstack/steth/blob/955884ceebf3bdc474c93cc5cf555e67d16458f1/stetho/agent/drivers/iperf.py#L45-L67
241,959
codenerix/django-codenerix-extensions
codenerix_extensions/helpers.py
get_language_database
def get_language_database(): ''' Return the language to be used to search the database contents ''' lang = None language = get_language() if language: for x in settings.LANGUAGES_DATABASES: if x.upper() == language.upper(): lang = language break if lang is None: lang = settings.LANGUAGES_DATABASES[0] return lang.lower()
python
def get_language_database(): ''' Return the language to be used to search the database contents ''' lang = None language = get_language() if language: for x in settings.LANGUAGES_DATABASES: if x.upper() == language.upper(): lang = language break if lang is None: lang = settings.LANGUAGES_DATABASES[0] return lang.lower()
[ "def", "get_language_database", "(", ")", ":", "lang", "=", "None", "language", "=", "get_language", "(", ")", "if", "language", ":", "for", "x", "in", "settings", ".", "LANGUAGES_DATABASES", ":", "if", "x", ".", "upper", "(", ")", "==", "language", ".", "upper", "(", ")", ":", "lang", "=", "language", "break", "if", "lang", "is", "None", ":", "lang", "=", "settings", ".", "LANGUAGES_DATABASES", "[", "0", "]", "return", "lang", ".", "lower", "(", ")" ]
Return the language to be used to search the database contents
[ "Return", "the", "language", "to", "be", "used", "to", "search", "the", "database", "contents" ]
e9c1d6f99f3e05833ab103bed2689ec34d64e591
https://github.com/codenerix/django-codenerix-extensions/blob/e9c1d6f99f3e05833ab103bed2689ec34d64e591/codenerix_extensions/helpers.py#L78-L92
241,960
shaypal5/pdutil
pdutil/display/display.py
df_string
def df_string(df, percentage_columns=(), format_map=None, **kwargs): """Return a nicely formatted string for the given dataframe. Arguments --------- df : pandas.DataFrame A dataframe object. percentage_columns : iterable A list of cloumn names to be displayed with a percentage sign. Returns ------- str A nicely formatted string for the given dataframe. Example ------- >>> import pandas as pd >>> df = pd.DataFrame([[8,'a'],[5,'b']],[1,2],['num', 'char']) >>> print(df_string(df)) num char 1 8 a 2 5 b """ formatters_map = {} for col, dtype in df.dtypes.iteritems(): if col in percentage_columns: formatters_map[col] = '{:,.2f} %'.format elif dtype == 'float64': formatters_map[col] = '{:,.2f}'.format if format_map: for key in format_map: formatters_map[key] = format_map[key] return df.to_string(formatters=formatters_map, **kwargs)
python
def df_string(df, percentage_columns=(), format_map=None, **kwargs): """Return a nicely formatted string for the given dataframe. Arguments --------- df : pandas.DataFrame A dataframe object. percentage_columns : iterable A list of cloumn names to be displayed with a percentage sign. Returns ------- str A nicely formatted string for the given dataframe. Example ------- >>> import pandas as pd >>> df = pd.DataFrame([[8,'a'],[5,'b']],[1,2],['num', 'char']) >>> print(df_string(df)) num char 1 8 a 2 5 b """ formatters_map = {} for col, dtype in df.dtypes.iteritems(): if col in percentage_columns: formatters_map[col] = '{:,.2f} %'.format elif dtype == 'float64': formatters_map[col] = '{:,.2f}'.format if format_map: for key in format_map: formatters_map[key] = format_map[key] return df.to_string(formatters=formatters_map, **kwargs)
[ "def", "df_string", "(", "df", ",", "percentage_columns", "=", "(", ")", ",", "format_map", "=", "None", ",", "*", "*", "kwargs", ")", ":", "formatters_map", "=", "{", "}", "for", "col", ",", "dtype", "in", "df", ".", "dtypes", ".", "iteritems", "(", ")", ":", "if", "col", "in", "percentage_columns", ":", "formatters_map", "[", "col", "]", "=", "'{:,.2f} %'", ".", "format", "elif", "dtype", "==", "'float64'", ":", "formatters_map", "[", "col", "]", "=", "'{:,.2f}'", ".", "format", "if", "format_map", ":", "for", "key", "in", "format_map", ":", "formatters_map", "[", "key", "]", "=", "format_map", "[", "key", "]", "return", "df", ".", "to_string", "(", "formatters", "=", "formatters_map", ",", "*", "*", "kwargs", ")" ]
Return a nicely formatted string for the given dataframe. Arguments --------- df : pandas.DataFrame A dataframe object. percentage_columns : iterable A list of cloumn names to be displayed with a percentage sign. Returns ------- str A nicely formatted string for the given dataframe. Example ------- >>> import pandas as pd >>> df = pd.DataFrame([[8,'a'],[5,'b']],[1,2],['num', 'char']) >>> print(df_string(df)) num char 1 8 a 2 5 b
[ "Return", "a", "nicely", "formatted", "string", "for", "the", "given", "dataframe", "." ]
231059634643af2558d22070f89767410978cf56
https://github.com/shaypal5/pdutil/blob/231059634643af2558d22070f89767410978cf56/pdutil/display/display.py#L9-L42
241,961
shaypal5/pdutil
pdutil/display/display.py
big_dataframe_setup
def big_dataframe_setup(): # pragma: no cover """Sets pandas to display really big data frames.""" pd.set_option('display.max_colwidth', sys.maxsize) pd.set_option('max_colwidth', sys.maxsize) # height has been deprecated. # pd.set_option('display.height', sys.maxsize) pd.set_option('display.max_rows', sys.maxsize) pd.set_option('display.width', sys.maxsize) pd.set_option('display.colheader_justify', 'center') pd.set_option('display.column_space', sys.maxsize) pd.set_option('display.max_seq_items', sys.maxsize) pd.set_option('display.expand_frame_repr', True)
python
def big_dataframe_setup(): # pragma: no cover """Sets pandas to display really big data frames.""" pd.set_option('display.max_colwidth', sys.maxsize) pd.set_option('max_colwidth', sys.maxsize) # height has been deprecated. # pd.set_option('display.height', sys.maxsize) pd.set_option('display.max_rows', sys.maxsize) pd.set_option('display.width', sys.maxsize) pd.set_option('display.colheader_justify', 'center') pd.set_option('display.column_space', sys.maxsize) pd.set_option('display.max_seq_items', sys.maxsize) pd.set_option('display.expand_frame_repr', True)
[ "def", "big_dataframe_setup", "(", ")", ":", "# pragma: no cover", "pd", ".", "set_option", "(", "'display.max_colwidth'", ",", "sys", ".", "maxsize", ")", "pd", ".", "set_option", "(", "'max_colwidth'", ",", "sys", ".", "maxsize", ")", "# height has been deprecated.", "# pd.set_option('display.height', sys.maxsize)", "pd", ".", "set_option", "(", "'display.max_rows'", ",", "sys", ".", "maxsize", ")", "pd", ".", "set_option", "(", "'display.width'", ",", "sys", ".", "maxsize", ")", "pd", ".", "set_option", "(", "'display.colheader_justify'", ",", "'center'", ")", "pd", ".", "set_option", "(", "'display.column_space'", ",", "sys", ".", "maxsize", ")", "pd", ".", "set_option", "(", "'display.max_seq_items'", ",", "sys", ".", "maxsize", ")", "pd", ".", "set_option", "(", "'display.expand_frame_repr'", ",", "True", ")" ]
Sets pandas to display really big data frames.
[ "Sets", "pandas", "to", "display", "really", "big", "data", "frames", "." ]
231059634643af2558d22070f89767410978cf56
https://github.com/shaypal5/pdutil/blob/231059634643af2558d22070f89767410978cf56/pdutil/display/display.py#L45-L56
241,962
shaypal5/pdutil
pdutil/display/display.py
df_to_html
def df_to_html(df, percentage_columns=None): # pragma: no cover """Return a nicely formatted HTML code string for the given dataframe. Arguments --------- df : pandas.DataFrame A dataframe object. percentage_columns : iterable A list of cloumn names to be displayed with a percentage sign. Returns ------- str A nicely formatted string for the given dataframe. """ big_dataframe_setup() try: res = '<br><h2> {} </h2>'.format(df.name) except AttributeError: res = '' df.style.set_properties(**{'text-align': 'center'}) res += df.to_html(formatters=_formatters_dict( input_df=df, percentage_columns=percentage_columns )) res += '<br>' return res
python
def df_to_html(df, percentage_columns=None): # pragma: no cover """Return a nicely formatted HTML code string for the given dataframe. Arguments --------- df : pandas.DataFrame A dataframe object. percentage_columns : iterable A list of cloumn names to be displayed with a percentage sign. Returns ------- str A nicely formatted string for the given dataframe. """ big_dataframe_setup() try: res = '<br><h2> {} </h2>'.format(df.name) except AttributeError: res = '' df.style.set_properties(**{'text-align': 'center'}) res += df.to_html(formatters=_formatters_dict( input_df=df, percentage_columns=percentage_columns )) res += '<br>' return res
[ "def", "df_to_html", "(", "df", ",", "percentage_columns", "=", "None", ")", ":", "# pragma: no cover", "big_dataframe_setup", "(", ")", "try", ":", "res", "=", "'<br><h2> {} </h2>'", ".", "format", "(", "df", ".", "name", ")", "except", "AttributeError", ":", "res", "=", "''", "df", ".", "style", ".", "set_properties", "(", "*", "*", "{", "'text-align'", ":", "'center'", "}", ")", "res", "+=", "df", ".", "to_html", "(", "formatters", "=", "_formatters_dict", "(", "input_df", "=", "df", ",", "percentage_columns", "=", "percentage_columns", ")", ")", "res", "+=", "'<br>'", "return", "res" ]
Return a nicely formatted HTML code string for the given dataframe. Arguments --------- df : pandas.DataFrame A dataframe object. percentage_columns : iterable A list of cloumn names to be displayed with a percentage sign. Returns ------- str A nicely formatted string for the given dataframe.
[ "Return", "a", "nicely", "formatted", "HTML", "code", "string", "for", "the", "given", "dataframe", "." ]
231059634643af2558d22070f89767410978cf56
https://github.com/shaypal5/pdutil/blob/231059634643af2558d22070f89767410978cf56/pdutil/display/display.py#L80-L106
241,963
lapets/parts
parts/parts.py
parts
def parts(xs, number = None, length = None): """ Split a list into either the specified number of parts or a number of parts each of the specified length. The elements are distributed somewhat evenly among the parts if possible. >>> list(parts([1,2,3,4,5,6,7], length=1)) [[1], [2], [3], [4], [5], [6], [7]] >>> list(parts([1,2,3,4,5,6,7], length=2)) [[1, 2], [3, 4], [5, 6], [7]] >>> list(parts([1,2,3,4,5,6,7], length=3)) [[1, 2, 3], [4, 5, 6], [7]] >>> list(parts([1,2,3,4,5,6,7], length=4)) [[1, 2, 3, 4], [5, 6, 7]] >>> list(parts([1,2,3,4,5,6,7], length=5)) [[1, 2, 3, 4, 5], [6, 7]] >>> list(parts([1,2,3,4,5,6,7], length=6)) [[1, 2, 3, 4, 5, 6], [7]] >>> list(parts([1,2,3,4,5,6,7], length=7)) [[1, 2, 3, 4, 5, 6, 7]] >>> list(parts([1,2,3,4,5,6,7], 1)) [[1, 2, 3, 4, 5, 6, 7]] >>> list(parts([1,2,3,4,5,6,7], 2)) [[1, 2, 3], [4, 5, 6, 7]] >>> list(parts([1,2,3,4,5,6,7], 3)) [[1, 2], [3, 4], [5, 6, 7]] >>> list(parts([1,2,3,4,5,6,7], 4)) [[1], [2, 3], [4, 5], [6, 7]] >>> list(parts([1,2,3,4,5,6,7], 5)) [[1], [2], [3], [4, 5], [6, 7]] >>> list(parts([1,2,3,4,5,6,7], 6)) [[1], [2], [3], [4], [5], [6, 7]] >>> list(parts([1,2,3,4,5,6,7], 7)) [[1], [2], [3], [4], [5], [6], [7]] >>> list(parts([1,2,3,4,5,6,7], 7, [1,1,1,1,1,1,1])) [[1], [2], [3], [4], [5], [6], [7]] >>> list(parts([1,2,3,4,5,6,7], length=[1,1,1,1,1,1,1])) [[1], [2], [3], [4], [5], [6], [7]] >>> list(parts([1,2,3,4,5,6], length=[2,2,2])) [[1, 2], [3, 4], [5, 6]] >>> list(parts([1,2,3,4,5,6], length=[1,2,3])) [[1], [2, 3], [4, 5, 6]] >>> list(parts([1,2,3,4,5,6], 2, 3)) [[1, 2, 3], [4, 5, 6]] >>> list(parts([1,2,3,4,5,6], number=3, length=2)) [[1, 2], [3, 4], [5, 6]] >>> list(parts([1,2,3,4,5,6], 2, length=[1,2,3])) Traceback (most recent call last): ... PartsError: 'Number of parts does not match number of part lengths specified in input.' >>> list(parts([1,2,3,4,5,6,7], number=3, length=2)) Traceback (most recent call last): ... PartsError: 'List cannot be split into 3 parts each of length 2.' """ if number is not None and type(number) is not int: raise PartsError("Number of parts must be an integer.") if length is not None: if type(length) is not int: if type(length) is not list or (not all([type(l) is int for l in length])): raise PartsError("Length parameter must be an integer or list of integers.") if number is not None and length is None: number = max(1, min(len(xs), number)) # Number should be reasonable. length = len(xs) // number i = 0 # Produce parts by updating length after each part to ensure # an even distribution. while number > 0 and i < len(xs): number -= 1 if number == 0: yield xs[i:] break else: yield xs[i:i + length] i += length length = (len(xs) - i) // number elif number is None and length is not None: if type(length) is int: length = max(1, length) for i in range(0, len(xs), length): # Yield parts of specified length. yield xs[i:i + length] else: # Length is a list of integers. xs_index = 0 len_index = 0 while xs_index < len(xs): if xs_index + length[len_index] <= len(xs): yield xs[xs_index:xs_index + length[len_index]] xs_index += length[len_index] len_index += 1 else: raise PartsError("Cannot return part of requested length; list too short.") elif number is not None and length is not None: if type(length) is int: if length * number != len(xs): raise PartsError("List cannot be split into " + str(number) + " parts each of length " + str(length) + ".") length = max(1, length) for i in range(0, len(xs), length): # Yield parts of specified length. yield xs[i:i + length] else: # Length is a list of integers. if len(length) == number: xs_index = 0 len_index = 0 while xs_index < len(xs): if xs_index + length[len_index] <= len(xs): yield xs[xs_index:xs_index + length[len_index]] xs_index += length[len_index] len_index += 1 else: raise PartsError("Cannot return part of requested length; list too short.") else: raise PartsError("Number of parts does not match number of part lengths specified in input.") else: # Neither is specified. raise PartsError("Must specify number of parts or length of each part.")
python
def parts(xs, number = None, length = None): """ Split a list into either the specified number of parts or a number of parts each of the specified length. The elements are distributed somewhat evenly among the parts if possible. >>> list(parts([1,2,3,4,5,6,7], length=1)) [[1], [2], [3], [4], [5], [6], [7]] >>> list(parts([1,2,3,4,5,6,7], length=2)) [[1, 2], [3, 4], [5, 6], [7]] >>> list(parts([1,2,3,4,5,6,7], length=3)) [[1, 2, 3], [4, 5, 6], [7]] >>> list(parts([1,2,3,4,5,6,7], length=4)) [[1, 2, 3, 4], [5, 6, 7]] >>> list(parts([1,2,3,4,5,6,7], length=5)) [[1, 2, 3, 4, 5], [6, 7]] >>> list(parts([1,2,3,4,5,6,7], length=6)) [[1, 2, 3, 4, 5, 6], [7]] >>> list(parts([1,2,3,4,5,6,7], length=7)) [[1, 2, 3, 4, 5, 6, 7]] >>> list(parts([1,2,3,4,5,6,7], 1)) [[1, 2, 3, 4, 5, 6, 7]] >>> list(parts([1,2,3,4,5,6,7], 2)) [[1, 2, 3], [4, 5, 6, 7]] >>> list(parts([1,2,3,4,5,6,7], 3)) [[1, 2], [3, 4], [5, 6, 7]] >>> list(parts([1,2,3,4,5,6,7], 4)) [[1], [2, 3], [4, 5], [6, 7]] >>> list(parts([1,2,3,4,5,6,7], 5)) [[1], [2], [3], [4, 5], [6, 7]] >>> list(parts([1,2,3,4,5,6,7], 6)) [[1], [2], [3], [4], [5], [6, 7]] >>> list(parts([1,2,3,4,5,6,7], 7)) [[1], [2], [3], [4], [5], [6], [7]] >>> list(parts([1,2,3,4,5,6,7], 7, [1,1,1,1,1,1,1])) [[1], [2], [3], [4], [5], [6], [7]] >>> list(parts([1,2,3,4,5,6,7], length=[1,1,1,1,1,1,1])) [[1], [2], [3], [4], [5], [6], [7]] >>> list(parts([1,2,3,4,5,6], length=[2,2,2])) [[1, 2], [3, 4], [5, 6]] >>> list(parts([1,2,3,4,5,6], length=[1,2,3])) [[1], [2, 3], [4, 5, 6]] >>> list(parts([1,2,3,4,5,6], 2, 3)) [[1, 2, 3], [4, 5, 6]] >>> list(parts([1,2,3,4,5,6], number=3, length=2)) [[1, 2], [3, 4], [5, 6]] >>> list(parts([1,2,3,4,5,6], 2, length=[1,2,3])) Traceback (most recent call last): ... PartsError: 'Number of parts does not match number of part lengths specified in input.' >>> list(parts([1,2,3,4,5,6,7], number=3, length=2)) Traceback (most recent call last): ... PartsError: 'List cannot be split into 3 parts each of length 2.' """ if number is not None and type(number) is not int: raise PartsError("Number of parts must be an integer.") if length is not None: if type(length) is not int: if type(length) is not list or (not all([type(l) is int for l in length])): raise PartsError("Length parameter must be an integer or list of integers.") if number is not None and length is None: number = max(1, min(len(xs), number)) # Number should be reasonable. length = len(xs) // number i = 0 # Produce parts by updating length after each part to ensure # an even distribution. while number > 0 and i < len(xs): number -= 1 if number == 0: yield xs[i:] break else: yield xs[i:i + length] i += length length = (len(xs) - i) // number elif number is None and length is not None: if type(length) is int: length = max(1, length) for i in range(0, len(xs), length): # Yield parts of specified length. yield xs[i:i + length] else: # Length is a list of integers. xs_index = 0 len_index = 0 while xs_index < len(xs): if xs_index + length[len_index] <= len(xs): yield xs[xs_index:xs_index + length[len_index]] xs_index += length[len_index] len_index += 1 else: raise PartsError("Cannot return part of requested length; list too short.") elif number is not None and length is not None: if type(length) is int: if length * number != len(xs): raise PartsError("List cannot be split into " + str(number) + " parts each of length " + str(length) + ".") length = max(1, length) for i in range(0, len(xs), length): # Yield parts of specified length. yield xs[i:i + length] else: # Length is a list of integers. if len(length) == number: xs_index = 0 len_index = 0 while xs_index < len(xs): if xs_index + length[len_index] <= len(xs): yield xs[xs_index:xs_index + length[len_index]] xs_index += length[len_index] len_index += 1 else: raise PartsError("Cannot return part of requested length; list too short.") else: raise PartsError("Number of parts does not match number of part lengths specified in input.") else: # Neither is specified. raise PartsError("Must specify number of parts or length of each part.")
[ "def", "parts", "(", "xs", ",", "number", "=", "None", ",", "length", "=", "None", ")", ":", "if", "number", "is", "not", "None", "and", "type", "(", "number", ")", "is", "not", "int", ":", "raise", "PartsError", "(", "\"Number of parts must be an integer.\"", ")", "if", "length", "is", "not", "None", ":", "if", "type", "(", "length", ")", "is", "not", "int", ":", "if", "type", "(", "length", ")", "is", "not", "list", "or", "(", "not", "all", "(", "[", "type", "(", "l", ")", "is", "int", "for", "l", "in", "length", "]", ")", ")", ":", "raise", "PartsError", "(", "\"Length parameter must be an integer or list of integers.\"", ")", "if", "number", "is", "not", "None", "and", "length", "is", "None", ":", "number", "=", "max", "(", "1", ",", "min", "(", "len", "(", "xs", ")", ",", "number", ")", ")", "# Number should be reasonable.", "length", "=", "len", "(", "xs", ")", "//", "number", "i", "=", "0", "# Produce parts by updating length after each part to ensure", "# an even distribution.", "while", "number", ">", "0", "and", "i", "<", "len", "(", "xs", ")", ":", "number", "-=", "1", "if", "number", "==", "0", ":", "yield", "xs", "[", "i", ":", "]", "break", "else", ":", "yield", "xs", "[", "i", ":", "i", "+", "length", "]", "i", "+=", "length", "length", "=", "(", "len", "(", "xs", ")", "-", "i", ")", "//", "number", "elif", "number", "is", "None", "and", "length", "is", "not", "None", ":", "if", "type", "(", "length", ")", "is", "int", ":", "length", "=", "max", "(", "1", ",", "length", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "xs", ")", ",", "length", ")", ":", "# Yield parts of specified length.", "yield", "xs", "[", "i", ":", "i", "+", "length", "]", "else", ":", "# Length is a list of integers.", "xs_index", "=", "0", "len_index", "=", "0", "while", "xs_index", "<", "len", "(", "xs", ")", ":", "if", "xs_index", "+", "length", "[", "len_index", "]", "<=", "len", "(", "xs", ")", ":", "yield", "xs", "[", "xs_index", ":", "xs_index", "+", "length", "[", "len_index", "]", "]", "xs_index", "+=", "length", "[", "len_index", "]", "len_index", "+=", "1", "else", ":", "raise", "PartsError", "(", "\"Cannot return part of requested length; list too short.\"", ")", "elif", "number", "is", "not", "None", "and", "length", "is", "not", "None", ":", "if", "type", "(", "length", ")", "is", "int", ":", "if", "length", "*", "number", "!=", "len", "(", "xs", ")", ":", "raise", "PartsError", "(", "\"List cannot be split into \"", "+", "str", "(", "number", ")", "+", "\" parts each of length \"", "+", "str", "(", "length", ")", "+", "\".\"", ")", "length", "=", "max", "(", "1", ",", "length", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "xs", ")", ",", "length", ")", ":", "# Yield parts of specified length.", "yield", "xs", "[", "i", ":", "i", "+", "length", "]", "else", ":", "# Length is a list of integers.", "if", "len", "(", "length", ")", "==", "number", ":", "xs_index", "=", "0", "len_index", "=", "0", "while", "xs_index", "<", "len", "(", "xs", ")", ":", "if", "xs_index", "+", "length", "[", "len_index", "]", "<=", "len", "(", "xs", ")", ":", "yield", "xs", "[", "xs_index", ":", "xs_index", "+", "length", "[", "len_index", "]", "]", "xs_index", "+=", "length", "[", "len_index", "]", "len_index", "+=", "1", "else", ":", "raise", "PartsError", "(", "\"Cannot return part of requested length; list too short.\"", ")", "else", ":", "raise", "PartsError", "(", "\"Number of parts does not match number of part lengths specified in input.\"", ")", "else", ":", "# Neither is specified.", "raise", "PartsError", "(", "\"Must specify number of parts or length of each part.\"", ")" ]
Split a list into either the specified number of parts or a number of parts each of the specified length. The elements are distributed somewhat evenly among the parts if possible. >>> list(parts([1,2,3,4,5,6,7], length=1)) [[1], [2], [3], [4], [5], [6], [7]] >>> list(parts([1,2,3,4,5,6,7], length=2)) [[1, 2], [3, 4], [5, 6], [7]] >>> list(parts([1,2,3,4,5,6,7], length=3)) [[1, 2, 3], [4, 5, 6], [7]] >>> list(parts([1,2,3,4,5,6,7], length=4)) [[1, 2, 3, 4], [5, 6, 7]] >>> list(parts([1,2,3,4,5,6,7], length=5)) [[1, 2, 3, 4, 5], [6, 7]] >>> list(parts([1,2,3,4,5,6,7], length=6)) [[1, 2, 3, 4, 5, 6], [7]] >>> list(parts([1,2,3,4,5,6,7], length=7)) [[1, 2, 3, 4, 5, 6, 7]] >>> list(parts([1,2,3,4,5,6,7], 1)) [[1, 2, 3, 4, 5, 6, 7]] >>> list(parts([1,2,3,4,5,6,7], 2)) [[1, 2, 3], [4, 5, 6, 7]] >>> list(parts([1,2,3,4,5,6,7], 3)) [[1, 2], [3, 4], [5, 6, 7]] >>> list(parts([1,2,3,4,5,6,7], 4)) [[1], [2, 3], [4, 5], [6, 7]] >>> list(parts([1,2,3,4,5,6,7], 5)) [[1], [2], [3], [4, 5], [6, 7]] >>> list(parts([1,2,3,4,5,6,7], 6)) [[1], [2], [3], [4], [5], [6, 7]] >>> list(parts([1,2,3,4,5,6,7], 7)) [[1], [2], [3], [4], [5], [6], [7]] >>> list(parts([1,2,3,4,5,6,7], 7, [1,1,1,1,1,1,1])) [[1], [2], [3], [4], [5], [6], [7]] >>> list(parts([1,2,3,4,5,6,7], length=[1,1,1,1,1,1,1])) [[1], [2], [3], [4], [5], [6], [7]] >>> list(parts([1,2,3,4,5,6], length=[2,2,2])) [[1, 2], [3, 4], [5, 6]] >>> list(parts([1,2,3,4,5,6], length=[1,2,3])) [[1], [2, 3], [4, 5, 6]] >>> list(parts([1,2,3,4,5,6], 2, 3)) [[1, 2, 3], [4, 5, 6]] >>> list(parts([1,2,3,4,5,6], number=3, length=2)) [[1, 2], [3, 4], [5, 6]] >>> list(parts([1,2,3,4,5,6], 2, length=[1,2,3])) Traceback (most recent call last): ... PartsError: 'Number of parts does not match number of part lengths specified in input.' >>> list(parts([1,2,3,4,5,6,7], number=3, length=2)) Traceback (most recent call last): ... PartsError: 'List cannot be split into 3 parts each of length 2.'
[ "Split", "a", "list", "into", "either", "the", "specified", "number", "of", "parts", "or", "a", "number", "of", "parts", "each", "of", "the", "specified", "length", ".", "The", "elements", "are", "distributed", "somewhat", "evenly", "among", "the", "parts", "if", "possible", "." ]
69add81e4ea14f7b85493f86d96663cdac05641e
https://github.com/lapets/parts/blob/69add81e4ea14f7b85493f86d96663cdac05641e/parts/parts.py#L22-L139
241,964
veeti/decent
decent/validators.py
All
def All(*validators): """ Combines all the given validator callables into one, running all the validators in sequence on the given value. """ @wraps(All) def built(value): for validator in validators: value = validator(value) return value return built
python
def All(*validators): """ Combines all the given validator callables into one, running all the validators in sequence on the given value. """ @wraps(All) def built(value): for validator in validators: value = validator(value) return value return built
[ "def", "All", "(", "*", "validators", ")", ":", "@", "wraps", "(", "All", ")", "def", "built", "(", "value", ")", ":", "for", "validator", "in", "validators", ":", "value", "=", "validator", "(", "value", ")", "return", "value", "return", "built" ]
Combines all the given validator callables into one, running all the validators in sequence on the given value.
[ "Combines", "all", "the", "given", "validator", "callables", "into", "one", "running", "all", "the", "validators", "in", "sequence", "on", "the", "given", "value", "." ]
07b11536953b9cf4402c65f241706ab717b90bff
https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L11-L21
241,965
veeti/decent
decent/validators.py
Any
def Any(*validators): """ Combines all the given validator callables into one, running the given value through them in sequence until a valid result is given. """ @wraps(Any) def built(value): error = None for validator in validators: try: return validator(value) except Error as e: error = e raise error return built
python
def Any(*validators): """ Combines all the given validator callables into one, running the given value through them in sequence until a valid result is given. """ @wraps(Any) def built(value): error = None for validator in validators: try: return validator(value) except Error as e: error = e raise error return built
[ "def", "Any", "(", "*", "validators", ")", ":", "@", "wraps", "(", "Any", ")", "def", "built", "(", "value", ")", ":", "error", "=", "None", "for", "validator", "in", "validators", ":", "try", ":", "return", "validator", "(", "value", ")", "except", "Error", "as", "e", ":", "error", "=", "e", "raise", "error", "return", "built" ]
Combines all the given validator callables into one, running the given value through them in sequence until a valid result is given.
[ "Combines", "all", "the", "given", "validator", "callables", "into", "one", "running", "the", "given", "value", "through", "them", "in", "sequence", "until", "a", "valid", "result", "is", "given", "." ]
07b11536953b9cf4402c65f241706ab717b90bff
https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L23-L37
241,966
veeti/decent
decent/validators.py
Maybe
def Maybe(validator): """ Wraps the given validator callable, only using it for the given value if it is not ``None``. """ @wraps(Maybe) def built(value): if value != None: return validator(value) return built
python
def Maybe(validator): """ Wraps the given validator callable, only using it for the given value if it is not ``None``. """ @wraps(Maybe) def built(value): if value != None: return validator(value) return built
[ "def", "Maybe", "(", "validator", ")", ":", "@", "wraps", "(", "Maybe", ")", "def", "built", "(", "value", ")", ":", "if", "value", "!=", "None", ":", "return", "validator", "(", "value", ")", "return", "built" ]
Wraps the given validator callable, only using it for the given value if it is not ``None``.
[ "Wraps", "the", "given", "validator", "callable", "only", "using", "it", "for", "the", "given", "value", "if", "it", "is", "not", "None", "." ]
07b11536953b9cf4402c65f241706ab717b90bff
https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L39-L48
241,967
veeti/decent
decent/validators.py
Msg
def Msg(validator, message): """ Wraps the given validator callable, replacing any error messages raised. """ @wraps(Msg) def built(value): try: return validator(value) except Error as e: e.message = message raise e return built
python
def Msg(validator, message): """ Wraps the given validator callable, replacing any error messages raised. """ @wraps(Msg) def built(value): try: return validator(value) except Error as e: e.message = message raise e return built
[ "def", "Msg", "(", "validator", ",", "message", ")", ":", "@", "wraps", "(", "Msg", ")", "def", "built", "(", "value", ")", ":", "try", ":", "return", "validator", "(", "value", ")", "except", "Error", "as", "e", ":", "e", ".", "message", "=", "message", "raise", "e", "return", "built" ]
Wraps the given validator callable, replacing any error messages raised.
[ "Wraps", "the", "given", "validator", "callable", "replacing", "any", "error", "messages", "raised", "." ]
07b11536953b9cf4402c65f241706ab717b90bff
https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L50-L61
241,968
veeti/decent
decent/validators.py
Default
def Default(default): """ Creates a validator callable that replaces ``None`` with the specified default value. """ @wraps(Default) def built(value): if value == None: return default return value return built
python
def Default(default): """ Creates a validator callable that replaces ``None`` with the specified default value. """ @wraps(Default) def built(value): if value == None: return default return value return built
[ "def", "Default", "(", "default", ")", ":", "@", "wraps", "(", "Default", ")", "def", "built", "(", "value", ")", ":", "if", "value", "==", "None", ":", "return", "default", "return", "value", "return", "built" ]
Creates a validator callable that replaces ``None`` with the specified default value.
[ "Creates", "a", "validator", "callable", "that", "replaces", "None", "with", "the", "specified", "default", "value", "." ]
07b11536953b9cf4402c65f241706ab717b90bff
https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L63-L73
241,969
veeti/decent
decent/validators.py
Eq
def Eq(value, message="Not equal to {!s}"): """ Creates a validator that compares the equality of the given value to ``value``. A custom message can be specified with ``message``. It will be formatted with ``value``. """ @wraps(Eq) def built(_value): if _value != value: raise Error(message.format(value)) return _value return built
python
def Eq(value, message="Not equal to {!s}"): """ Creates a validator that compares the equality of the given value to ``value``. A custom message can be specified with ``message``. It will be formatted with ``value``. """ @wraps(Eq) def built(_value): if _value != value: raise Error(message.format(value)) return _value return built
[ "def", "Eq", "(", "value", ",", "message", "=", "\"Not equal to {!s}\"", ")", ":", "@", "wraps", "(", "Eq", ")", "def", "built", "(", "_value", ")", ":", "if", "_value", "!=", "value", ":", "raise", "Error", "(", "message", ".", "format", "(", "value", ")", ")", "return", "_value", "return", "built" ]
Creates a validator that compares the equality of the given value to ``value``. A custom message can be specified with ``message``. It will be formatted with ``value``.
[ "Creates", "a", "validator", "that", "compares", "the", "equality", "of", "the", "given", "value", "to", "value", "." ]
07b11536953b9cf4402c65f241706ab717b90bff
https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L77-L90
241,970
veeti/decent
decent/validators.py
Instance
def Instance(expected, message="Not an instance of {}"): """ Creates a validator that checks if the given value is an instance of ``expected``. A custom message can be specified with ``message``. """ @wraps(Instance) def built(value): if not isinstance(value, expected): raise Error(message.format(expected.__name__)) return value return built
python
def Instance(expected, message="Not an instance of {}"): """ Creates a validator that checks if the given value is an instance of ``expected``. A custom message can be specified with ``message``. """ @wraps(Instance) def built(value): if not isinstance(value, expected): raise Error(message.format(expected.__name__)) return value return built
[ "def", "Instance", "(", "expected", ",", "message", "=", "\"Not an instance of {}\"", ")", ":", "@", "wraps", "(", "Instance", ")", "def", "built", "(", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "expected", ")", ":", "raise", "Error", "(", "message", ".", "format", "(", "expected", ".", "__name__", ")", ")", "return", "value", "return", "built" ]
Creates a validator that checks if the given value is an instance of ``expected``. A custom message can be specified with ``message``.
[ "Creates", "a", "validator", "that", "checks", "if", "the", "given", "value", "is", "an", "instance", "of", "expected", "." ]
07b11536953b9cf4402c65f241706ab717b90bff
https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L107-L119
241,971
veeti/decent
decent/validators.py
Coerce
def Coerce(type, message="Not a valid {} value"): """ Creates a validator that attempts to coerce the given value to the specified ``type``. Will raise an error if the coercion fails. A custom message can be specified with ``message``. """ @wraps(Coerce) def built(value): try: return type(value) except (TypeError, ValueError) as e: raise Error(message.format(type.__name__)) return built
python
def Coerce(type, message="Not a valid {} value"): """ Creates a validator that attempts to coerce the given value to the specified ``type``. Will raise an error if the coercion fails. A custom message can be specified with ``message``. """ @wraps(Coerce) def built(value): try: return type(value) except (TypeError, ValueError) as e: raise Error(message.format(type.__name__)) return built
[ "def", "Coerce", "(", "type", ",", "message", "=", "\"Not a valid {} value\"", ")", ":", "@", "wraps", "(", "Coerce", ")", "def", "built", "(", "value", ")", ":", "try", ":", "return", "type", "(", "value", ")", "except", "(", "TypeError", ",", "ValueError", ")", "as", "e", ":", "raise", "Error", "(", "message", ".", "format", "(", "type", ".", "__name__", ")", ")", "return", "built" ]
Creates a validator that attempts to coerce the given value to the specified ``type``. Will raise an error if the coercion fails. A custom message can be specified with ``message``.
[ "Creates", "a", "validator", "that", "attempts", "to", "coerce", "the", "given", "value", "to", "the", "specified", "type", ".", "Will", "raise", "an", "error", "if", "the", "coercion", "fails", "." ]
07b11536953b9cf4402c65f241706ab717b90bff
https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L121-L134
241,972
veeti/decent
decent/validators.py
List
def List(validator): """ Creates a validator that runs the given validator on every item in a list or other collection. The validator can mutate the values. Any raised errors will be collected into a single ``Invalid`` error. Their paths will be replaced with the index of the item. Will raise an error if the input value is not iterable. """ @wraps(List) def built(value): if not hasattr(value, '__iter__'): raise Error("Must be a list") invalid = Invalid() for i, item in enumerate(value): try: value[i] = validator(item) except Invalid as e: for error in e: error.path.insert(0, i) invalid.append(error) except Error as e: e.path.insert(0, i) invalid.append(e) if len(invalid): raise invalid return value return built
python
def List(validator): """ Creates a validator that runs the given validator on every item in a list or other collection. The validator can mutate the values. Any raised errors will be collected into a single ``Invalid`` error. Their paths will be replaced with the index of the item. Will raise an error if the input value is not iterable. """ @wraps(List) def built(value): if not hasattr(value, '__iter__'): raise Error("Must be a list") invalid = Invalid() for i, item in enumerate(value): try: value[i] = validator(item) except Invalid as e: for error in e: error.path.insert(0, i) invalid.append(error) except Error as e: e.path.insert(0, i) invalid.append(e) if len(invalid): raise invalid return value return built
[ "def", "List", "(", "validator", ")", ":", "@", "wraps", "(", "List", ")", "def", "built", "(", "value", ")", ":", "if", "not", "hasattr", "(", "value", ",", "'__iter__'", ")", ":", "raise", "Error", "(", "\"Must be a list\"", ")", "invalid", "=", "Invalid", "(", ")", "for", "i", ",", "item", "in", "enumerate", "(", "value", ")", ":", "try", ":", "value", "[", "i", "]", "=", "validator", "(", "item", ")", "except", "Invalid", "as", "e", ":", "for", "error", "in", "e", ":", "error", ".", "path", ".", "insert", "(", "0", ",", "i", ")", "invalid", ".", "append", "(", "error", ")", "except", "Error", "as", "e", ":", "e", ".", "path", ".", "insert", "(", "0", ",", "i", ")", "invalid", ".", "append", "(", "e", ")", "if", "len", "(", "invalid", ")", ":", "raise", "invalid", "return", "value", "return", "built" ]
Creates a validator that runs the given validator on every item in a list or other collection. The validator can mutate the values. Any raised errors will be collected into a single ``Invalid`` error. Their paths will be replaced with the index of the item. Will raise an error if the input value is not iterable.
[ "Creates", "a", "validator", "that", "runs", "the", "given", "validator", "on", "every", "item", "in", "a", "list", "or", "other", "collection", ".", "The", "validator", "can", "mutate", "the", "values", "." ]
07b11536953b9cf4402c65f241706ab717b90bff
https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L138-L167
241,973
veeti/decent
decent/validators.py
Range
def Range(min=None, max=None, min_message="Must be at least {min}", max_message="Must be at most {max}"): """ Creates a validator that checks if the given numeric value is in the specified range, inclusive. Accepts values specified by ``numbers.Number`` only, excluding booleans. The error messages raised can be customized with ``min_message`` and ``max_message``. The ``min`` and ``max`` arguments are formatted. """ @wraps(Range) def built(value): if not isinstance(value, numbers.Number) or isinstance(value, bool): raise Error("Not a number") if min is not None and min > value: raise Error(min_message.format(min=min, max=max)) if max is not None and value > max: raise Error(max_message.format(min=min, max=max)) return value return built
python
def Range(min=None, max=None, min_message="Must be at least {min}", max_message="Must be at most {max}"): """ Creates a validator that checks if the given numeric value is in the specified range, inclusive. Accepts values specified by ``numbers.Number`` only, excluding booleans. The error messages raised can be customized with ``min_message`` and ``max_message``. The ``min`` and ``max`` arguments are formatted. """ @wraps(Range) def built(value): if not isinstance(value, numbers.Number) or isinstance(value, bool): raise Error("Not a number") if min is not None and min > value: raise Error(min_message.format(min=min, max=max)) if max is not None and value > max: raise Error(max_message.format(min=min, max=max)) return value return built
[ "def", "Range", "(", "min", "=", "None", ",", "max", "=", "None", ",", "min_message", "=", "\"Must be at least {min}\"", ",", "max_message", "=", "\"Must be at most {max}\"", ")", ":", "@", "wraps", "(", "Range", ")", "def", "built", "(", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "numbers", ".", "Number", ")", "or", "isinstance", "(", "value", ",", "bool", ")", ":", "raise", "Error", "(", "\"Not a number\"", ")", "if", "min", "is", "not", "None", "and", "min", ">", "value", ":", "raise", "Error", "(", "min_message", ".", "format", "(", "min", "=", "min", ",", "max", "=", "max", ")", ")", "if", "max", "is", "not", "None", "and", "value", ">", "max", ":", "raise", "Error", "(", "max_message", ".", "format", "(", "min", "=", "min", ",", "max", "=", "max", ")", ")", "return", "value", "return", "built" ]
Creates a validator that checks if the given numeric value is in the specified range, inclusive. Accepts values specified by ``numbers.Number`` only, excluding booleans. The error messages raised can be customized with ``min_message`` and ``max_message``. The ``min`` and ``max`` arguments are formatted.
[ "Creates", "a", "validator", "that", "checks", "if", "the", "given", "numeric", "value", "is", "in", "the", "specified", "range", "inclusive", "." ]
07b11536953b9cf4402c65f241706ab717b90bff
https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L212-L231
241,974
veeti/decent
decent/validators.py
NotEmpty
def NotEmpty(): """ Creates a validator that validates the given string is not empty. Will raise an error for non-string types. """ @wraps(NotEmpty) def built(value): if not isinstance(value, six.string_types) or not value: raise Error("Must not be empty") return value return built
python
def NotEmpty(): """ Creates a validator that validates the given string is not empty. Will raise an error for non-string types. """ @wraps(NotEmpty) def built(value): if not isinstance(value, six.string_types) or not value: raise Error("Must not be empty") return value return built
[ "def", "NotEmpty", "(", ")", ":", "@", "wraps", "(", "NotEmpty", ")", "def", "built", "(", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", "or", "not", "value", ":", "raise", "Error", "(", "\"Must not be empty\"", ")", "return", "value", "return", "built" ]
Creates a validator that validates the given string is not empty. Will raise an error for non-string types.
[ "Creates", "a", "validator", "that", "validates", "the", "given", "string", "is", "not", "empty", ".", "Will", "raise", "an", "error", "for", "non", "-", "string", "types", "." ]
07b11536953b9cf4402c65f241706ab717b90bff
https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L286-L296
241,975
veeti/decent
decent/validators.py
Uuid
def Uuid(to_uuid=True): """ Creates a UUID validator. Will raise an error for non-string types and non-UUID values. The given value will be converted to an instance of ``uuid.UUID`` unless ``to_uuid`` is ``False``. """ @wraps(Uuid) def built(value): invalid = Error("Not a valid UUID") if isinstance(value, uuid.UUID): return value elif not isinstance(value, six.string_types): raise invalid try: as_uuid = uuid.UUID(value) except (ValueError, AttributeError) as e: raise invalid if to_uuid: return as_uuid return value return built
python
def Uuid(to_uuid=True): """ Creates a UUID validator. Will raise an error for non-string types and non-UUID values. The given value will be converted to an instance of ``uuid.UUID`` unless ``to_uuid`` is ``False``. """ @wraps(Uuid) def built(value): invalid = Error("Not a valid UUID") if isinstance(value, uuid.UUID): return value elif not isinstance(value, six.string_types): raise invalid try: as_uuid = uuid.UUID(value) except (ValueError, AttributeError) as e: raise invalid if to_uuid: return as_uuid return value return built
[ "def", "Uuid", "(", "to_uuid", "=", "True", ")", ":", "@", "wraps", "(", "Uuid", ")", "def", "built", "(", "value", ")", ":", "invalid", "=", "Error", "(", "\"Not a valid UUID\"", ")", "if", "isinstance", "(", "value", ",", "uuid", ".", "UUID", ")", ":", "return", "value", "elif", "not", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "raise", "invalid", "try", ":", "as_uuid", "=", "uuid", ".", "UUID", "(", "value", ")", "except", "(", "ValueError", ",", "AttributeError", ")", "as", "e", ":", "raise", "invalid", "if", "to_uuid", ":", "return", "as_uuid", "return", "value", "return", "built" ]
Creates a UUID validator. Will raise an error for non-string types and non-UUID values. The given value will be converted to an instance of ``uuid.UUID`` unless ``to_uuid`` is ``False``.
[ "Creates", "a", "UUID", "validator", ".", "Will", "raise", "an", "error", "for", "non", "-", "string", "types", "and", "non", "-", "UUID", "values", "." ]
07b11536953b9cf4402c65f241706ab717b90bff
https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L300-L325
241,976
lionel/counterparts
counterparts.py
counterpart_found
def counterpart_found(string, counterpart, options, rc_so_far): """The sunny-day action is to echo the counterpart to stdout. :param string: The lookup string (UNUSED) :param counterpart: The counterpart that the string mapped to :param options: ArgumentParser or equivalent to provide options.no_newline :param rc_so_far: Stays whatever value it was. """ format = "%s" if options.no_newline else "%s\n" sys.stdout.write(format % (counterpart)) return rc_so_far or 0
python
def counterpart_found(string, counterpart, options, rc_so_far): """The sunny-day action is to echo the counterpart to stdout. :param string: The lookup string (UNUSED) :param counterpart: The counterpart that the string mapped to :param options: ArgumentParser or equivalent to provide options.no_newline :param rc_so_far: Stays whatever value it was. """ format = "%s" if options.no_newline else "%s\n" sys.stdout.write(format % (counterpart)) return rc_so_far or 0
[ "def", "counterpart_found", "(", "string", ",", "counterpart", ",", "options", ",", "rc_so_far", ")", ":", "format", "=", "\"%s\"", "if", "options", ".", "no_newline", "else", "\"%s\\n\"", "sys", ".", "stdout", ".", "write", "(", "format", "%", "(", "counterpart", ")", ")", "return", "rc_so_far", "or", "0" ]
The sunny-day action is to echo the counterpart to stdout. :param string: The lookup string (UNUSED) :param counterpart: The counterpart that the string mapped to :param options: ArgumentParser or equivalent to provide options.no_newline :param rc_so_far: Stays whatever value it was.
[ "The", "sunny", "-", "day", "action", "is", "to", "echo", "the", "counterpart", "to", "stdout", "." ]
20db9852feff531f854972f76b412c442b2fafbf
https://github.com/lionel/counterparts/blob/20db9852feff531f854972f76b412c442b2fafbf/counterparts.py#L186-L196
241,977
lionel/counterparts
counterparts.py
no_counterpart_found
def no_counterpart_found(string, options, rc_so_far): """Takes action determined by options.else_action. Unless told to raise an exception, this function returns the errno that is supposed to be returned in this case. :param string: The lookup string. :param options: ArgumentParser or equivalent to provide options.else_action, options.else_errno, options.no_newline :param rc_so_far: Becomes set to the value set in options. """ logger.debug("options.else_action: %s", options.else_action) if options.else_action == "passthrough": format_list = [string] output_fd = sys.stdout elif options.else_action == "exception": raise KeyError("No counterpart found for: %s" % (string)) elif options.else_action == "error": format_list = ["# No counterpart found for: %s" % (string)] output_fd = sys.stderr if not options.no_newline: format_list.append("\n") output_fd.write("".join(format_list)) return options.else_errno
python
def no_counterpart_found(string, options, rc_so_far): """Takes action determined by options.else_action. Unless told to raise an exception, this function returns the errno that is supposed to be returned in this case. :param string: The lookup string. :param options: ArgumentParser or equivalent to provide options.else_action, options.else_errno, options.no_newline :param rc_so_far: Becomes set to the value set in options. """ logger.debug("options.else_action: %s", options.else_action) if options.else_action == "passthrough": format_list = [string] output_fd = sys.stdout elif options.else_action == "exception": raise KeyError("No counterpart found for: %s" % (string)) elif options.else_action == "error": format_list = ["# No counterpart found for: %s" % (string)] output_fd = sys.stderr if not options.no_newline: format_list.append("\n") output_fd.write("".join(format_list)) return options.else_errno
[ "def", "no_counterpart_found", "(", "string", ",", "options", ",", "rc_so_far", ")", ":", "logger", ".", "debug", "(", "\"options.else_action: %s\"", ",", "options", ".", "else_action", ")", "if", "options", ".", "else_action", "==", "\"passthrough\"", ":", "format_list", "=", "[", "string", "]", "output_fd", "=", "sys", ".", "stdout", "elif", "options", ".", "else_action", "==", "\"exception\"", ":", "raise", "KeyError", "(", "\"No counterpart found for: %s\"", "%", "(", "string", ")", ")", "elif", "options", ".", "else_action", "==", "\"error\"", ":", "format_list", "=", "[", "\"# No counterpart found for: %s\"", "%", "(", "string", ")", "]", "output_fd", "=", "sys", ".", "stderr", "if", "not", "options", ".", "no_newline", ":", "format_list", ".", "append", "(", "\"\\n\"", ")", "output_fd", ".", "write", "(", "\"\"", ".", "join", "(", "format_list", ")", ")", "return", "options", ".", "else_errno" ]
Takes action determined by options.else_action. Unless told to raise an exception, this function returns the errno that is supposed to be returned in this case. :param string: The lookup string. :param options: ArgumentParser or equivalent to provide options.else_action, options.else_errno, options.no_newline :param rc_so_far: Becomes set to the value set in options.
[ "Takes", "action", "determined", "by", "options", ".", "else_action", ".", "Unless", "told", "to", "raise", "an", "exception", "this", "function", "returns", "the", "errno", "that", "is", "supposed", "to", "be", "returned", "in", "this", "case", "." ]
20db9852feff531f854972f76b412c442b2fafbf
https://github.com/lionel/counterparts/blob/20db9852feff531f854972f76b412c442b2fafbf/counterparts.py#L199-L222
241,978
lionel/counterparts
counterparts.py
_generate_input
def _generate_input(options): """First send strings from any given file, one string per line, sends any strings provided on the command line. :param options: ArgumentParser or equivalent to provide options.input and options.strings. :return: string """ if options.input: fp = open(options.input) if options.input != "-" else sys.stdin for string in fp.readlines(): yield string if options.strings: for string in options.strings: yield string
python
def _generate_input(options): """First send strings from any given file, one string per line, sends any strings provided on the command line. :param options: ArgumentParser or equivalent to provide options.input and options.strings. :return: string """ if options.input: fp = open(options.input) if options.input != "-" else sys.stdin for string in fp.readlines(): yield string if options.strings: for string in options.strings: yield string
[ "def", "_generate_input", "(", "options", ")", ":", "if", "options", ".", "input", ":", "fp", "=", "open", "(", "options", ".", "input", ")", "if", "options", ".", "input", "!=", "\"-\"", "else", "sys", ".", "stdin", "for", "string", "in", "fp", ".", "readlines", "(", ")", ":", "yield", "string", "if", "options", ".", "strings", ":", "for", "string", "in", "options", ".", "strings", ":", "yield", "string" ]
First send strings from any given file, one string per line, sends any strings provided on the command line. :param options: ArgumentParser or equivalent to provide options.input and options.strings. :return: string
[ "First", "send", "strings", "from", "any", "given", "file", "one", "string", "per", "line", "sends", "any", "strings", "provided", "on", "the", "command", "line", "." ]
20db9852feff531f854972f76b412c442b2fafbf
https://github.com/lionel/counterparts/blob/20db9852feff531f854972f76b412c442b2fafbf/counterparts.py#L261-L276
241,979
lionel/counterparts
counterparts.py
ConfigFromFile.register_options
def register_options(this_class, argparser): """This class method is called so that ConfigFromFile can tell the command-line parser to register the options specific to the class. :param this_class: Not used (required by @classmethod interface) :param argparser: The argparser instance being prepared for use. """ default_path = this_class.rc_file_basename default_basename = os.path.basename(default_path) argparser.add_argument('-c', "--config-file", default=default_path, help=("Configuration file to use for lookups " + "(replaces DEFAULT=%s " % (default_path) + "but not ~/%s)" % (default_basename)))
python
def register_options(this_class, argparser): """This class method is called so that ConfigFromFile can tell the command-line parser to register the options specific to the class. :param this_class: Not used (required by @classmethod interface) :param argparser: The argparser instance being prepared for use. """ default_path = this_class.rc_file_basename default_basename = os.path.basename(default_path) argparser.add_argument('-c', "--config-file", default=default_path, help=("Configuration file to use for lookups " + "(replaces DEFAULT=%s " % (default_path) + "but not ~/%s)" % (default_basename)))
[ "def", "register_options", "(", "this_class", ",", "argparser", ")", ":", "default_path", "=", "this_class", ".", "rc_file_basename", "default_basename", "=", "os", ".", "path", ".", "basename", "(", "default_path", ")", "argparser", ".", "add_argument", "(", "'-c'", ",", "\"--config-file\"", ",", "default", "=", "default_path", ",", "help", "=", "(", "\"Configuration file to use for lookups \"", "+", "\"(replaces DEFAULT=%s \"", "%", "(", "default_path", ")", "+", "\"but not ~/%s)\"", "%", "(", "default_basename", ")", ")", ")" ]
This class method is called so that ConfigFromFile can tell the command-line parser to register the options specific to the class. :param this_class: Not used (required by @classmethod interface) :param argparser: The argparser instance being prepared for use.
[ "This", "class", "method", "is", "called", "so", "that", "ConfigFromFile", "can", "tell", "the", "command", "-", "line", "parser", "to", "register", "the", "options", "specific", "to", "the", "class", "." ]
20db9852feff531f854972f76b412c442b2fafbf
https://github.com/lionel/counterparts/blob/20db9852feff531f854972f76b412c442b2fafbf/counterparts.py#L127-L141
241,980
lionel/counterparts
counterparts.py
ConfigFromFile._check_and_handle_includes
def _check_and_handle_includes(self, from_file): """Look for an optional INCLUDE section in the given file path. If the parser set `paths`, it is cleared so that they do not keep showing up when additional files are parsed. """ logger.debug("Check/handle includes from %s", from_file) try: paths = self._parser.get("INCLUDE", "paths") except (config_parser.NoSectionError, config_parser.NoOptionError) as exc: logger.debug("_check_and_handle_includes: EXCEPTION: %s", exc) return paths_lines = [p.strip() for p in paths.split("\n")] logger.debug("paths = %s (wanted just once; CLEARING)", paths_lines) self._parser.remove_option("INCLUDE", "paths") for f in paths_lines: abspath = (f if os.path.isabs(f) else os.path.abspath( os.path.join(os.path.dirname(from_file), f))) use_path = os.path.normpath(abspath) if use_path in self._parsed_files: raise RecursionInConfigFile("In %s: %s already read", from_file, use_path) self._parsed_files.append(use_path) self._handle_rc_file(use_path)
python
def _check_and_handle_includes(self, from_file): """Look for an optional INCLUDE section in the given file path. If the parser set `paths`, it is cleared so that they do not keep showing up when additional files are parsed. """ logger.debug("Check/handle includes from %s", from_file) try: paths = self._parser.get("INCLUDE", "paths") except (config_parser.NoSectionError, config_parser.NoOptionError) as exc: logger.debug("_check_and_handle_includes: EXCEPTION: %s", exc) return paths_lines = [p.strip() for p in paths.split("\n")] logger.debug("paths = %s (wanted just once; CLEARING)", paths_lines) self._parser.remove_option("INCLUDE", "paths") for f in paths_lines: abspath = (f if os.path.isabs(f) else os.path.abspath( os.path.join(os.path.dirname(from_file), f))) use_path = os.path.normpath(abspath) if use_path in self._parsed_files: raise RecursionInConfigFile("In %s: %s already read", from_file, use_path) self._parsed_files.append(use_path) self._handle_rc_file(use_path)
[ "def", "_check_and_handle_includes", "(", "self", ",", "from_file", ")", ":", "logger", ".", "debug", "(", "\"Check/handle includes from %s\"", ",", "from_file", ")", "try", ":", "paths", "=", "self", ".", "_parser", ".", "get", "(", "\"INCLUDE\"", ",", "\"paths\"", ")", "except", "(", "config_parser", ".", "NoSectionError", ",", "config_parser", ".", "NoOptionError", ")", "as", "exc", ":", "logger", ".", "debug", "(", "\"_check_and_handle_includes: EXCEPTION: %s\"", ",", "exc", ")", "return", "paths_lines", "=", "[", "p", ".", "strip", "(", ")", "for", "p", "in", "paths", ".", "split", "(", "\"\\n\"", ")", "]", "logger", ".", "debug", "(", "\"paths = %s (wanted just once; CLEARING)\"", ",", "paths_lines", ")", "self", ".", "_parser", ".", "remove_option", "(", "\"INCLUDE\"", ",", "\"paths\"", ")", "for", "f", "in", "paths_lines", ":", "abspath", "=", "(", "f", "if", "os", ".", "path", ".", "isabs", "(", "f", ")", "else", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "from_file", ")", ",", "f", ")", ")", ")", "use_path", "=", "os", ".", "path", ".", "normpath", "(", "abspath", ")", "if", "use_path", "in", "self", ".", "_parsed_files", ":", "raise", "RecursionInConfigFile", "(", "\"In %s: %s already read\"", ",", "from_file", ",", "use_path", ")", "self", ".", "_parsed_files", ".", "append", "(", "use_path", ")", "self", ".", "_handle_rc_file", "(", "use_path", ")" ]
Look for an optional INCLUDE section in the given file path. If the parser set `paths`, it is cleared so that they do not keep showing up when additional files are parsed.
[ "Look", "for", "an", "optional", "INCLUDE", "section", "in", "the", "given", "file", "path", ".", "If", "the", "parser", "set", "paths", "it", "is", "cleared", "so", "that", "they", "do", "not", "keep", "showing", "up", "when", "additional", "files", "are", "parsed", "." ]
20db9852feff531f854972f76b412c442b2fafbf
https://github.com/lionel/counterparts/blob/20db9852feff531f854972f76b412c442b2fafbf/counterparts.py#L143-L168
241,981
jalanb/pysyte
pysyte/imports.py
extract_imports
def extract_imports(script): """Extract all imports from a python script""" if not os.path.isfile(script): raise ValueError('Not a file: %s' % script) parse_tree = parse_python(script) result = find_imports(parse_tree) result.path = script return result
python
def extract_imports(script): """Extract all imports from a python script""" if not os.path.isfile(script): raise ValueError('Not a file: %s' % script) parse_tree = parse_python(script) result = find_imports(parse_tree) result.path = script return result
[ "def", "extract_imports", "(", "script", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "script", ")", ":", "raise", "ValueError", "(", "'Not a file: %s'", "%", "script", ")", "parse_tree", "=", "parse_python", "(", "script", ")", "result", "=", "find_imports", "(", "parse_tree", ")", "result", ".", "path", "=", "script", "return", "result" ]
Extract all imports from a python script
[ "Extract", "all", "imports", "from", "a", "python", "script" ]
4e278101943d1ceb1a6bcaf6ddc72052ecf13114
https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/imports.py#L135-L142
241,982
cdeboever3/cdpybio
cdpybio/featureCounts.py
combine_counts
def combine_counts( fns, define_sample_name=None, ): """ Combine featureCounts output files for multiple samples. Parameters ---------- fns : list of strings Filenames of featureCounts output files to combine. define_sample_name : function A function mapping the featureCounts output filenames to sample names. If this is not provided, the header of the last column in the featureCounts output will be used as the sample name. Returns ------- combined_counts : pandas.DataFrame Combined featureCount counts. """ counts = [] for fn in fns: df = pd.read_table(fn, skiprows=1, index_col=0) counts.append(df[df.columns[-1]]) combined_counts = pd.DataFrame(counts).T if define_sample_name: names = [define_sample_name(x) for x in fns] combined_counts.columns = names combined_counts.index.name = '' return combined_counts
python
def combine_counts( fns, define_sample_name=None, ): """ Combine featureCounts output files for multiple samples. Parameters ---------- fns : list of strings Filenames of featureCounts output files to combine. define_sample_name : function A function mapping the featureCounts output filenames to sample names. If this is not provided, the header of the last column in the featureCounts output will be used as the sample name. Returns ------- combined_counts : pandas.DataFrame Combined featureCount counts. """ counts = [] for fn in fns: df = pd.read_table(fn, skiprows=1, index_col=0) counts.append(df[df.columns[-1]]) combined_counts = pd.DataFrame(counts).T if define_sample_name: names = [define_sample_name(x) for x in fns] combined_counts.columns = names combined_counts.index.name = '' return combined_counts
[ "def", "combine_counts", "(", "fns", ",", "define_sample_name", "=", "None", ",", ")", ":", "counts", "=", "[", "]", "for", "fn", "in", "fns", ":", "df", "=", "pd", ".", "read_table", "(", "fn", ",", "skiprows", "=", "1", ",", "index_col", "=", "0", ")", "counts", ".", "append", "(", "df", "[", "df", ".", "columns", "[", "-", "1", "]", "]", ")", "combined_counts", "=", "pd", ".", "DataFrame", "(", "counts", ")", ".", "T", "if", "define_sample_name", ":", "names", "=", "[", "define_sample_name", "(", "x", ")", "for", "x", "in", "fns", "]", "combined_counts", ".", "columns", "=", "names", "combined_counts", ".", "index", ".", "name", "=", "''", "return", "combined_counts" ]
Combine featureCounts output files for multiple samples. Parameters ---------- fns : list of strings Filenames of featureCounts output files to combine. define_sample_name : function A function mapping the featureCounts output filenames to sample names. If this is not provided, the header of the last column in the featureCounts output will be used as the sample name. Returns ------- combined_counts : pandas.DataFrame Combined featureCount counts.
[ "Combine", "featureCounts", "output", "files", "for", "multiple", "samples", "." ]
38efdf0e11d01bc00a135921cb91a19c03db5d5c
https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/featureCounts.py#L3-L35
241,983
fr33jc/bang
bang/deployers/default.py
ServerDeployer.add_to_inventory
def add_to_inventory(self): """Adds this server and its hostvars to the ansible inventory.""" self.stack.add_host(self.hostname, self.groups, self.hostvars)
python
def add_to_inventory(self): """Adds this server and its hostvars to the ansible inventory.""" self.stack.add_host(self.hostname, self.groups, self.hostvars)
[ "def", "add_to_inventory", "(", "self", ")", ":", "self", ".", "stack", ".", "add_host", "(", "self", ".", "hostname", ",", "self", ".", "groups", ",", "self", ".", "hostvars", ")" ]
Adds this server and its hostvars to the ansible inventory.
[ "Adds", "this", "server", "and", "its", "hostvars", "to", "the", "ansible", "inventory", "." ]
8f000713f88d2a9a8c1193b63ca10a6578560c16
https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/deployers/default.py#L45-L47
241,984
PRIArobotics/HedgehogUtils
hedgehog/utils/__init__.py
expect_all
def expect_all(a, b): """\ Asserts that two iterables contain the same values. """ assert all(_a == _b for _a, _b in zip_longest(a, b))
python
def expect_all(a, b): """\ Asserts that two iterables contain the same values. """ assert all(_a == _b for _a, _b in zip_longest(a, b))
[ "def", "expect_all", "(", "a", ",", "b", ")", ":", "assert", "all", "(", "_a", "==", "_b", "for", "_a", ",", "_b", "in", "zip_longest", "(", "a", ",", "b", ")", ")" ]
\ Asserts that two iterables contain the same values.
[ "\\", "Asserts", "that", "two", "iterables", "contain", "the", "same", "values", "." ]
cc368df270288c870cc66d707696ccb62823ca9c
https://github.com/PRIArobotics/HedgehogUtils/blob/cc368df270288c870cc66d707696ccb62823ca9c/hedgehog/utils/__init__.py#L14-L18
241,985
PRIArobotics/HedgehogUtils
hedgehog/utils/__init__.py
coroutine
def coroutine(func): """ A decorator to wrap a generator function into a callable interface. >>> @coroutine ... def sum(count): ... sum = 0 ... for _ in range(0, count): ... # note that generator arguments are passed as a tuple, hence `num, = ...` instead of `num = ...` ... num, = yield sum ... sum += num ... yield sum ... >>> add = sum(2) >>> add(2) 2 >>> add(3) 5 >>> add(4) Traceback (most recent call last): ... StopIteration As you can see, this lets you keep state between calls easily, as expected from a generator, while calling the function looks like a function. The same without `@coroutine` would look like this: >>> def sum(count): ... sum = 0 ... for _ in range(0, count): ... num = yield sum ... sum += num ... yield sum ... >>> add = sum(2) >>> next(add) # initial next call is necessary 0 >>> add.send(2) # to call the function, next or send must be used 2 >>> add.send(3) 5 >>> add.send(4) Traceback (most recent call last): ... StopIteration Here is an example that shows how to translate traditional functions to use this decorator: >>> def foo(a, b): ... # do some foo ... return a + b ... >>> def bar(c): ... # do some bar ... return 2*c ... >>> foo(1, 2) 3 >>> bar(3) 6 >>> @coroutine ... def func_maker(): ... a, b = yield ... # do some foo ... c, = yield foo(a, b) ... # do some bar ... yield bar(c) ... >>> func_once = func_maker() >>> func_once(1, 2) 3 >>> func_once(3) 6 The two differences are that a) using traditional functions, func1 and func2 don't share any context and b) using the decorator, both calls use the same function name, and calling the function is limited to wice (in this case). """ def decorator(*args, **kwargs): generator = func(*args, **kwargs) next(generator) return lambda *args: generator.send(args) return decorator
python
def coroutine(func): """ A decorator to wrap a generator function into a callable interface. >>> @coroutine ... def sum(count): ... sum = 0 ... for _ in range(0, count): ... # note that generator arguments are passed as a tuple, hence `num, = ...` instead of `num = ...` ... num, = yield sum ... sum += num ... yield sum ... >>> add = sum(2) >>> add(2) 2 >>> add(3) 5 >>> add(4) Traceback (most recent call last): ... StopIteration As you can see, this lets you keep state between calls easily, as expected from a generator, while calling the function looks like a function. The same without `@coroutine` would look like this: >>> def sum(count): ... sum = 0 ... for _ in range(0, count): ... num = yield sum ... sum += num ... yield sum ... >>> add = sum(2) >>> next(add) # initial next call is necessary 0 >>> add.send(2) # to call the function, next or send must be used 2 >>> add.send(3) 5 >>> add.send(4) Traceback (most recent call last): ... StopIteration Here is an example that shows how to translate traditional functions to use this decorator: >>> def foo(a, b): ... # do some foo ... return a + b ... >>> def bar(c): ... # do some bar ... return 2*c ... >>> foo(1, 2) 3 >>> bar(3) 6 >>> @coroutine ... def func_maker(): ... a, b = yield ... # do some foo ... c, = yield foo(a, b) ... # do some bar ... yield bar(c) ... >>> func_once = func_maker() >>> func_once(1, 2) 3 >>> func_once(3) 6 The two differences are that a) using traditional functions, func1 and func2 don't share any context and b) using the decorator, both calls use the same function name, and calling the function is limited to wice (in this case). """ def decorator(*args, **kwargs): generator = func(*args, **kwargs) next(generator) return lambda *args: generator.send(args) return decorator
[ "def", "coroutine", "(", "func", ")", ":", "def", "decorator", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "generator", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "next", "(", "generator", ")", "return", "lambda", "*", "args", ":", "generator", ".", "send", "(", "args", ")", "return", "decorator" ]
A decorator to wrap a generator function into a callable interface. >>> @coroutine ... def sum(count): ... sum = 0 ... for _ in range(0, count): ... # note that generator arguments are passed as a tuple, hence `num, = ...` instead of `num = ...` ... num, = yield sum ... sum += num ... yield sum ... >>> add = sum(2) >>> add(2) 2 >>> add(3) 5 >>> add(4) Traceback (most recent call last): ... StopIteration As you can see, this lets you keep state between calls easily, as expected from a generator, while calling the function looks like a function. The same without `@coroutine` would look like this: >>> def sum(count): ... sum = 0 ... for _ in range(0, count): ... num = yield sum ... sum += num ... yield sum ... >>> add = sum(2) >>> next(add) # initial next call is necessary 0 >>> add.send(2) # to call the function, next or send must be used 2 >>> add.send(3) 5 >>> add.send(4) Traceback (most recent call last): ... StopIteration Here is an example that shows how to translate traditional functions to use this decorator: >>> def foo(a, b): ... # do some foo ... return a + b ... >>> def bar(c): ... # do some bar ... return 2*c ... >>> foo(1, 2) 3 >>> bar(3) 6 >>> @coroutine ... def func_maker(): ... a, b = yield ... # do some foo ... c, = yield foo(a, b) ... # do some bar ... yield bar(c) ... >>> func_once = func_maker() >>> func_once(1, 2) 3 >>> func_once(3) 6 The two differences are that a) using traditional functions, func1 and func2 don't share any context and b) using the decorator, both calls use the same function name, and calling the function is limited to wice (in this case).
[ "A", "decorator", "to", "wrap", "a", "generator", "function", "into", "a", "callable", "interface", "." ]
cc368df270288c870cc66d707696ccb62823ca9c
https://github.com/PRIArobotics/HedgehogUtils/blob/cc368df270288c870cc66d707696ccb62823ca9c/hedgehog/utils/__init__.py#L21-L103
241,986
timothyhahn/rui
rui/rui.py
World.add_entity
def add_entity(self, entity, second=False): ''' Add entity to world. entity is of type Entity ''' if not entity in self._entities: if second: self._entities.append(entity) else: entity.set_world(self) else: raise DuplicateEntityError(entity)
python
def add_entity(self, entity, second=False): ''' Add entity to world. entity is of type Entity ''' if not entity in self._entities: if second: self._entities.append(entity) else: entity.set_world(self) else: raise DuplicateEntityError(entity)
[ "def", "add_entity", "(", "self", ",", "entity", ",", "second", "=", "False", ")", ":", "if", "not", "entity", "in", "self", ".", "_entities", ":", "if", "second", ":", "self", ".", "_entities", ".", "append", "(", "entity", ")", "else", ":", "entity", ".", "set_world", "(", "self", ")", "else", ":", "raise", "DuplicateEntityError", "(", "entity", ")" ]
Add entity to world. entity is of type Entity
[ "Add", "entity", "to", "world", ".", "entity", "is", "of", "type", "Entity" ]
ac9f587fb486760d77332866c6e876f78a810f74
https://github.com/timothyhahn/rui/blob/ac9f587fb486760d77332866c6e876f78a810f74/rui/rui.py#L21-L31
241,987
timothyhahn/rui
rui/rui.py
World.register_entity_to_group
def register_entity_to_group(self, entity, group): ''' Add entity to a group. If group does not exist, entity will be added as first member entity is of type Entity group is a string that is the name of the group ''' if entity in self._entities: if group in self._groups: self._groups[group].append(entity) else: self._groups[group] = [entity] else: raise UnmanagedEntityError(entity)
python
def register_entity_to_group(self, entity, group): ''' Add entity to a group. If group does not exist, entity will be added as first member entity is of type Entity group is a string that is the name of the group ''' if entity in self._entities: if group in self._groups: self._groups[group].append(entity) else: self._groups[group] = [entity] else: raise UnmanagedEntityError(entity)
[ "def", "register_entity_to_group", "(", "self", ",", "entity", ",", "group", ")", ":", "if", "entity", "in", "self", ".", "_entities", ":", "if", "group", "in", "self", ".", "_groups", ":", "self", ".", "_groups", "[", "group", "]", ".", "append", "(", "entity", ")", "else", ":", "self", ".", "_groups", "[", "group", "]", "=", "[", "entity", "]", "else", ":", "raise", "UnmanagedEntityError", "(", "entity", ")" ]
Add entity to a group. If group does not exist, entity will be added as first member entity is of type Entity group is a string that is the name of the group
[ "Add", "entity", "to", "a", "group", ".", "If", "group", "does", "not", "exist", "entity", "will", "be", "added", "as", "first", "member", "entity", "is", "of", "type", "Entity", "group", "is", "a", "string", "that", "is", "the", "name", "of", "the", "group" ]
ac9f587fb486760d77332866c6e876f78a810f74
https://github.com/timothyhahn/rui/blob/ac9f587fb486760d77332866c6e876f78a810f74/rui/rui.py#L52-L65
241,988
timothyhahn/rui
rui/rui.py
World.deregister_entity_from_group
def deregister_entity_from_group(self, entity, group): ''' Removes entity from group ''' if entity in self._entities: if entity in self._groups[group]: self._groups[group].remove(entity) else: raise UnmanagedEntityError(entity)
python
def deregister_entity_from_group(self, entity, group): ''' Removes entity from group ''' if entity in self._entities: if entity in self._groups[group]: self._groups[group].remove(entity) else: raise UnmanagedEntityError(entity)
[ "def", "deregister_entity_from_group", "(", "self", ",", "entity", ",", "group", ")", ":", "if", "entity", "in", "self", ".", "_entities", ":", "if", "entity", "in", "self", ".", "_groups", "[", "group", "]", ":", "self", ".", "_groups", "[", "group", "]", ".", "remove", "(", "entity", ")", "else", ":", "raise", "UnmanagedEntityError", "(", "entity", ")" ]
Removes entity from group
[ "Removes", "entity", "from", "group" ]
ac9f587fb486760d77332866c6e876f78a810f74
https://github.com/timothyhahn/rui/blob/ac9f587fb486760d77332866c6e876f78a810f74/rui/rui.py#L67-L75
241,989
timothyhahn/rui
rui/rui.py
World.remove_entity
def remove_entity(self, entity, second=False): ''' Removes entity from world and kills entity ''' if entity in self._entities: if second: for group in self._groups.keys(): if entity in self._groups[group]: self.deregister_entity_from_group(entity, group) self._entities.remove(entity) else: entity.kill() else: raise UnmanagedEntityError(entity)
python
def remove_entity(self, entity, second=False): ''' Removes entity from world and kills entity ''' if entity in self._entities: if second: for group in self._groups.keys(): if entity in self._groups[group]: self.deregister_entity_from_group(entity, group) self._entities.remove(entity) else: entity.kill() else: raise UnmanagedEntityError(entity)
[ "def", "remove_entity", "(", "self", ",", "entity", ",", "second", "=", "False", ")", ":", "if", "entity", "in", "self", ".", "_entities", ":", "if", "second", ":", "for", "group", "in", "self", ".", "_groups", ".", "keys", "(", ")", ":", "if", "entity", "in", "self", ".", "_groups", "[", "group", "]", ":", "self", ".", "deregister_entity_from_group", "(", "entity", ",", "group", ")", "self", ".", "_entities", ".", "remove", "(", "entity", ")", "else", ":", "entity", ".", "kill", "(", ")", "else", ":", "raise", "UnmanagedEntityError", "(", "entity", ")" ]
Removes entity from world and kills entity
[ "Removes", "entity", "from", "world", "and", "kills", "entity" ]
ac9f587fb486760d77332866c6e876f78a810f74
https://github.com/timothyhahn/rui/blob/ac9f587fb486760d77332866c6e876f78a810f74/rui/rui.py#L84-L97
241,990
timothyhahn/rui
rui/rui.py
World.remove_system
def remove_system(self, system): ''' Removes system from world and kills system ''' if system in self._systems: self._systems.remove(system) else: raise UnmanagedSystemError(system)
python
def remove_system(self, system): ''' Removes system from world and kills system ''' if system in self._systems: self._systems.remove(system) else: raise UnmanagedSystemError(system)
[ "def", "remove_system", "(", "self", ",", "system", ")", ":", "if", "system", "in", "self", ".", "_systems", ":", "self", ".", "_systems", ".", "remove", "(", "system", ")", "else", ":", "raise", "UnmanagedSystemError", "(", "system", ")" ]
Removes system from world and kills system
[ "Removes", "system", "from", "world", "and", "kills", "system" ]
ac9f587fb486760d77332866c6e876f78a810f74
https://github.com/timothyhahn/rui/blob/ac9f587fb486760d77332866c6e876f78a810f74/rui/rui.py#L99-L106
241,991
timothyhahn/rui
rui/rui.py
World.get_entity_by_tag
def get_entity_by_tag(self, tag): ''' Get entity by tag tag is a string that is the tag of the Entity. ''' matching_entities = list(filter(lambda entity: entity.get_tag() == tag, self._entities)) if matching_entities: return matching_entities[0] else: return None
python
def get_entity_by_tag(self, tag): ''' Get entity by tag tag is a string that is the tag of the Entity. ''' matching_entities = list(filter(lambda entity: entity.get_tag() == tag, self._entities)) if matching_entities: return matching_entities[0] else: return None
[ "def", "get_entity_by_tag", "(", "self", ",", "tag", ")", ":", "matching_entities", "=", "list", "(", "filter", "(", "lambda", "entity", ":", "entity", ".", "get_tag", "(", ")", "==", "tag", ",", "self", ".", "_entities", ")", ")", "if", "matching_entities", ":", "return", "matching_entities", "[", "0", "]", "else", ":", "return", "None" ]
Get entity by tag tag is a string that is the tag of the Entity.
[ "Get", "entity", "by", "tag", "tag", "is", "a", "string", "that", "is", "the", "tag", "of", "the", "Entity", "." ]
ac9f587fb486760d77332866c6e876f78a810f74
https://github.com/timothyhahn/rui/blob/ac9f587fb486760d77332866c6e876f78a810f74/rui/rui.py#L108-L118
241,992
timothyhahn/rui
rui/rui.py
World.get_entities_by_components
def get_entities_by_components(self, *components): ''' Get entity by list of components All members of components must be of type Component ''' return list(filter(lambda entity: set(components) <= set(map(type, entity.get_components())), self._entities))
python
def get_entities_by_components(self, *components): ''' Get entity by list of components All members of components must be of type Component ''' return list(filter(lambda entity: set(components) <= set(map(type, entity.get_components())), self._entities))
[ "def", "get_entities_by_components", "(", "self", ",", "*", "components", ")", ":", "return", "list", "(", "filter", "(", "lambda", "entity", ":", "set", "(", "components", ")", "<=", "set", "(", "map", "(", "type", ",", "entity", ".", "get_components", "(", ")", ")", ")", ",", "self", ".", "_entities", ")", ")" ]
Get entity by list of components All members of components must be of type Component
[ "Get", "entity", "by", "list", "of", "components", "All", "members", "of", "components", "must", "be", "of", "type", "Component" ]
ac9f587fb486760d77332866c6e876f78a810f74
https://github.com/timothyhahn/rui/blob/ac9f587fb486760d77332866c6e876f78a810f74/rui/rui.py#L120-L128
241,993
timothyhahn/rui
rui/rui.py
Entity.set_world
def set_world(self, world): ''' Sets the world an entity belongs to. Checks for tag conflicts before adding. ''' if world.get_entity_by_tag(self._tag) and self._tag != '': raise NonUniqueTagError(self._tag) else: self._world = world world.add_entity(self, True)
python
def set_world(self, world): ''' Sets the world an entity belongs to. Checks for tag conflicts before adding. ''' if world.get_entity_by_tag(self._tag) and self._tag != '': raise NonUniqueTagError(self._tag) else: self._world = world world.add_entity(self, True)
[ "def", "set_world", "(", "self", ",", "world", ")", ":", "if", "world", ".", "get_entity_by_tag", "(", "self", ".", "_tag", ")", "and", "self", ".", "_tag", "!=", "''", ":", "raise", "NonUniqueTagError", "(", "self", ".", "_tag", ")", "else", ":", "self", ".", "_world", "=", "world", "world", ".", "add_entity", "(", "self", ",", "True", ")" ]
Sets the world an entity belongs to. Checks for tag conflicts before adding.
[ "Sets", "the", "world", "an", "entity", "belongs", "to", ".", "Checks", "for", "tag", "conflicts", "before", "adding", "." ]
ac9f587fb486760d77332866c6e876f78a810f74
https://github.com/timothyhahn/rui/blob/ac9f587fb486760d77332866c6e876f78a810f74/rui/rui.py#L189-L198
241,994
timothyhahn/rui
rui/rui.py
Entity.set_tag
def set_tag(self, tag): ''' Sets the tag. If the Entity belongs to the world it will check for tag conflicts. ''' if self._world: if self._world.get_entity_by_tag(tag): raise NonUniqueTagError(tag) self._tag = tag
python
def set_tag(self, tag): ''' Sets the tag. If the Entity belongs to the world it will check for tag conflicts. ''' if self._world: if self._world.get_entity_by_tag(tag): raise NonUniqueTagError(tag) self._tag = tag
[ "def", "set_tag", "(", "self", ",", "tag", ")", ":", "if", "self", ".", "_world", ":", "if", "self", ".", "_world", ".", "get_entity_by_tag", "(", "tag", ")", ":", "raise", "NonUniqueTagError", "(", "tag", ")", "self", ".", "_tag", "=", "tag" ]
Sets the tag. If the Entity belongs to the world it will check for tag conflicts.
[ "Sets", "the", "tag", ".", "If", "the", "Entity", "belongs", "to", "the", "world", "it", "will", "check", "for", "tag", "conflicts", "." ]
ac9f587fb486760d77332866c6e876f78a810f74
https://github.com/timothyhahn/rui/blob/ac9f587fb486760d77332866c6e876f78a810f74/rui/rui.py#L215-L223
241,995
timothyhahn/rui
rui/rui.py
Entity.add_component
def add_component(self, component): ''' Adds a Component to an Entity ''' if component not in self._components: self._components.append(component) else: # Replace Component self._components[self._components.index(component)] = component
python
def add_component(self, component): ''' Adds a Component to an Entity ''' if component not in self._components: self._components.append(component) else: # Replace Component self._components[self._components.index(component)] = component
[ "def", "add_component", "(", "self", ",", "component", ")", ":", "if", "component", "not", "in", "self", ".", "_components", ":", "self", ".", "_components", ".", "append", "(", "component", ")", "else", ":", "# Replace Component", "self", ".", "_components", "[", "self", ".", "_components", ".", "index", "(", "component", ")", "]", "=", "component" ]
Adds a Component to an Entity
[ "Adds", "a", "Component", "to", "an", "Entity" ]
ac9f587fb486760d77332866c6e876f78a810f74
https://github.com/timothyhahn/rui/blob/ac9f587fb486760d77332866c6e876f78a810f74/rui/rui.py#L236-L243
241,996
timothyhahn/rui
rui/rui.py
Entity.get_component
def get_component(self, component_type): ''' Gets component of component_type or returns None ''' matching_components = list(filter(lambda component: isinstance(component, component_type), self._components)) if matching_components: return matching_components[0] else: return None
python
def get_component(self, component_type): ''' Gets component of component_type or returns None ''' matching_components = list(filter(lambda component: isinstance(component, component_type), self._components)) if matching_components: return matching_components[0] else: return None
[ "def", "get_component", "(", "self", ",", "component_type", ")", ":", "matching_components", "=", "list", "(", "filter", "(", "lambda", "component", ":", "isinstance", "(", "component", ",", "component_type", ")", ",", "self", ".", "_components", ")", ")", "if", "matching_components", ":", "return", "matching_components", "[", "0", "]", "else", ":", "return", "None" ]
Gets component of component_type or returns None
[ "Gets", "component", "of", "component_type", "or", "returns", "None" ]
ac9f587fb486760d77332866c6e876f78a810f74
https://github.com/timothyhahn/rui/blob/ac9f587fb486760d77332866c6e876f78a810f74/rui/rui.py#L246-L257
241,997
scivision/histutils
histutils/__init__.py
write_quota
def write_quota(outbytes: int, outfn: Path) -> Union[None, int]: """ aborts writing if not enough space on drive to write """ if not outfn: return None anch = Path(outfn).resolve().anchor freeout = shutil.disk_usage(anch).free if freeout < 10 * outbytes: raise IOError(f'out of disk space on {anch}.' '{freeout/1e9} GB free, wanting to write {outbytes/1e9} GB.') return freeout
python
def write_quota(outbytes: int, outfn: Path) -> Union[None, int]: """ aborts writing if not enough space on drive to write """ if not outfn: return None anch = Path(outfn).resolve().anchor freeout = shutil.disk_usage(anch).free if freeout < 10 * outbytes: raise IOError(f'out of disk space on {anch}.' '{freeout/1e9} GB free, wanting to write {outbytes/1e9} GB.') return freeout
[ "def", "write_quota", "(", "outbytes", ":", "int", ",", "outfn", ":", "Path", ")", "->", "Union", "[", "None", ",", "int", "]", ":", "if", "not", "outfn", ":", "return", "None", "anch", "=", "Path", "(", "outfn", ")", ".", "resolve", "(", ")", ".", "anchor", "freeout", "=", "shutil", ".", "disk_usage", "(", "anch", ")", ".", "free", "if", "freeout", "<", "10", "*", "outbytes", ":", "raise", "IOError", "(", "f'out of disk space on {anch}.'", "'{freeout/1e9} GB free, wanting to write {outbytes/1e9} GB.'", ")", "return", "freeout" ]
aborts writing if not enough space on drive to write
[ "aborts", "writing", "if", "not", "enough", "space", "on", "drive", "to", "write" ]
859a91d3894cb57faed34881c6ea16130b90571e
https://github.com/scivision/histutils/blob/859a91d3894cb57faed34881c6ea16130b90571e/histutils/__init__.py#L12-L26
241,998
scivision/histutils
histutils/__init__.py
sixteen2eight
def sixteen2eight(I: np.ndarray, Clim: tuple) -> np.ndarray: """ scipy.misc.bytescale had bugs inputs: ------ I: 2-D Numpy array of grayscale image data Clim: length 2 of tuple or numpy 1-D array specifying lowest and highest expected values in grayscale image Michael Hirsch, Ph.D. """ Q = normframe(I, Clim) Q *= 255 # stretch to [0,255] as a float return Q.round().astype(np.uint8)
python
def sixteen2eight(I: np.ndarray, Clim: tuple) -> np.ndarray: """ scipy.misc.bytescale had bugs inputs: ------ I: 2-D Numpy array of grayscale image data Clim: length 2 of tuple or numpy 1-D array specifying lowest and highest expected values in grayscale image Michael Hirsch, Ph.D. """ Q = normframe(I, Clim) Q *= 255 # stretch to [0,255] as a float return Q.round().astype(np.uint8)
[ "def", "sixteen2eight", "(", "I", ":", "np", ".", "ndarray", ",", "Clim", ":", "tuple", ")", "->", "np", ".", "ndarray", ":", "Q", "=", "normframe", "(", "I", ",", "Clim", ")", "Q", "*=", "255", "# stretch to [0,255] as a float", "return", "Q", ".", "round", "(", ")", ".", "astype", "(", "np", ".", "uint8", ")" ]
scipy.misc.bytescale had bugs inputs: ------ I: 2-D Numpy array of grayscale image data Clim: length 2 of tuple or numpy 1-D array specifying lowest and highest expected values in grayscale image Michael Hirsch, Ph.D.
[ "scipy", ".", "misc", ".", "bytescale", "had", "bugs" ]
859a91d3894cb57faed34881c6ea16130b90571e
https://github.com/scivision/histutils/blob/859a91d3894cb57faed34881c6ea16130b90571e/histutils/__init__.py#L29-L41
241,999
scivision/histutils
histutils/__init__.py
req2frame
def req2frame(req, N: int=0): """ output has to be numpy.arange for > comparison """ if req is None: frame = np.arange(N, dtype=np.int64) elif isinstance(req, int): # the user is specifying a step size frame = np.arange(0, N, req, dtype=np.int64) elif len(req) == 1: frame = np.arange(0, N, req[0], dtype=np.int64) elif len(req) == 2: frame = np.arange(req[0], req[1], dtype=np.int64) elif len(req) == 3: # this is -1 because user is specifying one-based index frame = np.arange(req[0], req[1], req[2], dtype=np.int64) - 1 # keep -1 ! else: # just return all frames frame = np.arange(N, dtype=np.int64) return frame
python
def req2frame(req, N: int=0): """ output has to be numpy.arange for > comparison """ if req is None: frame = np.arange(N, dtype=np.int64) elif isinstance(req, int): # the user is specifying a step size frame = np.arange(0, N, req, dtype=np.int64) elif len(req) == 1: frame = np.arange(0, N, req[0], dtype=np.int64) elif len(req) == 2: frame = np.arange(req[0], req[1], dtype=np.int64) elif len(req) == 3: # this is -1 because user is specifying one-based index frame = np.arange(req[0], req[1], req[2], dtype=np.int64) - 1 # keep -1 ! else: # just return all frames frame = np.arange(N, dtype=np.int64) return frame
[ "def", "req2frame", "(", "req", ",", "N", ":", "int", "=", "0", ")", ":", "if", "req", "is", "None", ":", "frame", "=", "np", ".", "arange", "(", "N", ",", "dtype", "=", "np", ".", "int64", ")", "elif", "isinstance", "(", "req", ",", "int", ")", ":", "# the user is specifying a step size", "frame", "=", "np", ".", "arange", "(", "0", ",", "N", ",", "req", ",", "dtype", "=", "np", ".", "int64", ")", "elif", "len", "(", "req", ")", "==", "1", ":", "frame", "=", "np", ".", "arange", "(", "0", ",", "N", ",", "req", "[", "0", "]", ",", "dtype", "=", "np", ".", "int64", ")", "elif", "len", "(", "req", ")", "==", "2", ":", "frame", "=", "np", ".", "arange", "(", "req", "[", "0", "]", ",", "req", "[", "1", "]", ",", "dtype", "=", "np", ".", "int64", ")", "elif", "len", "(", "req", ")", "==", "3", ":", "# this is -1 because user is specifying one-based index", "frame", "=", "np", ".", "arange", "(", "req", "[", "0", "]", ",", "req", "[", "1", "]", ",", "req", "[", "2", "]", ",", "dtype", "=", "np", ".", "int64", ")", "-", "1", "# keep -1 !", "else", ":", "# just return all frames", "frame", "=", "np", ".", "arange", "(", "N", ",", "dtype", "=", "np", ".", "int64", ")", "return", "frame" ]
output has to be numpy.arange for > comparison
[ "output", "has", "to", "be", "numpy", ".", "arange", "for", ">", "comparison" ]
859a91d3894cb57faed34881c6ea16130b90571e
https://github.com/scivision/histutils/blob/859a91d3894cb57faed34881c6ea16130b90571e/histutils/__init__.py#L94-L113