repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
getmillipede/millipede-python
millipede/__init__.py
compute_settings
def compute_settings(args, rc_settings): """ Merge arguments and rc_settings. """ settings = {} for key, value in args.items(): if key in ['reverse', 'opposite']: settings[key] = value ^ rc_settings.get(key, False) else: settings[key] = value or rc_settings.ge...
python
def compute_settings(args, rc_settings): """ Merge arguments and rc_settings. """ settings = {} for key, value in args.items(): if key in ['reverse', 'opposite']: settings[key] = value ^ rc_settings.get(key, False) else: settings[key] = value or rc_settings.ge...
[ "def", "compute_settings", "(", "args", ",", "rc_settings", ")", ":", "settings", "=", "{", "}", "for", "key", ",", "value", "in", "args", ".", "items", "(", ")", ":", "if", "key", "in", "[", "'reverse'", ",", "'opposite'", "]", ":", "settings", "[",...
Merge arguments and rc_settings.
[ "Merge", "arguments", "and", "rc_settings", "." ]
ae4f1fe388906c140d12c21fee260f2338f5b9df
https://github.com/getmillipede/millipede-python/blob/ae4f1fe388906c140d12c21fee260f2338f5b9df/millipede/__init__.py#L75-L88
train
getmillipede/millipede-python
millipede/__init__.py
millipede
def millipede(size, comment=None, reverse=False, template='default', position=0, opposite=False): """ Output the millipede """ padding_offsets = [2, 1, 0, 1, 2, 3, 4, 4, 3] padding_suite_length = len(padding_offsets) head_padding_extra_offset = 2 if opposite: padding_offsets.reverse...
python
def millipede(size, comment=None, reverse=False, template='default', position=0, opposite=False): """ Output the millipede """ padding_offsets = [2, 1, 0, 1, 2, 3, 4, 4, 3] padding_suite_length = len(padding_offsets) head_padding_extra_offset = 2 if opposite: padding_offsets.reverse...
[ "def", "millipede", "(", "size", ",", "comment", "=", "None", ",", "reverse", "=", "False", ",", "template", "=", "'default'", ",", "position", "=", "0", ",", "opposite", "=", "False", ")", ":", "padding_offsets", "=", "[", "2", ",", "1", ",", "0", ...
Output the millipede
[ "Output", "the", "millipede" ]
ae4f1fe388906c140d12c21fee260f2338f5b9df
https://github.com/getmillipede/millipede-python/blob/ae4f1fe388906c140d12c21fee260f2338f5b9df/millipede/__init__.py#L92-L158
train
getmillipede/millipede-python
millipede/__init__.py
api_post
def api_post(message, url, name, http_data=None, auth=None): """ Send `message` as `name` to `url`. You can specify extra variables in `http_data` """ try: import requests except ImportError: print('requests is required to do api post.', file=sys.stderr) sys.exit(1) data...
python
def api_post(message, url, name, http_data=None, auth=None): """ Send `message` as `name` to `url`. You can specify extra variables in `http_data` """ try: import requests except ImportError: print('requests is required to do api post.', file=sys.stderr) sys.exit(1) data...
[ "def", "api_post", "(", "message", ",", "url", ",", "name", ",", "http_data", "=", "None", ",", "auth", "=", "None", ")", ":", "try", ":", "import", "requests", "except", "ImportError", ":", "print", "(", "'requests is required to do api post.'", ",", "file"...
Send `message` as `name` to `url`. You can specify extra variables in `http_data`
[ "Send", "message", "as", "name", "to", "url", ".", "You", "can", "specify", "extra", "variables", "in", "http_data" ]
ae4f1fe388906c140d12c21fee260f2338f5b9df
https://github.com/getmillipede/millipede-python/blob/ae4f1fe388906c140d12c21fee260f2338f5b9df/millipede/__init__.py#L161-L184
train
getmillipede/millipede-python
millipede/__init__.py
main
def main(): """ Entry point """ rc_settings = read_rcfile() parser = ArgumentParser(description='Millipede generator') parser.add_argument('-s', '--size', type=int, nargs="?", help='the size of the millipede') parser.add...
python
def main(): """ Entry point """ rc_settings = read_rcfile() parser = ArgumentParser(description='Millipede generator') parser.add_argument('-s', '--size', type=int, nargs="?", help='the size of the millipede') parser.add...
[ "def", "main", "(", ")", ":", "rc_settings", "=", "read_rcfile", "(", ")", "parser", "=", "ArgumentParser", "(", "description", "=", "'Millipede generator'", ")", "parser", ".", "add_argument", "(", "'-s'", ",", "'--size'", ",", "type", "=", "int", ",", "n...
Entry point
[ "Entry", "point" ]
ae4f1fe388906c140d12c21fee260f2338f5b9df
https://github.com/getmillipede/millipede-python/blob/ae4f1fe388906c140d12c21fee260f2338f5b9df/millipede/__init__.py#L187-L271
train
walkr/nanoservice
setup.py
read_long_description
def read_long_description(readme_file): """ Read package long description from README file """ try: import pypandoc except (ImportError, OSError) as exception: print('No pypandoc or pandoc: %s' % (exception,)) if sys.version_info.major == 3: handle = open(readme_file, enc...
python
def read_long_description(readme_file): """ Read package long description from README file """ try: import pypandoc except (ImportError, OSError) as exception: print('No pypandoc or pandoc: %s' % (exception,)) if sys.version_info.major == 3: handle = open(readme_file, enc...
[ "def", "read_long_description", "(", "readme_file", ")", ":", "try", ":", "import", "pypandoc", "except", "(", "ImportError", ",", "OSError", ")", "as", "exception", ":", "print", "(", "'No pypandoc or pandoc: %s'", "%", "(", "exception", ",", ")", ")", "if", ...
Read package long description from README file
[ "Read", "package", "long", "description", "from", "README", "file" ]
e2098986b1baa5f283167ae487d14f3c6c21961a
https://github.com/walkr/nanoservice/blob/e2098986b1baa5f283167ae487d14f3c6c21961a/setup.py#L13-L27
train
GaretJax/lancet
lancet/utils.py
content_from_path
def content_from_path(path, encoding='utf-8'): """Return the content of the specified file as a string. This function also supports loading resources from packages. """ if not os.path.isabs(path) and ':' in path: package, path = path.split(':', 1) content = resource_string(package, path...
python
def content_from_path(path, encoding='utf-8'): """Return the content of the specified file as a string. This function also supports loading resources from packages. """ if not os.path.isabs(path) and ':' in path: package, path = path.split(':', 1) content = resource_string(package, path...
[ "def", "content_from_path", "(", "path", ",", "encoding", "=", "'utf-8'", ")", ":", "if", "not", "os", ".", "path", ".", "isabs", "(", "path", ")", "and", "':'", "in", "path", ":", "package", ",", "path", "=", "path", ".", "split", "(", "':'", ",",...
Return the content of the specified file as a string. This function also supports loading resources from packages.
[ "Return", "the", "content", "of", "the", "specified", "file", "as", "a", "string", "." ]
cf438c5c6166b18ee0dc5ffce55220793019bb95
https://github.com/GaretJax/lancet/blob/cf438c5c6166b18ee0dc5ffce55220793019bb95/lancet/utils.py#L99-L112
train
walkr/nanoservice
nanoservice/reqrep.py
Responder.execute
def execute(self, method, args, ref): """ Execute the method with args """ response = {'result': None, 'error': None, 'ref': ref} fun = self.methods.get(method) if not fun: response['error'] = 'Method `{}` not found'.format(method) else: try: ...
python
def execute(self, method, args, ref): """ Execute the method with args """ response = {'result': None, 'error': None, 'ref': ref} fun = self.methods.get(method) if not fun: response['error'] = 'Method `{}` not found'.format(method) else: try: ...
[ "def", "execute", "(", "self", ",", "method", ",", "args", ",", "ref", ")", ":", "response", "=", "{", "'result'", ":", "None", ",", "'error'", ":", "None", ",", "'ref'", ":", "ref", "}", "fun", "=", "self", ".", "methods", ".", "get", "(", "meth...
Execute the method with args
[ "Execute", "the", "method", "with", "args" ]
e2098986b1baa5f283167ae487d14f3c6c21961a
https://github.com/walkr/nanoservice/blob/e2098986b1baa5f283167ae487d14f3c6c21961a/nanoservice/reqrep.py#L58-L71
train
walkr/nanoservice
nanoservice/reqrep.py
Responder.register
def register(self, name, fun, description=None): """ Register function on this service """ self.methods[name] = fun self.descriptions[name] = description
python
def register(self, name, fun, description=None): """ Register function on this service """ self.methods[name] = fun self.descriptions[name] = description
[ "def", "register", "(", "self", ",", "name", ",", "fun", ",", "description", "=", "None", ")", ":", "self", ".", "methods", "[", "name", "]", "=", "fun", "self", ".", "descriptions", "[", "name", "]", "=", "description" ]
Register function on this service
[ "Register", "function", "on", "this", "service" ]
e2098986b1baa5f283167ae487d14f3c6c21961a
https://github.com/walkr/nanoservice/blob/e2098986b1baa5f283167ae487d14f3c6c21961a/nanoservice/reqrep.py#L73-L76
train
walkr/nanoservice
nanoservice/reqrep.py
Responder.parse
def parse(cls, payload): """ Parse client request """ try: method, args, ref = payload except Exception as exception: raise RequestParseError(exception) else: return method, args, ref
python
def parse(cls, payload): """ Parse client request """ try: method, args, ref = payload except Exception as exception: raise RequestParseError(exception) else: return method, args, ref
[ "def", "parse", "(", "cls", ",", "payload", ")", ":", "try", ":", "method", ",", "args", ",", "ref", "=", "payload", "except", "Exception", "as", "exception", ":", "raise", "RequestParseError", "(", "exception", ")", "else", ":", "return", "method", ",",...
Parse client request
[ "Parse", "client", "request" ]
e2098986b1baa5f283167ae487d14f3c6c21961a
https://github.com/walkr/nanoservice/blob/e2098986b1baa5f283167ae487d14f3c6c21961a/nanoservice/reqrep.py#L79-L86
train
walkr/nanoservice
nanoservice/reqrep.py
Responder.process
def process(self): """ Receive data from socket and process request """ response = None try: payload = self.receive() method, args, ref = self.parse(payload) response = self.execute(method, args, ref) except AuthenticateError as exception: ...
python
def process(self): """ Receive data from socket and process request """ response = None try: payload = self.receive() method, args, ref = self.parse(payload) response = self.execute(method, args, ref) except AuthenticateError as exception: ...
[ "def", "process", "(", "self", ")", ":", "response", "=", "None", "try", ":", "payload", "=", "self", ".", "receive", "(", ")", "method", ",", "args", ",", "ref", "=", "self", ".", "parse", "(", "payload", ")", "response", "=", "self", ".", "execut...
Receive data from socket and process request
[ "Receive", "data", "from", "socket", "and", "process", "request" ]
e2098986b1baa5f283167ae487d14f3c6c21961a
https://github.com/walkr/nanoservice/blob/e2098986b1baa5f283167ae487d14f3c6c21961a/nanoservice/reqrep.py#L89-L125
train
walkr/nanoservice
nanoservice/reqrep.py
Requester.build_payload
def build_payload(cls, method, args): """ Build the payload to be sent to a `Responder` """ ref = str(uuid.uuid4()) return (method, args, ref)
python
def build_payload(cls, method, args): """ Build the payload to be sent to a `Responder` """ ref = str(uuid.uuid4()) return (method, args, ref)
[ "def", "build_payload", "(", "cls", ",", "method", ",", "args", ")", ":", "ref", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "return", "(", "method", ",", "args", ",", "ref", ")" ]
Build the payload to be sent to a `Responder`
[ "Build", "the", "payload", "to", "be", "sent", "to", "a", "Responder" ]
e2098986b1baa5f283167ae487d14f3c6c21961a
https://github.com/walkr/nanoservice/blob/e2098986b1baa5f283167ae487d14f3c6c21961a/nanoservice/reqrep.py#L144-L147
train
walkr/nanoservice
nanoservice/reqrep.py
Requester.call
def call(self, method, *args): """ Make a call to a `Responder` and return the result """ payload = self.build_payload(method, args) logging.debug('* Client will send payload: {}'.format(payload)) self.send(payload) res = self.receive() assert payload[2] == res['ref'] ...
python
def call(self, method, *args): """ Make a call to a `Responder` and return the result """ payload = self.build_payload(method, args) logging.debug('* Client will send payload: {}'.format(payload)) self.send(payload) res = self.receive() assert payload[2] == res['ref'] ...
[ "def", "call", "(", "self", ",", "method", ",", "*", "args", ")", ":", "payload", "=", "self", ".", "build_payload", "(", "method", ",", "args", ")", "logging", ".", "debug", "(", "'* Client will send payload: {}'", ".", "format", "(", "payload", ")", ")...
Make a call to a `Responder` and return the result
[ "Make", "a", "call", "to", "a", "Responder", "and", "return", "the", "result" ]
e2098986b1baa5f283167ae487d14f3c6c21961a
https://github.com/walkr/nanoservice/blob/e2098986b1baa5f283167ae487d14f3c6c21961a/nanoservice/reqrep.py#L150-L159
train
walkr/nanoservice
nanoservice/config.py
load
def load(filepath=None, filecontent=None): """ Read the json file located at `filepath` If `filecontent` is specified, its content will be json decoded and loaded instead. Usage: config.load(filepath=None, filecontent=None): Provide either a filepath or a json string """ conf =...
python
def load(filepath=None, filecontent=None): """ Read the json file located at `filepath` If `filecontent` is specified, its content will be json decoded and loaded instead. Usage: config.load(filepath=None, filecontent=None): Provide either a filepath or a json string """ conf =...
[ "def", "load", "(", "filepath", "=", "None", ",", "filecontent", "=", "None", ")", ":", "conf", "=", "DotDict", "(", ")", "assert", "filepath", "or", "filecontent", "if", "not", "filecontent", ":", "with", "io", ".", "FileIO", "(", "filepath", ")", "as...
Read the json file located at `filepath` If `filecontent` is specified, its content will be json decoded and loaded instead. Usage: config.load(filepath=None, filecontent=None): Provide either a filepath or a json string
[ "Read", "the", "json", "file", "located", "at", "filepath" ]
e2098986b1baa5f283167ae487d14f3c6c21961a
https://github.com/walkr/nanoservice/blob/e2098986b1baa5f283167ae487d14f3c6c21961a/nanoservice/config.py#L17-L35
train
IzunaDevs/SnekChek
snekchek/__main__.py
run_main
def run_main(args: argparse.Namespace, do_exit=True) -> None: """Runs the checks and exits. To extend this tool, use this function and set do_exit to False to get returned the status code. """ if args.init: generate() return None # exit after generate instead of starting to lint ...
python
def run_main(args: argparse.Namespace, do_exit=True) -> None: """Runs the checks and exits. To extend this tool, use this function and set do_exit to False to get returned the status code. """ if args.init: generate() return None # exit after generate instead of starting to lint ...
[ "def", "run_main", "(", "args", ":", "argparse", ".", "Namespace", ",", "do_exit", "=", "True", ")", "->", "None", ":", "if", "args", ".", "init", ":", "generate", "(", ")", "return", "None", "# exit after generate instead of starting to lint", "handler", "=",...
Runs the checks and exits. To extend this tool, use this function and set do_exit to False to get returned the status code.
[ "Runs", "the", "checks", "and", "exits", "." ]
fdb01bdf1ec8e79d9aae2a11d96bfb27e53a97a9
https://github.com/IzunaDevs/SnekChek/blob/fdb01bdf1ec8e79d9aae2a11d96bfb27e53a97a9/snekchek/__main__.py#L39-L72
train
IzunaDevs/SnekChek
snekchek/__main__.py
main
def main() -> None: """Main entry point for console commands.""" parser = argparse.ArgumentParser() parser.add_argument( "--json", help="output in JSON format", action="store_true", default=False) parser.add_argument( "--config-file", help="Select config file to u...
python
def main() -> None: """Main entry point for console commands.""" parser = argparse.ArgumentParser() parser.add_argument( "--json", help="output in JSON format", action="store_true", default=False) parser.add_argument( "--config-file", help="Select config file to u...
[ "def", "main", "(", ")", "->", "None", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "\"--json\"", ",", "help", "=", "\"output in JSON format\"", ",", "action", "=", "\"store_true\"", ",", "default", "="...
Main entry point for console commands.
[ "Main", "entry", "point", "for", "console", "commands", "." ]
fdb01bdf1ec8e79d9aae2a11d96bfb27e53a97a9
https://github.com/IzunaDevs/SnekChek/blob/fdb01bdf1ec8e79d9aae2a11d96bfb27e53a97a9/snekchek/__main__.py#L75-L96
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/session.py
get_session
def get_session(user_agent=None, user_agent_config_yaml=None, user_agent_lookup=None, **kwargs): # type: (Optional[str], Optional[str], Optional[str], Any) -> requests.Session """Set up and return Session object that is set up with retrying. Requires either global user agent to be set or appropriate user ag...
python
def get_session(user_agent=None, user_agent_config_yaml=None, user_agent_lookup=None, **kwargs): # type: (Optional[str], Optional[str], Optional[str], Any) -> requests.Session """Set up and return Session object that is set up with retrying. Requires either global user agent to be set or appropriate user ag...
[ "def", "get_session", "(", "user_agent", "=", "None", ",", "user_agent_config_yaml", "=", "None", ",", "user_agent_lookup", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# type: (Optional[str], Optional[str], Optional[str], Any) -> requests.Session", "s", "=", "reque...
Set up and return Session object that is set up with retrying. Requires either global user agent to be set or appropriate user agent parameter(s) to be completed. Args: user_agent (Optional[str]): User agent string. HDXPythonUtilities/X.X.X- is prefixed. user_agent_config_yaml (Optional[str]): ...
[ "Set", "up", "and", "return", "Session", "object", "that", "is", "set", "up", "with", "retrying", ".", "Requires", "either", "global", "user", "agent", "to", "be", "set", "or", "appropriate", "user", "agent", "parameter", "(", "s", ")", "to", "be", "comp...
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/session.py#L22-L131
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/email.py
Email.connect
def connect(self): # type: () -> None """ Connect to server Returns: None """ if self.connection_type.lower() == 'ssl': self.server = smtplib.SMTP_SSL(host=self.host, port=self.port, local_hostname=self.local_hostname, ...
python
def connect(self): # type: () -> None """ Connect to server Returns: None """ if self.connection_type.lower() == 'ssl': self.server = smtplib.SMTP_SSL(host=self.host, port=self.port, local_hostname=self.local_hostname, ...
[ "def", "connect", "(", "self", ")", ":", "# type: () -> None", "if", "self", ".", "connection_type", ".", "lower", "(", ")", "==", "'ssl'", ":", "self", ".", "server", "=", "smtplib", ".", "SMTP_SSL", "(", "host", "=", "self", ".", "host", ",", "port",...
Connect to server Returns: None
[ "Connect", "to", "server" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/email.py#L106-L124
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/email.py
Email.send
def send(self, recipients, subject, text_body, html_body=None, sender=None, **kwargs): # type: (List[str], str, str, Optional[str], Optional[str], Any) -> None """ Send email Args: recipients (List[str]): Email recipient subject (str): Email subject t...
python
def send(self, recipients, subject, text_body, html_body=None, sender=None, **kwargs): # type: (List[str], str, str, Optional[str], Optional[str], Any) -> None """ Send email Args: recipients (List[str]): Email recipient subject (str): Email subject t...
[ "def", "send", "(", "self", ",", "recipients", ",", "subject", ",", "text_body", ",", "html_body", "=", "None", ",", "sender", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# type: (List[str], str, str, Optional[str], Optional[str], Any) -> None", "if", "sender...
Send email Args: recipients (List[str]): Email recipient subject (str): Email subject text_body (str): Plain text email body html_body (Optional[str]): HTML email body sender (Optional[str]): Email sender. Defaults to global sender. **kwar...
[ "Send", "email" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/email.py#L137-L180
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/database.py
Database.get_session
def get_session(db_url): # type: (str) -> Session """Gets SQLAlchemy session given url. Your tables must inherit from Base in hdx.utilities.database. Args: db_url (str): SQLAlchemy url Returns: sqlalchemy.orm.session.Session: SQLAlchemy session "...
python
def get_session(db_url): # type: (str) -> Session """Gets SQLAlchemy session given url. Your tables must inherit from Base in hdx.utilities.database. Args: db_url (str): SQLAlchemy url Returns: sqlalchemy.orm.session.Session: SQLAlchemy session "...
[ "def", "get_session", "(", "db_url", ")", ":", "# type: (str) -> Session", "engine", "=", "create_engine", "(", "db_url", ",", "poolclass", "=", "NullPool", ",", "echo", "=", "False", ")", "Session", "=", "sessionmaker", "(", "bind", "=", "engine", ")", "Bas...
Gets SQLAlchemy session given url. Your tables must inherit from Base in hdx.utilities.database. Args: db_url (str): SQLAlchemy url Returns: sqlalchemy.orm.session.Session: SQLAlchemy session
[ "Gets", "SQLAlchemy", "session", "given", "url", ".", "Your", "tables", "must", "inherit", "from", "Base", "in", "hdx", ".", "utilities", ".", "database", "." ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/database.py#L83-L97
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/database.py
Database.get_params_from_sqlalchemy_url
def get_params_from_sqlalchemy_url(db_url): # type: (str) -> Dict[str,Any] """Gets PostgreSQL database connection parameters from SQLAlchemy url Args: db_url (str): SQLAlchemy url Returns: Dict[str,Any]: Dictionary of database connection parameters """ ...
python
def get_params_from_sqlalchemy_url(db_url): # type: (str) -> Dict[str,Any] """Gets PostgreSQL database connection parameters from SQLAlchemy url Args: db_url (str): SQLAlchemy url Returns: Dict[str,Any]: Dictionary of database connection parameters """ ...
[ "def", "get_params_from_sqlalchemy_url", "(", "db_url", ")", ":", "# type: (str) -> Dict[str,Any]", "result", "=", "urlsplit", "(", "db_url", ")", "return", "{", "'database'", ":", "result", ".", "path", "[", "1", ":", "]", ",", "'host'", ":", "result", ".", ...
Gets PostgreSQL database connection parameters from SQLAlchemy url Args: db_url (str): SQLAlchemy url Returns: Dict[str,Any]: Dictionary of database connection parameters
[ "Gets", "PostgreSQL", "database", "connection", "parameters", "from", "SQLAlchemy", "url" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/database.py#L100-L112
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/database.py
Database.get_sqlalchemy_url
def get_sqlalchemy_url(database=None, host=None, port=None, username=None, password=None, driver='postgres'): # type: (Optional[str], Optional[str], Union[int, str, None], Optional[str], Optional[str], str) -> str """Gets SQLAlchemy url from database connection parameters Args: data...
python
def get_sqlalchemy_url(database=None, host=None, port=None, username=None, password=None, driver='postgres'): # type: (Optional[str], Optional[str], Union[int, str, None], Optional[str], Optional[str], str) -> str """Gets SQLAlchemy url from database connection parameters Args: data...
[ "def", "get_sqlalchemy_url", "(", "database", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ",", "username", "=", "None", ",", "password", "=", "None", ",", "driver", "=", "'postgres'", ")", ":", "# type: (Optional[str], Optional[str], Union...
Gets SQLAlchemy url from database connection parameters Args: database (Optional[str]): Database name host (Optional[str]): Host where database is located port (Union[int, str, None]): Database port username (Optional[str]): Username to log into database ...
[ "Gets", "SQLAlchemy", "url", "from", "database", "connection", "parameters" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/database.py#L115-L143
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/database.py
Database.wait_for_postgres
def wait_for_postgres(database, host, port, username, password): # type: (Optional[str], Optional[str], Union[int, str, None], Optional[str], Optional[str]) -> None """Waits for PostgreSQL database to be up Args: database (Optional[str]): Database name host (Optional[str...
python
def wait_for_postgres(database, host, port, username, password): # type: (Optional[str], Optional[str], Union[int, str, None], Optional[str], Optional[str]) -> None """Waits for PostgreSQL database to be up Args: database (Optional[str]): Database name host (Optional[str...
[ "def", "wait_for_postgres", "(", "database", ",", "host", ",", "port", ",", "username", ",", "password", ")", ":", "# type: (Optional[str], Optional[str], Union[int, str, None], Optional[str], Optional[str]) -> None", "connecting_string", "=", "'Checking for PostgreSQL...'", "if"...
Waits for PostgreSQL database to be up Args: database (Optional[str]): Database name host (Optional[str]): Host where database is located port (Union[int, str, None]): Database port username (Optional[str]): Username to log into database password (Opt...
[ "Waits", "for", "PostgreSQL", "database", "to", "be", "up" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/database.py#L146-L178
train
lucaoflaif/pyCoinMarketCapAPI
coinmarketcapapi/cache.py
Cache.get_unset_cache
def get_unset_cache(self): """return : returns a tuple (num_of_not_None_caches, [list of unset caches endpoint]) """ caches = [] if self._cached_api_global_response is None: caches.append('global') if self._cached_api_ticker_response is None: caches.append...
python
def get_unset_cache(self): """return : returns a tuple (num_of_not_None_caches, [list of unset caches endpoint]) """ caches = [] if self._cached_api_global_response is None: caches.append('global') if self._cached_api_ticker_response is None: caches.append...
[ "def", "get_unset_cache", "(", "self", ")", ":", "caches", "=", "[", "]", "if", "self", ".", "_cached_api_global_response", "is", "None", ":", "caches", ".", "append", "(", "'global'", ")", "if", "self", ".", "_cached_api_ticker_response", "is", "None", ":",...
return : returns a tuple (num_of_not_None_caches, [list of unset caches endpoint])
[ "return", ":", "returns", "a", "tuple", "(", "num_of_not_None_caches", "[", "list", "of", "unset", "caches", "endpoint", "]", ")" ]
a6ab1fa57c0610e8abf3a03e9144379bf9e49907
https://github.com/lucaoflaif/pyCoinMarketCapAPI/blob/a6ab1fa57c0610e8abf3a03e9144379bf9e49907/coinmarketcapapi/cache.py#L77-L85
train
lucaoflaif/pyCoinMarketCapAPI
coinmarketcapapi/utils.py
dicts_filter
def dicts_filter(dicts_object, field_to_filter, value_of_filter): """This function gets as arguments an array of dicts through the dicts_objects parameter, then it'll return the dicts that have a value value_of_filter of the key field_to_filter. """ lambda_query = lambda value: value[field_to_filter]...
python
def dicts_filter(dicts_object, field_to_filter, value_of_filter): """This function gets as arguments an array of dicts through the dicts_objects parameter, then it'll return the dicts that have a value value_of_filter of the key field_to_filter. """ lambda_query = lambda value: value[field_to_filter]...
[ "def", "dicts_filter", "(", "dicts_object", ",", "field_to_filter", ",", "value_of_filter", ")", ":", "lambda_query", "=", "lambda", "value", ":", "value", "[", "field_to_filter", "]", "==", "value_of_filter", "filtered_coin", "=", "filter", "(", "lambda_query", "...
This function gets as arguments an array of dicts through the dicts_objects parameter, then it'll return the dicts that have a value value_of_filter of the key field_to_filter.
[ "This", "function", "gets", "as", "arguments", "an", "array", "of", "dicts", "through", "the", "dicts_objects", "parameter", "then", "it", "ll", "return", "the", "dicts", "that", "have", "a", "value", "value_of_filter", "of", "the", "key", "field_to_filter", "...
a6ab1fa57c0610e8abf3a03e9144379bf9e49907
https://github.com/lucaoflaif/pyCoinMarketCapAPI/blob/a6ab1fa57c0610e8abf3a03e9144379bf9e49907/coinmarketcapapi/utils.py#L4-L14
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/downloader.py
Download.get_path_for_url
def get_path_for_url(url, folder=None, filename=None, overwrite=False): # type: (str, Optional[str], Optional[str], bool) -> str """Get filename from url and join to provided folder or temporary folder if no folder supplied, ensuring uniqueness Args: url (str): URL to download ...
python
def get_path_for_url(url, folder=None, filename=None, overwrite=False): # type: (str, Optional[str], Optional[str], bool) -> str """Get filename from url and join to provided folder or temporary folder if no folder supplied, ensuring uniqueness Args: url (str): URL to download ...
[ "def", "get_path_for_url", "(", "url", ",", "folder", "=", "None", ",", "filename", "=", "None", ",", "overwrite", "=", "False", ")", ":", "# type: (str, Optional[str], Optional[str], bool) -> str", "if", "not", "filename", ":", "urlpath", "=", "urlsplit", "(", ...
Get filename from url and join to provided folder or temporary folder if no folder supplied, ensuring uniqueness Args: url (str): URL to download folder (Optional[str]): Folder to download it to. Defaults to None (temporary folder). filename (Optional[str]): Filename to use ...
[ "Get", "filename", "from", "url", "and", "join", "to", "provided", "folder", "or", "temporary", "folder", "if", "no", "folder", "supplied", "ensuring", "uniqueness" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/downloader.py#L87-L118
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/downloader.py
Download.get_full_url
def get_full_url(self, url): # type: (str) -> str """Get full url including any additional parameters Args: url (str): URL for which to get full url Returns: str: Full url including any additional parameters """ request = Request('GET', url) ...
python
def get_full_url(self, url): # type: (str) -> str """Get full url including any additional parameters Args: url (str): URL for which to get full url Returns: str: Full url including any additional parameters """ request = Request('GET', url) ...
[ "def", "get_full_url", "(", "self", ",", "url", ")", ":", "# type: (str) -> str", "request", "=", "Request", "(", "'GET'", ",", "url", ")", "preparedrequest", "=", "self", ".", "session", ".", "prepare_request", "(", "request", ")", "return", "preparedrequest"...
Get full url including any additional parameters Args: url (str): URL for which to get full url Returns: str: Full url including any additional parameters
[ "Get", "full", "url", "including", "any", "additional", "parameters" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/downloader.py#L120-L132
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/downloader.py
Download.get_url_for_get
def get_url_for_get(url, parameters=None): # type: (str, Optional[Dict]) -> str """Get full url for GET request including parameters Args: url (str): URL to download parameters (Optional[Dict]): Parameters to pass. Defaults to None. Returns: str: Ful...
python
def get_url_for_get(url, parameters=None): # type: (str, Optional[Dict]) -> str """Get full url for GET request including parameters Args: url (str): URL to download parameters (Optional[Dict]): Parameters to pass. Defaults to None. Returns: str: Ful...
[ "def", "get_url_for_get", "(", "url", ",", "parameters", "=", "None", ")", ":", "# type: (str, Optional[Dict]) -> str", "spliturl", "=", "urlsplit", "(", "url", ")", "getparams", "=", "OrderedDict", "(", "parse_qsl", "(", "spliturl", ".", "query", ")", ")", "i...
Get full url for GET request including parameters Args: url (str): URL to download parameters (Optional[Dict]): Parameters to pass. Defaults to None. Returns: str: Full url
[ "Get", "full", "url", "for", "GET", "request", "including", "parameters" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/downloader.py#L135-L152
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/downloader.py
Download.get_url_params_for_post
def get_url_params_for_post(url, parameters=None): # type: (str, Optional[Dict]) -> Tuple[str, Dict] """Get full url for POST request and all parameters including any in the url Args: url (str): URL to download parameters (Optional[Dict]): Parameters to pass. Defaults to...
python
def get_url_params_for_post(url, parameters=None): # type: (str, Optional[Dict]) -> Tuple[str, Dict] """Get full url for POST request and all parameters including any in the url Args: url (str): URL to download parameters (Optional[Dict]): Parameters to pass. Defaults to...
[ "def", "get_url_params_for_post", "(", "url", ",", "parameters", "=", "None", ")", ":", "# type: (str, Optional[Dict]) -> Tuple[str, Dict]", "spliturl", "=", "urlsplit", "(", "url", ")", "getparams", "=", "OrderedDict", "(", "parse_qsl", "(", "spliturl", ".", "query...
Get full url for POST request and all parameters including any in the url Args: url (str): URL to download parameters (Optional[Dict]): Parameters to pass. Defaults to None. Returns: Tuple[str, Dict]: (Full url, parameters)
[ "Get", "full", "url", "for", "POST", "request", "and", "all", "parameters", "including", "any", "in", "the", "url" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/downloader.py#L155-L173
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/downloader.py
Download.setup
def setup(self, url, stream=True, post=False, parameters=None, timeout=None): # type: (str, bool, bool, Optional[Dict], Optional[float]) -> requests.Response """Setup download from provided url returning the response Args: url (str): URL to download stream (bool): Whethe...
python
def setup(self, url, stream=True, post=False, parameters=None, timeout=None): # type: (str, bool, bool, Optional[Dict], Optional[float]) -> requests.Response """Setup download from provided url returning the response Args: url (str): URL to download stream (bool): Whethe...
[ "def", "setup", "(", "self", ",", "url", ",", "stream", "=", "True", ",", "post", "=", "False", ",", "parameters", "=", "None", ",", "timeout", "=", "None", ")", ":", "# type: (str, bool, bool, Optional[Dict], Optional[float]) -> requests.Response", "self", ".", ...
Setup download from provided url returning the response Args: url (str): URL to download stream (bool): Whether to stream download. Defaults to True. post (bool): Whether to use POST instead of GET. Defaults to False. parameters (Optional[Dict]): Parameters to pa...
[ "Setup", "download", "from", "provided", "url", "returning", "the", "response" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/downloader.py#L175-L201
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/downloader.py
Download.hash_stream
def hash_stream(self, url): # type: (str) -> str """Stream file from url and hash it using MD5. Must call setup method first. Args: url (str): URL to download Returns: str: MD5 hash of file """ md5hash = hashlib.md5() try: fo...
python
def hash_stream(self, url): # type: (str) -> str """Stream file from url and hash it using MD5. Must call setup method first. Args: url (str): URL to download Returns: str: MD5 hash of file """ md5hash = hashlib.md5() try: fo...
[ "def", "hash_stream", "(", "self", ",", "url", ")", ":", "# type: (str) -> str", "md5hash", "=", "hashlib", ".", "md5", "(", ")", "try", ":", "for", "chunk", "in", "self", ".", "response", ".", "iter_content", "(", "chunk_size", "=", "10240", ")", ":", ...
Stream file from url and hash it using MD5. Must call setup method first. Args: url (str): URL to download Returns: str: MD5 hash of file
[ "Stream", "file", "from", "url", "and", "hash", "it", "using", "MD5", ".", "Must", "call", "setup", "method", "first", "." ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/downloader.py#L203-L221
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/downloader.py
Download.stream_file
def stream_file(self, url, folder=None, filename=None, overwrite=False): # type: (str, Optional[str], Optional[str], bool) -> str """Stream file from url and store in provided folder or temporary folder if no folder supplied. Must call setup method first. Args: url (str): UR...
python
def stream_file(self, url, folder=None, filename=None, overwrite=False): # type: (str, Optional[str], Optional[str], bool) -> str """Stream file from url and store in provided folder or temporary folder if no folder supplied. Must call setup method first. Args: url (str): UR...
[ "def", "stream_file", "(", "self", ",", "url", ",", "folder", "=", "None", ",", "filename", "=", "None", ",", "overwrite", "=", "False", ")", ":", "# type: (str, Optional[str], Optional[str], bool) -> str", "path", "=", "self", ".", "get_path_for_url", "(", "url...
Stream file from url and store in provided folder or temporary folder if no folder supplied. Must call setup method first. Args: url (str): URL to download filename (Optional[str]): Filename to use for downloaded file. Defaults to None (derive from the url). folder (...
[ "Stream", "file", "from", "url", "and", "store", "in", "provided", "folder", "or", "temporary", "folder", "if", "no", "folder", "supplied", ".", "Must", "call", "setup", "method", "first", "." ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/downloader.py#L223-L251
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/downloader.py
Download.download_file
def download_file(self, url, folder=None, filename=None, overwrite=False, post=False, parameters=None, timeout=None): # type: (str, Optional[str], Optional[str], bool, bool, Optional[Dict], Optional[float]) -> str """Download file from url and store in provided folder or temporary ...
python
def download_file(self, url, folder=None, filename=None, overwrite=False, post=False, parameters=None, timeout=None): # type: (str, Optional[str], Optional[str], bool, bool, Optional[Dict], Optional[float]) -> str """Download file from url and store in provided folder or temporary ...
[ "def", "download_file", "(", "self", ",", "url", ",", "folder", "=", "None", ",", "filename", "=", "None", ",", "overwrite", "=", "False", ",", "post", "=", "False", ",", "parameters", "=", "None", ",", "timeout", "=", "None", ")", ":", "# type: (str, ...
Download file from url and store in provided folder or temporary folder if no folder supplied Args: url (str): URL to download folder (Optional[str]): Folder to download it to. Defaults to None. filename (Optional[str]): Filename to use for downloaded file. Defaults to None ...
[ "Download", "file", "from", "url", "and", "store", "in", "provided", "folder", "or", "temporary", "folder", "if", "no", "folder", "supplied" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/downloader.py#L253-L272
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/downloader.py
Download.download
def download(self, url, post=False, parameters=None, timeout=None): # type: (str, bool, Optional[Dict], Optional[float]) -> requests.Response """Download url Args: url (str): URL to download post (bool): Whether to use POST instead of GET. Defaults to False. ...
python
def download(self, url, post=False, parameters=None, timeout=None): # type: (str, bool, Optional[Dict], Optional[float]) -> requests.Response """Download url Args: url (str): URL to download post (bool): Whether to use POST instead of GET. Defaults to False. ...
[ "def", "download", "(", "self", ",", "url", ",", "post", "=", "False", ",", "parameters", "=", "None", ",", "timeout", "=", "None", ")", ":", "# type: (str, bool, Optional[Dict], Optional[float]) -> requests.Response", "return", "self", ".", "setup", "(", "url", ...
Download url Args: url (str): URL to download post (bool): Whether to use POST instead of GET. Defaults to False. parameters (Optional[Dict]): Parameters to pass. Defaults to None. timeout (Optional[float]): Timeout for connecting to URL. Defaults to None (no tim...
[ "Download", "url" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/downloader.py#L274-L288
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/downloader.py
Download.get_tabular_stream
def get_tabular_stream(self, url, **kwargs): # type: (str, Any) -> tabulator.Stream """Get Tabulator stream. Args: url (str): URL to download **kwargs: headers (Union[int, List[int], List[str]]): Number of row(s) containing headers or list of headers ...
python
def get_tabular_stream(self, url, **kwargs): # type: (str, Any) -> tabulator.Stream """Get Tabulator stream. Args: url (str): URL to download **kwargs: headers (Union[int, List[int], List[str]]): Number of row(s) containing headers or list of headers ...
[ "def", "get_tabular_stream", "(", "self", ",", "url", ",", "*", "*", "kwargs", ")", ":", "# type: (str, Any) -> tabulator.Stream", "self", ".", "close_response", "(", ")", "file_type", "=", "kwargs", ".", "get", "(", "'file_type'", ")", "if", "file_type", "is"...
Get Tabulator stream. Args: url (str): URL to download **kwargs: headers (Union[int, List[int], List[str]]): Number of row(s) containing headers or list of headers file_type (Optional[str]): Type of file. Defaults to inferring. delimiter (Optional[str...
[ "Get", "Tabulator", "stream", "." ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/downloader.py#L300-L325
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/downloader.py
Download.get_tabular_rows
def get_tabular_rows(self, url, dict_rows=False, **kwargs): # type: (str, bool, Any) -> Iterator[Dict] """Get iterator for reading rows from tabular data. Each row is returned as a dictionary. Args: url (str): URL to download dict_rows (bool): Return dict (requires heade...
python
def get_tabular_rows(self, url, dict_rows=False, **kwargs): # type: (str, bool, Any) -> Iterator[Dict] """Get iterator for reading rows from tabular data. Each row is returned as a dictionary. Args: url (str): URL to download dict_rows (bool): Return dict (requires heade...
[ "def", "get_tabular_rows", "(", "self", ",", "url", ",", "dict_rows", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# type: (str, bool, Any) -> Iterator[Dict]", "return", "self", ".", "get_tabular_stream", "(", "url", ",", "*", "*", "kwargs", ")", ".", "...
Get iterator for reading rows from tabular data. Each row is returned as a dictionary. Args: url (str): URL to download dict_rows (bool): Return dict (requires headers parameter) or list for each row. Defaults to False (list). **kwargs: headers (Union[int, List[i...
[ "Get", "iterator", "for", "reading", "rows", "from", "tabular", "data", ".", "Each", "row", "is", "returned", "as", "a", "dictionary", "." ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/downloader.py#L327-L343
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/downloader.py
Download.download_tabular_key_value
def download_tabular_key_value(self, url, **kwargs): # type: (str, Any) -> Dict """Download 2 column csv from url and return a dictionary of keys (first column) and values (second column) Args: url (str): URL to download **kwargs: headers (Union[int, List[int...
python
def download_tabular_key_value(self, url, **kwargs): # type: (str, Any) -> Dict """Download 2 column csv from url and return a dictionary of keys (first column) and values (second column) Args: url (str): URL to download **kwargs: headers (Union[int, List[int...
[ "def", "download_tabular_key_value", "(", "self", ",", "url", ",", "*", "*", "kwargs", ")", ":", "# type: (str, Any) -> Dict", "output_dict", "=", "dict", "(", ")", "for", "row", "in", "self", ".", "get_tabular_rows", "(", "url", ",", "*", "*", "kwargs", "...
Download 2 column csv from url and return a dictionary of keys (first column) and values (second column) Args: url (str): URL to download **kwargs: headers (Union[int, List[int], List[str]]): Number of row(s) containing headers or list of headers file_type (Optio...
[ "Download", "2", "column", "csv", "from", "url", "and", "return", "a", "dictionary", "of", "keys", "(", "first", "column", ")", "and", "values", "(", "second", "column", ")" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/downloader.py#L345-L365
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/downloader.py
Download.download_tabular_rows_as_dicts
def download_tabular_rows_as_dicts(self, url, headers=1, keycolumn=1, **kwargs): # type: (str, Union[int, List[int], List[str]], int, Any) -> Dict[Dict] """Download multicolumn csv from url and return dictionary where keys are first column and values are dictionaries with keys from column header...
python
def download_tabular_rows_as_dicts(self, url, headers=1, keycolumn=1, **kwargs): # type: (str, Union[int, List[int], List[str]], int, Any) -> Dict[Dict] """Download multicolumn csv from url and return dictionary where keys are first column and values are dictionaries with keys from column header...
[ "def", "download_tabular_rows_as_dicts", "(", "self", ",", "url", ",", "headers", "=", "1", ",", "keycolumn", "=", "1", ",", "*", "*", "kwargs", ")", ":", "# type: (str, Union[int, List[int], List[str]], int, Any) -> Dict[Dict]", "kwargs", "[", "'headers'", "]", "="...
Download multicolumn csv from url and return dictionary where keys are first column and values are dictionaries with keys from column headers and values from columns beneath Args: url (str): URL to download headers (Union[int, List[int], List[str]]): Number of row(s) containing ...
[ "Download", "multicolumn", "csv", "from", "url", "and", "return", "dictionary", "where", "keys", "are", "first", "column", "and", "values", "are", "dictionaries", "with", "keys", "from", "column", "headers", "and", "values", "from", "columns", "beneath" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/downloader.py#L367-L398
train
GaretJax/lancet
lancet/commands/configuration.py
setup
def setup(ctx, force): """Wizard to create the user-level configuration file.""" if os.path.exists(USER_CONFIG) and not force: click.secho( 'An existing configuration file was found at "{}".\n' .format(USER_CONFIG), fg='red', bold=True ) click.secho( ...
python
def setup(ctx, force): """Wizard to create the user-level configuration file.""" if os.path.exists(USER_CONFIG) and not force: click.secho( 'An existing configuration file was found at "{}".\n' .format(USER_CONFIG), fg='red', bold=True ) click.secho( ...
[ "def", "setup", "(", "ctx", ",", "force", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "USER_CONFIG", ")", "and", "not", "force", ":", "click", ".", "secho", "(", "'An existing configuration file was found at \"{}\".\\n'", ".", "format", "(", "USER...
Wizard to create the user-level configuration file.
[ "Wizard", "to", "create", "the", "user", "-", "level", "configuration", "file", "." ]
cf438c5c6166b18ee0dc5ffce55220793019bb95
https://github.com/GaretJax/lancet/blob/cf438c5c6166b18ee0dc5ffce55220793019bb95/lancet/commands/configuration.py#L14-L54
train
GaretJax/lancet
lancet/commands/configuration.py
init
def init(ctx, force): """Wizard to create a project-level configuration file.""" if os.path.exists(PROJECT_CONFIG) and not force: click.secho( 'An existing configuration file was found at "{}".\n' .format(PROJECT_CONFIG), fg='red', bold=True ) click.se...
python
def init(ctx, force): """Wizard to create a project-level configuration file.""" if os.path.exists(PROJECT_CONFIG) and not force: click.secho( 'An existing configuration file was found at "{}".\n' .format(PROJECT_CONFIG), fg='red', bold=True ) click.se...
[ "def", "init", "(", "ctx", ",", "force", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "PROJECT_CONFIG", ")", "and", "not", "force", ":", "click", ".", "secho", "(", "'An existing configuration file was found at \"{}\".\\n'", ".", "format", "(", "PR...
Wizard to create a project-level configuration file.
[ "Wizard", "to", "create", "a", "project", "-", "level", "configuration", "file", "." ]
cf438c5c6166b18ee0dc5ffce55220793019bb95
https://github.com/GaretJax/lancet/blob/cf438c5c6166b18ee0dc5ffce55220793019bb95/lancet/commands/configuration.py#L63-L111
train
GaretJax/lancet
lancet/commands/configuration.py
logout
def logout(lancet, service): """Forget saved passwords for the web services.""" if service: services = [service] else: services = ['tracker', 'harvest'] for service in services: url = lancet.config.get(service, 'url') key = 'lancet+{}'.format(url) username = lanc...
python
def logout(lancet, service): """Forget saved passwords for the web services.""" if service: services = [service] else: services = ['tracker', 'harvest'] for service in services: url = lancet.config.get(service, 'url') key = 'lancet+{}'.format(url) username = lanc...
[ "def", "logout", "(", "lancet", ",", "service", ")", ":", "if", "service", ":", "services", "=", "[", "service", "]", "else", ":", "services", "=", "[", "'tracker'", ",", "'harvest'", "]", "for", "service", "in", "services", ":", "url", "=", "lancet", ...
Forget saved passwords for the web services.
[ "Forget", "saved", "passwords", "for", "the", "web", "services", "." ]
cf438c5c6166b18ee0dc5ffce55220793019bb95
https://github.com/GaretJax/lancet/blob/cf438c5c6166b18ee0dc5ffce55220793019bb95/lancet/commands/configuration.py#L117-L133
train
GaretJax/lancet
lancet/commands/configuration.py
_services
def _services(lancet): """List all currently configured services.""" def get_services(config): for s in config.sections(): if config.has_option(s, 'url'): if config.has_option(s, 'username'): yield s for s in get_services(lancet.config): click...
python
def _services(lancet): """List all currently configured services.""" def get_services(config): for s in config.sections(): if config.has_option(s, 'url'): if config.has_option(s, 'username'): yield s for s in get_services(lancet.config): click...
[ "def", "_services", "(", "lancet", ")", ":", "def", "get_services", "(", "config", ")", ":", "for", "s", "in", "config", ".", "sections", "(", ")", ":", "if", "config", ".", "has_option", "(", "s", ",", "'url'", ")", ":", "if", "config", ".", "has_...
List all currently configured services.
[ "List", "all", "currently", "configured", "services", "." ]
cf438c5c6166b18ee0dc5ffce55220793019bb95
https://github.com/GaretJax/lancet/blob/cf438c5c6166b18ee0dc5ffce55220793019bb95/lancet/commands/configuration.py#L138-L147
train
lucaoflaif/pyCoinMarketCapAPI
coinmarketcapapi/core.py
CoinMarketCapAPI.send_request
def send_request(self, endpoint='ticker', coin_name=None, **kwargs): """: param string 'ticker', it's 'ticker' if we want info about coins, 'global' for global market's info. : param string 'coin_name', specify the name of the coin, if None, we'll retrieve info about all avai...
python
def send_request(self, endpoint='ticker', coin_name=None, **kwargs): """: param string 'ticker', it's 'ticker' if we want info about coins, 'global' for global market's info. : param string 'coin_name', specify the name of the coin, if None, we'll retrieve info about all avai...
[ "def", "send_request", "(", "self", ",", "endpoint", "=", "'ticker'", ",", "coin_name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "built_url", "=", "self", ".", "_make_url", "(", "endpoint", ",", "coin_name", ")", "payload", "=", "dict", "(", "*"...
: param string 'ticker', it's 'ticker' if we want info about coins, 'global' for global market's info. : param string 'coin_name', specify the name of the coin, if None, we'll retrieve info about all available coins.
[ ":", "param", "string", "ticker", "it", "s", "ticker", "if", "we", "want", "info", "about", "coins", "global", "for", "global", "market", "s", "info", ".", ":", "param", "string", "coin_name", "specify", "the", "name", "of", "the", "coin", "if", "None", ...
a6ab1fa57c0610e8abf3a03e9144379bf9e49907
https://github.com/lucaoflaif/pyCoinMarketCapAPI/blob/a6ab1fa57c0610e8abf3a03e9144379bf9e49907/coinmarketcapapi/core.py#L78-L88
train
lucaoflaif/pyCoinMarketCapAPI
coinmarketcapapi/core.py
CoinMarketCapAPI.get_response
def get_response(self, data_type=None): """return json response from APIs converted into python list : param string 'data_type', if it's None it'll return the avaliable cache, if we've both global and ticker data, the function will return 'ticker' data, in that case, data_type...
python
def get_response(self, data_type=None): """return json response from APIs converted into python list : param string 'data_type', if it's None it'll return the avaliable cache, if we've both global and ticker data, the function will return 'ticker' data, in that case, data_type...
[ "def", "get_response", "(", "self", ",", "data_type", "=", "None", ")", ":", "if", "not", "data_type", ":", "return", "self", ".", "cache", ".", "get_response", "(", "r_type", "=", "'ticker'", ")", "or", "self", ".", "cache", ".", "get_response", "(", ...
return json response from APIs converted into python list : param string 'data_type', if it's None it'll return the avaliable cache, if we've both global and ticker data, the function will return 'ticker' data, in that case, data_type should be assigned with 'ticker' or 'global'
[ "return", "json", "response", "from", "APIs", "converted", "into", "python", "list", ":", "param", "string", "data_type", "if", "it", "s", "None", "it", "ll", "return", "the", "avaliable", "cache", "if", "we", "ve", "both", "global", "and", "ticker", "data...
a6ab1fa57c0610e8abf3a03e9144379bf9e49907
https://github.com/lucaoflaif/pyCoinMarketCapAPI/blob/a6ab1fa57c0610e8abf3a03e9144379bf9e49907/coinmarketcapapi/core.py#L90-L100
train
alephdata/languagecodes
languagecodes/__init__.py
iso_639_alpha3
def iso_639_alpha3(code): """Convert a given language identifier into an ISO 639 Part 2 code, such as "eng" or "deu". This will accept language codes in the two- or three- letter format, and some language names. If the given string cannot be converted, ``None`` will be returned. """ code = norma...
python
def iso_639_alpha3(code): """Convert a given language identifier into an ISO 639 Part 2 code, such as "eng" or "deu". This will accept language codes in the two- or three- letter format, and some language names. If the given string cannot be converted, ``None`` will be returned. """ code = norma...
[ "def", "iso_639_alpha3", "(", "code", ")", ":", "code", "=", "normalize_code", "(", "code", ")", "code", "=", "ISO3_MAP", ".", "get", "(", "code", ",", "code", ")", "if", "code", "in", "ISO3_ALL", ":", "return", "code" ]
Convert a given language identifier into an ISO 639 Part 2 code, such as "eng" or "deu". This will accept language codes in the two- or three- letter format, and some language names. If the given string cannot be converted, ``None`` will be returned.
[ "Convert", "a", "given", "language", "identifier", "into", "an", "ISO", "639", "Part", "2", "code", "such", "as", "eng", "or", "deu", ".", "This", "will", "accept", "language", "codes", "in", "the", "two", "-", "or", "three", "-", "letter", "format", "...
123d9e534fd31fcc69f9de68a067f95588c04ea2
https://github.com/alephdata/languagecodes/blob/123d9e534fd31fcc69f9de68a067f95588c04ea2/languagecodes/__init__.py#L8-L17
train
alephdata/languagecodes
languagecodes/__init__.py
list_to_alpha3
def list_to_alpha3(languages, synonyms=True): """Parse all the language codes in a given list into ISO 639 Part 2 codes and optionally expand them with synonyms (i.e. other names for the same language).""" codes = set([]) for language in ensure_list(languages): code = iso_639_alpha3(language...
python
def list_to_alpha3(languages, synonyms=True): """Parse all the language codes in a given list into ISO 639 Part 2 codes and optionally expand them with synonyms (i.e. other names for the same language).""" codes = set([]) for language in ensure_list(languages): code = iso_639_alpha3(language...
[ "def", "list_to_alpha3", "(", "languages", ",", "synonyms", "=", "True", ")", ":", "codes", "=", "set", "(", "[", "]", ")", "for", "language", "in", "ensure_list", "(", "languages", ")", ":", "code", "=", "iso_639_alpha3", "(", "language", ")", "if", "...
Parse all the language codes in a given list into ISO 639 Part 2 codes and optionally expand them with synonyms (i.e. other names for the same language).
[ "Parse", "all", "the", "language", "codes", "in", "a", "given", "list", "into", "ISO", "639", "Part", "2", "codes", "and", "optionally", "expand", "them", "with", "synonyms", "(", "i", ".", "e", ".", "other", "names", "for", "the", "same", "language", ...
123d9e534fd31fcc69f9de68a067f95588c04ea2
https://github.com/alephdata/languagecodes/blob/123d9e534fd31fcc69f9de68a067f95588c04ea2/languagecodes/__init__.py#L29-L41
train
GaretJax/lancet
lancet/commands/repository.py
pull_request
def pull_request(ctx, base_branch, open_pr, stop_timer): """Create a new pull request for this issue.""" lancet = ctx.obj review_status = lancet.config.get("tracker", "review_status") remote_name = lancet.config.get("repository", "remote_name") if not base_branch: base_branch = lancet.conf...
python
def pull_request(ctx, base_branch, open_pr, stop_timer): """Create a new pull request for this issue.""" lancet = ctx.obj review_status = lancet.config.get("tracker", "review_status") remote_name = lancet.config.get("repository", "remote_name") if not base_branch: base_branch = lancet.conf...
[ "def", "pull_request", "(", "ctx", ",", "base_branch", ",", "open_pr", ",", "stop_timer", ")", ":", "lancet", "=", "ctx", ".", "obj", "review_status", "=", "lancet", ".", "config", ".", "get", "(", "\"tracker\"", ",", "\"review_status\"", ")", "remote_name",...
Create a new pull request for this issue.
[ "Create", "a", "new", "pull", "request", "for", "this", "issue", "." ]
cf438c5c6166b18ee0dc5ffce55220793019bb95
https://github.com/GaretJax/lancet/blob/cf438c5c6166b18ee0dc5ffce55220793019bb95/lancet/commands/repository.py#L26-L105
train
GaretJax/lancet
lancet/commands/repository.py
checkout
def checkout(lancet, force, issue): """ Checkout the branch for the given issue. It is an error if the branch does no exist yet. """ issue = get_issue(lancet, issue) # Get the working branch branch = get_branch(lancet, issue, create=force) with taskstatus("Checking out working branch"...
python
def checkout(lancet, force, issue): """ Checkout the branch for the given issue. It is an error if the branch does no exist yet. """ issue = get_issue(lancet, issue) # Get the working branch branch = get_branch(lancet, issue, create=force) with taskstatus("Checking out working branch"...
[ "def", "checkout", "(", "lancet", ",", "force", ",", "issue", ")", ":", "issue", "=", "get_issue", "(", "lancet", ",", "issue", ")", "# Get the working branch", "branch", "=", "get_branch", "(", "lancet", ",", "issue", ",", "create", "=", "force", ")", "...
Checkout the branch for the given issue. It is an error if the branch does no exist yet.
[ "Checkout", "the", "branch", "for", "the", "given", "issue", "." ]
cf438c5c6166b18ee0dc5ffce55220793019bb95
https://github.com/GaretJax/lancet/blob/cf438c5c6166b18ee0dc5ffce55220793019bb95/lancet/commands/repository.py#L117-L132
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/html.py
get_soup
def get_soup(url, downloader=None, user_agent=None, user_agent_config_yaml=None, user_agent_lookup=None, **kwargs): # type: (str, Download, Optional[str], Optional[str], Optional[str], Any) -> BeautifulSoup """ Get BeautifulSoup object for a url. Requires either global user agent to be set or appropriate us...
python
def get_soup(url, downloader=None, user_agent=None, user_agent_config_yaml=None, user_agent_lookup=None, **kwargs): # type: (str, Download, Optional[str], Optional[str], Optional[str], Any) -> BeautifulSoup """ Get BeautifulSoup object for a url. Requires either global user agent to be set or appropriate us...
[ "def", "get_soup", "(", "url", ",", "downloader", "=", "None", ",", "user_agent", "=", "None", ",", "user_agent_config_yaml", "=", "None", ",", "user_agent_lookup", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# type: (str, Download, Optional[str], Optional[st...
Get BeautifulSoup object for a url. Requires either global user agent to be set or appropriate user agent parameter(s) to be completed. Args: url (str): url to read downloader (Download): Download object. Defaults to creating a Download object with given user agent values. user_agent (O...
[ "Get", "BeautifulSoup", "object", "for", "a", "url", ".", "Requires", "either", "global", "user", "agent", "to", "be", "set", "or", "appropriate", "user", "agent", "parameter", "(", "s", ")", "to", "be", "completed", "." ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/html.py#L14-L34
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/html.py
extract_table
def extract_table(tabletag): # type: (Tag) -> List[Dict] """ Extract HTML table as list of dictionaries Args: tabletag (Tag): BeautifulSoup tag Returns: str: Text of tag stripped of leading and trailing whitespace and newlines and with &nbsp replaced with space """ theadta...
python
def extract_table(tabletag): # type: (Tag) -> List[Dict] """ Extract HTML table as list of dictionaries Args: tabletag (Tag): BeautifulSoup tag Returns: str: Text of tag stripped of leading and trailing whitespace and newlines and with &nbsp replaced with space """ theadta...
[ "def", "extract_table", "(", "tabletag", ")", ":", "# type: (Tag) -> List[Dict]", "theadtag", "=", "tabletag", ".", "find_next", "(", "'thead'", ")", "headertags", "=", "theadtag", ".", "find_all", "(", "'th'", ")", "if", "len", "(", "headertags", ")", "==", ...
Extract HTML table as list of dictionaries Args: tabletag (Tag): BeautifulSoup tag Returns: str: Text of tag stripped of leading and trailing whitespace and newlines and with &nbsp replaced with space
[ "Extract", "HTML", "table", "as", "list", "of", "dictionaries" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/html.py#L52-L83
train
agile4you/bottle-neck
bottle_neck/routing.py
Route.wrap_callable
def wrap_callable(cls, uri, methods, callable_obj): """Wraps function-based callable_obj into a `Route` instance, else proxies a `bottle_neck.handlers.BaseHandler` subclass instance. Args: uri (str): The uri relative path. methods (tuple): A tuple of valid method string...
python
def wrap_callable(cls, uri, methods, callable_obj): """Wraps function-based callable_obj into a `Route` instance, else proxies a `bottle_neck.handlers.BaseHandler` subclass instance. Args: uri (str): The uri relative path. methods (tuple): A tuple of valid method string...
[ "def", "wrap_callable", "(", "cls", ",", "uri", ",", "methods", ",", "callable_obj", ")", ":", "if", "isinstance", "(", "callable_obj", ",", "HandlerMeta", ")", ":", "callable_obj", ".", "base_endpoint", "=", "uri", "callable_obj", ".", "is_valid", "=", "Tru...
Wraps function-based callable_obj into a `Route` instance, else proxies a `bottle_neck.handlers.BaseHandler` subclass instance. Args: uri (str): The uri relative path. methods (tuple): A tuple of valid method strings. callable_obj (instance): The callable object. ...
[ "Wraps", "function", "-", "based", "callable_obj", "into", "a", "Route", "instance", "else", "proxies", "a", "bottle_neck", ".", "handlers", ".", "BaseHandler", "subclass", "instance", "." ]
ebc670a4b178255473d68e9b4122ba04e38f4810
https://github.com/agile4you/bottle-neck/blob/ebc670a4b178255473d68e9b4122ba04e38f4810/bottle_neck/routing.py#L38-L61
train
agile4you/bottle-neck
bottle_neck/routing.py
Route.register_app
def register_app(self, app): """Register the route object to a `bottle.Bottle` app instance. Args: app (instance): Returns: Route instance (for chaining purposes) """ app.route(self.uri, methods=self.methods)(self.callable_obj) return self
python
def register_app(self, app): """Register the route object to a `bottle.Bottle` app instance. Args: app (instance): Returns: Route instance (for chaining purposes) """ app.route(self.uri, methods=self.methods)(self.callable_obj) return self
[ "def", "register_app", "(", "self", ",", "app", ")", ":", "app", ".", "route", "(", "self", ".", "uri", ",", "methods", "=", "self", ".", "methods", ")", "(", "self", ".", "callable_obj", ")", "return", "self" ]
Register the route object to a `bottle.Bottle` app instance. Args: app (instance): Returns: Route instance (for chaining purposes)
[ "Register", "the", "route", "object", "to", "a", "bottle", ".", "Bottle", "app", "instance", "." ]
ebc670a4b178255473d68e9b4122ba04e38f4810
https://github.com/agile4you/bottle-neck/blob/ebc670a4b178255473d68e9b4122ba04e38f4810/bottle_neck/routing.py#L73-L84
train
agile4you/bottle-neck
bottle_neck/routing.py
Router.register_handler
def register_handler(self, callable_obj, entrypoint, methods=('GET',)): """Register a handler callable to a specific route. Args: entrypoint (str): The uri relative path. methods (tuple): A tuple of valid method strings. callable_obj (callable): The callable object. ...
python
def register_handler(self, callable_obj, entrypoint, methods=('GET',)): """Register a handler callable to a specific route. Args: entrypoint (str): The uri relative path. methods (tuple): A tuple of valid method strings. callable_obj (callable): The callable object. ...
[ "def", "register_handler", "(", "self", ",", "callable_obj", ",", "entrypoint", ",", "methods", "=", "(", "'GET'", ",", ")", ")", ":", "router_obj", "=", "Route", ".", "wrap_callable", "(", "uri", "=", "entrypoint", ",", "methods", "=", "methods", ",", "...
Register a handler callable to a specific route. Args: entrypoint (str): The uri relative path. methods (tuple): A tuple of valid method strings. callable_obj (callable): The callable object. Returns: The Router instance (for chaining purposes). ...
[ "Register", "a", "handler", "callable", "to", "a", "specific", "route", "." ]
ebc670a4b178255473d68e9b4122ba04e38f4810
https://github.com/agile4you/bottle-neck/blob/ebc670a4b178255473d68e9b4122ba04e38f4810/bottle_neck/routing.py#L98-L128
train
agile4you/bottle-neck
bottle_neck/routing.py
Router.mount
def mount(self, app=None): """Mounts all registered routes to a bottle.py application instance. Args: app (instance): A `bottle.Bottle()` application instance. Returns: The Router instance (for chaining purposes). """ for endpoint in self._routes: ...
python
def mount(self, app=None): """Mounts all registered routes to a bottle.py application instance. Args: app (instance): A `bottle.Bottle()` application instance. Returns: The Router instance (for chaining purposes). """ for endpoint in self._routes: ...
[ "def", "mount", "(", "self", ",", "app", "=", "None", ")", ":", "for", "endpoint", "in", "self", ".", "_routes", ":", "endpoint", ".", "register_app", "(", "app", ")", "return", "self" ]
Mounts all registered routes to a bottle.py application instance. Args: app (instance): A `bottle.Bottle()` application instance. Returns: The Router instance (for chaining purposes).
[ "Mounts", "all", "registered", "routes", "to", "a", "bottle", ".", "py", "application", "instance", "." ]
ebc670a4b178255473d68e9b4122ba04e38f4810
https://github.com/agile4you/bottle-neck/blob/ebc670a4b178255473d68e9b4122ba04e38f4810/bottle_neck/routing.py#L130-L142
train
RockFeng0/rtsf
rtsf/p_applog.py
AppLog.setup_logger
def setup_logger(log_level, log_file=None, logger_name=None): """setup logger @param log_level: debug/info/warning/error/critical @param log_file: log file path @param logger_name: the name of logger, default is 'root' if not specify """ applogger = AppL...
python
def setup_logger(log_level, log_file=None, logger_name=None): """setup logger @param log_level: debug/info/warning/error/critical @param log_file: log file path @param logger_name: the name of logger, default is 'root' if not specify """ applogger = AppL...
[ "def", "setup_logger", "(", "log_level", ",", "log_file", "=", "None", ",", "logger_name", "=", "None", ")", ":", "applogger", "=", "AppLog", "(", "logger_name", ")", "level", "=", "getattr", "(", "logging", ",", "log_level", ".", "upper", "(", ")", ",",...
setup logger @param log_level: debug/info/warning/error/critical @param log_file: log file path @param logger_name: the name of logger, default is 'root' if not specify
[ "setup", "logger" ]
fbc0d57edaeca86418af3942472fcc6d3e9ce591
https://github.com/RockFeng0/rtsf/blob/fbc0d57edaeca86418af3942472fcc6d3e9ce591/rtsf/p_applog.py#L45-L66
train
RockFeng0/rtsf
rtsf/p_applog.py
AppLog._tolog
def _tolog(self,level): """ log with different level """ def wrapper(msg): if self.log_colors: color = self.log_colors[level.upper()] getattr(self.logger, level.lower())(coloring("- {}".format(msg), color)) else: getattr(self...
python
def _tolog(self,level): """ log with different level """ def wrapper(msg): if self.log_colors: color = self.log_colors[level.upper()] getattr(self.logger, level.lower())(coloring("- {}".format(msg), color)) else: getattr(self...
[ "def", "_tolog", "(", "self", ",", "level", ")", ":", "def", "wrapper", "(", "msg", ")", ":", "if", "self", ".", "log_colors", ":", "color", "=", "self", ".", "log_colors", "[", "level", ".", "upper", "(", ")", "]", "getattr", "(", "self", ".", "...
log with different level
[ "log", "with", "different", "level" ]
fbc0d57edaeca86418af3942472fcc6d3e9ce591
https://github.com/RockFeng0/rtsf/blob/fbc0d57edaeca86418af3942472fcc6d3e9ce591/rtsf/p_applog.py#L88-L97
train
agile4you/bottle-neck
bottle_neck/response.py
WSResponse.from_status
def from_status(cls, status_line, msg=None): """Returns a class method from bottle.HTTPError.status_line attribute. Useful for patching `bottle.HTTPError` for web services. Args: status_line (str): bottle.HTTPError.status_line text. msg: The message data for response. ...
python
def from_status(cls, status_line, msg=None): """Returns a class method from bottle.HTTPError.status_line attribute. Useful for patching `bottle.HTTPError` for web services. Args: status_line (str): bottle.HTTPError.status_line text. msg: The message data for response. ...
[ "def", "from_status", "(", "cls", ",", "status_line", ",", "msg", "=", "None", ")", ":", "method", "=", "getattr", "(", "cls", ",", "status_line", ".", "lower", "(", ")", "[", "4", ":", "]", ".", "replace", "(", "' '", ",", "'_'", ")", ")", "retu...
Returns a class method from bottle.HTTPError.status_line attribute. Useful for patching `bottle.HTTPError` for web services. Args: status_line (str): bottle.HTTPError.status_line text. msg: The message data for response. Returns: Class method based on statu...
[ "Returns", "a", "class", "method", "from", "bottle", ".", "HTTPError", ".", "status_line", "attribute", ".", "Useful", "for", "patching", "bottle", ".", "HTTPError", "for", "web", "services", "." ]
ebc670a4b178255473d68e9b4122ba04e38f4810
https://github.com/agile4you/bottle-neck/blob/ebc670a4b178255473d68e9b4122ba04e38f4810/bottle_neck/response.py#L111-L132
train
agile4you/bottle-neck
bottle_neck/response.py
WSResponse.created
def created(cls, data=None): """Shortcut API for HTTP 201 `Created` response. Args: data (object): Response key/value data. Returns: WSResponse Instance. """ if cls.expose_status: # pragma: no cover cls.response.content_type = 'application/j...
python
def created(cls, data=None): """Shortcut API for HTTP 201 `Created` response. Args: data (object): Response key/value data. Returns: WSResponse Instance. """ if cls.expose_status: # pragma: no cover cls.response.content_type = 'application/j...
[ "def", "created", "(", "cls", ",", "data", "=", "None", ")", ":", "if", "cls", ".", "expose_status", ":", "# pragma: no cover", "cls", ".", "response", ".", "content_type", "=", "'application/json'", "cls", ".", "response", ".", "_status_line", "=", "'201 Cr...
Shortcut API for HTTP 201 `Created` response. Args: data (object): Response key/value data. Returns: WSResponse Instance.
[ "Shortcut", "API", "for", "HTTP", "201", "Created", "response", "." ]
ebc670a4b178255473d68e9b4122ba04e38f4810
https://github.com/agile4you/bottle-neck/blob/ebc670a4b178255473d68e9b4122ba04e38f4810/bottle_neck/response.py#L150-L163
train
agile4you/bottle-neck
bottle_neck/response.py
WSResponse.not_modified
def not_modified(cls, errors=None): """Shortcut API for HTTP 304 `Not Modified` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance. """ if cls.expose_status: # pragma: no cover cls.response.content_type = 'a...
python
def not_modified(cls, errors=None): """Shortcut API for HTTP 304 `Not Modified` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance. """ if cls.expose_status: # pragma: no cover cls.response.content_type = 'a...
[ "def", "not_modified", "(", "cls", ",", "errors", "=", "None", ")", ":", "if", "cls", ".", "expose_status", ":", "# pragma: no cover", "cls", ".", "response", ".", "content_type", "=", "'application/json'", "cls", ".", "response", ".", "_status_line", "=", "...
Shortcut API for HTTP 304 `Not Modified` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance.
[ "Shortcut", "API", "for", "HTTP", "304", "Not", "Modified", "response", "." ]
ebc670a4b178255473d68e9b4122ba04e38f4810
https://github.com/agile4you/bottle-neck/blob/ebc670a4b178255473d68e9b4122ba04e38f4810/bottle_neck/response.py#L166-L179
train
agile4you/bottle-neck
bottle_neck/response.py
WSResponse.bad_request
def bad_request(cls, errors=None): """Shortcut API for HTTP 400 `Bad Request` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance. """ if cls.expose_status: # pragma: no cover cls.response.content_type = 'app...
python
def bad_request(cls, errors=None): """Shortcut API for HTTP 400 `Bad Request` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance. """ if cls.expose_status: # pragma: no cover cls.response.content_type = 'app...
[ "def", "bad_request", "(", "cls", ",", "errors", "=", "None", ")", ":", "if", "cls", ".", "expose_status", ":", "# pragma: no cover", "cls", ".", "response", ".", "content_type", "=", "'application/json'", "cls", ".", "response", ".", "_status_line", "=", "'...
Shortcut API for HTTP 400 `Bad Request` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance.
[ "Shortcut", "API", "for", "HTTP", "400", "Bad", "Request", "response", "." ]
ebc670a4b178255473d68e9b4122ba04e38f4810
https://github.com/agile4you/bottle-neck/blob/ebc670a4b178255473d68e9b4122ba04e38f4810/bottle_neck/response.py#L182-L195
train
agile4you/bottle-neck
bottle_neck/response.py
WSResponse.unauthorized
def unauthorized(cls, errors=None): """Shortcut API for HTTP 401 `Unauthorized` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance. """ if cls.expose_status: # pragma: no cover cls.response.content_type = 'a...
python
def unauthorized(cls, errors=None): """Shortcut API for HTTP 401 `Unauthorized` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance. """ if cls.expose_status: # pragma: no cover cls.response.content_type = 'a...
[ "def", "unauthorized", "(", "cls", ",", "errors", "=", "None", ")", ":", "if", "cls", ".", "expose_status", ":", "# pragma: no cover", "cls", ".", "response", ".", "content_type", "=", "'application/json'", "cls", ".", "response", ".", "_status_line", "=", "...
Shortcut API for HTTP 401 `Unauthorized` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance.
[ "Shortcut", "API", "for", "HTTP", "401", "Unauthorized", "response", "." ]
ebc670a4b178255473d68e9b4122ba04e38f4810
https://github.com/agile4you/bottle-neck/blob/ebc670a4b178255473d68e9b4122ba04e38f4810/bottle_neck/response.py#L198-L211
train
agile4you/bottle-neck
bottle_neck/response.py
WSResponse.forbidden
def forbidden(cls, errors=None): """Shortcut API for HTTP 403 `Forbidden` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance. """ if cls.expose_status: # pragma: no cover cls.response.content_type = 'applica...
python
def forbidden(cls, errors=None): """Shortcut API for HTTP 403 `Forbidden` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance. """ if cls.expose_status: # pragma: no cover cls.response.content_type = 'applica...
[ "def", "forbidden", "(", "cls", ",", "errors", "=", "None", ")", ":", "if", "cls", ".", "expose_status", ":", "# pragma: no cover", "cls", ".", "response", ".", "content_type", "=", "'application/json'", "cls", ".", "response", ".", "_status_line", "=", "'40...
Shortcut API for HTTP 403 `Forbidden` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance.
[ "Shortcut", "API", "for", "HTTP", "403", "Forbidden", "response", "." ]
ebc670a4b178255473d68e9b4122ba04e38f4810
https://github.com/agile4you/bottle-neck/blob/ebc670a4b178255473d68e9b4122ba04e38f4810/bottle_neck/response.py#L214-L227
train
agile4you/bottle-neck
bottle_neck/response.py
WSResponse.not_found
def not_found(cls, errors=None): """Shortcut API for HTTP 404 `Not found` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance. """ if cls.expose_status: # pragma: no cover cls.response.content_type = 'applica...
python
def not_found(cls, errors=None): """Shortcut API for HTTP 404 `Not found` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance. """ if cls.expose_status: # pragma: no cover cls.response.content_type = 'applica...
[ "def", "not_found", "(", "cls", ",", "errors", "=", "None", ")", ":", "if", "cls", ".", "expose_status", ":", "# pragma: no cover", "cls", ".", "response", ".", "content_type", "=", "'application/json'", "cls", ".", "response", ".", "_status_line", "=", "'40...
Shortcut API for HTTP 404 `Not found` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance.
[ "Shortcut", "API", "for", "HTTP", "404", "Not", "found", "response", "." ]
ebc670a4b178255473d68e9b4122ba04e38f4810
https://github.com/agile4you/bottle-neck/blob/ebc670a4b178255473d68e9b4122ba04e38f4810/bottle_neck/response.py#L230-L243
train
agile4you/bottle-neck
bottle_neck/response.py
WSResponse.method_not_allowed
def method_not_allowed(cls, errors=None): """Shortcut API for HTTP 405 `Method not allowed` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance. """ if cls.expose_status: # pragma: no cover cls.response.conte...
python
def method_not_allowed(cls, errors=None): """Shortcut API for HTTP 405 `Method not allowed` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance. """ if cls.expose_status: # pragma: no cover cls.response.conte...
[ "def", "method_not_allowed", "(", "cls", ",", "errors", "=", "None", ")", ":", "if", "cls", ".", "expose_status", ":", "# pragma: no cover", "cls", ".", "response", ".", "content_type", "=", "'application/json'", "cls", ".", "response", ".", "_status_line", "=...
Shortcut API for HTTP 405 `Method not allowed` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance.
[ "Shortcut", "API", "for", "HTTP", "405", "Method", "not", "allowed", "response", "." ]
ebc670a4b178255473d68e9b4122ba04e38f4810
https://github.com/agile4you/bottle-neck/blob/ebc670a4b178255473d68e9b4122ba04e38f4810/bottle_neck/response.py#L246-L259
train
agile4you/bottle-neck
bottle_neck/response.py
WSResponse.not_implemented
def not_implemented(cls, errors=None): """Shortcut API for HTTP 501 `Not Implemented` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance. """ if cls.expose_status: # pragma: no cover cls.response.content_typ...
python
def not_implemented(cls, errors=None): """Shortcut API for HTTP 501 `Not Implemented` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance. """ if cls.expose_status: # pragma: no cover cls.response.content_typ...
[ "def", "not_implemented", "(", "cls", ",", "errors", "=", "None", ")", ":", "if", "cls", ".", "expose_status", ":", "# pragma: no cover", "cls", ".", "response", ".", "content_type", "=", "'application/json'", "cls", ".", "response", ".", "_status_line", "=", ...
Shortcut API for HTTP 501 `Not Implemented` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance.
[ "Shortcut", "API", "for", "HTTP", "501", "Not", "Implemented", "response", "." ]
ebc670a4b178255473d68e9b4122ba04e38f4810
https://github.com/agile4you/bottle-neck/blob/ebc670a4b178255473d68e9b4122ba04e38f4810/bottle_neck/response.py#L262-L275
train
agile4you/bottle-neck
bottle_neck/response.py
WSResponse.service_unavailable
def service_unavailable(cls, errors=None): """Shortcut API for HTTP 503 `Service Unavailable` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance. """ if cls.expose_status: # pragma: no cover cls.response.con...
python
def service_unavailable(cls, errors=None): """Shortcut API for HTTP 503 `Service Unavailable` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance. """ if cls.expose_status: # pragma: no cover cls.response.con...
[ "def", "service_unavailable", "(", "cls", ",", "errors", "=", "None", ")", ":", "if", "cls", ".", "expose_status", ":", "# pragma: no cover", "cls", ".", "response", ".", "content_type", "=", "'application/json'", "cls", ".", "response", ".", "_status_line", "...
Shortcut API for HTTP 503 `Service Unavailable` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance.
[ "Shortcut", "API", "for", "HTTP", "503", "Service", "Unavailable", "response", "." ]
ebc670a4b178255473d68e9b4122ba04e38f4810
https://github.com/agile4you/bottle-neck/blob/ebc670a4b178255473d68e9b4122ba04e38f4810/bottle_neck/response.py#L278-L291
train
agile4you/bottle-neck
bottle_neck/response.py
WSResponse.to_json
def to_json(self): """Short cut for JSON response service data. Returns: Dict that implements JSON interface. """ web_resp = collections.OrderedDict() web_resp['status_code'] = self.status_code web_resp['status_text'] = dict(HTTP_CODES).get(self.status_code...
python
def to_json(self): """Short cut for JSON response service data. Returns: Dict that implements JSON interface. """ web_resp = collections.OrderedDict() web_resp['status_code'] = self.status_code web_resp['status_text'] = dict(HTTP_CODES).get(self.status_code...
[ "def", "to_json", "(", "self", ")", ":", "web_resp", "=", "collections", ".", "OrderedDict", "(", ")", "web_resp", "[", "'status_code'", "]", "=", "self", ".", "status_code", "web_resp", "[", "'status_text'", "]", "=", "dict", "(", "HTTP_CODES", ")", ".", ...
Short cut for JSON response service data. Returns: Dict that implements JSON interface.
[ "Short", "cut", "for", "JSON", "response", "service", "data", "." ]
ebc670a4b178255473d68e9b4122ba04e38f4810
https://github.com/agile4you/bottle-neck/blob/ebc670a4b178255473d68e9b4122ba04e38f4810/bottle_neck/response.py#L294-L308
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/easy_logging.py
setup_logging
def setup_logging(**kwargs): # type: (Any) -> None """Setup logging configuration Args: **kwargs: See below logging_config_dict (dict): Logging configuration dictionary OR logging_config_json (str): Path to JSON Logging configuration OR logging_config_yaml (str): Path to YAM...
python
def setup_logging(**kwargs): # type: (Any) -> None """Setup logging configuration Args: **kwargs: See below logging_config_dict (dict): Logging configuration dictionary OR logging_config_json (str): Path to JSON Logging configuration OR logging_config_yaml (str): Path to YAM...
[ "def", "setup_logging", "(", "*", "*", "kwargs", ")", ":", "# type: (Any) -> None", "smtp_config_found", "=", "False", "smtp_config_dict", "=", "kwargs", ".", "get", "(", "'smtp_config_dict'", ",", "None", ")", "if", "smtp_config_dict", ":", "smtp_config_found", "...
Setup logging configuration Args: **kwargs: See below logging_config_dict (dict): Logging configuration dictionary OR logging_config_json (str): Path to JSON Logging configuration OR logging_config_yaml (str): Path to YAML Logging configuration. Defaults to internal logging_configur...
[ "Setup", "logging", "configuration" ]
9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/easy_logging.py#L16-L99
train
meraki-analytics/merakicommons
merakicommons/container.py
SearchableList._search_generator
def _search_generator(self, item: Any, reverse: bool = False) -> Generator[Any, None, None]: """A helper method for `self.search` that returns a generator rather than a list.""" results = 0 for _, x in self.enumerate(item, reverse=reverse): yield x results += 1 if...
python
def _search_generator(self, item: Any, reverse: bool = False) -> Generator[Any, None, None]: """A helper method for `self.search` that returns a generator rather than a list.""" results = 0 for _, x in self.enumerate(item, reverse=reverse): yield x results += 1 if...
[ "def", "_search_generator", "(", "self", ",", "item", ":", "Any", ",", "reverse", ":", "bool", "=", "False", ")", "->", "Generator", "[", "Any", ",", "None", ",", "None", "]", ":", "results", "=", "0", "for", "_", ",", "x", "in", "self", ".", "en...
A helper method for `self.search` that returns a generator rather than a list.
[ "A", "helper", "method", "for", "self", ".", "search", "that", "returns", "a", "generator", "rather", "than", "a", "list", "." ]
d0c8ade8f4619a34ca488336c44722ed1aeaf7ef
https://github.com/meraki-analytics/merakicommons/blob/d0c8ade8f4619a34ca488336c44722ed1aeaf7ef/merakicommons/container.py#L108-L115
train
meraki-analytics/merakicommons
merakicommons/container.py
SearchableSet._search_generator
def _search_generator(self, item: Any) -> Generator[Any, None, None]: """A helper method for `self.search` that returns a generator rather than a list.""" results = 0 for x in self.enumerate(item): yield x results += 1 if results == 0: raise SearchErro...
python
def _search_generator(self, item: Any) -> Generator[Any, None, None]: """A helper method for `self.search` that returns a generator rather than a list.""" results = 0 for x in self.enumerate(item): yield x results += 1 if results == 0: raise SearchErro...
[ "def", "_search_generator", "(", "self", ",", "item", ":", "Any", ")", "->", "Generator", "[", "Any", ",", "None", ",", "None", "]", ":", "results", "=", "0", "for", "x", "in", "self", ".", "enumerate", "(", "item", ")", ":", "yield", "x", "results...
A helper method for `self.search` that returns a generator rather than a list.
[ "A", "helper", "method", "for", "self", ".", "search", "that", "returns", "a", "generator", "rather", "than", "a", "list", "." ]
d0c8ade8f4619a34ca488336c44722ed1aeaf7ef
https://github.com/meraki-analytics/merakicommons/blob/d0c8ade8f4619a34ca488336c44722ed1aeaf7ef/merakicommons/container.py#L175-L182
train
meraki-analytics/merakicommons
merakicommons/container.py
SearchableDictionary._search_generator
def _search_generator(self, item: Any) -> Generator[Tuple[Any, Any], None, None]: """A helper method for `self.search` that returns a generator rather than a list.""" results = 0 for key, value in self.enumerate(item): yield key, value results += 1 if results == 0...
python
def _search_generator(self, item: Any) -> Generator[Tuple[Any, Any], None, None]: """A helper method for `self.search` that returns a generator rather than a list.""" results = 0 for key, value in self.enumerate(item): yield key, value results += 1 if results == 0...
[ "def", "_search_generator", "(", "self", ",", "item", ":", "Any", ")", "->", "Generator", "[", "Tuple", "[", "Any", ",", "Any", "]", ",", "None", ",", "None", "]", ":", "results", "=", "0", "for", "key", ",", "value", "in", "self", ".", "enumerate"...
A helper method for `self.search` that returns a generator rather than a list.
[ "A", "helper", "method", "for", "self", ".", "search", "that", "returns", "a", "generator", "rather", "than", "a", "list", "." ]
d0c8ade8f4619a34ca488336c44722ed1aeaf7ef
https://github.com/meraki-analytics/merakicommons/blob/d0c8ade8f4619a34ca488336c44722ed1aeaf7ef/merakicommons/container.py#L243-L250
train
IzunaDevs/SnekChek
snekchek/config_gen.py
ask_bool
def ask_bool(question: str, default: bool = True) -> bool: """Asks a question yes no style""" default_q = "Y/n" if default else "y/N" answer = input("{0} [{1}]: ".format(question, default_q)) lower = answer.lower() if not lower: return default return lower == "y"
python
def ask_bool(question: str, default: bool = True) -> bool: """Asks a question yes no style""" default_q = "Y/n" if default else "y/N" answer = input("{0} [{1}]: ".format(question, default_q)) lower = answer.lower() if not lower: return default return lower == "y"
[ "def", "ask_bool", "(", "question", ":", "str", ",", "default", ":", "bool", "=", "True", ")", "->", "bool", ":", "default_q", "=", "\"Y/n\"", "if", "default", "else", "\"y/N\"", "answer", "=", "input", "(", "\"{0} [{1}]: \"", ".", "format", "(", "questi...
Asks a question yes no style
[ "Asks", "a", "question", "yes", "no", "style" ]
fdb01bdf1ec8e79d9aae2a11d96bfb27e53a97a9
https://github.com/IzunaDevs/SnekChek/blob/fdb01bdf1ec8e79d9aae2a11d96bfb27e53a97a9/snekchek/config_gen.py#L87-L94
train
IzunaDevs/SnekChek
snekchek/config_gen.py
ask_int
def ask_int(question: str, default: int = None) -> int: """Asks for a number in a question""" default_q = " [default: {0}]: ".format( default) if default is not None else "" answer = input("{0} [{1}]: ".format(question, default_q)) if not answer: if default is None: print("N...
python
def ask_int(question: str, default: int = None) -> int: """Asks for a number in a question""" default_q = " [default: {0}]: ".format( default) if default is not None else "" answer = input("{0} [{1}]: ".format(question, default_q)) if not answer: if default is None: print("N...
[ "def", "ask_int", "(", "question", ":", "str", ",", "default", ":", "int", "=", "None", ")", "->", "int", ":", "default_q", "=", "\" [default: {0}]: \"", ".", "format", "(", "default", ")", "if", "default", "is", "not", "None", "else", "\"\"", "answer", ...
Asks for a number in a question
[ "Asks", "for", "a", "number", "in", "a", "question" ]
fdb01bdf1ec8e79d9aae2a11d96bfb27e53a97a9
https://github.com/IzunaDevs/SnekChek/blob/fdb01bdf1ec8e79d9aae2a11d96bfb27e53a97a9/snekchek/config_gen.py#L97-L113
train
IzunaDevs/SnekChek
snekchek/config_gen.py
ask_path
def ask_path(question: str, default: str = None) -> str: """Asks for a path""" default_q = " [default: {0}]: ".format( default) if default is not None else "" answer = input("{0} [{1}]: ".format(question, default_q)) if answer == "": return default if os.path.isdir(answer): ...
python
def ask_path(question: str, default: str = None) -> str: """Asks for a path""" default_q = " [default: {0}]: ".format( default) if default is not None else "" answer = input("{0} [{1}]: ".format(question, default_q)) if answer == "": return default if os.path.isdir(answer): ...
[ "def", "ask_path", "(", "question", ":", "str", ",", "default", ":", "str", "=", "None", ")", "->", "str", ":", "default_q", "=", "\" [default: {0}]: \"", ".", "format", "(", "default", ")", "if", "default", "is", "not", "None", "else", "\"\"", "answer",...
Asks for a path
[ "Asks", "for", "a", "path" ]
fdb01bdf1ec8e79d9aae2a11d96bfb27e53a97a9
https://github.com/IzunaDevs/SnekChek/blob/fdb01bdf1ec8e79d9aae2a11d96bfb27e53a97a9/snekchek/config_gen.py#L116-L130
train
IzunaDevs/SnekChek
snekchek/config_gen.py
ask_list
def ask_list(question: str, default: list = None) -> list: """Asks for a comma seperated list of strings""" default_q = " [default: {0}]: ".format( ",".join(default)) if default is not None else "" answer = input("{0} [{1}]: ".format(question, default_q)) if answer == "": return default...
python
def ask_list(question: str, default: list = None) -> list: """Asks for a comma seperated list of strings""" default_q = " [default: {0}]: ".format( ",".join(default)) if default is not None else "" answer = input("{0} [{1}]: ".format(question, default_q)) if answer == "": return default...
[ "def", "ask_list", "(", "question", ":", "str", ",", "default", ":", "list", "=", "None", ")", "->", "list", ":", "default_q", "=", "\" [default: {0}]: \"", ".", "format", "(", "\",\"", ".", "join", "(", "default", ")", ")", "if", "default", "is", "not...
Asks for a comma seperated list of strings
[ "Asks", "for", "a", "comma", "seperated", "list", "of", "strings" ]
fdb01bdf1ec8e79d9aae2a11d96bfb27e53a97a9
https://github.com/IzunaDevs/SnekChek/blob/fdb01bdf1ec8e79d9aae2a11d96bfb27e53a97a9/snekchek/config_gen.py#L133-L141
train
IzunaDevs/SnekChek
snekchek/config_gen.py
ask_str
def ask_str(question: str, default: str = None): """Asks for a simple string""" default_q = " [default: {0}]: ".format( default) if default is not None else "" answer = input("{0} [{1}]: ".format(question, default_q)) if answer == "": return default return answer
python
def ask_str(question: str, default: str = None): """Asks for a simple string""" default_q = " [default: {0}]: ".format( default) if default is not None else "" answer = input("{0} [{1}]: ".format(question, default_q)) if answer == "": return default return answer
[ "def", "ask_str", "(", "question", ":", "str", ",", "default", ":", "str", "=", "None", ")", ":", "default_q", "=", "\" [default: {0}]: \"", ".", "format", "(", "default", ")", "if", "default", "is", "not", "None", "else", "\"\"", "answer", "=", "input",...
Asks for a simple string
[ "Asks", "for", "a", "simple", "string" ]
fdb01bdf1ec8e79d9aae2a11d96bfb27e53a97a9
https://github.com/IzunaDevs/SnekChek/blob/fdb01bdf1ec8e79d9aae2a11d96bfb27e53a97a9/snekchek/config_gen.py#L144-L152
train
IzunaDevs/SnekChek
snekchek/config_gen.py
ConfigGenerator.get_tools
def get_tools(self) -> list: """Lets the user enter the tools he want to use""" tools = "flake8,pylint,vulture,pyroma,isort,yapf,safety,dodgy,pytest,pypi".split( ",") print("Available tools: {0}".format(",".join(tools))) answer = ask_list("What tools would you like to use?", ...
python
def get_tools(self) -> list: """Lets the user enter the tools he want to use""" tools = "flake8,pylint,vulture,pyroma,isort,yapf,safety,dodgy,pytest,pypi".split( ",") print("Available tools: {0}".format(",".join(tools))) answer = ask_list("What tools would you like to use?", ...
[ "def", "get_tools", "(", "self", ")", "->", "list", ":", "tools", "=", "\"flake8,pylint,vulture,pyroma,isort,yapf,safety,dodgy,pytest,pypi\"", ".", "split", "(", "\",\"", ")", "print", "(", "\"Available tools: {0}\"", ".", "format", "(", "\",\"", ".", "join", "(", ...
Lets the user enter the tools he want to use
[ "Lets", "the", "user", "enter", "the", "tools", "he", "want", "to", "use" ]
fdb01bdf1ec8e79d9aae2a11d96bfb27e53a97a9
https://github.com/IzunaDevs/SnekChek/blob/fdb01bdf1ec8e79d9aae2a11d96bfb27e53a97a9/snekchek/config_gen.py#L15-L26
train
IzunaDevs/SnekChek
snekchek/config_gen.py
ConfigGenerator.main
def main(self) -> None: """The main function for generating the config file""" path = ask_path("where should the config be stored?", ".snekrc") conf = configobj.ConfigObj() tools = self.get_tools() for tool in tools: conf[tool] = getattr(self, tool)() # pylint: dis...
python
def main(self) -> None: """The main function for generating the config file""" path = ask_path("where should the config be stored?", ".snekrc") conf = configobj.ConfigObj() tools = self.get_tools() for tool in tools: conf[tool] = getattr(self, tool)() # pylint: dis...
[ "def", "main", "(", "self", ")", "->", "None", ":", "path", "=", "ask_path", "(", "\"where should the config be stored?\"", ",", "\".snekrc\"", ")", "conf", "=", "configobj", ".", "ConfigObj", "(", ")", "tools", "=", "self", ".", "get_tools", "(", ")", "fo...
The main function for generating the config file
[ "The", "main", "function", "for", "generating", "the", "config", "file" ]
fdb01bdf1ec8e79d9aae2a11d96bfb27e53a97a9
https://github.com/IzunaDevs/SnekChek/blob/fdb01bdf1ec8e79d9aae2a11d96bfb27e53a97a9/snekchek/config_gen.py#L68-L84
train
agile4you/bottle-neck
bottle_neck/webapi.py
paginator
def paginator(limit, offset, record_count, base_uri, page_nav_tpl='&limit={}&offset={}'): """Compute pagination info for collection filtering. Args: limit (int): Collection filter limit. offset (int): Collection filter offset. record_count (int): Collection filter total record count. ...
python
def paginator(limit, offset, record_count, base_uri, page_nav_tpl='&limit={}&offset={}'): """Compute pagination info for collection filtering. Args: limit (int): Collection filter limit. offset (int): Collection filter offset. record_count (int): Collection filter total record count. ...
[ "def", "paginator", "(", "limit", ",", "offset", ",", "record_count", ",", "base_uri", ",", "page_nav_tpl", "=", "'&limit={}&offset={}'", ")", ":", "total_pages", "=", "int", "(", "math", ".", "ceil", "(", "record_count", "/", "limit", ")", ")", "next_cond",...
Compute pagination info for collection filtering. Args: limit (int): Collection filter limit. offset (int): Collection filter offset. record_count (int): Collection filter total record count. base_uri (str): Collection filter base uri (without limit, offset) page_nav_tpl (st...
[ "Compute", "pagination", "info", "for", "collection", "filtering", "." ]
ebc670a4b178255473d68e9b4122ba04e38f4810
https://github.com/agile4you/bottle-neck/blob/ebc670a4b178255473d68e9b4122ba04e38f4810/bottle_neck/webapi.py#L36-L64
train
amcat/amcatclient
amcatclient/amcatclient.py
serialize
def serialize(obj): """JSON serializer that accepts datetime & date""" from datetime import datetime, date, time if isinstance(obj, date) and not isinstance(obj, datetime): obj = datetime.combine(obj, time.min) if isinstance(obj, datetime): return obj.isoformat()
python
def serialize(obj): """JSON serializer that accepts datetime & date""" from datetime import datetime, date, time if isinstance(obj, date) and not isinstance(obj, datetime): obj = datetime.combine(obj, time.min) if isinstance(obj, datetime): return obj.isoformat()
[ "def", "serialize", "(", "obj", ")", ":", "from", "datetime", "import", "datetime", ",", "date", ",", "time", "if", "isinstance", "(", "obj", ",", "date", ")", "and", "not", "isinstance", "(", "obj", ",", "datetime", ")", ":", "obj", "=", "datetime", ...
JSON serializer that accepts datetime & date
[ "JSON", "serializer", "that", "accepts", "datetime", "&", "date" ]
bda525f7ace0c26a09fa56d2baf7550f639e62ee
https://github.com/amcat/amcatclient/blob/bda525f7ace0c26a09fa56d2baf7550f639e62ee/amcatclient/amcatclient.py#L48-L54
train
amcat/amcatclient
amcatclient/amcatclient.py
check
def check(response, expected_status=200, url=None): """ Check whether the status code of the response equals expected_status and raise an APIError otherwise. @param url: The url of the response (for error messages). Defaults to response.url @param json: if True, return r.json(), othe...
python
def check(response, expected_status=200, url=None): """ Check whether the status code of the response equals expected_status and raise an APIError otherwise. @param url: The url of the response (for error messages). Defaults to response.url @param json: if True, return r.json(), othe...
[ "def", "check", "(", "response", ",", "expected_status", "=", "200", ",", "url", "=", "None", ")", ":", "if", "response", ".", "status_code", "!=", "expected_status", ":", "if", "url", "is", "None", ":", "url", "=", "response", ".", "url", "try", ":", ...
Check whether the status code of the response equals expected_status and raise an APIError otherwise. @param url: The url of the response (for error messages). Defaults to response.url @param json: if True, return r.json(), otherwise return r.text
[ "Check", "whether", "the", "status", "code", "of", "the", "response", "equals", "expected_status", "and", "raise", "an", "APIError", "otherwise", "." ]
bda525f7ace0c26a09fa56d2baf7550f639e62ee
https://github.com/amcat/amcatclient/blob/bda525f7ace0c26a09fa56d2baf7550f639e62ee/amcatclient/amcatclient.py#L94-L132
train
amcat/amcatclient
amcatclient/amcatclient.py
AmcatAPI._get_auth
def _get_auth(self, user=None, password=None): """ Get the authentication info for the current user, from 1) a ~/.amcatauth file, which should be a csv file containing host, username, password entries 2) the AMCAT_USER (or USER) and AMCAT_PASSWORD environment variables ...
python
def _get_auth(self, user=None, password=None): """ Get the authentication info for the current user, from 1) a ~/.amcatauth file, which should be a csv file containing host, username, password entries 2) the AMCAT_USER (or USER) and AMCAT_PASSWORD environment variables ...
[ "def", "_get_auth", "(", "self", ",", "user", "=", "None", ",", "password", "=", "None", ")", ":", "fn", "=", "os", ".", "path", ".", "expanduser", "(", "AUTH_FILE", ")", "if", "os", ".", "path", ".", "exists", "(", "fn", ")", ":", "for", "i", ...
Get the authentication info for the current user, from 1) a ~/.amcatauth file, which should be a csv file containing host, username, password entries 2) the AMCAT_USER (or USER) and AMCAT_PASSWORD environment variables
[ "Get", "the", "authentication", "info", "for", "the", "current", "user", "from", "1", ")", "a", "~", "/", ".", "amcatauth", "file", "which", "should", "be", "a", "csv", "file", "containing", "host", "username", "password", "entries", "2", ")", "the", "AM...
bda525f7ace0c26a09fa56d2baf7550f639e62ee
https://github.com/amcat/amcatclient/blob/bda525f7ace0c26a09fa56d2baf7550f639e62ee/amcatclient/amcatclient.py#L170-L195
train
amcat/amcatclient
amcatclient/amcatclient.py
AmcatAPI.request
def request(self, url, method="get", format="json", data=None, expected_status=None, headers=None, use_xpost=True, **options): """ Make an HTTP request to the given relative URL with the host, user, and password information. Returns the deserialized json if successful, an...
python
def request(self, url, method="get", format="json", data=None, expected_status=None, headers=None, use_xpost=True, **options): """ Make an HTTP request to the given relative URL with the host, user, and password information. Returns the deserialized json if successful, an...
[ "def", "request", "(", "self", ",", "url", ",", "method", "=", "\"get\"", ",", "format", "=", "\"json\"", ",", "data", "=", "None", ",", "expected_status", "=", "None", ",", "headers", "=", "None", ",", "use_xpost", "=", "True", ",", "*", "*", "optio...
Make an HTTP request to the given relative URL with the host, user, and password information. Returns the deserialized json if successful, and raises an exception otherwise
[ "Make", "an", "HTTP", "request", "to", "the", "given", "relative", "URL", "with", "the", "host", "user", "and", "password", "information", ".", "Returns", "the", "deserialized", "json", "if", "successful", "and", "raises", "an", "exception", "otherwise" ]
bda525f7ace0c26a09fa56d2baf7550f639e62ee
https://github.com/amcat/amcatclient/blob/bda525f7ace0c26a09fa56d2baf7550f639e62ee/amcatclient/amcatclient.py#L211-L250
train
amcat/amcatclient
amcatclient/amcatclient.py
AmcatAPI.get_pages
def get_pages(self, url, page=1, page_size=100, yield_pages=False, **filters): """ Get all pages at url, yielding individual results :param url: the url to fetch :param page: start from this page :param page_size: results per page :param yield_pages: yield whole pages rat...
python
def get_pages(self, url, page=1, page_size=100, yield_pages=False, **filters): """ Get all pages at url, yielding individual results :param url: the url to fetch :param page: start from this page :param page_size: results per page :param yield_pages: yield whole pages rat...
[ "def", "get_pages", "(", "self", ",", "url", ",", "page", "=", "1", ",", "page_size", "=", "100", ",", "yield_pages", "=", "False", ",", "*", "*", "filters", ")", ":", "n", "=", "0", "for", "page", "in", "itertools", ".", "count", "(", "page", ")...
Get all pages at url, yielding individual results :param url: the url to fetch :param page: start from this page :param page_size: results per page :param yield_pages: yield whole pages rather than individual results :param filters: additional filters :return: a generator...
[ "Get", "all", "pages", "at", "url", "yielding", "individual", "results", ":", "param", "url", ":", "the", "url", "to", "fetch", ":", "param", "page", ":", "start", "from", "this", "page", ":", "param", "page_size", ":", "results", "per", "page", ":", "...
bda525f7ace0c26a09fa56d2baf7550f639e62ee
https://github.com/amcat/amcatclient/blob/bda525f7ace0c26a09fa56d2baf7550f639e62ee/amcatclient/amcatclient.py#L254-L275
train
amcat/amcatclient
amcatclient/amcatclient.py
AmcatAPI.get_scroll
def get_scroll(self, url, page_size=100, yield_pages=False, **filters): """ Scroll through the resource at url and yield the individual results :param url: url to scroll through :param page_size: results per page :param yield_pages: yield whole pages rather than individual result...
python
def get_scroll(self, url, page_size=100, yield_pages=False, **filters): """ Scroll through the resource at url and yield the individual results :param url: url to scroll through :param page_size: results per page :param yield_pages: yield whole pages rather than individual result...
[ "def", "get_scroll", "(", "self", ",", "url", ",", "page_size", "=", "100", ",", "yield_pages", "=", "False", ",", "*", "*", "filters", ")", ":", "n", "=", "0", "options", "=", "dict", "(", "page_size", "=", "page_size", ",", "*", "*", "filters", "...
Scroll through the resource at url and yield the individual results :param url: url to scroll through :param page_size: results per page :param yield_pages: yield whole pages rather than individual results :param filters: Additional filters :return: a generator of objects (dicts)...
[ "Scroll", "through", "the", "resource", "at", "url", "and", "yield", "the", "individual", "results", ":", "param", "url", ":", "url", "to", "scroll", "through", ":", "param", "page_size", ":", "results", "per", "page", ":", "param", "yield_pages", ":", "yi...
bda525f7ace0c26a09fa56d2baf7550f639e62ee
https://github.com/amcat/amcatclient/blob/bda525f7ace0c26a09fa56d2baf7550f639e62ee/amcatclient/amcatclient.py#L277-L301
train
amcat/amcatclient
amcatclient/amcatclient.py
AmcatAPI.get_status
def get_status(self): """Get the AmCAT status page""" url = URL.status.format(**locals()) return self.get_request(url)
python
def get_status(self): """Get the AmCAT status page""" url = URL.status.format(**locals()) return self.get_request(url)
[ "def", "get_status", "(", "self", ")", ":", "url", "=", "URL", ".", "status", ".", "format", "(", "*", "*", "locals", "(", ")", ")", "return", "self", ".", "get_request", "(", "url", ")" ]
Get the AmCAT status page
[ "Get", "the", "AmCAT", "status", "page" ]
bda525f7ace0c26a09fa56d2baf7550f639e62ee
https://github.com/amcat/amcatclient/blob/bda525f7ace0c26a09fa56d2baf7550f639e62ee/amcatclient/amcatclient.py#L303-L306
train
amcat/amcatclient
amcatclient/amcatclient.py
AmcatAPI.aggregate
def aggregate(self, **filters): """Conduct an aggregate query""" url = URL.aggregate.format(**locals()) return self.get_pages(url, **filters)
python
def aggregate(self, **filters): """Conduct an aggregate query""" url = URL.aggregate.format(**locals()) return self.get_pages(url, **filters)
[ "def", "aggregate", "(", "self", ",", "*", "*", "filters", ")", ":", "url", "=", "URL", ".", "aggregate", ".", "format", "(", "*", "*", "locals", "(", ")", ")", "return", "self", ".", "get_pages", "(", "url", ",", "*", "*", "filters", ")" ]
Conduct an aggregate query
[ "Conduct", "an", "aggregate", "query" ]
bda525f7ace0c26a09fa56d2baf7550f639e62ee
https://github.com/amcat/amcatclient/blob/bda525f7ace0c26a09fa56d2baf7550f639e62ee/amcatclient/amcatclient.py#L308-L311
train
amcat/amcatclient
amcatclient/amcatclient.py
AmcatAPI.list_sets
def list_sets(self, project, **filters): """List the articlesets in a project""" url = URL.articlesets.format(**locals()) return self.get_pages(url, **filters)
python
def list_sets(self, project, **filters): """List the articlesets in a project""" url = URL.articlesets.format(**locals()) return self.get_pages(url, **filters)
[ "def", "list_sets", "(", "self", ",", "project", ",", "*", "*", "filters", ")", ":", "url", "=", "URL", ".", "articlesets", ".", "format", "(", "*", "*", "locals", "(", ")", ")", "return", "self", ".", "get_pages", "(", "url", ",", "*", "*", "fil...
List the articlesets in a project
[ "List", "the", "articlesets", "in", "a", "project" ]
bda525f7ace0c26a09fa56d2baf7550f639e62ee
https://github.com/amcat/amcatclient/blob/bda525f7ace0c26a09fa56d2baf7550f639e62ee/amcatclient/amcatclient.py#L313-L316
train
amcat/amcatclient
amcatclient/amcatclient.py
AmcatAPI.get_set
def get_set(self, project, articleset, **filters): """List the articlesets in a project""" url = URL.articleset.format(**locals()) return self.request(url, **filters)
python
def get_set(self, project, articleset, **filters): """List the articlesets in a project""" url = URL.articleset.format(**locals()) return self.request(url, **filters)
[ "def", "get_set", "(", "self", ",", "project", ",", "articleset", ",", "*", "*", "filters", ")", ":", "url", "=", "URL", ".", "articleset", ".", "format", "(", "*", "*", "locals", "(", ")", ")", "return", "self", ".", "request", "(", "url", ",", ...
List the articlesets in a project
[ "List", "the", "articlesets", "in", "a", "project" ]
bda525f7ace0c26a09fa56d2baf7550f639e62ee
https://github.com/amcat/amcatclient/blob/bda525f7ace0c26a09fa56d2baf7550f639e62ee/amcatclient/amcatclient.py#L318-L321
train
amcat/amcatclient
amcatclient/amcatclient.py
AmcatAPI.list_articles
def list_articles(self, project, articleset, page=1, **filters): """List the articles in a set""" url = URL.article.format(**locals()) return self.get_pages(url, page=page, **filters)
python
def list_articles(self, project, articleset, page=1, **filters): """List the articles in a set""" url = URL.article.format(**locals()) return self.get_pages(url, page=page, **filters)
[ "def", "list_articles", "(", "self", ",", "project", ",", "articleset", ",", "page", "=", "1", ",", "*", "*", "filters", ")", ":", "url", "=", "URL", ".", "article", ".", "format", "(", "*", "*", "locals", "(", ")", ")", "return", "self", ".", "g...
List the articles in a set
[ "List", "the", "articles", "in", "a", "set" ]
bda525f7ace0c26a09fa56d2baf7550f639e62ee
https://github.com/amcat/amcatclient/blob/bda525f7ace0c26a09fa56d2baf7550f639e62ee/amcatclient/amcatclient.py#L323-L326
train
amcat/amcatclient
amcatclient/amcatclient.py
AmcatAPI.create_set
def create_set(self, project, json_data=None, **options): """ Create a new article set. Provide the needed arguments using post_data or with key-value pairs """ url = URL.articlesets.format(**locals()) if json_data is None: # form encoded request r...
python
def create_set(self, project, json_data=None, **options): """ Create a new article set. Provide the needed arguments using post_data or with key-value pairs """ url = URL.articlesets.format(**locals()) if json_data is None: # form encoded request r...
[ "def", "create_set", "(", "self", ",", "project", ",", "json_data", "=", "None", ",", "*", "*", "options", ")", ":", "url", "=", "URL", ".", "articlesets", ".", "format", "(", "*", "*", "locals", "(", ")", ")", "if", "json_data", "is", "None", ":",...
Create a new article set. Provide the needed arguments using post_data or with key-value pairs
[ "Create", "a", "new", "article", "set", ".", "Provide", "the", "needed", "arguments", "using", "post_data", "or", "with", "key", "-", "value", "pairs" ]
bda525f7ace0c26a09fa56d2baf7550f639e62ee
https://github.com/amcat/amcatclient/blob/bda525f7ace0c26a09fa56d2baf7550f639e62ee/amcatclient/amcatclient.py#L333-L347
train
amcat/amcatclient
amcatclient/amcatclient.py
AmcatAPI.create_articles
def create_articles(self, project, articleset, json_data=None, **options): """ Create one or more articles in the set. Provide the needed arguments using the json_data or with key-value pairs @param json_data: A dictionary or list of dictionaries. Each dict can ...
python
def create_articles(self, project, articleset, json_data=None, **options): """ Create one or more articles in the set. Provide the needed arguments using the json_data or with key-value pairs @param json_data: A dictionary or list of dictionaries. Each dict can ...
[ "def", "create_articles", "(", "self", ",", "project", ",", "articleset", ",", "json_data", "=", "None", ",", "*", "*", "options", ")", ":", "url", "=", "URL", ".", "article", ".", "format", "(", "*", "*", "locals", "(", ")", ")", "# TODO duplicated fr...
Create one or more articles in the set. Provide the needed arguments using the json_data or with key-value pairs @param json_data: A dictionary or list of dictionaries. Each dict can contain a 'children' attribute which is another list of dictionaries.
[ "Create", "one", "or", "more", "articles", "in", "the", "set", ".", "Provide", "the", "needed", "arguments", "using", "the", "json_data", "or", "with", "key", "-", "value", "pairs" ]
bda525f7ace0c26a09fa56d2baf7550f639e62ee
https://github.com/amcat/amcatclient/blob/bda525f7ace0c26a09fa56d2baf7550f639e62ee/amcatclient/amcatclient.py#L349-L367
train
walkr/nanoservice
nanoservice/crypto.py
Authenticator.sign
def sign(self, encoded): """ Return authentication signature of encoded bytes """ signature = self._hmac.copy() signature.update(encoded) return signature.hexdigest().encode('utf-8')
python
def sign(self, encoded): """ Return authentication signature of encoded bytes """ signature = self._hmac.copy() signature.update(encoded) return signature.hexdigest().encode('utf-8')
[ "def", "sign", "(", "self", ",", "encoded", ")", ":", "signature", "=", "self", ".", "_hmac", ".", "copy", "(", ")", "signature", ".", "update", "(", "encoded", ")", "return", "signature", ".", "hexdigest", "(", ")", ".", "encode", "(", "'utf-8'", ")...
Return authentication signature of encoded bytes
[ "Return", "authentication", "signature", "of", "encoded", "bytes" ]
e2098986b1baa5f283167ae487d14f3c6c21961a
https://github.com/walkr/nanoservice/blob/e2098986b1baa5f283167ae487d14f3c6c21961a/nanoservice/crypto.py#L42-L46
train
walkr/nanoservice
nanoservice/crypto.py
Authenticator.split
def split(self, encoded): """ Split into signature and message """ maxlen = len(encoded) - self.sig_size message = encoded[:maxlen] signature = encoded[-self.sig_size:] return message, signature
python
def split(self, encoded): """ Split into signature and message """ maxlen = len(encoded) - self.sig_size message = encoded[:maxlen] signature = encoded[-self.sig_size:] return message, signature
[ "def", "split", "(", "self", ",", "encoded", ")", ":", "maxlen", "=", "len", "(", "encoded", ")", "-", "self", ".", "sig_size", "message", "=", "encoded", "[", ":", "maxlen", "]", "signature", "=", "encoded", "[", "-", "self", ".", "sig_size", ":", ...
Split into signature and message
[ "Split", "into", "signature", "and", "message" ]
e2098986b1baa5f283167ae487d14f3c6c21961a
https://github.com/walkr/nanoservice/blob/e2098986b1baa5f283167ae487d14f3c6c21961a/nanoservice/crypto.py#L58-L63
train
walkr/nanoservice
nanoservice/crypto.py
Authenticator.auth
def auth(self, encoded): """ Validate integrity of encoded bytes """ message, signature = self.split(encoded) computed = self.sign(message) if not hmac.compare_digest(signature, computed): raise AuthenticatorInvalidSignature
python
def auth(self, encoded): """ Validate integrity of encoded bytes """ message, signature = self.split(encoded) computed = self.sign(message) if not hmac.compare_digest(signature, computed): raise AuthenticatorInvalidSignature
[ "def", "auth", "(", "self", ",", "encoded", ")", ":", "message", ",", "signature", "=", "self", ".", "split", "(", "encoded", ")", "computed", "=", "self", ".", "sign", "(", "message", ")", "if", "not", "hmac", ".", "compare_digest", "(", "signature", ...
Validate integrity of encoded bytes
[ "Validate", "integrity", "of", "encoded", "bytes" ]
e2098986b1baa5f283167ae487d14f3c6c21961a
https://github.com/walkr/nanoservice/blob/e2098986b1baa5f283167ae487d14f3c6c21961a/nanoservice/crypto.py#L65-L70
train
agile4you/bottle-neck
bottle_neck/cbv.py
cached_classproperty
def cached_classproperty(fun): """A memorization decorator for class properties. It implements the above `classproperty` decorator, with the difference that the function result is computed and attached to class as direct attribute. (Lazy loading and caching.) """ @functools.wraps(fun) def ...
python
def cached_classproperty(fun): """A memorization decorator for class properties. It implements the above `classproperty` decorator, with the difference that the function result is computed and attached to class as direct attribute. (Lazy loading and caching.) """ @functools.wraps(fun) def ...
[ "def", "cached_classproperty", "(", "fun", ")", ":", "@", "functools", ".", "wraps", "(", "fun", ")", "def", "get", "(", "cls", ")", ":", "try", ":", "return", "cls", ".", "__cache", "[", "fun", "]", "except", "AttributeError", ":", "cls", ".", "__ca...
A memorization decorator for class properties. It implements the above `classproperty` decorator, with the difference that the function result is computed and attached to class as direct attribute. (Lazy loading and caching.)
[ "A", "memorization", "decorator", "for", "class", "properties", "." ]
ebc670a4b178255473d68e9b4122ba04e38f4810
https://github.com/agile4you/bottle-neck/blob/ebc670a4b178255473d68e9b4122ba04e38f4810/bottle_neck/cbv.py#L92-L109
train
agile4you/bottle-neck
bottle_neck/cbv.py
plugin_method
def plugin_method(*plugin_names): """Plugin Method decorator. Signs a web handler function with the plugins to be applied as attributes. Args: plugin_names (list): A list of plugin callable names Returns: A wrapped handler callable. Examples: >>> @plugin_method('json', 'bi...
python
def plugin_method(*plugin_names): """Plugin Method decorator. Signs a web handler function with the plugins to be applied as attributes. Args: plugin_names (list): A list of plugin callable names Returns: A wrapped handler callable. Examples: >>> @plugin_method('json', 'bi...
[ "def", "plugin_method", "(", "*", "plugin_names", ")", ":", "def", "wrapper", "(", "callable_obj", ")", ":", "for", "plugin_name", "in", "plugin_names", ":", "if", "not", "hasattr", "(", "callable_obj", ",", "plugin_name", ")", ":", "setattr", "(", "callable...
Plugin Method decorator. Signs a web handler function with the plugins to be applied as attributes. Args: plugin_names (list): A list of plugin callable names Returns: A wrapped handler callable. Examples: >>> @plugin_method('json', 'bill') ... def method(): .....
[ "Plugin", "Method", "decorator", ".", "Signs", "a", "web", "handler", "function", "with", "the", "plugins", "to", "be", "applied", "as", "attributes", "." ]
ebc670a4b178255473d68e9b4122ba04e38f4810
https://github.com/agile4you/bottle-neck/blob/ebc670a4b178255473d68e9b4122ba04e38f4810/bottle_neck/cbv.py#L112-L138
train
agile4you/bottle-neck
bottle_neck/cbv.py
route_method
def route_method(method_name, extra_part=False): """Custom handler routing decorator. Signs a web handler callable with the http method as attribute. Args: method_name (str): HTTP method name (i.e GET, POST) extra_part (bool): Indicates if wrapped callable name should be a part ...
python
def route_method(method_name, extra_part=False): """Custom handler routing decorator. Signs a web handler callable with the http method as attribute. Args: method_name (str): HTTP method name (i.e GET, POST) extra_part (bool): Indicates if wrapped callable name should be a part ...
[ "def", "route_method", "(", "method_name", ",", "extra_part", "=", "False", ")", ":", "def", "wrapper", "(", "callable_obj", ")", ":", "if", "method_name", ".", "lower", "(", ")", "not", "in", "DEFAULT_ROUTES", ":", "raise", "HandlerHTTPMethodError", "(", "'...
Custom handler routing decorator. Signs a web handler callable with the http method as attribute. Args: method_name (str): HTTP method name (i.e GET, POST) extra_part (bool): Indicates if wrapped callable name should be a part of the actual endpoint. Returns: ...
[ "Custom", "handler", "routing", "decorator", ".", "Signs", "a", "web", "handler", "callable", "with", "the", "http", "method", "as", "attribute", "." ]
ebc670a4b178255473d68e9b4122ba04e38f4810
https://github.com/agile4you/bottle-neck/blob/ebc670a4b178255473d68e9b4122ba04e38f4810/bottle_neck/cbv.py#L141-L175
train
GaretJax/lancet
lancet/commands/jira.py
issue_add
def issue_add(lancet, assign, add_to_sprint, summary): """ Create a new issue on the issue tracker. """ summary = " ".join(summary) issue = create_issue( lancet, summary, # project_id=project_id, add_to_active_sprint=add_to_sprint, ) if assign: if assi...
python
def issue_add(lancet, assign, add_to_sprint, summary): """ Create a new issue on the issue tracker. """ summary = " ".join(summary) issue = create_issue( lancet, summary, # project_id=project_id, add_to_active_sprint=add_to_sprint, ) if assign: if assi...
[ "def", "issue_add", "(", "lancet", ",", "assign", ",", "add_to_sprint", ",", "summary", ")", ":", "summary", "=", "\" \"", ".", "join", "(", "summary", ")", "issue", "=", "create_issue", "(", "lancet", ",", "summary", ",", "# project_id=project_id,", "add_to...
Create a new issue on the issue tracker.
[ "Create", "a", "new", "issue", "on", "the", "issue", "tracker", "." ]
cf438c5c6166b18ee0dc5ffce55220793019bb95
https://github.com/GaretJax/lancet/blob/cf438c5c6166b18ee0dc5ffce55220793019bb95/lancet/commands/jira.py#L31-L49
train
edx/edx-django-extensions
edx_management_commands/management_commands/management/commands/manage_user.py
Command._maybe_update
def _maybe_update(self, user, attribute, new_value): """ DRY helper. If the specified attribute of the user differs from the specified value, it will be updated. """ old_value = getattr(user, attribute) if new_value != old_value: self.stderr.write( ...
python
def _maybe_update(self, user, attribute, new_value): """ DRY helper. If the specified attribute of the user differs from the specified value, it will be updated. """ old_value = getattr(user, attribute) if new_value != old_value: self.stderr.write( ...
[ "def", "_maybe_update", "(", "self", ",", "user", ",", "attribute", ",", "new_value", ")", ":", "old_value", "=", "getattr", "(", "user", ",", "attribute", ")", "if", "new_value", "!=", "old_value", ":", "self", ".", "stderr", ".", "write", "(", "_", "...
DRY helper. If the specified attribute of the user differs from the specified value, it will be updated.
[ "DRY", "helper", ".", "If", "the", "specified", "attribute", "of", "the", "user", "differs", "from", "the", "specified", "value", "it", "will", "be", "updated", "." ]
35bbf7f95453c0e2c07acf3539722a92e7b6f548
https://github.com/edx/edx-django-extensions/blob/35bbf7f95453c0e2c07acf3539722a92e7b6f548/edx_management_commands/management_commands/management/commands/manage_user.py#L26-L38
train
edx/edx-django-extensions
edx_management_commands/management_commands/management/commands/manage_user.py
Command._check_email_match
def _check_email_match(self, user, email): """ DRY helper. Requiring the user to specify both username and email will help catch certain issues, for example if the expected username has already been taken by someone else. """ if user.email != email: #...
python
def _check_email_match(self, user, email): """ DRY helper. Requiring the user to specify both username and email will help catch certain issues, for example if the expected username has already been taken by someone else. """ if user.email != email: #...
[ "def", "_check_email_match", "(", "self", ",", "user", ",", "email", ")", ":", "if", "user", ".", "email", "!=", "email", ":", "# The passed email address doesn't match this username's email address.", "# Assume a problem and fail.", "raise", "CommandError", "(", "_", "...
DRY helper. Requiring the user to specify both username and email will help catch certain issues, for example if the expected username has already been taken by someone else.
[ "DRY", "helper", "." ]
35bbf7f95453c0e2c07acf3539722a92e7b6f548
https://github.com/edx/edx-django-extensions/blob/35bbf7f95453c0e2c07acf3539722a92e7b6f548/edx_management_commands/management_commands/management/commands/manage_user.py#L40-L56
train