repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
matheuscas/pyIE
ie/ac.py
start
def start(st_reg_number): """Checks the number valiaty for the Acre state""" #st_reg_number = str(st_reg_number) weights = [4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2] digits = st_reg_number[:len(st_reg_number) - 2] check_digits = st_reg_number[-2:] divisor = 11 if len(st_reg_number) > 13: return False sum_total = 0 for i in range(len(digits)): sum_total = sum_total + int(digits[i]) * weights[i] rest_division = sum_total % divisor first_digit = divisor - rest_division if first_digit == 10 or first_digit == 11: first_digit = 0 if str(first_digit) != check_digits[0]: return False digits = digits + str(first_digit) weights = [5] + weights sum_total = 0 for i in range(len(digits)): sum_total = sum_total + int(digits[i]) * weights[i] rest_division = sum_total % divisor second_digit = divisor - rest_division if second_digit == 10 or second_digit == 11: second_digit = 0 return str(first_digit) + str(second_digit) == check_digits
python
def start(st_reg_number): """Checks the number valiaty for the Acre state""" #st_reg_number = str(st_reg_number) weights = [4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2] digits = st_reg_number[:len(st_reg_number) - 2] check_digits = st_reg_number[-2:] divisor = 11 if len(st_reg_number) > 13: return False sum_total = 0 for i in range(len(digits)): sum_total = sum_total + int(digits[i]) * weights[i] rest_division = sum_total % divisor first_digit = divisor - rest_division if first_digit == 10 or first_digit == 11: first_digit = 0 if str(first_digit) != check_digits[0]: return False digits = digits + str(first_digit) weights = [5] + weights sum_total = 0 for i in range(len(digits)): sum_total = sum_total + int(digits[i]) * weights[i] rest_division = sum_total % divisor second_digit = divisor - rest_division if second_digit == 10 or second_digit == 11: second_digit = 0 return str(first_digit) + str(second_digit) == check_digits
[ "def", "start", "(", "st_reg_number", ")", ":", "#st_reg_number = str(st_reg_number)", "weights", "=", "[", "4", ",", "3", ",", "2", ",", "9", ",", "8", ",", "7", ",", "6", ",", "5", ",", "4", ",", "3", ",", "2", "]", "digits", "=", "st_reg_number"...
Checks the number valiaty for the Acre state
[ "Checks", "the", "number", "valiaty", "for", "the", "Acre", "state" ]
train
https://github.com/matheuscas/pyIE/blob/9e942dd692d0eab8a1e7717ad7ff3fe90d590ffb/ie/ac.py#L4-L42
Riparo/nougat
nougat/config.py
Config.load_from_object
def load_from_object(self, object_name): """ load all upper parameters of object as config parameters :param object_name: the object you wanna load :return: """ for key in dir(object_name): if key.isupper(): self[key] = getattr(object_name, key)
python
def load_from_object(self, object_name): """ load all upper parameters of object as config parameters :param object_name: the object you wanna load :return: """ for key in dir(object_name): if key.isupper(): self[key] = getattr(object_name, key)
[ "def", "load_from_object", "(", "self", ",", "object_name", ")", ":", "for", "key", "in", "dir", "(", "object_name", ")", ":", "if", "key", ".", "isupper", "(", ")", ":", "self", "[", "key", "]", "=", "getattr", "(", "object_name", ",", "key", ")" ]
load all upper parameters of object as config parameters :param object_name: the object you wanna load :return:
[ "load", "all", "upper", "parameters", "of", "object", "as", "config", "parameters", ":", "param", "object_name", ":", "the", "object", "you", "wanna", "load", ":", "return", ":" ]
train
https://github.com/Riparo/nougat/blob/8453bc37e0b782f296952f0a418532ebbbcd74f3/nougat/config.py#L21-L29
matheuscas/pyIE
ie/mg.py
start
def start(st_reg_number): """Checks the number valiaty for the Minas Gerais state""" #st_reg_number = str(st_reg_number) number_state_registration_first_digit = st_reg_number[0:3] + '0' + st_reg_number[3: len(st_reg_number)-2] weights_first_digit = [1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2] wights_second_digit = [3, 2, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2] first_digit = st_reg_number[-2] second_digit = st_reg_number[-1] sum_first_digit = 0 sum_second_digit = 0 sum_result_digit = '' sum_end = 0 if len(st_reg_number) != 13: return False for i in range(0, 12): sum_first_digit = weights_first_digit[i] * int(number_state_registration_first_digit[i]) sum_result_digit = sum_result_digit + str(sum_first_digit) for i in range(0, len(sum_result_digit)): sum_end = sum_end + int(sum_result_digit[i]) if sum_end % 10 == 0: check_digit_one = 0 elif sum_end < 10: check_digit_one = 10 - sum_end elif sum_end > 10: check_digit_one = (10 - sum_end % 10) if str(check_digit_one) != first_digit: return False number_state_registration_second_digit = st_reg_number + str(check_digit_one) for i in range(0, 12): sum_second_digit = sum_second_digit + wights_second_digit[i] * int(number_state_registration_second_digit[i]) check_second_digit = 11 - sum_second_digit % 11 if sum_second_digit == 1 or sum_second_digit == 0: return second_digit == '0' else: return str(check_second_digit) == second_digit
python
def start(st_reg_number): """Checks the number valiaty for the Minas Gerais state""" #st_reg_number = str(st_reg_number) number_state_registration_first_digit = st_reg_number[0:3] + '0' + st_reg_number[3: len(st_reg_number)-2] weights_first_digit = [1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2] wights_second_digit = [3, 2, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2] first_digit = st_reg_number[-2] second_digit = st_reg_number[-1] sum_first_digit = 0 sum_second_digit = 0 sum_result_digit = '' sum_end = 0 if len(st_reg_number) != 13: return False for i in range(0, 12): sum_first_digit = weights_first_digit[i] * int(number_state_registration_first_digit[i]) sum_result_digit = sum_result_digit + str(sum_first_digit) for i in range(0, len(sum_result_digit)): sum_end = sum_end + int(sum_result_digit[i]) if sum_end % 10 == 0: check_digit_one = 0 elif sum_end < 10: check_digit_one = 10 - sum_end elif sum_end > 10: check_digit_one = (10 - sum_end % 10) if str(check_digit_one) != first_digit: return False number_state_registration_second_digit = st_reg_number + str(check_digit_one) for i in range(0, 12): sum_second_digit = sum_second_digit + wights_second_digit[i] * int(number_state_registration_second_digit[i]) check_second_digit = 11 - sum_second_digit % 11 if sum_second_digit == 1 or sum_second_digit == 0: return second_digit == '0' else: return str(check_second_digit) == second_digit
[ "def", "start", "(", "st_reg_number", ")", ":", "#st_reg_number = str(st_reg_number)", "number_state_registration_first_digit", "=", "st_reg_number", "[", "0", ":", "3", "]", "+", "'0'", "+", "st_reg_number", "[", "3", ":", "len", "(", "st_reg_number", ")", "-", ...
Checks the number valiaty for the Minas Gerais state
[ "Checks", "the", "number", "valiaty", "for", "the", "Minas", "Gerais", "state" ]
train
https://github.com/matheuscas/pyIE/blob/9e942dd692d0eab8a1e7717ad7ff3fe90d590ffb/ie/mg.py#L5-L61
Riparo/nougat
nougat/app.py
Nougat.use
def use(self, *middleware: MiddlewareType) -> None: """ Register Middleware :param middleware: The Middleware Function """ for m in middleware: if is_middleware(m): self.middleware.append(m)
python
def use(self, *middleware: MiddlewareType) -> None: """ Register Middleware :param middleware: The Middleware Function """ for m in middleware: if is_middleware(m): self.middleware.append(m)
[ "def", "use", "(", "self", ",", "*", "middleware", ":", "MiddlewareType", ")", "->", "None", ":", "for", "m", "in", "middleware", ":", "if", "is_middleware", "(", "m", ")", ":", "self", ".", "middleware", ".", "append", "(", "m", ")" ]
Register Middleware :param middleware: The Middleware Function
[ "Register", "Middleware", ":", "param", "middleware", ":", "The", "Middleware", "Function" ]
train
https://github.com/Riparo/nougat/blob/8453bc37e0b782f296952f0a418532ebbbcd74f3/nougat/app.py#L35-L42
Riparo/nougat
nougat/app.py
Nougat.handler
async def handler(self, request: Request) -> Tuple[int, str, List[Tuple[str, str]], bytes]: """ The handler handling each request :param request: the Request instance :return: The Response instance """ response: 'Response' = Response() handler: Callable = empty chain_reverse = self.middleware[::-1] for middleware in chain_reverse: handler = map_context_to_middleware(middleware, self, request, response, handler) try: await handler() except HttpException as e: response.code = e.code response.content = e.body return response.code, response.status, response.header_as_list, response.output
python
async def handler(self, request: Request) -> Tuple[int, str, List[Tuple[str, str]], bytes]: """ The handler handling each request :param request: the Request instance :return: The Response instance """ response: 'Response' = Response() handler: Callable = empty chain_reverse = self.middleware[::-1] for middleware in chain_reverse: handler = map_context_to_middleware(middleware, self, request, response, handler) try: await handler() except HttpException as e: response.code = e.code response.content = e.body return response.code, response.status, response.header_as_list, response.output
[ "async", "def", "handler", "(", "self", ",", "request", ":", "Request", ")", "->", "Tuple", "[", "int", ",", "str", ",", "List", "[", "Tuple", "[", "str", ",", "str", "]", "]", ",", "bytes", "]", ":", "response", ":", "'Response'", "=", "Response",...
The handler handling each request :param request: the Request instance :return: The Response instance
[ "The", "handler", "handling", "each", "request", ":", "param", "request", ":", "the", "Request", "instance", ":", "return", ":", "The", "Response", "instance" ]
train
https://github.com/Riparo/nougat/blob/8453bc37e0b782f296952f0a418532ebbbcd74f3/nougat/app.py#L44-L64
Riparo/nougat
nougat/app.py
Nougat.run
def run(self, host: str="localhost", port: int=8000, debug: bool=False): """ start the http server :param host: The listening host :param port: The listening port :param debug: whether it is in debug mod or not """ self.debug = debug loop = asyncio.get_event_loop() try: loop.run_until_complete(self.start_server(host, port)) loop.run_forever() except KeyboardInterrupt: loop.run_until_complete(self.signal_manager.activate('before_close')) loop.run_until_complete(self.close_server_async()) loop.run_until_complete(self.signal_manager.activate('after_close')) loop.run_until_complete(asyncio.gather(*asyncio.Task.all_tasks())) loop.close()
python
def run(self, host: str="localhost", port: int=8000, debug: bool=False): """ start the http server :param host: The listening host :param port: The listening port :param debug: whether it is in debug mod or not """ self.debug = debug loop = asyncio.get_event_loop() try: loop.run_until_complete(self.start_server(host, port)) loop.run_forever() except KeyboardInterrupt: loop.run_until_complete(self.signal_manager.activate('before_close')) loop.run_until_complete(self.close_server_async()) loop.run_until_complete(self.signal_manager.activate('after_close')) loop.run_until_complete(asyncio.gather(*asyncio.Task.all_tasks())) loop.close()
[ "def", "run", "(", "self", ",", "host", ":", "str", "=", "\"localhost\"", ",", "port", ":", "int", "=", "8000", ",", "debug", ":", "bool", "=", "False", ")", ":", "self", ".", "debug", "=", "debug", "loop", "=", "asyncio", ".", "get_event_loop", "(...
start the http server :param host: The listening host :param port: The listening port :param debug: whether it is in debug mod or not
[ "start", "the", "http", "server", ":", "param", "host", ":", "The", "listening", "host", ":", "param", "port", ":", "The", "listening", "port", ":", "param", "debug", ":", "whether", "it", "is", "in", "debug", "mod", "or", "not" ]
train
https://github.com/Riparo/nougat/blob/8453bc37e0b782f296952f0a418532ebbbcd74f3/nougat/app.py#L66-L84
matheuscas/pyIE
ie/am.py
start
def start(st_reg_number): """Checks the number valiaty for the Amazonas state""" weights = range(2, 10) digits = st_reg_number[0:len(st_reg_number) - 1] control_digit = 11 check_digit = st_reg_number[-1:] if len(st_reg_number) != 9: return False sum_total = 0 for i in weights: sum_total = sum_total + i * int(digits[i-2]) if sum_total < control_digit: control_digit = 11 - sum_total return str(digit_calculated) == check_digit elif sum_total % 11 <= 1: return '0' == check_digit else: digit_calculated = 11 - sum_total % 11 return str(digit_calculated) == check_digit
python
def start(st_reg_number): """Checks the number valiaty for the Amazonas state""" weights = range(2, 10) digits = st_reg_number[0:len(st_reg_number) - 1] control_digit = 11 check_digit = st_reg_number[-1:] if len(st_reg_number) != 9: return False sum_total = 0 for i in weights: sum_total = sum_total + i * int(digits[i-2]) if sum_total < control_digit: control_digit = 11 - sum_total return str(digit_calculated) == check_digit elif sum_total % 11 <= 1: return '0' == check_digit else: digit_calculated = 11 - sum_total % 11 return str(digit_calculated) == check_digit
[ "def", "start", "(", "st_reg_number", ")", ":", "weights", "=", "range", "(", "2", ",", "10", ")", "digits", "=", "st_reg_number", "[", "0", ":", "len", "(", "st_reg_number", ")", "-", "1", "]", "control_digit", "=", "11", "check_digit", "=", "st_reg_n...
Checks the number valiaty for the Amazonas state
[ "Checks", "the", "number", "valiaty", "for", "the", "Amazonas", "state" ]
train
https://github.com/matheuscas/pyIE/blob/9e942dd692d0eab8a1e7717ad7ff3fe90d590ffb/ie/am.py#L5-L29
matheuscas/pyIE
ie/checking.py
start
def start(state_registration_number, state_abbreviation): """ This function is like a Facade to another modules that makes their own state validation. state_registration_number - string brazilian state registration number state_abbreviation - state abbreviation AC (Acre) AL (Alagoas) AM (Amazonas) AP (Amapá) BA (Bahia) CE (Ceará) DF (Distrito Federal) ES (Espírito Santo') GO (Goias) MA (Maranhão) MG (Minas Gerais) MS (Mato Grosso do Sul) MT (Mato Grosso) PA (Pará) PB (Paraíba) PE (Pernambuco) PI (Piauí) PR (Paraná) RJ (Rio de Janeiro) RN (Rio Grande do Norte) RO (Rondônia) RR (Roraima) RS (Rio Grande do Sul) SC (Santa Catarina) SE (Sergipe) SP (São Paulo) TO (Tocantins) """ state_abbreviation = state_abbreviation.upper() states_validations = { 'AC': "ac.start(" + "\"" + state_registration_number + "\"" + ")", 'AL': "al.start(" + "\"" + state_registration_number + "\"" + ")", 'AM': "am.start(" + "\"" + state_registration_number + "\"" + ")", 'AP': "ap.start(" + "\"" + state_registration_number + "\"" + ")", 'BA': "ba.start(" + "\"" + state_registration_number + "\"" + ")", 'CE': "ce.start(" + "\"" + state_registration_number + "\"" + ")", 'DF': "df.start(" + "\"" + state_registration_number + "\"" + ")", 'ES': "es.start(" + "\"" + state_registration_number + "\"" + ")", 'GO': "go.start(" + "\"" + state_registration_number + "\"" + ")", 'MA': "ma.start(" + "\"" + state_registration_number + "\"" + ")", 'MG': "mg.start(" + "\"" + state_registration_number + "\"" + ")", 'MS': "ms.start(" + "\"" + state_registration_number + "\"" + ")", 'MT': "mt.start(" + "\"" + state_registration_number + "\"" + ")", 'PA': "pa.start(" + "\"" + state_registration_number + "\"" + ")", 'PB': "pb.start(" + "\"" + state_registration_number + "\"" + ")", 'PE': "pe.start(" + "\"" + state_registration_number + "\"" + ")", 'PI': "pi.start(" + "\"" + state_registration_number + "\"" + ")", 'PR': "pr.start(" + "\"" + state_registration_number + "\"" + ")", 'RJ': "rj.start(" + "\"" + state_registration_number + "\"" + ")", 'RN': "rn.start(" + "\"" + state_registration_number + "\"" + ")", 'RO': "ro.start(" + "\"" + state_registration_number + "\"" + ")", 'RR': "rr.start(" + "\"" + state_registration_number + "\"" + ")", 'RS': "rs.start(" + "\"" + state_registration_number + "\"" + ")", 'SC': "sc.start(" + "\"" + state_registration_number + "\"" + ")", 'SE': "se.start(" + "\"" + state_registration_number + "\"" + ")", 'SP': "sp.start(" + "\"" + state_registration_number + "\"" + ")", 'TO': "to.start(" + "\"" + state_registration_number + "\"" + ")" } exec('validity = ' + states_validations[state_abbreviation]) return validity
python
def start(state_registration_number, state_abbreviation): """ This function is like a Facade to another modules that makes their own state validation. state_registration_number - string brazilian state registration number state_abbreviation - state abbreviation AC (Acre) AL (Alagoas) AM (Amazonas) AP (Amapá) BA (Bahia) CE (Ceará) DF (Distrito Federal) ES (Espírito Santo') GO (Goias) MA (Maranhão) MG (Minas Gerais) MS (Mato Grosso do Sul) MT (Mato Grosso) PA (Pará) PB (Paraíba) PE (Pernambuco) PI (Piauí) PR (Paraná) RJ (Rio de Janeiro) RN (Rio Grande do Norte) RO (Rondônia) RR (Roraima) RS (Rio Grande do Sul) SC (Santa Catarina) SE (Sergipe) SP (São Paulo) TO (Tocantins) """ state_abbreviation = state_abbreviation.upper() states_validations = { 'AC': "ac.start(" + "\"" + state_registration_number + "\"" + ")", 'AL': "al.start(" + "\"" + state_registration_number + "\"" + ")", 'AM': "am.start(" + "\"" + state_registration_number + "\"" + ")", 'AP': "ap.start(" + "\"" + state_registration_number + "\"" + ")", 'BA': "ba.start(" + "\"" + state_registration_number + "\"" + ")", 'CE': "ce.start(" + "\"" + state_registration_number + "\"" + ")", 'DF': "df.start(" + "\"" + state_registration_number + "\"" + ")", 'ES': "es.start(" + "\"" + state_registration_number + "\"" + ")", 'GO': "go.start(" + "\"" + state_registration_number + "\"" + ")", 'MA': "ma.start(" + "\"" + state_registration_number + "\"" + ")", 'MG': "mg.start(" + "\"" + state_registration_number + "\"" + ")", 'MS': "ms.start(" + "\"" + state_registration_number + "\"" + ")", 'MT': "mt.start(" + "\"" + state_registration_number + "\"" + ")", 'PA': "pa.start(" + "\"" + state_registration_number + "\"" + ")", 'PB': "pb.start(" + "\"" + state_registration_number + "\"" + ")", 'PE': "pe.start(" + "\"" + state_registration_number + "\"" + ")", 'PI': "pi.start(" + "\"" + state_registration_number + "\"" + ")", 'PR': "pr.start(" + "\"" + state_registration_number + "\"" + ")", 'RJ': "rj.start(" + "\"" + state_registration_number + "\"" + ")", 'RN': "rn.start(" + "\"" + state_registration_number + "\"" + ")", 'RO': "ro.start(" + "\"" + state_registration_number + "\"" + ")", 'RR': "rr.start(" + "\"" + state_registration_number + "\"" + ")", 'RS': "rs.start(" + "\"" + state_registration_number + "\"" + ")", 'SC': "sc.start(" + "\"" + state_registration_number + "\"" + ")", 'SE': "se.start(" + "\"" + state_registration_number + "\"" + ")", 'SP': "sp.start(" + "\"" + state_registration_number + "\"" + ")", 'TO': "to.start(" + "\"" + state_registration_number + "\"" + ")" } exec('validity = ' + states_validations[state_abbreviation]) return validity
[ "def", "start", "(", "state_registration_number", ",", "state_abbreviation", ")", ":", "state_abbreviation", "=", "state_abbreviation", ".", "upper", "(", ")", "states_validations", "=", "{", "'AC'", ":", "\"ac.start(\"", "+", "\"\\\"\"", "+", "state_registration_numb...
This function is like a Facade to another modules that makes their own state validation. state_registration_number - string brazilian state registration number state_abbreviation - state abbreviation AC (Acre) AL (Alagoas) AM (Amazonas) AP (Amapá) BA (Bahia) CE (Ceará) DF (Distrito Federal) ES (Espírito Santo') GO (Goias) MA (Maranhão) MG (Minas Gerais) MS (Mato Grosso do Sul) MT (Mato Grosso) PA (Pará) PB (Paraíba) PE (Pernambuco) PI (Piauí) PR (Paraná) RJ (Rio de Janeiro) RN (Rio Grande do Norte) RO (Rondônia) RR (Roraima) RS (Rio Grande do Sul) SC (Santa Catarina) SE (Sergipe) SP (São Paulo) TO (Tocantins)
[ "This", "function", "is", "like", "a", "Facade", "to", "another", "modules", "that", "makes", "their", "own", "state", "validation", "." ]
train
https://github.com/matheuscas/pyIE/blob/9e942dd692d0eab8a1e7717ad7ff3fe90d590ffb/ie/checking.py#L36-L106
matheuscas/pyIE
ie/al.py
start
def start(st_reg_number): """Checks the number valiaty for the Alagoas state""" if len(st_reg_number) > 9: return False if len(st_reg_number) < 9: return False if st_reg_number[0:2] != "24": return False if st_reg_number[2] not in ['0', '3', '5', '7', '8']: return False aux = 9 sum_total = 0 for i in range(len(st_reg_number)-1): sum_total = sum_total + int(st_reg_number[i]) * aux aux -= 1 product = sum_total * 10 aux_2 = int(product/11) digit = product - aux_2 * 11 if digit == 10: digit = 0 return digit == int(st_reg_number[len(st_reg_number)-1])
python
def start(st_reg_number): """Checks the number valiaty for the Alagoas state""" if len(st_reg_number) > 9: return False if len(st_reg_number) < 9: return False if st_reg_number[0:2] != "24": return False if st_reg_number[2] not in ['0', '3', '5', '7', '8']: return False aux = 9 sum_total = 0 for i in range(len(st_reg_number)-1): sum_total = sum_total + int(st_reg_number[i]) * aux aux -= 1 product = sum_total * 10 aux_2 = int(product/11) digit = product - aux_2 * 11 if digit == 10: digit = 0 return digit == int(st_reg_number[len(st_reg_number)-1])
[ "def", "start", "(", "st_reg_number", ")", ":", "if", "len", "(", "st_reg_number", ")", ">", "9", ":", "return", "False", "if", "len", "(", "st_reg_number", ")", "<", "9", ":", "return", "False", "if", "st_reg_number", "[", "0", ":", "2", "]", "!=", ...
Checks the number valiaty for the Alagoas state
[ "Checks", "the", "number", "valiaty", "for", "the", "Alagoas", "state" ]
train
https://github.com/matheuscas/pyIE/blob/9e942dd692d0eab8a1e7717ad7ff3fe90d590ffb/ie/al.py#L5-L35
matheuscas/pyIE
ie/ap.py
start
def start(st_reg_number): """Checks the number valiaty for the Alagoas state""" divisor = 11 if len(st_reg_number) > 9: return False if len(st_reg_number) < 9: return False if st_reg_number[0:2] != "03": return False aux = int(st_reg_number[0:len(st_reg_number) - 1]) if 3000000 < aux and aux < 3017001: control1 = 5 control2 = 0 if 3017000 < aux and aux < 3019023: control1 = 9 control2 = 1 if aux > 3019022: control1 = 0 control2 = 0 sum_total = 0 peso = 9 for i in range(len(st_reg_number)-1): sum_total = sum_total + int(st_reg_number[i]) * peso peso = peso - 1 sum_total += control1 rest_division = sum_total % divisor digit = divisor - rest_division if digit == 10: digit = 0 if digit == 11: digit = control2 return digit == int(st_reg_number[len(st_reg_number)-1])
python
def start(st_reg_number): """Checks the number valiaty for the Alagoas state""" divisor = 11 if len(st_reg_number) > 9: return False if len(st_reg_number) < 9: return False if st_reg_number[0:2] != "03": return False aux = int(st_reg_number[0:len(st_reg_number) - 1]) if 3000000 < aux and aux < 3017001: control1 = 5 control2 = 0 if 3017000 < aux and aux < 3019023: control1 = 9 control2 = 1 if aux > 3019022: control1 = 0 control2 = 0 sum_total = 0 peso = 9 for i in range(len(st_reg_number)-1): sum_total = sum_total + int(st_reg_number[i]) * peso peso = peso - 1 sum_total += control1 rest_division = sum_total % divisor digit = divisor - rest_division if digit == 10: digit = 0 if digit == 11: digit = control2 return digit == int(st_reg_number[len(st_reg_number)-1])
[ "def", "start", "(", "st_reg_number", ")", ":", "divisor", "=", "11", "if", "len", "(", "st_reg_number", ")", ">", "9", ":", "return", "False", "if", "len", "(", "st_reg_number", ")", "<", "9", ":", "return", "False", "if", "st_reg_number", "[", "0", ...
Checks the number valiaty for the Alagoas state
[ "Checks", "the", "number", "valiaty", "for", "the", "Alagoas", "state" ]
train
https://github.com/matheuscas/pyIE/blob/9e942dd692d0eab8a1e7717ad7ff3fe90d590ffb/ie/ap.py#L5-L47
paylogic/halogen
halogen/exceptions.py
ValidationError.to_dict
def to_dict(self): """Return a dictionary representation of the error. :return: A dict with the keys: - attr: Attribute which contains the error, or "<root>" if it refers to the schema root. - errors: A list of dictionary representations of the errors. """ def exception_to_dict(e): try: return e.to_dict() except AttributeError: return { "type": e.__class__.__name__, "error": str(e), } result = { "errors": [exception_to_dict(e) for e in self.errors] } if self.index is not None: result["index"] = self.index else: result["attr"] = self.attr if self.attr is not None else "<root>" return result
python
def to_dict(self): """Return a dictionary representation of the error. :return: A dict with the keys: - attr: Attribute which contains the error, or "<root>" if it refers to the schema root. - errors: A list of dictionary representations of the errors. """ def exception_to_dict(e): try: return e.to_dict() except AttributeError: return { "type": e.__class__.__name__, "error": str(e), } result = { "errors": [exception_to_dict(e) for e in self.errors] } if self.index is not None: result["index"] = self.index else: result["attr"] = self.attr if self.attr is not None else "<root>" return result
[ "def", "to_dict", "(", "self", ")", ":", "def", "exception_to_dict", "(", "e", ")", ":", "try", ":", "return", "e", ".", "to_dict", "(", ")", "except", "AttributeError", ":", "return", "{", "\"type\"", ":", "e", ".", "__class__", ".", "__name__", ",", ...
Return a dictionary representation of the error. :return: A dict with the keys: - attr: Attribute which contains the error, or "<root>" if it refers to the schema root. - errors: A list of dictionary representations of the errors.
[ "Return", "a", "dictionary", "representation", "of", "the", "error", "." ]
train
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/exceptions.py#L18-L41
dhondta/tinyscript
tinyscript/argreparse.py
ArgumentParser._filtered_actions
def _filtered_actions(self, *a_types): """ Get actions filtered on a list of action types. :param a_type: argparse.Action instance name (e.g. count, append) """ for a in filter(lambda _: self.is_action(_, *a_types), self._actions): yield a
python
def _filtered_actions(self, *a_types): """ Get actions filtered on a list of action types. :param a_type: argparse.Action instance name (e.g. count, append) """ for a in filter(lambda _: self.is_action(_, *a_types), self._actions): yield a
[ "def", "_filtered_actions", "(", "self", ",", "*", "a_types", ")", ":", "for", "a", "in", "filter", "(", "lambda", "_", ":", "self", ".", "is_action", "(", "_", ",", "*", "a_types", ")", ",", "self", ".", "_actions", ")", ":", "yield", "a" ]
Get actions filtered on a list of action types. :param a_type: argparse.Action instance name (e.g. count, append)
[ "Get", "actions", "filtered", "on", "a", "list", "of", "action", "types", ".", ":", "param", "a_type", ":", "argparse", ".", "Action", "instance", "name", "(", "e", ".", "g", ".", "count", "append", ")" ]
train
https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/argreparse.py#L289-L296
dhondta/tinyscript
tinyscript/argreparse.py
ArgumentParser._input_arg
def _input_arg(self, a): """ Ask the user for input of a single argument. :param a: argparse.Action instance :return: the user input, asked according to the action """ # if action of an argument that suppresses any other, just return if a.dest == SUPPRESS or a.default == SUPPRESS: return # prepare the prompt prompt = (a.help or a.dest).capitalize() r = {'required': a.required} # now handle each different action if self.is_action(a, 'store', 'append'): return user_input(prompt, a.choices, a.default, **r) elif self.is_action(a, 'store_const', 'append_const'): return user_input(prompt, ("(A)dd", "(D)iscard"), "d", **r) elif self.is_action(a, 'store_true'): return user_input(prompt, ("(Y)es", "(N)o"), "n", **r) elif self.is_action(a, 'store_false'): return user_input(prompt, ("(Y)es", "(N)o"), "n", **r) elif self.is_action(a, 'count'): return user_input(prompt, is_pos_int, 0, "positive integer", **r) elif self.is_action(a, 'parsers'): pmap = a._name_parser_map _ = list(pmap.keys()) return user_input(prompt, _, _[0], **r) if len(_) > 0 else None raise NotImplementedError("Unknown argparse action")
python
def _input_arg(self, a): """ Ask the user for input of a single argument. :param a: argparse.Action instance :return: the user input, asked according to the action """ # if action of an argument that suppresses any other, just return if a.dest == SUPPRESS or a.default == SUPPRESS: return # prepare the prompt prompt = (a.help or a.dest).capitalize() r = {'required': a.required} # now handle each different action if self.is_action(a, 'store', 'append'): return user_input(prompt, a.choices, a.default, **r) elif self.is_action(a, 'store_const', 'append_const'): return user_input(prompt, ("(A)dd", "(D)iscard"), "d", **r) elif self.is_action(a, 'store_true'): return user_input(prompt, ("(Y)es", "(N)o"), "n", **r) elif self.is_action(a, 'store_false'): return user_input(prompt, ("(Y)es", "(N)o"), "n", **r) elif self.is_action(a, 'count'): return user_input(prompt, is_pos_int, 0, "positive integer", **r) elif self.is_action(a, 'parsers'): pmap = a._name_parser_map _ = list(pmap.keys()) return user_input(prompt, _, _[0], **r) if len(_) > 0 else None raise NotImplementedError("Unknown argparse action")
[ "def", "_input_arg", "(", "self", ",", "a", ")", ":", "# if action of an argument that suppresses any other, just return", "if", "a", ".", "dest", "==", "SUPPRESS", "or", "a", ".", "default", "==", "SUPPRESS", ":", "return", "# prepare the prompt", "prompt", "=", ...
Ask the user for input of a single argument. :param a: argparse.Action instance :return: the user input, asked according to the action
[ "Ask", "the", "user", "for", "input", "of", "a", "single", "argument", ".", ":", "param", "a", ":", "argparse", ".", "Action", "instance", ":", "return", ":", "the", "user", "input", "asked", "according", "to", "the", "action" ]
train
https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/argreparse.py#L298-L326
dhondta/tinyscript
tinyscript/argreparse.py
ArgumentParser._set_arg
def _set_arg(self, a, s="main", c=False): """ Set a single argument. :param a: argparse.Action instance :param s: config section title :param c: use class' ConfigParser instance to get parameters """ # if action of an argument that suppresses any other, just return if a.dest is SUPPRESS or a.default is SUPPRESS: return # check if an option string is used for this action in sys.argv ; # if so, simply return as it will be parsed normally if any(o in sys.argv[1:] for o in a.option_strings): return # in case of non-null config, get the value from the config object default = a.default if a.default is None else str(a.default) if c: try: value = ArgumentParser._config.get(s, a.dest) except (NoOptionError, NoSectionError) as e: item = "setting" if isinstance(e, NoOptionError) else "section" # if the argument is required, just ask for the value value = self._input_arg(a) if a.required else default logger.debug("{} {} not present in config (set to {})" .format(a.dest, item, value)) # in case of null config, just ask for the value else: value = self._input_arg(a) # collect the option string before continuing try: ostr = a.option_strings[0] except IndexError: # occurs when positional argument ostr = None # now handle arguments regarding the action if self.is_action(a, 'store', 'append'): if value: if ostr: self._reparse_args['opt'].extend([ostr, value]) else: self._reparse_args['pos'].extend([value]) elif self.is_action(a, 'store_const', 'append_const'): if value.lower() == "add" or value != default: self._reparse_args['opt'].append(ostr) elif self.is_action(a, 'store_true'): if value.lower() in ["y", "true"]: self._reparse_args['opt'].append(ostr) elif self.is_action(a, 'store_false'): if value.lower() in ["n", "false"]: self._reparse_args['opt'].append(ostr) elif self.is_action(a, 'count'): v = int(value or 0) if v > 0: if ostr.startswith("--"): new_arg = [ostr for i in range(v)] else: new_arg = ["-{}".format(v * ostr.strip('-'))] self._reparse_args['opt'].extend(new_arg) elif self.is_action(a, 'parsers'): if not value: value = self._input_arg(a) pmap = a._name_parser_map if c: pmap[value].config_args(a.dest) pmap[value]._reparse_args['pos'].insert(0, value) else: pmap[value].input_args() self._reparse_args['sub'].append(pmap[value]) else: raise NotImplementedError("Unknown argparse action")
python
def _set_arg(self, a, s="main", c=False): """ Set a single argument. :param a: argparse.Action instance :param s: config section title :param c: use class' ConfigParser instance to get parameters """ # if action of an argument that suppresses any other, just return if a.dest is SUPPRESS or a.default is SUPPRESS: return # check if an option string is used for this action in sys.argv ; # if so, simply return as it will be parsed normally if any(o in sys.argv[1:] for o in a.option_strings): return # in case of non-null config, get the value from the config object default = a.default if a.default is None else str(a.default) if c: try: value = ArgumentParser._config.get(s, a.dest) except (NoOptionError, NoSectionError) as e: item = "setting" if isinstance(e, NoOptionError) else "section" # if the argument is required, just ask for the value value = self._input_arg(a) if a.required else default logger.debug("{} {} not present in config (set to {})" .format(a.dest, item, value)) # in case of null config, just ask for the value else: value = self._input_arg(a) # collect the option string before continuing try: ostr = a.option_strings[0] except IndexError: # occurs when positional argument ostr = None # now handle arguments regarding the action if self.is_action(a, 'store', 'append'): if value: if ostr: self._reparse_args['opt'].extend([ostr, value]) else: self._reparse_args['pos'].extend([value]) elif self.is_action(a, 'store_const', 'append_const'): if value.lower() == "add" or value != default: self._reparse_args['opt'].append(ostr) elif self.is_action(a, 'store_true'): if value.lower() in ["y", "true"]: self._reparse_args['opt'].append(ostr) elif self.is_action(a, 'store_false'): if value.lower() in ["n", "false"]: self._reparse_args['opt'].append(ostr) elif self.is_action(a, 'count'): v = int(value or 0) if v > 0: if ostr.startswith("--"): new_arg = [ostr for i in range(v)] else: new_arg = ["-{}".format(v * ostr.strip('-'))] self._reparse_args['opt'].extend(new_arg) elif self.is_action(a, 'parsers'): if not value: value = self._input_arg(a) pmap = a._name_parser_map if c: pmap[value].config_args(a.dest) pmap[value]._reparse_args['pos'].insert(0, value) else: pmap[value].input_args() self._reparse_args['sub'].append(pmap[value]) else: raise NotImplementedError("Unknown argparse action")
[ "def", "_set_arg", "(", "self", ",", "a", ",", "s", "=", "\"main\"", ",", "c", "=", "False", ")", ":", "# if action of an argument that suppresses any other, just return", "if", "a", ".", "dest", "is", "SUPPRESS", "or", "a", ".", "default", "is", "SUPPRESS", ...
Set a single argument. :param a: argparse.Action instance :param s: config section title :param c: use class' ConfigParser instance to get parameters
[ "Set", "a", "single", "argument", ".", ":", "param", "a", ":", "argparse", ".", "Action", "instance", ":", "param", "s", ":", "config", "section", "title", ":", "param", "c", ":", "use", "class", "ConfigParser", "instance", "to", "get", "parameters" ]
train
https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/argreparse.py#L336-L405
dhondta/tinyscript
tinyscript/argreparse.py
ArgumentParser._sorted_actions
def _sorted_actions(self): """ Generate the sorted list of actions based on the "last" attribute. """ for a in filter(lambda _: not _.last and \ not self.is_action(_, 'parsers'), self._actions): yield a for a in filter(lambda _: _.last and \ not self.is_action(_, 'parsers'), self._actions): yield a for a in filter(lambda _: self.is_action(_, 'parsers'), self._actions): yield a
python
def _sorted_actions(self): """ Generate the sorted list of actions based on the "last" attribute. """ for a in filter(lambda _: not _.last and \ not self.is_action(_, 'parsers'), self._actions): yield a for a in filter(lambda _: _.last and \ not self.is_action(_, 'parsers'), self._actions): yield a for a in filter(lambda _: self.is_action(_, 'parsers'), self._actions): yield a
[ "def", "_sorted_actions", "(", "self", ")", ":", "for", "a", "in", "filter", "(", "lambda", "_", ":", "not", "_", ".", "last", "and", "not", "self", ".", "is_action", "(", "_", ",", "'parsers'", ")", ",", "self", ".", "_actions", ")", ":", "yield",...
Generate the sorted list of actions based on the "last" attribute.
[ "Generate", "the", "sorted", "list", "of", "actions", "based", "on", "the", "last", "attribute", "." ]
train
https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/argreparse.py#L407-L419
dhondta/tinyscript
tinyscript/argreparse.py
ArgumentParser.config_args
def config_args(self, section="main"): """ Additional method for feeding input arguments from a config file. :param section: current config section name """ if self._config_parsed: return for a in self._filtered_actions("config"): for o in a.option_strings: try: i = sys.argv.index(o) sys.argv.pop(i) # remove the option string sys.argv.pop(i) # remove the value that follows except ValueError: pass for a in self._sorted_actions(): self._set_arg(a, section, True) self._config_parsed = True
python
def config_args(self, section="main"): """ Additional method for feeding input arguments from a config file. :param section: current config section name """ if self._config_parsed: return for a in self._filtered_actions("config"): for o in a.option_strings: try: i = sys.argv.index(o) sys.argv.pop(i) # remove the option string sys.argv.pop(i) # remove the value that follows except ValueError: pass for a in self._sorted_actions(): self._set_arg(a, section, True) self._config_parsed = True
[ "def", "config_args", "(", "self", ",", "section", "=", "\"main\"", ")", ":", "if", "self", ".", "_config_parsed", ":", "return", "for", "a", "in", "self", ".", "_filtered_actions", "(", "\"config\"", ")", ":", "for", "o", "in", "a", ".", "option_strings...
Additional method for feeding input arguments from a config file. :param section: current config section name
[ "Additional", "method", "for", "feeding", "input", "arguments", "from", "a", "config", "file", ".", ":", "param", "section", ":", "current", "config", "section", "name" ]
train
https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/argreparse.py#L422-L440
dhondta/tinyscript
tinyscript/argreparse.py
ArgumentParser.demo_args
def demo_args(self): """ Additional method for replacing input arguments by demo ones. """ argv = random.choice(self.examples).replace("--demo", "") self._reparse_args['pos'] = shlex.split(argv)
python
def demo_args(self): """ Additional method for replacing input arguments by demo ones. """ argv = random.choice(self.examples).replace("--demo", "") self._reparse_args['pos'] = shlex.split(argv)
[ "def", "demo_args", "(", "self", ")", ":", "argv", "=", "random", ".", "choice", "(", "self", ".", "examples", ")", ".", "replace", "(", "\"--demo\"", ",", "\"\"", ")", "self", ".", "_reparse_args", "[", "'pos'", "]", "=", "shlex", ".", "split", "(",...
Additional method for replacing input arguments by demo ones.
[ "Additional", "method", "for", "replacing", "input", "arguments", "by", "demo", "ones", "." ]
train
https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/argreparse.py#L442-L447
dhondta/tinyscript
tinyscript/argreparse.py
ArgumentParser.parse_args
def parse_args(self, args=None, namespace=None): """ Reparses new arguments when _DemoAction (triggering parser.demo_args()) or _WizardAction (triggering input_args()) was called. """ if not namespace: # use the new Namespace class for handling _config namespace = Namespace(self) namespace = super(ArgumentParser, self).parse_args(args, namespace) if len(self._reparse_args['pos']) > 0 or \ len(self._reparse_args['opt']) > 0 or \ len(self._reparse_args['sub']) > 0: args = self._reset_args() namespace = super(ArgumentParser, self).parse_args(args, namespace) # process "-hh..." here, after having parsed the arguments help_level = getattr(namespace, "help", 0) if help_level > 0: self.print_help() self.print_extended_help(help_level) self.exit() return namespace
python
def parse_args(self, args=None, namespace=None): """ Reparses new arguments when _DemoAction (triggering parser.demo_args()) or _WizardAction (triggering input_args()) was called. """ if not namespace: # use the new Namespace class for handling _config namespace = Namespace(self) namespace = super(ArgumentParser, self).parse_args(args, namespace) if len(self._reparse_args['pos']) > 0 or \ len(self._reparse_args['opt']) > 0 or \ len(self._reparse_args['sub']) > 0: args = self._reset_args() namespace = super(ArgumentParser, self).parse_args(args, namespace) # process "-hh..." here, after having parsed the arguments help_level = getattr(namespace, "help", 0) if help_level > 0: self.print_help() self.print_extended_help(help_level) self.exit() return namespace
[ "def", "parse_args", "(", "self", ",", "args", "=", "None", ",", "namespace", "=", "None", ")", ":", "if", "not", "namespace", ":", "# use the new Namespace class for handling _config", "namespace", "=", "Namespace", "(", "self", ")", "namespace", "=", "super", ...
Reparses new arguments when _DemoAction (triggering parser.demo_args()) or _WizardAction (triggering input_args()) was called.
[ "Reparses", "new", "arguments", "when", "_DemoAction", "(", "triggering", "parser", ".", "demo_args", "()", ")", "or", "_WizardAction", "(", "triggering", "input_args", "()", ")", "was", "called", "." ]
train
https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/argreparse.py#L456-L475
dhondta/tinyscript
tinyscript/argreparse.py
ArgumentParser.error
def error(self, message): """ Prints a usage message incorporating the message to stderr and exits in the case when no new arguments to be reparsed, that is when no special action like _DemoAction (triggering parser.demo_args()) or _WizardAction (triggering input_args()) was called. Otherwise, it simply does not stop execution so that new arguments can be reparsed. """ if all(len(x) == 0 for x in self._reparse_args.values()): # normal behavior with argparse self.print_usage(sys.stderr) self.exit(2, gt('%s: error: %s\n') % (self.prog, message))
python
def error(self, message): """ Prints a usage message incorporating the message to stderr and exits in the case when no new arguments to be reparsed, that is when no special action like _DemoAction (triggering parser.demo_args()) or _WizardAction (triggering input_args()) was called. Otherwise, it simply does not stop execution so that new arguments can be reparsed. """ if all(len(x) == 0 for x in self._reparse_args.values()): # normal behavior with argparse self.print_usage(sys.stderr) self.exit(2, gt('%s: error: %s\n') % (self.prog, message))
[ "def", "error", "(", "self", ",", "message", ")", ":", "if", "all", "(", "len", "(", "x", ")", "==", "0", "for", "x", "in", "self", ".", "_reparse_args", ".", "values", "(", ")", ")", ":", "# normal behavior with argparse", "self", ".", "print_usage", ...
Prints a usage message incorporating the message to stderr and exits in the case when no new arguments to be reparsed, that is when no special action like _DemoAction (triggering parser.demo_args()) or _WizardAction (triggering input_args()) was called. Otherwise, it simply does not stop execution so that new arguments can be reparsed.
[ "Prints", "a", "usage", "message", "incorporating", "the", "message", "to", "stderr", "and", "exits", "in", "the", "case", "when", "no", "new", "arguments", "to", "be", "reparsed", "that", "is", "when", "no", "special", "action", "like", "_DemoAction", "(", ...
train
https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/argreparse.py#L477-L488
dhondta/tinyscript
tinyscript/argreparse.py
ArgumentParser.add_to_config
def add_to_config(cls, section, name, value): """ Add a parameter to the shared ConfigParser object. :param section: parameter's section :param name: parameter's name :param value: parameter's value """ if value: if not cls._config.has_section(section): cls._config.add_section(section) cls._config.set(section, name, str(value))
python
def add_to_config(cls, section, name, value): """ Add a parameter to the shared ConfigParser object. :param section: parameter's section :param name: parameter's name :param value: parameter's value """ if value: if not cls._config.has_section(section): cls._config.add_section(section) cls._config.set(section, name, str(value))
[ "def", "add_to_config", "(", "cls", ",", "section", ",", "name", ",", "value", ")", ":", "if", "value", ":", "if", "not", "cls", ".", "_config", ".", "has_section", "(", "section", ")", ":", "cls", ".", "_config", ".", "add_section", "(", "section", ...
Add a parameter to the shared ConfigParser object. :param section: parameter's section :param name: parameter's name :param value: parameter's value
[ "Add", "a", "parameter", "to", "the", "shared", "ConfigParser", "object", ".", ":", "param", "section", ":", "parameter", "s", "section", ":", "param", "name", ":", "parameter", "s", "name", ":", "param", "value", ":", "parameter", "s", "value" ]
train
https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/argreparse.py#L498-L509
dhondta/tinyscript
tinyscript/report/__init__.py
output
def output(f): """ This decorator allows to choose to return an output as text or to save it to a file. """ def wrapper(self, *args, **kwargs): try: text = kwargs.get('text') or args[0] except IndexError: text = True _ = f(self, *args, **kwargs) if text: return _ elif _ is not None and isinstance(_, string_types): filename = "{}.{}".format(self.filename, f.__name__) while exists(filename): name, ext = splitext(filename) try: name, i = name.split('-') i = int(i) + 1 except ValueError: i = 2 filename = "{}-{}".format(name, i) + ext with open(filename, 'w') as out: out.write(_) return wrapper
python
def output(f): """ This decorator allows to choose to return an output as text or to save it to a file. """ def wrapper(self, *args, **kwargs): try: text = kwargs.get('text') or args[0] except IndexError: text = True _ = f(self, *args, **kwargs) if text: return _ elif _ is not None and isinstance(_, string_types): filename = "{}.{}".format(self.filename, f.__name__) while exists(filename): name, ext = splitext(filename) try: name, i = name.split('-') i = int(i) + 1 except ValueError: i = 2 filename = "{}-{}".format(name, i) + ext with open(filename, 'w') as out: out.write(_) return wrapper
[ "def", "output", "(", "f", ")", ":", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "text", "=", "kwargs", ".", "get", "(", "'text'", ")", "or", "args", "[", "0", "]", "except", "IndexError", ":"...
This decorator allows to choose to return an output as text or to save it to a file.
[ "This", "decorator", "allows", "to", "choose", "to", "return", "an", "output", "as", "text", "or", "to", "save", "it", "to", "a", "file", "." ]
train
https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/report/__init__.py#L32-L55
dhondta/tinyscript
tinyscript/report/__init__.py
Report.html
def html(self, text=TEXT): """ Generate an HTML file from the report data. """ self.logger.debug("Generating the HTML report{}..." .format(["", " (text only)"][text])) html = [] for piece in self._pieces: if isinstance(piece, string_types): html.append(markdown2.markdown(piece, extras=["tables"])) elif isinstance(piece, Element): html.append(piece.html()) return "\n\n".join(html)
python
def html(self, text=TEXT): """ Generate an HTML file from the report data. """ self.logger.debug("Generating the HTML report{}..." .format(["", " (text only)"][text])) html = [] for piece in self._pieces: if isinstance(piece, string_types): html.append(markdown2.markdown(piece, extras=["tables"])) elif isinstance(piece, Element): html.append(piece.html()) return "\n\n".join(html)
[ "def", "html", "(", "self", ",", "text", "=", "TEXT", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Generating the HTML report{}...\"", ".", "format", "(", "[", "\"\"", ",", "\" (text only)\"", "]", "[", "text", "]", ")", ")", "html", "=", "["...
Generate an HTML file from the report data.
[ "Generate", "an", "HTML", "file", "from", "the", "report", "data", "." ]
train
https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/report/__init__.py#L133-L143
dhondta/tinyscript
tinyscript/report/__init__.py
Report.pdf
def pdf(self, text=TEXT): """ Generate a PDF file from the report data. """ self.logger.debug("Generating the PDF report...") html = HTML(string=self.html()) css_file = self.css or join(dirname(abspath(__file__)), "{}.css".format(self.theme)) css = [css_file, CSS(string=PAGE_CSS % self.__dict__)] html.write_pdf("{}.pdf".format(self.filename), stylesheets=css)
python
def pdf(self, text=TEXT): """ Generate a PDF file from the report data. """ self.logger.debug("Generating the PDF report...") html = HTML(string=self.html()) css_file = self.css or join(dirname(abspath(__file__)), "{}.css".format(self.theme)) css = [css_file, CSS(string=PAGE_CSS % self.__dict__)] html.write_pdf("{}.pdf".format(self.filename), stylesheets=css)
[ "def", "pdf", "(", "self", ",", "text", "=", "TEXT", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Generating the PDF report...\"", ")", "html", "=", "HTML", "(", "string", "=", "self", ".", "html", "(", ")", ")", "css_file", "=", "self", "....
Generate a PDF file from the report data.
[ "Generate", "a", "PDF", "file", "from", "the", "report", "data", "." ]
train
https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/report/__init__.py#L163-L170
dhondta/tinyscript
tinyscript/report/__init__.py
Table.csv
def csv(self, text=TEXT, sep=',', index=True, float_fmt="%.2g"): """ Generate a CSV table from the table data. """ return self._data.to_csv(sep=sep, index=index, float_format=float_fmt)
python
def csv(self, text=TEXT, sep=',', index=True, float_fmt="%.2g"): """ Generate a CSV table from the table data. """ return self._data.to_csv(sep=sep, index=index, float_format=float_fmt)
[ "def", "csv", "(", "self", ",", "text", "=", "TEXT", ",", "sep", "=", "','", ",", "index", "=", "True", ",", "float_fmt", "=", "\"%.2g\"", ")", ":", "return", "self", ".", "_data", ".", "to_csv", "(", "sep", "=", "sep", ",", "index", "=", "index"...
Generate a CSV table from the table data.
[ "Generate", "a", "CSV", "table", "from", "the", "table", "data", "." ]
train
https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/report/__init__.py#L191-L193
dhondta/tinyscript
tinyscript/report/__init__.py
Table.md
def md(self, text=TEXT, float_format="%.2g"): """ Generate Markdown from the table data. """ cols = self._data.columns hl = pd.DataFrame([["---"] * len(cols)], index=["---"], columns=cols) df = pd.concat([hl, self._data]) return df.to_csv(sep='|', index=True, float_format=float_format)
python
def md(self, text=TEXT, float_format="%.2g"): """ Generate Markdown from the table data. """ cols = self._data.columns hl = pd.DataFrame([["---"] * len(cols)], index=["---"], columns=cols) df = pd.concat([hl, self._data]) return df.to_csv(sep='|', index=True, float_format=float_format)
[ "def", "md", "(", "self", ",", "text", "=", "TEXT", ",", "float_format", "=", "\"%.2g\"", ")", ":", "cols", "=", "self", ".", "_data", ".", "columns", "hl", "=", "pd", ".", "DataFrame", "(", "[", "[", "\"---\"", "]", "*", "len", "(", "cols", ")",...
Generate Markdown from the table data.
[ "Generate", "Markdown", "from", "the", "table", "data", "." ]
train
https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/report/__init__.py#L206-L211
dhondta/tinyscript
tinyscript/report/__init__.py
Table.xml
def xml(self, text=TEXT): """ Generate an XML output from the report data. """ def convert(line): xml = " <item>\n" for f in line.index: xml += " <field name=\"%s\">%s</field>\n" % (f, line[f]) xml += " </item>\n" return xml return "<items>\n" + '\n'.join(self._data.apply(convert, axis=1)) + \ "</items>"
python
def xml(self, text=TEXT): """ Generate an XML output from the report data. """ def convert(line): xml = " <item>\n" for f in line.index: xml += " <field name=\"%s\">%s</field>\n" % (f, line[f]) xml += " </item>\n" return xml return "<items>\n" + '\n'.join(self._data.apply(convert, axis=1)) + \ "</items>"
[ "def", "xml", "(", "self", ",", "text", "=", "TEXT", ")", ":", "def", "convert", "(", "line", ")", ":", "xml", "=", "\" <item>\\n\"", "for", "f", "in", "line", ".", "index", ":", "xml", "+=", "\" <field name=\\\"%s\\\">%s</field>\\n\"", "%", "(", "f"...
Generate an XML output from the report data.
[ "Generate", "an", "XML", "output", "from", "the", "report", "data", "." ]
train
https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/report/__init__.py#L214-L223
toumorokoshi/transmute-core
transmute_core/function/signature.py
FunctionSignature.from_argspec
def from_argspec(argspec): """ retrieve a FunctionSignature object from the argspec and the annotations passed. """ attributes = getattr(argspec, "args", []) + getattr(argspec, "keywords", []) defaults = argspec.defaults or [] arguments, keywords = [], {} attribute_list = ( attributes[: -len(defaults)] if len(defaults) != 0 else attributes[:] ) for name in attribute_list: if name == "self": continue typ = argspec.annotations.get(name) arguments.append(Argument(name, NoDefault, typ)) if len(defaults) != 0: for name, default in zip(attributes[-len(defaults) :], defaults): typ = argspec.annotations.get(name) keywords[name] = Argument(name, default, typ) return FunctionSignature(arguments, keywords)
python
def from_argspec(argspec): """ retrieve a FunctionSignature object from the argspec and the annotations passed. """ attributes = getattr(argspec, "args", []) + getattr(argspec, "keywords", []) defaults = argspec.defaults or [] arguments, keywords = [], {} attribute_list = ( attributes[: -len(defaults)] if len(defaults) != 0 else attributes[:] ) for name in attribute_list: if name == "self": continue typ = argspec.annotations.get(name) arguments.append(Argument(name, NoDefault, typ)) if len(defaults) != 0: for name, default in zip(attributes[-len(defaults) :], defaults): typ = argspec.annotations.get(name) keywords[name] = Argument(name, default, typ) return FunctionSignature(arguments, keywords)
[ "def", "from_argspec", "(", "argspec", ")", ":", "attributes", "=", "getattr", "(", "argspec", ",", "\"args\"", ",", "[", "]", ")", "+", "getattr", "(", "argspec", ",", "\"keywords\"", ",", "[", "]", ")", "defaults", "=", "argspec", ".", "defaults", "o...
retrieve a FunctionSignature object from the argspec and the annotations passed.
[ "retrieve", "a", "FunctionSignature", "object", "from", "the", "argspec", "and", "the", "annotations", "passed", "." ]
train
https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/function/signature.py#L38-L62
toumorokoshi/transmute-core
transmute_core/function/signature.py
FunctionSignature.split_args
def split_args(self, arg_dict): """ given a dictionary of arguments, split them into args and kwargs note: this destroys the arg_dict passed. if you need it, create a copy first. """ pos_args = [] for arg in self.args: pos_args.append(arg_dict[arg.name]) del arg_dict[arg.name] return pos_args, arg_dict
python
def split_args(self, arg_dict): """ given a dictionary of arguments, split them into args and kwargs note: this destroys the arg_dict passed. if you need it, create a copy first. """ pos_args = [] for arg in self.args: pos_args.append(arg_dict[arg.name]) del arg_dict[arg.name] return pos_args, arg_dict
[ "def", "split_args", "(", "self", ",", "arg_dict", ")", ":", "pos_args", "=", "[", "]", "for", "arg", "in", "self", ".", "args", ":", "pos_args", ".", "append", "(", "arg_dict", "[", "arg", ".", "name", "]", ")", "del", "arg_dict", "[", "arg", ".",...
given a dictionary of arguments, split them into args and kwargs note: this destroys the arg_dict passed. if you need it, create a copy first.
[ "given", "a", "dictionary", "of", "arguments", "split", "them", "into", "args", "and", "kwargs" ]
train
https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/function/signature.py#L70-L82
dhondta/tinyscript
tinyscript/helpers/utils.py
std_input
def std_input(prompt="", style=None): """ Very simple Python2/3-compatible input method. :param prompt: prompt message :param style: dictionary of ansi_wrap keyword-arguments """ p = ansi_wrap(prompt, **(style or {})) try: return raw_input(p).strip() except NameError: return input(p).strip()
python
def std_input(prompt="", style=None): """ Very simple Python2/3-compatible input method. :param prompt: prompt message :param style: dictionary of ansi_wrap keyword-arguments """ p = ansi_wrap(prompt, **(style or {})) try: return raw_input(p).strip() except NameError: return input(p).strip()
[ "def", "std_input", "(", "prompt", "=", "\"\"", ",", "style", "=", "None", ")", ":", "p", "=", "ansi_wrap", "(", "prompt", ",", "*", "*", "(", "style", "or", "{", "}", ")", ")", "try", ":", "return", "raw_input", "(", "p", ")", ".", "strip", "(...
Very simple Python2/3-compatible input method. :param prompt: prompt message :param style: dictionary of ansi_wrap keyword-arguments
[ "Very", "simple", "Python2", "/", "3", "-", "compatible", "input", "method", ".", ":", "param", "prompt", ":", "prompt", "message", ":", "param", "style", ":", "dictionary", "of", "ansi_wrap", "keyword", "-", "arguments" ]
train
https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/helpers/utils.py#L43-L54
dhondta/tinyscript
tinyscript/helpers/utils.py
user_input
def user_input(prompt="", choices=None, default=None, choices_str="", required=False): """ Python2/3-compatible input method handling choices and default value. :param prompt: prompt message :param choices: list of possible choices or lambda function :param default: default value :param required: make non-null user input mandatory :return: handled user input """ if type(choices) in [list, tuple, set]: choices = list(map(str, choices)) choices_str = " {%s}" % (choices_str or \ '|'.join(list(map(str, choices)))) # consider choices of the form ["(Y)es", "(N)o"] ; # in this case, we want the choices to be ['y', 'n'] for the sake of # simplicity for the user m = list(map(lambda x: CHOICE_REGEX.match(x), choices)) choices = [x.group(1).lower() if x else c for x, c in zip(m, choices)] # this way, if using ["Yes", "No"], choices will remain so _check = lambda v: v in choices elif is_lambda(choices): _check = choices else: _check = lambda v: True prompt += "{}{}\n".format(choices_str, [" [{}]".format(default), ""]\ [default is None and required]) user_input, first = None, True while not user_input: user_input = std_input(["", prompt][first] + " >> ") first = False if type(choices) in [list, tuple, set]: choices = list(map(lambda x: x.lower(), choices)) user_input = user_input.lower() if user_input == "" and default is not None and _check(default): return str(default) if user_input != "" and _check(user_input): return user_input if not required: return
python
def user_input(prompt="", choices=None, default=None, choices_str="", required=False): """ Python2/3-compatible input method handling choices and default value. :param prompt: prompt message :param choices: list of possible choices or lambda function :param default: default value :param required: make non-null user input mandatory :return: handled user input """ if type(choices) in [list, tuple, set]: choices = list(map(str, choices)) choices_str = " {%s}" % (choices_str or \ '|'.join(list(map(str, choices)))) # consider choices of the form ["(Y)es", "(N)o"] ; # in this case, we want the choices to be ['y', 'n'] for the sake of # simplicity for the user m = list(map(lambda x: CHOICE_REGEX.match(x), choices)) choices = [x.group(1).lower() if x else c for x, c in zip(m, choices)] # this way, if using ["Yes", "No"], choices will remain so _check = lambda v: v in choices elif is_lambda(choices): _check = choices else: _check = lambda v: True prompt += "{}{}\n".format(choices_str, [" [{}]".format(default), ""]\ [default is None and required]) user_input, first = None, True while not user_input: user_input = std_input(["", prompt][first] + " >> ") first = False if type(choices) in [list, tuple, set]: choices = list(map(lambda x: x.lower(), choices)) user_input = user_input.lower() if user_input == "" and default is not None and _check(default): return str(default) if user_input != "" and _check(user_input): return user_input if not required: return
[ "def", "user_input", "(", "prompt", "=", "\"\"", ",", "choices", "=", "None", ",", "default", "=", "None", ",", "choices_str", "=", "\"\"", ",", "required", "=", "False", ")", ":", "if", "type", "(", "choices", ")", "in", "[", "list", ",", "tuple", ...
Python2/3-compatible input method handling choices and default value. :param prompt: prompt message :param choices: list of possible choices or lambda function :param default: default value :param required: make non-null user input mandatory :return: handled user input
[ "Python2", "/", "3", "-", "compatible", "input", "method", "handling", "choices", "and", "default", "value", ".", ":", "param", "prompt", ":", "prompt", "message", ":", "param", "choices", ":", "list", "of", "possible", "choices", "or", "lambda", "function",...
train
https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/helpers/utils.py#L57-L97
agoragames/chai
chai/exception.py
pretty_format_args
def pretty_format_args(*args, **kwargs): """ Take the args, and kwargs that are passed them and format in a prototype style. """ args = list([repr(a) for a in args]) for key, value in kwargs.items(): args.append("%s=%s" % (key, repr(value))) return "(%s)" % ", ".join([a for a in args])
python
def pretty_format_args(*args, **kwargs): """ Take the args, and kwargs that are passed them and format in a prototype style. """ args = list([repr(a) for a in args]) for key, value in kwargs.items(): args.append("%s=%s" % (key, repr(value))) return "(%s)" % ", ".join([a for a in args])
[ "def", "pretty_format_args", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "args", "=", "list", "(", "[", "repr", "(", "a", ")", "for", "a", "in", "args", "]", ")", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":",...
Take the args, and kwargs that are passed them and format in a prototype style.
[ "Take", "the", "args", "and", "kwargs", "that", "are", "passed", "them", "and", "format", "in", "a", "prototype", "style", "." ]
train
https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/exception.py#L16-L24
inveniosoftware/invenio-previewer
invenio_previewer/extensions/xml_prismjs.py
render
def render(file): """Pretty print the XML file for rendering.""" with file.open() as fp: encoding = detect_encoding(fp, default='utf-8') file_content = fp.read().decode(encoding) parsed_xml = xml.dom.minidom.parseString(file_content) return parsed_xml.toprettyxml(indent=' ', newl='')
python
def render(file): """Pretty print the XML file for rendering.""" with file.open() as fp: encoding = detect_encoding(fp, default='utf-8') file_content = fp.read().decode(encoding) parsed_xml = xml.dom.minidom.parseString(file_content) return parsed_xml.toprettyxml(indent=' ', newl='')
[ "def", "render", "(", "file", ")", ":", "with", "file", ".", "open", "(", ")", "as", "fp", ":", "encoding", "=", "detect_encoding", "(", "fp", ",", "default", "=", "'utf-8'", ")", "file_content", "=", "fp", ".", "read", "(", ")", ".", "decode", "("...
Pretty print the XML file for rendering.
[ "Pretty", "print", "the", "XML", "file", "for", "rendering", "." ]
train
https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/extensions/xml_prismjs.py#L22-L28
inveniosoftware/invenio-previewer
invenio_previewer/extensions/xml_prismjs.py
validate_xml
def validate_xml(file): """Validate an XML file.""" max_file_size = current_app.config.get( 'PREVIEWER_MAX_FILE_SIZE_BYTES', 1 * 1024 * 1024) if file.size > max_file_size: return False with file.open() as fp: try: content = fp.read().decode('utf-8') xml.dom.minidom.parseString(content) return True except: return False
python
def validate_xml(file): """Validate an XML file.""" max_file_size = current_app.config.get( 'PREVIEWER_MAX_FILE_SIZE_BYTES', 1 * 1024 * 1024) if file.size > max_file_size: return False with file.open() as fp: try: content = fp.read().decode('utf-8') xml.dom.minidom.parseString(content) return True except: return False
[ "def", "validate_xml", "(", "file", ")", ":", "max_file_size", "=", "current_app", ".", "config", ".", "get", "(", "'PREVIEWER_MAX_FILE_SIZE_BYTES'", ",", "1", "*", "1024", "*", "1024", ")", "if", "file", ".", "size", ">", "max_file_size", ":", "return", "...
Validate an XML file.
[ "Validate", "an", "XML", "file", "." ]
train
https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/extensions/xml_prismjs.py#L31-L44
inveniosoftware/invenio-previewer
invenio_previewer/extensions/xml_prismjs.py
preview
def preview(file): """Render appropiate template with embed flag.""" return render_template( 'invenio_previewer/xml_prismjs.html', file=file, content=render(file), js_bundles=['previewer_prism_js'], css_bundles=['previewer_prism_css'], )
python
def preview(file): """Render appropiate template with embed flag.""" return render_template( 'invenio_previewer/xml_prismjs.html', file=file, content=render(file), js_bundles=['previewer_prism_js'], css_bundles=['previewer_prism_css'], )
[ "def", "preview", "(", "file", ")", ":", "return", "render_template", "(", "'invenio_previewer/xml_prismjs.html'", ",", "file", "=", "file", ",", "content", "=", "render", "(", "file", ")", ",", "js_bundles", "=", "[", "'previewer_prism_js'", "]", ",", "css_bu...
Render appropiate template with embed flag.
[ "Render", "appropiate", "template", "with", "embed", "flag", "." ]
train
https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/extensions/xml_prismjs.py#L54-L62
paylogic/halogen
halogen/schema.py
_get_context
def _get_context(argspec, kwargs): """Prepare a context for the serialization. :param argspec: The argspec of the serialization function. :param kwargs: Dict with context :return: Keywords arguments that function can accept. """ if argspec.keywords is not None: return kwargs return dict((arg, kwargs[arg]) for arg in argspec.args if arg in kwargs)
python
def _get_context(argspec, kwargs): """Prepare a context for the serialization. :param argspec: The argspec of the serialization function. :param kwargs: Dict with context :return: Keywords arguments that function can accept. """ if argspec.keywords is not None: return kwargs return dict((arg, kwargs[arg]) for arg in argspec.args if arg in kwargs)
[ "def", "_get_context", "(", "argspec", ",", "kwargs", ")", ":", "if", "argspec", ".", "keywords", "is", "not", "None", ":", "return", "kwargs", "return", "dict", "(", "(", "arg", ",", "kwargs", "[", "arg", "]", ")", "for", "arg", "in", "argspec", "."...
Prepare a context for the serialization. :param argspec: The argspec of the serialization function. :param kwargs: Dict with context :return: Keywords arguments that function can accept.
[ "Prepare", "a", "context", "for", "the", "serialization", "." ]
train
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/schema.py#L29-L38
paylogic/halogen
halogen/schema.py
Accessor.get
def get(self, obj, **kwargs): """Get an attribute from a value. :param obj: Object to get the attribute value from. :return: Value of object's attribute. """ assert self.getter is not None, "Getter accessor is not specified." if callable(self.getter): return self.getter(obj, **_get_context(self._getter_argspec, kwargs)) assert isinstance(self.getter, string_types), "Accessor must be a function or a dot-separated string." for attr in self.getter.split("."): if isinstance(obj, dict): obj = obj[attr] else: obj = getattr(obj, attr) if callable(obj): return obj() return obj
python
def get(self, obj, **kwargs): """Get an attribute from a value. :param obj: Object to get the attribute value from. :return: Value of object's attribute. """ assert self.getter is not None, "Getter accessor is not specified." if callable(self.getter): return self.getter(obj, **_get_context(self._getter_argspec, kwargs)) assert isinstance(self.getter, string_types), "Accessor must be a function or a dot-separated string." for attr in self.getter.split("."): if isinstance(obj, dict): obj = obj[attr] else: obj = getattr(obj, attr) if callable(obj): return obj() return obj
[ "def", "get", "(", "self", ",", "obj", ",", "*", "*", "kwargs", ")", ":", "assert", "self", ".", "getter", "is", "not", "None", ",", "\"Getter accessor is not specified.\"", "if", "callable", "(", "self", ".", "getter", ")", ":", "return", "self", ".", ...
Get an attribute from a value. :param obj: Object to get the attribute value from. :return: Value of object's attribute.
[ "Get", "an", "attribute", "from", "a", "value", "." ]
train
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/schema.py#L54-L75
paylogic/halogen
halogen/schema.py
Accessor.set
def set(self, obj, value): """Set value for obj's attribute. :param obj: Result object or dict to assign the attribute to. :param value: Value to be assigned. """ assert self.setter is not None, "Setter accessor is not specified." if callable(self.setter): return self.setter(obj, value) assert isinstance(self.setter, string_types), "Accessor must be a function or a dot-separated string." def _set(obj, attr, value): if isinstance(obj, dict): obj[attr] = value else: setattr(obj, attr, value) return value path = self.setter.split(".") for attr in path[:-1]: obj = _set(obj, attr, {}) _set(obj, path[-1], value)
python
def set(self, obj, value): """Set value for obj's attribute. :param obj: Result object or dict to assign the attribute to. :param value: Value to be assigned. """ assert self.setter is not None, "Setter accessor is not specified." if callable(self.setter): return self.setter(obj, value) assert isinstance(self.setter, string_types), "Accessor must be a function or a dot-separated string." def _set(obj, attr, value): if isinstance(obj, dict): obj[attr] = value else: setattr(obj, attr, value) return value path = self.setter.split(".") for attr in path[:-1]: obj = _set(obj, attr, {}) _set(obj, path[-1], value)
[ "def", "set", "(", "self", ",", "obj", ",", "value", ")", ":", "assert", "self", ".", "setter", "is", "not", "None", ",", "\"Setter accessor is not specified.\"", "if", "callable", "(", "self", ".", "setter", ")", ":", "return", "self", ".", "setter", "(...
Set value for obj's attribute. :param obj: Result object or dict to assign the attribute to. :param value: Value to be assigned.
[ "Set", "value", "for", "obj", "s", "attribute", "." ]
train
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/schema.py#L77-L100
paylogic/halogen
halogen/schema.py
Attr.accessor
def accessor(self): """Get an attribute's accessor with the getter and the setter. :return: `Accessor` instance. """ if isinstance(self.attr, Accessor): return self.attr if callable(self.attr): return Accessor(getter=self.attr) attr = self.attr or self.name return Accessor(getter=attr, setter=attr)
python
def accessor(self): """Get an attribute's accessor with the getter and the setter. :return: `Accessor` instance. """ if isinstance(self.attr, Accessor): return self.attr if callable(self.attr): return Accessor(getter=self.attr) attr = self.attr or self.name return Accessor(getter=attr, setter=attr)
[ "def", "accessor", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "attr", ",", "Accessor", ")", ":", "return", "self", ".", "attr", "if", "callable", "(", "self", ".", "attr", ")", ":", "return", "Accessor", "(", "getter", "=", "self", ...
Get an attribute's accessor with the getter and the setter. :return: `Accessor` instance.
[ "Get", "an", "attribute", "s", "accessor", "with", "the", "getter", "and", "the", "setter", "." ]
train
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/schema.py#L144-L156
paylogic/halogen
halogen/schema.py
Attr.serialize
def serialize(self, value, **kwargs): """Serialize the attribute of the input data. Gets the attribute value with accessor and converts it using the type serialization. Schema will place this serialized value into corresponding compartment of the HAL structure with the name of the attribute as a key. :param value: Value to get the attribute value from. :return: Serialized attribute value. """ if types.Type.is_type(self.attr_type): try: value = self.accessor.get(value, **kwargs) except (AttributeError, KeyError): if not hasattr(self, "default") and self.required: raise value = self.default() if callable(self.default) else self.default return self.attr_type.serialize(value, **_get_context(self._attr_type_serialize_argspec, kwargs)) return self.attr_type
python
def serialize(self, value, **kwargs): """Serialize the attribute of the input data. Gets the attribute value with accessor and converts it using the type serialization. Schema will place this serialized value into corresponding compartment of the HAL structure with the name of the attribute as a key. :param value: Value to get the attribute value from. :return: Serialized attribute value. """ if types.Type.is_type(self.attr_type): try: value = self.accessor.get(value, **kwargs) except (AttributeError, KeyError): if not hasattr(self, "default") and self.required: raise value = self.default() if callable(self.default) else self.default return self.attr_type.serialize(value, **_get_context(self._attr_type_serialize_argspec, kwargs)) return self.attr_type
[ "def", "serialize", "(", "self", ",", "value", ",", "*", "*", "kwargs", ")", ":", "if", "types", ".", "Type", ".", "is_type", "(", "self", ".", "attr_type", ")", ":", "try", ":", "value", "=", "self", ".", "accessor", ".", "get", "(", "value", ",...
Serialize the attribute of the input data. Gets the attribute value with accessor and converts it using the type serialization. Schema will place this serialized value into corresponding compartment of the HAL structure with the name of the attribute as a key. :param value: Value to get the attribute value from. :return: Serialized attribute value.
[ "Serialize", "the", "attribute", "of", "the", "input", "data", "." ]
train
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/schema.py#L162-L183
paylogic/halogen
halogen/schema.py
Attr.deserialize
def deserialize(self, value, **kwargs): """Deserialize the attribute from a HAL structure. Get the value from the HAL structure from the attribute's compartment using the attribute's name as a key, convert it using the attribute's type. Schema will either return it to parent schema or will assign to the output value if specified using the attribute's accessor setter. :param value: HAL structure to get the value from. :return: Deserialized attribute value. :raises: ValidationError. """ compartment = value if self.compartment is not None: compartment = value[self.compartment] try: value = self.accessor.get(compartment, **kwargs) except (KeyError, AttributeError): if not hasattr(self, "default") and self.required: raise return self.default() if callable(self.default) else self.default return self.attr_type.deserialize(value, **kwargs)
python
def deserialize(self, value, **kwargs): """Deserialize the attribute from a HAL structure. Get the value from the HAL structure from the attribute's compartment using the attribute's name as a key, convert it using the attribute's type. Schema will either return it to parent schema or will assign to the output value if specified using the attribute's accessor setter. :param value: HAL structure to get the value from. :return: Deserialized attribute value. :raises: ValidationError. """ compartment = value if self.compartment is not None: compartment = value[self.compartment] try: value = self.accessor.get(compartment, **kwargs) except (KeyError, AttributeError): if not hasattr(self, "default") and self.required: raise return self.default() if callable(self.default) else self.default return self.attr_type.deserialize(value, **kwargs)
[ "def", "deserialize", "(", "self", ",", "value", ",", "*", "*", "kwargs", ")", ":", "compartment", "=", "value", "if", "self", ".", "compartment", "is", "not", "None", ":", "compartment", "=", "value", "[", "self", ".", "compartment", "]", "try", ":", ...
Deserialize the attribute from a HAL structure. Get the value from the HAL structure from the attribute's compartment using the attribute's name as a key, convert it using the attribute's type. Schema will either return it to parent schema or will assign to the output value if specified using the attribute's accessor setter. :param value: HAL structure to get the value from. :return: Deserialized attribute value. :raises: ValidationError.
[ "Deserialize", "the", "attribute", "from", "a", "HAL", "structure", "." ]
train
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/schema.py#L185-L209
paylogic/halogen
halogen/schema.py
Embedded.key
def key(self): """Embedded supports curies.""" if self.curie is None: return self.name return ":".join((self.curie.name, self.name))
python
def key(self): """Embedded supports curies.""" if self.curie is None: return self.name return ":".join((self.curie.name, self.name))
[ "def", "key", "(", "self", ")", ":", "if", "self", ".", "curie", "is", "None", ":", "return", "self", ".", "name", "return", "\":\"", ".", "join", "(", "(", "self", ".", "curie", ".", "name", ",", "self", ".", "name", ")", ")" ]
Embedded supports curies.
[ "Embedded", "supports", "curies", "." ]
train
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/schema.py#L376-L380
paylogic/halogen
halogen/schema.py
_Schema.deserialize
def deserialize(cls, value, output=None, **kwargs): """Deserialize the HAL structure into the output value. :param value: Dict of already loaded json which will be deserialized by schema attributes. :param output: If present, the output object will be updated instead of returning the deserialized data. :returns: Dict of deserialized value for attributes. Where key is name of schema's attribute and value is deserialized value from value dict. :raises: ValidationError. """ errors = [] result = {} for attr in cls.__attrs__.values(): try: result[attr.name] = attr.deserialize(value, **kwargs) except NotImplementedError: # Links don't support deserialization continue except ValueError as e: errors.append(exceptions.ValidationError(e, attr.name)) except exceptions.ValidationError as e: e.attr = attr.name errors.append(e) except (KeyError, AttributeError): if attr.required: errors.append(exceptions.ValidationError("Missing attribute.", attr.name)) if errors: raise exceptions.ValidationError(errors) if output is None: return result for attr in cls.__attrs__.values(): if attr.name in result: attr.accessor.set(output, result[attr.name])
python
def deserialize(cls, value, output=None, **kwargs): """Deserialize the HAL structure into the output value. :param value: Dict of already loaded json which will be deserialized by schema attributes. :param output: If present, the output object will be updated instead of returning the deserialized data. :returns: Dict of deserialized value for attributes. Where key is name of schema's attribute and value is deserialized value from value dict. :raises: ValidationError. """ errors = [] result = {} for attr in cls.__attrs__.values(): try: result[attr.name] = attr.deserialize(value, **kwargs) except NotImplementedError: # Links don't support deserialization continue except ValueError as e: errors.append(exceptions.ValidationError(e, attr.name)) except exceptions.ValidationError as e: e.attr = attr.name errors.append(e) except (KeyError, AttributeError): if attr.required: errors.append(exceptions.ValidationError("Missing attribute.", attr.name)) if errors: raise exceptions.ValidationError(errors) if output is None: return result for attr in cls.__attrs__.values(): if attr.name in result: attr.accessor.set(output, result[attr.name])
[ "def", "deserialize", "(", "cls", ",", "value", ",", "output", "=", "None", ",", "*", "*", "kwargs", ")", ":", "errors", "=", "[", "]", "result", "=", "{", "}", "for", "attr", "in", "cls", ".", "__attrs__", ".", "values", "(", ")", ":", "try", ...
Deserialize the HAL structure into the output value. :param value: Dict of already loaded json which will be deserialized by schema attributes. :param output: If present, the output object will be updated instead of returning the deserialized data. :returns: Dict of deserialized value for attributes. Where key is name of schema's attribute and value is deserialized value from value dict. :raises: ValidationError.
[ "Deserialize", "the", "HAL", "structure", "into", "the", "output", "value", "." ]
train
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/schema.py#L416-L450
d0ugal/python-rfxcom
rfxcom/protocol/temperature.py
Temperature.parse
def parse(self, data): """Parse a 9 bytes packet in the Temperature format and return a dictionary containing the data extracted. An example of a return value would be: .. code-block:: python { 'id': "0x2EB2", 'packet_length': 8, 'packet_type': 80, 'packet_type_name': 'Temperature sensors', 'sequence_number': 0, 'packet_subtype': 1, 'packet_subtype_name': "THR128/138, THC138", 'temperature': 21.3, 'signal_level': 9, 'battery_level': 6, } :param data: bytearray to be parsed :type data: bytearray :return: Data dictionary containing the parsed values :rtype: dict """ self.validate_packet(data) id_ = self.dump_hex(data[4:6]) # channel = data[5] TBC temperature = ((data[6] & 0x7f) * 256 + data[7]) / 10 signbit = data[6] & 0x80 if signbit != 0: temperature = -temperature sensor_specific = { 'id': id_, # 'channel': channel, TBC 'temperature': temperature } results = self.parse_header_part(data) results.update(RfxPacketUtils.parse_signal_and_battery(data[8])) results.update(sensor_specific) return results
python
def parse(self, data): """Parse a 9 bytes packet in the Temperature format and return a dictionary containing the data extracted. An example of a return value would be: .. code-block:: python { 'id': "0x2EB2", 'packet_length': 8, 'packet_type': 80, 'packet_type_name': 'Temperature sensors', 'sequence_number': 0, 'packet_subtype': 1, 'packet_subtype_name': "THR128/138, THC138", 'temperature': 21.3, 'signal_level': 9, 'battery_level': 6, } :param data: bytearray to be parsed :type data: bytearray :return: Data dictionary containing the parsed values :rtype: dict """ self.validate_packet(data) id_ = self.dump_hex(data[4:6]) # channel = data[5] TBC temperature = ((data[6] & 0x7f) * 256 + data[7]) / 10 signbit = data[6] & 0x80 if signbit != 0: temperature = -temperature sensor_specific = { 'id': id_, # 'channel': channel, TBC 'temperature': temperature } results = self.parse_header_part(data) results.update(RfxPacketUtils.parse_signal_and_battery(data[8])) results.update(sensor_specific) return results
[ "def", "parse", "(", "self", ",", "data", ")", ":", "self", ".", "validate_packet", "(", "data", ")", "id_", "=", "self", ".", "dump_hex", "(", "data", "[", "4", ":", "6", "]", ")", "# channel = data[5] TBC", "temperature", "=", "(", "(", "data", "["...
Parse a 9 bytes packet in the Temperature format and return a dictionary containing the data extracted. An example of a return value would be: .. code-block:: python { 'id': "0x2EB2", 'packet_length': 8, 'packet_type': 80, 'packet_type_name': 'Temperature sensors', 'sequence_number': 0, 'packet_subtype': 1, 'packet_subtype_name': "THR128/138, THC138", 'temperature': 21.3, 'signal_level': 9, 'battery_level': 6, } :param data: bytearray to be parsed :type data: bytearray :return: Data dictionary containing the parsed values :rtype: dict
[ "Parse", "a", "9", "bytes", "packet", "in", "the", "Temperature", "format", "and", "return", "a", "dictionary", "containing", "the", "data", "extracted", ".", "An", "example", "of", "a", "return", "value", "would", "be", ":" ]
train
https://github.com/d0ugal/python-rfxcom/blob/2eb87f85e5f5a04d00f32f25e0f010edfefbde0d/rfxcom/protocol/temperature.py#L49-L96
dhondta/tinyscript
tinyscript/helpers/types.py
neg_int
def neg_int(i): """ Simple negative integer validation. """ try: if isinstance(i, string_types): i = int(i) if not isinstance(i, int) or i > 0: raise Exception() except: raise ValueError("Not a negative integer") return i
python
def neg_int(i): """ Simple negative integer validation. """ try: if isinstance(i, string_types): i = int(i) if not isinstance(i, int) or i > 0: raise Exception() except: raise ValueError("Not a negative integer") return i
[ "def", "neg_int", "(", "i", ")", ":", "try", ":", "if", "isinstance", "(", "i", ",", "string_types", ")", ":", "i", "=", "int", "(", "i", ")", "if", "not", "isinstance", "(", "i", ",", "int", ")", "or", "i", ">", "0", ":", "raise", "Exception",...
Simple negative integer validation.
[ "Simple", "negative", "integer", "validation", "." ]
train
https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/helpers/types.py#L21-L30
dhondta/tinyscript
tinyscript/helpers/types.py
pos_int
def pos_int(i): """ Simple positive integer validation. """ try: if isinstance(i, string_types): i = int(i) if not isinstance(i, int) or i < 0: raise Exception() except: raise ValueError("Not a positive integer") return i
python
def pos_int(i): """ Simple positive integer validation. """ try: if isinstance(i, string_types): i = int(i) if not isinstance(i, int) or i < 0: raise Exception() except: raise ValueError("Not a positive integer") return i
[ "def", "pos_int", "(", "i", ")", ":", "try", ":", "if", "isinstance", "(", "i", ",", "string_types", ")", ":", "i", "=", "int", "(", "i", ")", "if", "not", "isinstance", "(", "i", ",", "int", ")", "or", "i", "<", "0", ":", "raise", "Exception",...
Simple positive integer validation.
[ "Simple", "positive", "integer", "validation", "." ]
train
https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/helpers/types.py#L34-L43
dhondta/tinyscript
tinyscript/helpers/types.py
ints
def ints(l, ifilter=lambda x: x, idescr=None): """ Parses a comma-separated list of ints. """ if isinstance(l, string_types): if l[0] == '[' and l[-1] == ']': l = l[1:-1] l = list(map(lambda x: x.strip(), l.split(','))) try: l = list(map(ifilter, list(map(int, l)))) except: raise ValueError("Bad list of {}integers" .format("" if idescr is None else idescr + " ")) return l
python
def ints(l, ifilter=lambda x: x, idescr=None): """ Parses a comma-separated list of ints. """ if isinstance(l, string_types): if l[0] == '[' and l[-1] == ']': l = l[1:-1] l = list(map(lambda x: x.strip(), l.split(','))) try: l = list(map(ifilter, list(map(int, l)))) except: raise ValueError("Bad list of {}integers" .format("" if idescr is None else idescr + " ")) return l
[ "def", "ints", "(", "l", ",", "ifilter", "=", "lambda", "x", ":", "x", ",", "idescr", "=", "None", ")", ":", "if", "isinstance", "(", "l", ",", "string_types", ")", ":", "if", "l", "[", "0", "]", "==", "'['", "and", "l", "[", "-", "1", "]", ...
Parses a comma-separated list of ints.
[ "Parses", "a", "comma", "-", "separated", "list", "of", "ints", "." ]
train
https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/helpers/types.py#L47-L58
dhondta/tinyscript
tinyscript/helpers/types.py
ip_address_list
def ip_address_list(ips): """ IP address range validation and expansion. """ # first, try it as a single IP address try: return ip_address(ips) except ValueError: pass # then, consider it as an ipaddress.IPv[4|6]Network instance and expand it return list(ipaddress.ip_network(u(ips)).hosts())
python
def ip_address_list(ips): """ IP address range validation and expansion. """ # first, try it as a single IP address try: return ip_address(ips) except ValueError: pass # then, consider it as an ipaddress.IPv[4|6]Network instance and expand it return list(ipaddress.ip_network(u(ips)).hosts())
[ "def", "ip_address_list", "(", "ips", ")", ":", "# first, try it as a single IP address", "try", ":", "return", "ip_address", "(", "ips", ")", "except", "ValueError", ":", "pass", "# then, consider it as an ipaddress.IPv[4|6]Network instance and expand it", "return", "list", ...
IP address range validation and expansion.
[ "IP", "address", "range", "validation", "and", "expansion", "." ]
train
https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/helpers/types.py#L72-L80
dhondta/tinyscript
tinyscript/helpers/types.py
port_number
def port_number(port): """ Port number validation. """ try: port = int(port) except ValueError: raise ValueError("Bad port number") if not 0 <= port < 2 ** 16: raise ValueError("Bad port number") return port
python
def port_number(port): """ Port number validation. """ try: port = int(port) except ValueError: raise ValueError("Bad port number") if not 0 <= port < 2 ** 16: raise ValueError("Bad port number") return port
[ "def", "port_number", "(", "port", ")", ":", "try", ":", "port", "=", "int", "(", "port", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "\"Bad port number\"", ")", "if", "not", "0", "<=", "port", "<", "2", "**", "16", ":", "raise", "V...
Port number validation.
[ "Port", "number", "validation", "." ]
train
https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/helpers/types.py#L94-L102
dhondta/tinyscript
tinyscript/helpers/types.py
port_number_range
def port_number_range(prange): """ Port number range validation and expansion. """ # first, try it as a normal port number try: return port_number(prange) except ValueError: pass # then, consider it as a range with the format "x-y" and expand it try: bounds = list(map(int, re.match(r'^(\d+)\-(\d+)$', prange).groups())) if bounds[0] > bounds[1]: raise AttributeError() except (AttributeError, TypeError): raise ValueError("Bad port number range") return list(range(bounds[0], bounds[1] + 1))
python
def port_number_range(prange): """ Port number range validation and expansion. """ # first, try it as a normal port number try: return port_number(prange) except ValueError: pass # then, consider it as a range with the format "x-y" and expand it try: bounds = list(map(int, re.match(r'^(\d+)\-(\d+)$', prange).groups())) if bounds[0] > bounds[1]: raise AttributeError() except (AttributeError, TypeError): raise ValueError("Bad port number range") return list(range(bounds[0], bounds[1] + 1))
[ "def", "port_number_range", "(", "prange", ")", ":", "# first, try it as a normal port number", "try", ":", "return", "port_number", "(", "prange", ")", "except", "ValueError", ":", "pass", "# then, consider it as a range with the format \"x-y\" and expand it", "try", ":", ...
Port number range validation and expansion.
[ "Port", "number", "range", "validation", "and", "expansion", "." ]
train
https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/helpers/types.py#L105-L119
d0ugal/python-rfxcom
rfxcom/protocol/base.py
BasePacket.parse_header_part
def parse_header_part(self, data): """Extracts and converts the RFX common header part of all valid packets to a plain dictionary. RFX header part is the 4 bytes prior the sensor vendor specific data part. The RFX common header part contains respectively: - packet length - packet type - packet sub-type - sequence number :param data: bytearray of received data :type data: bytearray """ packet_length = data[0] packet_type = data[1] packet_subtype = data[2] sequence_number = data[3] return { 'packet_length': packet_length, 'packet_type': packet_type, 'packet_type_name': self.PACKET_TYPES.get(packet_type), 'packet_subtype': packet_subtype, 'packet_subtype_name': self.PACKET_SUBTYPES.get(packet_subtype), 'sequence_number': sequence_number }
python
def parse_header_part(self, data): """Extracts and converts the RFX common header part of all valid packets to a plain dictionary. RFX header part is the 4 bytes prior the sensor vendor specific data part. The RFX common header part contains respectively: - packet length - packet type - packet sub-type - sequence number :param data: bytearray of received data :type data: bytearray """ packet_length = data[0] packet_type = data[1] packet_subtype = data[2] sequence_number = data[3] return { 'packet_length': packet_length, 'packet_type': packet_type, 'packet_type_name': self.PACKET_TYPES.get(packet_type), 'packet_subtype': packet_subtype, 'packet_subtype_name': self.PACKET_SUBTYPES.get(packet_subtype), 'sequence_number': sequence_number }
[ "def", "parse_header_part", "(", "self", ",", "data", ")", ":", "packet_length", "=", "data", "[", "0", "]", "packet_type", "=", "data", "[", "1", "]", "packet_subtype", "=", "data", "[", "2", "]", "sequence_number", "=", "data", "[", "3", "]", "return...
Extracts and converts the RFX common header part of all valid packets to a plain dictionary. RFX header part is the 4 bytes prior the sensor vendor specific data part. The RFX common header part contains respectively: - packet length - packet type - packet sub-type - sequence number :param data: bytearray of received data :type data: bytearray
[ "Extracts", "and", "converts", "the", "RFX", "common", "header", "part", "of", "all", "valid", "packets", "to", "a", "plain", "dictionary", ".", "RFX", "header", "part", "is", "the", "4", "bytes", "prior", "the", "sensor", "vendor", "specific", "data", "pa...
train
https://github.com/d0ugal/python-rfxcom/blob/2eb87f85e5f5a04d00f32f25e0f010edfefbde0d/rfxcom/protocol/base.py#L58-L84
d0ugal/python-rfxcom
rfxcom/protocol/base.py
BasePacket.load
def load(self, data): """This is the entrance method for all data which is used to store the raw data and start parsing the data. :param data: The raw untouched bytearray as recieved by the RFXtrx :type data: bytearray :return: The parsed data represented in a dictionary :rtype: dict """ self.loaded_at = datetime.utcnow() self.raw = data self.data = self.parse(data) return self.data
python
def load(self, data): """This is the entrance method for all data which is used to store the raw data and start parsing the data. :param data: The raw untouched bytearray as recieved by the RFXtrx :type data: bytearray :return: The parsed data represented in a dictionary :rtype: dict """ self.loaded_at = datetime.utcnow() self.raw = data self.data = self.parse(data) return self.data
[ "def", "load", "(", "self", ",", "data", ")", ":", "self", ".", "loaded_at", "=", "datetime", ".", "utcnow", "(", ")", "self", ".", "raw", "=", "data", "self", ".", "data", "=", "self", ".", "parse", "(", "data", ")", "return", "self", ".", "data...
This is the entrance method for all data which is used to store the raw data and start parsing the data. :param data: The raw untouched bytearray as recieved by the RFXtrx :type data: bytearray :return: The parsed data represented in a dictionary :rtype: dict
[ "This", "is", "the", "entrance", "method", "for", "all", "data", "which", "is", "used", "to", "store", "the", "raw", "data", "and", "start", "parsing", "the", "data", "." ]
train
https://github.com/d0ugal/python-rfxcom/blob/2eb87f85e5f5a04d00f32f25e0f010edfefbde0d/rfxcom/protocol/base.py#L86-L99
d0ugal/python-rfxcom
rfxcom/protocol/base.py
BasePacketHandler.validate_packet
def validate_packet(self, data): """Validate a packet against this packet handler and determine if it meets the requirements. This is done by checking the following conditions are true. - The length of the packet is equal to the first byte. - The second byte is in the set of defined PACKET_TYPES for this class. - The third byte is in the set of this class defined PACKET_SUBTYPES. If one or more of these conditions isn't met then we have a packet that isn't valid or at least isn't understood by this handler. :param data: bytearray to be verified :type data: bytearray :raises: :py:class:`rfxcom.exceptions.InvalidPacketLength`: If the number of bytes in the packet doesn't match the expected length. :raises: :py:class:`rfxcom.exceptions.UnknownPacketType`: If the packet type is unknown to this packet handler :raises: :py:class:`rfxcom.exceptions.UnknownPacketSubtype`: If the packet sub type is unknown to this packet handler :return: true is returned if validation passes. :rtype: boolean """ # Validate length. # The first byte in the packet should be equal to the number of # remaining bytes (i.e. length excluding the first byte). expected_length = data[0] + 1 if len(data) != expected_length: raise InvalidPacketLength( "Expected packet length to be %s bytes but it was %s bytes" % (expected_length, len(data)) ) # Validate minimal length. # The packet contains at least the RFX header: # packet_length (1 byte) + packet_type (1 byte) # + packet_subtype (1 byte) + sequence_number (1 byte) if expected_length < 4: raise MalformedPacket( "Expected packet length to be larger than 4 bytes but \ it was %s bytes" % (len(data)) ) # Validate Packet Type. # This specifies the family of devices. # Check it is one of the supported packet types packet_type = data[1] if self.PACKET_TYPES and packet_type not in self.PACKET_TYPES: types = ",".join("0x{:02x}".format(pt) for pt in self.PACKET_TYPES) raise UnknownPacketType( "Expected packet type to be one of [%s] but recieved %s" % (types, packet_type) ) # Validate Packet Subtype. # This specifies the sub-family of devices. # Check it is one of the supported packet subtypes for current type sub_type = data[2] if self.PACKET_SUBTYPES and sub_type not in self.PACKET_SUBTYPES: types = \ ",".join("0x{:02x}".format(pt) for pt in self.PACKET_SUBTYPES) raise UnknownPacketSubtype( "Expected packet type to be one of [%s] but recieved %s" % (types, sub_type)) return True
python
def validate_packet(self, data): """Validate a packet against this packet handler and determine if it meets the requirements. This is done by checking the following conditions are true. - The length of the packet is equal to the first byte. - The second byte is in the set of defined PACKET_TYPES for this class. - The third byte is in the set of this class defined PACKET_SUBTYPES. If one or more of these conditions isn't met then we have a packet that isn't valid or at least isn't understood by this handler. :param data: bytearray to be verified :type data: bytearray :raises: :py:class:`rfxcom.exceptions.InvalidPacketLength`: If the number of bytes in the packet doesn't match the expected length. :raises: :py:class:`rfxcom.exceptions.UnknownPacketType`: If the packet type is unknown to this packet handler :raises: :py:class:`rfxcom.exceptions.UnknownPacketSubtype`: If the packet sub type is unknown to this packet handler :return: true is returned if validation passes. :rtype: boolean """ # Validate length. # The first byte in the packet should be equal to the number of # remaining bytes (i.e. length excluding the first byte). expected_length = data[0] + 1 if len(data) != expected_length: raise InvalidPacketLength( "Expected packet length to be %s bytes but it was %s bytes" % (expected_length, len(data)) ) # Validate minimal length. # The packet contains at least the RFX header: # packet_length (1 byte) + packet_type (1 byte) # + packet_subtype (1 byte) + sequence_number (1 byte) if expected_length < 4: raise MalformedPacket( "Expected packet length to be larger than 4 bytes but \ it was %s bytes" % (len(data)) ) # Validate Packet Type. # This specifies the family of devices. # Check it is one of the supported packet types packet_type = data[1] if self.PACKET_TYPES and packet_type not in self.PACKET_TYPES: types = ",".join("0x{:02x}".format(pt) for pt in self.PACKET_TYPES) raise UnknownPacketType( "Expected packet type to be one of [%s] but recieved %s" % (types, packet_type) ) # Validate Packet Subtype. # This specifies the sub-family of devices. # Check it is one of the supported packet subtypes for current type sub_type = data[2] if self.PACKET_SUBTYPES and sub_type not in self.PACKET_SUBTYPES: types = \ ",".join("0x{:02x}".format(pt) for pt in self.PACKET_SUBTYPES) raise UnknownPacketSubtype( "Expected packet type to be one of [%s] but recieved %s" % (types, sub_type)) return True
[ "def", "validate_packet", "(", "self", ",", "data", ")", ":", "# Validate length.", "# The first byte in the packet should be equal to the number of", "# remaining bytes (i.e. length excluding the first byte).", "expected_length", "=", "data", "[", "0", "]", "+", "1", "if", "...
Validate a packet against this packet handler and determine if it meets the requirements. This is done by checking the following conditions are true. - The length of the packet is equal to the first byte. - The second byte is in the set of defined PACKET_TYPES for this class. - The third byte is in the set of this class defined PACKET_SUBTYPES. If one or more of these conditions isn't met then we have a packet that isn't valid or at least isn't understood by this handler. :param data: bytearray to be verified :type data: bytearray :raises: :py:class:`rfxcom.exceptions.InvalidPacketLength`: If the number of bytes in the packet doesn't match the expected length. :raises: :py:class:`rfxcom.exceptions.UnknownPacketType`: If the packet type is unknown to this packet handler :raises: :py:class:`rfxcom.exceptions.UnknownPacketSubtype`: If the packet sub type is unknown to this packet handler :return: true is returned if validation passes. :rtype: boolean
[ "Validate", "a", "packet", "against", "this", "packet", "handler", "and", "determine", "if", "it", "meets", "the", "requirements", ".", "This", "is", "done", "by", "checking", "the", "following", "conditions", "are", "true", "." ]
train
https://github.com/d0ugal/python-rfxcom/blob/2eb87f85e5f5a04d00f32f25e0f010edfefbde0d/rfxcom/protocol/base.py#L122-L198
toumorokoshi/transmute-core
transmute_core/object_serializers/schematics_serializer.py
_enforce_instance
def _enforce_instance(model_or_class): """ It's a common mistake to not initialize a schematics class. We should handle that by just calling the default constructor. """ if isinstance(model_or_class, type) and issubclass(model_or_class, BaseType): return model_or_class() return model_or_class
python
def _enforce_instance(model_or_class): """ It's a common mistake to not initialize a schematics class. We should handle that by just calling the default constructor. """ if isinstance(model_or_class, type) and issubclass(model_or_class, BaseType): return model_or_class() return model_or_class
[ "def", "_enforce_instance", "(", "model_or_class", ")", ":", "if", "isinstance", "(", "model_or_class", ",", "type", ")", "and", "issubclass", "(", "model_or_class", ",", "BaseType", ")", ":", "return", "model_or_class", "(", ")", "return", "model_or_class" ]
It's a common mistake to not initialize a schematics class. We should handle that by just calling the default constructor.
[ "It", "s", "a", "common", "mistake", "to", "not", "initialize", "a", "schematics", "class", ".", "We", "should", "handle", "that", "by", "just", "calling", "the", "default", "constructor", "." ]
train
https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/object_serializers/schematics_serializer.py#L177-L185
inveniosoftware/invenio-previewer
invenio_previewer/extensions/ipynb.py
render
def render(file): """Generate the result HTML.""" fp = file.open() content = fp.read() fp.close() notebook = nbformat.reads(content.decode('utf-8'), as_version=4) html_exporter = HTMLExporter() html_exporter.template_file = 'basic' (body, resources) = html_exporter.from_notebook_node(notebook) return body, resources
python
def render(file): """Generate the result HTML.""" fp = file.open() content = fp.read() fp.close() notebook = nbformat.reads(content.decode('utf-8'), as_version=4) html_exporter = HTMLExporter() html_exporter.template_file = 'basic' (body, resources) = html_exporter.from_notebook_node(notebook) return body, resources
[ "def", "render", "(", "file", ")", ":", "fp", "=", "file", ".", "open", "(", ")", "content", "=", "fp", ".", "read", "(", ")", "fp", ".", "close", "(", ")", "notebook", "=", "nbformat", ".", "reads", "(", "content", ".", "decode", "(", "'utf-8'",...
Generate the result HTML.
[ "Generate", "the", "result", "HTML", "." ]
train
https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/extensions/ipynb.py#L18-L29
inveniosoftware/invenio-previewer
invenio_previewer/extensions/ipynb.py
preview
def preview(file): """Render the IPython Notebook.""" body, resources = render(file) default_ipython_style = resources['inlining']['css'][1] return render_template( 'invenio_previewer/ipynb.html', file=file, content=body, style=default_ipython_style )
python
def preview(file): """Render the IPython Notebook.""" body, resources = render(file) default_ipython_style = resources['inlining']['css'][1] return render_template( 'invenio_previewer/ipynb.html', file=file, content=body, style=default_ipython_style )
[ "def", "preview", "(", "file", ")", ":", "body", ",", "resources", "=", "render", "(", "file", ")", "default_ipython_style", "=", "resources", "[", "'inlining'", "]", "[", "'css'", "]", "[", "1", "]", "return", "render_template", "(", "'invenio_previewer/ipy...
Render the IPython Notebook.
[ "Render", "the", "IPython", "Notebook", "." ]
train
https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/extensions/ipynb.py#L37-L46
toumorokoshi/transmute-core
example.py
transmute_route
def transmute_route(app, fn, context=default_context): """ this is the main interface to transmute. It will handle adding converting the python function into the a flask-compatible route, and adding it to the application. """ transmute_func = TransmuteFunction(fn) routes, handler = create_routes_and_handler(transmute_func, context) for r in routes: """ the route being attached is a great place to start building up a swagger spec. the SwaggerSpec object handles creating the swagger spec from transmute routes for you. almost all web frameworks provide some app-specific context that one can add values to. It's recommended to attach and retrieve the swagger spec from there. """ if not hasattr(app, SWAGGER_ATTR_NAME): setattr(app, SWAGGER_ATTR_NAME, SwaggerSpec()) swagger_obj = getattr(app, SWAGGER_ATTR_NAME) swagger_obj.add_func(transmute_func, context) app.route(r, methods=transmute_func.methods)(handler)
python
def transmute_route(app, fn, context=default_context): """ this is the main interface to transmute. It will handle adding converting the python function into the a flask-compatible route, and adding it to the application. """ transmute_func = TransmuteFunction(fn) routes, handler = create_routes_and_handler(transmute_func, context) for r in routes: """ the route being attached is a great place to start building up a swagger spec. the SwaggerSpec object handles creating the swagger spec from transmute routes for you. almost all web frameworks provide some app-specific context that one can add values to. It's recommended to attach and retrieve the swagger spec from there. """ if not hasattr(app, SWAGGER_ATTR_NAME): setattr(app, SWAGGER_ATTR_NAME, SwaggerSpec()) swagger_obj = getattr(app, SWAGGER_ATTR_NAME) swagger_obj.add_func(transmute_func, context) app.route(r, methods=transmute_func.methods)(handler)
[ "def", "transmute_route", "(", "app", ",", "fn", ",", "context", "=", "default_context", ")", ":", "transmute_func", "=", "TransmuteFunction", "(", "fn", ")", "routes", ",", "handler", "=", "create_routes_and_handler", "(", "transmute_func", ",", "context", ")",...
this is the main interface to transmute. It will handle adding converting the python function into the a flask-compatible route, and adding it to the application.
[ "this", "is", "the", "main", "interface", "to", "transmute", ".", "It", "will", "handle", "adding", "converting", "the", "python", "function", "into", "the", "a", "flask", "-", "compatible", "route", "and", "adding", "it", "to", "the", "application", "." ]
train
https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/example.py#L27-L49
toumorokoshi/transmute-core
example.py
create_routes_and_handler
def create_routes_and_handler(transmute_func, context): """ return back a handler that is the api generated from the transmute_func, and a list of routes it should be mounted to. """ @wraps(transmute_func.raw_func) def handler(): exc, result = None, None try: args, kwargs = ParamExtractorFlask().extract_params( context, transmute_func, request.content_type ) result = transmute_func(*args, **kwargs) except Exception as e: exc = e """ attaching the traceack is done for you in Python 3, but in Python 2 the __traceback__ must be attached to the object manually. """ exc.__traceback__ = sys.exc_info()[2] """ transmute_func.process_result handles converting the response from the function into the response body, the status code that should be returned, and the response content-type. """ response = transmute_func.process_result( context, result, exc, request.content_type ) return Response( response["body"], status=response["code"], mimetype=response["content-type"], headers=response["headers"] ) return ( _convert_paths_to_flask(transmute_func.paths), handler )
python
def create_routes_and_handler(transmute_func, context): """ return back a handler that is the api generated from the transmute_func, and a list of routes it should be mounted to. """ @wraps(transmute_func.raw_func) def handler(): exc, result = None, None try: args, kwargs = ParamExtractorFlask().extract_params( context, transmute_func, request.content_type ) result = transmute_func(*args, **kwargs) except Exception as e: exc = e """ attaching the traceack is done for you in Python 3, but in Python 2 the __traceback__ must be attached to the object manually. """ exc.__traceback__ = sys.exc_info()[2] """ transmute_func.process_result handles converting the response from the function into the response body, the status code that should be returned, and the response content-type. """ response = transmute_func.process_result( context, result, exc, request.content_type ) return Response( response["body"], status=response["code"], mimetype=response["content-type"], headers=response["headers"] ) return ( _convert_paths_to_flask(transmute_func.paths), handler )
[ "def", "create_routes_and_handler", "(", "transmute_func", ",", "context", ")", ":", "@", "wraps", "(", "transmute_func", ".", "raw_func", ")", "def", "handler", "(", ")", ":", "exc", ",", "result", "=", "None", ",", "None", "try", ":", "args", ",", "kwa...
return back a handler that is the api generated from the transmute_func, and a list of routes it should be mounted to.
[ "return", "back", "a", "handler", "that", "is", "the", "api", "generated", "from", "the", "transmute_func", "and", "a", "list", "of", "routes", "it", "should", "be", "mounted", "to", "." ]
train
https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/example.py#L52-L92
toumorokoshi/transmute-core
example.py
_convert_paths_to_flask
def _convert_paths_to_flask(transmute_paths): """ convert transmute-core's path syntax (which uses {var} as the variable wildcard) into flask's <var>. """ paths = [] for p in transmute_paths: paths.append(p.replace("{", "<").replace("}", ">")) return paths
python
def _convert_paths_to_flask(transmute_paths): """ convert transmute-core's path syntax (which uses {var} as the variable wildcard) into flask's <var>. """ paths = [] for p in transmute_paths: paths.append(p.replace("{", "<").replace("}", ">")) return paths
[ "def", "_convert_paths_to_flask", "(", "transmute_paths", ")", ":", "paths", "=", "[", "]", "for", "p", "in", "transmute_paths", ":", "paths", ".", "append", "(", "p", ".", "replace", "(", "\"{\"", ",", "\"<\"", ")", ".", "replace", "(", "\"}\"", ",", ...
convert transmute-core's path syntax (which uses {var} as the variable wildcard) into flask's <var>.
[ "convert", "transmute", "-", "core", "s", "path", "syntax", "(", "which", "uses", "{", "var", "}", "as", "the", "variable", "wildcard", ")", "into", "flask", "s", "<var", ">", "." ]
train
https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/example.py#L95-L103
toumorokoshi/transmute-core
example.py
add_swagger
def add_swagger(app, json_route, html_route, **kwargs): """ add a swagger html page, and a swagger.json generated from the routes added to the app. """ spec = getattr(app, SWAGGER_ATTR_NAME) if spec: spec = spec.swagger_definition(**kwargs) else: spec = {} encoded_spec = json.dumps(spec).encode("UTF-8") @app.route(json_route) def swagger(): return Response( encoded_spec, # we allow CORS, so this can be requested at swagger.io headers={"Access-Control-Allow-Origin": "*"}, content_type="application/json", ) # add the statics static_root = get_swagger_static_root() swagger_body = generate_swagger_html( STATIC_PATH, json_route ).encode("utf-8") @app.route(html_route) def swagger_ui(): return Response(swagger_body, content_type="text/html") # the blueprint work is the easiest way to integrate a static # directory into flask. blueprint = Blueprint('swagger', __name__, static_url_path=STATIC_PATH, static_folder=static_root) app.register_blueprint(blueprint)
python
def add_swagger(app, json_route, html_route, **kwargs): """ add a swagger html page, and a swagger.json generated from the routes added to the app. """ spec = getattr(app, SWAGGER_ATTR_NAME) if spec: spec = spec.swagger_definition(**kwargs) else: spec = {} encoded_spec = json.dumps(spec).encode("UTF-8") @app.route(json_route) def swagger(): return Response( encoded_spec, # we allow CORS, so this can be requested at swagger.io headers={"Access-Control-Allow-Origin": "*"}, content_type="application/json", ) # add the statics static_root = get_swagger_static_root() swagger_body = generate_swagger_html( STATIC_PATH, json_route ).encode("utf-8") @app.route(html_route) def swagger_ui(): return Response(swagger_body, content_type="text/html") # the blueprint work is the easiest way to integrate a static # directory into flask. blueprint = Blueprint('swagger', __name__, static_url_path=STATIC_PATH, static_folder=static_root) app.register_blueprint(blueprint)
[ "def", "add_swagger", "(", "app", ",", "json_route", ",", "html_route", ",", "*", "*", "kwargs", ")", ":", "spec", "=", "getattr", "(", "app", ",", "SWAGGER_ATTR_NAME", ")", "if", "spec", ":", "spec", "=", "spec", ".", "swagger_definition", "(", "*", "...
add a swagger html page, and a swagger.json generated from the routes added to the app.
[ "add", "a", "swagger", "html", "page", "and", "a", "swagger", ".", "json", "generated", "from", "the", "routes", "added", "to", "the", "app", "." ]
train
https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/example.py#L155-L190
d0ugal/python-rfxcom
rfxcom/protocol/status.py
Status._log_enabled_protocols
def _log_enabled_protocols(self, flags, protocols): """Given a list of single character strings of 1's and 0's and a list of protocol names. Log the status of each protocol where ``"1"`` is enabled and ``"0"`` is disabled. The order of the lists here is important as they need to be zipped together to create the mapping. Then return a tuple of two lists containing the names of the enabled and disabled protocols. :param character: A list of single character strings of 1's and 0's :type character: list :param protocols: A list of protocol names. :type protocols: list :return: Tuple containing two lists which contain n strings. :rtype: tuple """ enabled, disabled = [], [] for procol, flag in sorted(zip(protocols, flags)): if flag == '1': enabled.append(procol) status = 'Enabled' else: disabled.append(procol) status = 'Disabled' message = "{0:21}: {1}".format(procol, status) self.log.info(message) return enabled, disabled
python
def _log_enabled_protocols(self, flags, protocols): """Given a list of single character strings of 1's and 0's and a list of protocol names. Log the status of each protocol where ``"1"`` is enabled and ``"0"`` is disabled. The order of the lists here is important as they need to be zipped together to create the mapping. Then return a tuple of two lists containing the names of the enabled and disabled protocols. :param character: A list of single character strings of 1's and 0's :type character: list :param protocols: A list of protocol names. :type protocols: list :return: Tuple containing two lists which contain n strings. :rtype: tuple """ enabled, disabled = [], [] for procol, flag in sorted(zip(protocols, flags)): if flag == '1': enabled.append(procol) status = 'Enabled' else: disabled.append(procol) status = 'Disabled' message = "{0:21}: {1}".format(procol, status) self.log.info(message) return enabled, disabled
[ "def", "_log_enabled_protocols", "(", "self", ",", "flags", ",", "protocols", ")", ":", "enabled", ",", "disabled", "=", "[", "]", ",", "[", "]", "for", "procol", ",", "flag", "in", "sorted", "(", "zip", "(", "protocols", ",", "flags", ")", ")", ":",...
Given a list of single character strings of 1's and 0's and a list of protocol names. Log the status of each protocol where ``"1"`` is enabled and ``"0"`` is disabled. The order of the lists here is important as they need to be zipped together to create the mapping. Then return a tuple of two lists containing the names of the enabled and disabled protocols. :param character: A list of single character strings of 1's and 0's :type character: list :param protocols: A list of protocol names. :type protocols: list :return: Tuple containing two lists which contain n strings. :rtype: tuple
[ "Given", "a", "list", "of", "single", "character", "strings", "of", "1", "s", "and", "0", "s", "and", "a", "list", "of", "protocol", "names", ".", "Log", "the", "status", "of", "each", "protocol", "where", "1", "is", "enabled", "and", "0", "is", "dis...
train
https://github.com/d0ugal/python-rfxcom/blob/2eb87f85e5f5a04d00f32f25e0f010edfefbde0d/rfxcom/protocol/status.py#L98-L130
d0ugal/python-rfxcom
rfxcom/protocol/status.py
Status.parse
def parse(self, data): """Parse a 13 byte packet in the Status format. :param data: bytearray to be parsed :type data: bytearray :return: Data dictionary containing the parsed values :rtype: dict """ self.validate_packet(data) packet_length = data[0] packet_type = data[1] sub_type = data[2] sequence_number = data[3] command_type = data[4] transceiver_type = data[5] transceiver_type_text = _MSG1_RECEIVER_TYPE.get(data[5]) firmware_version = data[6] flags = self._int_to_binary_list(data[7]) flags.extend(self._int_to_binary_list(data[8])) flags.extend(self._int_to_binary_list(data[9])) enabled, disabled = self._log_enabled_protocols(flags, PROTOCOLS) return { 'packet_length': packet_length, 'packet_type': packet_type, 'packet_type_name': self.PACKET_TYPES.get(packet_type), 'sequence_number': sequence_number, 'sub_type': sub_type, 'sub_type_name': self.PACKET_SUBTYPES.get(sub_type), 'command_type': command_type, 'transceiver_type': transceiver_type, 'transceiver_type_text': transceiver_type_text, 'firmware_version': firmware_version, 'enabled_protocols': enabled, 'disabled_protocols': disabled, }
python
def parse(self, data): """Parse a 13 byte packet in the Status format. :param data: bytearray to be parsed :type data: bytearray :return: Data dictionary containing the parsed values :rtype: dict """ self.validate_packet(data) packet_length = data[0] packet_type = data[1] sub_type = data[2] sequence_number = data[3] command_type = data[4] transceiver_type = data[5] transceiver_type_text = _MSG1_RECEIVER_TYPE.get(data[5]) firmware_version = data[6] flags = self._int_to_binary_list(data[7]) flags.extend(self._int_to_binary_list(data[8])) flags.extend(self._int_to_binary_list(data[9])) enabled, disabled = self._log_enabled_protocols(flags, PROTOCOLS) return { 'packet_length': packet_length, 'packet_type': packet_type, 'packet_type_name': self.PACKET_TYPES.get(packet_type), 'sequence_number': sequence_number, 'sub_type': sub_type, 'sub_type_name': self.PACKET_SUBTYPES.get(sub_type), 'command_type': command_type, 'transceiver_type': transceiver_type, 'transceiver_type_text': transceiver_type_text, 'firmware_version': firmware_version, 'enabled_protocols': enabled, 'disabled_protocols': disabled, }
[ "def", "parse", "(", "self", ",", "data", ")", ":", "self", ".", "validate_packet", "(", "data", ")", "packet_length", "=", "data", "[", "0", "]", "packet_type", "=", "data", "[", "1", "]", "sub_type", "=", "data", "[", "2", "]", "sequence_number", "...
Parse a 13 byte packet in the Status format. :param data: bytearray to be parsed :type data: bytearray :return: Data dictionary containing the parsed values :rtype: dict
[ "Parse", "a", "13", "byte", "packet", "in", "the", "Status", "format", "." ]
train
https://github.com/d0ugal/python-rfxcom/blob/2eb87f85e5f5a04d00f32f25e0f010edfefbde0d/rfxcom/protocol/status.py#L144-L184
dhondta/tinyscript
tinyscript/timing.py
set_time_items
def set_time_items(glob): """ This function prepares the benchmark items for inclusion in main script's global scope. :param glob: main script's global scope dictionary reference """ a = glob['args'] l = glob['logger'] class __TimeManager(object): def __init__(self): c = a._collisions self._stats = getattr(a, c.get("stats") or "stats", False) self._timings = getattr(a, c.get("timings") or "timings", False) self.enabled = self._stats or self._timings self.last = self.start = time.time() self.times = [] def stats(self): end = time.time() b = "" for d, s, e in self.times: b += "\n{}\n> {} seconds".format(d, e - s) l.time("Total time: {} seconds{}".format(end - self.start, b)) glob['time_manager'] = manager = __TimeManager() def _take_time(start=None, descr=None): t = manager.last = time.time() if start is not None and descr is not None: manager.times.append((descr, float(start), float(t))) return t - (start or 0) class Timer(object): class TimeoutError(Exception): pass # TimeoutError is not handled in Python 2 def __init__(self, description=None, message=TO_MSG, timeout=None, fail_on_timeout=False): self.fail = fail_on_timeout self.id = len(manager.times) self.descr = "#" + str(self.id) + \ (": " + (description or "")).rstrip(": ") self.message = message self.start = _take_time() self.timeout = timeout def __enter__(self): if manager.enabled: if self.timeout is not None: signal.signal(signal.SIGALRM, self._handler) signal.alarm(self.timeout) if manager._timings and self.descr: l.time(self.descr) return self def __exit__(self, exc_type, exc_value, exc_traceback): if manager.enabled: d = _take_time(self.start, self.descr) if manager._timings: l.time("> Time elapsed: {} seconds".format(d)) if self.timeout is not None: if self.fail and exc_type is Timer.TimeoutError: return True def _handler(self, signum, frame): raise Timer.TimeoutError(self.message) glob['Timer'] = Timer def get_time(message=None, start=manager.start): if manager._timings: l.time("> {}: {} seconds".format(message or "Time elapsed since " "execution start", _take_time(start))) glob['get_time'] = get_time def get_time_since_last(message=None): get_time(message or "Time elapsed since last measure", manager.last) glob['get_time_since_last'] = get_time_since_last
python
def set_time_items(glob): """ This function prepares the benchmark items for inclusion in main script's global scope. :param glob: main script's global scope dictionary reference """ a = glob['args'] l = glob['logger'] class __TimeManager(object): def __init__(self): c = a._collisions self._stats = getattr(a, c.get("stats") or "stats", False) self._timings = getattr(a, c.get("timings") or "timings", False) self.enabled = self._stats or self._timings self.last = self.start = time.time() self.times = [] def stats(self): end = time.time() b = "" for d, s, e in self.times: b += "\n{}\n> {} seconds".format(d, e - s) l.time("Total time: {} seconds{}".format(end - self.start, b)) glob['time_manager'] = manager = __TimeManager() def _take_time(start=None, descr=None): t = manager.last = time.time() if start is not None and descr is not None: manager.times.append((descr, float(start), float(t))) return t - (start or 0) class Timer(object): class TimeoutError(Exception): pass # TimeoutError is not handled in Python 2 def __init__(self, description=None, message=TO_MSG, timeout=None, fail_on_timeout=False): self.fail = fail_on_timeout self.id = len(manager.times) self.descr = "#" + str(self.id) + \ (": " + (description or "")).rstrip(": ") self.message = message self.start = _take_time() self.timeout = timeout def __enter__(self): if manager.enabled: if self.timeout is not None: signal.signal(signal.SIGALRM, self._handler) signal.alarm(self.timeout) if manager._timings and self.descr: l.time(self.descr) return self def __exit__(self, exc_type, exc_value, exc_traceback): if manager.enabled: d = _take_time(self.start, self.descr) if manager._timings: l.time("> Time elapsed: {} seconds".format(d)) if self.timeout is not None: if self.fail and exc_type is Timer.TimeoutError: return True def _handler(self, signum, frame): raise Timer.TimeoutError(self.message) glob['Timer'] = Timer def get_time(message=None, start=manager.start): if manager._timings: l.time("> {}: {} seconds".format(message or "Time elapsed since " "execution start", _take_time(start))) glob['get_time'] = get_time def get_time_since_last(message=None): get_time(message or "Time elapsed since last measure", manager.last) glob['get_time_since_last'] = get_time_since_last
[ "def", "set_time_items", "(", "glob", ")", ":", "a", "=", "glob", "[", "'args'", "]", "l", "=", "glob", "[", "'logger'", "]", "class", "__TimeManager", "(", "object", ")", ":", "def", "__init__", "(", "self", ")", ":", "c", "=", "a", ".", "_collisi...
This function prepares the benchmark items for inclusion in main script's global scope. :param glob: main script's global scope dictionary reference
[ "This", "function", "prepares", "the", "benchmark", "items", "for", "inclusion", "in", "main", "script", "s", "global", "scope", ".", ":", "param", "glob", ":", "main", "script", "s", "global", "scope", "dictionary", "reference" ]
train
https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/timing.py#L17-L98
dhondta/tinyscript
tinyscript/step.py
set_step_items
def set_step_items(glob): """ This function prepares the stepping items for inclusion in main script's global scope. :param glob: main script's global scope dictionary reference """ a = glob['args'] l = glob['logger'] enabled = getattr(a, a._collisions.get("step") or "step", False) # Step context manager, for defining a block of code that can be paused at # its start and end class Step(object): def __init__(self, message=None, at_end=False): self.message = message self.at_end = at_end def __enter__(self): if enabled: if self.message: l.step(self.message) if not self.at_end: std_input("Press enter to continue", {'color': STEP_COLOR, 'bold': True}) return self def __exit__(self, *args): if enabled and self.at_end: std_input("Press enter to continue", {'color': STEP_COLOR, 'bold': True}) glob['Step'] = Step # stepping function, for stopping the execution and displaying a message if # any defined def step(message=None): if enabled: if message: l.step(message) std_input("Press enter to continue", {'color': STEP_COLOR, 'bold': True}) glob['step'] = step
python
def set_step_items(glob): """ This function prepares the stepping items for inclusion in main script's global scope. :param glob: main script's global scope dictionary reference """ a = glob['args'] l = glob['logger'] enabled = getattr(a, a._collisions.get("step") or "step", False) # Step context manager, for defining a block of code that can be paused at # its start and end class Step(object): def __init__(self, message=None, at_end=False): self.message = message self.at_end = at_end def __enter__(self): if enabled: if self.message: l.step(self.message) if not self.at_end: std_input("Press enter to continue", {'color': STEP_COLOR, 'bold': True}) return self def __exit__(self, *args): if enabled and self.at_end: std_input("Press enter to continue", {'color': STEP_COLOR, 'bold': True}) glob['Step'] = Step # stepping function, for stopping the execution and displaying a message if # any defined def step(message=None): if enabled: if message: l.step(message) std_input("Press enter to continue", {'color': STEP_COLOR, 'bold': True}) glob['step'] = step
[ "def", "set_step_items", "(", "glob", ")", ":", "a", "=", "glob", "[", "'args'", "]", "l", "=", "glob", "[", "'logger'", "]", "enabled", "=", "getattr", "(", "a", ",", "a", ".", "_collisions", ".", "get", "(", "\"step\"", ")", "or", "\"step\"", ","...
This function prepares the stepping items for inclusion in main script's global scope. :param glob: main script's global scope dictionary reference
[ "This", "function", "prepares", "the", "stepping", "items", "for", "inclusion", "in", "main", "script", "s", "global", "scope", ".", ":", "param", "glob", ":", "main", "script", "s", "global", "scope", "dictionary", "reference" ]
train
https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/step.py#L13-L52
toumorokoshi/transmute-core
transmute_core/swagger/template.py
_capture_variable
def _capture_variable(iterator, parameters): """ return the replacement string. this assumes the preceeding {{ has already been popped off. """ key = "" next_c = next(iterator) while next_c != "}": key += next_c next_c = next(iterator) # remove the final "}" next(iterator) return parameters[key]
python
def _capture_variable(iterator, parameters): """ return the replacement string. this assumes the preceeding {{ has already been popped off. """ key = "" next_c = next(iterator) while next_c != "}": key += next_c next_c = next(iterator) # remove the final "}" next(iterator) return parameters[key]
[ "def", "_capture_variable", "(", "iterator", ",", "parameters", ")", ":", "key", "=", "\"\"", "next_c", "=", "next", "(", "iterator", ")", "while", "next_c", "!=", "\"}\"", ":", "key", "+=", "next_c", "next_c", "=", "next", "(", "iterator", ")", "# remov...
return the replacement string. this assumes the preceeding {{ has already been popped off.
[ "return", "the", "replacement", "string", ".", "this", "assumes", "the", "preceeding", "{{", "has", "already", "been", "popped", "off", "." ]
train
https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/swagger/template.py#L30-L43
tehmaze/ansi
ansi/colour/rgb.py
rgb_distance
def rgb_distance(rgb1, rgb2): ''' Calculate the distance between two RGB sequences. ''' return sum(map(lambda c: (c[0] - c[1]) ** 2, zip(rgb1, rgb2)))
python
def rgb_distance(rgb1, rgb2): ''' Calculate the distance between two RGB sequences. ''' return sum(map(lambda c: (c[0] - c[1]) ** 2, zip(rgb1, rgb2)))
[ "def", "rgb_distance", "(", "rgb1", ",", "rgb2", ")", ":", "return", "sum", "(", "map", "(", "lambda", "c", ":", "(", "c", "[", "0", "]", "-", "c", "[", "1", "]", ")", "**", "2", ",", "zip", "(", "rgb1", ",", "rgb2", ")", ")", ")" ]
Calculate the distance between two RGB sequences.
[ "Calculate", "the", "distance", "between", "two", "RGB", "sequences", "." ]
train
https://github.com/tehmaze/ansi/blob/7d3d23bcbb5ae02b614111d94c2b4798c064073e/ansi/colour/rgb.py#L15-L20
tehmaze/ansi
ansi/colour/rgb.py
rgb_reduce
def rgb_reduce(r, g, b, mode=8): ''' Convert an RGB colour to 8 or 16 colour ANSI graphics. ''' colours = ANSI_COLOURS[:mode] matches = [(rgb_distance(c, map(int, [r, g, b])), i) for i, c in enumerate(colours)] matches.sort() return sequence('m')(str(30 + matches[0][1]))
python
def rgb_reduce(r, g, b, mode=8): ''' Convert an RGB colour to 8 or 16 colour ANSI graphics. ''' colours = ANSI_COLOURS[:mode] matches = [(rgb_distance(c, map(int, [r, g, b])), i) for i, c in enumerate(colours)] matches.sort() return sequence('m')(str(30 + matches[0][1]))
[ "def", "rgb_reduce", "(", "r", ",", "g", ",", "b", ",", "mode", "=", "8", ")", ":", "colours", "=", "ANSI_COLOURS", "[", ":", "mode", "]", "matches", "=", "[", "(", "rgb_distance", "(", "c", ",", "map", "(", "int", ",", "[", "r", ",", "g", ",...
Convert an RGB colour to 8 or 16 colour ANSI graphics.
[ "Convert", "an", "RGB", "colour", "to", "8", "or", "16", "colour", "ANSI", "graphics", "." ]
train
https://github.com/tehmaze/ansi/blob/7d3d23bcbb5ae02b614111d94c2b4798c064073e/ansi/colour/rgb.py#L22-L30
tehmaze/ansi
ansi/colour/rgb.py
rgb256
def rgb256(r, g, b): ''' Convert an RGB colour to 256 colour ANSI graphics. ''' grey = False poss = True step = 2.5 while poss: # As long as the colour could be grey scale if r < step or g < step or b < step: grey = r < step and g < step and b < step poss = False step += 42.5 if grey: colour = 232 + int(float(sum([r, g, b]) / 33.0)) else: colour = sum([16] + [int (6 * float(val) / 256) * mod for val, mod in ((r, 36), (g, 6), (b, 1))]) return sequence('m', fields=3)(38, 5, colour)
python
def rgb256(r, g, b): ''' Convert an RGB colour to 256 colour ANSI graphics. ''' grey = False poss = True step = 2.5 while poss: # As long as the colour could be grey scale if r < step or g < step or b < step: grey = r < step and g < step and b < step poss = False step += 42.5 if grey: colour = 232 + int(float(sum([r, g, b]) / 33.0)) else: colour = sum([16] + [int (6 * float(val) / 256) * mod for val, mod in ((r, 36), (g, 6), (b, 1))]) return sequence('m', fields=3)(38, 5, colour)
[ "def", "rgb256", "(", "r", ",", "g", ",", "b", ")", ":", "grey", "=", "False", "poss", "=", "True", "step", "=", "2.5", "while", "poss", ":", "# As long as the colour could be grey scale", "if", "r", "<", "step", "or", "g", "<", "step", "or", "b", "<...
Convert an RGB colour to 256 colour ANSI graphics.
[ "Convert", "an", "RGB", "colour", "to", "256", "colour", "ANSI", "graphics", "." ]
train
https://github.com/tehmaze/ansi/blob/7d3d23bcbb5ae02b614111d94c2b4798c064073e/ansi/colour/rgb.py#L44-L65
inveniosoftware/invenio-previewer
invenio_previewer/api.py
PreviewFile.uri
def uri(self): """Get file download link. .. note:: The URI generation assumes that you can download the file using the view ``invenio_records_ui.<pid_type>_files``. """ return url_for( '.{0}_files'.format(self.pid.pid_type), pid_value=self.pid.pid_value, filename=self.file.key)
python
def uri(self): """Get file download link. .. note:: The URI generation assumes that you can download the file using the view ``invenio_records_ui.<pid_type>_files``. """ return url_for( '.{0}_files'.format(self.pid.pid_type), pid_value=self.pid.pid_value, filename=self.file.key)
[ "def", "uri", "(", "self", ")", ":", "return", "url_for", "(", "'.{0}_files'", ".", "format", "(", "self", ".", "pid", ".", "pid_type", ")", ",", "pid_value", "=", "self", ".", "pid", ".", "pid_value", ",", "filename", "=", "self", ".", "file", ".", ...
Get file download link. .. note:: The URI generation assumes that you can download the file using the view ``invenio_records_ui.<pid_type>_files``.
[ "Get", "file", "download", "link", "." ]
train
https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/api.py#L46-L57
inveniosoftware/invenio-previewer
invenio_previewer/api.py
PreviewFile.has_extensions
def has_extensions(self, *exts): """Check if file has one of the extensions.""" file_ext = splitext(self.filename)[1] file_ext = file_ext.lower() for e in exts: if file_ext == e: return True return False
python
def has_extensions(self, *exts): """Check if file has one of the extensions.""" file_ext = splitext(self.filename)[1] file_ext = file_ext.lower() for e in exts: if file_ext == e: return True return False
[ "def", "has_extensions", "(", "self", ",", "*", "exts", ")", ":", "file_ext", "=", "splitext", "(", "self", ".", "filename", ")", "[", "1", "]", "file_ext", "=", "file_ext", ".", "lower", "(", ")", "for", "e", "in", "exts", ":", "if", "file_ext", "...
Check if file has one of the extensions.
[ "Check", "if", "file", "has", "one", "of", "the", "extensions", "." ]
train
https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/api.py#L63-L71
inveniosoftware/invenio-previewer
invenio_previewer/extensions/json_prismjs.py
render
def render(file): """Pretty print the JSON file for rendering.""" with file.open() as fp: encoding = detect_encoding(fp, default='utf-8') file_content = fp.read().decode(encoding) json_data = json.loads(file_content, object_pairs_hook=OrderedDict) return json.dumps(json_data, indent=4, separators=(',', ': '))
python
def render(file): """Pretty print the JSON file for rendering.""" with file.open() as fp: encoding = detect_encoding(fp, default='utf-8') file_content = fp.read().decode(encoding) json_data = json.loads(file_content, object_pairs_hook=OrderedDict) return json.dumps(json_data, indent=4, separators=(',', ': '))
[ "def", "render", "(", "file", ")", ":", "with", "file", ".", "open", "(", ")", "as", "fp", ":", "encoding", "=", "detect_encoding", "(", "fp", ",", "default", "=", "'utf-8'", ")", "file_content", "=", "fp", ".", "read", "(", ")", ".", "decode", "("...
Pretty print the JSON file for rendering.
[ "Pretty", "print", "the", "JSON", "file", "for", "rendering", "." ]
train
https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/extensions/json_prismjs.py#L23-L29
inveniosoftware/invenio-previewer
invenio_previewer/extensions/json_prismjs.py
validate_json
def validate_json(file): """Validate a JSON file.""" max_file_size = current_app.config.get( 'PREVIEWER_MAX_FILE_SIZE_BYTES', 1 * 1024 * 1024) if file.size > max_file_size: return False with file.open() as fp: try: json.loads(fp.read().decode('utf-8')) return True except: return False
python
def validate_json(file): """Validate a JSON file.""" max_file_size = current_app.config.get( 'PREVIEWER_MAX_FILE_SIZE_BYTES', 1 * 1024 * 1024) if file.size > max_file_size: return False with file.open() as fp: try: json.loads(fp.read().decode('utf-8')) return True except: return False
[ "def", "validate_json", "(", "file", ")", ":", "max_file_size", "=", "current_app", ".", "config", ".", "get", "(", "'PREVIEWER_MAX_FILE_SIZE_BYTES'", ",", "1", "*", "1024", "*", "1024", ")", "if", "file", ".", "size", ">", "max_file_size", ":", "return", ...
Validate a JSON file.
[ "Validate", "a", "JSON", "file", "." ]
train
https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/extensions/json_prismjs.py#L32-L44
LCAV/pylocus
pylocus/edm_completion.py
optspace
def optspace(edm_missing, rank, niter=500, tol=1e-6, print_out=False): """Complete and denoise EDM using OptSpace algorithm. Uses OptSpace algorithm to complete and denoise EDM. The problem being solved is X,S,Y = argmin_(X,S,Y) || W ° (D - XSY') ||_F^2 :param edm_missing: EDM with 0 where no measurement was taken. :param rank: expected rank of complete EDM. :param niter, tol: see opt_space module for description. :return: Completed matrix. """ from .opt_space import opt_space N = edm_missing.shape[0] X, S, Y, __ = opt_space(edm_missing, r=rank, niter=niter, tol=tol, print_out=print_out) edm_complete = X.dot(S.dot(Y.T)) edm_complete[range(N), range(N)] = 0.0 return edm_complete
python
def optspace(edm_missing, rank, niter=500, tol=1e-6, print_out=False): """Complete and denoise EDM using OptSpace algorithm. Uses OptSpace algorithm to complete and denoise EDM. The problem being solved is X,S,Y = argmin_(X,S,Y) || W ° (D - XSY') ||_F^2 :param edm_missing: EDM with 0 where no measurement was taken. :param rank: expected rank of complete EDM. :param niter, tol: see opt_space module for description. :return: Completed matrix. """ from .opt_space import opt_space N = edm_missing.shape[0] X, S, Y, __ = opt_space(edm_missing, r=rank, niter=niter, tol=tol, print_out=print_out) edm_complete = X.dot(S.dot(Y.T)) edm_complete[range(N), range(N)] = 0.0 return edm_complete
[ "def", "optspace", "(", "edm_missing", ",", "rank", ",", "niter", "=", "500", ",", "tol", "=", "1e-6", ",", "print_out", "=", "False", ")", ":", "from", ".", "opt_space", "import", "opt_space", "N", "=", "edm_missing", ".", "shape", "[", "0", "]", "X...
Complete and denoise EDM using OptSpace algorithm. Uses OptSpace algorithm to complete and denoise EDM. The problem being solved is X,S,Y = argmin_(X,S,Y) || W ° (D - XSY') ||_F^2 :param edm_missing: EDM with 0 where no measurement was taken. :param rank: expected rank of complete EDM. :param niter, tol: see opt_space module for description. :return: Completed matrix.
[ "Complete", "and", "denoise", "EDM", "using", "OptSpace", "algorithm", "." ]
train
https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/edm_completion.py#L9-L27
LCAV/pylocus
pylocus/edm_completion.py
rank_alternation
def rank_alternation(edm_missing, rank, niter=50, print_out=False, edm_true=None): """Complete and denoise EDM using rank alternation. Iteratively impose rank and strucutre to complete marix entries :param edm_missing: EDM with 0 where no measurement was taken. :param rank: expected rank of complete EDM. :param niter: maximum number of iterations. :param edm: if given, the relative EDM error is tracked. :return: Completed matrix and array of errors (empty if no true edm is given). The matrix is of the correct structure, but might not have the right measured entries. """ from pylocus.basics import low_rank_approximation errs = [] N = edm_missing.shape[0] edm_complete = edm_missing.copy() edm_complete[edm_complete == 0] = np.mean(edm_complete[edm_complete > 0]) for i in range(niter): # impose matrix rank edm_complete = low_rank_approximation(edm_complete, rank) # impose known entries edm_complete[edm_missing > 0] = edm_missing[edm_missing > 0] # impose matrix structure edm_complete[range(N), range(N)] = 0.0 edm_complete[edm_complete < 0] = 0.0 edm_complete = 0.5 * (edm_complete + edm_complete.T) if edm_true is not None: err = np.linalg.norm(edm_complete - edm_true) errs.append(err) return edm_complete, errs
python
def rank_alternation(edm_missing, rank, niter=50, print_out=False, edm_true=None): """Complete and denoise EDM using rank alternation. Iteratively impose rank and strucutre to complete marix entries :param edm_missing: EDM with 0 where no measurement was taken. :param rank: expected rank of complete EDM. :param niter: maximum number of iterations. :param edm: if given, the relative EDM error is tracked. :return: Completed matrix and array of errors (empty if no true edm is given). The matrix is of the correct structure, but might not have the right measured entries. """ from pylocus.basics import low_rank_approximation errs = [] N = edm_missing.shape[0] edm_complete = edm_missing.copy() edm_complete[edm_complete == 0] = np.mean(edm_complete[edm_complete > 0]) for i in range(niter): # impose matrix rank edm_complete = low_rank_approximation(edm_complete, rank) # impose known entries edm_complete[edm_missing > 0] = edm_missing[edm_missing > 0] # impose matrix structure edm_complete[range(N), range(N)] = 0.0 edm_complete[edm_complete < 0] = 0.0 edm_complete = 0.5 * (edm_complete + edm_complete.T) if edm_true is not None: err = np.linalg.norm(edm_complete - edm_true) errs.append(err) return edm_complete, errs
[ "def", "rank_alternation", "(", "edm_missing", ",", "rank", ",", "niter", "=", "50", ",", "print_out", "=", "False", ",", "edm_true", "=", "None", ")", ":", "from", "pylocus", ".", "basics", "import", "low_rank_approximation", "errs", "=", "[", "]", "N", ...
Complete and denoise EDM using rank alternation. Iteratively impose rank and strucutre to complete marix entries :param edm_missing: EDM with 0 where no measurement was taken. :param rank: expected rank of complete EDM. :param niter: maximum number of iterations. :param edm: if given, the relative EDM error is tracked. :return: Completed matrix and array of errors (empty if no true edm is given). The matrix is of the correct structure, but might not have the right measured entries.
[ "Complete", "and", "denoise", "EDM", "using", "rank", "alternation", "." ]
train
https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/edm_completion.py#L30-L64
LCAV/pylocus
pylocus/edm_completion.py
semidefinite_relaxation
def semidefinite_relaxation(edm_missing, lamda, W=None, print_out=False, **kwargs): """Complete and denoise EDM using semidefinite relaxation. Returns solution to the relaxation of the following problem: D = argmin || W * (D - edm_missing) || s.t. D is EDM where edm_missing is measured matrix, W is a weight matrix, and * is pointwise multiplication. Refer to paper "Euclidean Distance Matrices - Essential Theory, Algorithms and Applications", Algorithm 5, for details. (https://www.doi.org/%2010.1109/MSP.2015.2398954) :param edm_missing: EDM with 0 where no measurement was taken. :param lamda: Regularization parameter. :param W: Optional mask. If no mask is given, a binary mask is created based on missing elements of edm_missing. If mask is given :param kwargs: more options passed to the solver. See cvxpy documentation for all options. """ from .algorithms import reconstruct_mds def kappa(gram): n = len(gram) e = np.ones(n) return np.outer(np.diag(gram), e) + np.outer(e, np.diag(gram).T) - 2 * gram def kappa_cvx(gram, n): e = np.ones((n, 1)) return reshape(diag(gram), (n, 1)) * e.T + e * reshape(diag(gram), (1, n)) - 2 * gram method = kwargs.pop('method', 'maximize') options = {'solver': 'CVXOPT'} options.update(kwargs) if W is None: W = (edm_missing > 0) else: W[edm_missing == 0] = 0.0 n = edm_missing.shape[0] V = np.c_[-np.ones((n - 1, 1)) / np.sqrt(n), np.eye(n - 1) - np.ones((n - 1, n - 1)) / (n + np.sqrt(n))].T H = Variable((n - 1, n - 1), PSD=True) G = V * H * V.T # * is overloaded edm_optimize = kappa_cvx(G, n) if method == 'maximize': obj = Maximize(trace(H) - lamda * norm(multiply(W, (edm_optimize - edm_missing)), p=1)) # TODO: add a reference to paper where "minimize" is used instead of maximize. elif method == 'minimize': obj = Minimize(trace(H) + lamda * norm(multiply(W, (edm_optimize - edm_missing)), p=1)) prob = Problem(obj) total = prob.solve(**options) if print_out: print('total cost:', total) print('SDP status:', prob.status) if H.value is not None: Gbest = V.dot(H.value).dot(V.T) if print_out: print('eigenvalues:', np.sum(np.linalg.eigvals(Gbest)[2:])) edm_complete = kappa(Gbest) else: edm_complete = edm_missing if (print_out): if H.value is not None: print('trace of H:', np.trace(H.value)) print('other cost:', lamda * norm(multiply(W, (edm_complete - edm_missing)), p=1).value) return np.array(edm_complete)
python
def semidefinite_relaxation(edm_missing, lamda, W=None, print_out=False, **kwargs): """Complete and denoise EDM using semidefinite relaxation. Returns solution to the relaxation of the following problem: D = argmin || W * (D - edm_missing) || s.t. D is EDM where edm_missing is measured matrix, W is a weight matrix, and * is pointwise multiplication. Refer to paper "Euclidean Distance Matrices - Essential Theory, Algorithms and Applications", Algorithm 5, for details. (https://www.doi.org/%2010.1109/MSP.2015.2398954) :param edm_missing: EDM with 0 where no measurement was taken. :param lamda: Regularization parameter. :param W: Optional mask. If no mask is given, a binary mask is created based on missing elements of edm_missing. If mask is given :param kwargs: more options passed to the solver. See cvxpy documentation for all options. """ from .algorithms import reconstruct_mds def kappa(gram): n = len(gram) e = np.ones(n) return np.outer(np.diag(gram), e) + np.outer(e, np.diag(gram).T) - 2 * gram def kappa_cvx(gram, n): e = np.ones((n, 1)) return reshape(diag(gram), (n, 1)) * e.T + e * reshape(diag(gram), (1, n)) - 2 * gram method = kwargs.pop('method', 'maximize') options = {'solver': 'CVXOPT'} options.update(kwargs) if W is None: W = (edm_missing > 0) else: W[edm_missing == 0] = 0.0 n = edm_missing.shape[0] V = np.c_[-np.ones((n - 1, 1)) / np.sqrt(n), np.eye(n - 1) - np.ones((n - 1, n - 1)) / (n + np.sqrt(n))].T H = Variable((n - 1, n - 1), PSD=True) G = V * H * V.T # * is overloaded edm_optimize = kappa_cvx(G, n) if method == 'maximize': obj = Maximize(trace(H) - lamda * norm(multiply(W, (edm_optimize - edm_missing)), p=1)) # TODO: add a reference to paper where "minimize" is used instead of maximize. elif method == 'minimize': obj = Minimize(trace(H) + lamda * norm(multiply(W, (edm_optimize - edm_missing)), p=1)) prob = Problem(obj) total = prob.solve(**options) if print_out: print('total cost:', total) print('SDP status:', prob.status) if H.value is not None: Gbest = V.dot(H.value).dot(V.T) if print_out: print('eigenvalues:', np.sum(np.linalg.eigvals(Gbest)[2:])) edm_complete = kappa(Gbest) else: edm_complete = edm_missing if (print_out): if H.value is not None: print('trace of H:', np.trace(H.value)) print('other cost:', lamda * norm(multiply(W, (edm_complete - edm_missing)), p=1).value) return np.array(edm_complete)
[ "def", "semidefinite_relaxation", "(", "edm_missing", ",", "lamda", ",", "W", "=", "None", ",", "print_out", "=", "False", ",", "*", "*", "kwargs", ")", ":", "from", ".", "algorithms", "import", "reconstruct_mds", "def", "kappa", "(", "gram", ")", ":", "...
Complete and denoise EDM using semidefinite relaxation. Returns solution to the relaxation of the following problem: D = argmin || W * (D - edm_missing) || s.t. D is EDM where edm_missing is measured matrix, W is a weight matrix, and * is pointwise multiplication. Refer to paper "Euclidean Distance Matrices - Essential Theory, Algorithms and Applications", Algorithm 5, for details. (https://www.doi.org/%2010.1109/MSP.2015.2398954) :param edm_missing: EDM with 0 where no measurement was taken. :param lamda: Regularization parameter. :param W: Optional mask. If no mask is given, a binary mask is created based on missing elements of edm_missing. If mask is given :param kwargs: more options passed to the solver. See cvxpy documentation for all options.
[ "Complete", "and", "denoise", "EDM", "using", "semidefinite", "relaxation", "." ]
train
https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/edm_completion.py#L67-L141
LCAV/pylocus
pylocus/edm_completion.py
completion_acd
def completion_acd(edm, X0, W=None, tol=1e-6, sweeps=3): """ Complete an denoise EDM using alternating decent. The idea here is to simply run reconstruct_acd for a few iterations, yieding a position estimate, which can in turn be used to get a completed and denoised edm. :param edm: noisy matrix (NxN) :param X0: starting points (Nxd) :param W: optional weight matrix. :param tol: Stopping criterion of iterative algorithm. :param sweeps: Maximum number of sweeps. """ from .algorithms import reconstruct_acd Xhat, costs = reconstruct_acd(edm, X0, W, tol=tol, sweeps=sweeps) return get_edm(Xhat)
python
def completion_acd(edm, X0, W=None, tol=1e-6, sweeps=3): """ Complete an denoise EDM using alternating decent. The idea here is to simply run reconstruct_acd for a few iterations, yieding a position estimate, which can in turn be used to get a completed and denoised edm. :param edm: noisy matrix (NxN) :param X0: starting points (Nxd) :param W: optional weight matrix. :param tol: Stopping criterion of iterative algorithm. :param sweeps: Maximum number of sweeps. """ from .algorithms import reconstruct_acd Xhat, costs = reconstruct_acd(edm, X0, W, tol=tol, sweeps=sweeps) return get_edm(Xhat)
[ "def", "completion_acd", "(", "edm", ",", "X0", ",", "W", "=", "None", ",", "tol", "=", "1e-6", ",", "sweeps", "=", "3", ")", ":", "from", ".", "algorithms", "import", "reconstruct_acd", "Xhat", ",", "costs", "=", "reconstruct_acd", "(", "edm", ",", ...
Complete an denoise EDM using alternating decent. The idea here is to simply run reconstruct_acd for a few iterations, yieding a position estimate, which can in turn be used to get a completed and denoised edm. :param edm: noisy matrix (NxN) :param X0: starting points (Nxd) :param W: optional weight matrix. :param tol: Stopping criterion of iterative algorithm. :param sweeps: Maximum number of sweeps.
[ "Complete", "an", "denoise", "EDM", "using", "alternating", "decent", "." ]
train
https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/edm_completion.py#L144-L159
LCAV/pylocus
pylocus/edm_completion.py
completion_dwmds
def completion_dwmds(edm, X0, W=None, tol=1e-10, sweeps=100): """ Complete an denoise EDM using dwMDS. The idea here is to simply run reconstruct_dwmds for a few iterations, yieding a position estimate, which can in turn be used to get a completed and denoised edm. :param edm: noisy matrix (NxN) :param X0: starting points (Nxd) :param W: optional weight matrix. :param tol: Stopping criterion of iterative algorithm. :param sweeps: Maximum number of sweeps. """ from .algorithms import reconstruct_dwmds Xhat, costs = reconstruct_dwmds(edm, X0, W, n=1, tol=tol, sweeps=sweeps) return get_edm(Xhat)
python
def completion_dwmds(edm, X0, W=None, tol=1e-10, sweeps=100): """ Complete an denoise EDM using dwMDS. The idea here is to simply run reconstruct_dwmds for a few iterations, yieding a position estimate, which can in turn be used to get a completed and denoised edm. :param edm: noisy matrix (NxN) :param X0: starting points (Nxd) :param W: optional weight matrix. :param tol: Stopping criterion of iterative algorithm. :param sweeps: Maximum number of sweeps. """ from .algorithms import reconstruct_dwmds Xhat, costs = reconstruct_dwmds(edm, X0, W, n=1, tol=tol, sweeps=sweeps) return get_edm(Xhat)
[ "def", "completion_dwmds", "(", "edm", ",", "X0", ",", "W", "=", "None", ",", "tol", "=", "1e-10", ",", "sweeps", "=", "100", ")", ":", "from", ".", "algorithms", "import", "reconstruct_dwmds", "Xhat", ",", "costs", "=", "reconstruct_dwmds", "(", "edm", ...
Complete an denoise EDM using dwMDS. The idea here is to simply run reconstruct_dwmds for a few iterations, yieding a position estimate, which can in turn be used to get a completed and denoised edm. :param edm: noisy matrix (NxN) :param X0: starting points (Nxd) :param W: optional weight matrix. :param tol: Stopping criterion of iterative algorithm. :param sweeps: Maximum number of sweeps.
[ "Complete", "an", "denoise", "EDM", "using", "dwMDS", "." ]
train
https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/edm_completion.py#L162-L177
toumorokoshi/transmute-core
transmute_core/frameworks/tornado/url.py
url_spec
def url_spec(transmute_path, handler, *args, **kwargs): """ convert the transmute_path to a tornado compatible regex, and return a tornado url object. """ p = _to_tornado_pattern(transmute_path) for m in METHODS: method = getattr(handler, m) if hasattr(method, "transmute_func"): method.transmute_func.paths.add(transmute_path) return tornado.web.URLSpec( p, handler, *args, **kwargs )
python
def url_spec(transmute_path, handler, *args, **kwargs): """ convert the transmute_path to a tornado compatible regex, and return a tornado url object. """ p = _to_tornado_pattern(transmute_path) for m in METHODS: method = getattr(handler, m) if hasattr(method, "transmute_func"): method.transmute_func.paths.add(transmute_path) return tornado.web.URLSpec( p, handler, *args, **kwargs )
[ "def", "url_spec", "(", "transmute_path", ",", "handler", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "p", "=", "_to_tornado_pattern", "(", "transmute_path", ")", "for", "m", "in", "METHODS", ":", "method", "=", "getattr", "(", "handler", ",", ...
convert the transmute_path to a tornado compatible regex, and return a tornado url object.
[ "convert", "the", "transmute_path", "to", "a", "tornado", "compatible", "regex", "and", "return", "a", "tornado", "url", "object", "." ]
train
https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/frameworks/tornado/url.py#L6-L20
LCAV/pylocus
pylocus/point_set.py
PointSet.set_points
def set_points(self, mode='', points=None, range_=RANGE, size=1): """ Initialize points according to predefined modes. :param range_:[xmin, xmax, ymin, ymax], range of point sets """ if mode == 'last': if points is None: print('Error: empty last point specification given.') return tol = 0.1 [i, j, k] = points alpha = 2.0 * np.random.rand(1) + 0.5 beta = 2.0 * np.random.rand(1) + 0.5 if i >= 0 and j < 0 and k < 0: # at one corner of triangle assert i < 3 other = np.delete(np.arange(3), i) u = (self.points[i, :] - self.points[other[0], :] ) / np.linalg.norm( self.points[i, :] - self.points[other[0], :]) v = (self.points[i, :] - self.points[other[1], :] ) / np.linalg.norm( self.points[i, :] - self.points[other[1], :]) self.points[-1, :] = self.points[i, :] + alpha * u + beta * v elif i >= 0 and j >= 0 and k < 0: found = False safety_it = 0 while not found: alpha = np.random.uniform(tol, 1 - tol) beta = 1.0 - alpha gamma = 2 * np.random.rand(1) + tol assert j < 3 other = np.delete(np.arange(3), (i, j)) u = ( self.points[i, :] - self.points[other, :] ) # /np.linalg.norm(self.points[i,:] - self.points[other,:]) v = ( self.points[j, :] - self.points[other, :] ) # /np.linalg.norm(self.points[j,:] - self.points[other,:]) self.points[-1, :] = (1.0 + gamma) * ( self.points[other, :] + alpha * u + beta * v) #check if new direction lies between u and v. new_direction = self.points[-1, :] - self.points[other, :] new_direction = new_direction.reshape( (-1, )) / np.linalg.norm(new_direction) u = u.reshape((-1, )) / np.linalg.norm(u) v = v.reshape((-1, )) / np.linalg.norm(v) #print('{} + {} = {}'.format(acos(np.dot(new_direction,u)),acos(np.dot(new_direction,v)),acos(np.dot(u,v)))) if abs( acos(np.dot(new_direction, u)) + acos(np.dot(new_direction, v)) - acos(np.dot(u, v))) < 1e-10: found = True safety_it += 1 if safety_it > 100: print('Error: nothing found after 100 iterations.') return elif i >= 0 and j >= 0 and k >= 0: # inside triangle assert k < 3 found = False safety_it = 0 while not found: alpha = np.random.rand(1) + tol beta = np.random.rand(1) + tol other = np.delete(np.arange(3), i) u = self.points[other[0], :] - self.points[i, :] v = self.points[other[1], :] - self.points[i, :] temptative_point = self.points[i, :] + alpha * u + beta * v vjk = self.points[other[1], :] - self.points[other[0], :] njk = [vjk[1], -vjk[0]] if (np.dot(self.points[j, :] - self.points[i, :], njk) > 0) != (np.dot(temptative_point - self.points[j, :], njk) > 0): self.points[-1, :] = temptative_point found = True safety_it += 1 if safety_it > 100: print('Error: nothing found after 100 iterations.') return elif i < 0 and j < 0 and k < 0: x = range_[0] + ( range_[1] - range_[0]) * np.random.rand(1) y = range_[2] + ( range_[1] - range_[0]) * np.random.rand(1) self.points[-1, :] = [x, y] else: print("Error: non-valid arguments.") elif mode == 'random': """ Create N uniformly distributed points in [0, size] x [0, size] """ self.points = np.random.uniform(0, size, (self.N, self.d)) elif mode == 'normal': self.points = np.random.normal(0, size, (self.N, self.d)) elif mode == 'circle': from math import cos, sin x_range = size / 2.0 y_range = size / 2.0 c = np.array((x_range, y_range)) r = 0.9 * min(x_range, y_range) theta = 2 * pi / self.N for i in range(self.N): theta_tot = i * theta self.points[i, :] = c + np.array( (r * cos(theta_tot), r * sin(theta_tot))) elif mode == 'set': """ Place points according to hard coded rule. """ if self.N == 3: x = [-1.0, 1.0, 0.0] y = [-1.0, -1.0, 1.0] elif self.N == 4: x = [-1.0, 1.0, 0.0, 0.0] y = [-1.0, -1.0, 1.0, 0.0] elif self.N == 5: x = [-0.0, 1.5, 1.5, -0.0, -1.0] y = [-1.0, -1.0, 1.0, 1.0, 0.0] else: print("Error: No rule defined for N = ", self.N) return self.points = np.c_[x, y] elif mode == 'geogebra': if self.N == 4: self.points = np.array(((1.5, 1.8), (7.9, 2.5), (2.3, 5.1), (3.34, -1.36))) elif self.N == 5: self.points = np.array(((1.5, 1.8), (7.9, 2.5), (2.3, 5.1), (3.34, -1.36), (5, 1.4))) else: print("Error: No rule defined for N = ", self.N) elif mode == '': if points is None: raise NotImplementedError("Need to give either mode or points.") else: self.points = points self.N, self.d = points.shape self.init()
python
def set_points(self, mode='', points=None, range_=RANGE, size=1): """ Initialize points according to predefined modes. :param range_:[xmin, xmax, ymin, ymax], range of point sets """ if mode == 'last': if points is None: print('Error: empty last point specification given.') return tol = 0.1 [i, j, k] = points alpha = 2.0 * np.random.rand(1) + 0.5 beta = 2.0 * np.random.rand(1) + 0.5 if i >= 0 and j < 0 and k < 0: # at one corner of triangle assert i < 3 other = np.delete(np.arange(3), i) u = (self.points[i, :] - self.points[other[0], :] ) / np.linalg.norm( self.points[i, :] - self.points[other[0], :]) v = (self.points[i, :] - self.points[other[1], :] ) / np.linalg.norm( self.points[i, :] - self.points[other[1], :]) self.points[-1, :] = self.points[i, :] + alpha * u + beta * v elif i >= 0 and j >= 0 and k < 0: found = False safety_it = 0 while not found: alpha = np.random.uniform(tol, 1 - tol) beta = 1.0 - alpha gamma = 2 * np.random.rand(1) + tol assert j < 3 other = np.delete(np.arange(3), (i, j)) u = ( self.points[i, :] - self.points[other, :] ) # /np.linalg.norm(self.points[i,:] - self.points[other,:]) v = ( self.points[j, :] - self.points[other, :] ) # /np.linalg.norm(self.points[j,:] - self.points[other,:]) self.points[-1, :] = (1.0 + gamma) * ( self.points[other, :] + alpha * u + beta * v) #check if new direction lies between u and v. new_direction = self.points[-1, :] - self.points[other, :] new_direction = new_direction.reshape( (-1, )) / np.linalg.norm(new_direction) u = u.reshape((-1, )) / np.linalg.norm(u) v = v.reshape((-1, )) / np.linalg.norm(v) #print('{} + {} = {}'.format(acos(np.dot(new_direction,u)),acos(np.dot(new_direction,v)),acos(np.dot(u,v)))) if abs( acos(np.dot(new_direction, u)) + acos(np.dot(new_direction, v)) - acos(np.dot(u, v))) < 1e-10: found = True safety_it += 1 if safety_it > 100: print('Error: nothing found after 100 iterations.') return elif i >= 0 and j >= 0 and k >= 0: # inside triangle assert k < 3 found = False safety_it = 0 while not found: alpha = np.random.rand(1) + tol beta = np.random.rand(1) + tol other = np.delete(np.arange(3), i) u = self.points[other[0], :] - self.points[i, :] v = self.points[other[1], :] - self.points[i, :] temptative_point = self.points[i, :] + alpha * u + beta * v vjk = self.points[other[1], :] - self.points[other[0], :] njk = [vjk[1], -vjk[0]] if (np.dot(self.points[j, :] - self.points[i, :], njk) > 0) != (np.dot(temptative_point - self.points[j, :], njk) > 0): self.points[-1, :] = temptative_point found = True safety_it += 1 if safety_it > 100: print('Error: nothing found after 100 iterations.') return elif i < 0 and j < 0 and k < 0: x = range_[0] + ( range_[1] - range_[0]) * np.random.rand(1) y = range_[2] + ( range_[1] - range_[0]) * np.random.rand(1) self.points[-1, :] = [x, y] else: print("Error: non-valid arguments.") elif mode == 'random': """ Create N uniformly distributed points in [0, size] x [0, size] """ self.points = np.random.uniform(0, size, (self.N, self.d)) elif mode == 'normal': self.points = np.random.normal(0, size, (self.N, self.d)) elif mode == 'circle': from math import cos, sin x_range = size / 2.0 y_range = size / 2.0 c = np.array((x_range, y_range)) r = 0.9 * min(x_range, y_range) theta = 2 * pi / self.N for i in range(self.N): theta_tot = i * theta self.points[i, :] = c + np.array( (r * cos(theta_tot), r * sin(theta_tot))) elif mode == 'set': """ Place points according to hard coded rule. """ if self.N == 3: x = [-1.0, 1.0, 0.0] y = [-1.0, -1.0, 1.0] elif self.N == 4: x = [-1.0, 1.0, 0.0, 0.0] y = [-1.0, -1.0, 1.0, 0.0] elif self.N == 5: x = [-0.0, 1.5, 1.5, -0.0, -1.0] y = [-1.0, -1.0, 1.0, 1.0, 0.0] else: print("Error: No rule defined for N = ", self.N) return self.points = np.c_[x, y] elif mode == 'geogebra': if self.N == 4: self.points = np.array(((1.5, 1.8), (7.9, 2.5), (2.3, 5.1), (3.34, -1.36))) elif self.N == 5: self.points = np.array(((1.5, 1.8), (7.9, 2.5), (2.3, 5.1), (3.34, -1.36), (5, 1.4))) else: print("Error: No rule defined for N = ", self.N) elif mode == '': if points is None: raise NotImplementedError("Need to give either mode or points.") else: self.points = points self.N, self.d = points.shape self.init()
[ "def", "set_points", "(", "self", ",", "mode", "=", "''", ",", "points", "=", "None", ",", "range_", "=", "RANGE", ",", "size", "=", "1", ")", ":", "if", "mode", "==", "'last'", ":", "if", "points", "is", "None", ":", "print", "(", "'Error: empty l...
Initialize points according to predefined modes. :param range_:[xmin, xmax, ymin, ymax], range of point sets
[ "Initialize", "points", "according", "to", "predefined", "modes", "." ]
train
https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/point_set.py#L46-L184
LCAV/pylocus
pylocus/point_set.py
AngleSet.create_theta
def create_theta(self): """ Returns the set of inner angles (between 0 and pi) reconstructed from point coordinates. Also returns the corners corresponding to each entry of theta. """ import itertools from pylocus.basics_angles import from_0_to_pi theta = np.empty((self.M, )) corners = np.empty((self.M, 3)) k = 0 indices = np.arange(self.N) for triangle in itertools.combinations(indices, 3): for counter, idx in enumerate(triangle): corner = idx other = np.delete(triangle, counter) corners[k, :] = [corner, other[0], other[1]] theta[k] = self.get_inner_angle(corner, other) theta[k] = from_0_to_pi(theta[k]) if DEBUG: print(self.abs_angles[corner, other[0]], self.abs_angles[corner, other[1]]) print('theta', corners[k, :], theta[k]) k = k + 1 inner_angle_sum = theta[k - 1] + theta[k - 2] + theta[k - 3] assert abs(inner_angle_sum - pi) < 1e-10, \ 'inner angle sum: {} {} {}'.format( triangle, inner_angle_sum, (theta[k - 1], theta[k - 2], theta[k - 3])) self.theta = theta self.corners = corners return theta, corners
python
def create_theta(self): """ Returns the set of inner angles (between 0 and pi) reconstructed from point coordinates. Also returns the corners corresponding to each entry of theta. """ import itertools from pylocus.basics_angles import from_0_to_pi theta = np.empty((self.M, )) corners = np.empty((self.M, 3)) k = 0 indices = np.arange(self.N) for triangle in itertools.combinations(indices, 3): for counter, idx in enumerate(triangle): corner = idx other = np.delete(triangle, counter) corners[k, :] = [corner, other[0], other[1]] theta[k] = self.get_inner_angle(corner, other) theta[k] = from_0_to_pi(theta[k]) if DEBUG: print(self.abs_angles[corner, other[0]], self.abs_angles[corner, other[1]]) print('theta', corners[k, :], theta[k]) k = k + 1 inner_angle_sum = theta[k - 1] + theta[k - 2] + theta[k - 3] assert abs(inner_angle_sum - pi) < 1e-10, \ 'inner angle sum: {} {} {}'.format( triangle, inner_angle_sum, (theta[k - 1], theta[k - 2], theta[k - 3])) self.theta = theta self.corners = corners return theta, corners
[ "def", "create_theta", "(", "self", ")", ":", "import", "itertools", "from", "pylocus", ".", "basics_angles", "import", "from_0_to_pi", "theta", "=", "np", ".", "empty", "(", "(", "self", ".", "M", ",", ")", ")", "corners", "=", "np", ".", "empty", "("...
Returns the set of inner angles (between 0 and pi) reconstructed from point coordinates. Also returns the corners corresponding to each entry of theta.
[ "Returns", "the", "set", "of", "inner", "angles", "(", "between", "0", "and", "pi", ")", "reconstructed", "from", "point", "coordinates", ".", "Also", "returns", "the", "corners", "corresponding", "to", "each", "entry", "of", "theta", "." ]
train
https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/point_set.py#L264-L294
LCAV/pylocus
pylocus/point_set.py
AngleSet.get_orientation
def get_orientation(k, i, j): from pylocus.basics_angles import from_0_to_2pi """calculate angles theta_ik and theta_jk theta produce point Pk. Should give the same as get_absolute_angle! """ theta_ij = own.abs_angles[i, j] theta_ji = own.abs_angles[j, i] # complicated xi = own.points[i, 0] xj = own.points[j, 0] yi = own.points[i, 1] yj = own.points[j, 1] w = np.array([yi - yj, xj - xi]) test = np.dot(own.points[k, :] - own.points[i, :], w) > 0 # more elegant theta_ik = truth.abs_angles[i, k] diff = from_0_to_2pi(theta_ik - theta_ij) test2 = (diff > 0 and diff < pi) assert (test == test2), "diff: %r, scalar prodcut: %r" % (diff, np.dot( own.points[k, :] - own.points[i, :], w)) thetai_jk = truth.get_theta(i, j, k) thetaj_ik = truth.get_theta(j, i, k) if test: theta_ik = theta_ij + thetai_jk theta_jk = theta_ji - thetaj_ik else: theta_ik = theta_ij - thetai_jk theta_jk = theta_ji + thetaj_ik theta_ik = from_0_to_2pi(theta_ik) theta_jk = from_0_to_2pi(theta_jk) return theta_ik, theta_jk
python
def get_orientation(k, i, j): from pylocus.basics_angles import from_0_to_2pi """calculate angles theta_ik and theta_jk theta produce point Pk. Should give the same as get_absolute_angle! """ theta_ij = own.abs_angles[i, j] theta_ji = own.abs_angles[j, i] # complicated xi = own.points[i, 0] xj = own.points[j, 0] yi = own.points[i, 1] yj = own.points[j, 1] w = np.array([yi - yj, xj - xi]) test = np.dot(own.points[k, :] - own.points[i, :], w) > 0 # more elegant theta_ik = truth.abs_angles[i, k] diff = from_0_to_2pi(theta_ik - theta_ij) test2 = (diff > 0 and diff < pi) assert (test == test2), "diff: %r, scalar prodcut: %r" % (diff, np.dot( own.points[k, :] - own.points[i, :], w)) thetai_jk = truth.get_theta(i, j, k) thetaj_ik = truth.get_theta(j, i, k) if test: theta_ik = theta_ij + thetai_jk theta_jk = theta_ji - thetaj_ik else: theta_ik = theta_ij - thetai_jk theta_jk = theta_ji + thetaj_ik theta_ik = from_0_to_2pi(theta_ik) theta_jk = from_0_to_2pi(theta_jk) return theta_ik, theta_jk
[ "def", "get_orientation", "(", "k", ",", "i", ",", "j", ")", ":", "from", "pylocus", ".", "basics_angles", "import", "from_0_to_2pi", "theta_ij", "=", "own", ".", "abs_angles", "[", "i", ",", "j", "]", "theta_ji", "=", "own", ".", "abs_angles", "[", "j...
calculate angles theta_ik and theta_jk theta produce point Pk. Should give the same as get_absolute_angle!
[ "calculate", "angles", "theta_ik", "and", "theta_jk", "theta", "produce", "point", "Pk", ".", "Should", "give", "the", "same", "as", "get_absolute_angle!" ]
train
https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/point_set.py#L306-L338
LCAV/pylocus
pylocus/point_set.py
AngleSet.get_indices
def get_indices(self, k): """ Get indices of theta vector that have k as first corner. :param k: Index of corner. :return indices_rays: Indices of ray angles in theta vector. :return indices_triangles: Indices of triangle angles in theta vector. :return corners_rays: List of corners of ray angles. :return angles_rays: List of corners of triangles angles. """ indices_rays = [] indices_triangles = [] corners_rays = [] angles_rays = [] for t, triangle in enumerate(self.corners): if triangle[0] == k: indices_rays.append(t) corners_rays.append(triangle) angles_rays.append(self.theta[t]) else: indices_triangles.append(t) np_corners_rays = np.vstack(corners_rays) np_angles_rays = np.vstack(angles_rays).reshape((-1, )) return indices_rays, indices_triangles, np_corners_rays, np_angles_rays
python
def get_indices(self, k): """ Get indices of theta vector that have k as first corner. :param k: Index of corner. :return indices_rays: Indices of ray angles in theta vector. :return indices_triangles: Indices of triangle angles in theta vector. :return corners_rays: List of corners of ray angles. :return angles_rays: List of corners of triangles angles. """ indices_rays = [] indices_triangles = [] corners_rays = [] angles_rays = [] for t, triangle in enumerate(self.corners): if triangle[0] == k: indices_rays.append(t) corners_rays.append(triangle) angles_rays.append(self.theta[t]) else: indices_triangles.append(t) np_corners_rays = np.vstack(corners_rays) np_angles_rays = np.vstack(angles_rays).reshape((-1, )) return indices_rays, indices_triangles, np_corners_rays, np_angles_rays
[ "def", "get_indices", "(", "self", ",", "k", ")", ":", "indices_rays", "=", "[", "]", "indices_triangles", "=", "[", "]", "corners_rays", "=", "[", "]", "angles_rays", "=", "[", "]", "for", "t", ",", "triangle", "in", "enumerate", "(", "self", ".", "...
Get indices of theta vector that have k as first corner. :param k: Index of corner. :return indices_rays: Indices of ray angles in theta vector. :return indices_triangles: Indices of triangle angles in theta vector. :return corners_rays: List of corners of ray angles. :return angles_rays: List of corners of triangles angles.
[ "Get", "indices", "of", "theta", "vector", "that", "have", "k", "as", "first", "corner", ".", ":", "param", "k", ":", "Index", "of", "corner", "." ]
train
https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/point_set.py#L398-L421
LCAV/pylocus
pylocus/point_set.py
AngleSet.get_G
def get_G(self, k, add_noise=True): """ get G matrix from angles. """ G = np.ones((self.N - 1, self.N - 1)) if (add_noise): noise = pi * 0.1 * np.random.rand( (self.N - 1) * (self.N - 1)).reshape((self.N - 1, self.N - 1)) other_indices = np.delete(range(self.N), k) for idx, i in enumerate(other_indices): for jdx, j in enumerate(other_indices): if (add_noise and i != j): # do not add noise on diagonal elements. thetak_ij = self.get_inner_angle(k, (i, j)) + noise[idx, jdx] else: thetak_ij = self.get_inner_angle(k, (i, j)) G[idx, jdx] = cos(thetak_ij) G[jdx, idx] = cos(thetak_ij) return G
python
def get_G(self, k, add_noise=True): """ get G matrix from angles. """ G = np.ones((self.N - 1, self.N - 1)) if (add_noise): noise = pi * 0.1 * np.random.rand( (self.N - 1) * (self.N - 1)).reshape((self.N - 1, self.N - 1)) other_indices = np.delete(range(self.N), k) for idx, i in enumerate(other_indices): for jdx, j in enumerate(other_indices): if (add_noise and i != j): # do not add noise on diagonal elements. thetak_ij = self.get_inner_angle(k, (i, j)) + noise[idx, jdx] else: thetak_ij = self.get_inner_angle(k, (i, j)) G[idx, jdx] = cos(thetak_ij) G[jdx, idx] = cos(thetak_ij) return G
[ "def", "get_G", "(", "self", ",", "k", ",", "add_noise", "=", "True", ")", ":", "G", "=", "np", ".", "ones", "(", "(", "self", ".", "N", "-", "1", ",", "self", ".", "N", "-", "1", ")", ")", "if", "(", "add_noise", ")", ":", "noise", "=", ...
get G matrix from angles.
[ "get", "G", "matrix", "from", "angles", "." ]
train
https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/point_set.py#L423-L440
LCAV/pylocus
pylocus/point_set.py
AngleSet.get_convex_polygons
def get_convex_polygons(self, m, print_out=False): """ :param m: size of polygones (number of corners) :return: (ordered) indices of all convex polygones of size m. """ convex_polygons = [] for corners in itertools.combinations(np.arange(self.N), m): p = np.zeros(m, np.uint) p[0] = corners[0] left = corners[1:] # loop through second corners for i, second in enumerate(corners[1:m - 1]): p[1] = second left = np.delete(corners, (0, i + 1)) for j, last in enumerate(corners[i + 2:]): left = np.delete(corners, (0, i + 1, j + i + 2)) p[-1] = last # loop through all permutations of left corners. for permut in itertools.permutations(left): p[2:-1] = permut sum_theta = 0 # sum over all inner angles. for k in range(m): sum_theta += self.get_inner_angle( p[1], (p[0], p[2])) p = np.roll(p, 1) angle = sum_theta sum_angle = (m - 2) * pi if (abs(angle - sum_angle) < 1e-14 or abs(angle) < 1e-14): if (print_out): print("convex polygon found: ", p) convex_polygons.append(p.copy()) # elif (angle < sum_angle): # if (print_out): print("non convex polygon found:",p,angle) elif (angle > sum_angle): if (print_out): print("oops") return convex_polygons
python
def get_convex_polygons(self, m, print_out=False): """ :param m: size of polygones (number of corners) :return: (ordered) indices of all convex polygones of size m. """ convex_polygons = [] for corners in itertools.combinations(np.arange(self.N), m): p = np.zeros(m, np.uint) p[0] = corners[0] left = corners[1:] # loop through second corners for i, second in enumerate(corners[1:m - 1]): p[1] = second left = np.delete(corners, (0, i + 1)) for j, last in enumerate(corners[i + 2:]): left = np.delete(corners, (0, i + 1, j + i + 2)) p[-1] = last # loop through all permutations of left corners. for permut in itertools.permutations(left): p[2:-1] = permut sum_theta = 0 # sum over all inner angles. for k in range(m): sum_theta += self.get_inner_angle( p[1], (p[0], p[2])) p = np.roll(p, 1) angle = sum_theta sum_angle = (m - 2) * pi if (abs(angle - sum_angle) < 1e-14 or abs(angle) < 1e-14): if (print_out): print("convex polygon found: ", p) convex_polygons.append(p.copy()) # elif (angle < sum_angle): # if (print_out): print("non convex polygon found:",p,angle) elif (angle > sum_angle): if (print_out): print("oops") return convex_polygons
[ "def", "get_convex_polygons", "(", "self", ",", "m", ",", "print_out", "=", "False", ")", ":", "convex_polygons", "=", "[", "]", "for", "corners", "in", "itertools", ".", "combinations", "(", "np", ".", "arange", "(", "self", ".", "N", ")", ",", "m", ...
:param m: size of polygones (number of corners) :return: (ordered) indices of all convex polygones of size m.
[ ":", "param", "m", ":", "size", "of", "polygones", "(", "number", "of", "corners", ")", ":", "return", ":", "(", "ordered", ")", "indices", "of", "all", "convex", "polygones", "of", "size", "m", "." ]
train
https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/point_set.py#L467-L506
LCAV/pylocus
pylocus/point_set.py
AngleSet.get_polygon_constraints
def get_polygon_constraints(self, range_polygones=range(3, 5), print_out=False): """ :param range_polygones: list of numbers of polygones to test. :return A, b: the constraints on the theta-vector of the form A*theta = b """ rows_A = [] rows_b = [] for m in range_polygones: if (print_out): print('checking {}-polygones'.format(m)) polygons = self.get_convex_polygons(m) row_A, row_b = self.get_polygon_constraints_m(polygons, print_out) rows_A.append(row_A) rows_b.append(row_b) self.A = np.vstack(rows_A) self.b = np.hstack(rows_b) return self.A, self.b
python
def get_polygon_constraints(self, range_polygones=range(3, 5), print_out=False): """ :param range_polygones: list of numbers of polygones to test. :return A, b: the constraints on the theta-vector of the form A*theta = b """ rows_A = [] rows_b = [] for m in range_polygones: if (print_out): print('checking {}-polygones'.format(m)) polygons = self.get_convex_polygons(m) row_A, row_b = self.get_polygon_constraints_m(polygons, print_out) rows_A.append(row_A) rows_b.append(row_b) self.A = np.vstack(rows_A) self.b = np.hstack(rows_b) return self.A, self.b
[ "def", "get_polygon_constraints", "(", "self", ",", "range_polygones", "=", "range", "(", "3", ",", "5", ")", ",", "print_out", "=", "False", ")", ":", "rows_A", "=", "[", "]", "rows_b", "=", "[", "]", "for", "m", "in", "range_polygones", ":", "if", ...
:param range_polygones: list of numbers of polygones to test. :return A, b: the constraints on the theta-vector of the form A*theta = b
[ ":", "param", "range_polygones", ":", "list", "of", "numbers", "of", "polygones", "to", "test", ".", ":", "return", "A", "b", ":", "the", "constraints", "on", "the", "theta", "-", "vector", "of", "the", "form", "A", "*", "theta", "=", "b" ]
train
https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/point_set.py#L508-L527
LCAV/pylocus
pylocus/point_set.py
AngleSet.get_polygon_constraints_m
def get_polygon_constraints_m(self, polygons_m, print_out=False): """ :param range_polygones: list of numbers of polygones to test. :return A, b: the constraints on the theta-vector of the form A*theta = b """ rows_b = [] rows_A = [] m = len(polygons_m[0]) rows_b.append((m - 2) * pi * np.ones( len(polygons_m), )) for p in polygons_m: row = np.zeros((self.theta.shape[0], )) for k in range(m): index = get_index(self.corners, p[1], (p[0], p[2])) row[index] = 1 p = np.roll(p, 1) assert np.sum(row) == m rows_A.append(row) A = np.vstack(rows_A) b = np.hstack(rows_b) num_constraints = A.shape[0] A_repeat = np.repeat(A.astype(bool), 3).reshape((1, -1)) corners = self.corners.reshape((1, -1)) corners_tiled = np.tile(corners, num_constraints) if (print_out): print('shape of A {}'.format(A.shape)) if (print_out): print('chosen angles m={}:\n{}'.format(m, (corners_tiled)[A_repeat] .reshape((-1, m * 3)))) if (print_out): print('{}-polygones: {}'.format(m, rows_A)) self.A = A self.b = b return A, b
python
def get_polygon_constraints_m(self, polygons_m, print_out=False): """ :param range_polygones: list of numbers of polygones to test. :return A, b: the constraints on the theta-vector of the form A*theta = b """ rows_b = [] rows_A = [] m = len(polygons_m[0]) rows_b.append((m - 2) * pi * np.ones( len(polygons_m), )) for p in polygons_m: row = np.zeros((self.theta.shape[0], )) for k in range(m): index = get_index(self.corners, p[1], (p[0], p[2])) row[index] = 1 p = np.roll(p, 1) assert np.sum(row) == m rows_A.append(row) A = np.vstack(rows_A) b = np.hstack(rows_b) num_constraints = A.shape[0] A_repeat = np.repeat(A.astype(bool), 3).reshape((1, -1)) corners = self.corners.reshape((1, -1)) corners_tiled = np.tile(corners, num_constraints) if (print_out): print('shape of A {}'.format(A.shape)) if (print_out): print('chosen angles m={}:\n{}'.format(m, (corners_tiled)[A_repeat] .reshape((-1, m * 3)))) if (print_out): print('{}-polygones: {}'.format(m, rows_A)) self.A = A self.b = b return A, b
[ "def", "get_polygon_constraints_m", "(", "self", ",", "polygons_m", ",", "print_out", "=", "False", ")", ":", "rows_b", "=", "[", "]", "rows_A", "=", "[", "]", "m", "=", "len", "(", "polygons_m", "[", "0", "]", ")", "rows_b", ".", "append", "(", "(",...
:param range_polygones: list of numbers of polygones to test. :return A, b: the constraints on the theta-vector of the form A*theta = b
[ ":", "param", "range_polygones", ":", "list", "of", "numbers", "of", "polygones", "to", "test", "." ]
train
https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/point_set.py#L581-L615
LCAV/pylocus
pylocus/point_set.py
HeterogenousSet.get_KE_constraints
def get_KE_constraints(self): """Get linear constraints on KE matrix. """ C2 = np.eye(self.m) C2 = C2[:self.m - 2, :] to_be_deleted = [] for idx_vij_1 in range(self.m - 2): idx_vij_2 = idx_vij_1 + 1 C2[idx_vij_1, idx_vij_2] = -1 i1 = np.where(self.C[idx_vij_1, :] == 1)[0][0] i2 = np.where(self.C[idx_vij_2, :] == 1)[0][0] j = np.where(self.C[idx_vij_1, :] == -1)[0][0] if i1 == i2: i = i1 k = np.where(self.C[idx_vij_2, :] == -1)[0][0] i_indices = self.C[:, j] == 1 j_indices = self.C[:, k] == -1 idx_vij_3 = np.where(np.bitwise_and( i_indices, j_indices))[0][0] #print('v{}{}, v{}{}, v{}{}\n{} {} {}'.format(j,i,k,i,k,j,idx_vij_1,idx_vij_2,idx_vij_3)) C2[idx_vij_1, idx_vij_3] = 1 else: #print('v{}{}, v{}{} not considered.'.format(j,i1,j,i2)) to_be_deleted.append(idx_vij_1) C2 = np.delete(C2, to_be_deleted, axis=0) b = np.zeros((C2.shape[0], 1)) return C2, b
python
def get_KE_constraints(self): """Get linear constraints on KE matrix. """ C2 = np.eye(self.m) C2 = C2[:self.m - 2, :] to_be_deleted = [] for idx_vij_1 in range(self.m - 2): idx_vij_2 = idx_vij_1 + 1 C2[idx_vij_1, idx_vij_2] = -1 i1 = np.where(self.C[idx_vij_1, :] == 1)[0][0] i2 = np.where(self.C[idx_vij_2, :] == 1)[0][0] j = np.where(self.C[idx_vij_1, :] == -1)[0][0] if i1 == i2: i = i1 k = np.where(self.C[idx_vij_2, :] == -1)[0][0] i_indices = self.C[:, j] == 1 j_indices = self.C[:, k] == -1 idx_vij_3 = np.where(np.bitwise_and( i_indices, j_indices))[0][0] #print('v{}{}, v{}{}, v{}{}\n{} {} {}'.format(j,i,k,i,k,j,idx_vij_1,idx_vij_2,idx_vij_3)) C2[idx_vij_1, idx_vij_3] = 1 else: #print('v{}{}, v{}{} not considered.'.format(j,i1,j,i2)) to_be_deleted.append(idx_vij_1) C2 = np.delete(C2, to_be_deleted, axis=0) b = np.zeros((C2.shape[0], 1)) return C2, b
[ "def", "get_KE_constraints", "(", "self", ")", ":", "C2", "=", "np", ".", "eye", "(", "self", ".", "m", ")", "C2", "=", "C2", "[", ":", "self", ".", "m", "-", "2", ",", ":", "]", "to_be_deleted", "=", "[", "]", "for", "idx_vij_1", "in", "range"...
Get linear constraints on KE matrix.
[ "Get", "linear", "constraints", "on", "KE", "matrix", "." ]
train
https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/point_set.py#L666-L692
d0ugal/python-rfxcom
rfxcom/protocol/lighting2.py
Lighting2.parse
def parse(self, data): """Parse a 12 bytes packet in the Lighting2 format and return a dictionary containing the data extracted. An example of a return value would be: .. code-block:: python { 'id': "0x111F342", 'packet_length': 10, 'packet_type': 17, 'packet_type_name': 'Humidity sensors', 'sequence_number': 19, 'packet_subtype': 0, 'packet_subtype_name': "AC", 'unit_code': 10, 'command': 1, 'command_text': "Off", 'level': 7, 'signal_level': 9, } :param data: bytearray to be parsed :type data: bytearray :return: Data dictionary containing the parsed values :rtype: dict """ self.validate_packet(data) results = self.parse_header_part(data) sub_type = results['packet_subtype'] id_ = self.dump_hex(data[4:8]) unit_code = data[8] command = data[9] command_text = SUB_TYPE_COMMANDS.get(sub_type, {}).get(command) dim_level = DIM_LEVEL_TO_PERCENT.get(data[10], '--??--') sensor_specific = { 'id': id_, 'unit_code': unit_code, 'command': command, 'command_text': command_text, 'dim_level': dim_level } results.update(RfxPacketUtils.parse_signal_upper(data[11])) results.update(sensor_specific) return results
python
def parse(self, data): """Parse a 12 bytes packet in the Lighting2 format and return a dictionary containing the data extracted. An example of a return value would be: .. code-block:: python { 'id': "0x111F342", 'packet_length': 10, 'packet_type': 17, 'packet_type_name': 'Humidity sensors', 'sequence_number': 19, 'packet_subtype': 0, 'packet_subtype_name': "AC", 'unit_code': 10, 'command': 1, 'command_text': "Off", 'level': 7, 'signal_level': 9, } :param data: bytearray to be parsed :type data: bytearray :return: Data dictionary containing the parsed values :rtype: dict """ self.validate_packet(data) results = self.parse_header_part(data) sub_type = results['packet_subtype'] id_ = self.dump_hex(data[4:8]) unit_code = data[8] command = data[9] command_text = SUB_TYPE_COMMANDS.get(sub_type, {}).get(command) dim_level = DIM_LEVEL_TO_PERCENT.get(data[10], '--??--') sensor_specific = { 'id': id_, 'unit_code': unit_code, 'command': command, 'command_text': command_text, 'dim_level': dim_level } results.update(RfxPacketUtils.parse_signal_upper(data[11])) results.update(sensor_specific) return results
[ "def", "parse", "(", "self", ",", "data", ")", ":", "self", ".", "validate_packet", "(", "data", ")", "results", "=", "self", ".", "parse_header_part", "(", "data", ")", "sub_type", "=", "results", "[", "'packet_subtype'", "]", "id_", "=", "self", ".", ...
Parse a 12 bytes packet in the Lighting2 format and return a dictionary containing the data extracted. An example of a return value would be: .. code-block:: python { 'id': "0x111F342", 'packet_length': 10, 'packet_type': 17, 'packet_type_name': 'Humidity sensors', 'sequence_number': 19, 'packet_subtype': 0, 'packet_subtype_name': "AC", 'unit_code': 10, 'command': 1, 'command_text': "Off", 'level': 7, 'signal_level': 9, } :param data: bytearray to be parsed :type data: bytearray :return: Data dictionary containing the parsed values :rtype: dict
[ "Parse", "a", "12", "bytes", "packet", "in", "the", "Lighting2", "format", "and", "return", "a", "dictionary", "containing", "the", "data", "extracted", ".", "An", "example", "of", "a", "return", "value", "would", "be", ":" ]
train
https://github.com/d0ugal/python-rfxcom/blob/2eb87f85e5f5a04d00f32f25e0f010edfefbde0d/rfxcom/protocol/lighting2.py#L89-L141
d0ugal/python-rfxcom
rfxcom/protocol/elec.py
Elec._bytes_to_uint_48
def _bytes_to_uint_48(self, bytes_): """Converts an array of 6 bytes to a 48bit integer. :param data: bytearray to be converted to a 48bit integer :type data: bytearray :return: the integer :rtype: int """ return ((bytes_[0] * pow(2, 40)) + (bytes_[1] * pow(2, 32)) + (bytes_[2] * pow(2, 24)) + (bytes_[3] << 16) + (bytes_[4] << 8) + bytes_[4])
python
def _bytes_to_uint_48(self, bytes_): """Converts an array of 6 bytes to a 48bit integer. :param data: bytearray to be converted to a 48bit integer :type data: bytearray :return: the integer :rtype: int """ return ((bytes_[0] * pow(2, 40)) + (bytes_[1] * pow(2, 32)) + (bytes_[2] * pow(2, 24)) + (bytes_[3] << 16) + (bytes_[4] << 8) + bytes_[4])
[ "def", "_bytes_to_uint_48", "(", "self", ",", "bytes_", ")", ":", "return", "(", "(", "bytes_", "[", "0", "]", "*", "pow", "(", "2", ",", "40", ")", ")", "+", "(", "bytes_", "[", "1", "]", "*", "pow", "(", "2", ",", "32", ")", ")", "+", "("...
Converts an array of 6 bytes to a 48bit integer. :param data: bytearray to be converted to a 48bit integer :type data: bytearray :return: the integer :rtype: int
[ "Converts", "an", "array", "of", "6", "bytes", "to", "a", "48bit", "integer", "." ]
train
https://github.com/d0ugal/python-rfxcom/blob/2eb87f85e5f5a04d00f32f25e0f010edfefbde0d/rfxcom/protocol/elec.py#L64-L75
d0ugal/python-rfxcom
rfxcom/protocol/elec.py
Elec.parse
def parse(self, data): """Parse a 18 bytes packet in the Electricity format and return a dictionary containing the data extracted. An example of a return value would be: .. code-block:: python { 'count': 3, 'current_watts': 692, 'id': "0x2EB2", 'packet_length': 17, 'packet_type': 90, 'packet_type_name': 'Energy usage sensors', 'sequence_number': 0, 'packet_subtype': 1, 'packet_subtype_name': "CM119/160", 'total_watts': 920825.1947099693, 'signal_level': 9, 'battery_level': 6, } :param data: bytearray to be parsed :type data: bytearray :return: Data dictionary containing the parsed values :rtype: dict """ self.validate_packet(data) TOTAL_DIVISOR = 223.666 id_ = self.dump_hex(data[4:6]) count = data[6] instant = data[7:11] total = data[11:16] current_watts = self._bytes_to_uint_32(instant) total_watts = self._bytes_to_uint_48(total) / TOTAL_DIVISOR sensor_specific = { 'count': count, 'current_watts': current_watts, 'id': id_, 'total_watts': total_watts } results = self.parse_header_part(data) results.update(RfxPacketUtils.parse_signal_and_battery(data[17])) results.update(sensor_specific) return results
python
def parse(self, data): """Parse a 18 bytes packet in the Electricity format and return a dictionary containing the data extracted. An example of a return value would be: .. code-block:: python { 'count': 3, 'current_watts': 692, 'id': "0x2EB2", 'packet_length': 17, 'packet_type': 90, 'packet_type_name': 'Energy usage sensors', 'sequence_number': 0, 'packet_subtype': 1, 'packet_subtype_name': "CM119/160", 'total_watts': 920825.1947099693, 'signal_level': 9, 'battery_level': 6, } :param data: bytearray to be parsed :type data: bytearray :return: Data dictionary containing the parsed values :rtype: dict """ self.validate_packet(data) TOTAL_DIVISOR = 223.666 id_ = self.dump_hex(data[4:6]) count = data[6] instant = data[7:11] total = data[11:16] current_watts = self._bytes_to_uint_32(instant) total_watts = self._bytes_to_uint_48(total) / TOTAL_DIVISOR sensor_specific = { 'count': count, 'current_watts': current_watts, 'id': id_, 'total_watts': total_watts } results = self.parse_header_part(data) results.update(RfxPacketUtils.parse_signal_and_battery(data[17])) results.update(sensor_specific) return results
[ "def", "parse", "(", "self", ",", "data", ")", ":", "self", ".", "validate_packet", "(", "data", ")", "TOTAL_DIVISOR", "=", "223.666", "id_", "=", "self", ".", "dump_hex", "(", "data", "[", "4", ":", "6", "]", ")", "count", "=", "data", "[", "6", ...
Parse a 18 bytes packet in the Electricity format and return a dictionary containing the data extracted. An example of a return value would be: .. code-block:: python { 'count': 3, 'current_watts': 692, 'id': "0x2EB2", 'packet_length': 17, 'packet_type': 90, 'packet_type_name': 'Energy usage sensors', 'sequence_number': 0, 'packet_subtype': 1, 'packet_subtype_name': "CM119/160", 'total_watts': 920825.1947099693, 'signal_level': 9, 'battery_level': 6, } :param data: bytearray to be parsed :type data: bytearray :return: Data dictionary containing the parsed values :rtype: dict
[ "Parse", "a", "18", "bytes", "packet", "in", "the", "Electricity", "format", "and", "return", "a", "dictionary", "containing", "the", "data", "extracted", ".", "An", "example", "of", "a", "return", "value", "would", "be", ":" ]
train
https://github.com/d0ugal/python-rfxcom/blob/2eb87f85e5f5a04d00f32f25e0f010edfefbde0d/rfxcom/protocol/elec.py#L77-L129
nephila/djangocms-redirect
djangocms_redirect/utils.py
get_key_from_path_and_site
def get_key_from_path_and_site(path, site_id): ''' cache key has to be < 250 chars to avoid memcache.Client.MemcachedKeyLengthError The best algoritm is SHA-224 whose output (224 chars) respects this limitations ''' key = '{}_{}'.format(path, site_id) key = hashlib.sha224(key.encode('utf-8')).hexdigest() return key
python
def get_key_from_path_and_site(path, site_id): ''' cache key has to be < 250 chars to avoid memcache.Client.MemcachedKeyLengthError The best algoritm is SHA-224 whose output (224 chars) respects this limitations ''' key = '{}_{}'.format(path, site_id) key = hashlib.sha224(key.encode('utf-8')).hexdigest() return key
[ "def", "get_key_from_path_and_site", "(", "path", ",", "site_id", ")", ":", "key", "=", "'{}_{}'", ".", "format", "(", "path", ",", "site_id", ")", "key", "=", "hashlib", ".", "sha224", "(", "key", ".", "encode", "(", "'utf-8'", ")", ")", ".", "hexdige...
cache key has to be < 250 chars to avoid memcache.Client.MemcachedKeyLengthError The best algoritm is SHA-224 whose output (224 chars) respects this limitations
[ "cache", "key", "has", "to", "be", "<", "250", "chars", "to", "avoid", "memcache", ".", "Client", ".", "MemcachedKeyLengthError", "The", "best", "algoritm", "is", "SHA", "-", "224", "whose", "output", "(", "224", "chars", ")", "respects", "this", "limitati...
train
https://github.com/nephila/djangocms-redirect/blob/ccded920218fe1b34d5d563566642278a4f3a155/djangocms_redirect/utils.py#L5-L12
inveniosoftware/invenio-previewer
invenio_previewer/extensions/csv_dthreejs.py
validate_csv
def validate_csv(file): """Return dialect information about given csv file.""" try: # Detect encoding and dialect with file.open() as fp: encoding = detect_encoding(fp, default='utf-8') sample = fp.read( current_app.config.get('PREVIEWER_CSV_VALIDATION_BYTES', 1024)) delimiter = csv.Sniffer().sniff(sample.decode(encoding)).delimiter is_valid = True except Exception as e: current_app.logger.debug( 'File {0} is not valid CSV: {1}'.format(file.uri, e)) encoding = '' delimiter = '' is_valid = False return { 'delimiter': delimiter, 'encoding': encoding, 'is_valid': is_valid }
python
def validate_csv(file): """Return dialect information about given csv file.""" try: # Detect encoding and dialect with file.open() as fp: encoding = detect_encoding(fp, default='utf-8') sample = fp.read( current_app.config.get('PREVIEWER_CSV_VALIDATION_BYTES', 1024)) delimiter = csv.Sniffer().sniff(sample.decode(encoding)).delimiter is_valid = True except Exception as e: current_app.logger.debug( 'File {0} is not valid CSV: {1}'.format(file.uri, e)) encoding = '' delimiter = '' is_valid = False return { 'delimiter': delimiter, 'encoding': encoding, 'is_valid': is_valid }
[ "def", "validate_csv", "(", "file", ")", ":", "try", ":", "# Detect encoding and dialect", "with", "file", ".", "open", "(", ")", "as", "fp", ":", "encoding", "=", "detect_encoding", "(", "fp", ",", "default", "=", "'utf-8'", ")", "sample", "=", "fp", "....
Return dialect information about given csv file.
[ "Return", "dialect", "information", "about", "given", "csv", "file", "." ]
train
https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/extensions/csv_dthreejs.py#L23-L44
inveniosoftware/invenio-previewer
invenio_previewer/extensions/csv_dthreejs.py
preview
def preview(file): """Render appropiate template with embed flag.""" file_info = validate_csv(file) return render_template( 'invenio_previewer/csv_bar.html', file=file, delimiter=file_info['delimiter'], encoding=file_info['encoding'], js_bundles=current_previewer.js_bundles + ['previewer_csv_js'], css_bundles=current_previewer.css_bundles, )
python
def preview(file): """Render appropiate template with embed flag.""" file_info = validate_csv(file) return render_template( 'invenio_previewer/csv_bar.html', file=file, delimiter=file_info['delimiter'], encoding=file_info['encoding'], js_bundles=current_previewer.js_bundles + ['previewer_csv_js'], css_bundles=current_previewer.css_bundles, )
[ "def", "preview", "(", "file", ")", ":", "file_info", "=", "validate_csv", "(", "file", ")", "return", "render_template", "(", "'invenio_previewer/csv_bar.html'", ",", "file", "=", "file", ",", "delimiter", "=", "file_info", "[", "'delimiter'", "]", ",", "enco...
Render appropiate template with embed flag.
[ "Render", "appropiate", "template", "with", "embed", "flag", "." ]
train
https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/extensions/csv_dthreejs.py#L54-L64
inveniosoftware/invenio-previewer
invenio_previewer/extensions/zip.py
make_tree
def make_tree(file): """Create tree structure from ZIP archive.""" max_files_count = current_app.config.get('PREVIEWER_ZIP_MAX_FILES', 1000) tree = {'type': 'folder', 'id': -1, 'children': {}} try: with file.open() as fp: zf = zipfile.ZipFile(fp) # Detect filenames encoding. sample = ' '.join(zf.namelist()[:max_files_count]) if not isinstance(sample, binary_type): sample = sample.encode('utf-16be') encoding = chardet.detect(sample).get('encoding', 'utf-8') for i, info in enumerate(zf.infolist()): if i > max_files_count: raise BufferError('Too many files inside the ZIP file.') comps = info.filename.split(os.sep) node = tree for c in comps: if not isinstance(c, text_type): c = c.decode(encoding) if c not in node['children']: if c == '': node['type'] = 'folder' continue node['children'][c] = { 'name': c, 'type': 'item', 'id': 'item{0}'.format(i), 'children': {} } node = node['children'][c] node['size'] = info.file_size except BufferError: return tree, True, None except (zipfile.LargeZipFile): return tree, False, 'Zipfile is too large to be previewed.' except Exception as e: current_app.logger.warning(str(e), exc_info=True) return tree, False, 'Zipfile is not previewable.' return tree, False, None
python
def make_tree(file): """Create tree structure from ZIP archive.""" max_files_count = current_app.config.get('PREVIEWER_ZIP_MAX_FILES', 1000) tree = {'type': 'folder', 'id': -1, 'children': {}} try: with file.open() as fp: zf = zipfile.ZipFile(fp) # Detect filenames encoding. sample = ' '.join(zf.namelist()[:max_files_count]) if not isinstance(sample, binary_type): sample = sample.encode('utf-16be') encoding = chardet.detect(sample).get('encoding', 'utf-8') for i, info in enumerate(zf.infolist()): if i > max_files_count: raise BufferError('Too many files inside the ZIP file.') comps = info.filename.split(os.sep) node = tree for c in comps: if not isinstance(c, text_type): c = c.decode(encoding) if c not in node['children']: if c == '': node['type'] = 'folder' continue node['children'][c] = { 'name': c, 'type': 'item', 'id': 'item{0}'.format(i), 'children': {} } node = node['children'][c] node['size'] = info.file_size except BufferError: return tree, True, None except (zipfile.LargeZipFile): return tree, False, 'Zipfile is too large to be previewed.' except Exception as e: current_app.logger.warning(str(e), exc_info=True) return tree, False, 'Zipfile is not previewable.' return tree, False, None
[ "def", "make_tree", "(", "file", ")", ":", "max_files_count", "=", "current_app", ".", "config", ".", "get", "(", "'PREVIEWER_ZIP_MAX_FILES'", ",", "1000", ")", "tree", "=", "{", "'type'", ":", "'folder'", ",", "'id'", ":", "-", "1", ",", "'children'", "...
Create tree structure from ZIP archive.
[ "Create", "tree", "structure", "from", "ZIP", "archive", "." ]
train
https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/extensions/zip.py#L26-L67
inveniosoftware/invenio-previewer
invenio_previewer/extensions/zip.py
children_to_list
def children_to_list(node): """Organize children structure.""" if node['type'] == 'item' and len(node['children']) == 0: del node['children'] else: node['type'] = 'folder' node['children'] = list(node['children'].values()) node['children'].sort(key=lambda x: x['name']) node['children'] = map(children_to_list, node['children']) return node
python
def children_to_list(node): """Organize children structure.""" if node['type'] == 'item' and len(node['children']) == 0: del node['children'] else: node['type'] = 'folder' node['children'] = list(node['children'].values()) node['children'].sort(key=lambda x: x['name']) node['children'] = map(children_to_list, node['children']) return node
[ "def", "children_to_list", "(", "node", ")", ":", "if", "node", "[", "'type'", "]", "==", "'item'", "and", "len", "(", "node", "[", "'children'", "]", ")", "==", "0", ":", "del", "node", "[", "'children'", "]", "else", ":", "node", "[", "'type'", "...
Organize children structure.
[ "Organize", "children", "structure", "." ]
train
https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/extensions/zip.py#L70-L79
inveniosoftware/invenio-previewer
invenio_previewer/extensions/zip.py
preview
def preview(file): """Return appropriate template and pass the file and an embed flag.""" tree, limit_reached, error = make_tree(file) list = children_to_list(tree)['children'] return render_template( "invenio_previewer/zip.html", file=file, tree=list, limit_reached=limit_reached, error=error, js_bundles=current_previewer.js_bundles + ['previewer_fullscreen_js'], css_bundles=current_previewer.css_bundles, )
python
def preview(file): """Return appropriate template and pass the file and an embed flag.""" tree, limit_reached, error = make_tree(file) list = children_to_list(tree)['children'] return render_template( "invenio_previewer/zip.html", file=file, tree=list, limit_reached=limit_reached, error=error, js_bundles=current_previewer.js_bundles + ['previewer_fullscreen_js'], css_bundles=current_previewer.css_bundles, )
[ "def", "preview", "(", "file", ")", ":", "tree", ",", "limit_reached", ",", "error", "=", "make_tree", "(", "file", ")", "list", "=", "children_to_list", "(", "tree", ")", "[", "'children'", "]", "return", "render_template", "(", "\"invenio_previewer/zip.html\...
Return appropriate template and pass the file and an embed flag.
[ "Return", "appropriate", "template", "and", "pass", "the", "file", "and", "an", "embed", "flag", "." ]
train
https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/extensions/zip.py#L87-L99
LCAV/pylocus
pylocus/simulation.py
create_noisy_edm
def create_noisy_edm(edm, noise, n=None): """Create noisy version of edm Adds symmetric Gaussian noise to non-diagonal elements of EDM (to distances!). The output EDM is ensured to have only positive entries. :param edm: Original, noiseless EDM. :param noise: Standard deviation of Gaussian noise to be added to distances. :param n: How many rows/columns to consider. Set to size of edm by default. :return: Noisy version of input EDM. """ N = edm.shape[0] if n is None: n = N found = False max_it = 100 i = 0 while not found: i += 1 dm = np.sqrt(edm) + np.random.normal(scale=noise, size=edm.shape) dm = np.triu(dm) edm_noisy = np.power(dm + dm.T, 2) edm_noisy[range(N), range(N)] = 0.0 edm_noisy[n:, n:] = edm[n:, n:] if (edm_noisy >= 0).all(): found = True if i > max_it: print('create_noisy_edm: last EDM', edm_noisy) raise RuntimeError( 'Could not generate all positive edm in {} iterations.'.format(max_it)) return edm_noisy
python
def create_noisy_edm(edm, noise, n=None): """Create noisy version of edm Adds symmetric Gaussian noise to non-diagonal elements of EDM (to distances!). The output EDM is ensured to have only positive entries. :param edm: Original, noiseless EDM. :param noise: Standard deviation of Gaussian noise to be added to distances. :param n: How many rows/columns to consider. Set to size of edm by default. :return: Noisy version of input EDM. """ N = edm.shape[0] if n is None: n = N found = False max_it = 100 i = 0 while not found: i += 1 dm = np.sqrt(edm) + np.random.normal(scale=noise, size=edm.shape) dm = np.triu(dm) edm_noisy = np.power(dm + dm.T, 2) edm_noisy[range(N), range(N)] = 0.0 edm_noisy[n:, n:] = edm[n:, n:] if (edm_noisy >= 0).all(): found = True if i > max_it: print('create_noisy_edm: last EDM', edm_noisy) raise RuntimeError( 'Could not generate all positive edm in {} iterations.'.format(max_it)) return edm_noisy
[ "def", "create_noisy_edm", "(", "edm", ",", "noise", ",", "n", "=", "None", ")", ":", "N", "=", "edm", ".", "shape", "[", "0", "]", "if", "n", "is", "None", ":", "n", "=", "N", "found", "=", "False", "max_it", "=", "100", "i", "=", "0", "whil...
Create noisy version of edm Adds symmetric Gaussian noise to non-diagonal elements of EDM (to distances!). The output EDM is ensured to have only positive entries. :param edm: Original, noiseless EDM. :param noise: Standard deviation of Gaussian noise to be added to distances. :param n: How many rows/columns to consider. Set to size of edm by default. :return: Noisy version of input EDM.
[ "Create", "noisy", "version", "of", "edm", "Adds", "symmetric", "Gaussian", "noise", "to", "non", "-", "diagonal", "elements", "of", "EDM", "(", "to", "distances!", ")", ".", "The", "output", "EDM", "is", "ensured", "to", "have", "only", "positive", "entri...
train
https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/simulation.py#L33-L64
LCAV/pylocus
pylocus/simulation.py
create_mask
def create_mask(N, method='all', nmissing=0): """ Create weight mask according to method. :param N: Dimension of square weight matrix. :param method: Method to use (default: 'all'). - none: no missing entries (only diagonal is set to 0 for dwMDS) - first: only randomly delete measurements to first point (zeros in first row/column of matrix) - all: randomly delete measurements in whole matrix :param nmissing: Number of deleted measurements, used by methods 'first' and 'all' :return: Binary weight mask. :rtype: numpy.ndarray """ weights = np.ones((N, N)) weights[range(N), range(N)] = 0 if method == 'none': return weights # create indices object to choose from elif method == 'all': all_indices = np.triu_indices(N, 1) elif method == 'first': all_indices = [np.zeros(N - 1).astype(np.int), np.arange(1, N).astype(np.int)] ntotal = len(all_indices[0]) # randomly choose from indices and set to 0 choice = np.random.choice(ntotal, nmissing, replace=False) chosen = [all_indices[0][choice], all_indices[1][choice]] weights[chosen] = 0 weights[chosen[1], chosen[0]] = 0 return weights
python
def create_mask(N, method='all', nmissing=0): """ Create weight mask according to method. :param N: Dimension of square weight matrix. :param method: Method to use (default: 'all'). - none: no missing entries (only diagonal is set to 0 for dwMDS) - first: only randomly delete measurements to first point (zeros in first row/column of matrix) - all: randomly delete measurements in whole matrix :param nmissing: Number of deleted measurements, used by methods 'first' and 'all' :return: Binary weight mask. :rtype: numpy.ndarray """ weights = np.ones((N, N)) weights[range(N), range(N)] = 0 if method == 'none': return weights # create indices object to choose from elif method == 'all': all_indices = np.triu_indices(N, 1) elif method == 'first': all_indices = [np.zeros(N - 1).astype(np.int), np.arange(1, N).astype(np.int)] ntotal = len(all_indices[0]) # randomly choose from indices and set to 0 choice = np.random.choice(ntotal, nmissing, replace=False) chosen = [all_indices[0][choice], all_indices[1][choice]] weights[chosen] = 0 weights[chosen[1], chosen[0]] = 0 return weights
[ "def", "create_mask", "(", "N", ",", "method", "=", "'all'", ",", "nmissing", "=", "0", ")", ":", "weights", "=", "np", ".", "ones", "(", "(", "N", ",", "N", ")", ")", "weights", "[", "range", "(", "N", ")", ",", "range", "(", "N", ")", "]", ...
Create weight mask according to method. :param N: Dimension of square weight matrix. :param method: Method to use (default: 'all'). - none: no missing entries (only diagonal is set to 0 for dwMDS) - first: only randomly delete measurements to first point (zeros in first row/column of matrix) - all: randomly delete measurements in whole matrix :param nmissing: Number of deleted measurements, used by methods 'first' and 'all' :return: Binary weight mask. :rtype: numpy.ndarray
[ "Create", "weight", "mask", "according", "to", "method", "." ]
train
https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/simulation.py#L67-L99
toumorokoshi/transmute-core
transmute_core/decorators.py
describe
def describe(**kwargs): """ describe is a decorator to customize the rest API that transmute generates, such as choosing certain arguments to be query parameters or body parameters, or a different method. :param list(str) paths: the path(s) for the handler to represent (using swagger's syntax for a path) :param list(str) methods: the methods this function should respond to. if non is set, transmute defaults to a GET. :param list(str) query_parameters: the names of arguments that should be query parameters. By default, all arguments are query_or path parameters for a GET request. :param body_parameters: the names of arguments that should be body parameters. By default, all arguments are either body or path parameters for a non-GET request. in the case of a single string, the whole body is validated against a single object. :type body_parameters: List[str] or str :param list(str) header_parameters: the arguments that should be passed into the header. :param list(str) path_parameters: the arguments that are specified by the path. By default, arguments that are found in the path are used first before the query_parameters and body_parameters. :param list(str) parameter_descriptions: descriptions for each parameter, keyed by attribute name. this will appear in the swagger documentation. """ # if we have a single method, make it a list. if isinstance(kwargs.get("paths"), string_type): kwargs["paths"] = [kwargs["paths"]] if isinstance(kwargs.get("methods"), string_type): kwargs["methods"] = [kwargs["methods"]] attrs = TransmuteAttributes(**kwargs) def decorator(f): if hasattr(f, "transmute"): f.transmute = f.transmute | attrs else: f.transmute = attrs return f return decorator
python
def describe(**kwargs): """ describe is a decorator to customize the rest API that transmute generates, such as choosing certain arguments to be query parameters or body parameters, or a different method. :param list(str) paths: the path(s) for the handler to represent (using swagger's syntax for a path) :param list(str) methods: the methods this function should respond to. if non is set, transmute defaults to a GET. :param list(str) query_parameters: the names of arguments that should be query parameters. By default, all arguments are query_or path parameters for a GET request. :param body_parameters: the names of arguments that should be body parameters. By default, all arguments are either body or path parameters for a non-GET request. in the case of a single string, the whole body is validated against a single object. :type body_parameters: List[str] or str :param list(str) header_parameters: the arguments that should be passed into the header. :param list(str) path_parameters: the arguments that are specified by the path. By default, arguments that are found in the path are used first before the query_parameters and body_parameters. :param list(str) parameter_descriptions: descriptions for each parameter, keyed by attribute name. this will appear in the swagger documentation. """ # if we have a single method, make it a list. if isinstance(kwargs.get("paths"), string_type): kwargs["paths"] = [kwargs["paths"]] if isinstance(kwargs.get("methods"), string_type): kwargs["methods"] = [kwargs["methods"]] attrs = TransmuteAttributes(**kwargs) def decorator(f): if hasattr(f, "transmute"): f.transmute = f.transmute | attrs else: f.transmute = attrs return f return decorator
[ "def", "describe", "(", "*", "*", "kwargs", ")", ":", "# if we have a single method, make it a list.", "if", "isinstance", "(", "kwargs", ".", "get", "(", "\"paths\"", ")", ",", "string_type", ")", ":", "kwargs", "[", "\"paths\"", "]", "=", "[", "kwargs", "[...
describe is a decorator to customize the rest API that transmute generates, such as choosing certain arguments to be query parameters or body parameters, or a different method. :param list(str) paths: the path(s) for the handler to represent (using swagger's syntax for a path) :param list(str) methods: the methods this function should respond to. if non is set, transmute defaults to a GET. :param list(str) query_parameters: the names of arguments that should be query parameters. By default, all arguments are query_or path parameters for a GET request. :param body_parameters: the names of arguments that should be body parameters. By default, all arguments are either body or path parameters for a non-GET request. in the case of a single string, the whole body is validated against a single object. :type body_parameters: List[str] or str :param list(str) header_parameters: the arguments that should be passed into the header. :param list(str) path_parameters: the arguments that are specified by the path. By default, arguments that are found in the path are used first before the query_parameters and body_parameters. :param list(str) parameter_descriptions: descriptions for each parameter, keyed by attribute name. this will appear in the swagger documentation.
[ "describe", "is", "a", "decorator", "to", "customize", "the", "rest", "API", "that", "transmute", "generates", "such", "as", "choosing", "certain", "arguments", "to", "be", "query", "parameters", "or", "body", "parameters", "or", "a", "different", "method", "....
train
https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/decorators.py#L5-L47
toumorokoshi/transmute-core
transmute_core/frameworks/aiohttp/swagger.py
add_swagger
def add_swagger(app, json_route, html_route): """ a convenience method for both adding a swagger.json route, as well as adding a page showing the html documentation """ app.router.add_route('GET', json_route, create_swagger_json_handler(app)) add_swagger_api_route(app, html_route, json_route)
python
def add_swagger(app, json_route, html_route): """ a convenience method for both adding a swagger.json route, as well as adding a page showing the html documentation """ app.router.add_route('GET', json_route, create_swagger_json_handler(app)) add_swagger_api_route(app, html_route, json_route)
[ "def", "add_swagger", "(", "app", ",", "json_route", ",", "html_route", ")", ":", "app", ".", "router", ".", "add_route", "(", "'GET'", ",", "json_route", ",", "create_swagger_json_handler", "(", "app", ")", ")", "add_swagger_api_route", "(", "app", ",", "ht...
a convenience method for both adding a swagger.json route, as well as adding a page showing the html documentation
[ "a", "convenience", "method", "for", "both", "adding", "a", "swagger", ".", "json", "route", "as", "well", "as", "adding", "a", "page", "showing", "the", "html", "documentation" ]
train
https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/frameworks/aiohttp/swagger.py#L20-L26
toumorokoshi/transmute-core
transmute_core/frameworks/aiohttp/swagger.py
add_swagger_api_route
def add_swagger_api_route(app, target_route, swagger_json_route): """ mount a swagger statics page. app: the aiohttp app object target_route: the path to mount the statics page. swagger_json_route: the path where the swagger json definitions is expected to be. """ static_root = get_swagger_static_root() swagger_body = generate_swagger_html( STATIC_ROOT, swagger_json_route ).encode("utf-8") async def swagger_ui(request): return web.Response(body=swagger_body, content_type="text/html") app.router.add_route("GET", target_route, swagger_ui) app.router.add_static(STATIC_ROOT, static_root)
python
def add_swagger_api_route(app, target_route, swagger_json_route): """ mount a swagger statics page. app: the aiohttp app object target_route: the path to mount the statics page. swagger_json_route: the path where the swagger json definitions is expected to be. """ static_root = get_swagger_static_root() swagger_body = generate_swagger_html( STATIC_ROOT, swagger_json_route ).encode("utf-8") async def swagger_ui(request): return web.Response(body=swagger_body, content_type="text/html") app.router.add_route("GET", target_route, swagger_ui) app.router.add_static(STATIC_ROOT, static_root)
[ "def", "add_swagger_api_route", "(", "app", ",", "target_route", ",", "swagger_json_route", ")", ":", "static_root", "=", "get_swagger_static_root", "(", ")", "swagger_body", "=", "generate_swagger_html", "(", "STATIC_ROOT", ",", "swagger_json_route", ")", ".", "encod...
mount a swagger statics page. app: the aiohttp app object target_route: the path to mount the statics page. swagger_json_route: the path where the swagger json definitions is expected to be.
[ "mount", "a", "swagger", "statics", "page", "." ]
train
https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/frameworks/aiohttp/swagger.py#L29-L47