repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
sequencelengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
sequencelengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
RudolfCardinal/pythonlib
cardinal_pythonlib/email/sendmail.py
send_msg
def send_msg(from_addr: str, to_addrs: Union[str, List[str]], host: str, user: str, password: str, port: int = None, use_tls: bool = True, msg: email.mime.multipart.MIMEMultipart = None, msg_string: str = None) -> None: """ Sends a pre-built e-mail message. Args: from_addr: e-mail address for 'From:' field to_addrs: address or list of addresses to transmit to host: mail server host user: username on mail server password: password for username on mail server port: port to use, or ``None`` for protocol default use_tls: use TLS, rather than plain SMTP? msg: a :class:`email.mime.multipart.MIMEMultipart` msg_string: alternative: specify the message as a raw string Raises: :exc:`RuntimeError` See also: - https://tools.ietf.org/html/rfc3207 """ assert bool(msg) != bool(msg_string), "Specify either msg or msg_string" # Connect try: session = smtplib.SMTP(host, port) except smtplib.SMTPException as e: raise RuntimeError( "send_msg: Failed to connect to host {}, port {}: {}".format( host, port, e)) try: session.ehlo() except smtplib.SMTPException as e: raise RuntimeError("send_msg: Failed to issue EHLO: {}".format(e)) if use_tls: try: session.starttls() session.ehlo() except smtplib.SMTPException as e: raise RuntimeError( "send_msg: Failed to initiate TLS: {}".format(e)) # Log in if user: try: session.login(user, password) except smtplib.SMTPException as e: raise RuntimeError( "send_msg: Failed to login as user {}: {}".format(user, e)) else: log.debug("Not using SMTP AUTH; no user specified") # For systems with... lax... security requirements # Send try: session.sendmail(from_addr, to_addrs, msg.as_string()) except smtplib.SMTPException as e: raise RuntimeError("send_msg: Failed to send e-mail: {}".format(e)) # Log out session.quit()
python
def send_msg(from_addr: str, to_addrs: Union[str, List[str]], host: str, user: str, password: str, port: int = None, use_tls: bool = True, msg: email.mime.multipart.MIMEMultipart = None, msg_string: str = None) -> None: """ Sends a pre-built e-mail message. Args: from_addr: e-mail address for 'From:' field to_addrs: address or list of addresses to transmit to host: mail server host user: username on mail server password: password for username on mail server port: port to use, or ``None`` for protocol default use_tls: use TLS, rather than plain SMTP? msg: a :class:`email.mime.multipart.MIMEMultipart` msg_string: alternative: specify the message as a raw string Raises: :exc:`RuntimeError` See also: - https://tools.ietf.org/html/rfc3207 """ assert bool(msg) != bool(msg_string), "Specify either msg or msg_string" # Connect try: session = smtplib.SMTP(host, port) except smtplib.SMTPException as e: raise RuntimeError( "send_msg: Failed to connect to host {}, port {}: {}".format( host, port, e)) try: session.ehlo() except smtplib.SMTPException as e: raise RuntimeError("send_msg: Failed to issue EHLO: {}".format(e)) if use_tls: try: session.starttls() session.ehlo() except smtplib.SMTPException as e: raise RuntimeError( "send_msg: Failed to initiate TLS: {}".format(e)) # Log in if user: try: session.login(user, password) except smtplib.SMTPException as e: raise RuntimeError( "send_msg: Failed to login as user {}: {}".format(user, e)) else: log.debug("Not using SMTP AUTH; no user specified") # For systems with... lax... security requirements # Send try: session.sendmail(from_addr, to_addrs, msg.as_string()) except smtplib.SMTPException as e: raise RuntimeError("send_msg: Failed to send e-mail: {}".format(e)) # Log out session.quit()
[ "def", "send_msg", "(", "from_addr", ":", "str", ",", "to_addrs", ":", "Union", "[", "str", ",", "List", "[", "str", "]", "]", ",", "host", ":", "str", ",", "user", ":", "str", ",", "password", ":", "str", ",", "port", ":", "int", "=", "None", ",", "use_tls", ":", "bool", "=", "True", ",", "msg", ":", "email", ".", "mime", ".", "multipart", ".", "MIMEMultipart", "=", "None", ",", "msg_string", ":", "str", "=", "None", ")", "->", "None", ":", "assert", "bool", "(", "msg", ")", "!=", "bool", "(", "msg_string", ")", ",", "\"Specify either msg or msg_string\"", "# Connect", "try", ":", "session", "=", "smtplib", ".", "SMTP", "(", "host", ",", "port", ")", "except", "smtplib", ".", "SMTPException", "as", "e", ":", "raise", "RuntimeError", "(", "\"send_msg: Failed to connect to host {}, port {}: {}\"", ".", "format", "(", "host", ",", "port", ",", "e", ")", ")", "try", ":", "session", ".", "ehlo", "(", ")", "except", "smtplib", ".", "SMTPException", "as", "e", ":", "raise", "RuntimeError", "(", "\"send_msg: Failed to issue EHLO: {}\"", ".", "format", "(", "e", ")", ")", "if", "use_tls", ":", "try", ":", "session", ".", "starttls", "(", ")", "session", ".", "ehlo", "(", ")", "except", "smtplib", ".", "SMTPException", "as", "e", ":", "raise", "RuntimeError", "(", "\"send_msg: Failed to initiate TLS: {}\"", ".", "format", "(", "e", ")", ")", "# Log in", "if", "user", ":", "try", ":", "session", ".", "login", "(", "user", ",", "password", ")", "except", "smtplib", ".", "SMTPException", "as", "e", ":", "raise", "RuntimeError", "(", "\"send_msg: Failed to login as user {}: {}\"", ".", "format", "(", "user", ",", "e", ")", ")", "else", ":", "log", ".", "debug", "(", "\"Not using SMTP AUTH; no user specified\"", ")", "# For systems with... lax... security requirements", "# Send", "try", ":", "session", ".", "sendmail", "(", "from_addr", ",", "to_addrs", ",", "msg", ".", "as_string", "(", ")", ")", "except", "smtplib", ".", "SMTPException", "as", "e", ":", "raise", "RuntimeError", "(", "\"send_msg: Failed to send e-mail: {}\"", ".", "format", "(", "e", ")", ")", "# Log out", "session", ".", "quit", "(", ")" ]
Sends a pre-built e-mail message. Args: from_addr: e-mail address for 'From:' field to_addrs: address or list of addresses to transmit to host: mail server host user: username on mail server password: password for username on mail server port: port to use, or ``None`` for protocol default use_tls: use TLS, rather than plain SMTP? msg: a :class:`email.mime.multipart.MIMEMultipart` msg_string: alternative: specify the message as a raw string Raises: :exc:`RuntimeError` See also: - https://tools.ietf.org/html/rfc3207
[ "Sends", "a", "pre", "-", "built", "e", "-", "mail", "message", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/email/sendmail.py#L247-L319
RudolfCardinal/pythonlib
cardinal_pythonlib/email/sendmail.py
send_email
def send_email(from_addr: str, host: str, user: str, password: str, port: int = None, use_tls: bool = True, date: str = None, sender: str = "", reply_to: Union[str, List[str]] = "", to: Union[str, List[str]] = "", cc: Union[str, List[str]] = "", bcc: Union[str, List[str]] = "", subject: str = "", body: str = "", content_type: str = CONTENT_TYPE_TEXT, charset: str = "utf8", attachment_filenames: Sequence[str] = None, attachment_binaries: Sequence[bytes] = None, attachment_binary_filenames: Sequence[str] = None, verbose: bool = False) -> Tuple[bool, str]: """ Sends an e-mail in text/html format using SMTP via TLS. Args: host: mail server host user: username on mail server password: password for username on mail server port: port to use, or ``None`` for protocol default use_tls: use TLS, rather than plain SMTP? date: e-mail date in RFC 2822 format, or ``None`` for "now" from_addr: name of the sender for the "From:" field sender: name of the sender for the "Sender:" field reply_to: name of the sender for the "Reply-To:" field to: e-mail address(es) of the recipients for "To:" field cc: e-mail address(es) of the recipients for "Cc:" field bcc: e-mail address(es) of the recipients for "Bcc:" field subject: e-mail subject body: e-mail body content_type: MIME type for body content, default ``text/plain`` charset: character set for body; default ``utf8`` attachment_filenames: filenames of attachments to add attachment_binaries: binary objects to add as attachments attachment_binary_filenames: filenames corresponding to ``attachment_binaries`` verbose: be verbose? Returns: tuple: ``(success, error_or_success_message)`` See - https://tools.ietf.org/html/rfc2822 - https://tools.ietf.org/html/rfc5322 - http://segfault.in/2010/12/sending-gmail-from-python/ - http://stackoverflow.com/questions/64505 - http://stackoverflow.com/questions/3362600 Re security: - TLS supersedes SSL: https://en.wikipedia.org/wiki/Transport_Layer_Security - https://en.wikipedia.org/wiki/Email_encryption - SMTP connections on ports 25 and 587 are commonly secured via TLS using the ``STARTTLS`` command: https://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol - https://tools.ietf.org/html/rfc8314 - "STARTTLS on port 587" is one common method. Django refers to this as "explicit TLS" (its ``E_MAIL_USE_TLS`` setting; see https://docs.djangoproject.com/en/2.1/ref/settings/#std:setting-EMAIL_USE_TLS). - Port 465 is also used for "implicit TLS" (3.3 in https://tools.ietf.org/html/rfc8314). Django refers to this as "implicit TLS" too, or SSL; see its ``EMAIL_USE_SSL`` setting at https://docs.djangoproject.com/en/2.1/ref/settings/#email-use-ssl). We don't support that here. """ # noqa if isinstance(to, str): to = [to] if isinstance(cc, str): cc = [cc] if isinstance(bcc, str): bcc = [bcc] # ------------------------------------------------------------------------- # Make it # ------------------------------------------------------------------------- try: msg = make_email( from_addr=from_addr, date=date, sender=sender, reply_to=reply_to, to=to, cc=cc, bcc=bcc, subject=subject, body=body, content_type=content_type, charset=charset, attachment_filenames=attachment_filenames, attachment_binaries=attachment_binaries, attachment_binary_filenames=attachment_binary_filenames, verbose=verbose, ) except (AssertionError, ValueError) as e: errmsg = str(e) log.error("{}", errmsg) return False, errmsg # ------------------------------------------------------------------------- # Send it # ------------------------------------------------------------------------- to_addrs = to + cc + bcc try: send_msg( msg=msg, from_addr=from_addr, to_addrs=to_addrs, host=host, user=user, password=password, port=port, use_tls=use_tls, ) except RuntimeError as e: errmsg = str(e) log.error("{}", e) return False, errmsg return True, "Success"
python
def send_email(from_addr: str, host: str, user: str, password: str, port: int = None, use_tls: bool = True, date: str = None, sender: str = "", reply_to: Union[str, List[str]] = "", to: Union[str, List[str]] = "", cc: Union[str, List[str]] = "", bcc: Union[str, List[str]] = "", subject: str = "", body: str = "", content_type: str = CONTENT_TYPE_TEXT, charset: str = "utf8", attachment_filenames: Sequence[str] = None, attachment_binaries: Sequence[bytes] = None, attachment_binary_filenames: Sequence[str] = None, verbose: bool = False) -> Tuple[bool, str]: """ Sends an e-mail in text/html format using SMTP via TLS. Args: host: mail server host user: username on mail server password: password for username on mail server port: port to use, or ``None`` for protocol default use_tls: use TLS, rather than plain SMTP? date: e-mail date in RFC 2822 format, or ``None`` for "now" from_addr: name of the sender for the "From:" field sender: name of the sender for the "Sender:" field reply_to: name of the sender for the "Reply-To:" field to: e-mail address(es) of the recipients for "To:" field cc: e-mail address(es) of the recipients for "Cc:" field bcc: e-mail address(es) of the recipients for "Bcc:" field subject: e-mail subject body: e-mail body content_type: MIME type for body content, default ``text/plain`` charset: character set for body; default ``utf8`` attachment_filenames: filenames of attachments to add attachment_binaries: binary objects to add as attachments attachment_binary_filenames: filenames corresponding to ``attachment_binaries`` verbose: be verbose? Returns: tuple: ``(success, error_or_success_message)`` See - https://tools.ietf.org/html/rfc2822 - https://tools.ietf.org/html/rfc5322 - http://segfault.in/2010/12/sending-gmail-from-python/ - http://stackoverflow.com/questions/64505 - http://stackoverflow.com/questions/3362600 Re security: - TLS supersedes SSL: https://en.wikipedia.org/wiki/Transport_Layer_Security - https://en.wikipedia.org/wiki/Email_encryption - SMTP connections on ports 25 and 587 are commonly secured via TLS using the ``STARTTLS`` command: https://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol - https://tools.ietf.org/html/rfc8314 - "STARTTLS on port 587" is one common method. Django refers to this as "explicit TLS" (its ``E_MAIL_USE_TLS`` setting; see https://docs.djangoproject.com/en/2.1/ref/settings/#std:setting-EMAIL_USE_TLS). - Port 465 is also used for "implicit TLS" (3.3 in https://tools.ietf.org/html/rfc8314). Django refers to this as "implicit TLS" too, or SSL; see its ``EMAIL_USE_SSL`` setting at https://docs.djangoproject.com/en/2.1/ref/settings/#email-use-ssl). We don't support that here. """ # noqa if isinstance(to, str): to = [to] if isinstance(cc, str): cc = [cc] if isinstance(bcc, str): bcc = [bcc] # ------------------------------------------------------------------------- # Make it # ------------------------------------------------------------------------- try: msg = make_email( from_addr=from_addr, date=date, sender=sender, reply_to=reply_to, to=to, cc=cc, bcc=bcc, subject=subject, body=body, content_type=content_type, charset=charset, attachment_filenames=attachment_filenames, attachment_binaries=attachment_binaries, attachment_binary_filenames=attachment_binary_filenames, verbose=verbose, ) except (AssertionError, ValueError) as e: errmsg = str(e) log.error("{}", errmsg) return False, errmsg # ------------------------------------------------------------------------- # Send it # ------------------------------------------------------------------------- to_addrs = to + cc + bcc try: send_msg( msg=msg, from_addr=from_addr, to_addrs=to_addrs, host=host, user=user, password=password, port=port, use_tls=use_tls, ) except RuntimeError as e: errmsg = str(e) log.error("{}", e) return False, errmsg return True, "Success"
[ "def", "send_email", "(", "from_addr", ":", "str", ",", "host", ":", "str", ",", "user", ":", "str", ",", "password", ":", "str", ",", "port", ":", "int", "=", "None", ",", "use_tls", ":", "bool", "=", "True", ",", "date", ":", "str", "=", "None", ",", "sender", ":", "str", "=", "\"\"", ",", "reply_to", ":", "Union", "[", "str", ",", "List", "[", "str", "]", "]", "=", "\"\"", ",", "to", ":", "Union", "[", "str", ",", "List", "[", "str", "]", "]", "=", "\"\"", ",", "cc", ":", "Union", "[", "str", ",", "List", "[", "str", "]", "]", "=", "\"\"", ",", "bcc", ":", "Union", "[", "str", ",", "List", "[", "str", "]", "]", "=", "\"\"", ",", "subject", ":", "str", "=", "\"\"", ",", "body", ":", "str", "=", "\"\"", ",", "content_type", ":", "str", "=", "CONTENT_TYPE_TEXT", ",", "charset", ":", "str", "=", "\"utf8\"", ",", "attachment_filenames", ":", "Sequence", "[", "str", "]", "=", "None", ",", "attachment_binaries", ":", "Sequence", "[", "bytes", "]", "=", "None", ",", "attachment_binary_filenames", ":", "Sequence", "[", "str", "]", "=", "None", ",", "verbose", ":", "bool", "=", "False", ")", "->", "Tuple", "[", "bool", ",", "str", "]", ":", "# noqa", "if", "isinstance", "(", "to", ",", "str", ")", ":", "to", "=", "[", "to", "]", "if", "isinstance", "(", "cc", ",", "str", ")", ":", "cc", "=", "[", "cc", "]", "if", "isinstance", "(", "bcc", ",", "str", ")", ":", "bcc", "=", "[", "bcc", "]", "# -------------------------------------------------------------------------", "# Make it", "# -------------------------------------------------------------------------", "try", ":", "msg", "=", "make_email", "(", "from_addr", "=", "from_addr", ",", "date", "=", "date", ",", "sender", "=", "sender", ",", "reply_to", "=", "reply_to", ",", "to", "=", "to", ",", "cc", "=", "cc", ",", "bcc", "=", "bcc", ",", "subject", "=", "subject", ",", "body", "=", "body", ",", "content_type", "=", "content_type", ",", "charset", "=", "charset", ",", "attachment_filenames", "=", "attachment_filenames", ",", "attachment_binaries", "=", "attachment_binaries", ",", "attachment_binary_filenames", "=", "attachment_binary_filenames", ",", "verbose", "=", "verbose", ",", ")", "except", "(", "AssertionError", ",", "ValueError", ")", "as", "e", ":", "errmsg", "=", "str", "(", "e", ")", "log", ".", "error", "(", "\"{}\"", ",", "errmsg", ")", "return", "False", ",", "errmsg", "# -------------------------------------------------------------------------", "# Send it", "# -------------------------------------------------------------------------", "to_addrs", "=", "to", "+", "cc", "+", "bcc", "try", ":", "send_msg", "(", "msg", "=", "msg", ",", "from_addr", "=", "from_addr", ",", "to_addrs", "=", "to_addrs", ",", "host", "=", "host", ",", "user", "=", "user", ",", "password", "=", "password", ",", "port", "=", "port", ",", "use_tls", "=", "use_tls", ",", ")", "except", "RuntimeError", "as", "e", ":", "errmsg", "=", "str", "(", "e", ")", "log", ".", "error", "(", "\"{}\"", ",", "e", ")", "return", "False", ",", "errmsg", "return", "True", ",", "\"Success\"" ]
Sends an e-mail in text/html format using SMTP via TLS. Args: host: mail server host user: username on mail server password: password for username on mail server port: port to use, or ``None`` for protocol default use_tls: use TLS, rather than plain SMTP? date: e-mail date in RFC 2822 format, or ``None`` for "now" from_addr: name of the sender for the "From:" field sender: name of the sender for the "Sender:" field reply_to: name of the sender for the "Reply-To:" field to: e-mail address(es) of the recipients for "To:" field cc: e-mail address(es) of the recipients for "Cc:" field bcc: e-mail address(es) of the recipients for "Bcc:" field subject: e-mail subject body: e-mail body content_type: MIME type for body content, default ``text/plain`` charset: character set for body; default ``utf8`` attachment_filenames: filenames of attachments to add attachment_binaries: binary objects to add as attachments attachment_binary_filenames: filenames corresponding to ``attachment_binaries`` verbose: be verbose? Returns: tuple: ``(success, error_or_success_message)`` See - https://tools.ietf.org/html/rfc2822 - https://tools.ietf.org/html/rfc5322 - http://segfault.in/2010/12/sending-gmail-from-python/ - http://stackoverflow.com/questions/64505 - http://stackoverflow.com/questions/3362600 Re security: - TLS supersedes SSL: https://en.wikipedia.org/wiki/Transport_Layer_Security - https://en.wikipedia.org/wiki/Email_encryption - SMTP connections on ports 25 and 587 are commonly secured via TLS using the ``STARTTLS`` command: https://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol - https://tools.ietf.org/html/rfc8314 - "STARTTLS on port 587" is one common method. Django refers to this as "explicit TLS" (its ``E_MAIL_USE_TLS`` setting; see https://docs.djangoproject.com/en/2.1/ref/settings/#std:setting-EMAIL_USE_TLS). - Port 465 is also used for "implicit TLS" (3.3 in https://tools.ietf.org/html/rfc8314). Django refers to this as "implicit TLS" too, or SSL; see its ``EMAIL_USE_SSL`` setting at https://docs.djangoproject.com/en/2.1/ref/settings/#email-use-ssl). We don't support that here.
[ "Sends", "an", "e", "-", "mail", "in", "text", "/", "html", "format", "using", "SMTP", "via", "TLS", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/email/sendmail.py#L326-L466
RudolfCardinal/pythonlib
cardinal_pythonlib/email/sendmail.py
main
def main() -> None: """ Command-line processor. See ``--help`` for details. """ logging.basicConfig() log.setLevel(logging.DEBUG) parser = argparse.ArgumentParser( description="Send an e-mail from the command line.") parser.add_argument("sender", action="store", help="Sender's e-mail address") parser.add_argument("host", action="store", help="SMTP server hostname") parser.add_argument("user", action="store", help="SMTP username") parser.add_argument("password", action="store", help="SMTP password") parser.add_argument("recipient", action="append", help="Recipient e-mail address(es)") parser.add_argument("subject", action="store", help="Message subject") parser.add_argument("body", action="store", help="Message body") parser.add_argument("--attach", nargs="*", help="Filename(s) to attach") parser.add_argument("--tls", action="store_false", help="Use TLS connection security") parser.add_argument("--verbose", action="store_true", help="Be verbose") parser.add_argument("-h --help", action="help", help="Prints this help") args = parser.parse_args() (result, msg) = send_email( from_addr=args.sender, to=args.recipient, subject=args.subject, body=args.body, host=args.host, user=args.user, password=args.password, use_tls=args.tls, attachment_filenames=args.attach, verbose=args.verbose, ) if result: log.info("Success") else: log.info("Failure") # log.error(msg) sys.exit(0 if result else 1)
python
def main() -> None: """ Command-line processor. See ``--help`` for details. """ logging.basicConfig() log.setLevel(logging.DEBUG) parser = argparse.ArgumentParser( description="Send an e-mail from the command line.") parser.add_argument("sender", action="store", help="Sender's e-mail address") parser.add_argument("host", action="store", help="SMTP server hostname") parser.add_argument("user", action="store", help="SMTP username") parser.add_argument("password", action="store", help="SMTP password") parser.add_argument("recipient", action="append", help="Recipient e-mail address(es)") parser.add_argument("subject", action="store", help="Message subject") parser.add_argument("body", action="store", help="Message body") parser.add_argument("--attach", nargs="*", help="Filename(s) to attach") parser.add_argument("--tls", action="store_false", help="Use TLS connection security") parser.add_argument("--verbose", action="store_true", help="Be verbose") parser.add_argument("-h --help", action="help", help="Prints this help") args = parser.parse_args() (result, msg) = send_email( from_addr=args.sender, to=args.recipient, subject=args.subject, body=args.body, host=args.host, user=args.user, password=args.password, use_tls=args.tls, attachment_filenames=args.attach, verbose=args.verbose, ) if result: log.info("Success") else: log.info("Failure") # log.error(msg) sys.exit(0 if result else 1)
[ "def", "main", "(", ")", "->", "None", ":", "logging", ".", "basicConfig", "(", ")", "log", ".", "setLevel", "(", "logging", ".", "DEBUG", ")", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Send an e-mail from the command line.\"", ")", "parser", ".", "add_argument", "(", "\"sender\"", ",", "action", "=", "\"store\"", ",", "help", "=", "\"Sender's e-mail address\"", ")", "parser", ".", "add_argument", "(", "\"host\"", ",", "action", "=", "\"store\"", ",", "help", "=", "\"SMTP server hostname\"", ")", "parser", ".", "add_argument", "(", "\"user\"", ",", "action", "=", "\"store\"", ",", "help", "=", "\"SMTP username\"", ")", "parser", ".", "add_argument", "(", "\"password\"", ",", "action", "=", "\"store\"", ",", "help", "=", "\"SMTP password\"", ")", "parser", ".", "add_argument", "(", "\"recipient\"", ",", "action", "=", "\"append\"", ",", "help", "=", "\"Recipient e-mail address(es)\"", ")", "parser", ".", "add_argument", "(", "\"subject\"", ",", "action", "=", "\"store\"", ",", "help", "=", "\"Message subject\"", ")", "parser", ".", "add_argument", "(", "\"body\"", ",", "action", "=", "\"store\"", ",", "help", "=", "\"Message body\"", ")", "parser", ".", "add_argument", "(", "\"--attach\"", ",", "nargs", "=", "\"*\"", ",", "help", "=", "\"Filename(s) to attach\"", ")", "parser", ".", "add_argument", "(", "\"--tls\"", ",", "action", "=", "\"store_false\"", ",", "help", "=", "\"Use TLS connection security\"", ")", "parser", ".", "add_argument", "(", "\"--verbose\"", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Be verbose\"", ")", "parser", ".", "add_argument", "(", "\"-h --help\"", ",", "action", "=", "\"help\"", ",", "help", "=", "\"Prints this help\"", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "(", "result", ",", "msg", ")", "=", "send_email", "(", "from_addr", "=", "args", ".", "sender", ",", "to", "=", "args", ".", "recipient", ",", "subject", "=", "args", ".", "subject", ",", "body", "=", "args", ".", "body", ",", "host", "=", "args", ".", "host", ",", "user", "=", "args", ".", "user", ",", "password", "=", "args", ".", "password", ",", "use_tls", "=", "args", ".", "tls", ",", "attachment_filenames", "=", "args", ".", "attach", ",", "verbose", "=", "args", ".", "verbose", ",", ")", "if", "result", ":", "log", ".", "info", "(", "\"Success\"", ")", "else", ":", "log", ".", "info", "(", "\"Failure\"", ")", "# log.error(msg)", "sys", ".", "exit", "(", "0", "if", "result", "else", "1", ")" ]
Command-line processor. See ``--help`` for details.
[ "Command", "-", "line", "processor", ".", "See", "--", "help", "for", "details", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/email/sendmail.py#L495-L543
AndrewWalker/glud
glud/parsing.py
parse_string
def parse_string(contents, name='tmp.cpp', **kwargs): """ Parse a string of C/C++ code """ idx = clang.cindex.Index.create() tu = idx.parse(name, unsaved_files=[(name, contents)], **kwargs) return _ensure_parse_valid(tu)
python
def parse_string(contents, name='tmp.cpp', **kwargs): """ Parse a string of C/C++ code """ idx = clang.cindex.Index.create() tu = idx.parse(name, unsaved_files=[(name, contents)], **kwargs) return _ensure_parse_valid(tu)
[ "def", "parse_string", "(", "contents", ",", "name", "=", "'tmp.cpp'", ",", "*", "*", "kwargs", ")", ":", "idx", "=", "clang", ".", "cindex", ".", "Index", ".", "create", "(", ")", "tu", "=", "idx", ".", "parse", "(", "name", ",", "unsaved_files", "=", "[", "(", "name", ",", "contents", ")", "]", ",", "*", "*", "kwargs", ")", "return", "_ensure_parse_valid", "(", "tu", ")" ]
Parse a string of C/C++ code
[ "Parse", "a", "string", "of", "C", "/", "C", "++", "code" ]
train
https://github.com/AndrewWalker/glud/blob/57de000627fed13d0c383f131163795b09549257/glud/parsing.py#L27-L32
AndrewWalker/glud
glud/parsing.py
parse
def parse(name, **kwargs): """ Parse a C/C++ file """ idx = clang.cindex.Index.create() assert os.path.exists(name) tu = idx.parse(name, **kwargs) return _ensure_parse_valid(tu)
python
def parse(name, **kwargs): """ Parse a C/C++ file """ idx = clang.cindex.Index.create() assert os.path.exists(name) tu = idx.parse(name, **kwargs) return _ensure_parse_valid(tu)
[ "def", "parse", "(", "name", ",", "*", "*", "kwargs", ")", ":", "idx", "=", "clang", ".", "cindex", ".", "Index", ".", "create", "(", ")", "assert", "os", ".", "path", ".", "exists", "(", "name", ")", "tu", "=", "idx", ".", "parse", "(", "name", ",", "*", "*", "kwargs", ")", "return", "_ensure_parse_valid", "(", "tu", ")" ]
Parse a C/C++ file
[ "Parse", "a", "C", "/", "C", "++", "file" ]
train
https://github.com/AndrewWalker/glud/blob/57de000627fed13d0c383f131163795b09549257/glud/parsing.py#L35-L41
RudolfCardinal/pythonlib
cardinal_pythonlib/wsgi/reverse_proxied_mw.py
ip_addresses_from_xff
def ip_addresses_from_xff(value: str) -> List[str]: """ Returns a list of IP addresses (as strings), given the value of an HTTP ``X-Forwarded-For`` (or ``WSGI HTTP_X_FORWARDED_FOR``) header. Args: value: the value of an HTTP ``X-Forwarded-For`` (or ``WSGI HTTP_X_FORWARDED_FOR``) header Returns: a list of IP address as strings See: - https://en.wikipedia.org/wiki/X-Forwarded-For - https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For # noqa - NOT THIS: http://tools.ietf.org/html/rfc7239 """ if not value: return [] return [x.strip() for x in value.split(",")]
python
def ip_addresses_from_xff(value: str) -> List[str]: """ Returns a list of IP addresses (as strings), given the value of an HTTP ``X-Forwarded-For`` (or ``WSGI HTTP_X_FORWARDED_FOR``) header. Args: value: the value of an HTTP ``X-Forwarded-For`` (or ``WSGI HTTP_X_FORWARDED_FOR``) header Returns: a list of IP address as strings See: - https://en.wikipedia.org/wiki/X-Forwarded-For - https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For # noqa - NOT THIS: http://tools.ietf.org/html/rfc7239 """ if not value: return [] return [x.strip() for x in value.split(",")]
[ "def", "ip_addresses_from_xff", "(", "value", ":", "str", ")", "->", "List", "[", "str", "]", ":", "if", "not", "value", ":", "return", "[", "]", "return", "[", "x", ".", "strip", "(", ")", "for", "x", "in", "value", ".", "split", "(", "\",\"", ")", "]" ]
Returns a list of IP addresses (as strings), given the value of an HTTP ``X-Forwarded-For`` (or ``WSGI HTTP_X_FORWARDED_FOR``) header. Args: value: the value of an HTTP ``X-Forwarded-For`` (or ``WSGI HTTP_X_FORWARDED_FOR``) header Returns: a list of IP address as strings See: - https://en.wikipedia.org/wiki/X-Forwarded-For - https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For # noqa - NOT THIS: http://tools.ietf.org/html/rfc7239
[ "Returns", "a", "list", "of", "IP", "addresses", "(", "as", "strings", ")", "given", "the", "value", "of", "an", "HTTP", "X", "-", "Forwarded", "-", "For", "(", "or", "WSGI", "HTTP_X_FORWARDED_FOR", ")", "header", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/wsgi/reverse_proxied_mw.py#L50-L70
RudolfCardinal/pythonlib
cardinal_pythonlib/wsgi/reverse_proxied_mw.py
ReverseProxiedConfig.necessary
def necessary(self) -> bool: """ Is any special handling (e.g. the addition of :class:`ReverseProxiedMiddleware`) necessary for thie config? """ return any([ self.trusted_proxy_headers, self.http_host, self.remote_addr, self.script_name, self.server_name, self.server_port, self.url_scheme, self.rewrite_path_info, ])
python
def necessary(self) -> bool: """ Is any special handling (e.g. the addition of :class:`ReverseProxiedMiddleware`) necessary for thie config? """ return any([ self.trusted_proxy_headers, self.http_host, self.remote_addr, self.script_name, self.server_name, self.server_port, self.url_scheme, self.rewrite_path_info, ])
[ "def", "necessary", "(", "self", ")", "->", "bool", ":", "return", "any", "(", "[", "self", ".", "trusted_proxy_headers", ",", "self", ".", "http_host", ",", "self", ".", "remote_addr", ",", "self", ".", "script_name", ",", "self", ".", "server_name", ",", "self", ".", "server_port", ",", "self", ".", "url_scheme", ",", "self", ".", "rewrite_path_info", ",", "]", ")" ]
Is any special handling (e.g. the addition of :class:`ReverseProxiedMiddleware`) necessary for thie config?
[ "Is", "any", "special", "handling", "(", "e", ".", "g", ".", "the", "addition", "of", ":", "class", ":", "ReverseProxiedMiddleware", ")", "necessary", "for", "thie", "config?" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/wsgi/reverse_proxied_mw.py#L241-L255
calston/rhumba
rhumba/client.py
AsyncRhumbaClient.queue
def queue(self, queue, message, params={}, uids=[]): """ Queue a job in Rhumba """ d = { 'id': uuid.uuid1().get_hex(), 'version': 1, 'message': message, 'params': params } if uids: for uid in uids: yield self.client.lpush('rhumba.dq.%s.%s' % ( uid, queue), json.dumps(d)) else: yield self.client.lpush('rhumba.q.%s' % queue, json.dumps(d)) defer.returnValue(d['id'])
python
def queue(self, queue, message, params={}, uids=[]): """ Queue a job in Rhumba """ d = { 'id': uuid.uuid1().get_hex(), 'version': 1, 'message': message, 'params': params } if uids: for uid in uids: yield self.client.lpush('rhumba.dq.%s.%s' % ( uid, queue), json.dumps(d)) else: yield self.client.lpush('rhumba.q.%s' % queue, json.dumps(d)) defer.returnValue(d['id'])
[ "def", "queue", "(", "self", ",", "queue", ",", "message", ",", "params", "=", "{", "}", ",", "uids", "=", "[", "]", ")", ":", "d", "=", "{", "'id'", ":", "uuid", ".", "uuid1", "(", ")", ".", "get_hex", "(", ")", ",", "'version'", ":", "1", ",", "'message'", ":", "message", ",", "'params'", ":", "params", "}", "if", "uids", ":", "for", "uid", "in", "uids", ":", "yield", "self", ".", "client", ".", "lpush", "(", "'rhumba.dq.%s.%s'", "%", "(", "uid", ",", "queue", ")", ",", "json", ".", "dumps", "(", "d", ")", ")", "else", ":", "yield", "self", ".", "client", ".", "lpush", "(", "'rhumba.q.%s'", "%", "queue", ",", "json", ".", "dumps", "(", "d", ")", ")", "defer", ".", "returnValue", "(", "d", "[", "'id'", "]", ")" ]
Queue a job in Rhumba
[ "Queue", "a", "job", "in", "Rhumba" ]
train
https://github.com/calston/rhumba/blob/05e3cbf4e531cc51b4777912eb98a4f006893f5e/rhumba/client.py#L30-L48
calston/rhumba
rhumba/client.py
AsyncRhumbaClient.getResult
def getResult(self, queue, uid, suid=None): """ Retrieve the result of a job from its ID """ if suid: r = yield self.client.get('rhumba.dq.%s.%s.%s' % (suid, queue, uid)) else: r = yield self.client.get('rhumba.q.%s.%s' % (queue, uid)) if r: defer.returnValue(json.loads(r)) else: defer.returnValue(None)
python
def getResult(self, queue, uid, suid=None): """ Retrieve the result of a job from its ID """ if suid: r = yield self.client.get('rhumba.dq.%s.%s.%s' % (suid, queue, uid)) else: r = yield self.client.get('rhumba.q.%s.%s' % (queue, uid)) if r: defer.returnValue(json.loads(r)) else: defer.returnValue(None)
[ "def", "getResult", "(", "self", ",", "queue", ",", "uid", ",", "suid", "=", "None", ")", ":", "if", "suid", ":", "r", "=", "yield", "self", ".", "client", ".", "get", "(", "'rhumba.dq.%s.%s.%s'", "%", "(", "suid", ",", "queue", ",", "uid", ")", ")", "else", ":", "r", "=", "yield", "self", ".", "client", ".", "get", "(", "'rhumba.q.%s.%s'", "%", "(", "queue", ",", "uid", ")", ")", "if", "r", ":", "defer", ".", "returnValue", "(", "json", ".", "loads", "(", "r", ")", ")", "else", ":", "defer", ".", "returnValue", "(", "None", ")" ]
Retrieve the result of a job from its ID
[ "Retrieve", "the", "result", "of", "a", "job", "from", "its", "ID" ]
train
https://github.com/calston/rhumba/blob/05e3cbf4e531cc51b4777912eb98a4f006893f5e/rhumba/client.py#L51-L64
calston/rhumba
rhumba/client.py
AsyncRhumbaClient.clusterStatus
def clusterStatus(self): """ Returns a dict of cluster nodes and their status information """ servers = yield self.client.keys('rhumba.server.*.heartbeat') d = {} now = time.time() for s in servers: sname = s.split('.', 2)[-1].rsplit('.', 1)[0] last = yield self.client.get('rhumba.server.%s.heartbeat' % sname) if not last: last = 0 status = yield self.client.get('rhumba.server.%s.status' % sname) if (status == 'ready') and (now - last > 5): status = 'offline' d[sname] = { 'lastseen': last, 'status': status } defer.returnValue(d)
python
def clusterStatus(self): """ Returns a dict of cluster nodes and their status information """ servers = yield self.client.keys('rhumba.server.*.heartbeat') d = {} now = time.time() for s in servers: sname = s.split('.', 2)[-1].rsplit('.', 1)[0] last = yield self.client.get('rhumba.server.%s.heartbeat' % sname) if not last: last = 0 status = yield self.client.get('rhumba.server.%s.status' % sname) if (status == 'ready') and (now - last > 5): status = 'offline' d[sname] = { 'lastseen': last, 'status': status } defer.returnValue(d)
[ "def", "clusterStatus", "(", "self", ")", ":", "servers", "=", "yield", "self", ".", "client", ".", "keys", "(", "'rhumba.server.*.heartbeat'", ")", "d", "=", "{", "}", "now", "=", "time", ".", "time", "(", ")", "for", "s", "in", "servers", ":", "sname", "=", "s", ".", "split", "(", "'.'", ",", "2", ")", "[", "-", "1", "]", ".", "rsplit", "(", "'.'", ",", "1", ")", "[", "0", "]", "last", "=", "yield", "self", ".", "client", ".", "get", "(", "'rhumba.server.%s.heartbeat'", "%", "sname", ")", "if", "not", "last", ":", "last", "=", "0", "status", "=", "yield", "self", ".", "client", ".", "get", "(", "'rhumba.server.%s.status'", "%", "sname", ")", "if", "(", "status", "==", "'ready'", ")", "and", "(", "now", "-", "last", ">", "5", ")", ":", "status", "=", "'offline'", "d", "[", "sname", "]", "=", "{", "'lastseen'", ":", "last", ",", "'status'", ":", "status", "}", "defer", ".", "returnValue", "(", "d", ")" ]
Returns a dict of cluster nodes and their status information
[ "Returns", "a", "dict", "of", "cluster", "nodes", "and", "their", "status", "information" ]
train
https://github.com/calston/rhumba/blob/05e3cbf4e531cc51b4777912eb98a4f006893f5e/rhumba/client.py#L67-L95
calston/rhumba
rhumba/client.py
RhumbaClient.queue
def queue(self, queue, message, params={}, uids=[]): """ Queue a job in Rhumba """ d = { 'id': uuid.uuid1().get_hex(), 'version': 1, 'message': message, 'params': params } if uids: for uid in uids: self._get_client().lpush('rhumba.dq.%s.%s' % ( uid, queue), json.dumps(d)) else: self._get_client().lpush('rhumba.q.%s' % queue, json.dumps(d)) return d['id']
python
def queue(self, queue, message, params={}, uids=[]): """ Queue a job in Rhumba """ d = { 'id': uuid.uuid1().get_hex(), 'version': 1, 'message': message, 'params': params } if uids: for uid in uids: self._get_client().lpush('rhumba.dq.%s.%s' % ( uid, queue), json.dumps(d)) else: self._get_client().lpush('rhumba.q.%s' % queue, json.dumps(d)) return d['id']
[ "def", "queue", "(", "self", ",", "queue", ",", "message", ",", "params", "=", "{", "}", ",", "uids", "=", "[", "]", ")", ":", "d", "=", "{", "'id'", ":", "uuid", ".", "uuid1", "(", ")", ".", "get_hex", "(", ")", ",", "'version'", ":", "1", ",", "'message'", ":", "message", ",", "'params'", ":", "params", "}", "if", "uids", ":", "for", "uid", "in", "uids", ":", "self", ".", "_get_client", "(", ")", ".", "lpush", "(", "'rhumba.dq.%s.%s'", "%", "(", "uid", ",", "queue", ")", ",", "json", ".", "dumps", "(", "d", ")", ")", "else", ":", "self", ".", "_get_client", "(", ")", ".", "lpush", "(", "'rhumba.q.%s'", "%", "queue", ",", "json", ".", "dumps", "(", "d", ")", ")", "return", "d", "[", "'id'", "]" ]
Queue a job in Rhumba
[ "Queue", "a", "job", "in", "Rhumba" ]
train
https://github.com/calston/rhumba/blob/05e3cbf4e531cc51b4777912eb98a4f006893f5e/rhumba/client.py#L109-L127
calston/rhumba
rhumba/client.py
RhumbaClient.getResult
def getResult(self, queue, uid, suid=None): """ Retrieve the result of a job from its ID """ if suid: r = self._get_client().get('rhumba.dq.%s.%s.%s' % (suid, queue, uid)) else: r = self._get_client().get('rhumba.q.%s.%s' % (queue, uid)) if r: return json.loads(r) else: return None
python
def getResult(self, queue, uid, suid=None): """ Retrieve the result of a job from its ID """ if suid: r = self._get_client().get('rhumba.dq.%s.%s.%s' % (suid, queue, uid)) else: r = self._get_client().get('rhumba.q.%s.%s' % (queue, uid)) if r: return json.loads(r) else: return None
[ "def", "getResult", "(", "self", ",", "queue", ",", "uid", ",", "suid", "=", "None", ")", ":", "if", "suid", ":", "r", "=", "self", ".", "_get_client", "(", ")", ".", "get", "(", "'rhumba.dq.%s.%s.%s'", "%", "(", "suid", ",", "queue", ",", "uid", ")", ")", "else", ":", "r", "=", "self", ".", "_get_client", "(", ")", ".", "get", "(", "'rhumba.q.%s.%s'", "%", "(", "queue", ",", "uid", ")", ")", "if", "r", ":", "return", "json", ".", "loads", "(", "r", ")", "else", ":", "return", "None" ]
Retrieve the result of a job from its ID
[ "Retrieve", "the", "result", "of", "a", "job", "from", "its", "ID" ]
train
https://github.com/calston/rhumba/blob/05e3cbf4e531cc51b4777912eb98a4f006893f5e/rhumba/client.py#L129-L141
calston/rhumba
rhumba/client.py
RhumbaClient.clusterStatus
def clusterStatus(self): """ Returns a dict of cluster nodes and their status information """ c = self._get_client() servers = c.keys('rhumba.server.*.heartbeat') d = {} now = time.time() for s in servers: sname = s.split('.', 2)[-1].rsplit('.', 1)[0] last = float(c.get('rhumba.server.%s.heartbeat' % sname)) status = c.get('rhumba.server.%s.status' % sname) if (status == 'ready') and (now - last > 5): status = 'offline' d[sname] = { 'lastseen': last, 'status': status } return d
python
def clusterStatus(self): """ Returns a dict of cluster nodes and their status information """ c = self._get_client() servers = c.keys('rhumba.server.*.heartbeat') d = {} now = time.time() for s in servers: sname = s.split('.', 2)[-1].rsplit('.', 1)[0] last = float(c.get('rhumba.server.%s.heartbeat' % sname)) status = c.get('rhumba.server.%s.status' % sname) if (status == 'ready') and (now - last > 5): status = 'offline' d[sname] = { 'lastseen': last, 'status': status } return d
[ "def", "clusterStatus", "(", "self", ")", ":", "c", "=", "self", ".", "_get_client", "(", ")", "servers", "=", "c", ".", "keys", "(", "'rhumba.server.*.heartbeat'", ")", "d", "=", "{", "}", "now", "=", "time", ".", "time", "(", ")", "for", "s", "in", "servers", ":", "sname", "=", "s", ".", "split", "(", "'.'", ",", "2", ")", "[", "-", "1", "]", ".", "rsplit", "(", "'.'", ",", "1", ")", "[", "0", "]", "last", "=", "float", "(", "c", ".", "get", "(", "'rhumba.server.%s.heartbeat'", "%", "sname", ")", ")", "status", "=", "c", ".", "get", "(", "'rhumba.server.%s.status'", "%", "sname", ")", "if", "(", "status", "==", "'ready'", ")", "and", "(", "now", "-", "last", ">", "5", ")", ":", "status", "=", "'offline'", "d", "[", "sname", "]", "=", "{", "'lastseen'", ":", "last", ",", "'status'", ":", "status", "}", "return", "d" ]
Returns a dict of cluster nodes and their status information
[ "Returns", "a", "dict", "of", "cluster", "nodes", "and", "their", "status", "information" ]
train
https://github.com/calston/rhumba/blob/05e3cbf4e531cc51b4777912eb98a4f006893f5e/rhumba/client.py#L143-L168
The-Politico/politico-civic-geography
geography/management/commands/bootstrap/_toposimplify.py
Toposimplify.toposimplify
def toposimplify(geojson, p): """ Convert geojson and simplify topology. geojson is a dict representing geojson. p is a simplification threshold value between 0 and 1. """ proc_out = subprocess.run( ['geo2topo'], input=bytes( json.dumps(geojson), 'utf-8'), stdout=subprocess.PIPE ) proc_out = subprocess.run( ['toposimplify', '-P', p], input=proc_out.stdout, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL ) topojson = json.loads(proc_out.stdout) # Standardize object name topojson['objects']['divisions'] = topojson['objects'].pop('-') return topojson
python
def toposimplify(geojson, p): """ Convert geojson and simplify topology. geojson is a dict representing geojson. p is a simplification threshold value between 0 and 1. """ proc_out = subprocess.run( ['geo2topo'], input=bytes( json.dumps(geojson), 'utf-8'), stdout=subprocess.PIPE ) proc_out = subprocess.run( ['toposimplify', '-P', p], input=proc_out.stdout, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL ) topojson = json.loads(proc_out.stdout) # Standardize object name topojson['objects']['divisions'] = topojson['objects'].pop('-') return topojson
[ "def", "toposimplify", "(", "geojson", ",", "p", ")", ":", "proc_out", "=", "subprocess", ".", "run", "(", "[", "'geo2topo'", "]", ",", "input", "=", "bytes", "(", "json", ".", "dumps", "(", "geojson", ")", ",", "'utf-8'", ")", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "proc_out", "=", "subprocess", ".", "run", "(", "[", "'toposimplify'", ",", "'-P'", ",", "p", "]", ",", "input", "=", "proc_out", ".", "stdout", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "DEVNULL", ")", "topojson", "=", "json", ".", "loads", "(", "proc_out", ".", "stdout", ")", "# Standardize object name", "topojson", "[", "'objects'", "]", "[", "'divisions'", "]", "=", "topojson", "[", "'objects'", "]", ".", "pop", "(", "'-'", ")", "return", "topojson" ]
Convert geojson and simplify topology. geojson is a dict representing geojson. p is a simplification threshold value between 0 and 1.
[ "Convert", "geojson", "and", "simplify", "topology", "." ]
train
https://github.com/The-Politico/politico-civic-geography/blob/032b3ee773b50b65cfe672f230dda772df0f89e0/geography/management/commands/bootstrap/_toposimplify.py#L7-L30
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/engine_func.py
get_sqlserver_product_version
def get_sqlserver_product_version(engine: "Engine") -> Tuple[int]: """ Gets SQL Server version information. Attempted to use ``dialect.server_version_info``: .. code-block:: python from sqlalchemy import create_engine url = "mssql+pyodbc://USER:PASSWORD@ODBC_NAME" engine = create_engine(url) dialect = engine.dialect vi = dialect.server_version_info Unfortunately, ``vi == ()`` for an SQL Server 2014 instance via ``mssql+pyodbc``. It's also ``None`` for a ``mysql+pymysql`` connection. So this seems ``server_version_info`` is a badly supported feature. So the only other way is to ask the database directly. The problem is that this requires an :class:`Engine` or similar. (The initial hope was to be able to use this from within SQL compilation hooks, to vary the SQL based on the engine version. Still, this isn't so bad.) We could use either .. code-block:: sql SELECT @@version; -- returns a human-readable string SELECT SERVERPROPERTY('ProductVersion'); -- better The ``pyodbc`` interface will fall over with ``ODBC SQL type -150 is not yet supported`` with that last call, though, meaning that a ``VARIANT`` is coming back, so we ``CAST`` as per the source below. """ assert is_sqlserver(engine), ( "Only call get_sqlserver_product_version() for Microsoft SQL Server " "instances." ) sql = "SELECT CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR)" rp = engine.execute(sql) # type: ResultProxy row = rp.fetchone() dotted_version = row[0] # type: str # e.g. '12.0.5203.0' return tuple(int(x) for x in dotted_version.split("."))
python
def get_sqlserver_product_version(engine: "Engine") -> Tuple[int]: """ Gets SQL Server version information. Attempted to use ``dialect.server_version_info``: .. code-block:: python from sqlalchemy import create_engine url = "mssql+pyodbc://USER:PASSWORD@ODBC_NAME" engine = create_engine(url) dialect = engine.dialect vi = dialect.server_version_info Unfortunately, ``vi == ()`` for an SQL Server 2014 instance via ``mssql+pyodbc``. It's also ``None`` for a ``mysql+pymysql`` connection. So this seems ``server_version_info`` is a badly supported feature. So the only other way is to ask the database directly. The problem is that this requires an :class:`Engine` or similar. (The initial hope was to be able to use this from within SQL compilation hooks, to vary the SQL based on the engine version. Still, this isn't so bad.) We could use either .. code-block:: sql SELECT @@version; -- returns a human-readable string SELECT SERVERPROPERTY('ProductVersion'); -- better The ``pyodbc`` interface will fall over with ``ODBC SQL type -150 is not yet supported`` with that last call, though, meaning that a ``VARIANT`` is coming back, so we ``CAST`` as per the source below. """ assert is_sqlserver(engine), ( "Only call get_sqlserver_product_version() for Microsoft SQL Server " "instances." ) sql = "SELECT CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR)" rp = engine.execute(sql) # type: ResultProxy row = rp.fetchone() dotted_version = row[0] # type: str # e.g. '12.0.5203.0' return tuple(int(x) for x in dotted_version.split("."))
[ "def", "get_sqlserver_product_version", "(", "engine", ":", "\"Engine\"", ")", "->", "Tuple", "[", "int", "]", ":", "assert", "is_sqlserver", "(", "engine", ")", ",", "(", "\"Only call get_sqlserver_product_version() for Microsoft SQL Server \"", "\"instances.\"", ")", "sql", "=", "\"SELECT CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR)\"", "rp", "=", "engine", ".", "execute", "(", "sql", ")", "# type: ResultProxy", "row", "=", "rp", ".", "fetchone", "(", ")", "dotted_version", "=", "row", "[", "0", "]", "# type: str # e.g. '12.0.5203.0'", "return", "tuple", "(", "int", "(", "x", ")", "for", "x", "in", "dotted_version", ".", "split", "(", "\".\"", ")", ")" ]
Gets SQL Server version information. Attempted to use ``dialect.server_version_info``: .. code-block:: python from sqlalchemy import create_engine url = "mssql+pyodbc://USER:PASSWORD@ODBC_NAME" engine = create_engine(url) dialect = engine.dialect vi = dialect.server_version_info Unfortunately, ``vi == ()`` for an SQL Server 2014 instance via ``mssql+pyodbc``. It's also ``None`` for a ``mysql+pymysql`` connection. So this seems ``server_version_info`` is a badly supported feature. So the only other way is to ask the database directly. The problem is that this requires an :class:`Engine` or similar. (The initial hope was to be able to use this from within SQL compilation hooks, to vary the SQL based on the engine version. Still, this isn't so bad.) We could use either .. code-block:: sql SELECT @@version; -- returns a human-readable string SELECT SERVERPROPERTY('ProductVersion'); -- better The ``pyodbc`` interface will fall over with ``ODBC SQL type -150 is not yet supported`` with that last call, though, meaning that a ``VARIANT`` is coming back, so we ``CAST`` as per the source below.
[ "Gets", "SQL", "Server", "version", "information", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/engine_func.py#L53-L96
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/engine_func.py
is_sqlserver_2008_or_later
def is_sqlserver_2008_or_later(engine: "Engine") -> bool: """ Is the SQLAlchemy :class:`Engine` an instance of Microsoft SQL Server, version 2008 or later? """ if not is_sqlserver(engine): return False version_tuple = get_sqlserver_product_version(engine) return version_tuple >= (SQLSERVER_MAJOR_VERSION_2008, )
python
def is_sqlserver_2008_or_later(engine: "Engine") -> bool: """ Is the SQLAlchemy :class:`Engine` an instance of Microsoft SQL Server, version 2008 or later? """ if not is_sqlserver(engine): return False version_tuple = get_sqlserver_product_version(engine) return version_tuple >= (SQLSERVER_MAJOR_VERSION_2008, )
[ "def", "is_sqlserver_2008_or_later", "(", "engine", ":", "\"Engine\"", ")", "->", "bool", ":", "if", "not", "is_sqlserver", "(", "engine", ")", ":", "return", "False", "version_tuple", "=", "get_sqlserver_product_version", "(", "engine", ")", "return", "version_tuple", ">=", "(", "SQLSERVER_MAJOR_VERSION_2008", ",", ")" ]
Is the SQLAlchemy :class:`Engine` an instance of Microsoft SQL Server, version 2008 or later?
[ "Is", "the", "SQLAlchemy", ":", "class", ":", "Engine", "an", "instance", "of", "Microsoft", "SQL", "Server", "version", "2008", "or", "later?" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/engine_func.py#L109-L117
davenquinn/Attitude
attitude/orientation/linear/regression.py
add_ones
def add_ones(a): """Adds a column of 1s at the end of the array""" arr = N.ones((a.shape[0],a.shape[1]+1)) arr[:,:-1] = a return arr
python
def add_ones(a): """Adds a column of 1s at the end of the array""" arr = N.ones((a.shape[0],a.shape[1]+1)) arr[:,:-1] = a return arr
[ "def", "add_ones", "(", "a", ")", ":", "arr", "=", "N", ".", "ones", "(", "(", "a", ".", "shape", "[", "0", "]", ",", "a", ".", "shape", "[", "1", "]", "+", "1", ")", ")", "arr", "[", ":", ",", ":", "-", "1", "]", "=", "a", "return", "arr" ]
Adds a column of 1s at the end of the array
[ "Adds", "a", "column", "of", "1s", "at", "the", "end", "of", "the", "array" ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/orientation/linear/regression.py#L9-L13
henzk/featuremonkey
featuremonkey/importhooks.py
ImportHookBase._uninstall
def _uninstall(cls): """ uninstall the hook if installed """ if cls._hook: sys.meta_path.remove(cls._hook) cls._hook = None
python
def _uninstall(cls): """ uninstall the hook if installed """ if cls._hook: sys.meta_path.remove(cls._hook) cls._hook = None
[ "def", "_uninstall", "(", "cls", ")", ":", "if", "cls", ".", "_hook", ":", "sys", ".", "meta_path", ".", "remove", "(", "cls", ".", "_hook", ")", "cls", ".", "_hook", "=", "None" ]
uninstall the hook if installed
[ "uninstall", "the", "hook", "if", "installed" ]
train
https://github.com/henzk/featuremonkey/blob/e44414fc68427bcd71ad33ec2d816da0dd78eefa/featuremonkey/importhooks.py#L34-L40
henzk/featuremonkey
featuremonkey/importhooks.py
LazyComposerHook.add
def add(cls, module_name, fsts, composer): ''' add a couple of fsts to be superimposed on the module given by module_name as soon as it is imported. internal - use featuremonkey.compose_later ''' cls._to_compose.setdefault(module_name, []) cls._to_compose[module_name].append( (list(fsts), composer) ) cls._install()
python
def add(cls, module_name, fsts, composer): ''' add a couple of fsts to be superimposed on the module given by module_name as soon as it is imported. internal - use featuremonkey.compose_later ''' cls._to_compose.setdefault(module_name, []) cls._to_compose[module_name].append( (list(fsts), composer) ) cls._install()
[ "def", "add", "(", "cls", ",", "module_name", ",", "fsts", ",", "composer", ")", ":", "cls", ".", "_to_compose", ".", "setdefault", "(", "module_name", ",", "[", "]", ")", "cls", ".", "_to_compose", "[", "module_name", "]", ".", "append", "(", "(", "list", "(", "fsts", ")", ",", "composer", ")", ")", "cls", ".", "_install", "(", ")" ]
add a couple of fsts to be superimposed on the module given by module_name as soon as it is imported. internal - use featuremonkey.compose_later
[ "add", "a", "couple", "of", "fsts", "to", "be", "superimposed", "on", "the", "module", "given", "by", "module_name", "as", "soon", "as", "it", "is", "imported", "." ]
train
https://github.com/henzk/featuremonkey/blob/e44414fc68427bcd71ad33ec2d816da0dd78eefa/featuremonkey/importhooks.py#L69-L80
henzk/featuremonkey
featuremonkey/importhooks.py
ImportGuardHook.add
def add(cls, module_name, msg=''): ''' Until the guard is dropped again, disallow imports of the module given by ``module_name``. If the module is imported while the guard is in place an ``ImportGuard`` is raised. An additional message on why the module cannot be imported can optionally be specified using the parameter ``msg``. If multiple guards are placed on the same module, all these guards have to be dropped before the module can be imported again. ''' if module_name in sys.modules: raise ImportGuard( 'Module to guard has already been imported: ' + module_name ) cls._guards.setdefault(module_name, []) cls._guards[module_name].append(msg) cls._num_entries += 1 cls._install()
python
def add(cls, module_name, msg=''): ''' Until the guard is dropped again, disallow imports of the module given by ``module_name``. If the module is imported while the guard is in place an ``ImportGuard`` is raised. An additional message on why the module cannot be imported can optionally be specified using the parameter ``msg``. If multiple guards are placed on the same module, all these guards have to be dropped before the module can be imported again. ''' if module_name in sys.modules: raise ImportGuard( 'Module to guard has already been imported: ' + module_name ) cls._guards.setdefault(module_name, []) cls._guards[module_name].append(msg) cls._num_entries += 1 cls._install()
[ "def", "add", "(", "cls", ",", "module_name", ",", "msg", "=", "''", ")", ":", "if", "module_name", "in", "sys", ".", "modules", ":", "raise", "ImportGuard", "(", "'Module to guard has already been imported: '", "+", "module_name", ")", "cls", ".", "_guards", ".", "setdefault", "(", "module_name", ",", "[", "]", ")", "cls", ".", "_guards", "[", "module_name", "]", ".", "append", "(", "msg", ")", "cls", ".", "_num_entries", "+=", "1", "cls", ".", "_install", "(", ")" ]
Until the guard is dropped again, disallow imports of the module given by ``module_name``. If the module is imported while the guard is in place an ``ImportGuard`` is raised. An additional message on why the module cannot be imported can optionally be specified using the parameter ``msg``. If multiple guards are placed on the same module, all these guards have to be dropped before the module can be imported again.
[ "Until", "the", "guard", "is", "dropped", "again", "disallow", "imports", "of", "the", "module", "given", "by", "module_name", "." ]
train
https://github.com/henzk/featuremonkey/blob/e44414fc68427bcd71ad33ec2d816da0dd78eefa/featuremonkey/importhooks.py#L132-L153
henzk/featuremonkey
featuremonkey/importhooks.py
ImportGuardHook.remove
def remove(cls, module_name): """ drop a previously created guard on ``module_name`` if the module is not guarded, then this is a no-op. """ module_guards = cls._guards.get(module_name, False) if module_guards: module_guards.pop() cls._num_entries -= 1 if cls._num_entries < 1: if cls._num_entries < 0: raise Exception( 'Bug: ImportGuardHook._num_entries became negative!' ) cls._uninstall()
python
def remove(cls, module_name): """ drop a previously created guard on ``module_name`` if the module is not guarded, then this is a no-op. """ module_guards = cls._guards.get(module_name, False) if module_guards: module_guards.pop() cls._num_entries -= 1 if cls._num_entries < 1: if cls._num_entries < 0: raise Exception( 'Bug: ImportGuardHook._num_entries became negative!' ) cls._uninstall()
[ "def", "remove", "(", "cls", ",", "module_name", ")", ":", "module_guards", "=", "cls", ".", "_guards", ".", "get", "(", "module_name", ",", "False", ")", "if", "module_guards", ":", "module_guards", ".", "pop", "(", ")", "cls", ".", "_num_entries", "-=", "1", "if", "cls", ".", "_num_entries", "<", "1", ":", "if", "cls", ".", "_num_entries", "<", "0", ":", "raise", "Exception", "(", "'Bug: ImportGuardHook._num_entries became negative!'", ")", "cls", ".", "_uninstall", "(", ")" ]
drop a previously created guard on ``module_name`` if the module is not guarded, then this is a no-op.
[ "drop", "a", "previously", "created", "guard", "on", "module_name", "if", "the", "module", "is", "not", "guarded", "then", "this", "is", "a", "no", "-", "op", "." ]
train
https://github.com/henzk/featuremonkey/blob/e44414fc68427bcd71ad33ec2d816da0dd78eefa/featuremonkey/importhooks.py#L156-L170
nxdevel/nx_itertools
nx_itertools/recipes.py
random_product
def random_product(*args, repeat=1): "Random selection from itertools.product(*args, **kwds)" pools = [tuple(pool) for pool in args] * repeat return tuple(random.choice(pool) for pool in pools)
python
def random_product(*args, repeat=1): "Random selection from itertools.product(*args, **kwds)" pools = [tuple(pool) for pool in args] * repeat return tuple(random.choice(pool) for pool in pools)
[ "def", "random_product", "(", "*", "args", ",", "repeat", "=", "1", ")", ":", "pools", "=", "[", "tuple", "(", "pool", ")", "for", "pool", "in", "args", "]", "*", "repeat", "return", "tuple", "(", "random", ".", "choice", "(", "pool", ")", "for", "pool", "in", "pools", ")" ]
Random selection from itertools.product(*args, **kwds)
[ "Random", "selection", "from", "itertools", ".", "product", "(", "*", "args", "**", "kwds", ")" ]
train
https://github.com/nxdevel/nx_itertools/blob/744da75c616a8a7991b963a549152fe9c434abd9/nx_itertools/recipes.py#L203-L206
JohnVinyard/featureflow
featureflow/feature.py
Feature.copy
def copy( self, extractor=None, needs=None, store=None, data_writer=None, persistence=None, extractor_args=None): """ Use self as a template to build a new feature, replacing values in kwargs """ f = Feature( extractor or self.extractor, needs=needs, store=self.store if store is None else store, encoder=self.encoder, decoder=self.decoder, key=self.key, data_writer=data_writer, persistence=persistence, **(extractor_args or self.extractor_args)) f._fixup_needs() return f
python
def copy( self, extractor=None, needs=None, store=None, data_writer=None, persistence=None, extractor_args=None): """ Use self as a template to build a new feature, replacing values in kwargs """ f = Feature( extractor or self.extractor, needs=needs, store=self.store if store is None else store, encoder=self.encoder, decoder=self.decoder, key=self.key, data_writer=data_writer, persistence=persistence, **(extractor_args or self.extractor_args)) f._fixup_needs() return f
[ "def", "copy", "(", "self", ",", "extractor", "=", "None", ",", "needs", "=", "None", ",", "store", "=", "None", ",", "data_writer", "=", "None", ",", "persistence", "=", "None", ",", "extractor_args", "=", "None", ")", ":", "f", "=", "Feature", "(", "extractor", "or", "self", ".", "extractor", ",", "needs", "=", "needs", ",", "store", "=", "self", ".", "store", "if", "store", "is", "None", "else", "store", ",", "encoder", "=", "self", ".", "encoder", ",", "decoder", "=", "self", ".", "decoder", ",", "key", "=", "self", ".", "key", ",", "data_writer", "=", "data_writer", ",", "persistence", "=", "persistence", ",", "*", "*", "(", "extractor_args", "or", "self", ".", "extractor_args", ")", ")", "f", ".", "_fixup_needs", "(", ")", "return", "f" ]
Use self as a template to build a new feature, replacing values in kwargs
[ "Use", "self", "as", "a", "template", "to", "build", "a", "new", "feature", "replacing", "values", "in", "kwargs" ]
train
https://github.com/JohnVinyard/featureflow/blob/7731487b00e38fa4f58c88b7881870fda2d69fdb/featureflow/feature.py#L107-L130
JohnVinyard/featureflow
featureflow/feature.py
Feature._can_compute
def _can_compute(self, _id, persistence): """ Return true if this feature stored, or is unstored, but can be computed from stored dependencies """ if self.store and self._stored(_id, persistence): return True if self.is_root: return False return all( [n._can_compute(_id, persistence) for n in self.dependencies])
python
def _can_compute(self, _id, persistence): """ Return true if this feature stored, or is unstored, but can be computed from stored dependencies """ if self.store and self._stored(_id, persistence): return True if self.is_root: return False return all( [n._can_compute(_id, persistence) for n in self.dependencies])
[ "def", "_can_compute", "(", "self", ",", "_id", ",", "persistence", ")", ":", "if", "self", ".", "store", "and", "self", ".", "_stored", "(", "_id", ",", "persistence", ")", ":", "return", "True", "if", "self", ".", "is_root", ":", "return", "False", "return", "all", "(", "[", "n", ".", "_can_compute", "(", "_id", ",", "persistence", ")", "for", "n", "in", "self", ".", "dependencies", "]", ")" ]
Return true if this feature stored, or is unstored, but can be computed from stored dependencies
[ "Return", "true", "if", "this", "feature", "stored", "or", "is", "unstored", "but", "can", "be", "computed", "from", "stored", "dependencies" ]
train
https://github.com/JohnVinyard/featureflow/blob/7731487b00e38fa4f58c88b7881870fda2d69fdb/featureflow/feature.py#L163-L175
JohnVinyard/featureflow
featureflow/feature.py
Feature._partial
def _partial(self, _id, features=None, persistence=None): """ TODO: _partial is a shit name for this, kind of. I'm building a graph such that I can only do work necessary to compute self, and no more """ root = features is None stored = self._stored(_id, persistence) is_cached = self.store and stored if self.store and not stored: data_writer = None elif root: data_writer = BytesIODataWriter else: data_writer = None should_store = self.store and not stored nf = self.copy( extractor=DecoderNode if is_cached else self.extractor, store=root or should_store, needs=dict(), data_writer=data_writer, persistence=self.persistence, extractor_args=dict(decodifier=self.decoder, version=self.version) \ if is_cached else self.extractor_args) if root: features = dict() features[self.key] = nf if not is_cached: for k, v in list(self.needs.items()): v._partial(_id, features=features, persistence=persistence) nf.needs[k] = features[v.key] return features
python
def _partial(self, _id, features=None, persistence=None): """ TODO: _partial is a shit name for this, kind of. I'm building a graph such that I can only do work necessary to compute self, and no more """ root = features is None stored = self._stored(_id, persistence) is_cached = self.store and stored if self.store and not stored: data_writer = None elif root: data_writer = BytesIODataWriter else: data_writer = None should_store = self.store and not stored nf = self.copy( extractor=DecoderNode if is_cached else self.extractor, store=root or should_store, needs=dict(), data_writer=data_writer, persistence=self.persistence, extractor_args=dict(decodifier=self.decoder, version=self.version) \ if is_cached else self.extractor_args) if root: features = dict() features[self.key] = nf if not is_cached: for k, v in list(self.needs.items()): v._partial(_id, features=features, persistence=persistence) nf.needs[k] = features[v.key] return features
[ "def", "_partial", "(", "self", ",", "_id", ",", "features", "=", "None", ",", "persistence", "=", "None", ")", ":", "root", "=", "features", "is", "None", "stored", "=", "self", ".", "_stored", "(", "_id", ",", "persistence", ")", "is_cached", "=", "self", ".", "store", "and", "stored", "if", "self", ".", "store", "and", "not", "stored", ":", "data_writer", "=", "None", "elif", "root", ":", "data_writer", "=", "BytesIODataWriter", "else", ":", "data_writer", "=", "None", "should_store", "=", "self", ".", "store", "and", "not", "stored", "nf", "=", "self", ".", "copy", "(", "extractor", "=", "DecoderNode", "if", "is_cached", "else", "self", ".", "extractor", ",", "store", "=", "root", "or", "should_store", ",", "needs", "=", "dict", "(", ")", ",", "data_writer", "=", "data_writer", ",", "persistence", "=", "self", ".", "persistence", ",", "extractor_args", "=", "dict", "(", "decodifier", "=", "self", ".", "decoder", ",", "version", "=", "self", ".", "version", ")", "if", "is_cached", "else", "self", ".", "extractor_args", ")", "if", "root", ":", "features", "=", "dict", "(", ")", "features", "[", "self", ".", "key", "]", "=", "nf", "if", "not", "is_cached", ":", "for", "k", ",", "v", "in", "list", "(", "self", ".", "needs", ".", "items", "(", ")", ")", ":", "v", ".", "_partial", "(", "_id", ",", "features", "=", "features", ",", "persistence", "=", "persistence", ")", "nf", ".", "needs", "[", "k", "]", "=", "features", "[", "v", ".", "key", "]", "return", "features" ]
TODO: _partial is a shit name for this, kind of. I'm building a graph such that I can only do work necessary to compute self, and no more
[ "TODO", ":", "_partial", "is", "a", "shit", "name", "for", "this", "kind", "of", ".", "I", "m", "building", "a", "graph", "such", "that", "I", "can", "only", "do", "work", "necessary", "to", "compute", "self", "and", "no", "more" ]
train
https://github.com/JohnVinyard/featureflow/blob/7731487b00e38fa4f58c88b7881870fda2d69fdb/featureflow/feature.py#L229-L267
RudolfCardinal/pythonlib
cardinal_pythonlib/dbfunc.py
genrows
def genrows(cursor: Cursor, arraysize: int = 1000) \ -> Generator[List[Any], None, None]: """ Generate all rows from a cursor. Args: cursor: the cursor arraysize: split fetches into chunks of this many records Yields: each row """ # http://code.activestate.com/recipes/137270-use-generators-for-fetching-large-db-record-sets/ # noqa while True: results = cursor.fetchmany(arraysize) if not results: break for result in results: yield result
python
def genrows(cursor: Cursor, arraysize: int = 1000) \ -> Generator[List[Any], None, None]: """ Generate all rows from a cursor. Args: cursor: the cursor arraysize: split fetches into chunks of this many records Yields: each row """ # http://code.activestate.com/recipes/137270-use-generators-for-fetching-large-db-record-sets/ # noqa while True: results = cursor.fetchmany(arraysize) if not results: break for result in results: yield result
[ "def", "genrows", "(", "cursor", ":", "Cursor", ",", "arraysize", ":", "int", "=", "1000", ")", "->", "Generator", "[", "List", "[", "Any", "]", ",", "None", ",", "None", "]", ":", "# http://code.activestate.com/recipes/137270-use-generators-for-fetching-large-db-record-sets/ # noqa", "while", "True", ":", "results", "=", "cursor", ".", "fetchmany", "(", "arraysize", ")", "if", "not", "results", ":", "break", "for", "result", "in", "results", ":", "yield", "result" ]
Generate all rows from a cursor. Args: cursor: the cursor arraysize: split fetches into chunks of this many records Yields: each row
[ "Generate", "all", "rows", "from", "a", "cursor", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dbfunc.py#L44-L62
RudolfCardinal/pythonlib
cardinal_pythonlib/dbfunc.py
genfirstvalues
def genfirstvalues(cursor: Cursor, arraysize: int = 1000) \ -> Generator[Any, None, None]: """ Generate the first value in each row. Args: cursor: the cursor arraysize: split fetches into chunks of this many records Yields: the first value of each row """ return (row[0] for row in genrows(cursor, arraysize))
python
def genfirstvalues(cursor: Cursor, arraysize: int = 1000) \ -> Generator[Any, None, None]: """ Generate the first value in each row. Args: cursor: the cursor arraysize: split fetches into chunks of this many records Yields: the first value of each row """ return (row[0] for row in genrows(cursor, arraysize))
[ "def", "genfirstvalues", "(", "cursor", ":", "Cursor", ",", "arraysize", ":", "int", "=", "1000", ")", "->", "Generator", "[", "Any", ",", "None", ",", "None", "]", ":", "return", "(", "row", "[", "0", "]", "for", "row", "in", "genrows", "(", "cursor", ",", "arraysize", ")", ")" ]
Generate the first value in each row. Args: cursor: the cursor arraysize: split fetches into chunks of this many records Yields: the first value of each row
[ "Generate", "the", "first", "value", "in", "each", "row", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dbfunc.py#L65-L77
RudolfCardinal/pythonlib
cardinal_pythonlib/dbfunc.py
gendicts
def gendicts(cursor: Cursor, arraysize: int = 1000) \ -> Generator[Dict[str, Any], None, None]: """ Generate all rows from a cursor as :class:`OrderedDict` objects. Args: cursor: the cursor arraysize: split fetches into chunks of this many records Yields: each row, as an :class:`OrderedDict` whose key are column names and whose values are the row values """ columns = get_fieldnames_from_cursor(cursor) return ( OrderedDict(zip(columns, row)) for row in genrows(cursor, arraysize) )
python
def gendicts(cursor: Cursor, arraysize: int = 1000) \ -> Generator[Dict[str, Any], None, None]: """ Generate all rows from a cursor as :class:`OrderedDict` objects. Args: cursor: the cursor arraysize: split fetches into chunks of this many records Yields: each row, as an :class:`OrderedDict` whose key are column names and whose values are the row values """ columns = get_fieldnames_from_cursor(cursor) return ( OrderedDict(zip(columns, row)) for row in genrows(cursor, arraysize) )
[ "def", "gendicts", "(", "cursor", ":", "Cursor", ",", "arraysize", ":", "int", "=", "1000", ")", "->", "Generator", "[", "Dict", "[", "str", ",", "Any", "]", ",", "None", ",", "None", "]", ":", "columns", "=", "get_fieldnames_from_cursor", "(", "cursor", ")", "return", "(", "OrderedDict", "(", "zip", "(", "columns", ",", "row", ")", ")", "for", "row", "in", "genrows", "(", "cursor", ",", "arraysize", ")", ")" ]
Generate all rows from a cursor as :class:`OrderedDict` objects. Args: cursor: the cursor arraysize: split fetches into chunks of this many records Yields: each row, as an :class:`OrderedDict` whose key are column names and whose values are the row values
[ "Generate", "all", "rows", "from", "a", "cursor", "as", ":", "class", ":", "OrderedDict", "objects", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dbfunc.py#L87-L104
RudolfCardinal/pythonlib
cardinal_pythonlib/dbfunc.py
dictfetchall
def dictfetchall(cursor: Cursor) -> List[Dict[str, Any]]: """ Return all rows from a cursor as a list of :class:`OrderedDict` objects. Args: cursor: the cursor Returns: a list (one item per row) of :class:`OrderedDict` objects whose key are column names and whose values are the row values """ columns = get_fieldnames_from_cursor(cursor) return [ OrderedDict(zip(columns, row)) for row in cursor.fetchall() ]
python
def dictfetchall(cursor: Cursor) -> List[Dict[str, Any]]: """ Return all rows from a cursor as a list of :class:`OrderedDict` objects. Args: cursor: the cursor Returns: a list (one item per row) of :class:`OrderedDict` objects whose key are column names and whose values are the row values """ columns = get_fieldnames_from_cursor(cursor) return [ OrderedDict(zip(columns, row)) for row in cursor.fetchall() ]
[ "def", "dictfetchall", "(", "cursor", ":", "Cursor", ")", "->", "List", "[", "Dict", "[", "str", ",", "Any", "]", "]", ":", "columns", "=", "get_fieldnames_from_cursor", "(", "cursor", ")", "return", "[", "OrderedDict", "(", "zip", "(", "columns", ",", "row", ")", ")", "for", "row", "in", "cursor", ".", "fetchall", "(", ")", "]" ]
Return all rows from a cursor as a list of :class:`OrderedDict` objects. Args: cursor: the cursor Returns: a list (one item per row) of :class:`OrderedDict` objects whose key are column names and whose values are the row values
[ "Return", "all", "rows", "from", "a", "cursor", "as", "a", "list", "of", ":", "class", ":", "OrderedDict", "objects", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dbfunc.py#L107-L122
RudolfCardinal/pythonlib
cardinal_pythonlib/dbfunc.py
dictfetchone
def dictfetchone(cursor: Cursor) -> Optional[Dict[str, Any]]: """ Return the next row from a cursor as an :class:`OrderedDict`, or ``None``. """ columns = get_fieldnames_from_cursor(cursor) row = cursor.fetchone() if not row: return None return OrderedDict(zip(columns, row))
python
def dictfetchone(cursor: Cursor) -> Optional[Dict[str, Any]]: """ Return the next row from a cursor as an :class:`OrderedDict`, or ``None``. """ columns = get_fieldnames_from_cursor(cursor) row = cursor.fetchone() if not row: return None return OrderedDict(zip(columns, row))
[ "def", "dictfetchone", "(", "cursor", ":", "Cursor", ")", "->", "Optional", "[", "Dict", "[", "str", ",", "Any", "]", "]", ":", "columns", "=", "get_fieldnames_from_cursor", "(", "cursor", ")", "row", "=", "cursor", ".", "fetchone", "(", ")", "if", "not", "row", ":", "return", "None", "return", "OrderedDict", "(", "zip", "(", "columns", ",", "row", ")", ")" ]
Return the next row from a cursor as an :class:`OrderedDict`, or ``None``.
[ "Return", "the", "next", "row", "from", "a", "cursor", "as", "an", ":", "class", ":", "OrderedDict", "or", "None", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dbfunc.py#L125-L133
RudolfCardinal/pythonlib
cardinal_pythonlib/colander_utils.py
get_values_and_permissible
def get_values_and_permissible(values: Iterable[Tuple[Any, str]], add_none: bool = False, none_description: str = "[None]") \ -> Tuple[List[Tuple[Any, str]], List[Any]]: """ Used when building Colander nodes. Args: values: an iterable of tuples like ``(value, description)`` used in HTML forms add_none: add a tuple ``(None, none_description)`` at the start of ``values`` in the result? none_description: the description used for ``None`` if ``add_none`` is set Returns: a tuple ``(values, permissible_values)``, where - ``values`` is what was passed in (perhaps with the addition of the "None" tuple at the start) - ``permissible_values`` is a list of all the ``value`` elements of the original ``values`` """ permissible_values = list(x[0] for x in values) # ... does not include the None value; those do not go to the validator if add_none: none_tuple = (SERIALIZED_NONE, none_description) values = [none_tuple] + list(values) return values, permissible_values
python
def get_values_and_permissible(values: Iterable[Tuple[Any, str]], add_none: bool = False, none_description: str = "[None]") \ -> Tuple[List[Tuple[Any, str]], List[Any]]: """ Used when building Colander nodes. Args: values: an iterable of tuples like ``(value, description)`` used in HTML forms add_none: add a tuple ``(None, none_description)`` at the start of ``values`` in the result? none_description: the description used for ``None`` if ``add_none`` is set Returns: a tuple ``(values, permissible_values)``, where - ``values`` is what was passed in (perhaps with the addition of the "None" tuple at the start) - ``permissible_values`` is a list of all the ``value`` elements of the original ``values`` """ permissible_values = list(x[0] for x in values) # ... does not include the None value; those do not go to the validator if add_none: none_tuple = (SERIALIZED_NONE, none_description) values = [none_tuple] + list(values) return values, permissible_values
[ "def", "get_values_and_permissible", "(", "values", ":", "Iterable", "[", "Tuple", "[", "Any", ",", "str", "]", "]", ",", "add_none", ":", "bool", "=", "False", ",", "none_description", ":", "str", "=", "\"[None]\"", ")", "->", "Tuple", "[", "List", "[", "Tuple", "[", "Any", ",", "str", "]", "]", ",", "List", "[", "Any", "]", "]", ":", "permissible_values", "=", "list", "(", "x", "[", "0", "]", "for", "x", "in", "values", ")", "# ... does not include the None value; those do not go to the validator", "if", "add_none", ":", "none_tuple", "=", "(", "SERIALIZED_NONE", ",", "none_description", ")", "values", "=", "[", "none_tuple", "]", "+", "list", "(", "values", ")", "return", "values", ",", "permissible_values" ]
Used when building Colander nodes. Args: values: an iterable of tuples like ``(value, description)`` used in HTML forms add_none: add a tuple ``(None, none_description)`` at the start of ``values`` in the result? none_description: the description used for ``None`` if ``add_none`` is set Returns: a tuple ``(values, permissible_values)``, where - ``values`` is what was passed in (perhaps with the addition of the "None" tuple at the start) - ``permissible_values`` is a list of all the ``value`` elements of the original ``values``
[ "Used", "when", "building", "Colander", "nodes", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/colander_utils.py#L198-L229
RudolfCardinal/pythonlib
cardinal_pythonlib/colander_utils.py
PendulumType.serialize
def serialize(self, node: SchemaNode, appstruct: Union[PotentialDatetimeType, ColanderNullType]) \ -> Union[str, ColanderNullType]: """ Serializes Python object to string representation. """ if not appstruct: return colander.null try: appstruct = coerce_to_pendulum(appstruct, assume_local=self.use_local_tz) except (ValueError, ParserError) as e: raise Invalid( node, "{!r} is not a pendulum.DateTime object; error was " "{!r}".format(appstruct, e)) return appstruct.isoformat()
python
def serialize(self, node: SchemaNode, appstruct: Union[PotentialDatetimeType, ColanderNullType]) \ -> Union[str, ColanderNullType]: """ Serializes Python object to string representation. """ if not appstruct: return colander.null try: appstruct = coerce_to_pendulum(appstruct, assume_local=self.use_local_tz) except (ValueError, ParserError) as e: raise Invalid( node, "{!r} is not a pendulum.DateTime object; error was " "{!r}".format(appstruct, e)) return appstruct.isoformat()
[ "def", "serialize", "(", "self", ",", "node", ":", "SchemaNode", ",", "appstruct", ":", "Union", "[", "PotentialDatetimeType", ",", "ColanderNullType", "]", ")", "->", "Union", "[", "str", ",", "ColanderNullType", "]", ":", "if", "not", "appstruct", ":", "return", "colander", ".", "null", "try", ":", "appstruct", "=", "coerce_to_pendulum", "(", "appstruct", ",", "assume_local", "=", "self", ".", "use_local_tz", ")", "except", "(", "ValueError", ",", "ParserError", ")", "as", "e", ":", "raise", "Invalid", "(", "node", ",", "\"{!r} is not a pendulum.DateTime object; error was \"", "\"{!r}\"", ".", "format", "(", "appstruct", ",", "e", ")", ")", "return", "appstruct", ".", "isoformat", "(", ")" ]
Serializes Python object to string representation.
[ "Serializes", "Python", "object", "to", "string", "representation", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/colander_utils.py#L100-L118
RudolfCardinal/pythonlib
cardinal_pythonlib/colander_utils.py
PendulumType.deserialize
def deserialize(self, node: SchemaNode, cstruct: Union[str, ColanderNullType]) \ -> Optional[Pendulum]: """ Deserializes string representation to Python object. """ if not cstruct: return colander.null try: result = coerce_to_pendulum(cstruct, assume_local=self.use_local_tz) except (ValueError, ParserError) as e: raise Invalid(node, "Invalid date/time: value={!r}, error=" "{!r}".format(cstruct, e)) return result
python
def deserialize(self, node: SchemaNode, cstruct: Union[str, ColanderNullType]) \ -> Optional[Pendulum]: """ Deserializes string representation to Python object. """ if not cstruct: return colander.null try: result = coerce_to_pendulum(cstruct, assume_local=self.use_local_tz) except (ValueError, ParserError) as e: raise Invalid(node, "Invalid date/time: value={!r}, error=" "{!r}".format(cstruct, e)) return result
[ "def", "deserialize", "(", "self", ",", "node", ":", "SchemaNode", ",", "cstruct", ":", "Union", "[", "str", ",", "ColanderNullType", "]", ")", "->", "Optional", "[", "Pendulum", "]", ":", "if", "not", "cstruct", ":", "return", "colander", ".", "null", "try", ":", "result", "=", "coerce_to_pendulum", "(", "cstruct", ",", "assume_local", "=", "self", ".", "use_local_tz", ")", "except", "(", "ValueError", ",", "ParserError", ")", "as", "e", ":", "raise", "Invalid", "(", "node", ",", "\"Invalid date/time: value={!r}, error=\"", "\"{!r}\"", ".", "format", "(", "cstruct", ",", "e", ")", ")", "return", "result" ]
Deserializes string representation to Python object.
[ "Deserializes", "string", "representation", "to", "Python", "object", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/colander_utils.py#L120-L135
RudolfCardinal/pythonlib
cardinal_pythonlib/colander_utils.py
AllowNoneType.serialize
def serialize(self, node: SchemaNode, value: Any) -> Union[str, ColanderNullType]: """ Serializes Python object to string representation. """ if value is None: retval = '' else: # noinspection PyUnresolvedReferences retval = self.type_.serialize(node, value) # log.debug("AllowNoneType.serialize: {!r} -> {!r}", value, retval) return retval
python
def serialize(self, node: SchemaNode, value: Any) -> Union[str, ColanderNullType]: """ Serializes Python object to string representation. """ if value is None: retval = '' else: # noinspection PyUnresolvedReferences retval = self.type_.serialize(node, value) # log.debug("AllowNoneType.serialize: {!r} -> {!r}", value, retval) return retval
[ "def", "serialize", "(", "self", ",", "node", ":", "SchemaNode", ",", "value", ":", "Any", ")", "->", "Union", "[", "str", ",", "ColanderNullType", "]", ":", "if", "value", "is", "None", ":", "retval", "=", "''", "else", ":", "# noinspection PyUnresolvedReferences", "retval", "=", "self", ".", "type_", ".", "serialize", "(", "node", ",", "value", ")", "# log.debug(\"AllowNoneType.serialize: {!r} -> {!r}\", value, retval)", "return", "retval" ]
Serializes Python object to string representation.
[ "Serializes", "Python", "object", "to", "string", "representation", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/colander_utils.py#L167-L178
henzk/featuremonkey
featuremonkey/composer.py
get_features_from_equation_file
def get_features_from_equation_file(filename): """ returns list of feature names read from equation file given by ``filename``. format: one feature per line; comments start with ``#`` Example:: #this is a comment basefeature #empty lines are ignored myfeature anotherfeature :param filename: :return: """ features = [] for line in open(filename): line = line.split('#')[0].strip() if line: features.append(line) return features
python
def get_features_from_equation_file(filename): """ returns list of feature names read from equation file given by ``filename``. format: one feature per line; comments start with ``#`` Example:: #this is a comment basefeature #empty lines are ignored myfeature anotherfeature :param filename: :return: """ features = [] for line in open(filename): line = line.split('#')[0].strip() if line: features.append(line) return features
[ "def", "get_features_from_equation_file", "(", "filename", ")", ":", "features", "=", "[", "]", "for", "line", "in", "open", "(", "filename", ")", ":", "line", "=", "line", ".", "split", "(", "'#'", ")", "[", "0", "]", ".", "strip", "(", ")", "if", "line", ":", "features", ".", "append", "(", "line", ")", "return", "features" ]
returns list of feature names read from equation file given by ``filename``. format: one feature per line; comments start with ``#`` Example:: #this is a comment basefeature #empty lines are ignored myfeature anotherfeature :param filename: :return:
[ "returns", "list", "of", "feature", "names", "read", "from", "equation", "file", "given", "by", "filename", "." ]
train
https://github.com/henzk/featuremonkey/blob/e44414fc68427bcd71ad33ec2d816da0dd78eefa/featuremonkey/composer.py#L19-L42
henzk/featuremonkey
featuremonkey/composer.py
Composer._create_refinement_wrapper
def _create_refinement_wrapper(transformation, baseattr, base, target_attrname): """ applies refinement ``transformation`` to ``baseattr`` attribute of ``base``. ``baseattr`` can be any type of callable (function, method, functor) this method handles the differences. docstrings are also rescued from the original if the refinement has no docstring set. """ # first step: extract the original special_refinement_type=None instance_refinement = _is_class_instance(base) if instance_refinement: dictelem = base.__class__.__dict__.get(target_attrname, None) else: dictelem = base.__dict__.get(target_attrname, None) if isinstance(dictelem, staticmethod): special_refinement_type = 'staticmethod' original = _extract_staticmethod(dictelem) elif isinstance(dictelem, classmethod): special_refinement_type = 'classmethod' original = _extract_classmethod(dictelem) else: if instance_refinement: # methods need a delegator original = _delegate(baseattr) # TODO: evaluate this: # original = base.__class__.__dict__[target_attrname] else: # default handling original = baseattr # step two: call the refinement passing it the original # the result is the wrapper wrapper = transformation(original) # rescue docstring if not wrapper.__doc__: wrapper.__doc__ = baseattr.__doc__ # step three: make wrapper ready for injection if special_refinement_type == 'staticmethod': wrapper = staticmethod(wrapper) elif special_refinement_type == 'classmethod': wrapper = classmethod(wrapper) if instance_refinement: wrapper = wrapper.__get__(base, base.__class__) return wrapper
python
def _create_refinement_wrapper(transformation, baseattr, base, target_attrname): """ applies refinement ``transformation`` to ``baseattr`` attribute of ``base``. ``baseattr`` can be any type of callable (function, method, functor) this method handles the differences. docstrings are also rescued from the original if the refinement has no docstring set. """ # first step: extract the original special_refinement_type=None instance_refinement = _is_class_instance(base) if instance_refinement: dictelem = base.__class__.__dict__.get(target_attrname, None) else: dictelem = base.__dict__.get(target_attrname, None) if isinstance(dictelem, staticmethod): special_refinement_type = 'staticmethod' original = _extract_staticmethod(dictelem) elif isinstance(dictelem, classmethod): special_refinement_type = 'classmethod' original = _extract_classmethod(dictelem) else: if instance_refinement: # methods need a delegator original = _delegate(baseattr) # TODO: evaluate this: # original = base.__class__.__dict__[target_attrname] else: # default handling original = baseattr # step two: call the refinement passing it the original # the result is the wrapper wrapper = transformation(original) # rescue docstring if not wrapper.__doc__: wrapper.__doc__ = baseattr.__doc__ # step three: make wrapper ready for injection if special_refinement_type == 'staticmethod': wrapper = staticmethod(wrapper) elif special_refinement_type == 'classmethod': wrapper = classmethod(wrapper) if instance_refinement: wrapper = wrapper.__get__(base, base.__class__) return wrapper
[ "def", "_create_refinement_wrapper", "(", "transformation", ",", "baseattr", ",", "base", ",", "target_attrname", ")", ":", "# first step: extract the original", "special_refinement_type", "=", "None", "instance_refinement", "=", "_is_class_instance", "(", "base", ")", "if", "instance_refinement", ":", "dictelem", "=", "base", ".", "__class__", ".", "__dict__", ".", "get", "(", "target_attrname", ",", "None", ")", "else", ":", "dictelem", "=", "base", ".", "__dict__", ".", "get", "(", "target_attrname", ",", "None", ")", "if", "isinstance", "(", "dictelem", ",", "staticmethod", ")", ":", "special_refinement_type", "=", "'staticmethod'", "original", "=", "_extract_staticmethod", "(", "dictelem", ")", "elif", "isinstance", "(", "dictelem", ",", "classmethod", ")", ":", "special_refinement_type", "=", "'classmethod'", "original", "=", "_extract_classmethod", "(", "dictelem", ")", "else", ":", "if", "instance_refinement", ":", "# methods need a delegator", "original", "=", "_delegate", "(", "baseattr", ")", "# TODO: evaluate this:", "# original = base.__class__.__dict__[target_attrname]", "else", ":", "# default handling", "original", "=", "baseattr", "# step two: call the refinement passing it the original", "# the result is the wrapper", "wrapper", "=", "transformation", "(", "original", ")", "# rescue docstring", "if", "not", "wrapper", ".", "__doc__", ":", "wrapper", ".", "__doc__", "=", "baseattr", ".", "__doc__", "# step three: make wrapper ready for injection", "if", "special_refinement_type", "==", "'staticmethod'", ":", "wrapper", "=", "staticmethod", "(", "wrapper", ")", "elif", "special_refinement_type", "==", "'classmethod'", ":", "wrapper", "=", "classmethod", "(", "wrapper", ")", "if", "instance_refinement", ":", "wrapper", "=", "wrapper", ".", "__get__", "(", "base", ",", "base", ".", "__class__", ")", "return", "wrapper" ]
applies refinement ``transformation`` to ``baseattr`` attribute of ``base``. ``baseattr`` can be any type of callable (function, method, functor) this method handles the differences. docstrings are also rescued from the original if the refinement has no docstring set.
[ "applies", "refinement", "transformation", "to", "baseattr", "attribute", "of", "base", ".", "baseattr", "can", "be", "any", "type", "of", "callable", "(", "function", "method", "functor", ")", "this", "method", "handles", "the", "differences", ".", "docstrings", "are", "also", "rescued", "from", "the", "original", "if", "the", "refinement", "has", "no", "docstring", "set", "." ]
train
https://github.com/henzk/featuremonkey/blob/e44414fc68427bcd71ad33ec2d816da0dd78eefa/featuremonkey/composer.py#L155-L205
henzk/featuremonkey
featuremonkey/composer.py
Composer._compose_pair
def _compose_pair(self, role, base): ''' composes onto base by applying the role ''' # apply transformations in role to base for attrname in dir(role): transformation = getattr(role, attrname) self._apply_transformation(role, base, transformation, attrname) return base
python
def _compose_pair(self, role, base): ''' composes onto base by applying the role ''' # apply transformations in role to base for attrname in dir(role): transformation = getattr(role, attrname) self._apply_transformation(role, base, transformation, attrname) return base
[ "def", "_compose_pair", "(", "self", ",", "role", ",", "base", ")", ":", "# apply transformations in role to base", "for", "attrname", "in", "dir", "(", "role", ")", ":", "transformation", "=", "getattr", "(", "role", ",", "attrname", ")", "self", ".", "_apply_transformation", "(", "role", ",", "base", ",", "transformation", ",", "attrname", ")", "return", "base" ]
composes onto base by applying the role
[ "composes", "onto", "base", "by", "applying", "the", "role" ]
train
https://github.com/henzk/featuremonkey/blob/e44414fc68427bcd71ad33ec2d816da0dd78eefa/featuremonkey/composer.py#L219-L228
henzk/featuremonkey
featuremonkey/composer.py
Composer.compose
def compose(self, *things): ''' compose applies multiple fsts onto a base implementation. Pass the base implementation as last parameter. fsts are merged from RIGHT TO LEFT (like function application) e.g.: class MyFST(object): #place introductions and refinements here introduce_foo = 'bar' compose(MyFST(), MyClass) ''' if not len(things): raise CompositionError('nothing to compose') if len(things) == 1: # composing one element is simple return things[0] else: # recurse after applying last role to object return self.compose(*( list(things[:-2]) # all but the last two # plus the composition of the last two + [self._compose_pair(things[-2], things[-1])] ))
python
def compose(self, *things): ''' compose applies multiple fsts onto a base implementation. Pass the base implementation as last parameter. fsts are merged from RIGHT TO LEFT (like function application) e.g.: class MyFST(object): #place introductions and refinements here introduce_foo = 'bar' compose(MyFST(), MyClass) ''' if not len(things): raise CompositionError('nothing to compose') if len(things) == 1: # composing one element is simple return things[0] else: # recurse after applying last role to object return self.compose(*( list(things[:-2]) # all but the last two # plus the composition of the last two + [self._compose_pair(things[-2], things[-1])] ))
[ "def", "compose", "(", "self", ",", "*", "things", ")", ":", "if", "not", "len", "(", "things", ")", ":", "raise", "CompositionError", "(", "'nothing to compose'", ")", "if", "len", "(", "things", ")", "==", "1", ":", "# composing one element is simple", "return", "things", "[", "0", "]", "else", ":", "# recurse after applying last role to object", "return", "self", ".", "compose", "(", "*", "(", "list", "(", "things", "[", ":", "-", "2", "]", ")", "# all but the last two", "# plus the composition of the last two", "+", "[", "self", ".", "_compose_pair", "(", "things", "[", "-", "2", "]", ",", "things", "[", "-", "1", "]", ")", "]", ")", ")" ]
compose applies multiple fsts onto a base implementation. Pass the base implementation as last parameter. fsts are merged from RIGHT TO LEFT (like function application) e.g.: class MyFST(object): #place introductions and refinements here introduce_foo = 'bar' compose(MyFST(), MyClass)
[ "compose", "applies", "multiple", "fsts", "onto", "a", "base", "implementation", ".", "Pass", "the", "base", "implementation", "as", "last", "parameter", ".", "fsts", "are", "merged", "from", "RIGHT", "TO", "LEFT", "(", "like", "function", "application", ")", "e", ".", "g", ".", ":" ]
train
https://github.com/henzk/featuremonkey/blob/e44414fc68427bcd71ad33ec2d816da0dd78eefa/featuremonkey/composer.py#L230-L254
henzk/featuremonkey
featuremonkey/composer.py
Composer.compose_later
def compose_later(self, *things): """ register list of things for composition using compose() compose_later takes a list of fsts. The last element specifies the base module as string things are composed directly after the base module is imported by application code """ if len(things) == 1: return things[0] module_name = things[-1] if module_name in sys.modules: raise CompositionError( 'compose_later call after module has been imported: ' + module_name ) LazyComposerHook.add(module_name, things[:-1], self)
python
def compose_later(self, *things): """ register list of things for composition using compose() compose_later takes a list of fsts. The last element specifies the base module as string things are composed directly after the base module is imported by application code """ if len(things) == 1: return things[0] module_name = things[-1] if module_name in sys.modules: raise CompositionError( 'compose_later call after module has been imported: ' + module_name ) LazyComposerHook.add(module_name, things[:-1], self)
[ "def", "compose_later", "(", "self", ",", "*", "things", ")", ":", "if", "len", "(", "things", ")", "==", "1", ":", "return", "things", "[", "0", "]", "module_name", "=", "things", "[", "-", "1", "]", "if", "module_name", "in", "sys", ".", "modules", ":", "raise", "CompositionError", "(", "'compose_later call after module has been imported: '", "+", "module_name", ")", "LazyComposerHook", ".", "add", "(", "module_name", ",", "things", "[", ":", "-", "1", "]", ",", "self", ")" ]
register list of things for composition using compose() compose_later takes a list of fsts. The last element specifies the base module as string things are composed directly after the base module is imported by application code
[ "register", "list", "of", "things", "for", "composition", "using", "compose", "()" ]
train
https://github.com/henzk/featuremonkey/blob/e44414fc68427bcd71ad33ec2d816da0dd78eefa/featuremonkey/composer.py#L256-L273
henzk/featuremonkey
featuremonkey/composer.py
Composer.select
def select(self, *features): """ selects the features given as string e.g passing 'hello' and 'world' will result in imports of 'hello' and 'world'. Then, if possible 'hello.feature' and 'world.feature' are imported and select is called in each feature module. """ for feature_name in features: feature_module = importlib.import_module(feature_name) # if available, import feature.py and select the feature try: feature_spec_module = importlib.import_module( feature_name + '.feature' ) if not hasattr(feature_spec_module, 'select'): raise CompositionError( 'Function %s.feature.select not found!\n ' 'Feature modules need to specify a function' ' select(composer).' % ( feature_name ) ) args, varargs, keywords, defaults = inspect.getargspec( feature_spec_module.select ) if varargs or keywords or defaults or len(args) != 1: raise CompositionError( 'invalid signature: %s.feature.select must ' 'have the signature select(composer)' % ( feature_name ) ) # call the feature`s select function feature_spec_module.select(self) except ImportError: # Unfortunately, python makes it really hard # to distinguish missing modules from modules # that contain errors. # Hacks like parsing the exception message will # not work reliably due to import hooks and such. # Conclusion: features must contain a feature.py for now # re-raise raise
python
def select(self, *features): """ selects the features given as string e.g passing 'hello' and 'world' will result in imports of 'hello' and 'world'. Then, if possible 'hello.feature' and 'world.feature' are imported and select is called in each feature module. """ for feature_name in features: feature_module = importlib.import_module(feature_name) # if available, import feature.py and select the feature try: feature_spec_module = importlib.import_module( feature_name + '.feature' ) if not hasattr(feature_spec_module, 'select'): raise CompositionError( 'Function %s.feature.select not found!\n ' 'Feature modules need to specify a function' ' select(composer).' % ( feature_name ) ) args, varargs, keywords, defaults = inspect.getargspec( feature_spec_module.select ) if varargs or keywords or defaults or len(args) != 1: raise CompositionError( 'invalid signature: %s.feature.select must ' 'have the signature select(composer)' % ( feature_name ) ) # call the feature`s select function feature_spec_module.select(self) except ImportError: # Unfortunately, python makes it really hard # to distinguish missing modules from modules # that contain errors. # Hacks like parsing the exception message will # not work reliably due to import hooks and such. # Conclusion: features must contain a feature.py for now # re-raise raise
[ "def", "select", "(", "self", ",", "*", "features", ")", ":", "for", "feature_name", "in", "features", ":", "feature_module", "=", "importlib", ".", "import_module", "(", "feature_name", ")", "# if available, import feature.py and select the feature", "try", ":", "feature_spec_module", "=", "importlib", ".", "import_module", "(", "feature_name", "+", "'.feature'", ")", "if", "not", "hasattr", "(", "feature_spec_module", ",", "'select'", ")", ":", "raise", "CompositionError", "(", "'Function %s.feature.select not found!\\n '", "'Feature modules need to specify a function'", "' select(composer).'", "%", "(", "feature_name", ")", ")", "args", ",", "varargs", ",", "keywords", ",", "defaults", "=", "inspect", ".", "getargspec", "(", "feature_spec_module", ".", "select", ")", "if", "varargs", "or", "keywords", "or", "defaults", "or", "len", "(", "args", ")", "!=", "1", ":", "raise", "CompositionError", "(", "'invalid signature: %s.feature.select must '", "'have the signature select(composer)'", "%", "(", "feature_name", ")", ")", "# call the feature`s select function", "feature_spec_module", ".", "select", "(", "self", ")", "except", "ImportError", ":", "# Unfortunately, python makes it really hard", "# to distinguish missing modules from modules", "# that contain errors.", "# Hacks like parsing the exception message will", "# not work reliably due to import hooks and such.", "# Conclusion: features must contain a feature.py for now", "# re-raise", "raise" ]
selects the features given as string e.g passing 'hello' and 'world' will result in imports of 'hello' and 'world'. Then, if possible 'hello.feature' and 'world.feature' are imported and select is called in each feature module.
[ "selects", "the", "features", "given", "as", "string", "e", ".", "g", "passing", "hello", "and", "world", "will", "result", "in", "imports", "of", "hello", "and", "world", ".", "Then", "if", "possible", "hello", ".", "feature", "and", "world", ".", "feature", "are", "imported", "and", "select", "is", "called", "in", "each", "feature", "module", "." ]
train
https://github.com/henzk/featuremonkey/blob/e44414fc68427bcd71ad33ec2d816da0dd78eefa/featuremonkey/composer.py#L275-L320
davenquinn/Attitude
attitude/display/pca_aligned.py
plot_aligned
def plot_aligned(pca, sparse=True, **kwargs): """ Plots the residuals of a principal component analysis of attiude data. """ colormap = kwargs.pop('colormap',None) A = pca.rotated() # Flip the result if upside down if pca.normal[2] < 0: A[:,-1] *= -1 minmax = [(A[:,i].min(),A[:,i].max()) for i in range(3)] lengths = [j-i for i,j in minmax] if sparse: i = 1 l = len(A) if l > 10000: i = N.ceil(l/10000) A = A[::int(i)] log.info("Plotting with {} points".format(len(A))) w = 8 ratio = (lengths[2]*2+lengths[1])/lengths[0]*1.5 h = w*ratio if h < 3: h = 3 r = (lengths[1]+5)/(lengths[2]+5) if r > 5: r = 5 fig = Figure(figsize=(w,h)) fig.canvas = FigureCanvas(fig) def setup_axes(): gs = GridSpec(3,1, height_ratios=[r,1,1]) kwargs = dict() axes = [] for g in gs: ax = fig.add_subplot(g,**kwargs) kwargs['sharex'] = ax yield ax axes = list(setup_axes()) fig.subplots_adjust(hspace=0, wspace=0.1) #lengths = attitude.pca.singular_values[::-1] titles = ( "Plan view", "Long cross-section", "Short cross-section") ylabels = ( "Meters", "Residuals (m)", "Residuals (m)") colors = ['cornflowerblue','red'] hyp = sampling_axes(pca) vertical = vector(0,0,1) for title,ax,(a,b),ylabel in zip(titles,axes, [(0,1),(0,2),(1,2)],ylabels): kw = dict(linewidth=2, alpha=0.5) bounds = minmax[a] if b != 2: ax.plot(bounds,(0,0), c=colors[a], **kw) ax.plot((0,0),minmax[b], c=colors[b], **kw) else: ax.plot(bounds,(-10,-10), c=colors[a], **kw) v0 = N.zeros(3) v0[a] = 1 axes = N.array([v0,vertical]) ax_ = (axes@N.diag(hyp)@axes.T).T ax_ = N.sqrt(ax_) l1 = N.linalg.norm(ax_[:-1]) l2 = N.linalg.norm(ax_[-1]) ang_error = 2*N.degrees(N.arctan2(l2,l1)) title += ": {:.0f} m long, angular error (95% CI): {:.2f}º".format(lengths[a], ang_error) bounds = minmax[0] x_ = N.linspace(bounds[0]*1.2,bounds[1]*1.2,100) err = HyperbolicErrors(hyp,x_,axes=axes) err.plot(ax, fc='#cccccc', alpha=0.3) x,y = A[:,a], A[:,b] kw = dict(alpha=0.5, zorder=5) if colormap is None: ax.plot(x,y,c="#555555", linestyle='None', marker='.',**kw) else: ax.scatter(x,y,c=A[:,-1], cmap=colormap, **kw) #ax.set_aspect("equal") ax.text(0.01,.99,title, verticalalignment='top', transform=ax.transAxes) #ax.autoscale(tight=True) ax.yaxis.set_ticks([]) ax.xaxis.set_ticks_position('bottom') if a != 1: pass #ax.xaxis.set_ticks([]) #ax.spines['bottom'].set_color('none') for spine in ax.spines.values(): spine.set_visible(False) ax.text(0.99,0.99,"Max residual: {:.1f} m".format(lengths[2]), verticalalignment='bottom', ha='right', transform=ax.transAxes) ax.set_xlabel("Meters") return fig
python
def plot_aligned(pca, sparse=True, **kwargs): """ Plots the residuals of a principal component analysis of attiude data. """ colormap = kwargs.pop('colormap',None) A = pca.rotated() # Flip the result if upside down if pca.normal[2] < 0: A[:,-1] *= -1 minmax = [(A[:,i].min(),A[:,i].max()) for i in range(3)] lengths = [j-i for i,j in minmax] if sparse: i = 1 l = len(A) if l > 10000: i = N.ceil(l/10000) A = A[::int(i)] log.info("Plotting with {} points".format(len(A))) w = 8 ratio = (lengths[2]*2+lengths[1])/lengths[0]*1.5 h = w*ratio if h < 3: h = 3 r = (lengths[1]+5)/(lengths[2]+5) if r > 5: r = 5 fig = Figure(figsize=(w,h)) fig.canvas = FigureCanvas(fig) def setup_axes(): gs = GridSpec(3,1, height_ratios=[r,1,1]) kwargs = dict() axes = [] for g in gs: ax = fig.add_subplot(g,**kwargs) kwargs['sharex'] = ax yield ax axes = list(setup_axes()) fig.subplots_adjust(hspace=0, wspace=0.1) #lengths = attitude.pca.singular_values[::-1] titles = ( "Plan view", "Long cross-section", "Short cross-section") ylabels = ( "Meters", "Residuals (m)", "Residuals (m)") colors = ['cornflowerblue','red'] hyp = sampling_axes(pca) vertical = vector(0,0,1) for title,ax,(a,b),ylabel in zip(titles,axes, [(0,1),(0,2),(1,2)],ylabels): kw = dict(linewidth=2, alpha=0.5) bounds = minmax[a] if b != 2: ax.plot(bounds,(0,0), c=colors[a], **kw) ax.plot((0,0),minmax[b], c=colors[b], **kw) else: ax.plot(bounds,(-10,-10), c=colors[a], **kw) v0 = N.zeros(3) v0[a] = 1 axes = N.array([v0,vertical]) ax_ = (axes@N.diag(hyp)@axes.T).T ax_ = N.sqrt(ax_) l1 = N.linalg.norm(ax_[:-1]) l2 = N.linalg.norm(ax_[-1]) ang_error = 2*N.degrees(N.arctan2(l2,l1)) title += ": {:.0f} m long, angular error (95% CI): {:.2f}º".format(lengths[a], ang_error) bounds = minmax[0] x_ = N.linspace(bounds[0]*1.2,bounds[1]*1.2,100) err = HyperbolicErrors(hyp,x_,axes=axes) err.plot(ax, fc='#cccccc', alpha=0.3) x,y = A[:,a], A[:,b] kw = dict(alpha=0.5, zorder=5) if colormap is None: ax.plot(x,y,c="#555555", linestyle='None', marker='.',**kw) else: ax.scatter(x,y,c=A[:,-1], cmap=colormap, **kw) #ax.set_aspect("equal") ax.text(0.01,.99,title, verticalalignment='top', transform=ax.transAxes) #ax.autoscale(tight=True) ax.yaxis.set_ticks([]) ax.xaxis.set_ticks_position('bottom') if a != 1: pass #ax.xaxis.set_ticks([]) #ax.spines['bottom'].set_color('none') for spine in ax.spines.values(): spine.set_visible(False) ax.text(0.99,0.99,"Max residual: {:.1f} m".format(lengths[2]), verticalalignment='bottom', ha='right', transform=ax.transAxes) ax.set_xlabel("Meters") return fig
[ "def", "plot_aligned", "(", "pca", ",", "sparse", "=", "True", ",", "*", "*", "kwargs", ")", ":", "colormap", "=", "kwargs", ".", "pop", "(", "'colormap'", ",", "None", ")", "A", "=", "pca", ".", "rotated", "(", ")", "# Flip the result if upside down", "if", "pca", ".", "normal", "[", "2", "]", "<", "0", ":", "A", "[", ":", ",", "-", "1", "]", "*=", "-", "1", "minmax", "=", "[", "(", "A", "[", ":", ",", "i", "]", ".", "min", "(", ")", ",", "A", "[", ":", ",", "i", "]", ".", "max", "(", ")", ")", "for", "i", "in", "range", "(", "3", ")", "]", "lengths", "=", "[", "j", "-", "i", "for", "i", ",", "j", "in", "minmax", "]", "if", "sparse", ":", "i", "=", "1", "l", "=", "len", "(", "A", ")", "if", "l", ">", "10000", ":", "i", "=", "N", ".", "ceil", "(", "l", "/", "10000", ")", "A", "=", "A", "[", ":", ":", "int", "(", "i", ")", "]", "log", ".", "info", "(", "\"Plotting with {} points\"", ".", "format", "(", "len", "(", "A", ")", ")", ")", "w", "=", "8", "ratio", "=", "(", "lengths", "[", "2", "]", "*", "2", "+", "lengths", "[", "1", "]", ")", "/", "lengths", "[", "0", "]", "*", "1.5", "h", "=", "w", "*", "ratio", "if", "h", "<", "3", ":", "h", "=", "3", "r", "=", "(", "lengths", "[", "1", "]", "+", "5", ")", "/", "(", "lengths", "[", "2", "]", "+", "5", ")", "if", "r", ">", "5", ":", "r", "=", "5", "fig", "=", "Figure", "(", "figsize", "=", "(", "w", ",", "h", ")", ")", "fig", ".", "canvas", "=", "FigureCanvas", "(", "fig", ")", "def", "setup_axes", "(", ")", ":", "gs", "=", "GridSpec", "(", "3", ",", "1", ",", "height_ratios", "=", "[", "r", ",", "1", ",", "1", "]", ")", "kwargs", "=", "dict", "(", ")", "axes", "=", "[", "]", "for", "g", "in", "gs", ":", "ax", "=", "fig", ".", "add_subplot", "(", "g", ",", "*", "*", "kwargs", ")", "kwargs", "[", "'sharex'", "]", "=", "ax", "yield", "ax", "axes", "=", "list", "(", "setup_axes", "(", ")", ")", "fig", ".", "subplots_adjust", "(", "hspace", "=", "0", ",", "wspace", "=", "0.1", ")", "#lengths = attitude.pca.singular_values[::-1]", "titles", "=", "(", "\"Plan view\"", ",", "\"Long cross-section\"", ",", "\"Short cross-section\"", ")", "ylabels", "=", "(", "\"Meters\"", ",", "\"Residuals (m)\"", ",", "\"Residuals (m)\"", ")", "colors", "=", "[", "'cornflowerblue'", ",", "'red'", "]", "hyp", "=", "sampling_axes", "(", "pca", ")", "vertical", "=", "vector", "(", "0", ",", "0", ",", "1", ")", "for", "title", ",", "ax", ",", "(", "a", ",", "b", ")", ",", "ylabel", "in", "zip", "(", "titles", ",", "axes", ",", "[", "(", "0", ",", "1", ")", ",", "(", "0", ",", "2", ")", ",", "(", "1", ",", "2", ")", "]", ",", "ylabels", ")", ":", "kw", "=", "dict", "(", "linewidth", "=", "2", ",", "alpha", "=", "0.5", ")", "bounds", "=", "minmax", "[", "a", "]", "if", "b", "!=", "2", ":", "ax", ".", "plot", "(", "bounds", ",", "(", "0", ",", "0", ")", ",", "c", "=", "colors", "[", "a", "]", ",", "*", "*", "kw", ")", "ax", ".", "plot", "(", "(", "0", ",", "0", ")", ",", "minmax", "[", "b", "]", ",", "c", "=", "colors", "[", "b", "]", ",", "*", "*", "kw", ")", "else", ":", "ax", ".", "plot", "(", "bounds", ",", "(", "-", "10", ",", "-", "10", ")", ",", "c", "=", "colors", "[", "a", "]", ",", "*", "*", "kw", ")", "v0", "=", "N", ".", "zeros", "(", "3", ")", "v0", "[", "a", "]", "=", "1", "axes", "=", "N", ".", "array", "(", "[", "v0", ",", "vertical", "]", ")", "ax_", "=", "(", "axes", "@", "N", ".", "diag", "(", "hyp", ")", "@", "axes", ".", "T", ")", ".", "T", "ax_", "=", "N", ".", "sqrt", "(", "ax_", ")", "l1", "=", "N", ".", "linalg", ".", "norm", "(", "ax_", "[", ":", "-", "1", "]", ")", "l2", "=", "N", ".", "linalg", ".", "norm", "(", "ax_", "[", "-", "1", "]", ")", "ang_error", "=", "2", "*", "N", ".", "degrees", "(", "N", ".", "arctan2", "(", "l2", ",", "l1", ")", ")", "title", "+=", "\": {:.0f} m long, angular error (95% CI): {:.2f}º\".", "f", "ormat(", "l", "engths[", "a", "]", ",", " ", "ng_error)", "", "bounds", "=", "minmax", "[", "0", "]", "x_", "=", "N", ".", "linspace", "(", "bounds", "[", "0", "]", "*", "1.2", ",", "bounds", "[", "1", "]", "*", "1.2", ",", "100", ")", "err", "=", "HyperbolicErrors", "(", "hyp", ",", "x_", ",", "axes", "=", "axes", ")", "err", ".", "plot", "(", "ax", ",", "fc", "=", "'#cccccc'", ",", "alpha", "=", "0.3", ")", "x", ",", "y", "=", "A", "[", ":", ",", "a", "]", ",", "A", "[", ":", ",", "b", "]", "kw", "=", "dict", "(", "alpha", "=", "0.5", ",", "zorder", "=", "5", ")", "if", "colormap", "is", "None", ":", "ax", ".", "plot", "(", "x", ",", "y", ",", "c", "=", "\"#555555\"", ",", "linestyle", "=", "'None'", ",", "marker", "=", "'.'", ",", "*", "*", "kw", ")", "else", ":", "ax", ".", "scatter", "(", "x", ",", "y", ",", "c", "=", "A", "[", ":", ",", "-", "1", "]", ",", "cmap", "=", "colormap", ",", "*", "*", "kw", ")", "#ax.set_aspect(\"equal\")", "ax", ".", "text", "(", "0.01", ",", ".99", ",", "title", ",", "verticalalignment", "=", "'top'", ",", "transform", "=", "ax", ".", "transAxes", ")", "#ax.autoscale(tight=True)", "ax", ".", "yaxis", ".", "set_ticks", "(", "[", "]", ")", "ax", ".", "xaxis", ".", "set_ticks_position", "(", "'bottom'", ")", "if", "a", "!=", "1", ":", "pass", "#ax.xaxis.set_ticks([])", "#ax.spines['bottom'].set_color('none')", "for", "spine", "in", "ax", ".", "spines", ".", "values", "(", ")", ":", "spine", ".", "set_visible", "(", "False", ")", "ax", ".", "text", "(", "0.99", ",", "0.99", ",", "\"Max residual: {:.1f} m\"", ".", "format", "(", "lengths", "[", "2", "]", ")", ",", "verticalalignment", "=", "'bottom'", ",", "ha", "=", "'right'", ",", "transform", "=", "ax", ".", "transAxes", ")", "ax", ".", "set_xlabel", "(", "\"Meters\"", ")", "return", "fig" ]
Plots the residuals of a principal component analysis of attiude data.
[ "Plots", "the", "residuals", "of", "a", "principal", "component", "analysis", "of", "attiude", "data", "." ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/display/pca_aligned.py#L18-L141
meyersj/geotweet
geotweet/mapreduce/poi_nearby_tweets.py
POINearbyTweetsMRJob.mapper_metro
def mapper_metro(self, _, data): """ map each osm POI and geotweets based on spatial lookup of metro area """ # OSM POI record if 'tags' in data: type_tag = 1 lonlat = data['coordinates'] payload = data['tags'] # Tweet with coordinates from Streaming API elif 'user_id' in data: type_tag = 2 # only allow tweets from the listed domains to try and filter out # noise such as HR tweets, Weather reports and news updates accept = [ "twitter\.com", "foursquare\.com", "instagram\.com", "untappd\.com" ] expr = "|".join(accept) if not re.findall(expr, data['source']): return lonlat = data['lonlat'] payload = None # spatial lookup using Rtree with cached results metro = self.lookup.get(lonlat, METRO_DISTANCE) if not metro: return yield metro, (type_tag, lonlat, payload)
python
def mapper_metro(self, _, data): """ map each osm POI and geotweets based on spatial lookup of metro area """ # OSM POI record if 'tags' in data: type_tag = 1 lonlat = data['coordinates'] payload = data['tags'] # Tweet with coordinates from Streaming API elif 'user_id' in data: type_tag = 2 # only allow tweets from the listed domains to try and filter out # noise such as HR tweets, Weather reports and news updates accept = [ "twitter\.com", "foursquare\.com", "instagram\.com", "untappd\.com" ] expr = "|".join(accept) if not re.findall(expr, data['source']): return lonlat = data['lonlat'] payload = None # spatial lookup using Rtree with cached results metro = self.lookup.get(lonlat, METRO_DISTANCE) if not metro: return yield metro, (type_tag, lonlat, payload)
[ "def", "mapper_metro", "(", "self", ",", "_", ",", "data", ")", ":", "# OSM POI record", "if", "'tags'", "in", "data", ":", "type_tag", "=", "1", "lonlat", "=", "data", "[", "'coordinates'", "]", "payload", "=", "data", "[", "'tags'", "]", "# Tweet with coordinates from Streaming API", "elif", "'user_id'", "in", "data", ":", "type_tag", "=", "2", "# only allow tweets from the listed domains to try and filter out", "# noise such as HR tweets, Weather reports and news updates", "accept", "=", "[", "\"twitter\\.com\"", ",", "\"foursquare\\.com\"", ",", "\"instagram\\.com\"", ",", "\"untappd\\.com\"", "]", "expr", "=", "\"|\"", ".", "join", "(", "accept", ")", "if", "not", "re", ".", "findall", "(", "expr", ",", "data", "[", "'source'", "]", ")", ":", "return", "lonlat", "=", "data", "[", "'lonlat'", "]", "payload", "=", "None", "# spatial lookup using Rtree with cached results", "metro", "=", "self", ".", "lookup", ".", "get", "(", "lonlat", ",", "METRO_DISTANCE", ")", "if", "not", "metro", ":", "return", "yield", "metro", ",", "(", "type_tag", ",", "lonlat", ",", "payload", ")" ]
map each osm POI and geotweets based on spatial lookup of metro area
[ "map", "each", "osm", "POI", "and", "geotweets", "based", "on", "spatial", "lookup", "of", "metro", "area" ]
train
https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/poi_nearby_tweets.py#L81-L108
meyersj/geotweet
geotweet/mapreduce/poi_nearby_tweets.py
POINearbyTweetsMRJob.reducer_metro
def reducer_metro(self, metro, values): """ Output tags of POI locations nearby tweet locations Values will be sorted coming into reducer. First element in each value tuple will be either 1 (osm POI) or 2 (geotweet). Build a spatial index with POI records. For each tweet lookup nearby POI, and emit tag values for predefined tags. """ lookup = CachedLookup(precision=POI_GEOHASH_PRECISION) for i, value in enumerate(values): type_tag, lonlat, data = value if type_tag == 1: # OSM POI node, construct geojson and add to Rtree index lookup.insert(i, dict( geometry=dict(type='Point', coordinates=project(lonlat)), properties=dict(tags=data) )) else: # geotweet, lookup nearest POI from index if not lookup.data_store: return poi_names = [] kwargs = dict(buffer_size=POI_DISTANCE, multiple=True) # lookup nearby POI from Rtree index (caching results) # for any tags we care about emit the tags value and 1 for poi in lookup.get(lonlat, **kwargs): has_tag = [ tag in poi['tags'] for tag in POI_TAGS ] if any(has_tag) and 'name' in poi['tags']: poi_names.append(poi['tags']['name']) for poi in set(poi_names): yield (metro, poi), 1
python
def reducer_metro(self, metro, values): """ Output tags of POI locations nearby tweet locations Values will be sorted coming into reducer. First element in each value tuple will be either 1 (osm POI) or 2 (geotweet). Build a spatial index with POI records. For each tweet lookup nearby POI, and emit tag values for predefined tags. """ lookup = CachedLookup(precision=POI_GEOHASH_PRECISION) for i, value in enumerate(values): type_tag, lonlat, data = value if type_tag == 1: # OSM POI node, construct geojson and add to Rtree index lookup.insert(i, dict( geometry=dict(type='Point', coordinates=project(lonlat)), properties=dict(tags=data) )) else: # geotweet, lookup nearest POI from index if not lookup.data_store: return poi_names = [] kwargs = dict(buffer_size=POI_DISTANCE, multiple=True) # lookup nearby POI from Rtree index (caching results) # for any tags we care about emit the tags value and 1 for poi in lookup.get(lonlat, **kwargs): has_tag = [ tag in poi['tags'] for tag in POI_TAGS ] if any(has_tag) and 'name' in poi['tags']: poi_names.append(poi['tags']['name']) for poi in set(poi_names): yield (metro, poi), 1
[ "def", "reducer_metro", "(", "self", ",", "metro", ",", "values", ")", ":", "lookup", "=", "CachedLookup", "(", "precision", "=", "POI_GEOHASH_PRECISION", ")", "for", "i", ",", "value", "in", "enumerate", "(", "values", ")", ":", "type_tag", ",", "lonlat", ",", "data", "=", "value", "if", "type_tag", "==", "1", ":", "# OSM POI node, construct geojson and add to Rtree index", "lookup", ".", "insert", "(", "i", ",", "dict", "(", "geometry", "=", "dict", "(", "type", "=", "'Point'", ",", "coordinates", "=", "project", "(", "lonlat", ")", ")", ",", "properties", "=", "dict", "(", "tags", "=", "data", ")", ")", ")", "else", ":", "# geotweet, lookup nearest POI from index", "if", "not", "lookup", ".", "data_store", ":", "return", "poi_names", "=", "[", "]", "kwargs", "=", "dict", "(", "buffer_size", "=", "POI_DISTANCE", ",", "multiple", "=", "True", ")", "# lookup nearby POI from Rtree index (caching results)", "# for any tags we care about emit the tags value and 1", "for", "poi", "in", "lookup", ".", "get", "(", "lonlat", ",", "*", "*", "kwargs", ")", ":", "has_tag", "=", "[", "tag", "in", "poi", "[", "'tags'", "]", "for", "tag", "in", "POI_TAGS", "]", "if", "any", "(", "has_tag", ")", "and", "'name'", "in", "poi", "[", "'tags'", "]", ":", "poi_names", ".", "append", "(", "poi", "[", "'tags'", "]", "[", "'name'", "]", ")", "for", "poi", "in", "set", "(", "poi_names", ")", ":", "yield", "(", "metro", ",", "poi", ")", ",", "1" ]
Output tags of POI locations nearby tweet locations Values will be sorted coming into reducer. First element in each value tuple will be either 1 (osm POI) or 2 (geotweet). Build a spatial index with POI records. For each tweet lookup nearby POI, and emit tag values for predefined tags.
[ "Output", "tags", "of", "POI", "locations", "nearby", "tweet", "locations" ]
train
https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/poi_nearby_tweets.py#L110-L142
meyersj/geotweet
geotweet/mapreduce/poi_nearby_tweets.py
POINearbyTweetsMRJob.reducer_count
def reducer_count(self, key, values): """ count occurences for each (metro, POI) record """ total = sum(values) metro, poi = key # group data by metro areas for final output yield metro, (total, poi)
python
def reducer_count(self, key, values): """ count occurences for each (metro, POI) record """ total = sum(values) metro, poi = key # group data by metro areas for final output yield metro, (total, poi)
[ "def", "reducer_count", "(", "self", ",", "key", ",", "values", ")", ":", "total", "=", "sum", "(", "values", ")", "metro", ",", "poi", "=", "key", "# group data by metro areas for final output ", "yield", "metro", ",", "(", "total", ",", "poi", ")" ]
count occurences for each (metro, POI) record
[ "count", "occurences", "for", "each", "(", "metro", "POI", ")", "record" ]
train
https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/poi_nearby_tweets.py#L144-L149
meyersj/geotweet
geotweet/mapreduce/poi_nearby_tweets.py
POINearbyTweetsMRJob.reducer_output
def reducer_output(self, metro, values): """ store each record in MongoDB and output tab delimited lines """ records = [] # build up list of data for each metro area and submit as one network # call instead of individually for value in values: total, poi = value records.append(dict( metro_area=metro, poi=poi, count=total )) output = "{0}\t{1}\t{2}" output = output.format(metro.encode('utf-8'), total, poi.encode('utf-8')) yield None, output if self.mongo: self.mongo.insert_many(records)
python
def reducer_output(self, metro, values): """ store each record in MongoDB and output tab delimited lines """ records = [] # build up list of data for each metro area and submit as one network # call instead of individually for value in values: total, poi = value records.append(dict( metro_area=metro, poi=poi, count=total )) output = "{0}\t{1}\t{2}" output = output.format(metro.encode('utf-8'), total, poi.encode('utf-8')) yield None, output if self.mongo: self.mongo.insert_many(records)
[ "def", "reducer_output", "(", "self", ",", "metro", ",", "values", ")", ":", "records", "=", "[", "]", "# build up list of data for each metro area and submit as one network", "# call instead of individually ", "for", "value", "in", "values", ":", "total", ",", "poi", "=", "value", "records", ".", "append", "(", "dict", "(", "metro_area", "=", "metro", ",", "poi", "=", "poi", ",", "count", "=", "total", ")", ")", "output", "=", "\"{0}\\t{1}\\t{2}\"", "output", "=", "output", ".", "format", "(", "metro", ".", "encode", "(", "'utf-8'", ")", ",", "total", ",", "poi", ".", "encode", "(", "'utf-8'", ")", ")", "yield", "None", ",", "output", "if", "self", ".", "mongo", ":", "self", ".", "mongo", ".", "insert_many", "(", "records", ")" ]
store each record in MongoDB and output tab delimited lines
[ "store", "each", "record", "in", "MongoDB", "and", "output", "tab", "delimited", "lines" ]
train
https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/poi_nearby_tweets.py#L159-L175
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/sqlfunc.py
fail_unknown_dialect
def fail_unknown_dialect(compiler: "SQLCompiler", task: str) -> None: """ Raise :exc:`NotImplementedError` in relation to a dialect for which a function hasn't been implemented (with a helpful error message). """ raise NotImplementedError( "Don't know how to {task} on dialect {dialect!r}. " "(Check also: if you printed the SQL before it was bound to an " "engine, you will be trying to use a dialect like StrSQLCompiler, " "which could be a reason for failure.)".format( task=task, dialect=compiler.dialect ) )
python
def fail_unknown_dialect(compiler: "SQLCompiler", task: str) -> None: """ Raise :exc:`NotImplementedError` in relation to a dialect for which a function hasn't been implemented (with a helpful error message). """ raise NotImplementedError( "Don't know how to {task} on dialect {dialect!r}. " "(Check also: if you printed the SQL before it was bound to an " "engine, you will be trying to use a dialect like StrSQLCompiler, " "which could be a reason for failure.)".format( task=task, dialect=compiler.dialect ) )
[ "def", "fail_unknown_dialect", "(", "compiler", ":", "\"SQLCompiler\"", ",", "task", ":", "str", ")", "->", "None", ":", "raise", "NotImplementedError", "(", "\"Don't know how to {task} on dialect {dialect!r}. \"", "\"(Check also: if you printed the SQL before it was bound to an \"", "\"engine, you will be trying to use a dialect like StrSQLCompiler, \"", "\"which could be a reason for failure.)\"", ".", "format", "(", "task", "=", "task", ",", "dialect", "=", "compiler", ".", "dialect", ")", ")" ]
Raise :exc:`NotImplementedError` in relation to a dialect for which a function hasn't been implemented (with a helpful error message).
[ "Raise", ":", "exc", ":", "NotImplementedError", "in", "relation", "to", "a", "dialect", "for", "which", "a", "function", "hasn", "t", "been", "implemented", "(", "with", "a", "helpful", "error", "message", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/sqlfunc.py#L50-L63
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/sqlfunc.py
fetch_processed_single_clause
def fetch_processed_single_clause(element: "ClauseElement", compiler: "SQLCompiler") -> str: """ Takes a clause element that must have a single clause, and converts it to raw SQL text. """ if len(element.clauses) != 1: raise TypeError("Only one argument supported; {} were passed".format( len(element.clauses))) clauselist = element.clauses # type: ClauseList first = clauselist.get_children()[0] return compiler.process(first)
python
def fetch_processed_single_clause(element: "ClauseElement", compiler: "SQLCompiler") -> str: """ Takes a clause element that must have a single clause, and converts it to raw SQL text. """ if len(element.clauses) != 1: raise TypeError("Only one argument supported; {} were passed".format( len(element.clauses))) clauselist = element.clauses # type: ClauseList first = clauselist.get_children()[0] return compiler.process(first)
[ "def", "fetch_processed_single_clause", "(", "element", ":", "\"ClauseElement\"", ",", "compiler", ":", "\"SQLCompiler\"", ")", "->", "str", ":", "if", "len", "(", "element", ".", "clauses", ")", "!=", "1", ":", "raise", "TypeError", "(", "\"Only one argument supported; {} were passed\"", ".", "format", "(", "len", "(", "element", ".", "clauses", ")", ")", ")", "clauselist", "=", "element", ".", "clauses", "# type: ClauseList", "first", "=", "clauselist", ".", "get_children", "(", ")", "[", "0", "]", "return", "compiler", ".", "process", "(", "first", ")" ]
Takes a clause element that must have a single clause, and converts it to raw SQL text.
[ "Takes", "a", "clause", "element", "that", "must", "have", "a", "single", "clause", "and", "converts", "it", "to", "raw", "SQL", "text", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/sqlfunc.py#L66-L77
RudolfCardinal/pythonlib
cardinal_pythonlib/django/forms.py
clean_int
def clean_int(x) -> int: """ Returns its parameter as an integer, or raises ``django.forms.ValidationError``. """ try: return int(x) except ValueError: raise forms.ValidationError( "Cannot convert to integer: {}".format(repr(x)))
python
def clean_int(x) -> int: """ Returns its parameter as an integer, or raises ``django.forms.ValidationError``. """ try: return int(x) except ValueError: raise forms.ValidationError( "Cannot convert to integer: {}".format(repr(x)))
[ "def", "clean_int", "(", "x", ")", "->", "int", ":", "try", ":", "return", "int", "(", "x", ")", "except", "ValueError", ":", "raise", "forms", ".", "ValidationError", "(", "\"Cannot convert to integer: {}\"", ".", "format", "(", "repr", "(", "x", ")", ")", ")" ]
Returns its parameter as an integer, or raises ``django.forms.ValidationError``.
[ "Returns", "its", "parameter", "as", "an", "integer", "or", "raises", "django", ".", "forms", ".", "ValidationError", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/forms.py#L40-L49
RudolfCardinal/pythonlib
cardinal_pythonlib/django/forms.py
clean_nhs_number
def clean_nhs_number(x) -> int: """ Returns its parameter as a valid integer NHS number, or raises ``django.forms.ValidationError``. """ try: x = int(x) if not is_valid_nhs_number(x): raise ValueError return x except ValueError: raise forms.ValidationError( "Not a valid NHS number: {}".format(repr(x)))
python
def clean_nhs_number(x) -> int: """ Returns its parameter as a valid integer NHS number, or raises ``django.forms.ValidationError``. """ try: x = int(x) if not is_valid_nhs_number(x): raise ValueError return x except ValueError: raise forms.ValidationError( "Not a valid NHS number: {}".format(repr(x)))
[ "def", "clean_nhs_number", "(", "x", ")", "->", "int", ":", "try", ":", "x", "=", "int", "(", "x", ")", "if", "not", "is_valid_nhs_number", "(", "x", ")", ":", "raise", "ValueError", "return", "x", "except", "ValueError", ":", "raise", "forms", ".", "ValidationError", "(", "\"Not a valid NHS number: {}\"", ".", "format", "(", "repr", "(", "x", ")", ")", ")" ]
Returns its parameter as a valid integer NHS number, or raises ``django.forms.ValidationError``.
[ "Returns", "its", "parameter", "as", "a", "valid", "integer", "NHS", "number", "or", "raises", "django", ".", "forms", ".", "ValidationError", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/forms.py#L52-L64
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/orm_inspect.py
coltype_as_typeengine
def coltype_as_typeengine(coltype: Union[VisitableType, TypeEngine]) -> TypeEngine: """ Instances of SQLAlchemy column types are subclasses of ``TypeEngine``. It's possible to specify column types either as such instances, or as the class type. This function ensures that such classes are converted to instances. To explain: you can specify columns like .. code-block:: python a = Column("a", Integer) b = Column("b", Integer()) c = Column("c", String(length=50)) isinstance(Integer, TypeEngine) # False isinstance(Integer(), TypeEngine) # True isinstance(String(length=50), TypeEngine) # True type(Integer) # <class 'sqlalchemy.sql.visitors.VisitableType'> type(Integer()) # <class 'sqlalchemy.sql.sqltypes.Integer'> type(String) # <class 'sqlalchemy.sql.visitors.VisitableType'> type(String(length=50)) # <class 'sqlalchemy.sql.sqltypes.String'> This function coerces things to a :class:`TypeEngine`. """ if isinstance(coltype, TypeEngine): return coltype return coltype()
python
def coltype_as_typeengine(coltype: Union[VisitableType, TypeEngine]) -> TypeEngine: """ Instances of SQLAlchemy column types are subclasses of ``TypeEngine``. It's possible to specify column types either as such instances, or as the class type. This function ensures that such classes are converted to instances. To explain: you can specify columns like .. code-block:: python a = Column("a", Integer) b = Column("b", Integer()) c = Column("c", String(length=50)) isinstance(Integer, TypeEngine) # False isinstance(Integer(), TypeEngine) # True isinstance(String(length=50), TypeEngine) # True type(Integer) # <class 'sqlalchemy.sql.visitors.VisitableType'> type(Integer()) # <class 'sqlalchemy.sql.sqltypes.Integer'> type(String) # <class 'sqlalchemy.sql.visitors.VisitableType'> type(String(length=50)) # <class 'sqlalchemy.sql.sqltypes.String'> This function coerces things to a :class:`TypeEngine`. """ if isinstance(coltype, TypeEngine): return coltype return coltype()
[ "def", "coltype_as_typeengine", "(", "coltype", ":", "Union", "[", "VisitableType", ",", "TypeEngine", "]", ")", "->", "TypeEngine", ":", "if", "isinstance", "(", "coltype", ",", "TypeEngine", ")", ":", "return", "coltype", "return", "coltype", "(", ")" ]
Instances of SQLAlchemy column types are subclasses of ``TypeEngine``. It's possible to specify column types either as such instances, or as the class type. This function ensures that such classes are converted to instances. To explain: you can specify columns like .. code-block:: python a = Column("a", Integer) b = Column("b", Integer()) c = Column("c", String(length=50)) isinstance(Integer, TypeEngine) # False isinstance(Integer(), TypeEngine) # True isinstance(String(length=50), TypeEngine) # True type(Integer) # <class 'sqlalchemy.sql.visitors.VisitableType'> type(Integer()) # <class 'sqlalchemy.sql.sqltypes.Integer'> type(String) # <class 'sqlalchemy.sql.visitors.VisitableType'> type(String(length=50)) # <class 'sqlalchemy.sql.sqltypes.String'> This function coerces things to a :class:`TypeEngine`.
[ "Instances", "of", "SQLAlchemy", "column", "types", "are", "subclasses", "of", "TypeEngine", ".", "It", "s", "possible", "to", "specify", "column", "types", "either", "as", "such", "instances", "or", "as", "the", "class", "type", ".", "This", "function", "ensures", "that", "such", "classes", "are", "converted", "to", "instances", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L60-L89
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/orm_inspect.py
walk_orm_tree
def walk_orm_tree(obj, debug: bool = False, seen: Set = None, skip_relationships_always: List[str] = None, skip_relationships_by_tablename: Dict[str, List[str]] = None, skip_all_relationships_for_tablenames: List[str] = None, skip_all_objects_for_tablenames: List[str] = None) \ -> Generator[object, None, None]: """ Starting with a SQLAlchemy ORM object, this function walks a relationship tree, yielding each of the objects once. To skip attributes by name, put the attribute name(s) in ``skip_attrs_always``. To skip by table name, pass ``skip_attrs_by_tablename`` as e.g. .. code-block:: python {'sometable': ['attr1_to_skip', 'attr2_to_skip']} Args: obj: the SQLAlchemy ORM object to walk debug: be verbose seen: usually ``None``, but can be a set of objects marked as "already seen"; if an object is in this set, it is skipped skip_relationships_always: relationships are skipped if the relationship has a name in this (optional) list skip_relationships_by_tablename: optional dictionary mapping table names (keys) to relationship attribute names (values); if the "related table"/"relationship attribute" pair are in this dictionary, the relationship is skipped skip_all_relationships_for_tablenames: relationships are skipped if the the related table has a name in this (optional) list skip_all_objects_for_tablenames: if the object belongs to a table whose name is in this (optional) list, the object is skipped Yields: SQLAlchemy ORM objects (including the starting object) """ # http://docs.sqlalchemy.org/en/latest/faq/sessions.html#faq-walk-objects skip_relationships_always = skip_relationships_always or [] # type: List[str] # noqa skip_relationships_by_tablename = skip_relationships_by_tablename or {} # type: Dict[str, List[str]] # noqa skip_all_relationships_for_tablenames = skip_all_relationships_for_tablenames or [] # type: List[str] # noqa skip_all_objects_for_tablenames = skip_all_objects_for_tablenames or [] # type: List[str] # noqa stack = [obj] if seen is None: seen = set() while stack: obj = stack.pop(0) if obj in seen: continue tablename = obj.__tablename__ if tablename in skip_all_objects_for_tablenames: continue seen.add(obj) if debug: log.debug("walk: yielding {!r}", obj) yield obj insp = inspect(obj) # type: InstanceState for relationship in insp.mapper.relationships: # type: RelationshipProperty # noqa attrname = relationship.key # Skip? if attrname in skip_relationships_always: continue if tablename in skip_all_relationships_for_tablenames: continue if (tablename in skip_relationships_by_tablename and attrname in skip_relationships_by_tablename[tablename]): continue # Process relationship if debug: log.debug("walk: following relationship {}", relationship) related = getattr(obj, attrname) if debug and related: log.debug("walk: queueing {!r}", related) if relationship.uselist: stack.extend(related) elif related is not None: stack.append(related)
python
def walk_orm_tree(obj, debug: bool = False, seen: Set = None, skip_relationships_always: List[str] = None, skip_relationships_by_tablename: Dict[str, List[str]] = None, skip_all_relationships_for_tablenames: List[str] = None, skip_all_objects_for_tablenames: List[str] = None) \ -> Generator[object, None, None]: """ Starting with a SQLAlchemy ORM object, this function walks a relationship tree, yielding each of the objects once. To skip attributes by name, put the attribute name(s) in ``skip_attrs_always``. To skip by table name, pass ``skip_attrs_by_tablename`` as e.g. .. code-block:: python {'sometable': ['attr1_to_skip', 'attr2_to_skip']} Args: obj: the SQLAlchemy ORM object to walk debug: be verbose seen: usually ``None``, but can be a set of objects marked as "already seen"; if an object is in this set, it is skipped skip_relationships_always: relationships are skipped if the relationship has a name in this (optional) list skip_relationships_by_tablename: optional dictionary mapping table names (keys) to relationship attribute names (values); if the "related table"/"relationship attribute" pair are in this dictionary, the relationship is skipped skip_all_relationships_for_tablenames: relationships are skipped if the the related table has a name in this (optional) list skip_all_objects_for_tablenames: if the object belongs to a table whose name is in this (optional) list, the object is skipped Yields: SQLAlchemy ORM objects (including the starting object) """ # http://docs.sqlalchemy.org/en/latest/faq/sessions.html#faq-walk-objects skip_relationships_always = skip_relationships_always or [] # type: List[str] # noqa skip_relationships_by_tablename = skip_relationships_by_tablename or {} # type: Dict[str, List[str]] # noqa skip_all_relationships_for_tablenames = skip_all_relationships_for_tablenames or [] # type: List[str] # noqa skip_all_objects_for_tablenames = skip_all_objects_for_tablenames or [] # type: List[str] # noqa stack = [obj] if seen is None: seen = set() while stack: obj = stack.pop(0) if obj in seen: continue tablename = obj.__tablename__ if tablename in skip_all_objects_for_tablenames: continue seen.add(obj) if debug: log.debug("walk: yielding {!r}", obj) yield obj insp = inspect(obj) # type: InstanceState for relationship in insp.mapper.relationships: # type: RelationshipProperty # noqa attrname = relationship.key # Skip? if attrname in skip_relationships_always: continue if tablename in skip_all_relationships_for_tablenames: continue if (tablename in skip_relationships_by_tablename and attrname in skip_relationships_by_tablename[tablename]): continue # Process relationship if debug: log.debug("walk: following relationship {}", relationship) related = getattr(obj, attrname) if debug and related: log.debug("walk: queueing {!r}", related) if relationship.uselist: stack.extend(related) elif related is not None: stack.append(related)
[ "def", "walk_orm_tree", "(", "obj", ",", "debug", ":", "bool", "=", "False", ",", "seen", ":", "Set", "=", "None", ",", "skip_relationships_always", ":", "List", "[", "str", "]", "=", "None", ",", "skip_relationships_by_tablename", ":", "Dict", "[", "str", ",", "List", "[", "str", "]", "]", "=", "None", ",", "skip_all_relationships_for_tablenames", ":", "List", "[", "str", "]", "=", "None", ",", "skip_all_objects_for_tablenames", ":", "List", "[", "str", "]", "=", "None", ")", "->", "Generator", "[", "object", ",", "None", ",", "None", "]", ":", "# http://docs.sqlalchemy.org/en/latest/faq/sessions.html#faq-walk-objects", "skip_relationships_always", "=", "skip_relationships_always", "or", "[", "]", "# type: List[str] # noqa", "skip_relationships_by_tablename", "=", "skip_relationships_by_tablename", "or", "{", "}", "# type: Dict[str, List[str]] # noqa", "skip_all_relationships_for_tablenames", "=", "skip_all_relationships_for_tablenames", "or", "[", "]", "# type: List[str] # noqa", "skip_all_objects_for_tablenames", "=", "skip_all_objects_for_tablenames", "or", "[", "]", "# type: List[str] # noqa", "stack", "=", "[", "obj", "]", "if", "seen", "is", "None", ":", "seen", "=", "set", "(", ")", "while", "stack", ":", "obj", "=", "stack", ".", "pop", "(", "0", ")", "if", "obj", "in", "seen", ":", "continue", "tablename", "=", "obj", ".", "__tablename__", "if", "tablename", "in", "skip_all_objects_for_tablenames", ":", "continue", "seen", ".", "add", "(", "obj", ")", "if", "debug", ":", "log", ".", "debug", "(", "\"walk: yielding {!r}\"", ",", "obj", ")", "yield", "obj", "insp", "=", "inspect", "(", "obj", ")", "# type: InstanceState", "for", "relationship", "in", "insp", ".", "mapper", ".", "relationships", ":", "# type: RelationshipProperty # noqa", "attrname", "=", "relationship", ".", "key", "# Skip?", "if", "attrname", "in", "skip_relationships_always", ":", "continue", "if", "tablename", "in", "skip_all_relationships_for_tablenames", ":", "continue", "if", "(", "tablename", "in", "skip_relationships_by_tablename", "and", "attrname", "in", "skip_relationships_by_tablename", "[", "tablename", "]", ")", ":", "continue", "# Process relationship", "if", "debug", ":", "log", ".", "debug", "(", "\"walk: following relationship {}\"", ",", "relationship", ")", "related", "=", "getattr", "(", "obj", ",", "attrname", ")", "if", "debug", "and", "related", ":", "log", ".", "debug", "(", "\"walk: queueing {!r}\"", ",", "related", ")", "if", "relationship", ".", "uselist", ":", "stack", ".", "extend", "(", "related", ")", "elif", "related", "is", "not", "None", ":", "stack", ".", "append", "(", "related", ")" ]
Starting with a SQLAlchemy ORM object, this function walks a relationship tree, yielding each of the objects once. To skip attributes by name, put the attribute name(s) in ``skip_attrs_always``. To skip by table name, pass ``skip_attrs_by_tablename`` as e.g. .. code-block:: python {'sometable': ['attr1_to_skip', 'attr2_to_skip']} Args: obj: the SQLAlchemy ORM object to walk debug: be verbose seen: usually ``None``, but can be a set of objects marked as "already seen"; if an object is in this set, it is skipped skip_relationships_always: relationships are skipped if the relationship has a name in this (optional) list skip_relationships_by_tablename: optional dictionary mapping table names (keys) to relationship attribute names (values); if the "related table"/"relationship attribute" pair are in this dictionary, the relationship is skipped skip_all_relationships_for_tablenames: relationships are skipped if the the related table has a name in this (optional) list skip_all_objects_for_tablenames: if the object belongs to a table whose name is in this (optional) list, the object is skipped Yields: SQLAlchemy ORM objects (including the starting object)
[ "Starting", "with", "a", "SQLAlchemy", "ORM", "object", "this", "function", "walks", "a", "relationship", "tree", "yielding", "each", "of", "the", "objects", "once", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L140-L226
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/orm_inspect.py
copy_sqla_object
def copy_sqla_object(obj: object, omit_fk: bool = True, omit_pk: bool = True, omit_attrs: List[str] = None, debug: bool = False) -> object: """ Given an SQLAlchemy object, creates a new object (FOR WHICH THE OBJECT MUST SUPPORT CREATION USING ``__init__()`` WITH NO PARAMETERS), and copies across all attributes, omitting PKs (by default), FKs (by default), and relationship attributes (always omitted). Args: obj: the object to copy omit_fk: omit foreign keys (FKs)? omit_pk: omit primary keys (PKs)? omit_attrs: attributes (by name) not to copy debug: be verbose Returns: a new copy of the object """ omit_attrs = omit_attrs or [] # type: List[str] cls = type(obj) mapper = class_mapper(cls) newobj = cls() # not: cls.__new__(cls) rel_keys = set([c.key for c in mapper.relationships]) prohibited = rel_keys if omit_pk: pk_keys = set([c.key for c in mapper.primary_key]) prohibited |= pk_keys if omit_fk: fk_keys = set([c.key for c in mapper.columns if c.foreign_keys]) prohibited |= fk_keys prohibited |= set(omit_attrs) if debug: log.debug("copy_sqla_object: skipping: {}", prohibited) for k in [p.key for p in mapper.iterate_properties if p.key not in prohibited]: try: value = getattr(obj, k) if debug: log.debug("copy_sqla_object: processing attribute {} = {}", k, value) setattr(newobj, k, value) except AttributeError: if debug: log.debug("copy_sqla_object: failed attribute {}", k) pass return newobj
python
def copy_sqla_object(obj: object, omit_fk: bool = True, omit_pk: bool = True, omit_attrs: List[str] = None, debug: bool = False) -> object: """ Given an SQLAlchemy object, creates a new object (FOR WHICH THE OBJECT MUST SUPPORT CREATION USING ``__init__()`` WITH NO PARAMETERS), and copies across all attributes, omitting PKs (by default), FKs (by default), and relationship attributes (always omitted). Args: obj: the object to copy omit_fk: omit foreign keys (FKs)? omit_pk: omit primary keys (PKs)? omit_attrs: attributes (by name) not to copy debug: be verbose Returns: a new copy of the object """ omit_attrs = omit_attrs or [] # type: List[str] cls = type(obj) mapper = class_mapper(cls) newobj = cls() # not: cls.__new__(cls) rel_keys = set([c.key for c in mapper.relationships]) prohibited = rel_keys if omit_pk: pk_keys = set([c.key for c in mapper.primary_key]) prohibited |= pk_keys if omit_fk: fk_keys = set([c.key for c in mapper.columns if c.foreign_keys]) prohibited |= fk_keys prohibited |= set(omit_attrs) if debug: log.debug("copy_sqla_object: skipping: {}", prohibited) for k in [p.key for p in mapper.iterate_properties if p.key not in prohibited]: try: value = getattr(obj, k) if debug: log.debug("copy_sqla_object: processing attribute {} = {}", k, value) setattr(newobj, k, value) except AttributeError: if debug: log.debug("copy_sqla_object: failed attribute {}", k) pass return newobj
[ "def", "copy_sqla_object", "(", "obj", ":", "object", ",", "omit_fk", ":", "bool", "=", "True", ",", "omit_pk", ":", "bool", "=", "True", ",", "omit_attrs", ":", "List", "[", "str", "]", "=", "None", ",", "debug", ":", "bool", "=", "False", ")", "->", "object", ":", "omit_attrs", "=", "omit_attrs", "or", "[", "]", "# type: List[str]", "cls", "=", "type", "(", "obj", ")", "mapper", "=", "class_mapper", "(", "cls", ")", "newobj", "=", "cls", "(", ")", "# not: cls.__new__(cls)", "rel_keys", "=", "set", "(", "[", "c", ".", "key", "for", "c", "in", "mapper", ".", "relationships", "]", ")", "prohibited", "=", "rel_keys", "if", "omit_pk", ":", "pk_keys", "=", "set", "(", "[", "c", ".", "key", "for", "c", "in", "mapper", ".", "primary_key", "]", ")", "prohibited", "|=", "pk_keys", "if", "omit_fk", ":", "fk_keys", "=", "set", "(", "[", "c", ".", "key", "for", "c", "in", "mapper", ".", "columns", "if", "c", ".", "foreign_keys", "]", ")", "prohibited", "|=", "fk_keys", "prohibited", "|=", "set", "(", "omit_attrs", ")", "if", "debug", ":", "log", ".", "debug", "(", "\"copy_sqla_object: skipping: {}\"", ",", "prohibited", ")", "for", "k", "in", "[", "p", ".", "key", "for", "p", "in", "mapper", ".", "iterate_properties", "if", "p", ".", "key", "not", "in", "prohibited", "]", ":", "try", ":", "value", "=", "getattr", "(", "obj", ",", "k", ")", "if", "debug", ":", "log", ".", "debug", "(", "\"copy_sqla_object: processing attribute {} = {}\"", ",", "k", ",", "value", ")", "setattr", "(", "newobj", ",", "k", ",", "value", ")", "except", "AttributeError", ":", "if", "debug", ":", "log", ".", "debug", "(", "\"copy_sqla_object: failed attribute {}\"", ",", "k", ")", "pass", "return", "newobj" ]
Given an SQLAlchemy object, creates a new object (FOR WHICH THE OBJECT MUST SUPPORT CREATION USING ``__init__()`` WITH NO PARAMETERS), and copies across all attributes, omitting PKs (by default), FKs (by default), and relationship attributes (always omitted). Args: obj: the object to copy omit_fk: omit foreign keys (FKs)? omit_pk: omit primary keys (PKs)? omit_attrs: attributes (by name) not to copy debug: be verbose Returns: a new copy of the object
[ "Given", "an", "SQLAlchemy", "object", "creates", "a", "new", "object", "(", "FOR", "WHICH", "THE", "OBJECT", "MUST", "SUPPORT", "CREATION", "USING", "__init__", "()", "WITH", "NO", "PARAMETERS", ")", "and", "copies", "across", "all", "attributes", "omitting", "PKs", "(", "by", "default", ")", "FKs", "(", "by", "default", ")", "and", "relationship", "attributes", "(", "always", "omitted", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L240-L288
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/orm_inspect.py
rewrite_relationships
def rewrite_relationships(oldobj: object, newobj: object, objmap: Dict[object, object], debug: bool = False, skip_table_names: List[str] = None) -> None: """ A utility function only. Used in copying objects between SQLAlchemy sessions. Both ``oldobj`` and ``newobj`` are SQLAlchemy instances. The instance ``newobj`` is already a copy of ``oldobj`` but we wish to rewrite its relationships, according to the map ``objmap``, which maps old to new objects. For example: - Suppose a source session has a Customer record and a Sale record containing ``sale.customer_id``, a foreign key to Customer. - We may have corresponding Python SQLAlchemy ORM objects ``customer_1_src`` and ``sale_1_src``. - We copy them into a destination database, where their Python ORM objects are ``customer_1_dest`` and ``sale_1_dest``. - In the process we set up an object map looking like: .. code-block:: none Old session New session ------------------------------- customer_1_src customer_1_dest sale_1_src sale_1_dest - Now, we wish to make ``sale_1_dest`` have a relationship to ``customer_1_dest``, in the same way that ``sale_1_src`` has a relationship to ``customer_1_src``. This function will modify ``sale_1_dest`` accordingly, given this object map. It will observe that ``sale_1_src`` (here ``oldobj``) has a relationship to ``customer_1_src``; it will note that ``objmap`` maps ``customer_1_src`` to ``customer_1_dest``; it will create the relationship from ``sale_1_dest`` (here ``newobj``) to ``customer_1_dest``. Args: oldobj: SQLAlchemy ORM object to read from newobj: SQLAlchemy ORM object to write to objmap: dictionary mapping "source" objects to their corresponding "destination" object. debug: be verbose skip_table_names: if a related table's name is in this (optional) list, that relationship is skipped """ skip_table_names = skip_table_names or [] # type: List[str] insp = inspect(oldobj) # type: InstanceState # insp.mapper.relationships is of type # sqlalchemy.utils._collections.ImmutableProperties, which is basically # a sort of AttrDict. for attrname_rel in insp.mapper.relationships.items(): # type: Tuple[str, RelationshipProperty] # noqa attrname = attrname_rel[0] rel_prop = attrname_rel[1] if rel_prop.viewonly: if debug: log.debug("Skipping viewonly relationship") continue # don't attempt to write viewonly relationships # noqa related_class = rel_prop.mapper.class_ related_table_name = related_class.__tablename__ # type: str if related_table_name in skip_table_names: if debug: log.debug("Skipping relationship for related table {!r}", related_table_name) continue # The relationship is an abstract object (so getting the # relationship from the old object and from the new, with e.g. # newrel = newinsp.mapper.relationships[oldrel.key], # yield the same object. All we need from it is the key name. # rel_key = rel.key # type: str # ... but also available from the mapper as attrname, above related_old = getattr(oldobj, attrname) if rel_prop.uselist: related_new = [objmap[r] for r in related_old] elif related_old is not None: related_new = objmap[related_old] else: related_new = None if debug: log.debug("rewrite_relationships: relationship {} -> {}", attrname, related_new) setattr(newobj, attrname, related_new)
python
def rewrite_relationships(oldobj: object, newobj: object, objmap: Dict[object, object], debug: bool = False, skip_table_names: List[str] = None) -> None: """ A utility function only. Used in copying objects between SQLAlchemy sessions. Both ``oldobj`` and ``newobj`` are SQLAlchemy instances. The instance ``newobj`` is already a copy of ``oldobj`` but we wish to rewrite its relationships, according to the map ``objmap``, which maps old to new objects. For example: - Suppose a source session has a Customer record and a Sale record containing ``sale.customer_id``, a foreign key to Customer. - We may have corresponding Python SQLAlchemy ORM objects ``customer_1_src`` and ``sale_1_src``. - We copy them into a destination database, where their Python ORM objects are ``customer_1_dest`` and ``sale_1_dest``. - In the process we set up an object map looking like: .. code-block:: none Old session New session ------------------------------- customer_1_src customer_1_dest sale_1_src sale_1_dest - Now, we wish to make ``sale_1_dest`` have a relationship to ``customer_1_dest``, in the same way that ``sale_1_src`` has a relationship to ``customer_1_src``. This function will modify ``sale_1_dest`` accordingly, given this object map. It will observe that ``sale_1_src`` (here ``oldobj``) has a relationship to ``customer_1_src``; it will note that ``objmap`` maps ``customer_1_src`` to ``customer_1_dest``; it will create the relationship from ``sale_1_dest`` (here ``newobj``) to ``customer_1_dest``. Args: oldobj: SQLAlchemy ORM object to read from newobj: SQLAlchemy ORM object to write to objmap: dictionary mapping "source" objects to their corresponding "destination" object. debug: be verbose skip_table_names: if a related table's name is in this (optional) list, that relationship is skipped """ skip_table_names = skip_table_names or [] # type: List[str] insp = inspect(oldobj) # type: InstanceState # insp.mapper.relationships is of type # sqlalchemy.utils._collections.ImmutableProperties, which is basically # a sort of AttrDict. for attrname_rel in insp.mapper.relationships.items(): # type: Tuple[str, RelationshipProperty] # noqa attrname = attrname_rel[0] rel_prop = attrname_rel[1] if rel_prop.viewonly: if debug: log.debug("Skipping viewonly relationship") continue # don't attempt to write viewonly relationships # noqa related_class = rel_prop.mapper.class_ related_table_name = related_class.__tablename__ # type: str if related_table_name in skip_table_names: if debug: log.debug("Skipping relationship for related table {!r}", related_table_name) continue # The relationship is an abstract object (so getting the # relationship from the old object and from the new, with e.g. # newrel = newinsp.mapper.relationships[oldrel.key], # yield the same object. All we need from it is the key name. # rel_key = rel.key # type: str # ... but also available from the mapper as attrname, above related_old = getattr(oldobj, attrname) if rel_prop.uselist: related_new = [objmap[r] for r in related_old] elif related_old is not None: related_new = objmap[related_old] else: related_new = None if debug: log.debug("rewrite_relationships: relationship {} -> {}", attrname, related_new) setattr(newobj, attrname, related_new)
[ "def", "rewrite_relationships", "(", "oldobj", ":", "object", ",", "newobj", ":", "object", ",", "objmap", ":", "Dict", "[", "object", ",", "object", "]", ",", "debug", ":", "bool", "=", "False", ",", "skip_table_names", ":", "List", "[", "str", "]", "=", "None", ")", "->", "None", ":", "skip_table_names", "=", "skip_table_names", "or", "[", "]", "# type: List[str]", "insp", "=", "inspect", "(", "oldobj", ")", "# type: InstanceState", "# insp.mapper.relationships is of type", "# sqlalchemy.utils._collections.ImmutableProperties, which is basically", "# a sort of AttrDict.", "for", "attrname_rel", "in", "insp", ".", "mapper", ".", "relationships", ".", "items", "(", ")", ":", "# type: Tuple[str, RelationshipProperty] # noqa", "attrname", "=", "attrname_rel", "[", "0", "]", "rel_prop", "=", "attrname_rel", "[", "1", "]", "if", "rel_prop", ".", "viewonly", ":", "if", "debug", ":", "log", ".", "debug", "(", "\"Skipping viewonly relationship\"", ")", "continue", "# don't attempt to write viewonly relationships # noqa", "related_class", "=", "rel_prop", ".", "mapper", ".", "class_", "related_table_name", "=", "related_class", ".", "__tablename__", "# type: str", "if", "related_table_name", "in", "skip_table_names", ":", "if", "debug", ":", "log", ".", "debug", "(", "\"Skipping relationship for related table {!r}\"", ",", "related_table_name", ")", "continue", "# The relationship is an abstract object (so getting the", "# relationship from the old object and from the new, with e.g.", "# newrel = newinsp.mapper.relationships[oldrel.key],", "# yield the same object. All we need from it is the key name.", "# rel_key = rel.key # type: str", "# ... but also available from the mapper as attrname, above", "related_old", "=", "getattr", "(", "oldobj", ",", "attrname", ")", "if", "rel_prop", ".", "uselist", ":", "related_new", "=", "[", "objmap", "[", "r", "]", "for", "r", "in", "related_old", "]", "elif", "related_old", "is", "not", "None", ":", "related_new", "=", "objmap", "[", "related_old", "]", "else", ":", "related_new", "=", "None", "if", "debug", ":", "log", ".", "debug", "(", "\"rewrite_relationships: relationship {} -> {}\"", ",", "attrname", ",", "related_new", ")", "setattr", "(", "newobj", ",", "attrname", ",", "related_new", ")" ]
A utility function only. Used in copying objects between SQLAlchemy sessions. Both ``oldobj`` and ``newobj`` are SQLAlchemy instances. The instance ``newobj`` is already a copy of ``oldobj`` but we wish to rewrite its relationships, according to the map ``objmap``, which maps old to new objects. For example: - Suppose a source session has a Customer record and a Sale record containing ``sale.customer_id``, a foreign key to Customer. - We may have corresponding Python SQLAlchemy ORM objects ``customer_1_src`` and ``sale_1_src``. - We copy them into a destination database, where their Python ORM objects are ``customer_1_dest`` and ``sale_1_dest``. - In the process we set up an object map looking like: .. code-block:: none Old session New session ------------------------------- customer_1_src customer_1_dest sale_1_src sale_1_dest - Now, we wish to make ``sale_1_dest`` have a relationship to ``customer_1_dest``, in the same way that ``sale_1_src`` has a relationship to ``customer_1_src``. This function will modify ``sale_1_dest`` accordingly, given this object map. It will observe that ``sale_1_src`` (here ``oldobj``) has a relationship to ``customer_1_src``; it will note that ``objmap`` maps ``customer_1_src`` to ``customer_1_dest``; it will create the relationship from ``sale_1_dest`` (here ``newobj``) to ``customer_1_dest``. Args: oldobj: SQLAlchemy ORM object to read from newobj: SQLAlchemy ORM object to write to objmap: dictionary mapping "source" objects to their corresponding "destination" object. debug: be verbose skip_table_names: if a related table's name is in this (optional) list, that relationship is skipped
[ "A", "utility", "function", "only", ".", "Used", "in", "copying", "objects", "between", "SQLAlchemy", "sessions", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L291-L382
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/orm_inspect.py
deepcopy_sqla_objects
def deepcopy_sqla_objects( startobjs: List[object], session: Session, flush: bool = True, debug: bool = False, debug_walk: bool = True, debug_rewrite_rel: bool = False, objmap: Dict[object, object] = None) -> None: """ Makes a copy of the specified SQLAlchemy ORM objects, inserting them into a new session. This function operates in several passes: 1. Walk the ORM tree through all objects and their relationships, copying every object thus found (via :func:`copy_sqla_object`, without their relationships), and building a map from each source-session object to its equivalent destination-session object. 2. Work through all the destination objects, rewriting their relationships (via :func:`rewrite_relationships`) so they relate to each other (rather than their source-session brethren). 3. Insert all the destination-session objects into the destination session. For this to succeed, every object must take an ``__init__`` call with no arguments (see :func:`copy_sqla_object`). (We can't specify the required ``args``/``kwargs``, since we are copying a tree of arbitrary objects.) Args: startobjs: SQLAlchemy ORM objects to copy session: destination SQLAlchemy :class:`Session` into which to insert the copies flush: flush the session when we've finished? debug: be verbose? debug_walk: be extra verbose when walking the ORM tree? debug_rewrite_rel: be extra verbose when rewriting relationships? objmap: starting object map from source-session to destination-session objects (see :func:`rewrite_relationships` for more detail); usually ``None`` to begin with. """ if objmap is None: objmap = {} # keys = old objects, values = new objects if debug: log.debug("deepcopy_sqla_objects: pass 1: create new objects") # Pass 1: iterate through all objects. (Can't guarantee to get # relationships correct until we've done this, since we don't know whether # or where the "root" of the PK tree is.) seen = set() for startobj in startobjs: for oldobj in walk_orm_tree(startobj, seen=seen, debug=debug_walk): if debug: log.debug("deepcopy_sqla_objects: copying {}", oldobj) newobj = copy_sqla_object(oldobj, omit_pk=True, omit_fk=True) # Don't insert the new object into the session here; it may trigger # an autoflush as the relationships are queried, and the new # objects are not ready for insertion yet (as their relationships # aren't set). # Note also the session.no_autoflush option: # "sqlalchemy.exc.OperationalError: (raised as a result of Query- # invoked autoflush; consider using a session.no_autoflush block if # this flush is occurring prematurely)..." objmap[oldobj] = newobj # Pass 2: set all relationship properties. if debug: log.debug("deepcopy_sqla_objects: pass 2: set relationships") for oldobj, newobj in objmap.items(): if debug: log.debug("deepcopy_sqla_objects: newobj: {}", newobj) rewrite_relationships(oldobj, newobj, objmap, debug=debug_rewrite_rel) # Now we can do session insert. if debug: log.debug("deepcopy_sqla_objects: pass 3: insert into session") for newobj in objmap.values(): session.add(newobj) # Done if debug: log.debug("deepcopy_sqla_objects: done") if flush: session.flush()
python
def deepcopy_sqla_objects( startobjs: List[object], session: Session, flush: bool = True, debug: bool = False, debug_walk: bool = True, debug_rewrite_rel: bool = False, objmap: Dict[object, object] = None) -> None: """ Makes a copy of the specified SQLAlchemy ORM objects, inserting them into a new session. This function operates in several passes: 1. Walk the ORM tree through all objects and their relationships, copying every object thus found (via :func:`copy_sqla_object`, without their relationships), and building a map from each source-session object to its equivalent destination-session object. 2. Work through all the destination objects, rewriting their relationships (via :func:`rewrite_relationships`) so they relate to each other (rather than their source-session brethren). 3. Insert all the destination-session objects into the destination session. For this to succeed, every object must take an ``__init__`` call with no arguments (see :func:`copy_sqla_object`). (We can't specify the required ``args``/``kwargs``, since we are copying a tree of arbitrary objects.) Args: startobjs: SQLAlchemy ORM objects to copy session: destination SQLAlchemy :class:`Session` into which to insert the copies flush: flush the session when we've finished? debug: be verbose? debug_walk: be extra verbose when walking the ORM tree? debug_rewrite_rel: be extra verbose when rewriting relationships? objmap: starting object map from source-session to destination-session objects (see :func:`rewrite_relationships` for more detail); usually ``None`` to begin with. """ if objmap is None: objmap = {} # keys = old objects, values = new objects if debug: log.debug("deepcopy_sqla_objects: pass 1: create new objects") # Pass 1: iterate through all objects. (Can't guarantee to get # relationships correct until we've done this, since we don't know whether # or where the "root" of the PK tree is.) seen = set() for startobj in startobjs: for oldobj in walk_orm_tree(startobj, seen=seen, debug=debug_walk): if debug: log.debug("deepcopy_sqla_objects: copying {}", oldobj) newobj = copy_sqla_object(oldobj, omit_pk=True, omit_fk=True) # Don't insert the new object into the session here; it may trigger # an autoflush as the relationships are queried, and the new # objects are not ready for insertion yet (as their relationships # aren't set). # Note also the session.no_autoflush option: # "sqlalchemy.exc.OperationalError: (raised as a result of Query- # invoked autoflush; consider using a session.no_autoflush block if # this flush is occurring prematurely)..." objmap[oldobj] = newobj # Pass 2: set all relationship properties. if debug: log.debug("deepcopy_sqla_objects: pass 2: set relationships") for oldobj, newobj in objmap.items(): if debug: log.debug("deepcopy_sqla_objects: newobj: {}", newobj) rewrite_relationships(oldobj, newobj, objmap, debug=debug_rewrite_rel) # Now we can do session insert. if debug: log.debug("deepcopy_sqla_objects: pass 3: insert into session") for newobj in objmap.values(): session.add(newobj) # Done if debug: log.debug("deepcopy_sqla_objects: done") if flush: session.flush()
[ "def", "deepcopy_sqla_objects", "(", "startobjs", ":", "List", "[", "object", "]", ",", "session", ":", "Session", ",", "flush", ":", "bool", "=", "True", ",", "debug", ":", "bool", "=", "False", ",", "debug_walk", ":", "bool", "=", "True", ",", "debug_rewrite_rel", ":", "bool", "=", "False", ",", "objmap", ":", "Dict", "[", "object", ",", "object", "]", "=", "None", ")", "->", "None", ":", "if", "objmap", "is", "None", ":", "objmap", "=", "{", "}", "# keys = old objects, values = new objects", "if", "debug", ":", "log", ".", "debug", "(", "\"deepcopy_sqla_objects: pass 1: create new objects\"", ")", "# Pass 1: iterate through all objects. (Can't guarantee to get", "# relationships correct until we've done this, since we don't know whether", "# or where the \"root\" of the PK tree is.)", "seen", "=", "set", "(", ")", "for", "startobj", "in", "startobjs", ":", "for", "oldobj", "in", "walk_orm_tree", "(", "startobj", ",", "seen", "=", "seen", ",", "debug", "=", "debug_walk", ")", ":", "if", "debug", ":", "log", ".", "debug", "(", "\"deepcopy_sqla_objects: copying {}\"", ",", "oldobj", ")", "newobj", "=", "copy_sqla_object", "(", "oldobj", ",", "omit_pk", "=", "True", ",", "omit_fk", "=", "True", ")", "# Don't insert the new object into the session here; it may trigger", "# an autoflush as the relationships are queried, and the new", "# objects are not ready for insertion yet (as their relationships", "# aren't set).", "# Note also the session.no_autoflush option:", "# \"sqlalchemy.exc.OperationalError: (raised as a result of Query-", "# invoked autoflush; consider using a session.no_autoflush block if", "# this flush is occurring prematurely)...\"", "objmap", "[", "oldobj", "]", "=", "newobj", "# Pass 2: set all relationship properties.", "if", "debug", ":", "log", ".", "debug", "(", "\"deepcopy_sqla_objects: pass 2: set relationships\"", ")", "for", "oldobj", ",", "newobj", "in", "objmap", ".", "items", "(", ")", ":", "if", "debug", ":", "log", ".", "debug", "(", "\"deepcopy_sqla_objects: newobj: {}\"", ",", "newobj", ")", "rewrite_relationships", "(", "oldobj", ",", "newobj", ",", "objmap", ",", "debug", "=", "debug_rewrite_rel", ")", "# Now we can do session insert.", "if", "debug", ":", "log", ".", "debug", "(", "\"deepcopy_sqla_objects: pass 3: insert into session\"", ")", "for", "newobj", "in", "objmap", ".", "values", "(", ")", ":", "session", ".", "add", "(", "newobj", ")", "# Done", "if", "debug", ":", "log", ".", "debug", "(", "\"deepcopy_sqla_objects: done\"", ")", "if", "flush", ":", "session", ".", "flush", "(", ")" ]
Makes a copy of the specified SQLAlchemy ORM objects, inserting them into a new session. This function operates in several passes: 1. Walk the ORM tree through all objects and their relationships, copying every object thus found (via :func:`copy_sqla_object`, without their relationships), and building a map from each source-session object to its equivalent destination-session object. 2. Work through all the destination objects, rewriting their relationships (via :func:`rewrite_relationships`) so they relate to each other (rather than their source-session brethren). 3. Insert all the destination-session objects into the destination session. For this to succeed, every object must take an ``__init__`` call with no arguments (see :func:`copy_sqla_object`). (We can't specify the required ``args``/``kwargs``, since we are copying a tree of arbitrary objects.) Args: startobjs: SQLAlchemy ORM objects to copy session: destination SQLAlchemy :class:`Session` into which to insert the copies flush: flush the session when we've finished? debug: be verbose? debug_walk: be extra verbose when walking the ORM tree? debug_rewrite_rel: be extra verbose when rewriting relationships? objmap: starting object map from source-session to destination-session objects (see :func:`rewrite_relationships` for more detail); usually ``None`` to begin with.
[ "Makes", "a", "copy", "of", "the", "specified", "SQLAlchemy", "ORM", "objects", "inserting", "them", "into", "a", "new", "session", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L385-L468
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/orm_inspect.py
deepcopy_sqla_object
def deepcopy_sqla_object(startobj: object, session: Session, flush: bool = True, debug: bool = False, debug_walk: bool = False, debug_rewrite_rel: bool = False, objmap: Dict[object, object] = None) -> object: """ Makes a copy of the object, inserting it into ``session``. Uses :func:`deepcopy_sqla_objects` (q.v.). A problem is the creation of duplicate dependency objects if you call it repeatedly. Optionally, if you pass the objmap in (which maps old to new objects), you can call this function repeatedly to clone a related set of objects... ... no, that doesn't really work, as it doesn't visit parents before children. The :func:`cardinal_pythonlib.sqlalchemy.merge_db.merge_db` function does that properly. Args: startobj: SQLAlchemy ORM object to deep-copy session: see :func:`deepcopy_sqla_objects` flush: see :func:`deepcopy_sqla_objects` debug: see :func:`deepcopy_sqla_objects` debug_walk: see :func:`deepcopy_sqla_objects` debug_rewrite_rel: see :func:`deepcopy_sqla_objects` objmap: see :func:`deepcopy_sqla_objects` Returns: the copied object matching ``startobj`` """ if objmap is None: objmap = {} # keys = old objects, values = new objects deepcopy_sqla_objects( startobjs=[startobj], session=session, flush=flush, debug=debug, debug_walk=debug_walk, debug_rewrite_rel=debug_rewrite_rel, objmap=objmap ) return objmap[startobj]
python
def deepcopy_sqla_object(startobj: object, session: Session, flush: bool = True, debug: bool = False, debug_walk: bool = False, debug_rewrite_rel: bool = False, objmap: Dict[object, object] = None) -> object: """ Makes a copy of the object, inserting it into ``session``. Uses :func:`deepcopy_sqla_objects` (q.v.). A problem is the creation of duplicate dependency objects if you call it repeatedly. Optionally, if you pass the objmap in (which maps old to new objects), you can call this function repeatedly to clone a related set of objects... ... no, that doesn't really work, as it doesn't visit parents before children. The :func:`cardinal_pythonlib.sqlalchemy.merge_db.merge_db` function does that properly. Args: startobj: SQLAlchemy ORM object to deep-copy session: see :func:`deepcopy_sqla_objects` flush: see :func:`deepcopy_sqla_objects` debug: see :func:`deepcopy_sqla_objects` debug_walk: see :func:`deepcopy_sqla_objects` debug_rewrite_rel: see :func:`deepcopy_sqla_objects` objmap: see :func:`deepcopy_sqla_objects` Returns: the copied object matching ``startobj`` """ if objmap is None: objmap = {} # keys = old objects, values = new objects deepcopy_sqla_objects( startobjs=[startobj], session=session, flush=flush, debug=debug, debug_walk=debug_walk, debug_rewrite_rel=debug_rewrite_rel, objmap=objmap ) return objmap[startobj]
[ "def", "deepcopy_sqla_object", "(", "startobj", ":", "object", ",", "session", ":", "Session", ",", "flush", ":", "bool", "=", "True", ",", "debug", ":", "bool", "=", "False", ",", "debug_walk", ":", "bool", "=", "False", ",", "debug_rewrite_rel", ":", "bool", "=", "False", ",", "objmap", ":", "Dict", "[", "object", ",", "object", "]", "=", "None", ")", "->", "object", ":", "if", "objmap", "is", "None", ":", "objmap", "=", "{", "}", "# keys = old objects, values = new objects", "deepcopy_sqla_objects", "(", "startobjs", "=", "[", "startobj", "]", ",", "session", "=", "session", ",", "flush", "=", "flush", ",", "debug", "=", "debug", ",", "debug_walk", "=", "debug_walk", ",", "debug_rewrite_rel", "=", "debug_rewrite_rel", ",", "objmap", "=", "objmap", ")", "return", "objmap", "[", "startobj", "]" ]
Makes a copy of the object, inserting it into ``session``. Uses :func:`deepcopy_sqla_objects` (q.v.). A problem is the creation of duplicate dependency objects if you call it repeatedly. Optionally, if you pass the objmap in (which maps old to new objects), you can call this function repeatedly to clone a related set of objects... ... no, that doesn't really work, as it doesn't visit parents before children. The :func:`cardinal_pythonlib.sqlalchemy.merge_db.merge_db` function does that properly. Args: startobj: SQLAlchemy ORM object to deep-copy session: see :func:`deepcopy_sqla_objects` flush: see :func:`deepcopy_sqla_objects` debug: see :func:`deepcopy_sqla_objects` debug_walk: see :func:`deepcopy_sqla_objects` debug_rewrite_rel: see :func:`deepcopy_sqla_objects` objmap: see :func:`deepcopy_sqla_objects` Returns: the copied object matching ``startobj``
[ "Makes", "a", "copy", "of", "the", "object", "inserting", "it", "into", "session", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L471-L516
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/orm_inspect.py
gen_columns
def gen_columns(obj) -> Generator[Tuple[str, Column], None, None]: """ Asks a SQLAlchemy ORM object: "what are your SQLAlchemy columns?" Yields tuples of ``(attr_name, Column)`` from an SQLAlchemy ORM object instance. Also works with the corresponding SQLAlchemy ORM class. Examples: .. code-block:: python from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.sql.schema import Column from sqlalchemy.sql.sqltypes import Integer Base = declarative_base() class MyClass(Base): __tablename__ = "mytable" pk = Column("pk", Integer, primary_key=True, autoincrement=True) a = Column("a", Integer) x = MyClass() list(gen_columns(x)) list(gen_columns(MyClass)) """ mapper = obj.__mapper__ # type: Mapper assert mapper, "gen_columns called on {!r} which is not an " \ "SQLAlchemy ORM object".format(obj) colmap = mapper.columns # type: OrderedProperties if not colmap: return for attrname, column in colmap.items(): # NB: column.name is the SQL column name, not the attribute name yield attrname, column
python
def gen_columns(obj) -> Generator[Tuple[str, Column], None, None]: """ Asks a SQLAlchemy ORM object: "what are your SQLAlchemy columns?" Yields tuples of ``(attr_name, Column)`` from an SQLAlchemy ORM object instance. Also works with the corresponding SQLAlchemy ORM class. Examples: .. code-block:: python from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.sql.schema import Column from sqlalchemy.sql.sqltypes import Integer Base = declarative_base() class MyClass(Base): __tablename__ = "mytable" pk = Column("pk", Integer, primary_key=True, autoincrement=True) a = Column("a", Integer) x = MyClass() list(gen_columns(x)) list(gen_columns(MyClass)) """ mapper = obj.__mapper__ # type: Mapper assert mapper, "gen_columns called on {!r} which is not an " \ "SQLAlchemy ORM object".format(obj) colmap = mapper.columns # type: OrderedProperties if not colmap: return for attrname, column in colmap.items(): # NB: column.name is the SQL column name, not the attribute name yield attrname, column
[ "def", "gen_columns", "(", "obj", ")", "->", "Generator", "[", "Tuple", "[", "str", ",", "Column", "]", ",", "None", ",", "None", "]", ":", "mapper", "=", "obj", ".", "__mapper__", "# type: Mapper", "assert", "mapper", ",", "\"gen_columns called on {!r} which is not an \"", "\"SQLAlchemy ORM object\"", ".", "format", "(", "obj", ")", "colmap", "=", "mapper", ".", "columns", "# type: OrderedProperties", "if", "not", "colmap", ":", "return", "for", "attrname", ",", "column", "in", "colmap", ".", "items", "(", ")", ":", "# NB: column.name is the SQL column name, not the attribute name", "yield", "attrname", ",", "column" ]
Asks a SQLAlchemy ORM object: "what are your SQLAlchemy columns?" Yields tuples of ``(attr_name, Column)`` from an SQLAlchemy ORM object instance. Also works with the corresponding SQLAlchemy ORM class. Examples: .. code-block:: python from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.sql.schema import Column from sqlalchemy.sql.sqltypes import Integer Base = declarative_base() class MyClass(Base): __tablename__ = "mytable" pk = Column("pk", Integer, primary_key=True, autoincrement=True) a = Column("a", Integer) x = MyClass() list(gen_columns(x)) list(gen_columns(MyClass))
[ "Asks", "a", "SQLAlchemy", "ORM", "object", ":", "what", "are", "your", "SQLAlchemy", "columns?" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L523-L557
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/orm_inspect.py
get_pk_attrnames
def get_pk_attrnames(obj) -> List[str]: """ Asks an SQLAlchemy ORM object: "what are your primary key(s)?" Args: obj: SQLAlchemy ORM object Returns: list of attribute names of primary-key columns """ return [attrname for attrname, column in gen_columns(obj) if column.primary_key]
python
def get_pk_attrnames(obj) -> List[str]: """ Asks an SQLAlchemy ORM object: "what are your primary key(s)?" Args: obj: SQLAlchemy ORM object Returns: list of attribute names of primary-key columns """ return [attrname for attrname, column in gen_columns(obj) if column.primary_key]
[ "def", "get_pk_attrnames", "(", "obj", ")", "->", "List", "[", "str", "]", ":", "return", "[", "attrname", "for", "attrname", ",", "column", "in", "gen_columns", "(", "obj", ")", "if", "column", ".", "primary_key", "]" ]
Asks an SQLAlchemy ORM object: "what are your primary key(s)?" Args: obj: SQLAlchemy ORM object Returns: list of attribute names of primary-key columns
[ "Asks", "an", "SQLAlchemy", "ORM", "object", ":", "what", "are", "your", "primary", "key", "(", "s", ")", "?" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L566-L579
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/orm_inspect.py
gen_columns_for_uninstrumented_class
def gen_columns_for_uninstrumented_class(cls: Type) \ -> Generator[Tuple[str, Column], None, None]: """ Generate ``(attr_name, Column)`` tuples from an UNINSTRUMENTED class, i.e. one that does not inherit from ``declarative_base()``. Use this for mixins of that kind. SUBOPTIMAL. May produce warnings like: .. code-block:: none SAWarning: Unmanaged access of declarative attribute id from non-mapped class GenericTabletRecordMixin Try to use :func:`gen_columns` instead. """ # noqa for attrname in dir(cls): potential_column = getattr(cls, attrname) if isinstance(potential_column, Column): yield attrname, potential_column
python
def gen_columns_for_uninstrumented_class(cls: Type) \ -> Generator[Tuple[str, Column], None, None]: """ Generate ``(attr_name, Column)`` tuples from an UNINSTRUMENTED class, i.e. one that does not inherit from ``declarative_base()``. Use this for mixins of that kind. SUBOPTIMAL. May produce warnings like: .. code-block:: none SAWarning: Unmanaged access of declarative attribute id from non-mapped class GenericTabletRecordMixin Try to use :func:`gen_columns` instead. """ # noqa for attrname in dir(cls): potential_column = getattr(cls, attrname) if isinstance(potential_column, Column): yield attrname, potential_column
[ "def", "gen_columns_for_uninstrumented_class", "(", "cls", ":", "Type", ")", "->", "Generator", "[", "Tuple", "[", "str", ",", "Column", "]", ",", "None", ",", "None", "]", ":", "# noqa", "for", "attrname", "in", "dir", "(", "cls", ")", ":", "potential_column", "=", "getattr", "(", "cls", ",", "attrname", ")", "if", "isinstance", "(", "potential_column", ",", "Column", ")", ":", "yield", "attrname", ",", "potential_column" ]
Generate ``(attr_name, Column)`` tuples from an UNINSTRUMENTED class, i.e. one that does not inherit from ``declarative_base()``. Use this for mixins of that kind. SUBOPTIMAL. May produce warnings like: .. code-block:: none SAWarning: Unmanaged access of declarative attribute id from non-mapped class GenericTabletRecordMixin Try to use :func:`gen_columns` instead.
[ "Generate", "(", "attr_name", "Column", ")", "tuples", "from", "an", "UNINSTRUMENTED", "class", "i", ".", "e", ".", "one", "that", "does", "not", "inherit", "from", "declarative_base", "()", ".", "Use", "this", "for", "mixins", "of", "that", "kind", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L582-L600
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/orm_inspect.py
attrname_to_colname_dict
def attrname_to_colname_dict(cls) -> Dict[str, str]: """ Asks an SQLAlchemy class how its attribute names correspond to database column names. Args: cls: SQLAlchemy ORM class Returns: a dictionary mapping attribute names to database column names """ attr_col = {} # type: Dict[str, str] for attrname, column in gen_columns(cls): attr_col[attrname] = column.name return attr_col
python
def attrname_to_colname_dict(cls) -> Dict[str, str]: """ Asks an SQLAlchemy class how its attribute names correspond to database column names. Args: cls: SQLAlchemy ORM class Returns: a dictionary mapping attribute names to database column names """ attr_col = {} # type: Dict[str, str] for attrname, column in gen_columns(cls): attr_col[attrname] = column.name return attr_col
[ "def", "attrname_to_colname_dict", "(", "cls", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "attr_col", "=", "{", "}", "# type: Dict[str, str]", "for", "attrname", ",", "column", "in", "gen_columns", "(", "cls", ")", ":", "attr_col", "[", "attrname", "]", "=", "column", ".", "name", "return", "attr_col" ]
Asks an SQLAlchemy class how its attribute names correspond to database column names. Args: cls: SQLAlchemy ORM class Returns: a dictionary mapping attribute names to database column names
[ "Asks", "an", "SQLAlchemy", "class", "how", "its", "attribute", "names", "correspond", "to", "database", "column", "names", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L603-L617
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/orm_inspect.py
gen_relationships
def gen_relationships(obj) -> Generator[Tuple[str, RelationshipProperty, Type], None, None]: """ Yields tuples of ``(attrname, RelationshipProperty, related_class)`` for all relationships of an ORM object. The object 'obj' can be EITHER an instance OR a class. """ insp = inspect(obj) # type: InstanceState # insp.mapper.relationships is of type # sqlalchemy.utils._collections.ImmutableProperties, which is basically # a sort of AttrDict. for attrname, rel_prop in insp.mapper.relationships.items(): # type: Tuple[str, RelationshipProperty] # noqa # noinspection PyUnresolvedReferences related_class = rel_prop.mapper.class_ # log.critical("gen_relationships: attrname={!r}, " # "rel_prop={!r}, related_class={!r}, rel_prop.info={!r}", # attrname, rel_prop, related_class, rel_prop.info) yield attrname, rel_prop, related_class
python
def gen_relationships(obj) -> Generator[Tuple[str, RelationshipProperty, Type], None, None]: """ Yields tuples of ``(attrname, RelationshipProperty, related_class)`` for all relationships of an ORM object. The object 'obj' can be EITHER an instance OR a class. """ insp = inspect(obj) # type: InstanceState # insp.mapper.relationships is of type # sqlalchemy.utils._collections.ImmutableProperties, which is basically # a sort of AttrDict. for attrname, rel_prop in insp.mapper.relationships.items(): # type: Tuple[str, RelationshipProperty] # noqa # noinspection PyUnresolvedReferences related_class = rel_prop.mapper.class_ # log.critical("gen_relationships: attrname={!r}, " # "rel_prop={!r}, related_class={!r}, rel_prop.info={!r}", # attrname, rel_prop, related_class, rel_prop.info) yield attrname, rel_prop, related_class
[ "def", "gen_relationships", "(", "obj", ")", "->", "Generator", "[", "Tuple", "[", "str", ",", "RelationshipProperty", ",", "Type", "]", ",", "None", ",", "None", "]", ":", "insp", "=", "inspect", "(", "obj", ")", "# type: InstanceState", "# insp.mapper.relationships is of type", "# sqlalchemy.utils._collections.ImmutableProperties, which is basically", "# a sort of AttrDict.", "for", "attrname", ",", "rel_prop", "in", "insp", ".", "mapper", ".", "relationships", ".", "items", "(", ")", ":", "# type: Tuple[str, RelationshipProperty] # noqa", "# noinspection PyUnresolvedReferences", "related_class", "=", "rel_prop", ".", "mapper", ".", "class_", "# log.critical(\"gen_relationships: attrname={!r}, \"", "# \"rel_prop={!r}, related_class={!r}, rel_prop.info={!r}\",", "# attrname, rel_prop, related_class, rel_prop.info)", "yield", "attrname", ",", "rel_prop", ",", "related_class" ]
Yields tuples of ``(attrname, RelationshipProperty, related_class)`` for all relationships of an ORM object. The object 'obj' can be EITHER an instance OR a class.
[ "Yields", "tuples", "of", "(", "attrname", "RelationshipProperty", "related_class", ")", "for", "all", "relationships", "of", "an", "ORM", "object", ".", "The", "object", "obj", "can", "be", "EITHER", "an", "instance", "OR", "a", "class", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L628-L645
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/orm_inspect.py
get_orm_columns
def get_orm_columns(cls: Type) -> List[Column]: """ Gets :class:`Column` objects from an SQLAlchemy ORM class. Does not provide their attribute names. """ mapper = inspect(cls) # type: Mapper # ... returns InstanceState if called with an ORM object # http://docs.sqlalchemy.org/en/latest/orm/session_state_management.html#session-object-states # noqa # ... returns Mapper if called with an ORM class # http://docs.sqlalchemy.org/en/latest/orm/mapping_api.html#sqlalchemy.orm.mapper.Mapper # noqa colmap = mapper.columns # type: OrderedProperties return colmap.values()
python
def get_orm_columns(cls: Type) -> List[Column]: """ Gets :class:`Column` objects from an SQLAlchemy ORM class. Does not provide their attribute names. """ mapper = inspect(cls) # type: Mapper # ... returns InstanceState if called with an ORM object # http://docs.sqlalchemy.org/en/latest/orm/session_state_management.html#session-object-states # noqa # ... returns Mapper if called with an ORM class # http://docs.sqlalchemy.org/en/latest/orm/mapping_api.html#sqlalchemy.orm.mapper.Mapper # noqa colmap = mapper.columns # type: OrderedProperties return colmap.values()
[ "def", "get_orm_columns", "(", "cls", ":", "Type", ")", "->", "List", "[", "Column", "]", ":", "mapper", "=", "inspect", "(", "cls", ")", "# type: Mapper", "# ... returns InstanceState if called with an ORM object", "# http://docs.sqlalchemy.org/en/latest/orm/session_state_management.html#session-object-states # noqa", "# ... returns Mapper if called with an ORM class", "# http://docs.sqlalchemy.org/en/latest/orm/mapping_api.html#sqlalchemy.orm.mapper.Mapper # noqa", "colmap", "=", "mapper", ".", "columns", "# type: OrderedProperties", "return", "colmap", ".", "values", "(", ")" ]
Gets :class:`Column` objects from an SQLAlchemy ORM class. Does not provide their attribute names.
[ "Gets", ":", "class", ":", "Column", "objects", "from", "an", "SQLAlchemy", "ORM", "class", ".", "Does", "not", "provide", "their", "attribute", "names", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L652-L663
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/orm_inspect.py
get_orm_column_names
def get_orm_column_names(cls: Type, sort: bool = False) -> List[str]: """ Gets column names (that is, database column names) from an SQLAlchemy ORM class. """ colnames = [col.name for col in get_orm_columns(cls)] return sorted(colnames) if sort else colnames
python
def get_orm_column_names(cls: Type, sort: bool = False) -> List[str]: """ Gets column names (that is, database column names) from an SQLAlchemy ORM class. """ colnames = [col.name for col in get_orm_columns(cls)] return sorted(colnames) if sort else colnames
[ "def", "get_orm_column_names", "(", "cls", ":", "Type", ",", "sort", ":", "bool", "=", "False", ")", "->", "List", "[", "str", "]", ":", "colnames", "=", "[", "col", ".", "name", "for", "col", "in", "get_orm_columns", "(", "cls", ")", "]", "return", "sorted", "(", "colnames", ")", "if", "sort", "else", "colnames" ]
Gets column names (that is, database column names) from an SQLAlchemy ORM class.
[ "Gets", "column", "names", "(", "that", "is", "database", "column", "names", ")", "from", "an", "SQLAlchemy", "ORM", "class", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L666-L672
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/orm_inspect.py
get_table_names_from_metadata
def get_table_names_from_metadata(metadata: MetaData) -> List[str]: """ Returns all database table names found in an SQLAlchemy :class:`MetaData` object. """ return [table.name for table in metadata.tables.values()]
python
def get_table_names_from_metadata(metadata: MetaData) -> List[str]: """ Returns all database table names found in an SQLAlchemy :class:`MetaData` object. """ return [table.name for table in metadata.tables.values()]
[ "def", "get_table_names_from_metadata", "(", "metadata", ":", "MetaData", ")", "->", "List", "[", "str", "]", ":", "return", "[", "table", ".", "name", "for", "table", "in", "metadata", ".", "tables", ".", "values", "(", ")", "]" ]
Returns all database table names found in an SQLAlchemy :class:`MetaData` object.
[ "Returns", "all", "database", "table", "names", "found", "in", "an", "SQLAlchemy", ":", "class", ":", "MetaData", "object", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L679-L684
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/orm_inspect.py
gen_orm_classes_from_base
def gen_orm_classes_from_base(base: Type) -> Generator[Type, None, None]: """ From an SQLAlchemy ORM base class, yield all the subclasses (except those that are abstract). If you begin with the proper :class`Base` class, then this should give all ORM classes in use. """ for cls in gen_all_subclasses(base): if _get_immediate_cls_attr(cls, '__abstract__', strict=True): # This is SQLAlchemy's own way of detecting abstract classes; see # sqlalchemy.ext.declarative.base continue # NOT an ORM class yield cls
python
def gen_orm_classes_from_base(base: Type) -> Generator[Type, None, None]: """ From an SQLAlchemy ORM base class, yield all the subclasses (except those that are abstract). If you begin with the proper :class`Base` class, then this should give all ORM classes in use. """ for cls in gen_all_subclasses(base): if _get_immediate_cls_attr(cls, '__abstract__', strict=True): # This is SQLAlchemy's own way of detecting abstract classes; see # sqlalchemy.ext.declarative.base continue # NOT an ORM class yield cls
[ "def", "gen_orm_classes_from_base", "(", "base", ":", "Type", ")", "->", "Generator", "[", "Type", ",", "None", ",", "None", "]", ":", "for", "cls", "in", "gen_all_subclasses", "(", "base", ")", ":", "if", "_get_immediate_cls_attr", "(", "cls", ",", "'__abstract__'", ",", "strict", "=", "True", ")", ":", "# This is SQLAlchemy's own way of detecting abstract classes; see", "# sqlalchemy.ext.declarative.base", "continue", "# NOT an ORM class", "yield", "cls" ]
From an SQLAlchemy ORM base class, yield all the subclasses (except those that are abstract). If you begin with the proper :class`Base` class, then this should give all ORM classes in use.
[ "From", "an", "SQLAlchemy", "ORM", "base", "class", "yield", "all", "the", "subclasses", "(", "except", "those", "that", "are", "abstract", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L697-L710
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/orm_inspect.py
get_orm_classes_by_table_name_from_base
def get_orm_classes_by_table_name_from_base(base: Type) -> Dict[str, Type]: """ Given an SQLAlchemy ORM base class, returns a dictionary whose keys are table names and whose values are ORM classes. If you begin with the proper :class`Base` class, then this should give all tables and ORM classes in use. """ # noinspection PyUnresolvedReferences return {cls.__tablename__: cls for cls in gen_orm_classes_from_base(base)}
python
def get_orm_classes_by_table_name_from_base(base: Type) -> Dict[str, Type]: """ Given an SQLAlchemy ORM base class, returns a dictionary whose keys are table names and whose values are ORM classes. If you begin with the proper :class`Base` class, then this should give all tables and ORM classes in use. """ # noinspection PyUnresolvedReferences return {cls.__tablename__: cls for cls in gen_orm_classes_from_base(base)}
[ "def", "get_orm_classes_by_table_name_from_base", "(", "base", ":", "Type", ")", "->", "Dict", "[", "str", ",", "Type", "]", ":", "# noinspection PyUnresolvedReferences", "return", "{", "cls", ".", "__tablename__", ":", "cls", "for", "cls", "in", "gen_orm_classes_from_base", "(", "base", ")", "}" ]
Given an SQLAlchemy ORM base class, returns a dictionary whose keys are table names and whose values are ORM classes. If you begin with the proper :class`Base` class, then this should give all tables and ORM classes in use.
[ "Given", "an", "SQLAlchemy", "ORM", "base", "class", "returns", "a", "dictionary", "whose", "keys", "are", "table", "names", "and", "whose", "values", "are", "ORM", "classes", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L713-L722
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/orm_inspect.py
SqlAlchemyAttrDictMixin.get_attrdict
def get_attrdict(self) -> OrderedNamespace: """ Returns what looks like a plain object with the values of the SQLAlchemy ORM object. """ # noinspection PyUnresolvedReferences columns = self.__table__.columns.keys() values = (getattr(self, x) for x in columns) zipped = zip(columns, values) return OrderedNamespace(zipped)
python
def get_attrdict(self) -> OrderedNamespace: """ Returns what looks like a plain object with the values of the SQLAlchemy ORM object. """ # noinspection PyUnresolvedReferences columns = self.__table__.columns.keys() values = (getattr(self, x) for x in columns) zipped = zip(columns, values) return OrderedNamespace(zipped)
[ "def", "get_attrdict", "(", "self", ")", "->", "OrderedNamespace", ":", "# noinspection PyUnresolvedReferences", "columns", "=", "self", ".", "__table__", ".", "columns", ".", "keys", "(", ")", "values", "=", "(", "getattr", "(", "self", ",", "x", ")", "for", "x", "in", "columns", ")", "zipped", "=", "zip", "(", "columns", ",", "values", ")", "return", "OrderedNamespace", "(", "zipped", ")" ]
Returns what looks like a plain object with the values of the SQLAlchemy ORM object.
[ "Returns", "what", "looks", "like", "a", "plain", "object", "with", "the", "values", "of", "the", "SQLAlchemy", "ORM", "object", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L108-L117
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/orm_inspect.py
SqlAlchemyAttrDictMixin.from_attrdict
def from_attrdict(cls, attrdict: OrderedNamespace) -> object: """ Builds a new instance of the ORM object from values in an attrdict. """ dictionary = attrdict.__dict__ # noinspection PyArgumentList return cls(**dictionary)
python
def from_attrdict(cls, attrdict: OrderedNamespace) -> object: """ Builds a new instance of the ORM object from values in an attrdict. """ dictionary = attrdict.__dict__ # noinspection PyArgumentList return cls(**dictionary)
[ "def", "from_attrdict", "(", "cls", ",", "attrdict", ":", "OrderedNamespace", ")", "->", "object", ":", "dictionary", "=", "attrdict", ".", "__dict__", "# noinspection PyArgumentList", "return", "cls", "(", "*", "*", "dictionary", ")" ]
Builds a new instance of the ORM object from values in an attrdict.
[ "Builds", "a", "new", "instance", "of", "the", "ORM", "object", "from", "values", "in", "an", "attrdict", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L127-L133
RudolfCardinal/pythonlib
cardinal_pythonlib/classes.py
derived_class_implements_method
def derived_class_implements_method(derived: Type[T1], base: Type[T2], method_name: str) -> bool: """ Does a derived class implement a method (and not just inherit a base class's version)? Args: derived: a derived class base: a base class method_name: the name of a method Returns: whether the derived class method is (a) present, and (b) different to the base class's version of the same method Note: if C derives from B derives from A, then a check on C versus A will succeed if C implements the method, or if C inherits it from B but B has re-implemented it compared to A. """ derived_method = getattr(derived, method_name, None) if derived_method is None: return False base_method = getattr(base, method_name, None) # if six.PY2: # return derived_method.__func__ != base_method.__func__ # else: # return derived_method is not base_method return derived_method is not base_method
python
def derived_class_implements_method(derived: Type[T1], base: Type[T2], method_name: str) -> bool: """ Does a derived class implement a method (and not just inherit a base class's version)? Args: derived: a derived class base: a base class method_name: the name of a method Returns: whether the derived class method is (a) present, and (b) different to the base class's version of the same method Note: if C derives from B derives from A, then a check on C versus A will succeed if C implements the method, or if C inherits it from B but B has re-implemented it compared to A. """ derived_method = getattr(derived, method_name, None) if derived_method is None: return False base_method = getattr(base, method_name, None) # if six.PY2: # return derived_method.__func__ != base_method.__func__ # else: # return derived_method is not base_method return derived_method is not base_method
[ "def", "derived_class_implements_method", "(", "derived", ":", "Type", "[", "T1", "]", ",", "base", ":", "Type", "[", "T2", "]", ",", "method_name", ":", "str", ")", "->", "bool", ":", "derived_method", "=", "getattr", "(", "derived", ",", "method_name", ",", "None", ")", "if", "derived_method", "is", "None", ":", "return", "False", "base_method", "=", "getattr", "(", "base", ",", "method_name", ",", "None", ")", "# if six.PY2:", "# return derived_method.__func__ != base_method.__func__", "# else:", "# return derived_method is not base_method", "return", "derived_method", "is", "not", "base_method" ]
Does a derived class implement a method (and not just inherit a base class's version)? Args: derived: a derived class base: a base class method_name: the name of a method Returns: whether the derived class method is (a) present, and (b) different to the base class's version of the same method Note: if C derives from B derives from A, then a check on C versus A will succeed if C implements the method, or if C inherits it from B but B has re-implemented it compared to A.
[ "Does", "a", "derived", "class", "implement", "a", "method", "(", "and", "not", "just", "inherit", "a", "base", "class", "s", "version", ")", "?" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/classes.py#L73-L102
RudolfCardinal/pythonlib
cardinal_pythonlib/classes.py
gen_all_subclasses
def gen_all_subclasses(cls: Type) -> Generator[Type, None, None]: """ Generates all subclasses of a class. Args: cls: a class Yields: all subclasses """ for s1 in cls.__subclasses__(): yield s1 for s2 in gen_all_subclasses(s1): yield s2
python
def gen_all_subclasses(cls: Type) -> Generator[Type, None, None]: """ Generates all subclasses of a class. Args: cls: a class Yields: all subclasses """ for s1 in cls.__subclasses__(): yield s1 for s2 in gen_all_subclasses(s1): yield s2
[ "def", "gen_all_subclasses", "(", "cls", ":", "Type", ")", "->", "Generator", "[", "Type", ",", "None", ",", "None", "]", ":", "for", "s1", "in", "cls", ".", "__subclasses__", "(", ")", ":", "yield", "s1", "for", "s2", "in", "gen_all_subclasses", "(", "s1", ")", ":", "yield", "s2" ]
Generates all subclasses of a class. Args: cls: a class Yields: all subclasses
[ "Generates", "all", "subclasses", "of", "a", "class", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/classes.py#L110-L125
davenquinn/Attitude
attitude/geom/util.py
augment_tensor
def augment_tensor(matrix, ndim=None): """ Increase the dimensionality of a tensor, splicing it into an identity matrix of a higher dimension. Useful for generalizing transformation matrices. """ s = matrix.shape if ndim is None: ndim = s[0]+1 arr = N.identity(ndim) arr[:s[0],:s[1]] = matrix return arr
python
def augment_tensor(matrix, ndim=None): """ Increase the dimensionality of a tensor, splicing it into an identity matrix of a higher dimension. Useful for generalizing transformation matrices. """ s = matrix.shape if ndim is None: ndim = s[0]+1 arr = N.identity(ndim) arr[:s[0],:s[1]] = matrix return arr
[ "def", "augment_tensor", "(", "matrix", ",", "ndim", "=", "None", ")", ":", "s", "=", "matrix", ".", "shape", "if", "ndim", "is", "None", ":", "ndim", "=", "s", "[", "0", "]", "+", "1", "arr", "=", "N", ".", "identity", "(", "ndim", ")", "arr", "[", ":", "s", "[", "0", "]", ",", ":", "s", "[", "1", "]", "]", "=", "matrix", "return", "arr" ]
Increase the dimensionality of a tensor, splicing it into an identity matrix of a higher dimension. Useful for generalizing transformation matrices.
[ "Increase", "the", "dimensionality", "of", "a", "tensor", "splicing", "it", "into", "an", "identity", "matrix", "of", "a", "higher", "dimension", ".", "Useful", "for", "generalizing", "transformation", "matrices", "." ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/geom/util.py#L9-L21
davenquinn/Attitude
attitude/geom/util.py
angle
def angle(v1,v2, cos=False): """ Find the angle between two vectors. :param cos: If True, the cosine of the angle will be returned. False by default. """ n = (norm(v1)*norm(v2)) _ = dot(v1,v2)/n return _ if cos else N.arccos(_)
python
def angle(v1,v2, cos=False): """ Find the angle between two vectors. :param cos: If True, the cosine of the angle will be returned. False by default. """ n = (norm(v1)*norm(v2)) _ = dot(v1,v2)/n return _ if cos else N.arccos(_)
[ "def", "angle", "(", "v1", ",", "v2", ",", "cos", "=", "False", ")", ":", "n", "=", "(", "norm", "(", "v1", ")", "*", "norm", "(", "v2", ")", ")", "_", "=", "dot", "(", "v1", ",", "v2", ")", "/", "n", "return", "_", "if", "cos", "else", "N", ".", "arccos", "(", "_", ")" ]
Find the angle between two vectors. :param cos: If True, the cosine of the angle will be returned. False by default.
[ "Find", "the", "angle", "between", "two", "vectors", "." ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/geom/util.py#L55-L64
davenquinn/Attitude
attitude/geom/util.py
perpendicular_vector
def perpendicular_vector(n): """ Get a random vector perpendicular to the given vector """ dim = len(n) if dim == 2: return n[::-1] # More complex in 3d for ix in range(dim): _ = N.zeros(dim) # Try to keep axes near the global projection # by finding vectors perpendicular to higher- # index axes first. This may or may not be worth # doing. _[dim-ix-1] = 1 v1 = N.cross(n,_) if N.linalg.norm(v1) != 0: return v1 raise ValueError("Cannot find perpendicular vector")
python
def perpendicular_vector(n): """ Get a random vector perpendicular to the given vector """ dim = len(n) if dim == 2: return n[::-1] # More complex in 3d for ix in range(dim): _ = N.zeros(dim) # Try to keep axes near the global projection # by finding vectors perpendicular to higher- # index axes first. This may or may not be worth # doing. _[dim-ix-1] = 1 v1 = N.cross(n,_) if N.linalg.norm(v1) != 0: return v1 raise ValueError("Cannot find perpendicular vector")
[ "def", "perpendicular_vector", "(", "n", ")", ":", "dim", "=", "len", "(", "n", ")", "if", "dim", "==", "2", ":", "return", "n", "[", ":", ":", "-", "1", "]", "# More complex in 3d", "for", "ix", "in", "range", "(", "dim", ")", ":", "_", "=", "N", ".", "zeros", "(", "dim", ")", "# Try to keep axes near the global projection", "# by finding vectors perpendicular to higher-", "# index axes first. This may or may not be worth", "# doing.", "_", "[", "dim", "-", "ix", "-", "1", "]", "=", "1", "v1", "=", "N", ".", "cross", "(", "n", ",", "_", ")", "if", "N", ".", "linalg", ".", "norm", "(", "v1", ")", "!=", "0", ":", "return", "v1", "raise", "ValueError", "(", "\"Cannot find perpendicular vector\"", ")" ]
Get a random vector perpendicular to the given vector
[ "Get", "a", "random", "vector", "perpendicular", "to", "the", "given", "vector" ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/geom/util.py#L91-L110
RudolfCardinal/pythonlib
cardinal_pythonlib/signalfunc.py
trap_ctrl_c_ctrl_break
def trap_ctrl_c_ctrl_break() -> None: """ Prevent ``CTRL-C``, ``CTRL-BREAK``, and similar signals from doing anything. See - https://docs.python.org/3/library/signal.html#signal.SIG_IGN - https://msdn.microsoft.com/en-us/library/xdkz3x12.aspx - https://msdn.microsoft.com/en-us/library/windows/desktop/ms682541(v=vs.85).aspx Under Windows, the only options are: =========== ======================= ===================================== Signal Meaning Comment =========== ======================= ===================================== SIGABRT abnormal termination SIGFPE floating-point error SIGILL illegal instruction SIGINT CTRL+C signal -- trapped here SIGSEGV illegal storage access SIGTERM termination request -- trapped here SIGBREAK CTRL+BREAK -- trapped here under Windows =========== ======================= ===================================== In Linux, you also find: =========== ============================= Signal Meaning =========== ============================= SIGBUS bus error / unaligned access =========== ============================= To ignore, can do: .. code-block:: python signal.signal(signal.SIGINT, signal.SIG_IGN) # SIG_IGN = "ignore me" or pass a specified handler, as in the code here. """ # noqa signal.signal(signal.SIGINT, ctrl_c_trapper) signal.signal(signal.SIGTERM, sigterm_trapper) if platform.system() == 'Windows': # SIGBREAK isn't in the Linux signal module # noinspection PyUnresolvedReferences signal.signal(signal.SIGBREAK, ctrl_break_trapper)
python
def trap_ctrl_c_ctrl_break() -> None: """ Prevent ``CTRL-C``, ``CTRL-BREAK``, and similar signals from doing anything. See - https://docs.python.org/3/library/signal.html#signal.SIG_IGN - https://msdn.microsoft.com/en-us/library/xdkz3x12.aspx - https://msdn.microsoft.com/en-us/library/windows/desktop/ms682541(v=vs.85).aspx Under Windows, the only options are: =========== ======================= ===================================== Signal Meaning Comment =========== ======================= ===================================== SIGABRT abnormal termination SIGFPE floating-point error SIGILL illegal instruction SIGINT CTRL+C signal -- trapped here SIGSEGV illegal storage access SIGTERM termination request -- trapped here SIGBREAK CTRL+BREAK -- trapped here under Windows =========== ======================= ===================================== In Linux, you also find: =========== ============================= Signal Meaning =========== ============================= SIGBUS bus error / unaligned access =========== ============================= To ignore, can do: .. code-block:: python signal.signal(signal.SIGINT, signal.SIG_IGN) # SIG_IGN = "ignore me" or pass a specified handler, as in the code here. """ # noqa signal.signal(signal.SIGINT, ctrl_c_trapper) signal.signal(signal.SIGTERM, sigterm_trapper) if platform.system() == 'Windows': # SIGBREAK isn't in the Linux signal module # noinspection PyUnresolvedReferences signal.signal(signal.SIGBREAK, ctrl_break_trapper)
[ "def", "trap_ctrl_c_ctrl_break", "(", ")", "->", "None", ":", "# noqa", "signal", ".", "signal", "(", "signal", ".", "SIGINT", ",", "ctrl_c_trapper", ")", "signal", ".", "signal", "(", "signal", ".", "SIGTERM", ",", "sigterm_trapper", ")", "if", "platform", ".", "system", "(", ")", "==", "'Windows'", ":", "# SIGBREAK isn't in the Linux signal module", "# noinspection PyUnresolvedReferences", "signal", ".", "signal", "(", "signal", ".", "SIGBREAK", ",", "ctrl_break_trapper", ")" ]
Prevent ``CTRL-C``, ``CTRL-BREAK``, and similar signals from doing anything. See - https://docs.python.org/3/library/signal.html#signal.SIG_IGN - https://msdn.microsoft.com/en-us/library/xdkz3x12.aspx - https://msdn.microsoft.com/en-us/library/windows/desktop/ms682541(v=vs.85).aspx Under Windows, the only options are: =========== ======================= ===================================== Signal Meaning Comment =========== ======================= ===================================== SIGABRT abnormal termination SIGFPE floating-point error SIGILL illegal instruction SIGINT CTRL+C signal -- trapped here SIGSEGV illegal storage access SIGTERM termination request -- trapped here SIGBREAK CTRL+BREAK -- trapped here under Windows =========== ======================= ===================================== In Linux, you also find: =========== ============================= Signal Meaning =========== ============================= SIGBUS bus error / unaligned access =========== ============================= To ignore, can do: .. code-block:: python signal.signal(signal.SIGINT, signal.SIG_IGN) # SIG_IGN = "ignore me" or pass a specified handler, as in the code here.
[ "Prevent", "CTRL", "-", "C", "CTRL", "-", "BREAK", "and", "similar", "signals", "from", "doing", "anything", ".", "See", "-", "https", ":", "//", "docs", ".", "python", ".", "org", "/", "3", "/", "library", "/", "signal", ".", "html#signal", ".", "SIG_IGN", "-", "https", ":", "//", "msdn", ".", "microsoft", ".", "com", "/", "en", "-", "us", "/", "library", "/", "xdkz3x12", ".", "aspx", "-", "https", ":", "//", "msdn", ".", "microsoft", ".", "com", "/", "en", "-", "us", "/", "library", "/", "windows", "/", "desktop", "/", "ms682541", "(", "v", "=", "vs", ".", "85", ")", ".", "aspx" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/signalfunc.py#L66-L113
RudolfCardinal/pythonlib
cardinal_pythonlib/openxml/find_bad_openxml.py
is_openxml_good
def is_openxml_good(filename: str) -> bool: """ Determines whether an OpenXML file appears to be good (not corrupted). """ try: log.debug("Trying: {}", filename) with ZipFile(filename, 'r') as zip_ref: namelist = zip_ref.namelist() # type: List[str] # log.critical("\n{}", pformat(namelist)) # ----------------------------------------------------------------- # Contains key files? # ----------------------------------------------------------------- for mandatory_filename in MANDATORY_FILENAMES: if mandatory_filename not in namelist: log.debug("Bad [missing {!r}]: {}", mandatory_filename, filename) return False infolist = zip_ref.infolist() # type: List[ZipInfo] contains_docx = False contains_pptx = False contains_xlsx = False for info in infolist: # ------------------------------------------------------------- # Sensible date check? # ... NO: lots of perfectly good files have this date/time. # ------------------------------------------------------------- # if info.date_time == NULL_DATE_TIME: # log.debug("{!r}: {!r}", info.filename, info.date_time) # ------------------------------------------------------------- # Only one kind of contents? # ... YES, I think so. This has 100% reliability on my # stash of 34 PPTX, 223 DOCX, 85 XLSX, and labelled none as bad # from an HFC collection of 1866 such files. There are lots of # files emerging from Scalpel (plus my find_recovered_openxml # zip-fixing tool) that fail this test, though. # ------------------------------------------------------------- if (not contains_docx and DOCX_CONTENTS_REGEX.search(info.filename)): contains_docx = True if (not contains_pptx and PPTX_CONTENTS_REGEX.search(info.filename)): contains_pptx = True if (not contains_xlsx and XLSX_CONTENTS_REGEX.search(info.filename)): contains_xlsx = True if sum([contains_docx, contains_pptx, contains_xlsx]) > 1: log.debug("Bad [>1 of DOCX, PPTX, XLSX content]: {}", filename) return False return True except (BadZipFile, OSError) as e: # --------------------------------------------------------------------- # Duff file. Easy! # --------------------------------------------------------------------- log.debug("Bad [BadZipFile or OSError]: {!r}; error was {!r}", filename, e) return False
python
def is_openxml_good(filename: str) -> bool: """ Determines whether an OpenXML file appears to be good (not corrupted). """ try: log.debug("Trying: {}", filename) with ZipFile(filename, 'r') as zip_ref: namelist = zip_ref.namelist() # type: List[str] # log.critical("\n{}", pformat(namelist)) # ----------------------------------------------------------------- # Contains key files? # ----------------------------------------------------------------- for mandatory_filename in MANDATORY_FILENAMES: if mandatory_filename not in namelist: log.debug("Bad [missing {!r}]: {}", mandatory_filename, filename) return False infolist = zip_ref.infolist() # type: List[ZipInfo] contains_docx = False contains_pptx = False contains_xlsx = False for info in infolist: # ------------------------------------------------------------- # Sensible date check? # ... NO: lots of perfectly good files have this date/time. # ------------------------------------------------------------- # if info.date_time == NULL_DATE_TIME: # log.debug("{!r}: {!r}", info.filename, info.date_time) # ------------------------------------------------------------- # Only one kind of contents? # ... YES, I think so. This has 100% reliability on my # stash of 34 PPTX, 223 DOCX, 85 XLSX, and labelled none as bad # from an HFC collection of 1866 such files. There are lots of # files emerging from Scalpel (plus my find_recovered_openxml # zip-fixing tool) that fail this test, though. # ------------------------------------------------------------- if (not contains_docx and DOCX_CONTENTS_REGEX.search(info.filename)): contains_docx = True if (not contains_pptx and PPTX_CONTENTS_REGEX.search(info.filename)): contains_pptx = True if (not contains_xlsx and XLSX_CONTENTS_REGEX.search(info.filename)): contains_xlsx = True if sum([contains_docx, contains_pptx, contains_xlsx]) > 1: log.debug("Bad [>1 of DOCX, PPTX, XLSX content]: {}", filename) return False return True except (BadZipFile, OSError) as e: # --------------------------------------------------------------------- # Duff file. Easy! # --------------------------------------------------------------------- log.debug("Bad [BadZipFile or OSError]: {!r}; error was {!r}", filename, e) return False
[ "def", "is_openxml_good", "(", "filename", ":", "str", ")", "->", "bool", ":", "try", ":", "log", ".", "debug", "(", "\"Trying: {}\"", ",", "filename", ")", "with", "ZipFile", "(", "filename", ",", "'r'", ")", "as", "zip_ref", ":", "namelist", "=", "zip_ref", ".", "namelist", "(", ")", "# type: List[str]", "# log.critical(\"\\n{}\", pformat(namelist))", "# -----------------------------------------------------------------", "# Contains key files?", "# -----------------------------------------------------------------", "for", "mandatory_filename", "in", "MANDATORY_FILENAMES", ":", "if", "mandatory_filename", "not", "in", "namelist", ":", "log", ".", "debug", "(", "\"Bad [missing {!r}]: {}\"", ",", "mandatory_filename", ",", "filename", ")", "return", "False", "infolist", "=", "zip_ref", ".", "infolist", "(", ")", "# type: List[ZipInfo]", "contains_docx", "=", "False", "contains_pptx", "=", "False", "contains_xlsx", "=", "False", "for", "info", "in", "infolist", ":", "# -------------------------------------------------------------", "# Sensible date check?", "# ... NO: lots of perfectly good files have this date/time.", "# -------------------------------------------------------------", "# if info.date_time == NULL_DATE_TIME:", "# log.debug(\"{!r}: {!r}\", info.filename, info.date_time)", "# -------------------------------------------------------------", "# Only one kind of contents?", "# ... YES, I think so. This has 100% reliability on my", "# stash of 34 PPTX, 223 DOCX, 85 XLSX, and labelled none as bad", "# from an HFC collection of 1866 such files. There are lots of", "# files emerging from Scalpel (plus my find_recovered_openxml", "# zip-fixing tool) that fail this test, though.", "# -------------------------------------------------------------", "if", "(", "not", "contains_docx", "and", "DOCX_CONTENTS_REGEX", ".", "search", "(", "info", ".", "filename", ")", ")", ":", "contains_docx", "=", "True", "if", "(", "not", "contains_pptx", "and", "PPTX_CONTENTS_REGEX", ".", "search", "(", "info", ".", "filename", ")", ")", ":", "contains_pptx", "=", "True", "if", "(", "not", "contains_xlsx", "and", "XLSX_CONTENTS_REGEX", ".", "search", "(", "info", ".", "filename", ")", ")", ":", "contains_xlsx", "=", "True", "if", "sum", "(", "[", "contains_docx", ",", "contains_pptx", ",", "contains_xlsx", "]", ")", ">", "1", ":", "log", ".", "debug", "(", "\"Bad [>1 of DOCX, PPTX, XLSX content]: {}\"", ",", "filename", ")", "return", "False", "return", "True", "except", "(", "BadZipFile", ",", "OSError", ")", "as", "e", ":", "# ---------------------------------------------------------------------", "# Duff file. Easy!", "# ---------------------------------------------------------------------", "log", ".", "debug", "(", "\"Bad [BadZipFile or OSError]: {!r}; error was {!r}\"", ",", "filename", ",", "e", ")", "return", "False" ]
Determines whether an OpenXML file appears to be good (not corrupted).
[ "Determines", "whether", "an", "OpenXML", "file", "appears", "to", "be", "good", "(", "not", "corrupted", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/openxml/find_bad_openxml.py#L80-L139
RudolfCardinal/pythonlib
cardinal_pythonlib/openxml/find_bad_openxml.py
process_openxml_file
def process_openxml_file(filename: str, print_good: bool, delete_if_bad: bool) -> None: """ Prints the filename of, or deletes, an OpenXML file depending on whether it is corrupt or not. Args: filename: filename to check print_good: if ``True``, then prints the filename if the file appears good. delete_if_bad: if ``True``, then deletes the file if the file appears corrupt. """ print_bad = not print_good try: file_good = is_openxml_good(filename) file_bad = not file_good if (print_good and file_good) or (print_bad and file_bad): print(filename) if delete_if_bad and file_bad: log.warning("Deleting: {}", filename) os.remove(filename) except Exception as e: # Must explicitly catch and report errors, since otherwise they vanish # into the ether. log.critical("Uncaught error in subprocess: {!r}\n{}", e, traceback.format_exc()) raise
python
def process_openxml_file(filename: str, print_good: bool, delete_if_bad: bool) -> None: """ Prints the filename of, or deletes, an OpenXML file depending on whether it is corrupt or not. Args: filename: filename to check print_good: if ``True``, then prints the filename if the file appears good. delete_if_bad: if ``True``, then deletes the file if the file appears corrupt. """ print_bad = not print_good try: file_good = is_openxml_good(filename) file_bad = not file_good if (print_good and file_good) or (print_bad and file_bad): print(filename) if delete_if_bad and file_bad: log.warning("Deleting: {}", filename) os.remove(filename) except Exception as e: # Must explicitly catch and report errors, since otherwise they vanish # into the ether. log.critical("Uncaught error in subprocess: {!r}\n{}", e, traceback.format_exc()) raise
[ "def", "process_openxml_file", "(", "filename", ":", "str", ",", "print_good", ":", "bool", ",", "delete_if_bad", ":", "bool", ")", "->", "None", ":", "print_bad", "=", "not", "print_good", "try", ":", "file_good", "=", "is_openxml_good", "(", "filename", ")", "file_bad", "=", "not", "file_good", "if", "(", "print_good", "and", "file_good", ")", "or", "(", "print_bad", "and", "file_bad", ")", ":", "print", "(", "filename", ")", "if", "delete_if_bad", "and", "file_bad", ":", "log", ".", "warning", "(", "\"Deleting: {}\"", ",", "filename", ")", "os", ".", "remove", "(", "filename", ")", "except", "Exception", "as", "e", ":", "# Must explicitly catch and report errors, since otherwise they vanish", "# into the ether.", "log", ".", "critical", "(", "\"Uncaught error in subprocess: {!r}\\n{}\"", ",", "e", ",", "traceback", ".", "format_exc", "(", ")", ")", "raise" ]
Prints the filename of, or deletes, an OpenXML file depending on whether it is corrupt or not. Args: filename: filename to check print_good: if ``True``, then prints the filename if the file appears good. delete_if_bad: if ``True``, then deletes the file if the file appears corrupt.
[ "Prints", "the", "filename", "of", "or", "deletes", "an", "OpenXML", "file", "depending", "on", "whether", "it", "is", "corrupt", "or", "not", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/openxml/find_bad_openxml.py#L142-L170
RudolfCardinal/pythonlib
cardinal_pythonlib/openxml/find_bad_openxml.py
main
def main() -> None: """ Command-line handler for the ``find_bad_openxml`` tool. Use the ``--help`` option for help. """ parser = ArgumentParser( formatter_class=RawDescriptionHelpFormatter, description=""" Tool to scan rescued Microsoft Office OpenXML files (produced by the find_recovered_openxml.py tool in this kit; q.v.) and detect bad (corrupted) ones. """ ) parser.add_argument( "filename", nargs="*", help="File(s) to check. You can also specify directores if you use " "--recursive" ) parser.add_argument( "--filenames_from_stdin", "-x", action="store_true", help="Take filenames from stdin instead, one line per filename " "(useful for chained grep)." ) parser.add_argument( "--recursive", action="store_true", help="Allow search to descend recursively into any directories " "encountered." ) parser.add_argument( "--skip_files", nargs="*", default=[], help="File pattern(s) to skip. You can specify wildcards like '*.txt' " "(but you will have to enclose that pattern in quotes under " "UNIX-like operating systems). The basename of each file will be " "tested against these filenames/patterns. Consider including " "Scalpel's 'audit.txt'." ) parser.add_argument( "--good", action="store_true", help="List good files, not bad" ) parser.add_argument( "--delete_if_bad", action="store_true", help="If a file is found to be bad, delete it. DANGEROUS." ) parser.add_argument( "--run_repeatedly", type=int, help="Run the tool repeatedly with a pause of <run_repeatedly> " "seconds between runs. (For this to work well with the move/" "delete options, you should specify one or more DIRECTORIES in " "the 'filename' arguments, not files, and you will need the " "--recursive option.)" ) parser.add_argument( "--nprocesses", type=int, default=multiprocessing.cpu_count(), help="Specify the number of processes to run in parallel." ) parser.add_argument( "--verbose", action="store_true", help="Verbose output" ) args = parser.parse_args() main_only_quicksetup_rootlogger( level=logging.DEBUG if args.verbose else logging.INFO, with_process_id=True ) if bool(args.filenames_from_stdin) == bool(args.filename): raise ValueError("Specify --filenames_from_stdin or filenames on the " "command line, but not both") if args.filenames_from_stdin and args.run_repeatedly: raise ValueError("Can't use both --filenames_from_stdin and " "--run_repeatedly") # Repeated scanning loop while True: log.debug("Starting scan.") log.debug("- Scanning files/directories {!r}{}", args.filename, " recursively" if args.recursive else "") log.debug("- Skipping files matching {!r}", args.skip_files) log.debug("- Using {} simultaneous processes", args.nprocesses) log.debug("- Reporting {} filenames", "good" if args.good else "bad") if args.delete_if_bad: log.warning("- Deleting bad OpenXML files.") # Iterate through files pool = multiprocessing.Pool(processes=args.nprocesses) if args.filenames_from_stdin: generator = gen_from_stdin() else: generator = gen_filenames(starting_filenames=args.filename, recursive=args.recursive) for filename in generator: src_basename = os.path.basename(filename) if any(fnmatch.fnmatch(src_basename, pattern) for pattern in args.skip_files): log.debug("Skipping file as ordered: " + filename) continue exists, locked = exists_locked(filename) if locked or not exists: log.debug("Skipping currently inaccessible file: " + filename) continue kwargs = { 'filename': filename, 'print_good': args.good, 'delete_if_bad': args.delete_if_bad, } # log.critical("start") pool.apply_async(process_openxml_file, [], kwargs) # result = pool.apply_async(process_file, [], kwargs) # result.get() # will re-raise any child exceptions # ... but it waits for the process to complete! That's no help. # log.critical("next") # ... https://stackoverflow.com/questions/22094852/how-to-catch-exceptions-in-workers-in-multiprocessing # noqa pool.close() pool.join() log.debug("Finished scan.") if args.run_repeatedly is None: break log.info("Sleeping for {} s...", args.run_repeatedly) sleep(args.run_repeatedly)
python
def main() -> None: """ Command-line handler for the ``find_bad_openxml`` tool. Use the ``--help`` option for help. """ parser = ArgumentParser( formatter_class=RawDescriptionHelpFormatter, description=""" Tool to scan rescued Microsoft Office OpenXML files (produced by the find_recovered_openxml.py tool in this kit; q.v.) and detect bad (corrupted) ones. """ ) parser.add_argument( "filename", nargs="*", help="File(s) to check. You can also specify directores if you use " "--recursive" ) parser.add_argument( "--filenames_from_stdin", "-x", action="store_true", help="Take filenames from stdin instead, one line per filename " "(useful for chained grep)." ) parser.add_argument( "--recursive", action="store_true", help="Allow search to descend recursively into any directories " "encountered." ) parser.add_argument( "--skip_files", nargs="*", default=[], help="File pattern(s) to skip. You can specify wildcards like '*.txt' " "(but you will have to enclose that pattern in quotes under " "UNIX-like operating systems). The basename of each file will be " "tested against these filenames/patterns. Consider including " "Scalpel's 'audit.txt'." ) parser.add_argument( "--good", action="store_true", help="List good files, not bad" ) parser.add_argument( "--delete_if_bad", action="store_true", help="If a file is found to be bad, delete it. DANGEROUS." ) parser.add_argument( "--run_repeatedly", type=int, help="Run the tool repeatedly with a pause of <run_repeatedly> " "seconds between runs. (For this to work well with the move/" "delete options, you should specify one or more DIRECTORIES in " "the 'filename' arguments, not files, and you will need the " "--recursive option.)" ) parser.add_argument( "--nprocesses", type=int, default=multiprocessing.cpu_count(), help="Specify the number of processes to run in parallel." ) parser.add_argument( "--verbose", action="store_true", help="Verbose output" ) args = parser.parse_args() main_only_quicksetup_rootlogger( level=logging.DEBUG if args.verbose else logging.INFO, with_process_id=True ) if bool(args.filenames_from_stdin) == bool(args.filename): raise ValueError("Specify --filenames_from_stdin or filenames on the " "command line, but not both") if args.filenames_from_stdin and args.run_repeatedly: raise ValueError("Can't use both --filenames_from_stdin and " "--run_repeatedly") # Repeated scanning loop while True: log.debug("Starting scan.") log.debug("- Scanning files/directories {!r}{}", args.filename, " recursively" if args.recursive else "") log.debug("- Skipping files matching {!r}", args.skip_files) log.debug("- Using {} simultaneous processes", args.nprocesses) log.debug("- Reporting {} filenames", "good" if args.good else "bad") if args.delete_if_bad: log.warning("- Deleting bad OpenXML files.") # Iterate through files pool = multiprocessing.Pool(processes=args.nprocesses) if args.filenames_from_stdin: generator = gen_from_stdin() else: generator = gen_filenames(starting_filenames=args.filename, recursive=args.recursive) for filename in generator: src_basename = os.path.basename(filename) if any(fnmatch.fnmatch(src_basename, pattern) for pattern in args.skip_files): log.debug("Skipping file as ordered: " + filename) continue exists, locked = exists_locked(filename) if locked or not exists: log.debug("Skipping currently inaccessible file: " + filename) continue kwargs = { 'filename': filename, 'print_good': args.good, 'delete_if_bad': args.delete_if_bad, } # log.critical("start") pool.apply_async(process_openxml_file, [], kwargs) # result = pool.apply_async(process_file, [], kwargs) # result.get() # will re-raise any child exceptions # ... but it waits for the process to complete! That's no help. # log.critical("next") # ... https://stackoverflow.com/questions/22094852/how-to-catch-exceptions-in-workers-in-multiprocessing # noqa pool.close() pool.join() log.debug("Finished scan.") if args.run_repeatedly is None: break log.info("Sleeping for {} s...", args.run_repeatedly) sleep(args.run_repeatedly)
[ "def", "main", "(", ")", "->", "None", ":", "parser", "=", "ArgumentParser", "(", "formatter_class", "=", "RawDescriptionHelpFormatter", ",", "description", "=", "\"\"\"\nTool to scan rescued Microsoft Office OpenXML files (produced by the\nfind_recovered_openxml.py tool in this kit; q.v.) and detect bad (corrupted)\nones.\n \"\"\"", ")", "parser", ".", "add_argument", "(", "\"filename\"", ",", "nargs", "=", "\"*\"", ",", "help", "=", "\"File(s) to check. You can also specify directores if you use \"", "\"--recursive\"", ")", "parser", ".", "add_argument", "(", "\"--filenames_from_stdin\"", ",", "\"-x\"", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Take filenames from stdin instead, one line per filename \"", "\"(useful for chained grep).\"", ")", "parser", ".", "add_argument", "(", "\"--recursive\"", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Allow search to descend recursively into any directories \"", "\"encountered.\"", ")", "parser", ".", "add_argument", "(", "\"--skip_files\"", ",", "nargs", "=", "\"*\"", ",", "default", "=", "[", "]", ",", "help", "=", "\"File pattern(s) to skip. You can specify wildcards like '*.txt' \"", "\"(but you will have to enclose that pattern in quotes under \"", "\"UNIX-like operating systems). The basename of each file will be \"", "\"tested against these filenames/patterns. Consider including \"", "\"Scalpel's 'audit.txt'.\"", ")", "parser", ".", "add_argument", "(", "\"--good\"", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"List good files, not bad\"", ")", "parser", ".", "add_argument", "(", "\"--delete_if_bad\"", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"If a file is found to be bad, delete it. DANGEROUS.\"", ")", "parser", ".", "add_argument", "(", "\"--run_repeatedly\"", ",", "type", "=", "int", ",", "help", "=", "\"Run the tool repeatedly with a pause of <run_repeatedly> \"", "\"seconds between runs. (For this to work well with the move/\"", "\"delete options, you should specify one or more DIRECTORIES in \"", "\"the 'filename' arguments, not files, and you will need the \"", "\"--recursive option.)\"", ")", "parser", ".", "add_argument", "(", "\"--nprocesses\"", ",", "type", "=", "int", ",", "default", "=", "multiprocessing", ".", "cpu_count", "(", ")", ",", "help", "=", "\"Specify the number of processes to run in parallel.\"", ")", "parser", ".", "add_argument", "(", "\"--verbose\"", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Verbose output\"", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "main_only_quicksetup_rootlogger", "(", "level", "=", "logging", ".", "DEBUG", "if", "args", ".", "verbose", "else", "logging", ".", "INFO", ",", "with_process_id", "=", "True", ")", "if", "bool", "(", "args", ".", "filenames_from_stdin", ")", "==", "bool", "(", "args", ".", "filename", ")", ":", "raise", "ValueError", "(", "\"Specify --filenames_from_stdin or filenames on the \"", "\"command line, but not both\"", ")", "if", "args", ".", "filenames_from_stdin", "and", "args", ".", "run_repeatedly", ":", "raise", "ValueError", "(", "\"Can't use both --filenames_from_stdin and \"", "\"--run_repeatedly\"", ")", "# Repeated scanning loop", "while", "True", ":", "log", ".", "debug", "(", "\"Starting scan.\"", ")", "log", ".", "debug", "(", "\"- Scanning files/directories {!r}{}\"", ",", "args", ".", "filename", ",", "\" recursively\"", "if", "args", ".", "recursive", "else", "\"\"", ")", "log", ".", "debug", "(", "\"- Skipping files matching {!r}\"", ",", "args", ".", "skip_files", ")", "log", ".", "debug", "(", "\"- Using {} simultaneous processes\"", ",", "args", ".", "nprocesses", ")", "log", ".", "debug", "(", "\"- Reporting {} filenames\"", ",", "\"good\"", "if", "args", ".", "good", "else", "\"bad\"", ")", "if", "args", ".", "delete_if_bad", ":", "log", ".", "warning", "(", "\"- Deleting bad OpenXML files.\"", ")", "# Iterate through files", "pool", "=", "multiprocessing", ".", "Pool", "(", "processes", "=", "args", ".", "nprocesses", ")", "if", "args", ".", "filenames_from_stdin", ":", "generator", "=", "gen_from_stdin", "(", ")", "else", ":", "generator", "=", "gen_filenames", "(", "starting_filenames", "=", "args", ".", "filename", ",", "recursive", "=", "args", ".", "recursive", ")", "for", "filename", "in", "generator", ":", "src_basename", "=", "os", ".", "path", ".", "basename", "(", "filename", ")", "if", "any", "(", "fnmatch", ".", "fnmatch", "(", "src_basename", ",", "pattern", ")", "for", "pattern", "in", "args", ".", "skip_files", ")", ":", "log", ".", "debug", "(", "\"Skipping file as ordered: \"", "+", "filename", ")", "continue", "exists", ",", "locked", "=", "exists_locked", "(", "filename", ")", "if", "locked", "or", "not", "exists", ":", "log", ".", "debug", "(", "\"Skipping currently inaccessible file: \"", "+", "filename", ")", "continue", "kwargs", "=", "{", "'filename'", ":", "filename", ",", "'print_good'", ":", "args", ".", "good", ",", "'delete_if_bad'", ":", "args", ".", "delete_if_bad", ",", "}", "# log.critical(\"start\")", "pool", ".", "apply_async", "(", "process_openxml_file", ",", "[", "]", ",", "kwargs", ")", "# result = pool.apply_async(process_file, [], kwargs)", "# result.get() # will re-raise any child exceptions", "# ... but it waits for the process to complete! That's no help.", "# log.critical(\"next\")", "# ... https://stackoverflow.com/questions/22094852/how-to-catch-exceptions-in-workers-in-multiprocessing # noqa", "pool", ".", "close", "(", ")", "pool", ".", "join", "(", ")", "log", ".", "debug", "(", "\"Finished scan.\"", ")", "if", "args", ".", "run_repeatedly", "is", "None", ":", "break", "log", ".", "info", "(", "\"Sleeping for {} s...\"", ",", "args", ".", "run_repeatedly", ")", "sleep", "(", "args", ".", "run_repeatedly", ")" ]
Command-line handler for the ``find_bad_openxml`` tool. Use the ``--help`` option for help.
[ "Command", "-", "line", "handler", "for", "the", "find_bad_openxml", "tool", ".", "Use", "the", "--", "help", "option", "for", "help", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/openxml/find_bad_openxml.py#L173-L295
RudolfCardinal/pythonlib
cardinal_pythonlib/django/mail.py
SmtpEmailBackendTls1.open
def open(self) -> bool: """ Ensures we have a connection to the email server. Returns whether or not a new connection was required (True or False). """ if self.connection: # Nothing to do if the connection is already open. return False connection_params = {'local_hostname': DNS_NAME.get_fqdn()} if self.timeout is not None: connection_params['timeout'] = self.timeout try: self.connection = smtplib.SMTP(self.host, self.port, **connection_params) # TLS context = ssl.SSLContext(self._protocol()) if self.ssl_certfile: context.load_cert_chain(certfile=self.ssl_certfile, keyfile=self.ssl_keyfile) self.connection.ehlo() self.connection.starttls(context=context) self.connection.ehlo() if self.username and self.password: self.connection.login(self.username, self.password) log.debug("Successful SMTP connection/login") else: log.debug("Successful SMTP connection (without login)") return True except smtplib.SMTPException: log.debug("SMTP connection and/or login failed") if not self.fail_silently: raise
python
def open(self) -> bool: """ Ensures we have a connection to the email server. Returns whether or not a new connection was required (True or False). """ if self.connection: # Nothing to do if the connection is already open. return False connection_params = {'local_hostname': DNS_NAME.get_fqdn()} if self.timeout is not None: connection_params['timeout'] = self.timeout try: self.connection = smtplib.SMTP(self.host, self.port, **connection_params) # TLS context = ssl.SSLContext(self._protocol()) if self.ssl_certfile: context.load_cert_chain(certfile=self.ssl_certfile, keyfile=self.ssl_keyfile) self.connection.ehlo() self.connection.starttls(context=context) self.connection.ehlo() if self.username and self.password: self.connection.login(self.username, self.password) log.debug("Successful SMTP connection/login") else: log.debug("Successful SMTP connection (without login)") return True except smtplib.SMTPException: log.debug("SMTP connection and/or login failed") if not self.fail_silently: raise
[ "def", "open", "(", "self", ")", "->", "bool", ":", "if", "self", ".", "connection", ":", "# Nothing to do if the connection is already open.", "return", "False", "connection_params", "=", "{", "'local_hostname'", ":", "DNS_NAME", ".", "get_fqdn", "(", ")", "}", "if", "self", ".", "timeout", "is", "not", "None", ":", "connection_params", "[", "'timeout'", "]", "=", "self", ".", "timeout", "try", ":", "self", ".", "connection", "=", "smtplib", ".", "SMTP", "(", "self", ".", "host", ",", "self", ".", "port", ",", "*", "*", "connection_params", ")", "# TLS", "context", "=", "ssl", ".", "SSLContext", "(", "self", ".", "_protocol", "(", ")", ")", "if", "self", ".", "ssl_certfile", ":", "context", ".", "load_cert_chain", "(", "certfile", "=", "self", ".", "ssl_certfile", ",", "keyfile", "=", "self", ".", "ssl_keyfile", ")", "self", ".", "connection", ".", "ehlo", "(", ")", "self", ".", "connection", ".", "starttls", "(", "context", "=", "context", ")", "self", ".", "connection", ".", "ehlo", "(", ")", "if", "self", ".", "username", "and", "self", ".", "password", ":", "self", ".", "connection", ".", "login", "(", "self", ".", "username", ",", "self", ".", "password", ")", "log", ".", "debug", "(", "\"Successful SMTP connection/login\"", ")", "else", ":", "log", ".", "debug", "(", "\"Successful SMTP connection (without login)\"", ")", "return", "True", "except", "smtplib", ".", "SMTPException", ":", "log", ".", "debug", "(", "\"SMTP connection and/or login failed\"", ")", "if", "not", "self", ".", "fail_silently", ":", "raise" ]
Ensures we have a connection to the email server. Returns whether or not a new connection was required (True or False).
[ "Ensures", "we", "have", "a", "connection", "to", "the", "email", "server", ".", "Returns", "whether", "or", "not", "a", "new", "connection", "was", "required", "(", "True", "or", "False", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/mail.py#L93-L126
davenquinn/Attitude
attitude/__dustbin/statistical_distances.py
bhattacharyya_distance
def bhattacharyya_distance(pca1,pca2): """ A measure of the distance between two probability distributions """ u1 = pca1.coefficients s1 = pca1.covariance_matrix u2 = pca2.coefficients s2 = pca2.covariance_matrix sigma = (s1+s2)/2 assert all(u1 > 0) assert all(u2 > 0) assert all(s1.sum(axis=1) > 0) assert all(s2.sum(axis=1) > 0) _ = 1/8*dot((u1-u2).T, N.linalg.inv(sigma),u1-u2) _ += 1/2*N.log(N.linalg.det(sigma)/(N.linalg.det(s1)*N.linalg.det(s2))) return _
python
def bhattacharyya_distance(pca1,pca2): """ A measure of the distance between two probability distributions """ u1 = pca1.coefficients s1 = pca1.covariance_matrix u2 = pca2.coefficients s2 = pca2.covariance_matrix sigma = (s1+s2)/2 assert all(u1 > 0) assert all(u2 > 0) assert all(s1.sum(axis=1) > 0) assert all(s2.sum(axis=1) > 0) _ = 1/8*dot((u1-u2).T, N.linalg.inv(sigma),u1-u2) _ += 1/2*N.log(N.linalg.det(sigma)/(N.linalg.det(s1)*N.linalg.det(s2))) return _
[ "def", "bhattacharyya_distance", "(", "pca1", ",", "pca2", ")", ":", "u1", "=", "pca1", ".", "coefficients", "s1", "=", "pca1", ".", "covariance_matrix", "u2", "=", "pca2", ".", "coefficients", "s2", "=", "pca2", ".", "covariance_matrix", "sigma", "=", "(", "s1", "+", "s2", ")", "/", "2", "assert", "all", "(", "u1", ">", "0", ")", "assert", "all", "(", "u2", ">", "0", ")", "assert", "all", "(", "s1", ".", "sum", "(", "axis", "=", "1", ")", ">", "0", ")", "assert", "all", "(", "s2", ".", "sum", "(", "axis", "=", "1", ")", ">", "0", ")", "_", "=", "1", "/", "8", "*", "dot", "(", "(", "u1", "-", "u2", ")", ".", "T", ",", "N", ".", "linalg", ".", "inv", "(", "sigma", ")", ",", "u1", "-", "u2", ")", "_", "+=", "1", "/", "2", "*", "N", ".", "log", "(", "N", ".", "linalg", ".", "det", "(", "sigma", ")", "/", "(", "N", ".", "linalg", ".", "det", "(", "s1", ")", "*", "N", ".", "linalg", ".", "det", "(", "s2", ")", ")", ")", "return", "_" ]
A measure of the distance between two probability distributions
[ "A", "measure", "of", "the", "distance", "between", "two", "probability", "distributions" ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/__dustbin/statistical_distances.py#L13-L31
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_text.py
produce_csv_output
def produce_csv_output(filehandle: TextIO, fields: Sequence[str], values: Iterable[str]) -> None: """ Produce CSV output, without using ``csv.writer``, so the log can be used for lots of things. - ... eh? What was I talking about? - POOR; DEPRECATED. Args: filehandle: file to write to fields: field names values: values """ output_csv(filehandle, fields) for row in values: output_csv(filehandle, row)
python
def produce_csv_output(filehandle: TextIO, fields: Sequence[str], values: Iterable[str]) -> None: """ Produce CSV output, without using ``csv.writer``, so the log can be used for lots of things. - ... eh? What was I talking about? - POOR; DEPRECATED. Args: filehandle: file to write to fields: field names values: values """ output_csv(filehandle, fields) for row in values: output_csv(filehandle, row)
[ "def", "produce_csv_output", "(", "filehandle", ":", "TextIO", ",", "fields", ":", "Sequence", "[", "str", "]", ",", "values", ":", "Iterable", "[", "str", "]", ")", "->", "None", ":", "output_csv", "(", "filehandle", ",", "fields", ")", "for", "row", "in", "values", ":", "output_csv", "(", "filehandle", ",", "row", ")" ]
Produce CSV output, without using ``csv.writer``, so the log can be used for lots of things. - ... eh? What was I talking about? - POOR; DEPRECATED. Args: filehandle: file to write to fields: field names values: values
[ "Produce", "CSV", "output", "without", "using", "csv", ".", "writer", "so", "the", "log", "can", "be", "used", "for", "lots", "of", "things", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L39-L56
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_text.py
output_csv
def output_csv(filehandle: TextIO, values: Iterable[str]) -> None: """ Write a line of CSV. POOR; does not escape things properly. DEPRECATED. Args: filehandle: file to write to values: values """ line = ",".join(values) filehandle.write(line + "\n")
python
def output_csv(filehandle: TextIO, values: Iterable[str]) -> None: """ Write a line of CSV. POOR; does not escape things properly. DEPRECATED. Args: filehandle: file to write to values: values """ line = ",".join(values) filehandle.write(line + "\n")
[ "def", "output_csv", "(", "filehandle", ":", "TextIO", ",", "values", ":", "Iterable", "[", "str", "]", ")", "->", "None", ":", "line", "=", "\",\"", ".", "join", "(", "values", ")", "filehandle", ".", "write", "(", "line", "+", "\"\\n\"", ")" ]
Write a line of CSV. POOR; does not escape things properly. DEPRECATED. Args: filehandle: file to write to values: values
[ "Write", "a", "line", "of", "CSV", ".", "POOR", ";", "does", "not", "escape", "things", "properly", ".", "DEPRECATED", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L59-L68
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_text.py
get_what_follows_raw
def get_what_follows_raw(s: str, prefix: str, onlyatstart: bool = True, stripwhitespace: bool = True) -> Tuple[bool, str]: """ Find the part of ``s`` that is after ``prefix``. Args: s: string to analyse prefix: prefix to find onlyatstart: only accept the prefix if it is right at the start of ``s`` stripwhitespace: remove whitespace from the result Returns: tuple: ``(found, result)`` """ prefixstart = s.find(prefix) if ((prefixstart == 0 and onlyatstart) or (prefixstart != -1 and not onlyatstart)): # substring found resultstart = prefixstart + len(prefix) result = s[resultstart:] if stripwhitespace: result = result.strip() return True, result return False, ""
python
def get_what_follows_raw(s: str, prefix: str, onlyatstart: bool = True, stripwhitespace: bool = True) -> Tuple[bool, str]: """ Find the part of ``s`` that is after ``prefix``. Args: s: string to analyse prefix: prefix to find onlyatstart: only accept the prefix if it is right at the start of ``s`` stripwhitespace: remove whitespace from the result Returns: tuple: ``(found, result)`` """ prefixstart = s.find(prefix) if ((prefixstart == 0 and onlyatstart) or (prefixstart != -1 and not onlyatstart)): # substring found resultstart = prefixstart + len(prefix) result = s[resultstart:] if stripwhitespace: result = result.strip() return True, result return False, ""
[ "def", "get_what_follows_raw", "(", "s", ":", "str", ",", "prefix", ":", "str", ",", "onlyatstart", ":", "bool", "=", "True", ",", "stripwhitespace", ":", "bool", "=", "True", ")", "->", "Tuple", "[", "bool", ",", "str", "]", ":", "prefixstart", "=", "s", ".", "find", "(", "prefix", ")", "if", "(", "(", "prefixstart", "==", "0", "and", "onlyatstart", ")", "or", "(", "prefixstart", "!=", "-", "1", "and", "not", "onlyatstart", ")", ")", ":", "# substring found", "resultstart", "=", "prefixstart", "+", "len", "(", "prefix", ")", "result", "=", "s", "[", "resultstart", ":", "]", "if", "stripwhitespace", ":", "result", "=", "result", ".", "strip", "(", ")", "return", "True", ",", "result", "return", "False", ",", "\"\"" ]
Find the part of ``s`` that is after ``prefix``. Args: s: string to analyse prefix: prefix to find onlyatstart: only accept the prefix if it is right at the start of ``s`` stripwhitespace: remove whitespace from the result Returns: tuple: ``(found, result)``
[ "Find", "the", "part", "of", "s", "that", "is", "after", "prefix", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L71-L98
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_text.py
get_what_follows
def get_what_follows(strings: Sequence[str], prefix: str, onlyatstart: bool = True, stripwhitespace: bool = True, precedingline: str = "") -> str: """ Find a string in ``strings`` that begins with ``prefix``; return the part that's after ``prefix``. Optionally, require that the preceding string (line) is ``precedingline``. Args: strings: strings to analyse prefix: prefix to find onlyatstart: only accept the prefix if it is right at the start of ``s`` stripwhitespace: remove whitespace from the result precedingline: if truthy, require that the preceding line be as specified here Returns: the line fragment """ if not precedingline: for s in strings: (found, result) = get_what_follows_raw(s, prefix, onlyatstart, stripwhitespace) if found: return result return "" else: for i in range(1, len(strings)): # i indexes the second of a pair if strings[i-1].find(precedingline) == 0: # ... if found at the start (found, result) = get_what_follows_raw(strings[i], prefix, onlyatstart, stripwhitespace) if found: return result return ""
python
def get_what_follows(strings: Sequence[str], prefix: str, onlyatstart: bool = True, stripwhitespace: bool = True, precedingline: str = "") -> str: """ Find a string in ``strings`` that begins with ``prefix``; return the part that's after ``prefix``. Optionally, require that the preceding string (line) is ``precedingline``. Args: strings: strings to analyse prefix: prefix to find onlyatstart: only accept the prefix if it is right at the start of ``s`` stripwhitespace: remove whitespace from the result precedingline: if truthy, require that the preceding line be as specified here Returns: the line fragment """ if not precedingline: for s in strings: (found, result) = get_what_follows_raw(s, prefix, onlyatstart, stripwhitespace) if found: return result return "" else: for i in range(1, len(strings)): # i indexes the second of a pair if strings[i-1].find(precedingline) == 0: # ... if found at the start (found, result) = get_what_follows_raw(strings[i], prefix, onlyatstart, stripwhitespace) if found: return result return ""
[ "def", "get_what_follows", "(", "strings", ":", "Sequence", "[", "str", "]", ",", "prefix", ":", "str", ",", "onlyatstart", ":", "bool", "=", "True", ",", "stripwhitespace", ":", "bool", "=", "True", ",", "precedingline", ":", "str", "=", "\"\"", ")", "->", "str", ":", "if", "not", "precedingline", ":", "for", "s", "in", "strings", ":", "(", "found", ",", "result", ")", "=", "get_what_follows_raw", "(", "s", ",", "prefix", ",", "onlyatstart", ",", "stripwhitespace", ")", "if", "found", ":", "return", "result", "return", "\"\"", "else", ":", "for", "i", "in", "range", "(", "1", ",", "len", "(", "strings", ")", ")", ":", "# i indexes the second of a pair", "if", "strings", "[", "i", "-", "1", "]", ".", "find", "(", "precedingline", ")", "==", "0", ":", "# ... if found at the start", "(", "found", ",", "result", ")", "=", "get_what_follows_raw", "(", "strings", "[", "i", "]", ",", "prefix", ",", "onlyatstart", ",", "stripwhitespace", ")", "if", "found", ":", "return", "result", "return", "\"\"" ]
Find a string in ``strings`` that begins with ``prefix``; return the part that's after ``prefix``. Optionally, require that the preceding string (line) is ``precedingline``. Args: strings: strings to analyse prefix: prefix to find onlyatstart: only accept the prefix if it is right at the start of ``s`` stripwhitespace: remove whitespace from the result precedingline: if truthy, require that the preceding line be as specified here Returns: the line fragment
[ "Find", "a", "string", "in", "strings", "that", "begins", "with", "prefix", ";", "return", "the", "part", "that", "s", "after", "prefix", ".", "Optionally", "require", "that", "the", "preceding", "string", "(", "line", ")", "is", "precedingline", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L101-L140
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_text.py
get_string
def get_string(strings: Sequence[str], prefix: str, ignoreleadingcolon: bool = False, precedingline: str = "") -> Optional[str]: """ Find a string as per :func:`get_what_follows`. Args: strings: see :func:`get_what_follows` prefix: see :func:`get_what_follows` ignoreleadingcolon: if ``True``, restrict the result to what comes after its first colon (and whitespace-strip that) precedingline: see :func:`get_what_follows` Returns: the line fragment """ s = get_what_follows(strings, prefix, precedingline=precedingline) if ignoreleadingcolon: f = s.find(":") if f != -1: s = s[f+1:].strip() if len(s) == 0: return None return s
python
def get_string(strings: Sequence[str], prefix: str, ignoreleadingcolon: bool = False, precedingline: str = "") -> Optional[str]: """ Find a string as per :func:`get_what_follows`. Args: strings: see :func:`get_what_follows` prefix: see :func:`get_what_follows` ignoreleadingcolon: if ``True``, restrict the result to what comes after its first colon (and whitespace-strip that) precedingline: see :func:`get_what_follows` Returns: the line fragment """ s = get_what_follows(strings, prefix, precedingline=precedingline) if ignoreleadingcolon: f = s.find(":") if f != -1: s = s[f+1:].strip() if len(s) == 0: return None return s
[ "def", "get_string", "(", "strings", ":", "Sequence", "[", "str", "]", ",", "prefix", ":", "str", ",", "ignoreleadingcolon", ":", "bool", "=", "False", ",", "precedingline", ":", "str", "=", "\"\"", ")", "->", "Optional", "[", "str", "]", ":", "s", "=", "get_what_follows", "(", "strings", ",", "prefix", ",", "precedingline", "=", "precedingline", ")", "if", "ignoreleadingcolon", ":", "f", "=", "s", ".", "find", "(", "\":\"", ")", "if", "f", "!=", "-", "1", ":", "s", "=", "s", "[", "f", "+", "1", ":", "]", ".", "strip", "(", ")", "if", "len", "(", "s", ")", "==", "0", ":", "return", "None", "return", "s" ]
Find a string as per :func:`get_what_follows`. Args: strings: see :func:`get_what_follows` prefix: see :func:`get_what_follows` ignoreleadingcolon: if ``True``, restrict the result to what comes after its first colon (and whitespace-strip that) precedingline: see :func:`get_what_follows` Returns: the line fragment
[ "Find", "a", "string", "as", "per", ":", "func", ":", "get_what_follows", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L143-L168
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_text.py
get_string_relative
def get_string_relative(strings: Sequence[str], prefix1: str, delta: int, prefix2: str, ignoreleadingcolon: bool = False, stripwhitespace: bool = True) -> Optional[str]: """ Finds a line (string) in ``strings`` beginning with ``prefix1``. Moves ``delta`` lines (strings) further. Returns the end of the line that begins with ``prefix2``, if found. Args: strings: as above prefix1: as above delta: as above prefix2: as above ignoreleadingcolon: restrict the result to the part after its first colon? stripwhitespace: strip whitespace from the start/end of the result? Returns: the line fragment """ for firstline in range(0, len(strings)): if strings[firstline].find(prefix1) == 0: # if found... secondline = firstline + delta if secondline < 0 or secondline >= len(strings): continue if strings[secondline].find(prefix2) == 0: s = strings[secondline][len(prefix2):] if stripwhitespace: s = s.strip() if ignoreleadingcolon: f = s.find(":") if f != -1: s = s[f+1:].strip() if stripwhitespace: s = s.strip() if len(s) == 0: return None return s return None
python
def get_string_relative(strings: Sequence[str], prefix1: str, delta: int, prefix2: str, ignoreleadingcolon: bool = False, stripwhitespace: bool = True) -> Optional[str]: """ Finds a line (string) in ``strings`` beginning with ``prefix1``. Moves ``delta`` lines (strings) further. Returns the end of the line that begins with ``prefix2``, if found. Args: strings: as above prefix1: as above delta: as above prefix2: as above ignoreleadingcolon: restrict the result to the part after its first colon? stripwhitespace: strip whitespace from the start/end of the result? Returns: the line fragment """ for firstline in range(0, len(strings)): if strings[firstline].find(prefix1) == 0: # if found... secondline = firstline + delta if secondline < 0 or secondline >= len(strings): continue if strings[secondline].find(prefix2) == 0: s = strings[secondline][len(prefix2):] if stripwhitespace: s = s.strip() if ignoreleadingcolon: f = s.find(":") if f != -1: s = s[f+1:].strip() if stripwhitespace: s = s.strip() if len(s) == 0: return None return s return None
[ "def", "get_string_relative", "(", "strings", ":", "Sequence", "[", "str", "]", ",", "prefix1", ":", "str", ",", "delta", ":", "int", ",", "prefix2", ":", "str", ",", "ignoreleadingcolon", ":", "bool", "=", "False", ",", "stripwhitespace", ":", "bool", "=", "True", ")", "->", "Optional", "[", "str", "]", ":", "for", "firstline", "in", "range", "(", "0", ",", "len", "(", "strings", ")", ")", ":", "if", "strings", "[", "firstline", "]", ".", "find", "(", "prefix1", ")", "==", "0", ":", "# if found...", "secondline", "=", "firstline", "+", "delta", "if", "secondline", "<", "0", "or", "secondline", ">=", "len", "(", "strings", ")", ":", "continue", "if", "strings", "[", "secondline", "]", ".", "find", "(", "prefix2", ")", "==", "0", ":", "s", "=", "strings", "[", "secondline", "]", "[", "len", "(", "prefix2", ")", ":", "]", "if", "stripwhitespace", ":", "s", "=", "s", ".", "strip", "(", ")", "if", "ignoreleadingcolon", ":", "f", "=", "s", ".", "find", "(", "\":\"", ")", "if", "f", "!=", "-", "1", ":", "s", "=", "s", "[", "f", "+", "1", ":", "]", ".", "strip", "(", ")", "if", "stripwhitespace", ":", "s", "=", "s", ".", "strip", "(", ")", "if", "len", "(", "s", ")", "==", "0", ":", "return", "None", "return", "s", "return", "None" ]
Finds a line (string) in ``strings`` beginning with ``prefix1``. Moves ``delta`` lines (strings) further. Returns the end of the line that begins with ``prefix2``, if found. Args: strings: as above prefix1: as above delta: as above prefix2: as above ignoreleadingcolon: restrict the result to the part after its first colon? stripwhitespace: strip whitespace from the start/end of the result? Returns: the line fragment
[ "Finds", "a", "line", "(", "string", ")", "in", "strings", "beginning", "with", "prefix1", ".", "Moves", "delta", "lines", "(", "strings", ")", "further", ".", "Returns", "the", "end", "of", "the", "line", "that", "begins", "with", "prefix2", "if", "found", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L171-L212
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_text.py
get_int
def get_int(strings: Sequence[str], prefix: str, ignoreleadingcolon: bool = False, precedingline: str = "") -> Optional[int]: """ Fetches an integer parameter via :func:`get_string`. """ return get_int_raw(get_string(strings, prefix, ignoreleadingcolon=ignoreleadingcolon, precedingline=precedingline))
python
def get_int(strings: Sequence[str], prefix: str, ignoreleadingcolon: bool = False, precedingline: str = "") -> Optional[int]: """ Fetches an integer parameter via :func:`get_string`. """ return get_int_raw(get_string(strings, prefix, ignoreleadingcolon=ignoreleadingcolon, precedingline=precedingline))
[ "def", "get_int", "(", "strings", ":", "Sequence", "[", "str", "]", ",", "prefix", ":", "str", ",", "ignoreleadingcolon", ":", "bool", "=", "False", ",", "precedingline", ":", "str", "=", "\"\"", ")", "->", "Optional", "[", "int", "]", ":", "return", "get_int_raw", "(", "get_string", "(", "strings", ",", "prefix", ",", "ignoreleadingcolon", "=", "ignoreleadingcolon", ",", "precedingline", "=", "precedingline", ")", ")" ]
Fetches an integer parameter via :func:`get_string`.
[ "Fetches", "an", "integer", "parameter", "via", ":", "func", ":", "get_string", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L215-L224
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_text.py
get_float
def get_float(strings: Sequence[str], prefix: str, ignoreleadingcolon: bool = False, precedingline: str = "") -> Optional[float]: """ Fetches a float parameter via :func:`get_string`. """ return get_float_raw(get_string(strings, prefix, ignoreleadingcolon=ignoreleadingcolon, precedingline=precedingline))
python
def get_float(strings: Sequence[str], prefix: str, ignoreleadingcolon: bool = False, precedingline: str = "") -> Optional[float]: """ Fetches a float parameter via :func:`get_string`. """ return get_float_raw(get_string(strings, prefix, ignoreleadingcolon=ignoreleadingcolon, precedingline=precedingline))
[ "def", "get_float", "(", "strings", ":", "Sequence", "[", "str", "]", ",", "prefix", ":", "str", ",", "ignoreleadingcolon", ":", "bool", "=", "False", ",", "precedingline", ":", "str", "=", "\"\"", ")", "->", "Optional", "[", "float", "]", ":", "return", "get_float_raw", "(", "get_string", "(", "strings", ",", "prefix", ",", "ignoreleadingcolon", "=", "ignoreleadingcolon", ",", "precedingline", "=", "precedingline", ")", ")" ]
Fetches a float parameter via :func:`get_string`.
[ "Fetches", "a", "float", "parameter", "via", ":", "func", ":", "get_string", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L227-L236
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_text.py
get_bool_raw
def get_bool_raw(s: str) -> Optional[bool]: """ Maps ``"Y"``, ``"y"`` to ``True`` and ``"N"``, ``"n"`` to ``False``. """ if s == "Y" or s == "y": return True elif s == "N" or s == "n": return False return None
python
def get_bool_raw(s: str) -> Optional[bool]: """ Maps ``"Y"``, ``"y"`` to ``True`` and ``"N"``, ``"n"`` to ``False``. """ if s == "Y" or s == "y": return True elif s == "N" or s == "n": return False return None
[ "def", "get_bool_raw", "(", "s", ":", "str", ")", "->", "Optional", "[", "bool", "]", ":", "if", "s", "==", "\"Y\"", "or", "s", "==", "\"y\"", ":", "return", "True", "elif", "s", "==", "\"N\"", "or", "s", "==", "\"n\"", ":", "return", "False", "return", "None" ]
Maps ``"Y"``, ``"y"`` to ``True`` and ``"N"``, ``"n"`` to ``False``.
[ "Maps", "Y", "y", "to", "True", "and", "N", "n", "to", "False", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L258-L266
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_text.py
get_bool
def get_bool(strings: Sequence[str], prefix: str, ignoreleadingcolon: bool = False, precedingline: str = "") -> Optional[bool]: """ Fetches a boolean parameter via :func:`get_string`. """ return get_bool_raw(get_string(strings, prefix, ignoreleadingcolon=ignoreleadingcolon, precedingline=precedingline))
python
def get_bool(strings: Sequence[str], prefix: str, ignoreleadingcolon: bool = False, precedingline: str = "") -> Optional[bool]: """ Fetches a boolean parameter via :func:`get_string`. """ return get_bool_raw(get_string(strings, prefix, ignoreleadingcolon=ignoreleadingcolon, precedingline=precedingline))
[ "def", "get_bool", "(", "strings", ":", "Sequence", "[", "str", "]", ",", "prefix", ":", "str", ",", "ignoreleadingcolon", ":", "bool", "=", "False", ",", "precedingline", ":", "str", "=", "\"\"", ")", "->", "Optional", "[", "bool", "]", ":", "return", "get_bool_raw", "(", "get_string", "(", "strings", ",", "prefix", ",", "ignoreleadingcolon", "=", "ignoreleadingcolon", ",", "precedingline", "=", "precedingline", ")", ")" ]
Fetches a boolean parameter via :func:`get_string`.
[ "Fetches", "a", "boolean", "parameter", "via", ":", "func", ":", "get_string", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L288-L297
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_text.py
get_bool_relative
def get_bool_relative(strings: Sequence[str], prefix1: str, delta: int, prefix2: str, ignoreleadingcolon: bool = False) -> Optional[bool]: """ Fetches a boolean parameter via :func:`get_string_relative`. """ return get_bool_raw(get_string_relative( strings, prefix1, delta, prefix2, ignoreleadingcolon=ignoreleadingcolon))
python
def get_bool_relative(strings: Sequence[str], prefix1: str, delta: int, prefix2: str, ignoreleadingcolon: bool = False) -> Optional[bool]: """ Fetches a boolean parameter via :func:`get_string_relative`. """ return get_bool_raw(get_string_relative( strings, prefix1, delta, prefix2, ignoreleadingcolon=ignoreleadingcolon))
[ "def", "get_bool_relative", "(", "strings", ":", "Sequence", "[", "str", "]", ",", "prefix1", ":", "str", ",", "delta", ":", "int", ",", "prefix2", ":", "str", ",", "ignoreleadingcolon", ":", "bool", "=", "False", ")", "->", "Optional", "[", "bool", "]", ":", "return", "get_bool_raw", "(", "get_string_relative", "(", "strings", ",", "prefix1", ",", "delta", ",", "prefix2", ",", "ignoreleadingcolon", "=", "ignoreleadingcolon", ")", ")" ]
Fetches a boolean parameter via :func:`get_string_relative`.
[ "Fetches", "a", "boolean", "parameter", "via", ":", "func", ":", "get_string_relative", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L300-L310
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_text.py
get_float_relative
def get_float_relative(strings: Sequence[str], prefix1: str, delta: int, prefix2: str, ignoreleadingcolon: bool = False) -> Optional[float]: """ Fetches a float parameter via :func:`get_string_relative`. """ return get_float_raw(get_string_relative( strings, prefix1, delta, prefix2, ignoreleadingcolon=ignoreleadingcolon))
python
def get_float_relative(strings: Sequence[str], prefix1: str, delta: int, prefix2: str, ignoreleadingcolon: bool = False) -> Optional[float]: """ Fetches a float parameter via :func:`get_string_relative`. """ return get_float_raw(get_string_relative( strings, prefix1, delta, prefix2, ignoreleadingcolon=ignoreleadingcolon))
[ "def", "get_float_relative", "(", "strings", ":", "Sequence", "[", "str", "]", ",", "prefix1", ":", "str", ",", "delta", ":", "int", ",", "prefix2", ":", "str", ",", "ignoreleadingcolon", ":", "bool", "=", "False", ")", "->", "Optional", "[", "float", "]", ":", "return", "get_float_raw", "(", "get_string_relative", "(", "strings", ",", "prefix1", ",", "delta", ",", "prefix2", ",", "ignoreleadingcolon", "=", "ignoreleadingcolon", ")", ")" ]
Fetches a float parameter via :func:`get_string_relative`.
[ "Fetches", "a", "float", "parameter", "via", ":", "func", ":", "get_string_relative", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L313-L323
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_text.py
get_int_relative
def get_int_relative(strings: Sequence[str], prefix1: str, delta: int, prefix2: str, ignoreleadingcolon: bool = False) -> Optional[int]: """ Fetches an int parameter via :func:`get_string_relative`. """ return get_int_raw(get_string_relative( strings, prefix1, delta, prefix2, ignoreleadingcolon=ignoreleadingcolon))
python
def get_int_relative(strings: Sequence[str], prefix1: str, delta: int, prefix2: str, ignoreleadingcolon: bool = False) -> Optional[int]: """ Fetches an int parameter via :func:`get_string_relative`. """ return get_int_raw(get_string_relative( strings, prefix1, delta, prefix2, ignoreleadingcolon=ignoreleadingcolon))
[ "def", "get_int_relative", "(", "strings", ":", "Sequence", "[", "str", "]", ",", "prefix1", ":", "str", ",", "delta", ":", "int", ",", "prefix2", ":", "str", ",", "ignoreleadingcolon", ":", "bool", "=", "False", ")", "->", "Optional", "[", "int", "]", ":", "return", "get_int_raw", "(", "get_string_relative", "(", "strings", ",", "prefix1", ",", "delta", ",", "prefix2", ",", "ignoreleadingcolon", "=", "ignoreleadingcolon", ")", ")" ]
Fetches an int parameter via :func:`get_string_relative`.
[ "Fetches", "an", "int", "parameter", "via", ":", "func", ":", "get_string_relative", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L326-L336
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_text.py
get_datetime
def get_datetime(strings: Sequence[str], prefix: str, datetime_format_string: str, ignoreleadingcolon: bool = False, precedingline: str = "") -> Optional[datetime.datetime]: """ Fetches a ``datetime.datetime`` parameter via :func:`get_string`. """ x = get_string(strings, prefix, ignoreleadingcolon=ignoreleadingcolon, precedingline=precedingline) if len(x) == 0: return None # For the format strings you can pass to datetime.datetime.strptime, see # http://docs.python.org/library/datetime.html # A typical one is "%d-%b-%Y (%H:%M:%S)" d = datetime.datetime.strptime(x, datetime_format_string) return d
python
def get_datetime(strings: Sequence[str], prefix: str, datetime_format_string: str, ignoreleadingcolon: bool = False, precedingline: str = "") -> Optional[datetime.datetime]: """ Fetches a ``datetime.datetime`` parameter via :func:`get_string`. """ x = get_string(strings, prefix, ignoreleadingcolon=ignoreleadingcolon, precedingline=precedingline) if len(x) == 0: return None # For the format strings you can pass to datetime.datetime.strptime, see # http://docs.python.org/library/datetime.html # A typical one is "%d-%b-%Y (%H:%M:%S)" d = datetime.datetime.strptime(x, datetime_format_string) return d
[ "def", "get_datetime", "(", "strings", ":", "Sequence", "[", "str", "]", ",", "prefix", ":", "str", ",", "datetime_format_string", ":", "str", ",", "ignoreleadingcolon", ":", "bool", "=", "False", ",", "precedingline", ":", "str", "=", "\"\"", ")", "->", "Optional", "[", "datetime", ".", "datetime", "]", ":", "x", "=", "get_string", "(", "strings", ",", "prefix", ",", "ignoreleadingcolon", "=", "ignoreleadingcolon", ",", "precedingline", "=", "precedingline", ")", "if", "len", "(", "x", ")", "==", "0", ":", "return", "None", "# For the format strings you can pass to datetime.datetime.strptime, see", "# http://docs.python.org/library/datetime.html", "# A typical one is \"%d-%b-%Y (%H:%M:%S)\"", "d", "=", "datetime", ".", "datetime", ".", "strptime", "(", "x", ",", "datetime_format_string", ")", "return", "d" ]
Fetches a ``datetime.datetime`` parameter via :func:`get_string`.
[ "Fetches", "a", "datetime", ".", "datetime", "parameter", "via", ":", "func", ":", "get_string", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L339-L355
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_text.py
find_line_beginning
def find_line_beginning(strings: Sequence[str], linestart: Optional[str]) -> int: """ Finds the index of the line in ``strings`` that begins with ``linestart``, or ``-1`` if none is found. If ``linestart is None``, match an empty line. """ if linestart is None: # match an empty line for i in range(len(strings)): if is_empty_string(strings[i]): return i return -1 for i in range(len(strings)): if strings[i].find(linestart) == 0: return i return -1
python
def find_line_beginning(strings: Sequence[str], linestart: Optional[str]) -> int: """ Finds the index of the line in ``strings`` that begins with ``linestart``, or ``-1`` if none is found. If ``linestart is None``, match an empty line. """ if linestart is None: # match an empty line for i in range(len(strings)): if is_empty_string(strings[i]): return i return -1 for i in range(len(strings)): if strings[i].find(linestart) == 0: return i return -1
[ "def", "find_line_beginning", "(", "strings", ":", "Sequence", "[", "str", "]", ",", "linestart", ":", "Optional", "[", "str", "]", ")", "->", "int", ":", "if", "linestart", "is", "None", ":", "# match an empty line", "for", "i", "in", "range", "(", "len", "(", "strings", ")", ")", ":", "if", "is_empty_string", "(", "strings", "[", "i", "]", ")", ":", "return", "i", "return", "-", "1", "for", "i", "in", "range", "(", "len", "(", "strings", ")", ")", ":", "if", "strings", "[", "i", "]", ".", "find", "(", "linestart", ")", "==", "0", ":", "return", "i", "return", "-", "1" ]
Finds the index of the line in ``strings`` that begins with ``linestart``, or ``-1`` if none is found. If ``linestart is None``, match an empty line.
[ "Finds", "the", "index", "of", "the", "line", "in", "strings", "that", "begins", "with", "linestart", "or", "-", "1", "if", "none", "is", "found", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L358-L374
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_text.py
find_line_containing
def find_line_containing(strings: Sequence[str], contents: str) -> int: """ Finds the index of the line in ``strings`` that contains ``contents``, or ``-1`` if none is found. """ for i in range(len(strings)): if strings[i].find(contents) != -1: return i return -1
python
def find_line_containing(strings: Sequence[str], contents: str) -> int: """ Finds the index of the line in ``strings`` that contains ``contents``, or ``-1`` if none is found. """ for i in range(len(strings)): if strings[i].find(contents) != -1: return i return -1
[ "def", "find_line_containing", "(", "strings", ":", "Sequence", "[", "str", "]", ",", "contents", ":", "str", ")", "->", "int", ":", "for", "i", "in", "range", "(", "len", "(", "strings", ")", ")", ":", "if", "strings", "[", "i", "]", ".", "find", "(", "contents", ")", "!=", "-", "1", ":", "return", "i", "return", "-", "1" ]
Finds the index of the line in ``strings`` that contains ``contents``, or ``-1`` if none is found.
[ "Finds", "the", "index", "of", "the", "line", "in", "strings", "that", "contains", "contents", "or", "-", "1", "if", "none", "is", "found", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L377-L385
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_text.py
get_lines_from_to
def get_lines_from_to(strings: List[str], firstlinestart: str, list_of_lastline_starts: Iterable[Optional[str]]) \ -> List[str]: """ Takes a list of ``strings``. Returns a list of strings FROM ``firstlinestart`` (inclusive) TO the first of ``list_of_lastline_starts`` (exclusive). To search to the end of the list, use ``list_of_lastline_starts = []``. To search to a blank line, use ``list_of_lastline_starts = [None]`` """ start_index = find_line_beginning(strings, firstlinestart) # log.debug("start_index: {}", start_index) if start_index == -1: return [] end_offset = None # itself a valid slice index for lls in list_of_lastline_starts: possible_end_offset = find_line_beginning(strings[start_index:], lls) # log.debug("lls {!r} -> possible_end_offset {}", # lls, possible_end_offset) if possible_end_offset != -1: # found one if end_offset is None or possible_end_offset < end_offset: end_offset = possible_end_offset end_index = None if end_offset is None else (start_index + end_offset) # log.debug("end_index: {}", end_index) return strings[start_index:end_index]
python
def get_lines_from_to(strings: List[str], firstlinestart: str, list_of_lastline_starts: Iterable[Optional[str]]) \ -> List[str]: """ Takes a list of ``strings``. Returns a list of strings FROM ``firstlinestart`` (inclusive) TO the first of ``list_of_lastline_starts`` (exclusive). To search to the end of the list, use ``list_of_lastline_starts = []``. To search to a blank line, use ``list_of_lastline_starts = [None]`` """ start_index = find_line_beginning(strings, firstlinestart) # log.debug("start_index: {}", start_index) if start_index == -1: return [] end_offset = None # itself a valid slice index for lls in list_of_lastline_starts: possible_end_offset = find_line_beginning(strings[start_index:], lls) # log.debug("lls {!r} -> possible_end_offset {}", # lls, possible_end_offset) if possible_end_offset != -1: # found one if end_offset is None or possible_end_offset < end_offset: end_offset = possible_end_offset end_index = None if end_offset is None else (start_index + end_offset) # log.debug("end_index: {}", end_index) return strings[start_index:end_index]
[ "def", "get_lines_from_to", "(", "strings", ":", "List", "[", "str", "]", ",", "firstlinestart", ":", "str", ",", "list_of_lastline_starts", ":", "Iterable", "[", "Optional", "[", "str", "]", "]", ")", "->", "List", "[", "str", "]", ":", "start_index", "=", "find_line_beginning", "(", "strings", ",", "firstlinestart", ")", "# log.debug(\"start_index: {}\", start_index)", "if", "start_index", "==", "-", "1", ":", "return", "[", "]", "end_offset", "=", "None", "# itself a valid slice index", "for", "lls", "in", "list_of_lastline_starts", ":", "possible_end_offset", "=", "find_line_beginning", "(", "strings", "[", "start_index", ":", "]", ",", "lls", ")", "# log.debug(\"lls {!r} -> possible_end_offset {}\",", "# lls, possible_end_offset)", "if", "possible_end_offset", "!=", "-", "1", ":", "# found one", "if", "end_offset", "is", "None", "or", "possible_end_offset", "<", "end_offset", ":", "end_offset", "=", "possible_end_offset", "end_index", "=", "None", "if", "end_offset", "is", "None", "else", "(", "start_index", "+", "end_offset", ")", "# log.debug(\"end_index: {}\", end_index)", "return", "strings", "[", "start_index", ":", "end_index", "]" ]
Takes a list of ``strings``. Returns a list of strings FROM ``firstlinestart`` (inclusive) TO the first of ``list_of_lastline_starts`` (exclusive). To search to the end of the list, use ``list_of_lastline_starts = []``. To search to a blank line, use ``list_of_lastline_starts = [None]``
[ "Takes", "a", "list", "of", "strings", ".", "Returns", "a", "list", "of", "strings", "FROM", "firstlinestart", "(", "inclusive", ")", "TO", "the", "first", "of", "list_of_lastline_starts", "(", "exclusive", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L388-L415
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_text.py
csv_to_list_of_fields
def csv_to_list_of_fields(lines: List[str], csvheader: str, quotechar: str = '"') -> List[str]: """ Extracts data from a list of CSV lines (starting with a defined header line) embedded in a longer text block but ending with a blank line. Used for processing e.g. MonkeyCantab rescue text output. Args: lines: CSV lines csvheader: CSV header line quotechar: ``quotechar`` parameter passed to :func:`csv.reader` Returns: list (by row) of lists (by value); see example Test code: .. code-block:: python import logging from cardinal_pythonlib.rnc_text import * logging.basicConfig(level=logging.DEBUG) myheader = "field1,field2,field3" mycsvlines = [ "irrelevant line", myheader, # header: START "row1value1,row1value2,row1value3", "row2value1,row2value2,row2value3", "", # terminating blank line: END "other irrelevant line", ] csv_to_list_of_fields(mycsvlines, myheader) # [['row1value1', 'row1value2', 'row1value3'], ['row2value1', 'row2value2', 'row2value3']] """ # noqa data = [] # type: List[str] # an empty line marks the end of the block csvlines = get_lines_from_to(lines, csvheader, [None])[1:] # ... remove the CSV header reader = csv.reader(csvlines, quotechar=quotechar) for fields in reader: data.append(fields) return data
python
def csv_to_list_of_fields(lines: List[str], csvheader: str, quotechar: str = '"') -> List[str]: """ Extracts data from a list of CSV lines (starting with a defined header line) embedded in a longer text block but ending with a blank line. Used for processing e.g. MonkeyCantab rescue text output. Args: lines: CSV lines csvheader: CSV header line quotechar: ``quotechar`` parameter passed to :func:`csv.reader` Returns: list (by row) of lists (by value); see example Test code: .. code-block:: python import logging from cardinal_pythonlib.rnc_text import * logging.basicConfig(level=logging.DEBUG) myheader = "field1,field2,field3" mycsvlines = [ "irrelevant line", myheader, # header: START "row1value1,row1value2,row1value3", "row2value1,row2value2,row2value3", "", # terminating blank line: END "other irrelevant line", ] csv_to_list_of_fields(mycsvlines, myheader) # [['row1value1', 'row1value2', 'row1value3'], ['row2value1', 'row2value2', 'row2value3']] """ # noqa data = [] # type: List[str] # an empty line marks the end of the block csvlines = get_lines_from_to(lines, csvheader, [None])[1:] # ... remove the CSV header reader = csv.reader(csvlines, quotechar=quotechar) for fields in reader: data.append(fields) return data
[ "def", "csv_to_list_of_fields", "(", "lines", ":", "List", "[", "str", "]", ",", "csvheader", ":", "str", ",", "quotechar", ":", "str", "=", "'\"'", ")", "->", "List", "[", "str", "]", ":", "# noqa", "data", "=", "[", "]", "# type: List[str]", "# an empty line marks the end of the block", "csvlines", "=", "get_lines_from_to", "(", "lines", ",", "csvheader", ",", "[", "None", "]", ")", "[", "1", ":", "]", "# ... remove the CSV header", "reader", "=", "csv", ".", "reader", "(", "csvlines", ",", "quotechar", "=", "quotechar", ")", "for", "fields", "in", "reader", ":", "data", ".", "append", "(", "fields", ")", "return", "data" ]
Extracts data from a list of CSV lines (starting with a defined header line) embedded in a longer text block but ending with a blank line. Used for processing e.g. MonkeyCantab rescue text output. Args: lines: CSV lines csvheader: CSV header line quotechar: ``quotechar`` parameter passed to :func:`csv.reader` Returns: list (by row) of lists (by value); see example Test code: .. code-block:: python import logging from cardinal_pythonlib.rnc_text import * logging.basicConfig(level=logging.DEBUG) myheader = "field1,field2,field3" mycsvlines = [ "irrelevant line", myheader, # header: START "row1value1,row1value2,row1value3", "row2value1,row2value2,row2value3", "", # terminating blank line: END "other irrelevant line", ] csv_to_list_of_fields(mycsvlines, myheader) # [['row1value1', 'row1value2', 'row1value3'], ['row2value1', 'row2value2', 'row2value3']]
[ "Extracts", "data", "from", "a", "list", "of", "CSV", "lines", "(", "starting", "with", "a", "defined", "header", "line", ")", "embedded", "in", "a", "longer", "text", "block", "but", "ending", "with", "a", "blank", "line", ".", "Used", "for", "processing", "e", ".", "g", ".", "MonkeyCantab", "rescue", "text", "output", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L425-L470
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_text.py
csv_to_list_of_dicts
def csv_to_list_of_dicts(lines: List[str], csvheader: str, quotechar: str = '"') -> List[Dict[str, str]]: """ Extracts data from a list of CSV lines (starting with a defined header line) embedded in a longer text block but ending with a blank line. Args: lines: CSV lines csvheader: CSV header line quotechar: ``quotechar`` parameter passed to :func:`csv.reader` Returns: list of dictionaries mapping fieldnames (from the header) to values """ data = [] # type: List[Dict[str, str]] # an empty line marks the end of the block csvlines = get_lines_from_to(lines, csvheader, [None])[1:] # ... remove the CSV header headerfields = csvheader.split(",") reader = csv.reader(csvlines, quotechar=quotechar) for fields in reader: row = {} # type: Dict[str, str] for f in range(len(headerfields)): row[headerfields[f]] = fields[f] data.append(row) return data
python
def csv_to_list_of_dicts(lines: List[str], csvheader: str, quotechar: str = '"') -> List[Dict[str, str]]: """ Extracts data from a list of CSV lines (starting with a defined header line) embedded in a longer text block but ending with a blank line. Args: lines: CSV lines csvheader: CSV header line quotechar: ``quotechar`` parameter passed to :func:`csv.reader` Returns: list of dictionaries mapping fieldnames (from the header) to values """ data = [] # type: List[Dict[str, str]] # an empty line marks the end of the block csvlines = get_lines_from_to(lines, csvheader, [None])[1:] # ... remove the CSV header headerfields = csvheader.split(",") reader = csv.reader(csvlines, quotechar=quotechar) for fields in reader: row = {} # type: Dict[str, str] for f in range(len(headerfields)): row[headerfields[f]] = fields[f] data.append(row) return data
[ "def", "csv_to_list_of_dicts", "(", "lines", ":", "List", "[", "str", "]", ",", "csvheader", ":", "str", ",", "quotechar", ":", "str", "=", "'\"'", ")", "->", "List", "[", "Dict", "[", "str", ",", "str", "]", "]", ":", "data", "=", "[", "]", "# type: List[Dict[str, str]]", "# an empty line marks the end of the block", "csvlines", "=", "get_lines_from_to", "(", "lines", ",", "csvheader", ",", "[", "None", "]", ")", "[", "1", ":", "]", "# ... remove the CSV header", "headerfields", "=", "csvheader", ".", "split", "(", "\",\"", ")", "reader", "=", "csv", ".", "reader", "(", "csvlines", ",", "quotechar", "=", "quotechar", ")", "for", "fields", "in", "reader", ":", "row", "=", "{", "}", "# type: Dict[str, str]", "for", "f", "in", "range", "(", "len", "(", "headerfields", ")", ")", ":", "row", "[", "headerfields", "[", "f", "]", "]", "=", "fields", "[", "f", "]", "data", ".", "append", "(", "row", ")", "return", "data" ]
Extracts data from a list of CSV lines (starting with a defined header line) embedded in a longer text block but ending with a blank line. Args: lines: CSV lines csvheader: CSV header line quotechar: ``quotechar`` parameter passed to :func:`csv.reader` Returns: list of dictionaries mapping fieldnames (from the header) to values
[ "Extracts", "data", "from", "a", "list", "of", "CSV", "lines", "(", "starting", "with", "a", "defined", "header", "line", ")", "embedded", "in", "a", "longer", "text", "block", "but", "ending", "with", "a", "blank", "line", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L473-L500
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_text.py
dictlist_convert_to_string
def dictlist_convert_to_string(dict_list: Iterable[Dict], key: str) -> None: """ Process an iterable of dictionaries. For each dictionary ``d``, convert (in place) ``d[key]`` to a string form, ``str(d[key])``. If the result is a blank string, convert it to ``None``. """ for d in dict_list: d[key] = str(d[key]) if d[key] == "": d[key] = None
python
def dictlist_convert_to_string(dict_list: Iterable[Dict], key: str) -> None: """ Process an iterable of dictionaries. For each dictionary ``d``, convert (in place) ``d[key]`` to a string form, ``str(d[key])``. If the result is a blank string, convert it to ``None``. """ for d in dict_list: d[key] = str(d[key]) if d[key] == "": d[key] = None
[ "def", "dictlist_convert_to_string", "(", "dict_list", ":", "Iterable", "[", "Dict", "]", ",", "key", ":", "str", ")", "->", "None", ":", "for", "d", "in", "dict_list", ":", "d", "[", "key", "]", "=", "str", "(", "d", "[", "key", "]", ")", "if", "d", "[", "key", "]", "==", "\"\"", ":", "d", "[", "key", "]", "=", "None" ]
Process an iterable of dictionaries. For each dictionary ``d``, convert (in place) ``d[key]`` to a string form, ``str(d[key])``. If the result is a blank string, convert it to ``None``.
[ "Process", "an", "iterable", "of", "dictionaries", ".", "For", "each", "dictionary", "d", "convert", "(", "in", "place", ")", "d", "[", "key", "]", "to", "a", "string", "form", "str", "(", "d", "[", "key", "]", ")", ".", "If", "the", "result", "is", "a", "blank", "string", "convert", "it", "to", "None", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L503-L512
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_text.py
dictlist_convert_to_datetime
def dictlist_convert_to_datetime(dict_list: Iterable[Dict], key: str, datetime_format_string: str) -> None: """ Process an iterable of dictionaries. For each dictionary ``d``, convert (in place) ``d[key]`` to a ``datetime.datetime`` form, using ``datetime_format_string`` as the format parameter to :func:`datetime.datetime.strptime`. """ for d in dict_list: d[key] = datetime.datetime.strptime(d[key], datetime_format_string)
python
def dictlist_convert_to_datetime(dict_list: Iterable[Dict], key: str, datetime_format_string: str) -> None: """ Process an iterable of dictionaries. For each dictionary ``d``, convert (in place) ``d[key]`` to a ``datetime.datetime`` form, using ``datetime_format_string`` as the format parameter to :func:`datetime.datetime.strptime`. """ for d in dict_list: d[key] = datetime.datetime.strptime(d[key], datetime_format_string)
[ "def", "dictlist_convert_to_datetime", "(", "dict_list", ":", "Iterable", "[", "Dict", "]", ",", "key", ":", "str", ",", "datetime_format_string", ":", "str", ")", "->", "None", ":", "for", "d", "in", "dict_list", ":", "d", "[", "key", "]", "=", "datetime", ".", "datetime", ".", "strptime", "(", "d", "[", "key", "]", ",", "datetime_format_string", ")" ]
Process an iterable of dictionaries. For each dictionary ``d``, convert (in place) ``d[key]`` to a ``datetime.datetime`` form, using ``datetime_format_string`` as the format parameter to :func:`datetime.datetime.strptime`.
[ "Process", "an", "iterable", "of", "dictionaries", ".", "For", "each", "dictionary", "d", "convert", "(", "in", "place", ")", "d", "[", "key", "]", "to", "a", "datetime", ".", "datetime", "form", "using", "datetime_format_string", "as", "the", "format", "parameter", "to", ":", "func", ":", "datetime", ".", "datetime", ".", "strptime", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L515-L525
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_text.py
dictlist_convert_to_int
def dictlist_convert_to_int(dict_list: Iterable[Dict], key: str) -> None: """ Process an iterable of dictionaries. For each dictionary ``d``, convert (in place) ``d[key]`` to an integer. If that fails, convert it to ``None``. """ for d in dict_list: try: d[key] = int(d[key]) except ValueError: d[key] = None
python
def dictlist_convert_to_int(dict_list: Iterable[Dict], key: str) -> None: """ Process an iterable of dictionaries. For each dictionary ``d``, convert (in place) ``d[key]`` to an integer. If that fails, convert it to ``None``. """ for d in dict_list: try: d[key] = int(d[key]) except ValueError: d[key] = None
[ "def", "dictlist_convert_to_int", "(", "dict_list", ":", "Iterable", "[", "Dict", "]", ",", "key", ":", "str", ")", "->", "None", ":", "for", "d", "in", "dict_list", ":", "try", ":", "d", "[", "key", "]", "=", "int", "(", "d", "[", "key", "]", ")", "except", "ValueError", ":", "d", "[", "key", "]", "=", "None" ]
Process an iterable of dictionaries. For each dictionary ``d``, convert (in place) ``d[key]`` to an integer. If that fails, convert it to ``None``.
[ "Process", "an", "iterable", "of", "dictionaries", ".", "For", "each", "dictionary", "d", "convert", "(", "in", "place", ")", "d", "[", "key", "]", "to", "an", "integer", ".", "If", "that", "fails", "convert", "it", "to", "None", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L528-L537