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:
re... | 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:
re... | [
"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_... | 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_... | [
"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
... | 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
... | [
"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_eve... | 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_eve... | [
"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
... | 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
... | [
"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)
... | 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)
... | [
"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 (B... | [
"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... | 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... | [
"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])
... | 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])
... | [
"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 ex... | 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 ex... | [
"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 == SUPPRES... | 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 == SUPPRES... | [
"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, j... | 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, j... | [
"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 \
... | 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 \
... | [
"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... | 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... | [
"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 = N... | 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 = N... | [
"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 ... | 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 ... | [
"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... | [
"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_se... | 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_se... | [
"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)
i... | 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)
i... | [
"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):
... | 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):
... | [
"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))
c... | 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))
c... | [
"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_f... | 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_f... | [
"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
re... | 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
re... | [
"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 = [], {}
... | 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 = [], {}
... | [
"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... | 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... | [
"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:
... | 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:
... | [
"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 v... | 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 v... | [
"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=' ', new... | 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=' ', new... | [
"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.d... | 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.d... | [
"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 ... | 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 ... | [
"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 ... | 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 ... | [
"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):
re... | 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):
re... | [
"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 ... | 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 ... | [
"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
... | 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
... | [
"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: Val... | [
"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 ... | 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 ... | [
"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 specifie... | [
"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 deserializ... | 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 deserializ... | [
"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 attr... | [
"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,
... | 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,
... | [
"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,
... | [
"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))))
e... | 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))))
e... | [
"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(ip... | 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(ip... | [
"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... | 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... | [
"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
... | 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
... | [
"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
... | [
"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
... | 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
... | [
"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 def... | 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 def... | [
"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.
- ... | [
"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... | 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... | [
"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(n... | 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(n... | [
"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_ro... | 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_ro... | [
"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... | 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... | [
"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 = ... | 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 = ... | [
"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 zippe... | 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 zippe... | [
"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 o... | [
"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]
... | 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]
... | [
"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):
... | 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):
... | [
"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)... | 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)... | [
"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(... | 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(... | [
"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 = F... | 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 = F... | [
"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=s... | 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=s... | [
"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, ind... | 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, ind... | [
"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'))
re... | 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'))
re... | [
"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 measurem... | 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 measurem... | [
"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 nite... | [
"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 E... | 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 E... | [
"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... | [
"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 measure... | 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 measure... | [
"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 "Eu... | [
"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 matr... | 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 matr... | [
"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: opt... | [
"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 (Nx... | 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 (Nx... | [
"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 weigh... | [
"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... | 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... | [
"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 specifi... | 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 specifi... | [
"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 = ... | 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 = ... | [
"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
... | 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
... | [
"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: Li... | 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: Li... | [
"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.
:... | [
"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... | 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... | [
"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):
... | 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):
... | [
"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
... | 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
... | [
"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])
... | 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])
... | [
"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... | 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... | [
"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,
... | 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,
... | [
"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,
... | [
"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, 3... | 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, 3... | [
"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,
... | 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,
... | [
"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",
... | [
"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')).he... | 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')).he... | [
"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_BYT... | 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_BYT... | [
"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_b... | 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_b... | [
"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 encod... | 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 encod... | [
"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'])
... | 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'])
... | [
"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... | 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... | [
"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 Gaussia... | 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 Gaussia... | [
"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: H... | [
"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 ... | 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 ... | [
"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:... | [
"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... | 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... | [
"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) met... | [
"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.
"""
st... | 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.
"""
st... | [
"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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.