code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
public_key = None u_bits = useropt.split(':') username = u_bits[0] if len(u_bits) == 1: public_key = cryptorito.key_from_keybase(username) else: fingerprint = u_bits[1] public_key = cryptorito.key_from_keybase(username, fingerprint) if cryptorito.has_gpg_key(public_...
def import_keybase(useropt)
Imports a public GPG key from Keybase
3.491956
3.316361
1.052948
if len(sys.argv) == 5 and sys.argv[1] == "encrypt_file": encrypt_file(sys.argv[2], sys.argv[3], sys.argv[4]) elif len(sys.argv) == 4 and sys.argv[1] == "decrypt_file": decrypt_file(sys.argv[2], sys.argv[3]) elif len(sys.argv) == 3 and sys.argv[1] == "encrypt": encrypt_var(sys.ar...
def do_thing()
Execute command line cryptorito actions
1.985158
1.820985
1.090156
fmt = "%(asctime)s.%(msecs)03d" if with_process_id or with_thread_id: procinfo = [] # type: List[str] if with_process_id: procinfo.append("p%(process)d") if with_thread_id: procinfo.append("t%(thread)d") fmt += " [{}]".format(".".join(procinfo)) ...
def get_monochrome_handler( extranames: List[str] = None, with_process_id: bool = False, with_thread_id: bool = False, stream: TextIO = None) -> logging.StreamHandler
Gets a monochrome log handler using a standard format. Args: extranames: additional names to append to the logger's name with_process_id: include the process ID in the logger's name? with_thread_id: include the thread ID in the logger's name? stream: ``TextIO`` stream to send log ou...
2.428051
2.431041
0.99877
fmt = "%(white)s%(asctime)s.%(msecs)03d" # this is dim white = grey if with_process_id or with_thread_id: procinfo = [] # type: List[str] if with_process_id: procinfo.append("p%(process)d") if with_thread_id: procinfo.append("t%(thread)d") fmt += " ...
def get_colour_handler(extranames: List[str] = None, with_process_id: bool = False, with_thread_id: bool = False, stream: TextIO = None) -> logging.StreamHandler
Gets a colour log handler using a standard format. Args: extranames: additional names to append to the logger's name with_process_id: include the process ID in the logger's name? with_thread_id: include the thread ID in the logger's name? stream: ``TextIO`` stream to send log output...
2.771142
2.792028
0.992519
if remove_existing: logger.handlers = [] # http://stackoverflow.com/questions/7484454 handler = get_colour_handler(extranames, with_process_id=with_process_id, with_thread_id=with_thread_id) handler.setLevel(level) logger.ad...
def configure_logger_for_colour(logger: logging.Logger, level: int = logging.INFO, remove_existing: bool = False, extranames: List[str] = None, with_process_id: bool = False, ...
Applies a preconfigured datetime/colour scheme to a logger. Should ONLY be called from the ``if __name__ == 'main'`` script; see https://docs.python.org/3.4/howto/logging.html#library-config. Args: logger: logger to modify level: log level to set remove_existing: remove existing ha...
2.854783
2.968845
0.96158
# Nasty. Only call from "if __name__ == '__main__'" clauses! rootlogger = logging.getLogger() configure_logger_for_colour(rootlogger, level, remove_existing=True, with_process_id=with_process_id, with_thread_id=with_thread_id)
def main_only_quicksetup_rootlogger(level: int = logging.DEBUG, with_process_id: bool = False, with_thread_id: bool = False) -> None
Quick function to set up the root logger for colour. Should ONLY be called from the ``if __name__ == 'main'`` script; see https://docs.python.org/3.4/howto/logging.html#library-config. Args: level: log level to set with_process_id: include the process ID in the logger's name? with_...
5.498497
4.97116
1.106079
while logger.handlers: h = logger.handlers[0] logger.removeHandler(h)
def remove_all_logger_handlers(logger: logging.Logger) -> None
Remove all handlers from a logger. Args: logger: logger to modify
4.668515
6.030948
0.774093
handler = logging.StreamHandler() formatter = logging.Formatter(fmt=fmt, datefmt=datefmt) handler.setFormatter(formatter) remove_all_logger_handlers(logger) logger.addHandler(handler) logger.propagate = False
def reset_logformat(logger: logging.Logger, fmt: str, datefmt: str = '%Y-%m-%d %H:%M:%S') -> None
Create a new formatter and apply it to the logger. :func:`logging.basicConfig` won't reset the formatter if another module has called it, so always set the formatter like this. Args: logger: logger to modify fmt: passed to the ``fmt=`` argument of :class:`logging.Formatter` datefmt...
2.50842
3.025416
0.829116
namebit = extraname + ":" if extraname else "" fmt = ("%(asctime)s.%(msecs)03d:%(levelname)s:%(name)s:" + namebit + "%(message)s") # logger.info(fmt) reset_logformat(logger, fmt=fmt) # logger.info(fmt) logger.setLevel(level)
def reset_logformat_timestamped(logger: logging.Logger, extraname: str = "", level: int = logging.INFO) -> None
Apply a simple time-stamped log format to an existing logger, and set its loglevel to either ``logging.DEBUG`` or ``logging.INFO``. Args: logger: logger to modify extraname: additional name to append to the logger's name level: log level to set
3.639722
3.870122
0.940467
handler = get_colour_handler() apply_handler_to_all_logs(handler, remove_existing=remove_existing)
def configure_all_loggers_for_colour(remove_existing: bool = True) -> None
Applies a preconfigured datetime/colour scheme to ALL logger. Should ONLY be called from the ``if __name__ == 'main'`` script; see https://docs.python.org/3.4/howto/logging.html#library-config. Generally MORE SENSIBLE just to apply a handler to the root logger. Args: remove_existing: remove e...
7.032941
7.052717
0.997196
rootlog = logging.getLogger() if remove_existing: rootlog.handlers = [] rootlog.addHandler(handler)
def apply_handler_to_root_log(handler: logging.Handler, remove_existing: bool = False) -> None
Applies a handler to all logs, optionally removing existing handlers. Should ONLY be called from the ``if __name__ == 'main'`` script; see https://docs.python.org/3.4/howto/logging.html#library-config. Generally MORE SENSIBLE just to apply a handler to the root logger. Args: handler: the hand...
3.583843
4.138291
0.86602
# noinspection PyUnresolvedReferences for name, obj in logging.Logger.manager.loggerDict.items(): if remove_existing: obj.handlers = [] # http://stackoverflow.com/questions/7484454 obj.addHandler(handler)
def apply_handler_to_all_logs(handler: logging.Handler, remove_existing: bool = False) -> None
Applies a handler to all logs, optionally removing existing handlers. Should ONLY be called from the ``if __name__ == 'main'`` script; see https://docs.python.org/3.4/howto/logging.html#library-config. Generally MORE SENSIBLE just to apply a handler to the root logger. Args: handler: the hand...
4.033914
4.293224
0.9396
fh = logging.FileHandler(filename) # default file mode is 'a' for append formatter = logging.Formatter(fmt=fmt, datefmt=datefmt) fh.setFormatter(formatter) apply_handler_to_root_log(fh)
def copy_root_log_to_file(filename: str, fmt: str = LOG_FORMAT, datefmt: str = LOG_DATEFMT) -> None
Copy all currently configured logs to the specified file. Should ONLY be called from the ``if __name__ == 'main'`` script; see https://docs.python.org/3.4/howto/logging.html#library-config.
4.269395
3.59186
1.188631
fh = logging.FileHandler(filename) # default file mode is 'a' for append formatter = logging.Formatter(fmt=fmt, datefmt=datefmt) fh.setFormatter(formatter) apply_handler_to_all_logs(fh)
def copy_all_logs_to_file(filename: str, fmt: str = LOG_FORMAT, datefmt: str = LOG_DATEFMT) -> None
Copy all currently configured logs to the specified file. Should ONLY be called from the ``if __name__ == 'main'`` script; see https://docs.python.org/3.4/howto/logging.html#library-config. Args: filename: file to send log output to fmt: passed to the ``fmt=`` argument of :class:`logging.F...
4.451371
4.292132
1.0371
if f is None: return None return { '_fmt': f._fmt, 'datefmt': f.datefmt, '_style': str(f._style), }
def get_formatter_report(f: logging.Formatter) -> Optional[Dict[str, str]]
Returns information on a log formatter, as a dictionary. For debugging.
3.278553
3.019732
1.08571
return { 'get_name()': h.get_name(), 'level': h.level, 'formatter': get_formatter_report(h.formatter), 'filters': h.filters, }
def get_handler_report(h: logging.Handler) -> Dict[str, Any]
Returns information on a log handler, as a dictionary. For debugging.
3.276373
3.11328
1.052386
if isinstance(log, logging.Logger): # suppress invalid error for Logger.manager: # noinspection PyUnresolvedReferences return { '(object)': str(log), 'level': log.level, 'disabled': log.disabled, 'propagate': log.propagate, 'pa...
def get_log_report(log: Union[logging.Logger, logging.PlaceHolder]) -> Dict[str, Any]
Returns information on a log, as a dictionary. For debugging.
3.017906
3.023731
0.998074
d = {} # noinspection PyUnresolvedReferences for name, obj in logging.Logger.manager.loggerDict.items(): d[name] = get_log_report(obj) rootlogger = logging.getLogger() d['(root logger)'] = get_log_report(rootlogger) print(json.dumps(d, sort_keys=True, indent=4, separators=(',', ': '...
def print_report_on_all_logs() -> None
Use :func:`print` to report information on all logs.
3.047758
2.766267
1.101758
log.setLevel(level) for h in log.handlers: # type: logging.Handler h.setLevel(level)
def set_level_for_logger_and_its_handlers(log: logging.Logger, level: int) -> None
Set a log level for a log and all its handlers. Args: log: log to modify level: log level to set
3.157365
2.943296
1.072731
log = logging.getLogger(name) log.addHandler(logging.NullHandler()) return BraceStyleAdapter(log)
def get_brace_style_log_with_null_handler(name: str) -> BraceStyleAdapter
For use by library functions. Returns a log with the specifed name that has a null handler attached, and a :class:`BraceStyleAdapter`.
2.683064
2.32614
1.15344
# message = super().format(record) super().format(record) # Since fmt does not contain asctime, the Formatter.format() # will not write asctime (since its usesTime()) function will be # false. Therefore: record.asctime = self.formatTime(record, self.datefmt) ...
def format(self, record: logging.LogRecord) -> str
Internal function to format the :class:`LogRecord` as HTML. See https://docs.python.org/3.4/library/logging.html#logging.LogRecord
4.493131
4.511745
0.995874
# noinspection PyBroadException try: html = self.format(record) self.logfunction(html) except: # nopep8 self.handleError(record)
def emit(self, record: logging.LogRecord) -> None
Internal function to process a :class:`LogRecord`.
5.289938
4.433082
1.193287
insp = Inspector.from_engine(engine) return insp.get_table_names()
def get_table_names(engine: Engine) -> List[str]
Returns a list of database table names from the :class:`Engine`.
3.884866
3.215838
1.208041
insp = Inspector.from_engine(engine) return insp.get_view_names()
def get_view_names(engine: Engine) -> List[str]
Returns a list of database view names from the :class:`Engine`.
4.335773
3.338756
1.298619
tables_and_views = get_table_names(engine) + get_view_names(engine) return table_or_view_name in tables_and_views
def table_or_view_exists(engine: Engine, table_or_view_name: str) -> bool
Does the named table/view exist (either as a table or as a view) in the database?
3.356245
2.75853
1.216679
# Dictionary structure: see # http://docs.sqlalchemy.org/en/latest/core/reflection.html#sqlalchemy.engine.reflection.Inspector.get_columns # noqa insp = Inspector.from_engine(engine) for d in insp.get_columns(tablename): yield SqlaColumnInspectionInfo(d)
def gen_columns_info(engine: Engine, tablename: str) -> Generator[SqlaColumnInspectionInfo, None, None]
For the specified table, generate column information as :class:`SqlaColumnInspectionInfo` objects.
2.969964
3.216997
0.92321
for info in gen_columns_info(engine, tablename): if info.name == columnname: return info return None
def get_column_info(engine: Engine, tablename: str, columnname: str) -> Optional[SqlaColumnInspectionInfo]
For the specified column in the specified table, get column information as a :class:`SqlaColumnInspectionInfo` object (or ``None`` if such a column can't be found).
3.951026
4.743286
0.832972
for info in gen_columns_info(engine, tablename): if info.name == columnname: return info.type return None
def get_column_type(engine: Engine, tablename: str, columnname: str) -> Optional[TypeEngine]
For the specified column in the specified table, get its type as an instance of an SQLAlchemy column type class (or ``None`` if such a column can't be found). For more on :class:`TypeEngine`, see :func:`cardinal_pythonlib.orm_inspect.coltype_as_typeengine`.
4.264385
9.856228
0.432659
return [info.name for info in gen_columns_info(engine, tablename)]
def get_column_names(engine: Engine, tablename: str) -> List[str]
Get all the database column names for the specified table.
8.826628
7.429509
1.18805
pk_names = [] # type: List[str] for col in table_.columns: if col.primary_key: pk_names.append(col.name) return pk_names
def get_pk_colnames(table_: Table) -> List[str]
If a table has a PK, this will return its database column name(s); otherwise, ``None``.
2.107811
2.294767
0.91853
n_pks = 0 int_pk_names = [] for col in table_.columns: if col.primary_key: n_pks += 1 if is_sqlatype_integer(col.type): int_pk_names.append(col.name) if n_pks == 1 and len(int_pk_names) == 1: return int_pk_names[0] return None
def get_single_int_pk_colname(table_: Table) -> Optional[str]
If a table has a single-field (non-composite) integer PK, this will return its database column name; otherwise, None. Note that it is legitimate for a database table to have both a composite primary key and a separate ``IDENTITY`` (``AUTOINCREMENT``) integer field. This function won't find such columns...
2.069732
2.222562
0.931237
n_autoinc = 0 int_autoinc_names = [] for col in table_.columns: if col.autoincrement: n_autoinc += 1 if is_sqlatype_integer(col.type): int_autoinc_names.append(col.name) if n_autoinc > 1: log.warning("Table {!r} has {} autoincrement columns", ...
def get_single_int_autoincrement_colname(table_: Table) -> Optional[str]
If a table has a single integer ``AUTOINCREMENT`` column, this will return its name; otherwise, ``None``. - It's unlikely that a database has >1 ``AUTOINCREMENT`` field anyway, but we should check. - SQL Server's ``IDENTITY`` keyword is equivalent to MySQL's ``AUTOINCREMENT``. - Verify agai...
2.214374
2.404012
0.921116
insp = Inspector.from_engine(engine) return any(i['name'] == indexname for i in insp.get_indexes(tablename))
def index_exists(engine: Engine, tablename: str, indexname: str) -> bool
Does the specified index exist for the specified table?
3.740966
2.58512
1.447115
# http://docs.sqlalchemy.org/en/latest/core/connections.html#sqlalchemy.engine.Connection.execute # noqa # http://docs.sqlalchemy.org/en/latest/core/sqlelement.html#sqlalchemy.sql.expression.text # noqa # http://docs.sqlalchemy.org/en/latest/core/sqlelement.html#sqlalchemy.sql.expression.TextClause.b...
def mssql_get_pk_index_name(engine: Engine, tablename: str, schemaname: str = MSSQL_DEFAULT_SCHEMA) -> str
For Microsoft SQL Server specifically: fetch the name of the PK index for the specified table (in the specified schema), or ``''`` if none is found.
2.230173
2.139227
1.042513
sql = "SELECT @@TRANCOUNT" with contextlib.closing( engine_or_conn.execute(sql)) as result: # type: ResultProxy # noqa row = result.fetchone() return row[0] if row else None
def mssql_transaction_count(engine_or_conn: Union[Connection, Engine]) -> int
For Microsoft SQL Server specifically: fetch the value of the ``TRANCOUNT`` variable (see e.g. https://docs.microsoft.com/en-us/sql/t-sql/functions/trancount-transact-sql?view=sql-server-2017). Returns ``None`` if it can't be found (unlikely?).
3.761895
3.190378
1.179137
# noinspection PyUnresolvedReferences if dialect.name == SqlaDialectName.MSSQL: return Column(column_name, BigInteger, Sequence('dummy_name', start=1, increment=1)) else: # return Column(column_name, BigInteger, autoincrement=True) # noinspection PyUnresolv...
def make_bigint_autoincrement_column(column_name: str, dialect: Dialect) -> Column
Returns an instance of :class:`Column` representing a :class:`BigInteger` ``AUTOINCREMENT`` column in the specified :class:`Dialect`.
4.508335
4.515728
0.998363
# noqa return str(CreateColumn(sqla_column).compile(dialect=dialect))
def column_creation_ddl(sqla_column: Column, dialect: Dialect) -> str
Returns DDL to create a column, using the specified dialect. The column should already be bound to a table (because e.g. the SQL Server dialect requires this for DDL generation). Manual testing: .. code-block:: python from sqlalchemy.schema import Column, CreateColumn, MetaData, Sequence...
6.390392
7.563341
0.844917
if dialect.name == SqlaDialectName.SQLSERVER: return 'NVARCHAR(MAX)' elif dialect.name == SqlaDialectName.MYSQL: return 'LONGTEXT' else: raise ValueError("Unknown dialect: {}".format(dialect.name))
def giant_text_sqltype(dialect: Dialect) -> str
Returns the SQL column type used to make very large text columns for a given dialect. Args: dialect: a SQLAlchemy :class:`Dialect` Returns: the SQL data type of "giant text", typically 'LONGTEXT' for MySQL and 'NVARCHAR(MAX)' for SQL Server.
3.349147
2.745503
1.219866
# noinspection PyUnresolvedReferences ischema_names = dialect.ischema_names try: return ischema_names[coltype.upper()] except KeyError: return ischema_names[coltype.lower()]
def _get_sqla_coltype_class_from_str(coltype: str, dialect: Dialect) -> Type[TypeEngine]
Returns the SQLAlchemy class corresponding to a particular SQL column type in a given dialect. Performs an upper- and lower-case search. For example, the SQLite dialect uses upper case, and the MySQL dialect uses lower case.
2.845236
2.954401
0.96305
f = io.StringIO(x) reader = csv.reader(f, delimiter=',', quotechar="'", quoting=csv.QUOTE_ALL, skipinitialspace=True) for line in reader: # should only be one return [x for x in line]
def get_list_of_sql_string_literals_from_quoted_csv(x: str) -> List[str]
Used to extract SQL column type parameters. For example, MySQL has column types that look like ``ENUM('a', 'b', 'c', 'd')``. This function takes the ``"'a', 'b', 'c', 'd'"`` and converts it to ``['a', 'b', 'c', 'd']``.
3.349139
3.393463
0.986938
if not getattr(coltype, 'collation', None): return coltype newcoltype = copy.copy(coltype) newcoltype.collation = None return newcoltype
def remove_collation(coltype: TypeEngine) -> TypeEngine
Returns a copy of the specific column type with any ``COLLATION`` removed.
3.005105
2.378004
1.263709
assert coltype is not None # noinspection PyUnresolvedReferences to_mysql = dialect.name == SqlaDialectName.MYSQL # noinspection PyUnresolvedReferences to_mssql = dialect.name == SqlaDialectName.MSSQL typeclass = type(coltype) # --------------------------------------------------------...
def convert_sqla_type_for_dialect( coltype: TypeEngine, dialect: Dialect, strip_collation: bool = True, convert_mssql_timestamp: bool = True, expand_for_scrubbing: bool = False) -> TypeEngine
Converts an SQLAlchemy column type from one SQL dialect to another. Args: coltype: SQLAlchemy column type in the source dialect dialect: destination :class:`Dialect` strip_collation: remove any ``COLLATION`` information? convert_mssql_timestamp: since you cannot write...
4.807714
4.779693
1.005863
if isinstance(coltype, VisitableType): coltype = coltype() assert isinstance(coltype, TypeEngine) return coltype
def _coltype_to_typeengine(coltype: Union[TypeEngine, VisitableType]) -> TypeEngine
An example is simplest: if you pass in ``Integer()`` (an instance of :class:`TypeEngine`), you'll get ``Integer()`` back. If you pass in ``Integer`` (an instance of :class:`VisitableType`), you'll also get ``Integer()`` back. The function asserts that its return type is an instance of :class:`TypeEngine...
2.933476
2.359918
1.243042
# Several binary types inherit internally from _Binary, making that the # easiest to check. coltype = _coltype_to_typeengine(coltype) # noinspection PyProtectedMember return isinstance(coltype, sqltypes._Binary)
def is_sqlatype_binary(coltype: Union[TypeEngine, VisitableType]) -> bool
Is the SQLAlchemy column type a binary type?
12.124463
10.010344
1.211194
coltype = _coltype_to_typeengine(coltype) # No longer valid in SQLAlchemy 1.2.11: # return isinstance(coltype, sqltypes._DateAffinity) return ( isinstance(coltype, sqltypes.DateTime) or isinstance(coltype, sqltypes.Date) )
def is_sqlatype_date(coltype: TypeEngine) -> bool
Is the SQLAlchemy column type a date type?
4.738729
4.03558
1.174237
coltype = _coltype_to_typeengine(coltype) return isinstance(coltype, sqltypes.Integer)
def is_sqlatype_integer(coltype: Union[TypeEngine, VisitableType]) -> bool
Is the SQLAlchemy column type an integer type?
5.428642
3.479554
1.560154
coltype = _coltype_to_typeengine(coltype) return isinstance(coltype, sqltypes.Numeric)
def is_sqlatype_numeric(coltype: Union[TypeEngine, VisitableType]) -> bool
Is the SQLAlchemy column type one that inherits from :class:`Numeric`, such as :class:`Float`, :class:`Decimal`?
5.307374
4.406862
1.204343
coltype = _coltype_to_typeengine(coltype) return isinstance(coltype, sqltypes.String)
def is_sqlatype_string(coltype: Union[TypeEngine, VisitableType]) -> bool
Is the SQLAlchemy column type a string type?
5.326768
3.448133
1.544827
coltype = _coltype_to_typeengine(coltype) if not isinstance(coltype, sqltypes.String): return False # not a string/text type at all if coltype.length is None: return True # string of unlimited length return coltype.length >= min_length
def is_sqlatype_text_of_length_at_least( coltype: Union[TypeEngine, VisitableType], min_length: int = 1000) -> bool
Is the SQLAlchemy column type a string type that's at least the specified length?
3.78262
3.251771
1.163249
coltype = _coltype_to_typeengine(coltype) return is_sqlatype_text_of_length_at_least(coltype, 2)
def is_sqlatype_text_over_one_char( coltype: Union[TypeEngine, VisitableType]) -> bool
Is the SQLAlchemy column type a string type that's more than one character long?
5.0752
3.62324
1.400735
coltype = _coltype_to_typeengine(coltype) return is_sqlatype_text_of_length_at_least(coltype, min_length)
def does_sqlatype_merit_fulltext_index( coltype: Union[TypeEngine, VisitableType], min_length: int = 1000) -> bool
Is the SQLAlchemy column type a type that might merit a ``FULLTEXT`` index (meaning a string type of at least ``min_length``)?
5.452455
4.190344
1.301195
coltype = _coltype_to_typeengine(coltype) if isinstance(coltype, sqltypes.Text): return True if isinstance(coltype, sqltypes.LargeBinary): return True return False
def does_sqlatype_require_index_len( coltype: Union[TypeEngine, VisitableType]) -> bool
Is the SQLAlchemy column type one that requires its indexes to have a length specified? (MySQL, at least, requires index length to be specified for ``BLOB`` and ``TEXT`` columns: http://dev.mysql.com/doc/refman/5.7/en/create-index.html.)
3.639419
3.103062
1.172848
# noqa return str(a_coltype) == str(b_coltype)
def column_types_equal(a_coltype: TypeEngine, b_coltype: TypeEngine) -> bool
Checks that two SQLAlchemy column types are equal (by comparing ``str()`` versions of them). See http://stackoverflow.com/questions/34787794/sqlalchemy-column-type-comparison. IMPERFECT.
4.110072
5.922433
0.693984
return ( a.name == b.name and column_types_equal(a.type, b.type) and a.nullable == b.nullable )
def columns_equal(a: Column, b: Column) -> bool
Are two SQLAlchemy columns are equal? Checks based on: - column ``name`` - column ``type`` (see :func:`column_types_equal`) - ``nullable``
3.270076
2.537716
1.28859
n = len(a) if len(b) != n: return False for i in range(n): if not columns_equal(a[i], b[i]): log.debug("Mismatch: {!r} != {!r}", a[i], b[i]) return False return True
def column_lists_equal(a: List[Column], b: List[Column]) -> bool
Are all columns in list ``a`` equal to their counterparts in list ``b``, as per :func:`columns_equal`?
2.725826
2.36377
1.153169
return str(a) == str(b)
def indexes_equal(a: Index, b: Index) -> bool
Are two indexes equal? Checks by comparing ``str()`` versions of them. (AM UNSURE IF THIS IS ENOUGH.)
12.738266
5.548916
2.295631
n = len(a) if len(b) != n: return False for i in range(n): if not indexes_equal(a[i], b[i]): log.debug("Mismatch: {!r} != {!r}", a[i], b[i]) return False return True
def index_lists_equal(a: List[Index], b: List[Index]) -> bool
Are all indexes in list ``a`` equal to their counterparts in list ``b``, as per :func:`indexes_equal`?
2.764762
2.374236
1.164485
# noqa if isinstance(data, int): return bytearray([data]) return bytearray(data, encoding='latin-1')
def to_bytes(data: Any) -> bytearray
Convert anything to a ``bytearray``. See - http://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3 - http://stackoverflow.com/questions/10459067/how-to-convert-my-bytearrayb-x9e-x18k-x9a-to-something-like-this-x9e-x1
4.005502
7.181374
0.557763
assert n_bits % 8 == 0, "Must specify a whole number of bytes" n_bytes = n_bits // 8 b = val.to_bytes(n_bytes, byteorder=sys.byteorder, signed=True) return int.from_bytes(b, byteorder=sys.byteorder, signed=False)
def signed_to_twos_comp(val: int, n_bits: int) -> int
Convert a signed integer to its "two's complement" representation. Args: val: signed integer n_bits: number of bits (which must reflect a whole number of bytes) Returns: unsigned integer: two's complement version
2.601184
2.501657
1.039785
assert len(bytesdata) == 8 return sum((b << (k * 8) for k, b in enumerate(bytesdata)))
def bytes_to_long(bytesdata: bytes) -> int
Converts an 8-byte sequence to a long integer. Args: bytesdata: 8 consecutive bytes, as a ``bytes`` object, in little-endian format (least significant byte [LSB] first) Returns: integer
4.880477
5.342447
0.913528
# noqa c1 = 0xcc9e2d51 c2 = 0x1b873593 length = len(data) h1 = seed rounded_end = (length & 0xfffffffc) # round down to 4 byte block for i in range(0, rounded_end, 4): # little endian load order # RNC: removed ord() calls k1 = (data[i] & 0xff) | ((data[i + 1] & 0x...
def murmur3_x86_32(data: Union[bytes, bytearray], seed: int = 0) -> int
Pure 32-bit Python implementation of MurmurHash3; see http://stackoverflow.com/questions/13305290/is-there-a-pure-python-implementation-of-murmurhash. Args: data: data to hash seed: seed Returns: integer hash
1.520816
1.574916
0.965649
# noqa m = 0xc6a4a7935bd1e995 r = 47 mask = 2 ** 64 - 1 length = len(data) h = seed ^ ((m * length) & mask) offset = (length // 8) * 8 # RNC: was /, but for Python 3 that gives float; brackets added for clarity for ll in range(0, offset, 8): k = bytes_to_long(data[ll:ll...
def murmur3_64(data: Union[bytes, bytearray], seed: int = 19820125) -> int
Pure 64-bit Python implementation of MurmurHash3; see http://stackoverflow.com/questions/13305290/is-there-a-pure-python-implementation-of-murmurhash (plus RNC bugfixes). Args: data: data to hash seed: seed Returns: integer hash
2.2117
2.265274
0.97635
if x64arch: return pymmh3_hash128_x64(key, seed) else: return pymmh3_hash128_x86(key, seed)
def pymmh3_hash128(key: Union[bytes, bytearray], seed: int = 0, x64arch: bool = True) -> int
Implements 128bit murmur3 hash, as per ``pymmh3``. Args: key: data to hash seed: seed x64arch: is a 64-bit architecture available? Returns: integer hash
2.033057
2.198856
0.924598
hash_128 = pymmh3_hash128(key, seed, x64arch) unsigned_val1 = hash_128 & 0xFFFFFFFFFFFFFFFF # low half if unsigned_val1 & 0x8000000000000000 == 0: signed_val1 = unsigned_val1 else: signed_val1 = -((unsigned_val1 ^ 0xFFFFFFFFFFFFFFFF) + 1) unsigned_val2 = (hash_128 >> 64) & 0...
def pymmh3_hash64(key: Union[bytes, bytearray], seed: int = 0, x64arch: bool = True) -> Tuple[int, int]
Implements 64bit murmur3 hash, as per ``pymmh3``. Returns a tuple. Args: key: data to hash seed: seed x64arch: is a 64-bit architecture available? Returns: tuple: tuple of integers, ``(signed_val1, signed_val2)``
1.612732
1.612442
1.00018
assert mmh3, "Need mmh3 module" c_data = to_str(data) c_signed = mmh3.hash(c_data, seed=seed) # 32 bit py_data = to_bytes(c_data) py_unsigned = murmur3_x86_32(py_data, seed=seed) py_signed = twos_comp_to_signed(py_unsigned, n_bits=32) preamble = "Hashing {data} with MurmurHash3/32-bit/...
def compare_python_to_reference_murmur3_32(data: Any, seed: int = 0) -> None
Checks the pure Python implementation of 32-bit murmur3 against the ``mmh3`` C-based module. Args: data: data to hash seed: seed Raises: AssertionError: if the two calculations don't match
3.28291
3.145537
1.043672
assert mmh3, "Need mmh3 module" c_data = to_str(data) c_signed_low, c_signed_high = mmh3.hash64(c_data, seed=seed, x64arch=IS_64_BIT) py_data = to_bytes(c_data) py_signed_low, py_signed_high = pymmh3_hash64(py_data, seed=seed) preamble = "Hashin...
def compare_python_to_reference_murmur3_64(data: Any, seed: int = 0) -> None
Checks the pure Python implementation of 64-bit murmur3 against the ``mmh3`` C-based module. Args: data: data to hash seed: seed Raises: AssertionError: if the two calculations don't match
3.028842
2.932364
1.032901
with MultiTimerContext(timer, TIMING_HASH): c_data = to_str(data) if mmh3: return mmh3.hash(c_data, seed=seed) py_data = to_bytes(c_data) py_unsigned = murmur3_x86_32(py_data, seed=seed) return twos_comp_to_signed(py_unsigned, n_bits=32)
def hash32(data: Any, seed=0) -> int
Non-cryptographic, deterministic, fast hash. Args: data: data to hash seed: seed Returns: signed 32-bit integer
6.022164
6.096811
0.987756
# ------------------------------------------------------------------------- # MurmurHash3 # ------------------------------------------------------------------------- c_data = to_str(data) if mmh3: c_signed_low, _ = mmh3.hash64(data, seed=seed, x64arch=IS_64_BIT) return c_signed_...
def hash64(data: Any, seed: int = 0) -> int
Non-cryptographic, deterministic, fast hash. Args: data: data to hash seed: seed Returns: signed 64-bit integer
5.959081
5.789033
1.029374
_ = # noqa testdata = [ "hello", 1, ["bongos", "today"], ] for data in testdata: compare_python_to_reference_murmur3_32(data, seed=0) compare_python_to_reference_murmur3_64(data, seed=0) print("All OK")
def main() -> None
Command-line validation checks.
9.084596
8.288212
1.096086
with MultiTimerContext(timer, TIMING_HASH): raw_bytes = str(raw).encode('utf-8') hmac_obj = hmac.new(key=self.key_bytes, msg=raw_bytes, digestmod=self.digestmod) return hmac_obj.hexdigest()
def hash(self, raw: Any) -> str
Returns the hex digest of a HMAC-encoded version of the input.
4.968081
4.100882
1.211467
total = 0.0 # starting with "0.0" causes automatic conversion to float n = 0 for x in values: if x is not None: total += x n += 1 return total / n if n > 0 else None
def mean(values: Sequence[Union[int, float, None]]) -> Optional[float]
Returns the mean of a list of numbers. Args: values: values to mean, ignoring any values that are ``None`` Returns: the mean, or ``None`` if :math:`n = 0`
3.887695
4.616939
0.84205
r if p > 1 or p < 0: return None # can't take log of negative number if p == 1: return float("inf") if p == 0: return float("-inf") return math.log(p / (1 - p))
def safe_logit(p: Union[float, int]) -> Optional[float]
r""" Returns the logit (log odds) of its input probability .. math:: \alpha = logit(p) = log(x / (1 - x)) Args: p: :math:`p` Returns: :math:`\alpha`, or ``None`` if ``x`` is not in the range [0, 1].
3.132368
3.728312
0.840157
if not math.isfinite(x): return x factor = pow(10, dp) x = x * factor if x >= 0: x = math.floor(x + 0.5) else: x = math.ceil(x - 0.5) x = x / factor return x
def normal_round_float(x: float, dp: int = 0) -> float
Hmpf. Shouldn't need to have to implement this, but... Conventional rounding to integer via the "round half away from zero" method, e.g. .. code-block:: none 1.1 -> 1 1.5 -> 2 1.6 -> 2 2.0 -> 2 -1.6 -> -2 etc. ... or the equivalent for a certain numbe...
2.373757
2.690334
0.882328
if not math.isfinite(x): raise ValueError("Input to normal_round_int() is not finite") if x >= 0: # noinspection PyTypeChecker return math.floor(x + 0.5) else: # noinspection PyTypeChecker return math.ceil(x - 0.5)
def normal_round_int(x: float) -> int
Version of :func:`normal_round_float` but guaranteed to return an `int`.
2.47502
2.173202
1.138882
ca = [ mysqldump, "-u", username, "-p{}".format("*****" if hide_password else password), "--max_allowed_packet={}".format(max_allowed_packet), "--hex-blob", # preferable to raw binary in our .sql file ] if verbose: ca.append("--verbose") if with_drop...
def cmdargs(mysqldump: str, username: str, password: str, database: str, verbose: bool, with_drop_create_database: bool, max_allowed_packet: str, hide_password: bool = False) -> List[str]
Returns command arguments for a ``mysqldump`` call. Args: mysqldump: ``mysqldump`` executable filename username: user name password: password database: database name verbose: verbose output? with_drop_create_database: produce commands to ``DROP`` the database ...
3.264874
3.868238
0.844021
main_only_quicksetup_rootlogger() wdcd_suffix = "_with_drop_create_database" timeformat = "%Y%m%dT%H%M%S" parser = argparse.ArgumentParser( description=.format(timeformat=timeformat, suffix=wdcd_suffix), formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument...
def main() -> None
Command-line processor. See ``--help`` for details.
2.761003
2.750582
1.003788
if isinstance(mixed, Dialect): return mixed elif isinstance(mixed, Engine): return mixed.dialect elif isinstance(mixed, SQLCompiler): return mixed.dialect else: raise ValueError("get_dialect: 'mixed' parameter of wrong type")
def get_dialect(mixed: Union[SQLCompiler, Engine, Dialect]) -> Dialect
Finds the SQLAlchemy dialect in use. Args: mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or :class:`Dialect` object Returns: the SQLAlchemy :class:`Dialect` being used
2.406057
2.953938
0.814525
dialect = get_dialect(mixed) # noinspection PyUnresolvedReferences return dialect.name
def get_dialect_name(mixed: Union[SQLCompiler, Engine, Dialect]) -> str
Finds the name of the SQLAlchemy dialect in use. Args: mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or :class:`Dialect` object Returns: the SQLAlchemy dialect name being used
5.691182
10.127017
0.56198
dialect = get_dialect(mixed) # noinspection PyUnresolvedReferences return dialect.preparer(dialect)
def get_preparer(mixed: Union[SQLCompiler, Engine, Dialect]) -> IdentifierPreparer
Returns the SQLAlchemy :class:`IdentifierPreparer` in use for the dialect being used. Args: mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or :class:`Dialect` object Returns: an :class:`IdentifierPreparer`
5.469185
7.853193
0.696428
# See also http://sqlalchemy-utils.readthedocs.io/en/latest/_modules/sqlalchemy_utils/functions/orm.html # noqa return get_preparer(mixed).quote(identifier)
def quote_identifier(identifier: str, mixed: Union[SQLCompiler, Engine, Dialect]) -> str
Converts an SQL identifier to a quoted version, via the SQL dialect in use. Args: identifier: the identifier to be quoted mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or :class:`Dialect` object Returns: the quoted identifier
5.729322
6.816995
0.840447
if exists(antlr_jar_path): if lazy: return if not force: raise OSError(errno.EEXIST, 'file already exists', antlr_jar_path) tool_url = config['tool_url'] ssl_context = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH) with contextlib.closing(urlop...
def install(force=False, lazy=False)
Download the ANTLR v4 tool jar. (Raises :exception:`OSError` if jar is already available, unless ``lazy`` is ``True``.) :param bool force: Force download even if local jar already exists. :param bool lazy: Don't report an error if local jar already exists and don't try to download it either.
2.699399
2.491911
1.083265
arg_parser = ArgumentParser(description='Install helper tool to download the right version of the ANTLR v4 tool jar.') arg_parser.add_argument('--version', action='version', version='%(prog)s {version}'.format(version=__version__)) mode_group = arg_parser.add_mutually_exclusive_group() mode_grou...
def execute()
Entry point of the install helper tool to ease the download of the right version of the ANTLR v4 tool jar.
3.088243
2.279705
1.354668
if x is None: return "" x = str(x) return x.replace("\t", "\\t").replace("\n", "\\n")
def tsv_escape(x: Any) -> str
Escape data for tab-separated value (TSV) format.
3.063488
2.509495
1.220759
return "\t".join([tsv_escape(x) for x in values]) + "\n"
def make_tsv_row(values: List[Any]) -> str
From a list of values, make a TSV line.
6.429784
3.318599
1.937499
if not dictlist: return "" fieldnames = dictlist[0].keys() tsv = "\t".join([tsv_escape(f) for f in fieldnames]) + "\n" for d in dictlist: tsv += "\t".join([tsv_escape(v) for v in d.values()]) + "\n" return tsv
def dictlist_to_tsv(dictlist: List[Dict[str, Any]]) -> str
From a consistent list of dictionaries mapping fieldnames to values, make a TSV file.
2.199687
1.979636
1.111158
r items = line.split("\t") d = {} # type: Dict[str, str] for chunk in chunks(items, 2): if len(chunk) < 2: log.warning("Bad chunk, not of length 2: {!r}", chunk) continue key = chunk[0] value = unescape_tabs_newlines(chunk[1]) if key_lower: ...
def tsv_pairs_to_dict(line: str, key_lower: bool = True) -> Dict[str, str]
r""" Converts a TSV line into sequential key/value pairs as a dictionary. For example, .. code-block:: none field1\tvalue1\tfield2\tvalue2 becomes .. code-block:: none {"field1": "value1", "field2": "value2"} Args: line: the line key_lower: should the keys ...
3.080661
3.417901
0.901331
# http://stackoverflow.com/questions/3365740/how-to-import-all-submodules if isinstance(package, str): package = importlib.import_module(package, base_package_for_relative_import) results = {} for loader, name, is_pkg in pkgutil.walk_packages(packag...
def import_submodules(package: Union[str, ModuleType], base_package_for_relative_import: str = None, recursive: bool = True) -> Dict[str, ModuleType]
Import all submodules of a module, recursively, including subpackages. Args: package: package (name or actual module) base_package_for_relative_import: path to prepend? recursive: import submodules too? Returns: dict: mapping from full module name to module
1.916264
2.12643
0.901165
# noqa assert inspect.ismodule(module), '"{}" not a module.'.format(module) # If this module was loaded by a PEP 302-compliant CPython-specific loader # loading only C extensions, this module is a C extension. if isinstance(getattr(module, '__loader__', None), ExtensionFileLoader): return...
def is_c_extension(module: ModuleType) -> bool
Modified from https://stackoverflow.com/questions/20339053/in-python-how-can-one-tell-if-a-module-comes-from-a-c-extension. ``True`` only if the passed module is a C extension implemented as a dynamically linked shared library specific to the current platform. Args: module: Previously impo...
5.248243
6.127423
0.856517
oldpath = os.environ.get("PATH", "") os.environ["PATH"] = env.get("PATH") which = shutil.which(executable) os.environ["PATH"] = oldpath return which
def which_with_envpath(executable: str, env: Dict[str, str]) -> str
Performs a :func:`shutil.which` command using the PATH from the specified environment. Reason: when you use ``run([executable, ...], env)`` and therefore ``subprocess.run([executable, ...], env=env)``, the PATH that's searched for ``executable`` is the parent's, not the new child's -- so you have to ...
2.959602
3.315603
0.892629
if shutil.which(executable): return errmsg = "Missing command (must be on the PATH): " + executable log.critical(errmsg) raise FileNotFoundError(errmsg)
def require_executable(executable: str) -> None
If ``executable`` is not found by :func:`shutil.which`, raise :exc:`FileNotFoundError`.
6.481797
6.133365
1.056809
log.debug("mkdir -p " + path) os.makedirs(path, exist_ok=True)
def mkdir_p(path: str) -> None
Makes a directory, and any intermediate (parent) directories if required. This is the UNIX ``mkdir -p DIRECTORY`` command; of course, we use :func:`os.makedirs` instead, for portability.
5.580404
4.136871
1.348943
previous_dir = os.getcwd() os.chdir(directory) yield os.chdir(previous_dir)
def pushd(directory: str) -> None
Context manager: changes directory and preserves the original on exit. Example: .. code-block:: python with pushd(new_directory): # do things
3.520231
5.337633
0.659512
# http://stackoverflow.com/questions/169070/python-how-do-i-write-a-decorator-that-restores-the-cwd # noqa def decorator(*args_, **kwargs) -> Any: cwd = os.getcwd() result = func(*args_, **kwargs) os.chdir(cwd) return result return decorator
def preserve_cwd(func: Callable) -> Callable
Decorator to preserve the current working directory in calls to the decorated function. Example: .. code-block:: python @preserve_cwd def myfunc(): os.chdir("/faraway") os.chdir("/home") myfunc() assert os.getcwd() == "/home"
3.615231
4.189841
0.862856
something = False for filename in glob.glob(src): if allow_nonfiles or os.path.isfile(filename): shutil.copy(filename, dest) something = True if something or allow_nothing: return raise ValueError("No files found matching: {}".format(src))
def copyglob(src: str, dest: str, allow_nothing: bool = False, allow_nonfiles: bool = False) -> None
Copies files whose filenames match the glob src" into the directory "dest". Raises an error if no files are copied, unless allow_nothing is True. Args: src: source glob (e.g. ``/somewhere/*.txt``) dest: destination directory allow_nothing: don't raise an exception if no files are fo...
3.209847
3.368931
0.952779
dirname = os.path.basename(os.path.normpath(src_dir)) dest_dir = os.path.join(dest_parent, dirname) shutil.copytree(src_dir, dest_dir)
def copy_tree_root(src_dir: str, dest_parent: str) -> None
Copies a directory ``src_dir`` into the directory ``dest_parent``. That is, with a file structure like: .. code-block:: none /source/thing/a.txt /source/thing/b.txt /source/thing/somedir/c.txt the command .. code-block:: python copy_tree_root("/source/thing", "/dest"...
2.098126
2.467011
0.850473
log.info("Copying directory {} -> {}", srcdir, destdir) if os.path.exists(destdir): if not destroy: raise ValueError("Destination exists!") if not os.path.isdir(destdir): raise ValueError("Destination exists but isn't a directory!") log.debug("... removing ol...
def copy_tree_contents(srcdir: str, destdir: str, destroy: bool = False) -> None
Recursive copy. Unlike :func:`copy_tree_root`, :func:`copy_tree_contents` works as follows. With the file structure: .. code-block:: none /source/thing/a.txt /source/thing/b.txt /source/thing/somedir/c.txt the command .. code-block:: python copy_tree_contents("/sourc...
3.147371
3.679259
0.855436
for f in glob.glob(pattern): os.remove(f)
def rmglob(pattern: str) -> None
Deletes all files whose filename matches the glob ``pattern`` (via :func:`glob.glob`).
5.726292
4.541639
1.260843
for f in find(pattern, path): log.info("Deleting {}", f) os.remove(f)
def purge(path: str, pattern: str) -> None
Deletes all files in ``path`` matching ``pattern`` (via :func:`fnmatch.fnmatch`).
7.347629
6.978022
1.052967
for dirpath, dirnames, fnames in os.walk(directory): for f in fnames: if f in filenames: fullpath = os.path.join(dirpath, f) log.debug("Deleting {!r}", fullpath) os.remove(fullpath)
def delete_files_within_dir(directory: str, filenames: List[str]) -> None
Delete files within ``directory`` whose filename *exactly* matches one of ``filenames``.
2.698944
2.50735
1.076413
# noqa if not os.access(path, os.W_OK): # Is the error an access error ? os.chmod(path, stat.S_IWUSR) func(path) else: exc = exc_info[1] raise exc
def shutil_rmtree_onerror(func: Callable[[str], None], path: str, exc_info: EXC_INFO_TYPE) -> None
Error handler for ``shutil.rmtree``. If the error is due to an access error (read only file) it attempts to add write permission and then retries. If the error is for another reason it re-raises the error. Usage: ``shutil.rmtree(path, onerror=shutil_rmtree_onerror)`` See https://stackove...
2.481559
2.690822
0.922231