id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
400 | gmr/queries | queries/pool.py | PoolManager.shutdown | def shutdown(cls):
"""Close all connections on in all pools"""
for pid in list(cls._pools.keys()):
cls._pools[pid].shutdown()
LOGGER.info('Shutdown complete, all pooled connections closed') | python | def shutdown(cls):
for pid in list(cls._pools.keys()):
cls._pools[pid].shutdown()
LOGGER.info('Shutdown complete, all pooled connections closed') | [
"def",
"shutdown",
"(",
"cls",
")",
":",
"for",
"pid",
"in",
"list",
"(",
"cls",
".",
"_pools",
".",
"keys",
"(",
")",
")",
":",
"cls",
".",
"_pools",
"[",
"pid",
"]",
".",
"shutdown",
"(",
")",
"LOGGER",
".",
"info",
"(",
"'Shutdown complete, all ... | Close all connections on in all pools | [
"Close",
"all",
"connections",
"on",
"in",
"all",
"pools"
] | a68855013dc6aaf9ed7b6909a4701f8da8796a0a | https://github.com/gmr/queries/blob/a68855013dc6aaf9ed7b6909a4701f8da8796a0a/queries/pool.py#L653-L657 |
401 | gmr/queries | queries/pool.py | PoolManager.size | def size(cls, pid):
"""Return the number of connections in the pool
:param str pid: The pool id
:rtype int
"""
with cls._lock:
cls._ensure_pool_exists(pid)
return len(cls._pools[pid]) | python | def size(cls, pid):
with cls._lock:
cls._ensure_pool_exists(pid)
return len(cls._pools[pid]) | [
"def",
"size",
"(",
"cls",
",",
"pid",
")",
":",
"with",
"cls",
".",
"_lock",
":",
"cls",
".",
"_ensure_pool_exists",
"(",
"pid",
")",
"return",
"len",
"(",
"cls",
".",
"_pools",
"[",
"pid",
"]",
")"
] | Return the number of connections in the pool
:param str pid: The pool id
:rtype int | [
"Return",
"the",
"number",
"of",
"connections",
"in",
"the",
"pool"
] | a68855013dc6aaf9ed7b6909a4701f8da8796a0a | https://github.com/gmr/queries/blob/a68855013dc6aaf9ed7b6909a4701f8da8796a0a/queries/pool.py#L660-L669 |
402 | gmr/queries | queries/pool.py | PoolManager.report | def report(cls):
"""Return the state of the all of the registered pools.
:rtype: dict
"""
return {
'timestamp': datetime.datetime.utcnow().isoformat(),
'process': os.getpid(),
'pools': dict([(i, p.report()) for i, p in cls._pools.items()])
} | python | def report(cls):
return {
'timestamp': datetime.datetime.utcnow().isoformat(),
'process': os.getpid(),
'pools': dict([(i, p.report()) for i, p in cls._pools.items()])
} | [
"def",
"report",
"(",
"cls",
")",
":",
"return",
"{",
"'timestamp'",
":",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
".",
"isoformat",
"(",
")",
",",
"'process'",
":",
"os",
".",
"getpid",
"(",
")",
",",
"'pools'",
":",
"dict",
"(",
"[",... | Return the state of the all of the registered pools.
:rtype: dict | [
"Return",
"the",
"state",
"of",
"the",
"all",
"of",
"the",
"registered",
"pools",
"."
] | a68855013dc6aaf9ed7b6909a4701f8da8796a0a | https://github.com/gmr/queries/blob/a68855013dc6aaf9ed7b6909a4701f8da8796a0a/queries/pool.py#L672-L682 |
403 | gmr/queries | queries/pool.py | PoolManager._maybe_remove_pool | def _maybe_remove_pool(cls, pid):
"""If the pool has no open connections, remove it
:param str pid: The pool id to clean
"""
if not len(cls._pools[pid]):
del cls._pools[pid] | python | def _maybe_remove_pool(cls, pid):
if not len(cls._pools[pid]):
del cls._pools[pid] | [
"def",
"_maybe_remove_pool",
"(",
"cls",
",",
"pid",
")",
":",
"if",
"not",
"len",
"(",
"cls",
".",
"_pools",
"[",
"pid",
"]",
")",
":",
"del",
"cls",
".",
"_pools",
"[",
"pid",
"]"
] | If the pool has no open connections, remove it
:param str pid: The pool id to clean | [
"If",
"the",
"pool",
"has",
"no",
"open",
"connections",
"remove",
"it"
] | a68855013dc6aaf9ed7b6909a4701f8da8796a0a | https://github.com/gmr/queries/blob/a68855013dc6aaf9ed7b6909a4701f8da8796a0a/queries/pool.py#L697-L704 |
404 | gmr/queries | queries/session.py | Session.close | def close(self):
"""Explicitly close the connection and remove it from the connection
pool if pooling is enabled. If the connection is already closed
:raises: psycopg2.InterfaceError
"""
if not self._conn:
raise psycopg2.InterfaceError('Connection not open')
... | python | def close(self):
if not self._conn:
raise psycopg2.InterfaceError('Connection not open')
LOGGER.info('Closing connection %r in %s', self._conn, self.pid)
self._pool_manager.free(self.pid, self._conn)
self._pool_manager.remove_connection(self.pid, self._conn)
# Un-ass... | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_conn",
":",
"raise",
"psycopg2",
".",
"InterfaceError",
"(",
"'Connection not open'",
")",
"LOGGER",
".",
"info",
"(",
"'Closing connection %r in %s'",
",",
"self",
".",
"_conn",
",",
"self",... | Explicitly close the connection and remove it from the connection
pool if pooling is enabled. If the connection is already closed
:raises: psycopg2.InterfaceError | [
"Explicitly",
"close",
"the",
"connection",
"and",
"remove",
"it",
"from",
"the",
"connection",
"pool",
"if",
"pooling",
"is",
"enabled",
".",
"If",
"the",
"connection",
"is",
"already",
"closed"
] | a68855013dc6aaf9ed7b6909a4701f8da8796a0a | https://github.com/gmr/queries/blob/a68855013dc6aaf9ed7b6909a4701f8da8796a0a/queries/session.py#L131-L145 |
405 | gmr/queries | queries/session.py | Session.pid | def pid(self):
"""Return the pool ID used for connection pooling.
:rtype: str
"""
return hashlib.md5(':'.join([self.__class__.__name__,
self._uri]).encode('utf-8')).hexdigest() | python | def pid(self):
return hashlib.md5(':'.join([self.__class__.__name__,
self._uri]).encode('utf-8')).hexdigest() | [
"def",
"pid",
"(",
"self",
")",
":",
"return",
"hashlib",
".",
"md5",
"(",
"':'",
".",
"join",
"(",
"[",
"self",
".",
"__class__",
".",
"__name__",
",",
"self",
".",
"_uri",
"]",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
".",
"hexdigest",
"("... | Return the pool ID used for connection pooling.
:rtype: str | [
"Return",
"the",
"pool",
"ID",
"used",
"for",
"connection",
"pooling",
"."
] | a68855013dc6aaf9ed7b6909a4701f8da8796a0a | https://github.com/gmr/queries/blob/a68855013dc6aaf9ed7b6909a4701f8da8796a0a/queries/session.py#L184-L191 |
406 | gmr/queries | queries/session.py | Session.set_encoding | def set_encoding(self, value=DEFAULT_ENCODING):
"""Set the client encoding for the session if the value specified
is different than the current client encoding.
:param str value: The encoding value to use
"""
if self._conn.encoding != value:
self._conn.set_client_en... | python | def set_encoding(self, value=DEFAULT_ENCODING):
if self._conn.encoding != value:
self._conn.set_client_encoding(value) | [
"def",
"set_encoding",
"(",
"self",
",",
"value",
"=",
"DEFAULT_ENCODING",
")",
":",
"if",
"self",
".",
"_conn",
".",
"encoding",
"!=",
"value",
":",
"self",
".",
"_conn",
".",
"set_client_encoding",
"(",
"value",
")"
] | Set the client encoding for the session if the value specified
is different than the current client encoding.
:param str value: The encoding value to use | [
"Set",
"the",
"client",
"encoding",
"for",
"the",
"session",
"if",
"the",
"value",
"specified",
"is",
"different",
"than",
"the",
"current",
"client",
"encoding",
"."
] | a68855013dc6aaf9ed7b6909a4701f8da8796a0a | https://github.com/gmr/queries/blob/a68855013dc6aaf9ed7b6909a4701f8da8796a0a/queries/session.py#L221-L229 |
407 | gmr/queries | queries/session.py | Session._cleanup | def _cleanup(self):
"""Remove the connection from the stack, closing out the cursor"""
if self._cursor:
LOGGER.debug('Closing the cursor on %s', self.pid)
self._cursor.close()
self._cursor = None
if self._conn:
LOGGER.debug('Freeing %s in the pool... | python | def _cleanup(self):
if self._cursor:
LOGGER.debug('Closing the cursor on %s', self.pid)
self._cursor.close()
self._cursor = None
if self._conn:
LOGGER.debug('Freeing %s in the pool', self.pid)
try:
pool.PoolManager.instance().f... | [
"def",
"_cleanup",
"(",
"self",
")",
":",
"if",
"self",
".",
"_cursor",
":",
"LOGGER",
".",
"debug",
"(",
"'Closing the cursor on %s'",
",",
"self",
".",
"pid",
")",
"self",
".",
"_cursor",
".",
"close",
"(",
")",
"self",
".",
"_cursor",
"=",
"None",
... | Remove the connection from the stack, closing out the cursor | [
"Remove",
"the",
"connection",
"from",
"the",
"stack",
"closing",
"out",
"the",
"cursor"
] | a68855013dc6aaf9ed7b6909a4701f8da8796a0a | https://github.com/gmr/queries/blob/a68855013dc6aaf9ed7b6909a4701f8da8796a0a/queries/session.py#L258-L271 |
408 | gmr/queries | queries/session.py | Session._get_cursor | def _get_cursor(self, connection, name=None):
"""Return a cursor for the given cursor_factory. Specify a name to
use server-side cursors.
:param connection: The connection to create a cursor on
:type connection: psycopg2.extensions.connection
:param str name: A cursor name for a... | python | def _get_cursor(self, connection, name=None):
cursor = connection.cursor(name=name,
cursor_factory=self._cursor_factory)
if name is not None:
cursor.scrollable = True
cursor.withhold = True
return cursor | [
"def",
"_get_cursor",
"(",
"self",
",",
"connection",
",",
"name",
"=",
"None",
")",
":",
"cursor",
"=",
"connection",
".",
"cursor",
"(",
"name",
"=",
"name",
",",
"cursor_factory",
"=",
"self",
".",
"_cursor_factory",
")",
"if",
"name",
"is",
"not",
... | Return a cursor for the given cursor_factory. Specify a name to
use server-side cursors.
:param connection: The connection to create a cursor on
:type connection: psycopg2.extensions.connection
:param str name: A cursor name for a server side cursor
:rtype: psycopg2.extensions.c... | [
"Return",
"a",
"cursor",
"for",
"the",
"given",
"cursor_factory",
".",
"Specify",
"a",
"name",
"to",
"use",
"server",
"-",
"side",
"cursors",
"."
] | a68855013dc6aaf9ed7b6909a4701f8da8796a0a | https://github.com/gmr/queries/blob/a68855013dc6aaf9ed7b6909a4701f8da8796a0a/queries/session.py#L309-L324 |
409 | gmr/queries | queries/session.py | Session._register_unicode | def _register_unicode(connection):
"""Register the cursor to be able to receive Unicode string.
:type connection: psycopg2.extensions.connection
:param connection: Where to register things
"""
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE,
... | python | def _register_unicode(connection):
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE,
connection)
psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY,
connection) | [
"def",
"_register_unicode",
"(",
"connection",
")",
":",
"psycopg2",
".",
"extensions",
".",
"register_type",
"(",
"psycopg2",
".",
"extensions",
".",
"UNICODE",
",",
"connection",
")",
"psycopg2",
".",
"extensions",
".",
"register_type",
"(",
"psycopg2",
".",
... | Register the cursor to be able to receive Unicode string.
:type connection: psycopg2.extensions.connection
:param connection: Where to register things | [
"Register",
"the",
"cursor",
"to",
"be",
"able",
"to",
"receive",
"Unicode",
"string",
"."
] | a68855013dc6aaf9ed7b6909a4701f8da8796a0a | https://github.com/gmr/queries/blob/a68855013dc6aaf9ed7b6909a4701f8da8796a0a/queries/session.py#L345-L355 |
410 | gmr/queries | queries/session.py | Session._status | def _status(self):
"""Return the current connection status as an integer value.
The status should match one of the following constants:
- queries.Session.INTRANS: Connection established, in transaction
- queries.Session.PREPARED: Prepared for second phase of transaction
- queri... | python | def _status(self):
if self._conn.status == psycopg2.extensions.STATUS_BEGIN:
return self.READY
return self._conn.status | [
"def",
"_status",
"(",
"self",
")",
":",
"if",
"self",
".",
"_conn",
".",
"status",
"==",
"psycopg2",
".",
"extensions",
".",
"STATUS_BEGIN",
":",
"return",
"self",
".",
"READY",
"return",
"self",
".",
"_conn",
".",
"status"
] | Return the current connection status as an integer value.
The status should match one of the following constants:
- queries.Session.INTRANS: Connection established, in transaction
- queries.Session.PREPARED: Prepared for second phase of transaction
- queries.Session.READY: Connected, n... | [
"Return",
"the",
"current",
"connection",
"status",
"as",
"an",
"integer",
"value",
"."
] | a68855013dc6aaf9ed7b6909a4701f8da8796a0a | https://github.com/gmr/queries/blob/a68855013dc6aaf9ed7b6909a4701f8da8796a0a/queries/session.py#L368-L382 |
411 | gmr/queries | queries/results.py | Results.items | def items(self):
"""Return all of the rows that are in the result set.
:rtype: list
"""
if not self.cursor.rowcount:
return []
self.cursor.scroll(0, 'absolute')
return self.cursor.fetchall() | python | def items(self):
if not self.cursor.rowcount:
return []
self.cursor.scroll(0, 'absolute')
return self.cursor.fetchall() | [
"def",
"items",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"cursor",
".",
"rowcount",
":",
"return",
"[",
"]",
"self",
".",
"cursor",
".",
"scroll",
"(",
"0",
",",
"'absolute'",
")",
"return",
"self",
".",
"cursor",
".",
"fetchall",
"(",
")"
... | Return all of the rows that are in the result set.
:rtype: list | [
"Return",
"all",
"of",
"the",
"rows",
"that",
"are",
"in",
"the",
"result",
"set",
"."
] | a68855013dc6aaf9ed7b6909a4701f8da8796a0a | https://github.com/gmr/queries/blob/a68855013dc6aaf9ed7b6909a4701f8da8796a0a/queries/results.py#L98-L108 |
412 | gmr/queries | queries/utils.py | get_current_user | def get_current_user():
"""Return the current username for the logged in user
:rtype: str
"""
if pwd is None:
return getpass.getuser()
else:
try:
return pwd.getpwuid(os.getuid())[0]
except KeyError as error:
LOGGER.error('Could not get logged-in user... | python | def get_current_user():
if pwd is None:
return getpass.getuser()
else:
try:
return pwd.getpwuid(os.getuid())[0]
except KeyError as error:
LOGGER.error('Could not get logged-in user: %s', error) | [
"def",
"get_current_user",
"(",
")",
":",
"if",
"pwd",
"is",
"None",
":",
"return",
"getpass",
".",
"getuser",
"(",
")",
"else",
":",
"try",
":",
"return",
"pwd",
".",
"getpwuid",
"(",
"os",
".",
"getuid",
"(",
")",
")",
"[",
"0",
"]",
"except",
... | Return the current username for the logged in user
:rtype: str | [
"Return",
"the",
"current",
"username",
"for",
"the",
"logged",
"in",
"user"
] | a68855013dc6aaf9ed7b6909a4701f8da8796a0a | https://github.com/gmr/queries/blob/a68855013dc6aaf9ed7b6909a4701f8da8796a0a/queries/utils.py#L57-L69 |
413 | gmr/queries | queries/utils.py | uri | def uri(host='localhost', port=5432, dbname='postgres', user='postgres',
password=None):
"""Return a PostgreSQL connection URI for the specified values.
:param str host: Host to connect to
:param int port: Port to connect on
:param str dbname: The database name
:param str user: User to conn... | python | def uri(host='localhost', port=5432, dbname='postgres', user='postgres',
password=None):
if port:
host = '%s:%s' % (host, port)
if password:
return 'postgresql://%s:%s@%s/%s' % (user, password, host, dbname)
return 'postgresql://%s@%s/%s' % (user, host, dbname) | [
"def",
"uri",
"(",
"host",
"=",
"'localhost'",
",",
"port",
"=",
"5432",
",",
"dbname",
"=",
"'postgres'",
",",
"user",
"=",
"'postgres'",
",",
"password",
"=",
"None",
")",
":",
"if",
"port",
":",
"host",
"=",
"'%s:%s'",
"%",
"(",
"host",
",",
"po... | Return a PostgreSQL connection URI for the specified values.
:param str host: Host to connect to
:param int port: Port to connect on
:param str dbname: The database name
:param str user: User to connect as
:param str password: The password to use, None for no password
:return str: The PostgreSQ... | [
"Return",
"a",
"PostgreSQL",
"connection",
"URI",
"for",
"the",
"specified",
"values",
"."
] | a68855013dc6aaf9ed7b6909a4701f8da8796a0a | https://github.com/gmr/queries/blob/a68855013dc6aaf9ed7b6909a4701f8da8796a0a/queries/utils.py#L82-L98 |
414 | gmr/queries | queries/utils.py | uri_to_kwargs | def uri_to_kwargs(uri):
"""Return a URI as kwargs for connecting to PostgreSQL with psycopg2,
applying default values for non-specified areas of the URI.
:param str uri: The connection URI
:rtype: dict
"""
parsed = urlparse(uri)
default_user = get_current_user()
password = unquote(pars... | python | def uri_to_kwargs(uri):
parsed = urlparse(uri)
default_user = get_current_user()
password = unquote(parsed.password) if parsed.password else None
kwargs = {'host': parsed.hostname,
'port': parsed.port,
'dbname': parsed.path[1:] or default_user,
'user': parsed.us... | [
"def",
"uri_to_kwargs",
"(",
"uri",
")",
":",
"parsed",
"=",
"urlparse",
"(",
"uri",
")",
"default_user",
"=",
"get_current_user",
"(",
")",
"password",
"=",
"unquote",
"(",
"parsed",
".",
"password",
")",
"if",
"parsed",
".",
"password",
"else",
"None",
... | Return a URI as kwargs for connecting to PostgreSQL with psycopg2,
applying default values for non-specified areas of the URI.
:param str uri: The connection URI
:rtype: dict | [
"Return",
"a",
"URI",
"as",
"kwargs",
"for",
"connecting",
"to",
"PostgreSQL",
"with",
"psycopg2",
"applying",
"default",
"values",
"for",
"non",
"-",
"specified",
"areas",
"of",
"the",
"URI",
"."
] | a68855013dc6aaf9ed7b6909a4701f8da8796a0a | https://github.com/gmr/queries/blob/a68855013dc6aaf9ed7b6909a4701f8da8796a0a/queries/utils.py#L101-L127 |
415 | gmr/queries | queries/tornado_session.py | TornadoSession._ensure_pool_exists | def _ensure_pool_exists(self):
"""Create the pool in the pool manager if it does not exist."""
if self.pid not in self._pool_manager:
self._pool_manager.create(self.pid, self._pool_idle_ttl,
self._pool_max_size, self._ioloop.time) | python | def _ensure_pool_exists(self):
if self.pid not in self._pool_manager:
self._pool_manager.create(self.pid, self._pool_idle_ttl,
self._pool_max_size, self._ioloop.time) | [
"def",
"_ensure_pool_exists",
"(",
"self",
")",
":",
"if",
"self",
".",
"pid",
"not",
"in",
"self",
".",
"_pool_manager",
":",
"self",
".",
"_pool_manager",
".",
"create",
"(",
"self",
".",
"pid",
",",
"self",
".",
"_pool_idle_ttl",
",",
"self",
".",
"... | Create the pool in the pool manager if it does not exist. | [
"Create",
"the",
"pool",
"in",
"the",
"pool",
"manager",
"if",
"it",
"does",
"not",
"exist",
"."
] | a68855013dc6aaf9ed7b6909a4701f8da8796a0a | https://github.com/gmr/queries/blob/a68855013dc6aaf9ed7b6909a4701f8da8796a0a/queries/tornado_session.py#L165-L169 |
416 | gmr/queries | queries/tornado_session.py | TornadoSession._create_connection | def _create_connection(self, future):
"""Create a new PostgreSQL connection
:param tornado.concurrent.Future future: future for new conn result
"""
LOGGER.debug('Creating a new connection for %s', self.pid)
# Create a new PostgreSQL connection
kwargs = utils.uri_to_kwa... | python | def _create_connection(self, future):
LOGGER.debug('Creating a new connection for %s', self.pid)
# Create a new PostgreSQL connection
kwargs = utils.uri_to_kwargs(self._uri)
try:
connection = self._psycopg2_connect(kwargs)
except (psycopg2.Error, OSError, socket.err... | [
"def",
"_create_connection",
"(",
"self",
",",
"future",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'Creating a new connection for %s'",
",",
"self",
".",
"pid",
")",
"# Create a new PostgreSQL connection",
"kwargs",
"=",
"utils",
".",
"uri_to_kwargs",
"(",
"self",
"... | Create a new PostgreSQL connection
:param tornado.concurrent.Future future: future for new conn result | [
"Create",
"a",
"new",
"PostgreSQL",
"connection"
] | a68855013dc6aaf9ed7b6909a4701f8da8796a0a | https://github.com/gmr/queries/blob/a68855013dc6aaf9ed7b6909a4701f8da8796a0a/queries/tornado_session.py#L269-L336 |
417 | gmr/queries | queries/tornado_session.py | TornadoSession._exec_cleanup | def _exec_cleanup(self, cursor, fd):
"""Close the cursor, remove any references to the fd in internal state
and remove the fd from the ioloop.
:param psycopg2.extensions.cursor cursor: The cursor to close
:param int fd: The connection file descriptor
"""
LOGGER.debug('C... | python | def _exec_cleanup(self, cursor, fd):
LOGGER.debug('Closing cursor and cleaning %s', fd)
try:
cursor.close()
except (psycopg2.Error, psycopg2.Warning) as error:
LOGGER.debug('Error closing the cursor: %s', error)
self._cleanup_fd(fd)
# If the cleanup call... | [
"def",
"_exec_cleanup",
"(",
"self",
",",
"cursor",
",",
"fd",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'Closing cursor and cleaning %s'",
",",
"fd",
")",
"try",
":",
"cursor",
".",
"close",
"(",
")",
"except",
"(",
"psycopg2",
".",
"Error",
",",
"psycopg... | Close the cursor, remove any references to the fd in internal state
and remove the fd from the ioloop.
:param psycopg2.extensions.cursor cursor: The cursor to close
:param int fd: The connection file descriptor | [
"Close",
"the",
"cursor",
"remove",
"any",
"references",
"to",
"the",
"fd",
"in",
"internal",
"state",
"and",
"remove",
"the",
"fd",
"from",
"the",
"ioloop",
"."
] | a68855013dc6aaf9ed7b6909a4701f8da8796a0a | https://github.com/gmr/queries/blob/a68855013dc6aaf9ed7b6909a4701f8da8796a0a/queries/tornado_session.py#L408-L431 |
418 | gmr/queries | queries/tornado_session.py | TornadoSession._cleanup_fd | def _cleanup_fd(self, fd, close=False):
"""Ensure the socket socket is removed from the IOLoop, the
connection stack, and futures stack.
:param int fd: The fd # to cleanup
"""
self._ioloop.remove_handler(fd)
if fd in self._connections:
try:
s... | python | def _cleanup_fd(self, fd, close=False):
self._ioloop.remove_handler(fd)
if fd in self._connections:
try:
self._pool_manager.free(self.pid, self._connections[fd])
except pool.ConnectionNotFoundError:
pass
if close:
self._... | [
"def",
"_cleanup_fd",
"(",
"self",
",",
"fd",
",",
"close",
"=",
"False",
")",
":",
"self",
".",
"_ioloop",
".",
"remove_handler",
"(",
"fd",
")",
"if",
"fd",
"in",
"self",
".",
"_connections",
":",
"try",
":",
"self",
".",
"_pool_manager",
".",
"fre... | Ensure the socket socket is removed from the IOLoop, the
connection stack, and futures stack.
:param int fd: The fd # to cleanup | [
"Ensure",
"the",
"socket",
"socket",
"is",
"removed",
"from",
"the",
"IOLoop",
"the",
"connection",
"stack",
"and",
"futures",
"stack",
"."
] | a68855013dc6aaf9ed7b6909a4701f8da8796a0a | https://github.com/gmr/queries/blob/a68855013dc6aaf9ed7b6909a4701f8da8796a0a/queries/tornado_session.py#L433-L450 |
419 | gmr/queries | queries/tornado_session.py | TornadoSession._on_io_events | def _on_io_events(self, fd=None, _events=None):
"""Invoked by Tornado's IOLoop when there are events for the fd
:param int fd: The file descriptor for the event
:param int _events: The events raised
"""
if fd not in self._connections:
LOGGER.warning('Received IO eve... | python | def _on_io_events(self, fd=None, _events=None):
if fd not in self._connections:
LOGGER.warning('Received IO event for non-existing connection')
return
self._poll_connection(fd) | [
"def",
"_on_io_events",
"(",
"self",
",",
"fd",
"=",
"None",
",",
"_events",
"=",
"None",
")",
":",
"if",
"fd",
"not",
"in",
"self",
".",
"_connections",
":",
"LOGGER",
".",
"warning",
"(",
"'Received IO event for non-existing connection'",
")",
"return",
"s... | Invoked by Tornado's IOLoop when there are events for the fd
:param int fd: The file descriptor for the event
:param int _events: The events raised | [
"Invoked",
"by",
"Tornado",
"s",
"IOLoop",
"when",
"there",
"are",
"events",
"for",
"the",
"fd"
] | a68855013dc6aaf9ed7b6909a4701f8da8796a0a | https://github.com/gmr/queries/blob/a68855013dc6aaf9ed7b6909a4701f8da8796a0a/queries/tornado_session.py#L468-L478 |
420 | gmr/queries | queries/tornado_session.py | TornadoSession._poll_connection | def _poll_connection(self, fd):
"""Check with psycopg2 to see what action to take. If the state is
POLL_OK, we should have a pending callback for that fd.
:param int fd: The socket fd for the postgresql connection
"""
try:
state = self._connections[fd].poll()
... | python | def _poll_connection(self, fd):
try:
state = self._connections[fd].poll()
except (OSError, socket.error) as error:
self._ioloop.remove_handler(fd)
if fd in self._futures and not self._futures[fd].done():
self._futures[fd].set_exception(
... | [
"def",
"_poll_connection",
"(",
"self",
",",
"fd",
")",
":",
"try",
":",
"state",
"=",
"self",
".",
"_connections",
"[",
"fd",
"]",
".",
"poll",
"(",
")",
"except",
"(",
"OSError",
",",
"socket",
".",
"error",
")",
"as",
"error",
":",
"self",
".",
... | Check with psycopg2 to see what action to take. If the state is
POLL_OK, we should have a pending callback for that fd.
:param int fd: The socket fd for the postgresql connection | [
"Check",
"with",
"psycopg2",
"to",
"see",
"what",
"action",
"to",
"take",
".",
"If",
"the",
"state",
"is",
"POLL_OK",
"we",
"should",
"have",
"a",
"pending",
"callback",
"for",
"that",
"fd",
"."
] | a68855013dc6aaf9ed7b6909a4701f8da8796a0a | https://github.com/gmr/queries/blob/a68855013dc6aaf9ed7b6909a4701f8da8796a0a/queries/tornado_session.py#L480-L510 |
421 | jquast/wcwidth | setup.py | main | def main():
"""Setup.py entry point."""
import codecs
setuptools.setup(
name='wcwidth',
version='0.1.7',
description=("Measures number of Terminal column cells "
"of wide-character codes"),
long_description=codecs.open(
os.path.join(HERE, 'REA... | python | def main():
import codecs
setuptools.setup(
name='wcwidth',
version='0.1.7',
description=("Measures number of Terminal column cells "
"of wide-character codes"),
long_description=codecs.open(
os.path.join(HERE, 'README.rst'), 'r', 'utf8').read(),
... | [
"def",
"main",
"(",
")",
":",
"import",
"codecs",
"setuptools",
".",
"setup",
"(",
"name",
"=",
"'wcwidth'",
",",
"version",
"=",
"'0.1.7'",
",",
"description",
"=",
"(",
"\"Measures number of Terminal column cells \"",
"\"of wide-character codes\"",
")",
",",
"lo... | Setup.py entry point. | [
"Setup",
".",
"py",
"entry",
"point",
"."
] | 78800b68911880ef4ef95ae83886154710441871 | https://github.com/jquast/wcwidth/blob/78800b68911880ef4ef95ae83886154710441871/setup.py#L271-L307 |
422 | jquast/wcwidth | setup.py | SetupUpdate._do_readme_update | def _do_readme_update(self):
"""Patch README.rst to reflect the data files used in release."""
import codecs
import glob
# read in,
data_in = codecs.open(
os.path.join(HERE, 'README.rst'), 'r', 'utf8').read()
# search for beginning and end positions,
... | python | def _do_readme_update(self):
import codecs
import glob
# read in,
data_in = codecs.open(
os.path.join(HERE, 'README.rst'), 'r', 'utf8').read()
# search for beginning and end positions,
pos_begin = data_in.find(self.README_PATCH_FROM)
assert pos_begin... | [
"def",
"_do_readme_update",
"(",
"self",
")",
":",
"import",
"codecs",
"import",
"glob",
"# read in,",
"data_in",
"=",
"codecs",
".",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"HERE",
",",
"'README.rst'",
")",
",",
"'r'",
",",
"'utf8'",
")",
".... | Patch README.rst to reflect the data files used in release. | [
"Patch",
"README",
".",
"rst",
"to",
"reflect",
"the",
"data",
"files",
"used",
"in",
"release",
"."
] | 78800b68911880ef4ef95ae83886154710441871 | https://github.com/jquast/wcwidth/blob/78800b68911880ef4ef95ae83886154710441871/setup.py#L78-L112 |
423 | jquast/wcwidth | setup.py | SetupUpdate._do_east_asian | def _do_east_asian(self):
"""Fetch and update east-asian tables."""
self._do_retrieve(self.EAW_URL, self.EAW_IN)
(version, date, values) = self._parse_east_asian(
fname=self.EAW_IN,
properties=(u'W', u'F',)
)
table = self._make_table(values)
self._... | python | def _do_east_asian(self):
self._do_retrieve(self.EAW_URL, self.EAW_IN)
(version, date, values) = self._parse_east_asian(
fname=self.EAW_IN,
properties=(u'W', u'F',)
)
table = self._make_table(values)
self._do_write(self.EAW_OUT, 'WIDE_EASTASIAN', version, ... | [
"def",
"_do_east_asian",
"(",
"self",
")",
":",
"self",
".",
"_do_retrieve",
"(",
"self",
".",
"EAW_URL",
",",
"self",
".",
"EAW_IN",
")",
"(",
"version",
",",
"date",
",",
"values",
")",
"=",
"self",
".",
"_parse_east_asian",
"(",
"fname",
"=",
"self"... | Fetch and update east-asian tables. | [
"Fetch",
"and",
"update",
"east",
"-",
"asian",
"tables",
"."
] | 78800b68911880ef4ef95ae83886154710441871 | https://github.com/jquast/wcwidth/blob/78800b68911880ef4ef95ae83886154710441871/setup.py#L114-L122 |
424 | jquast/wcwidth | setup.py | SetupUpdate._do_zero_width | def _do_zero_width(self):
"""Fetch and update zero width tables."""
self._do_retrieve(self.UCD_URL, self.UCD_IN)
(version, date, values) = self._parse_category(
fname=self.UCD_IN,
categories=('Me', 'Mn',)
)
table = self._make_table(values)
self._do... | python | def _do_zero_width(self):
self._do_retrieve(self.UCD_URL, self.UCD_IN)
(version, date, values) = self._parse_category(
fname=self.UCD_IN,
categories=('Me', 'Mn',)
)
table = self._make_table(values)
self._do_write(self.ZERO_OUT, 'ZERO_WIDTH', version, date,... | [
"def",
"_do_zero_width",
"(",
"self",
")",
":",
"self",
".",
"_do_retrieve",
"(",
"self",
".",
"UCD_URL",
",",
"self",
".",
"UCD_IN",
")",
"(",
"version",
",",
"date",
",",
"values",
")",
"=",
"self",
".",
"_parse_category",
"(",
"fname",
"=",
"self",
... | Fetch and update zero width tables. | [
"Fetch",
"and",
"update",
"zero",
"width",
"tables",
"."
] | 78800b68911880ef4ef95ae83886154710441871 | https://github.com/jquast/wcwidth/blob/78800b68911880ef4ef95ae83886154710441871/setup.py#L124-L132 |
425 | jquast/wcwidth | setup.py | SetupUpdate._make_table | def _make_table(values):
"""Return a tuple of lookup tables for given values."""
import collections
table = collections.deque()
start, end = values[0], values[0]
for num, value in enumerate(values):
if num == 0:
table.append((value, value,))
... | python | def _make_table(values):
import collections
table = collections.deque()
start, end = values[0], values[0]
for num, value in enumerate(values):
if num == 0:
table.append((value, value,))
continue
start, end = table.pop()
... | [
"def",
"_make_table",
"(",
"values",
")",
":",
"import",
"collections",
"table",
"=",
"collections",
".",
"deque",
"(",
")",
"start",
",",
"end",
"=",
"values",
"[",
"0",
"]",
",",
"values",
"[",
"0",
"]",
"for",
"num",
",",
"value",
"in",
"enumerate... | Return a tuple of lookup tables for given values. | [
"Return",
"a",
"tuple",
"of",
"lookup",
"tables",
"for",
"given",
"values",
"."
] | 78800b68911880ef4ef95ae83886154710441871 | https://github.com/jquast/wcwidth/blob/78800b68911880ef4ef95ae83886154710441871/setup.py#L135-L150 |
426 | jquast/wcwidth | setup.py | SetupUpdate._do_retrieve | def _do_retrieve(url, fname):
"""Retrieve given url to target filepath fname."""
folder = os.path.dirname(fname)
if not os.path.exists(folder):
os.makedirs(folder)
print("{}/ created.".format(folder))
if not os.path.exists(fname):
with open(fname, 'wb'... | python | def _do_retrieve(url, fname):
folder = os.path.dirname(fname)
if not os.path.exists(folder):
os.makedirs(folder)
print("{}/ created.".format(folder))
if not os.path.exists(fname):
with open(fname, 'wb') as fout:
print("retrieving {}.".format(ur... | [
"def",
"_do_retrieve",
"(",
"url",
",",
"fname",
")",
":",
"folder",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"fname",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"folder",
")",
":",
"os",
".",
"makedirs",
"(",
"folder",
")",
"pr... | Retrieve given url to target filepath fname. | [
"Retrieve",
"given",
"url",
"to",
"target",
"filepath",
"fname",
"."
] | 78800b68911880ef4ef95ae83886154710441871 | https://github.com/jquast/wcwidth/blob/78800b68911880ef4ef95ae83886154710441871/setup.py#L153-L167 |
427 | jquast/wcwidth | setup.py | SetupUpdate._parse_east_asian | def _parse_east_asian(fname, properties=(u'W', u'F',)):
"""Parse unicode east-asian width tables."""
version, date, values = None, None, []
print("parsing {} ..".format(fname))
for line in open(fname, 'rb'):
uline = line.decode('utf-8')
if version is None:
... | python | def _parse_east_asian(fname, properties=(u'W', u'F',)):
version, date, values = None, None, []
print("parsing {} ..".format(fname))
for line in open(fname, 'rb'):
uline = line.decode('utf-8')
if version is None:
version = uline.split(None, 1)[1].rstrip()
... | [
"def",
"_parse_east_asian",
"(",
"fname",
",",
"properties",
"=",
"(",
"u'W'",
",",
"u'F'",
",",
")",
")",
":",
"version",
",",
"date",
",",
"values",
"=",
"None",
",",
"None",
",",
"[",
"]",
"print",
"(",
"\"parsing {} ..\"",
".",
"format",
"(",
"fn... | Parse unicode east-asian width tables. | [
"Parse",
"unicode",
"east",
"-",
"asian",
"width",
"tables",
"."
] | 78800b68911880ef4ef95ae83886154710441871 | https://github.com/jquast/wcwidth/blob/78800b68911880ef4ef95ae83886154710441871/setup.py#L180-L201 |
428 | jquast/wcwidth | setup.py | SetupUpdate._parse_category | def _parse_category(fname, categories):
"""Parse unicode category tables."""
version, date, values = None, None, []
print("parsing {} ..".format(fname))
for line in open(fname, 'rb'):
uline = line.decode('utf-8')
if version is None:
version = uline... | python | def _parse_category(fname, categories):
version, date, values = None, None, []
print("parsing {} ..".format(fname))
for line in open(fname, 'rb'):
uline = line.decode('utf-8')
if version is None:
version = uline.split(None, 1)[1].rstrip()
c... | [
"def",
"_parse_category",
"(",
"fname",
",",
"categories",
")",
":",
"version",
",",
"date",
",",
"values",
"=",
"None",
",",
"None",
",",
"[",
"]",
"print",
"(",
"\"parsing {} ..\"",
".",
"format",
"(",
"fname",
")",
")",
"for",
"line",
"in",
"open",
... | Parse unicode category tables. | [
"Parse",
"unicode",
"category",
"tables",
"."
] | 78800b68911880ef4ef95ae83886154710441871 | https://github.com/jquast/wcwidth/blob/78800b68911880ef4ef95ae83886154710441871/setup.py#L204-L226 |
429 | jquast/wcwidth | setup.py | SetupUpdate._do_write | def _do_write(fname, variable, version, date, table):
"""Write combining tables to filesystem as python code."""
# pylint: disable=R0914
# Too many local variables (19/15) (col 4)
print("writing {} ..".format(fname))
import unicodedata
import datetime
impo... | python | def _do_write(fname, variable, version, date, table):
# pylint: disable=R0914
# Too many local variables (19/15) (col 4)
print("writing {} ..".format(fname))
import unicodedata
import datetime
import string
utc_now = datetime.datetime.utcnow()
inde... | [
"def",
"_do_write",
"(",
"fname",
",",
"variable",
",",
"version",
",",
"date",
",",
"table",
")",
":",
"# pylint: disable=R0914",
"# Too many local variables (19/15) (col 4)",
"print",
"(",
"\"writing {} ..\"",
".",
"format",
"(",
"fname",
")",
")",
"import... | Write combining tables to filesystem as python code. | [
"Write",
"combining",
"tables",
"to",
"filesystem",
"as",
"python",
"code",
"."
] | 78800b68911880ef4ef95ae83886154710441871 | https://github.com/jquast/wcwidth/blob/78800b68911880ef4ef95ae83886154710441871/setup.py#L229-L268 |
430 | jquast/wcwidth | bin/wcwidth-libc-comparator.py | report_ucs_msg | def report_ucs_msg(ucs, wcwidth_libc, wcwidth_local):
"""
Return string report of combining character differences.
:param ucs: unicode point.
:type ucs: unicode
:param wcwidth_libc: libc-wcwidth's reported character length.
:type comb_py: int
:param wcwidth_local: wcwidth's reported charact... | python | def report_ucs_msg(ucs, wcwidth_libc, wcwidth_local):
ucp = (ucs.encode('unicode_escape')[2:]
.decode('ascii')
.upper()
.lstrip('0'))
url = "http://codepoints.net/U+{}".format(ucp)
name = unicodedata.name(ucs)
return (u"libc,ours={},{} [--o{}o--] name={} val={} {}"
... | [
"def",
"report_ucs_msg",
"(",
"ucs",
",",
"wcwidth_libc",
",",
"wcwidth_local",
")",
":",
"ucp",
"=",
"(",
"ucs",
".",
"encode",
"(",
"'unicode_escape'",
")",
"[",
"2",
":",
"]",
".",
"decode",
"(",
"'ascii'",
")",
".",
"upper",
"(",
")",
".",
"lstri... | Return string report of combining character differences.
:param ucs: unicode point.
:type ucs: unicode
:param wcwidth_libc: libc-wcwidth's reported character length.
:type comb_py: int
:param wcwidth_local: wcwidth's reported character length.
:type comb_wc: int
:rtype: unicode | [
"Return",
"string",
"report",
"of",
"combining",
"character",
"differences",
"."
] | 78800b68911880ef4ef95ae83886154710441871 | https://github.com/jquast/wcwidth/blob/78800b68911880ef4ef95ae83886154710441871/bin/wcwidth-libc-comparator.py#L44-L63 |
431 | jquast/wcwidth | bin/wcwidth-browser.py | validate_args | def validate_args(opts):
"""Validate and return options provided by docopt parsing."""
if opts['--wide'] is None:
opts['--wide'] = 2
else:
assert opts['--wide'] in ("1", "2"), opts['--wide']
if opts['--alignment'] is None:
opts['--alignment'] = 'left'
else:
assert opt... | python | def validate_args(opts):
if opts['--wide'] is None:
opts['--wide'] = 2
else:
assert opts['--wide'] in ("1", "2"), opts['--wide']
if opts['--alignment'] is None:
opts['--alignment'] = 'left'
else:
assert opts['--alignment'] in ('left', 'right'), opts['--alignment']
opt... | [
"def",
"validate_args",
"(",
"opts",
")",
":",
"if",
"opts",
"[",
"'--wide'",
"]",
"is",
"None",
":",
"opts",
"[",
"'--wide'",
"]",
"=",
"2",
"else",
":",
"assert",
"opts",
"[",
"'--wide'",
"]",
"in",
"(",
"\"1\"",
",",
"\"2\"",
")",
",",
"opts",
... | Validate and return options provided by docopt parsing. | [
"Validate",
"and",
"return",
"options",
"provided",
"by",
"docopt",
"parsing",
"."
] | 78800b68911880ef4ef95ae83886154710441871 | https://github.com/jquast/wcwidth/blob/78800b68911880ef4ef95ae83886154710441871/bin/wcwidth-browser.py#L661-L675 |
432 | jquast/wcwidth | bin/wcwidth-browser.py | Screen.hint_width | def hint_width(self):
"""Width of a column segment."""
return sum((len(self.style.delimiter),
self.wide,
len(self.style.delimiter),
len(u' '),
UCS_PRINTLEN + 2,
len(u' '),
self.style.n... | python | def hint_width(self):
return sum((len(self.style.delimiter),
self.wide,
len(self.style.delimiter),
len(u' '),
UCS_PRINTLEN + 2,
len(u' '),
self.style.name_len,)) | [
"def",
"hint_width",
"(",
"self",
")",
":",
"return",
"sum",
"(",
"(",
"len",
"(",
"self",
".",
"style",
".",
"delimiter",
")",
",",
"self",
".",
"wide",
",",
"len",
"(",
"self",
".",
"style",
".",
"delimiter",
")",
",",
"len",
"(",
"u' '",
")",
... | Width of a column segment. | [
"Width",
"of",
"a",
"column",
"segment",
"."
] | 78800b68911880ef4ef95ae83886154710441871 | https://github.com/jquast/wcwidth/blob/78800b68911880ef4ef95ae83886154710441871/bin/wcwidth-browser.py#L220-L228 |
433 | jquast/wcwidth | bin/wcwidth-browser.py | Screen.head_item | def head_item(self):
"""Text of a single column heading."""
delimiter = self.style.attr_minor(self.style.delimiter)
hint = self.style.header_hint * self.wide
heading = (u'{delimiter}{hint}{delimiter}'
.format(delimiter=delimiter, hint=hint))
alignment = lambda ... | python | def head_item(self):
delimiter = self.style.attr_minor(self.style.delimiter)
hint = self.style.header_hint * self.wide
heading = (u'{delimiter}{hint}{delimiter}'
.format(delimiter=delimiter, hint=hint))
alignment = lambda *args: (
self.term.rjust(*args) if ... | [
"def",
"head_item",
"(",
"self",
")",
":",
"delimiter",
"=",
"self",
".",
"style",
".",
"attr_minor",
"(",
"self",
".",
"style",
".",
"delimiter",
")",
"hint",
"=",
"self",
".",
"style",
".",
"header_hint",
"*",
"self",
".",
"wide",
"heading",
"=",
"... | Text of a single column heading. | [
"Text",
"of",
"a",
"single",
"column",
"heading",
"."
] | 78800b68911880ef4ef95ae83886154710441871 | https://github.com/jquast/wcwidth/blob/78800b68911880ef4ef95ae83886154710441871/bin/wcwidth-browser.py#L231-L241 |
434 | jquast/wcwidth | bin/wcwidth-browser.py | Screen.msg_intro | def msg_intro(self):
"""Introductory message disabled above heading."""
delim = self.style.attr_minor(self.style.delimiter)
txt = self.intro_msg_fmt.format(delim=delim).rstrip()
return self.term.center(txt) | python | def msg_intro(self):
delim = self.style.attr_minor(self.style.delimiter)
txt = self.intro_msg_fmt.format(delim=delim).rstrip()
return self.term.center(txt) | [
"def",
"msg_intro",
"(",
"self",
")",
":",
"delim",
"=",
"self",
".",
"style",
".",
"attr_minor",
"(",
"self",
".",
"style",
".",
"delimiter",
")",
"txt",
"=",
"self",
".",
"intro_msg_fmt",
".",
"format",
"(",
"delim",
"=",
"delim",
")",
".",
"rstrip... | Introductory message disabled above heading. | [
"Introductory",
"message",
"disabled",
"above",
"heading",
"."
] | 78800b68911880ef4ef95ae83886154710441871 | https://github.com/jquast/wcwidth/blob/78800b68911880ef4ef95ae83886154710441871/bin/wcwidth-browser.py#L244-L248 |
435 | jquast/wcwidth | bin/wcwidth-browser.py | Screen.num_columns | def num_columns(self):
"""Number of columns displayed."""
if self.term.is_a_tty:
return self.term.width // self.hint_width
return 1 | python | def num_columns(self):
if self.term.is_a_tty:
return self.term.width // self.hint_width
return 1 | [
"def",
"num_columns",
"(",
"self",
")",
":",
"if",
"self",
".",
"term",
".",
"is_a_tty",
":",
"return",
"self",
".",
"term",
".",
"width",
"//",
"self",
".",
"hint_width",
"return",
"1"
] | Number of columns displayed. | [
"Number",
"of",
"columns",
"displayed",
"."
] | 78800b68911880ef4ef95ae83886154710441871 | https://github.com/jquast/wcwidth/blob/78800b68911880ef4ef95ae83886154710441871/bin/wcwidth-browser.py#L256-L260 |
436 | jquast/wcwidth | bin/wcwidth-browser.py | Pager.on_resize | def on_resize(self, *args):
"""Signal handler callback for SIGWINCH."""
# pylint: disable=W0613
# Unused argument 'args'
self.screen.style.name_len = min(self.screen.style.name_len,
self.term.width - 15)
assert self.term.width >= s... | python | def on_resize(self, *args):
# pylint: disable=W0613
# Unused argument 'args'
self.screen.style.name_len = min(self.screen.style.name_len,
self.term.width - 15)
assert self.term.width >= self.screen.hint_width, (
'Screen to smal... | [
"def",
"on_resize",
"(",
"self",
",",
"*",
"args",
")",
":",
"# pylint: disable=W0613",
"# Unused argument 'args'",
"self",
".",
"screen",
".",
"style",
".",
"name_len",
"=",
"min",
"(",
"self",
".",
"screen",
".",
"style",
".",
"name_len",
",",
"sel... | Signal handler callback for SIGWINCH. | [
"Signal",
"handler",
"callback",
"for",
"SIGWINCH",
"."
] | 78800b68911880ef4ef95ae83886154710441871 | https://github.com/jquast/wcwidth/blob/78800b68911880ef4ef95ae83886154710441871/bin/wcwidth-browser.py#L305-L315 |
437 | jquast/wcwidth | bin/wcwidth-browser.py | Pager._set_lastpage | def _set_lastpage(self):
"""Calculate value of class attribute ``last_page``."""
self.last_page = (len(self._page_data) - 1) // self.screen.page_size | python | def _set_lastpage(self):
self.last_page = (len(self._page_data) - 1) // self.screen.page_size | [
"def",
"_set_lastpage",
"(",
"self",
")",
":",
"self",
".",
"last_page",
"=",
"(",
"len",
"(",
"self",
".",
"_page_data",
")",
"-",
"1",
")",
"//",
"self",
".",
"screen",
".",
"page_size"
] | Calculate value of class attribute ``last_page``. | [
"Calculate",
"value",
"of",
"class",
"attribute",
"last_page",
"."
] | 78800b68911880ef4ef95ae83886154710441871 | https://github.com/jquast/wcwidth/blob/78800b68911880ef4ef95ae83886154710441871/bin/wcwidth-browser.py#L317-L319 |
438 | jquast/wcwidth | bin/wcwidth-browser.py | Pager.display_initialize | def display_initialize(self):
"""Display 'please wait' message, and narrow build warning."""
echo(self.term.home + self.term.clear)
echo(self.term.move_y(self.term.height // 2))
echo(self.term.center('Initializing page data ...').rstrip())
flushout()
if LIMIT_UCS == 0x10... | python | def display_initialize(self):
echo(self.term.home + self.term.clear)
echo(self.term.move_y(self.term.height // 2))
echo(self.term.center('Initializing page data ...').rstrip())
flushout()
if LIMIT_UCS == 0x10000:
echo('\n\n')
echo(self.term.blink_red(self... | [
"def",
"display_initialize",
"(",
"self",
")",
":",
"echo",
"(",
"self",
".",
"term",
".",
"home",
"+",
"self",
".",
"term",
".",
"clear",
")",
"echo",
"(",
"self",
".",
"term",
".",
"move_y",
"(",
"self",
".",
"term",
".",
"height",
"//",
"2",
"... | Display 'please wait' message, and narrow build warning. | [
"Display",
"please",
"wait",
"message",
"and",
"narrow",
"build",
"warning",
"."
] | 78800b68911880ef4ef95ae83886154710441871 | https://github.com/jquast/wcwidth/blob/78800b68911880ef4ef95ae83886154710441871/bin/wcwidth-browser.py#L321-L334 |
439 | jquast/wcwidth | bin/wcwidth-browser.py | Pager.initialize_page_data | def initialize_page_data(self):
"""Initialize the page data for the given screen."""
if self.term.is_a_tty:
self.display_initialize()
self.character_generator = self.character_factory(self.screen.wide)
page_data = list()
while True:
try:
pa... | python | def initialize_page_data(self):
if self.term.is_a_tty:
self.display_initialize()
self.character_generator = self.character_factory(self.screen.wide)
page_data = list()
while True:
try:
page_data.append(next(self.character_generator))
ex... | [
"def",
"initialize_page_data",
"(",
"self",
")",
":",
"if",
"self",
".",
"term",
".",
"is_a_tty",
":",
"self",
".",
"display_initialize",
"(",
")",
"self",
".",
"character_generator",
"=",
"self",
".",
"character_factory",
"(",
"self",
".",
"screen",
".",
... | Initialize the page data for the given screen. | [
"Initialize",
"the",
"page",
"data",
"for",
"the",
"given",
"screen",
"."
] | 78800b68911880ef4ef95ae83886154710441871 | https://github.com/jquast/wcwidth/blob/78800b68911880ef4ef95ae83886154710441871/bin/wcwidth-browser.py#L336-L351 |
440 | jquast/wcwidth | bin/wcwidth-browser.py | Pager.page_data | def page_data(self, idx, offset):
"""
Return character data for page of given index and offset.
:param idx: page index.
:type idx: int
:param offset: scrolling region offset of current page.
:type offset: int
:returns: list of tuples in form of ``(ucs, name)``
... | python | def page_data(self, idx, offset):
size = self.screen.page_size
while offset < 0 and idx:
offset += size
idx -= 1
offset = max(0, offset)
while offset >= size:
offset -= size
idx += 1
if idx == self.last_page:
offset =... | [
"def",
"page_data",
"(",
"self",
",",
"idx",
",",
"offset",
")",
":",
"size",
"=",
"self",
".",
"screen",
".",
"page_size",
"while",
"offset",
"<",
"0",
"and",
"idx",
":",
"offset",
"+=",
"size",
"idx",
"-=",
"1",
"offset",
"=",
"max",
"(",
"0",
... | Return character data for page of given index and offset.
:param idx: page index.
:type idx: int
:param offset: scrolling region offset of current page.
:type offset: int
:returns: list of tuples in form of ``(ucs, name)``
:rtype: list[(unicode, unicode)] | [
"Return",
"character",
"data",
"for",
"page",
"of",
"given",
"index",
"and",
"offset",
"."
] | 78800b68911880ef4ef95ae83886154710441871 | https://github.com/jquast/wcwidth/blob/78800b68911880ef4ef95ae83886154710441871/bin/wcwidth-browser.py#L353-L381 |
441 | jquast/wcwidth | bin/wcwidth-browser.py | Pager._run_notty | def _run_notty(self, writer):
"""Pager run method for terminals that are not a tty."""
page_idx = page_offset = 0
while True:
npage_idx, _ = self.draw(writer, page_idx + 1, page_offset)
if npage_idx == self.last_page:
# page displayed was last page, quit.
... | python | def _run_notty(self, writer):
page_idx = page_offset = 0
while True:
npage_idx, _ = self.draw(writer, page_idx + 1, page_offset)
if npage_idx == self.last_page:
# page displayed was last page, quit.
break
page_idx = npage_idx
... | [
"def",
"_run_notty",
"(",
"self",
",",
"writer",
")",
":",
"page_idx",
"=",
"page_offset",
"=",
"0",
"while",
"True",
":",
"npage_idx",
",",
"_",
"=",
"self",
".",
"draw",
"(",
"writer",
",",
"page_idx",
"+",
"1",
",",
"page_offset",
")",
"if",
"npag... | Pager run method for terminals that are not a tty. | [
"Pager",
"run",
"method",
"for",
"terminals",
"that",
"are",
"not",
"a",
"tty",
"."
] | 78800b68911880ef4ef95ae83886154710441871 | https://github.com/jquast/wcwidth/blob/78800b68911880ef4ef95ae83886154710441871/bin/wcwidth-browser.py#L383-L393 |
442 | jquast/wcwidth | bin/wcwidth-browser.py | Pager._run_tty | def _run_tty(self, writer, reader):
"""Pager run method for terminals that are a tty."""
# allow window-change signal to reflow screen
signal.signal(signal.SIGWINCH, self.on_resize)
page_idx = page_offset = 0
while True:
if self.dirty:
page_idx, page_... | python | def _run_tty(self, writer, reader):
# allow window-change signal to reflow screen
signal.signal(signal.SIGWINCH, self.on_resize)
page_idx = page_offset = 0
while True:
if self.dirty:
page_idx, page_offset = self.draw(writer,
... | [
"def",
"_run_tty",
"(",
"self",
",",
"writer",
",",
"reader",
")",
":",
"# allow window-change signal to reflow screen",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGWINCH",
",",
"self",
".",
"on_resize",
")",
"page_idx",
"=",
"page_offset",
"=",
"0",
"whi... | Pager run method for terminals that are a tty. | [
"Pager",
"run",
"method",
"for",
"terminals",
"that",
"are",
"a",
"tty",
"."
] | 78800b68911880ef4ef95ae83886154710441871 | https://github.com/jquast/wcwidth/blob/78800b68911880ef4ef95ae83886154710441871/bin/wcwidth-browser.py#L395-L416 |
443 | jquast/wcwidth | bin/wcwidth-browser.py | Pager.run | def run(self, writer, reader):
"""
Pager entry point.
In interactive mode (terminal is a tty), run until
``process_keystroke()`` detects quit keystroke ('q'). In
non-interactive mode, exit after displaying all unicode points.
:param writer: callable writes to output st... | python | def run(self, writer, reader):
self._page_data = self.initialize_page_data()
self._set_lastpage()
if not self.term.is_a_tty:
self._run_notty(writer)
else:
self._run_tty(writer, reader) | [
"def",
"run",
"(",
"self",
",",
"writer",
",",
"reader",
")",
":",
"self",
".",
"_page_data",
"=",
"self",
".",
"initialize_page_data",
"(",
")",
"self",
".",
"_set_lastpage",
"(",
")",
"if",
"not",
"self",
".",
"term",
".",
"is_a_tty",
":",
"self",
... | Pager entry point.
In interactive mode (terminal is a tty), run until
``process_keystroke()`` detects quit keystroke ('q'). In
non-interactive mode, exit after displaying all unicode points.
:param writer: callable writes to output stream, receiving unicode.
:type writer: call... | [
"Pager",
"entry",
"point",
"."
] | 78800b68911880ef4ef95ae83886154710441871 | https://github.com/jquast/wcwidth/blob/78800b68911880ef4ef95ae83886154710441871/bin/wcwidth-browser.py#L418-L437 |
444 | jquast/wcwidth | bin/wcwidth-browser.py | Pager.process_keystroke | def process_keystroke(self, inp, idx, offset):
"""
Process keystroke ``inp``, adjusting screen parameters.
:param inp: return value of Terminal.inkey().
:type inp: blessed.keyboard.Keystroke
:param idx: page index.
:type idx: int
:param offset: scrolling region o... | python | def process_keystroke(self, inp, idx, offset):
if inp.lower() in (u'q', u'Q'):
# exit
return (-1, -1)
self._process_keystroke_commands(inp)
idx, offset = self._process_keystroke_movement(inp, idx, offset)
return idx, offset | [
"def",
"process_keystroke",
"(",
"self",
",",
"inp",
",",
"idx",
",",
"offset",
")",
":",
"if",
"inp",
".",
"lower",
"(",
")",
"in",
"(",
"u'q'",
",",
"u'Q'",
")",
":",
"# exit",
"return",
"(",
"-",
"1",
",",
"-",
"1",
")",
"self",
".",
"_proce... | Process keystroke ``inp``, adjusting screen parameters.
:param inp: return value of Terminal.inkey().
:type inp: blessed.keyboard.Keystroke
:param idx: page index.
:type idx: int
:param offset: scrolling region offset of current page.
:type offset: int
:returns: ... | [
"Process",
"keystroke",
"inp",
"adjusting",
"screen",
"parameters",
"."
] | 78800b68911880ef4ef95ae83886154710441871 | https://github.com/jquast/wcwidth/blob/78800b68911880ef4ef95ae83886154710441871/bin/wcwidth-browser.py#L439-L457 |
445 | jquast/wcwidth | bin/wcwidth-browser.py | Pager._process_keystroke_movement | def _process_keystroke_movement(self, inp, idx, offset):
"""Process keystrokes that adjust index and offset."""
term = self.term
if inp in (u'y', u'k') or inp.code in (term.KEY_UP,):
# scroll backward 1 line
idx, offset = (idx, offset - self.screen.num_columns)
el... | python | def _process_keystroke_movement(self, inp, idx, offset):
term = self.term
if inp in (u'y', u'k') or inp.code in (term.KEY_UP,):
# scroll backward 1 line
idx, offset = (idx, offset - self.screen.num_columns)
elif inp in (u'e', u'j') or inp.code in (term.KEY_ENTER,
... | [
"def",
"_process_keystroke_movement",
"(",
"self",
",",
"inp",
",",
"idx",
",",
"offset",
")",
":",
"term",
"=",
"self",
".",
"term",
"if",
"inp",
"in",
"(",
"u'y'",
",",
"u'k'",
")",
"or",
"inp",
".",
"code",
"in",
"(",
"term",
".",
"KEY_UP",
",",... | Process keystrokes that adjust index and offset. | [
"Process",
"keystrokes",
"that",
"adjust",
"index",
"and",
"offset",
"."
] | 78800b68911880ef4ef95ae83886154710441871 | https://github.com/jquast/wcwidth/blob/78800b68911880ef4ef95ae83886154710441871/bin/wcwidth-browser.py#L483-L511 |
446 | jquast/wcwidth | bin/wcwidth-browser.py | Pager.draw | def draw(self, writer, idx, offset):
"""
Draw the current page view to ``writer``.
:param writer: callable writes to output stream, receiving unicode.
:type writer: callable
:param idx: current page index.
:type idx: int
:param offset: scrolling region offset of ... | python | def draw(self, writer, idx, offset):
# as our screen can be resized while we're mid-calculation,
# our self.dirty flag can become re-toggled; because we are
# not re-flowing our pagination, we must begin over again.
while self.dirty:
self.draw_heading(writer)
self... | [
"def",
"draw",
"(",
"self",
",",
"writer",
",",
"idx",
",",
"offset",
")",
":",
"# as our screen can be resized while we're mid-calculation,",
"# our self.dirty flag can become re-toggled; because we are",
"# not re-flowing our pagination, we must begin over again.",
"while",
"self",... | Draw the current page view to ``writer``.
:param writer: callable writes to output stream, receiving unicode.
:type writer: callable
:param idx: current page index.
:type idx: int
:param offset: scrolling region offset of current page.
:type offset: int
:returns:... | [
"Draw",
"the",
"current",
"page",
"view",
"to",
"writer",
"."
] | 78800b68911880ef4ef95ae83886154710441871 | https://github.com/jquast/wcwidth/blob/78800b68911880ef4ef95ae83886154710441871/bin/wcwidth-browser.py#L513-L537 |
447 | jquast/wcwidth | bin/wcwidth-browser.py | Pager.draw_heading | def draw_heading(self, writer):
"""
Conditionally redraw screen when ``dirty`` attribute is valued REFRESH.
When Pager attribute ``dirty`` is ``STATE_REFRESH``, cursor is moved
to (0,0), screen is cleared, and heading is displayed.
:param writer: callable writes to output strea... | python | def draw_heading(self, writer):
if self.dirty == self.STATE_REFRESH:
writer(u''.join(
(self.term.home, self.term.clear,
self.screen.msg_intro, '\n',
self.screen.header, '\n',)))
return True | [
"def",
"draw_heading",
"(",
"self",
",",
"writer",
")",
":",
"if",
"self",
".",
"dirty",
"==",
"self",
".",
"STATE_REFRESH",
":",
"writer",
"(",
"u''",
".",
"join",
"(",
"(",
"self",
".",
"term",
".",
"home",
",",
"self",
".",
"term",
".",
"clear",... | Conditionally redraw screen when ``dirty`` attribute is valued REFRESH.
When Pager attribute ``dirty`` is ``STATE_REFRESH``, cursor is moved
to (0,0), screen is cleared, and heading is displayed.
:param writer: callable writes to output stream, receiving unicode.
:returns: True if clas... | [
"Conditionally",
"redraw",
"screen",
"when",
"dirty",
"attribute",
"is",
"valued",
"REFRESH",
"."
] | 78800b68911880ef4ef95ae83886154710441871 | https://github.com/jquast/wcwidth/blob/78800b68911880ef4ef95ae83886154710441871/bin/wcwidth-browser.py#L539-L554 |
448 | jquast/wcwidth | bin/wcwidth-browser.py | Pager.draw_status | def draw_status(self, writer, idx):
"""
Conditionally draw status bar when output terminal is a tty.
:param writer: callable writes to output stream, receiving unicode.
:param idx: current page position index.
:type idx: int
"""
if self.term.is_a_tty:
... | python | def draw_status(self, writer, idx):
if self.term.is_a_tty:
writer(self.term.hide_cursor())
style = self.screen.style
writer(self.term.move(self.term.height - 1))
if idx == self.last_page:
last_end = u'(END)'
else:
last_e... | [
"def",
"draw_status",
"(",
"self",
",",
"writer",
",",
"idx",
")",
":",
"if",
"self",
".",
"term",
".",
"is_a_tty",
":",
"writer",
"(",
"self",
".",
"term",
".",
"hide_cursor",
"(",
")",
")",
"style",
"=",
"self",
".",
"screen",
".",
"style",
"writ... | Conditionally draw status bar when output terminal is a tty.
:param writer: callable writes to output stream, receiving unicode.
:param idx: current page position index.
:type idx: int | [
"Conditionally",
"draw",
"status",
"bar",
"when",
"output",
"terminal",
"is",
"a",
"tty",
"."
] | 78800b68911880ef4ef95ae83886154710441871 | https://github.com/jquast/wcwidth/blob/78800b68911880ef4ef95ae83886154710441871/bin/wcwidth-browser.py#L556-L578 |
449 | jquast/wcwidth | bin/wcwidth-browser.py | Pager.page_view | def page_view(self, data):
"""
Generator yields text to be displayed for the current unicode pageview.
:param data: The current page's data as tuple of ``(ucs, name)``.
:rtype: generator
"""
if self.term.is_a_tty:
yield self.term.move(self.screen.row_begins, ... | python | def page_view(self, data):
if self.term.is_a_tty:
yield self.term.move(self.screen.row_begins, 0)
# sequence clears to end-of-line
clear_eol = self.term.clear_eol
# sequence clears to end-of-screen
clear_eos = self.term.clear_eos
# track our current column an... | [
"def",
"page_view",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"term",
".",
"is_a_tty",
":",
"yield",
"self",
".",
"term",
".",
"move",
"(",
"self",
".",
"screen",
".",
"row_begins",
",",
"0",
")",
"# sequence clears to end-of-line",
"clear_e... | Generator yields text to be displayed for the current unicode pageview.
:param data: The current page's data as tuple of ``(ucs, name)``.
:rtype: generator | [
"Generator",
"yields",
"text",
"to",
"be",
"displayed",
"for",
"the",
"current",
"unicode",
"pageview",
"."
] | 78800b68911880ef4ef95ae83886154710441871 | https://github.com/jquast/wcwidth/blob/78800b68911880ef4ef95ae83886154710441871/bin/wcwidth-browser.py#L580-L615 |
450 | matthew-brett/delocate | delocate/tools.py | back_tick | def back_tick(cmd, ret_err=False, as_str=True, raise_err=None):
""" Run command `cmd`, return stdout, or stdout, stderr if `ret_err`
Roughly equivalent to ``check_output`` in Python 2.7
Parameters
----------
cmd : sequence
command to execute
ret_err : bool, optional
If True, re... | python | def back_tick(cmd, ret_err=False, as_str=True, raise_err=None):
if raise_err is None:
raise_err = False if ret_err else True
cmd_is_seq = isinstance(cmd, (list, tuple))
proc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=not cmd_is_seq)
out, err = proc.communicate()
retcode = proc.returncode
... | [
"def",
"back_tick",
"(",
"cmd",
",",
"ret_err",
"=",
"False",
",",
"as_str",
"=",
"True",
",",
"raise_err",
"=",
"None",
")",
":",
"if",
"raise_err",
"is",
"None",
":",
"raise_err",
"=",
"False",
"if",
"ret_err",
"else",
"True",
"cmd_is_seq",
"=",
"isi... | Run command `cmd`, return stdout, or stdout, stderr if `ret_err`
Roughly equivalent to ``check_output`` in Python 2.7
Parameters
----------
cmd : sequence
command to execute
ret_err : bool, optional
If True, return stderr in addition to stdout. If False, just return
stdout... | [
"Run",
"command",
"cmd",
"return",
"stdout",
"or",
"stdout",
"stderr",
"if",
"ret_err"
] | ed48de15fce31c3f52f1a9f32cae1b02fc55aa60 | https://github.com/matthew-brett/delocate/blob/ed48de15fce31c3f52f1a9f32cae1b02fc55aa60/delocate/tools.py#L17-L69 |
451 | matthew-brett/delocate | delocate/tools.py | unique_by_index | def unique_by_index(sequence):
""" unique elements in `sequence` in the order in which they occur
Parameters
----------
sequence : iterable
Returns
-------
uniques : list
unique elements of sequence, ordered by the order in which the element
occurs in `sequence`
"""
... | python | def unique_by_index(sequence):
uniques = []
for element in sequence:
if element not in uniques:
uniques.append(element)
return uniques | [
"def",
"unique_by_index",
"(",
"sequence",
")",
":",
"uniques",
"=",
"[",
"]",
"for",
"element",
"in",
"sequence",
":",
"if",
"element",
"not",
"in",
"uniques",
":",
"uniques",
".",
"append",
"(",
"element",
")",
"return",
"uniques"
] | unique elements in `sequence` in the order in which they occur
Parameters
----------
sequence : iterable
Returns
-------
uniques : list
unique elements of sequence, ordered by the order in which the element
occurs in `sequence` | [
"unique",
"elements",
"in",
"sequence",
"in",
"the",
"order",
"in",
"which",
"they",
"occur"
] | ed48de15fce31c3f52f1a9f32cae1b02fc55aa60 | https://github.com/matthew-brett/delocate/blob/ed48de15fce31c3f52f1a9f32cae1b02fc55aa60/delocate/tools.py#L72-L89 |
452 | matthew-brett/delocate | delocate/tools.py | ensure_permissions | def ensure_permissions(mode_flags=stat.S_IWUSR):
"""decorator to ensure a filename has given permissions.
If changed, original permissions are restored after the decorated
modification.
"""
def decorator(f):
def modify(filename, *args, **kwargs):
m = chmod_perms(filename) if ex... | python | def ensure_permissions(mode_flags=stat.S_IWUSR):
def decorator(f):
def modify(filename, *args, **kwargs):
m = chmod_perms(filename) if exists(filename) else mode_flags
if not m & mode_flags:
os.chmod(filename, m | mode_flags)
try:
return f(... | [
"def",
"ensure_permissions",
"(",
"mode_flags",
"=",
"stat",
".",
"S_IWUSR",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"def",
"modify",
"(",
"filename",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"m",
"=",
"chmod_perms",
"(",
"filen... | decorator to ensure a filename has given permissions.
If changed, original permissions are restored after the decorated
modification. | [
"decorator",
"to",
"ensure",
"a",
"filename",
"has",
"given",
"permissions",
"."
] | ed48de15fce31c3f52f1a9f32cae1b02fc55aa60 | https://github.com/matthew-brett/delocate/blob/ed48de15fce31c3f52f1a9f32cae1b02fc55aa60/delocate/tools.py#L97-L117 |
453 | matthew-brett/delocate | delocate/tools.py | get_install_names | def get_install_names(filename):
""" Return install names from library named in `filename`
Returns tuple of install names
tuple will be empty if no install names, or if this is not an object file.
Parameters
----------
filename : str
filename of library
Returns
-------
in... | python | def get_install_names(filename):
lines = _cmd_out_err(['otool', '-L', filename])
if not _line0_says_object(lines[0], filename):
return ()
names = tuple(parse_install_name(line)[0] for line in lines[1:])
install_id = get_install_id(filename)
if not install_id is None:
assert names[0] ... | [
"def",
"get_install_names",
"(",
"filename",
")",
":",
"lines",
"=",
"_cmd_out_err",
"(",
"[",
"'otool'",
",",
"'-L'",
",",
"filename",
"]",
")",
"if",
"not",
"_line0_says_object",
"(",
"lines",
"[",
"0",
"]",
",",
"filename",
")",
":",
"return",
"(",
... | Return install names from library named in `filename`
Returns tuple of install names
tuple will be empty if no install names, or if this is not an object file.
Parameters
----------
filename : str
filename of library
Returns
-------
install_names : tuple
tuple of inst... | [
"Return",
"install",
"names",
"from",
"library",
"named",
"in",
"filename"
] | ed48de15fce31c3f52f1a9f32cae1b02fc55aa60 | https://github.com/matthew-brett/delocate/blob/ed48de15fce31c3f52f1a9f32cae1b02fc55aa60/delocate/tools.py#L197-L222 |
454 | matthew-brett/delocate | delocate/tools.py | get_install_id | def get_install_id(filename):
""" Return install id from library named in `filename`
Returns None if no install id, or if this is not an object file.
Parameters
----------
filename : str
filename of library
Returns
-------
install_id : str
install id of library `filena... | python | def get_install_id(filename):
lines = _cmd_out_err(['otool', '-D', filename])
if not _line0_says_object(lines[0], filename):
return None
if len(lines) == 1:
return None
if len(lines) != 2:
raise InstallNameError('Unexpected otool output ' + '\n'.join(lines))
return lines[1].s... | [
"def",
"get_install_id",
"(",
"filename",
")",
":",
"lines",
"=",
"_cmd_out_err",
"(",
"[",
"'otool'",
",",
"'-D'",
",",
"filename",
"]",
")",
"if",
"not",
"_line0_says_object",
"(",
"lines",
"[",
"0",
"]",
",",
"filename",
")",
":",
"return",
"None",
... | Return install id from library named in `filename`
Returns None if no install id, or if this is not an object file.
Parameters
----------
filename : str
filename of library
Returns
-------
install_id : str
install id of library `filename`, or None if no install id | [
"Return",
"install",
"id",
"from",
"library",
"named",
"in",
"filename"
] | ed48de15fce31c3f52f1a9f32cae1b02fc55aa60 | https://github.com/matthew-brett/delocate/blob/ed48de15fce31c3f52f1a9f32cae1b02fc55aa60/delocate/tools.py#L225-L247 |
455 | matthew-brett/delocate | delocate/tools.py | set_install_name | def set_install_name(filename, oldname, newname):
""" Set install name `oldname` to `newname` in library filename
Parameters
----------
filename : str
filename of library
oldname : str
current install name in library
newname : str
replacement name for `oldname`
"""
... | python | def set_install_name(filename, oldname, newname):
names = get_install_names(filename)
if oldname not in names:
raise InstallNameError('{0} not in install names for {1}'.format(
oldname, filename))
back_tick(['install_name_tool', '-change', oldname, newname, filename]) | [
"def",
"set_install_name",
"(",
"filename",
",",
"oldname",
",",
"newname",
")",
":",
"names",
"=",
"get_install_names",
"(",
"filename",
")",
"if",
"oldname",
"not",
"in",
"names",
":",
"raise",
"InstallNameError",
"(",
"'{0} not in install names for {1}'",
".",
... | Set install name `oldname` to `newname` in library filename
Parameters
----------
filename : str
filename of library
oldname : str
current install name in library
newname : str
replacement name for `oldname` | [
"Set",
"install",
"name",
"oldname",
"to",
"newname",
"in",
"library",
"filename"
] | ed48de15fce31c3f52f1a9f32cae1b02fc55aa60 | https://github.com/matthew-brett/delocate/blob/ed48de15fce31c3f52f1a9f32cae1b02fc55aa60/delocate/tools.py#L251-L267 |
456 | matthew-brett/delocate | delocate/tools.py | set_install_id | def set_install_id(filename, install_id):
""" Set install id for library named in `filename`
Parameters
----------
filename : str
filename of library
install_id : str
install id for library `filename`
Raises
------
RuntimeError if `filename` has not install id
"""
... | python | def set_install_id(filename, install_id):
if get_install_id(filename) is None:
raise InstallNameError('{0} has no install id'.format(filename))
back_tick(['install_name_tool', '-id', install_id, filename]) | [
"def",
"set_install_id",
"(",
"filename",
",",
"install_id",
")",
":",
"if",
"get_install_id",
"(",
"filename",
")",
"is",
"None",
":",
"raise",
"InstallNameError",
"(",
"'{0} has no install id'",
".",
"format",
"(",
"filename",
")",
")",
"back_tick",
"(",
"["... | Set install id for library named in `filename`
Parameters
----------
filename : str
filename of library
install_id : str
install id for library `filename`
Raises
------
RuntimeError if `filename` has not install id | [
"Set",
"install",
"id",
"for",
"library",
"named",
"in",
"filename"
] | ed48de15fce31c3f52f1a9f32cae1b02fc55aa60 | https://github.com/matthew-brett/delocate/blob/ed48de15fce31c3f52f1a9f32cae1b02fc55aa60/delocate/tools.py#L271-L287 |
457 | matthew-brett/delocate | delocate/tools.py | get_rpaths | def get_rpaths(filename):
""" Return a tuple of rpaths from the library `filename`
If `filename` is not a library then the returned tuple will be empty.
Parameters
----------
filaname : str
filename of library
Returns
-------
rpath : tuple
rpath paths in `filename`
... | python | def get_rpaths(filename):
try:
lines = _cmd_out_err(['otool', '-l', filename])
except RuntimeError:
return ()
if not _line0_says_object(lines[0], filename):
return ()
lines = [line.strip() for line in lines]
paths = []
line_no = 1
while line_no < len(lines):
l... | [
"def",
"get_rpaths",
"(",
"filename",
")",
":",
"try",
":",
"lines",
"=",
"_cmd_out_err",
"(",
"[",
"'otool'",
",",
"'-l'",
",",
"filename",
"]",
")",
"except",
"RuntimeError",
":",
"return",
"(",
")",
"if",
"not",
"_line0_says_object",
"(",
"lines",
"["... | Return a tuple of rpaths from the library `filename`
If `filename` is not a library then the returned tuple will be empty.
Parameters
----------
filaname : str
filename of library
Returns
-------
rpath : tuple
rpath paths in `filename` | [
"Return",
"a",
"tuple",
"of",
"rpaths",
"from",
"the",
"library",
"filename"
] | ed48de15fce31c3f52f1a9f32cae1b02fc55aa60 | https://github.com/matthew-brett/delocate/blob/ed48de15fce31c3f52f1a9f32cae1b02fc55aa60/delocate/tools.py#L292-L325 |
458 | matthew-brett/delocate | delocate/tools.py | dir2zip | def dir2zip(in_dir, zip_fname):
""" Make a zip file `zip_fname` with contents of directory `in_dir`
The recorded filenames are relative to `in_dir`, so doing a standard zip
unpack of the resulting `zip_fname` in an empty directory will result in
the original directory contents.
Parameters
----... | python | def dir2zip(in_dir, zip_fname):
z = zipfile.ZipFile(zip_fname, 'w',
compression=zipfile.ZIP_DEFLATED)
for root, dirs, files in os.walk(in_dir):
for file in files:
in_fname = pjoin(root, file)
in_stat = os.stat(in_fname)
# Preserve file permissi... | [
"def",
"dir2zip",
"(",
"in_dir",
",",
"zip_fname",
")",
":",
"z",
"=",
"zipfile",
".",
"ZipFile",
"(",
"zip_fname",
",",
"'w'",
",",
"compression",
"=",
"zipfile",
".",
"ZIP_DEFLATED",
")",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"... | Make a zip file `zip_fname` with contents of directory `in_dir`
The recorded filenames are relative to `in_dir`, so doing a standard zip
unpack of the resulting `zip_fname` in an empty directory will result in
the original directory contents.
Parameters
----------
in_dir : str
Director... | [
"Make",
"a",
"zip",
"file",
"zip_fname",
"with",
"contents",
"of",
"directory",
"in_dir"
] | ed48de15fce31c3f52f1a9f32cae1b02fc55aa60 | https://github.com/matthew-brett/delocate/blob/ed48de15fce31c3f52f1a9f32cae1b02fc55aa60/delocate/tools.py#L357-L393 |
459 | matthew-brett/delocate | delocate/tools.py | find_package_dirs | def find_package_dirs(root_path):
""" Find python package directories in directory `root_path`
Parameters
----------
root_path : str
Directory to search for package subdirectories
Returns
-------
package_sdirs : set
Set of strings where each is a subdirectory of `root_path`... | python | def find_package_dirs(root_path):
package_sdirs = set()
for entry in os.listdir(root_path):
fname = entry if root_path == '.' else pjoin(root_path, entry)
if isdir(fname) and exists(pjoin(fname, '__init__.py')):
package_sdirs.add(fname)
return package_sdirs | [
"def",
"find_package_dirs",
"(",
"root_path",
")",
":",
"package_sdirs",
"=",
"set",
"(",
")",
"for",
"entry",
"in",
"os",
".",
"listdir",
"(",
"root_path",
")",
":",
"fname",
"=",
"entry",
"if",
"root_path",
"==",
"'.'",
"else",
"pjoin",
"(",
"root_path... | Find python package directories in directory `root_path`
Parameters
----------
root_path : str
Directory to search for package subdirectories
Returns
-------
package_sdirs : set
Set of strings where each is a subdirectory of `root_path`, containing
an ``__init__.py`` fi... | [
"Find",
"python",
"package",
"directories",
"in",
"directory",
"root_path"
] | ed48de15fce31c3f52f1a9f32cae1b02fc55aa60 | https://github.com/matthew-brett/delocate/blob/ed48de15fce31c3f52f1a9f32cae1b02fc55aa60/delocate/tools.py#L396-L415 |
460 | matthew-brett/delocate | delocate/tools.py | cmp_contents | def cmp_contents(filename1, filename2):
""" Returns True if contents of the files are the same
Parameters
----------
filename1 : str
filename of first file to compare
filename2 : str
filename of second file to compare
Returns
-------
tf : bool
True if binary con... | python | def cmp_contents(filename1, filename2):
with open_readable(filename1, 'rb') as fobj:
contents1 = fobj.read()
with open_readable(filename2, 'rb') as fobj:
contents2 = fobj.read()
return contents1 == contents2 | [
"def",
"cmp_contents",
"(",
"filename1",
",",
"filename2",
")",
":",
"with",
"open_readable",
"(",
"filename1",
",",
"'rb'",
")",
"as",
"fobj",
":",
"contents1",
"=",
"fobj",
".",
"read",
"(",
")",
"with",
"open_readable",
"(",
"filename2",
",",
"'rb'",
... | Returns True if contents of the files are the same
Parameters
----------
filename1 : str
filename of first file to compare
filename2 : str
filename of second file to compare
Returns
-------
tf : bool
True if binary contents of `filename1` is same as binary contents ... | [
"Returns",
"True",
"if",
"contents",
"of",
"the",
"files",
"are",
"the",
"same"
] | ed48de15fce31c3f52f1a9f32cae1b02fc55aa60 | https://github.com/matthew-brett/delocate/blob/ed48de15fce31c3f52f1a9f32cae1b02fc55aa60/delocate/tools.py#L418-L438 |
461 | matthew-brett/delocate | delocate/tools.py | get_archs | def get_archs(libname):
""" Return architecture types from library `libname`
Parameters
----------
libname : str
filename of binary for which to return arch codes
Returns
-------
arch_names : frozenset
Empty (frozen)set if no arch codes. If not empty, contains one or more
... | python | def get_archs(libname):
if not exists(libname):
raise RuntimeError(libname + " is not a file")
try:
stdout = back_tick(['lipo', '-info', libname])
except RuntimeError:
return frozenset()
lines = [line.strip() for line in stdout.split('\n') if line.strip()]
# For some reason, ... | [
"def",
"get_archs",
"(",
"libname",
")",
":",
"if",
"not",
"exists",
"(",
"libname",
")",
":",
"raise",
"RuntimeError",
"(",
"libname",
"+",
"\" is not a file\"",
")",
"try",
":",
"stdout",
"=",
"back_tick",
"(",
"[",
"'lipo'",
",",
"'-info'",
",",
"libn... | Return architecture types from library `libname`
Parameters
----------
libname : str
filename of binary for which to return arch codes
Returns
-------
arch_names : frozenset
Empty (frozen)set if no arch codes. If not empty, contains one or more
of 'ppc', 'ppc64', 'i386... | [
"Return",
"architecture",
"types",
"from",
"library",
"libname"
] | ed48de15fce31c3f52f1a9f32cae1b02fc55aa60 | https://github.com/matthew-brett/delocate/blob/ed48de15fce31c3f52f1a9f32cae1b02fc55aa60/delocate/tools.py#L441-L476 |
462 | matthew-brett/delocate | delocate/tools.py | validate_signature | def validate_signature(filename):
""" Remove invalid signatures from a binary file
If the file signature is missing or valid then it will be ignored
Invalid signatures are replaced with an ad-hoc signature. This is the
closest you can get to removing a signature on MacOS
Parameters
---------... | python | def validate_signature(filename):
out, err = back_tick(['codesign', '--verify', filename],
ret_err=True, as_str=True, raise_err=False)
if not err:
return # The existing signature is valid
if 'code object is not signed at all' in err:
return # File has no signature, a... | [
"def",
"validate_signature",
"(",
"filename",
")",
":",
"out",
",",
"err",
"=",
"back_tick",
"(",
"[",
"'codesign'",
",",
"'--verify'",
",",
"filename",
"]",
",",
"ret_err",
"=",
"True",
",",
"as_str",
"=",
"True",
",",
"raise_err",
"=",
"False",
")",
... | Remove invalid signatures from a binary file
If the file signature is missing or valid then it will be ignored
Invalid signatures are replaced with an ad-hoc signature. This is the
closest you can get to removing a signature on MacOS
Parameters
----------
filename : str
Filepath to a... | [
"Remove",
"invalid",
"signatures",
"from",
"a",
"binary",
"file"
] | ed48de15fce31c3f52f1a9f32cae1b02fc55aa60 | https://github.com/matthew-brett/delocate/blob/ed48de15fce31c3f52f1a9f32cae1b02fc55aa60/delocate/tools.py#L513-L534 |
463 | matthew-brett/delocate | delocate/fuse.py | fuse_trees | def fuse_trees(to_tree, from_tree, lib_exts=('.so', '.dylib', '.a')):
""" Fuse path `from_tree` into path `to_tree`
For each file in `from_tree` - check for library file extension (in
`lib_exts` - if present, check if there is a file with matching relative
path in `to_tree`, if so, use :func:`delocate.... | python | def fuse_trees(to_tree, from_tree, lib_exts=('.so', '.dylib', '.a')):
for from_dirpath, dirnames, filenames in os.walk(from_tree):
to_dirpath = pjoin(to_tree, relpath(from_dirpath, from_tree))
# Copy any missing directories in to_path
for dirname in tuple(dirnames):
to_path = pjo... | [
"def",
"fuse_trees",
"(",
"to_tree",
",",
"from_tree",
",",
"lib_exts",
"=",
"(",
"'.so'",
",",
"'.dylib'",
",",
"'.a'",
")",
")",
":",
"for",
"from_dirpath",
",",
"dirnames",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"from_tree",
")",
":",
"to_d... | Fuse path `from_tree` into path `to_tree`
For each file in `from_tree` - check for library file extension (in
`lib_exts` - if present, check if there is a file with matching relative
path in `to_tree`, if so, use :func:`delocate.tools.lipo_fuse` to fuse the
two libraries together and write into `to_tre... | [
"Fuse",
"path",
"from_tree",
"into",
"path",
"to_tree"
] | ed48de15fce31c3f52f1a9f32cae1b02fc55aa60 | https://github.com/matthew-brett/delocate/blob/ed48de15fce31c3f52f1a9f32cae1b02fc55aa60/delocate/fuse.py#L36-L77 |
464 | matthew-brett/delocate | delocate/fuse.py | fuse_wheels | def fuse_wheels(to_wheel, from_wheel, out_wheel):
""" Fuse `from_wheel` into `to_wheel`, write to `out_wheel`
Parameters
---------
to_wheel : str
filename of wheel to fuse into
from_wheel : str
filename of wheel to fuse from
out_wheel : str
filename of new wheel from fus... | python | def fuse_wheels(to_wheel, from_wheel, out_wheel):
to_wheel, from_wheel, out_wheel = [
abspath(w) for w in (to_wheel, from_wheel, out_wheel)]
with InTemporaryDirectory():
zip2dir(to_wheel, 'to_wheel')
zip2dir(from_wheel, 'from_wheel')
fuse_trees('to_wheel', 'from_wheel')
r... | [
"def",
"fuse_wheels",
"(",
"to_wheel",
",",
"from_wheel",
",",
"out_wheel",
")",
":",
"to_wheel",
",",
"from_wheel",
",",
"out_wheel",
"=",
"[",
"abspath",
"(",
"w",
")",
"for",
"w",
"in",
"(",
"to_wheel",
",",
"from_wheel",
",",
"out_wheel",
")",
"]",
... | Fuse `from_wheel` into `to_wheel`, write to `out_wheel`
Parameters
---------
to_wheel : str
filename of wheel to fuse into
from_wheel : str
filename of wheel to fuse from
out_wheel : str
filename of new wheel from fusion of `to_wheel` and `from_wheel` | [
"Fuse",
"from_wheel",
"into",
"to_wheel",
"write",
"to",
"out_wheel"
] | ed48de15fce31c3f52f1a9f32cae1b02fc55aa60 | https://github.com/matthew-brett/delocate/blob/ed48de15fce31c3f52f1a9f32cae1b02fc55aa60/delocate/fuse.py#L80-L99 |
465 | matthew-brett/delocate | delocate/delocating.py | delocate_tree_libs | def delocate_tree_libs(lib_dict, lib_path, root_path):
""" Move needed libraries in `lib_dict` into `lib_path`
`lib_dict` has keys naming libraries required by the files in the
corresponding value. Call the keys, "required libs". Call the values
"requiring objects".
Copy all the required libs to... | python | def delocate_tree_libs(lib_dict, lib_path, root_path):
copied_libs = {}
delocated_libs = set()
copied_basenames = set()
rp_root_path = realpath(root_path)
rp_lib_path = realpath(lib_path)
# Test for errors first to avoid getting half-way through changing the tree
for required, requirings in ... | [
"def",
"delocate_tree_libs",
"(",
"lib_dict",
",",
"lib_path",
",",
"root_path",
")",
":",
"copied_libs",
"=",
"{",
"}",
"delocated_libs",
"=",
"set",
"(",
")",
"copied_basenames",
"=",
"set",
"(",
")",
"rp_root_path",
"=",
"realpath",
"(",
"root_path",
")",... | Move needed libraries in `lib_dict` into `lib_path`
`lib_dict` has keys naming libraries required by the files in the
corresponding value. Call the keys, "required libs". Call the values
"requiring objects".
Copy all the required libs to `lib_path`. Fix up the rpaths and install
names in the re... | [
"Move",
"needed",
"libraries",
"in",
"lib_dict",
"into",
"lib_path"
] | ed48de15fce31c3f52f1a9f32cae1b02fc55aa60 | https://github.com/matthew-brett/delocate/blob/ed48de15fce31c3f52f1a9f32cae1b02fc55aa60/delocate/delocating.py#L27-L101 |
466 | matthew-brett/delocate | delocate/delocating.py | copy_recurse | def copy_recurse(lib_path, copy_filt_func = None, copied_libs = None):
""" Analyze `lib_path` for library dependencies and copy libraries
`lib_path` is a directory containing libraries. The libraries might
themselves have dependencies. This function analyzes the dependencies and
copies library depend... | python | def copy_recurse(lib_path, copy_filt_func = None, copied_libs = None):
if copied_libs is None:
copied_libs = {}
else:
copied_libs = dict(copied_libs)
done = False
while not done:
in_len = len(copied_libs)
_copy_required(lib_path, copy_filt_func, copied_libs)
done ... | [
"def",
"copy_recurse",
"(",
"lib_path",
",",
"copy_filt_func",
"=",
"None",
",",
"copied_libs",
"=",
"None",
")",
":",
"if",
"copied_libs",
"is",
"None",
":",
"copied_libs",
"=",
"{",
"}",
"else",
":",
"copied_libs",
"=",
"dict",
"(",
"copied_libs",
")",
... | Analyze `lib_path` for library dependencies and copy libraries
`lib_path` is a directory containing libraries. The libraries might
themselves have dependencies. This function analyzes the dependencies and
copies library dependencies that match the filter `copy_filt_func`. It also
adjusts the dependin... | [
"Analyze",
"lib_path",
"for",
"library",
"dependencies",
"and",
"copy",
"libraries"
] | ed48de15fce31c3f52f1a9f32cae1b02fc55aa60 | https://github.com/matthew-brett/delocate/blob/ed48de15fce31c3f52f1a9f32cae1b02fc55aa60/delocate/delocating.py#L104-L147 |
467 | matthew-brett/delocate | delocate/delocating.py | _copy_required | def _copy_required(lib_path, copy_filt_func, copied_libs):
""" Copy libraries required for files in `lib_path` to `lib_path`
Augment `copied_libs` dictionary with any newly copied libraries, modifying
`copied_libs` in-place - see Notes.
This is one pass of ``copy_recurse``
Parameters
--------... | python | def _copy_required(lib_path, copy_filt_func, copied_libs):
# Paths will be prepended with `lib_path`
lib_dict = tree_libs(lib_path)
# Map library paths after copy ('copied') to path before copy ('orig')
rp_lp = realpath(lib_path)
copied2orig = dict((pjoin(rp_lp, basename(c)), c) for c in copied_libs... | [
"def",
"_copy_required",
"(",
"lib_path",
",",
"copy_filt_func",
",",
"copied_libs",
")",
":",
"# Paths will be prepended with `lib_path`",
"lib_dict",
"=",
"tree_libs",
"(",
"lib_path",
")",
"# Map library paths after copy ('copied') to path before copy ('orig')",
"rp_lp",
"="... | Copy libraries required for files in `lib_path` to `lib_path`
Augment `copied_libs` dictionary with any newly copied libraries, modifying
`copied_libs` in-place - see Notes.
This is one pass of ``copy_recurse``
Parameters
----------
lib_path : str
Directory containing libraries
co... | [
"Copy",
"libraries",
"required",
"for",
"files",
"in",
"lib_path",
"to",
"lib_path"
] | ed48de15fce31c3f52f1a9f32cae1b02fc55aa60 | https://github.com/matthew-brett/delocate/blob/ed48de15fce31c3f52f1a9f32cae1b02fc55aa60/delocate/delocating.py#L150-L233 |
468 | matthew-brett/delocate | delocate/delocating.py | delocate_path | def delocate_path(tree_path, lib_path,
lib_filt_func = None,
copy_filt_func = filter_system_libs):
""" Copy required libraries for files in `tree_path` into `lib_path`
Parameters
----------
tree_path : str
Root path of tree to search for required libraries
... | python | def delocate_path(tree_path, lib_path,
lib_filt_func = None,
copy_filt_func = filter_system_libs):
if lib_filt_func == "dylibs-only":
lib_filt_func = _dylibs_only
if not exists(lib_path):
os.makedirs(lib_path)
lib_dict = tree_libs(tree_path, lib_filt_func)... | [
"def",
"delocate_path",
"(",
"tree_path",
",",
"lib_path",
",",
"lib_filt_func",
"=",
"None",
",",
"copy_filt_func",
"=",
"filter_system_libs",
")",
":",
"if",
"lib_filt_func",
"==",
"\"dylibs-only\"",
":",
"lib_filt_func",
"=",
"_dylibs_only",
"if",
"not",
"exist... | Copy required libraries for files in `tree_path` into `lib_path`
Parameters
----------
tree_path : str
Root path of tree to search for required libraries
lib_path : str
Directory into which we copy required libraries
lib_filt_func : None or str or callable, optional
If None,... | [
"Copy",
"required",
"libraries",
"for",
"files",
"in",
"tree_path",
"into",
"lib_path"
] | ed48de15fce31c3f52f1a9f32cae1b02fc55aa60 | https://github.com/matthew-brett/delocate/blob/ed48de15fce31c3f52f1a9f32cae1b02fc55aa60/delocate/delocating.py#L246-L289 |
469 | matthew-brett/delocate | delocate/delocating.py | _merge_lib_dict | def _merge_lib_dict(d1, d2):
""" Merges lib_dict `d2` into lib_dict `d1`
"""
for required, requirings in d2.items():
if required in d1:
d1[required].update(requirings)
else:
d1[required] = requirings
return None | python | def _merge_lib_dict(d1, d2):
for required, requirings in d2.items():
if required in d1:
d1[required].update(requirings)
else:
d1[required] = requirings
return None | [
"def",
"_merge_lib_dict",
"(",
"d1",
",",
"d2",
")",
":",
"for",
"required",
",",
"requirings",
"in",
"d2",
".",
"items",
"(",
")",
":",
"if",
"required",
"in",
"d1",
":",
"d1",
"[",
"required",
"]",
".",
"update",
"(",
"requirings",
")",
"else",
"... | Merges lib_dict `d2` into lib_dict `d1` | [
"Merges",
"lib_dict",
"d2",
"into",
"lib_dict",
"d1"
] | ed48de15fce31c3f52f1a9f32cae1b02fc55aa60 | https://github.com/matthew-brett/delocate/blob/ed48de15fce31c3f52f1a9f32cae1b02fc55aa60/delocate/delocating.py#L292-L300 |
470 | matthew-brett/delocate | delocate/delocating.py | delocate_wheel | def delocate_wheel(in_wheel,
out_wheel = None,
lib_sdir = '.dylibs',
lib_filt_func = None,
copy_filt_func = filter_system_libs,
require_archs = None,
check_verbose = False,
):
""" Upda... | python | def delocate_wheel(in_wheel,
out_wheel = None,
lib_sdir = '.dylibs',
lib_filt_func = None,
copy_filt_func = filter_system_libs,
require_archs = None,
check_verbose = False,
):
if lib_f... | [
"def",
"delocate_wheel",
"(",
"in_wheel",
",",
"out_wheel",
"=",
"None",
",",
"lib_sdir",
"=",
"'.dylibs'",
",",
"lib_filt_func",
"=",
"None",
",",
"copy_filt_func",
"=",
"filter_system_libs",
",",
"require_archs",
"=",
"None",
",",
"check_verbose",
"=",
"False"... | Update wheel by copying required libraries to `lib_sdir` in wheel
Create `lib_sdir` in wheel tree only if we are copying one or more
libraries.
If `out_wheel` is None (the default), overwrite the wheel `in_wheel`
in-place.
Parameters
----------
in_wheel : str
Filename of wheel to ... | [
"Update",
"wheel",
"by",
"copying",
"required",
"libraries",
"to",
"lib_sdir",
"in",
"wheel"
] | ed48de15fce31c3f52f1a9f32cae1b02fc55aa60 | https://github.com/matthew-brett/delocate/blob/ed48de15fce31c3f52f1a9f32cae1b02fc55aa60/delocate/delocating.py#L303-L407 |
471 | matthew-brett/delocate | delocate/delocating.py | patch_wheel | def patch_wheel(in_wheel, patch_fname, out_wheel=None):
""" Apply ``-p1`` style patch in `patch_fname` to contents of `in_wheel`
If `out_wheel` is None (the default), overwrite the wheel `in_wheel`
in-place.
Parameters
----------
in_wheel : str
Filename of wheel to process
patch_fn... | python | def patch_wheel(in_wheel, patch_fname, out_wheel=None):
in_wheel = abspath(in_wheel)
patch_fname = abspath(patch_fname)
if out_wheel is None:
out_wheel = in_wheel
else:
out_wheel = abspath(out_wheel)
if not exists(patch_fname):
raise ValueError("patch file {0} does not exist"... | [
"def",
"patch_wheel",
"(",
"in_wheel",
",",
"patch_fname",
",",
"out_wheel",
"=",
"None",
")",
":",
"in_wheel",
"=",
"abspath",
"(",
"in_wheel",
")",
"patch_fname",
"=",
"abspath",
"(",
"patch_fname",
")",
"if",
"out_wheel",
"is",
"None",
":",
"out_wheel",
... | Apply ``-p1`` style patch in `patch_fname` to contents of `in_wheel`
If `out_wheel` is None (the default), overwrite the wheel `in_wheel`
in-place.
Parameters
----------
in_wheel : str
Filename of wheel to process
patch_fname : str
Filename of patch file. Will be applied with ... | [
"Apply",
"-",
"p1",
"style",
"patch",
"in",
"patch_fname",
"to",
"contents",
"of",
"in_wheel"
] | ed48de15fce31c3f52f1a9f32cae1b02fc55aa60 | https://github.com/matthew-brett/delocate/blob/ed48de15fce31c3f52f1a9f32cae1b02fc55aa60/delocate/delocating.py#L410-L443 |
472 | matthew-brett/delocate | delocate/delocating.py | check_archs | def check_archs(copied_libs, require_archs=(), stop_fast=False):
""" Check compatibility of archs in `copied_libs` dict
Parameters
----------
copied_libs : dict
dict containing the (key, value) pairs of (``copied_lib_path``,
``dependings_dict``), where ``copied_lib_path`` is a library r... | python | def check_archs(copied_libs, require_archs=(), stop_fast=False):
if isinstance(require_archs, string_types):
require_archs = (['i386', 'x86_64'] if require_archs == 'intel'
else [require_archs])
require_archs = frozenset(require_archs)
bads = []
for depended_lib, dep_dic... | [
"def",
"check_archs",
"(",
"copied_libs",
",",
"require_archs",
"=",
"(",
")",
",",
"stop_fast",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"require_archs",
",",
"string_types",
")",
":",
"require_archs",
"=",
"(",
"[",
"'i386'",
",",
"'x86_64'",
"]"... | Check compatibility of archs in `copied_libs` dict
Parameters
----------
copied_libs : dict
dict containing the (key, value) pairs of (``copied_lib_path``,
``dependings_dict``), where ``copied_lib_path`` is a library real path
that has been copied during delocation, and ``dependings... | [
"Check",
"compatibility",
"of",
"archs",
"in",
"copied_libs",
"dict"
] | ed48de15fce31c3f52f1a9f32cae1b02fc55aa60 | https://github.com/matthew-brett/delocate/blob/ed48de15fce31c3f52f1a9f32cae1b02fc55aa60/delocate/delocating.py#L446-L505 |
473 | matthew-brett/delocate | delocate/delocating.py | bads_report | def bads_report(bads, path_prefix=None):
""" Return a nice report of bad architectures in `bads`
Parameters
----------
bads : set
set of length 2 or 3 tuples. A length 2 tuple is of form
``(depending_lib, missing_archs)`` meaning that an arch in
`require_archs` was missing from ... | python | def bads_report(bads, path_prefix=None):
path_processor = ((lambda x : x) if path_prefix is None
else get_rp_stripper(path_prefix))
reports = []
for result in bads:
if len(result) == 3:
depended_lib, depending_lib, missing_archs = result
reports.append("... | [
"def",
"bads_report",
"(",
"bads",
",",
"path_prefix",
"=",
"None",
")",
":",
"path_processor",
"=",
"(",
"(",
"lambda",
"x",
":",
"x",
")",
"if",
"path_prefix",
"is",
"None",
"else",
"get_rp_stripper",
"(",
"path_prefix",
")",
")",
"reports",
"=",
"[",
... | Return a nice report of bad architectures in `bads`
Parameters
----------
bads : set
set of length 2 or 3 tuples. A length 2 tuple is of form
``(depending_lib, missing_archs)`` meaning that an arch in
`require_archs` was missing from ``depending_lib``. A length 3 tuple
is o... | [
"Return",
"a",
"nice",
"report",
"of",
"bad",
"architectures",
"in",
"bads"
] | ed48de15fce31c3f52f1a9f32cae1b02fc55aa60 | https://github.com/matthew-brett/delocate/blob/ed48de15fce31c3f52f1a9f32cae1b02fc55aa60/delocate/delocating.py#L508-L552 |
474 | matthew-brett/delocate | delocate/libsana.py | tree_libs | def tree_libs(start_path, filt_func=None):
""" Return analysis of library dependencies within `start_path`
Parameters
----------
start_path : str
root path of tree to search for libraries depending on other libraries.
filt_func : None or callable, optional
If None, inspect all files... | python | def tree_libs(start_path, filt_func=None):
lib_dict = {}
for dirpath, dirnames, basenames in os.walk(start_path):
for base in basenames:
depending_libpath = realpath(pjoin(dirpath, base))
if not filt_func is None and not filt_func(depending_libpath):
continue
... | [
"def",
"tree_libs",
"(",
"start_path",
",",
"filt_func",
"=",
"None",
")",
":",
"lib_dict",
"=",
"{",
"}",
"for",
"dirpath",
",",
"dirnames",
",",
"basenames",
"in",
"os",
".",
"walk",
"(",
"start_path",
")",
":",
"for",
"base",
"in",
"basenames",
":",... | Return analysis of library dependencies within `start_path`
Parameters
----------
start_path : str
root path of tree to search for libraries depending on other libraries.
filt_func : None or callable, optional
If None, inspect all files for library dependencies. If callable,
acc... | [
"Return",
"analysis",
"of",
"library",
"dependencies",
"within",
"start_path"
] | ed48de15fce31c3f52f1a9f32cae1b02fc55aa60 | https://github.com/matthew-brett/delocate/blob/ed48de15fce31c3f52f1a9f32cae1b02fc55aa60/delocate/libsana.py#L14-L65 |
475 | matthew-brett/delocate | delocate/libsana.py | get_prefix_stripper | def get_prefix_stripper(strip_prefix):
""" Return function to strip `strip_prefix` prefix from string if present
Parameters
----------
prefix : str
Prefix to strip from the beginning of string if present
Returns
-------
stripper : func
function such that ``stripper(a_string... | python | def get_prefix_stripper(strip_prefix):
n = len(strip_prefix)
def stripper(path):
return path if not path.startswith(strip_prefix) else path[n:]
return stripper | [
"def",
"get_prefix_stripper",
"(",
"strip_prefix",
")",
":",
"n",
"=",
"len",
"(",
"strip_prefix",
")",
"def",
"stripper",
"(",
"path",
")",
":",
"return",
"path",
"if",
"not",
"path",
".",
"startswith",
"(",
"strip_prefix",
")",
"else",
"path",
"[",
"n"... | Return function to strip `strip_prefix` prefix from string if present
Parameters
----------
prefix : str
Prefix to strip from the beginning of string if present
Returns
-------
stripper : func
function such that ``stripper(a_string)`` will strip `prefix` from
``a_string... | [
"Return",
"function",
"to",
"strip",
"strip_prefix",
"prefix",
"from",
"string",
"if",
"present"
] | ed48de15fce31c3f52f1a9f32cae1b02fc55aa60 | https://github.com/matthew-brett/delocate/blob/ed48de15fce31c3f52f1a9f32cae1b02fc55aa60/delocate/libsana.py#L107-L124 |
476 | matthew-brett/delocate | delocate/libsana.py | stripped_lib_dict | def stripped_lib_dict(lib_dict, strip_prefix):
""" Return `lib_dict` with `strip_prefix` removed from start of paths
Use to give form of `lib_dict` that appears relative to some base path
given by `strip_prefix`. Particularly useful for analyzing wheels where we
unpack to a temporary path before analy... | python | def stripped_lib_dict(lib_dict, strip_prefix):
relative_dict = {}
stripper = get_prefix_stripper(strip_prefix)
for lib_path, dependings_dict in lib_dict.items():
ding_dict = {}
for depending_libpath, install_name in dependings_dict.items():
ding_dict[stripper(depending_libpath)]... | [
"def",
"stripped_lib_dict",
"(",
"lib_dict",
",",
"strip_prefix",
")",
":",
"relative_dict",
"=",
"{",
"}",
"stripper",
"=",
"get_prefix_stripper",
"(",
"strip_prefix",
")",
"for",
"lib_path",
",",
"dependings_dict",
"in",
"lib_dict",
".",
"items",
"(",
")",
"... | Return `lib_dict` with `strip_prefix` removed from start of paths
Use to give form of `lib_dict` that appears relative to some base path
given by `strip_prefix`. Particularly useful for analyzing wheels where we
unpack to a temporary path before analyzing.
Parameters
----------
lib_dict : dic... | [
"Return",
"lib_dict",
"with",
"strip_prefix",
"removed",
"from",
"start",
"of",
"paths"
] | ed48de15fce31c3f52f1a9f32cae1b02fc55aa60 | https://github.com/matthew-brett/delocate/blob/ed48de15fce31c3f52f1a9f32cae1b02fc55aa60/delocate/libsana.py#L145-L175 |
477 | matthew-brett/delocate | delocate/libsana.py | wheel_libs | def wheel_libs(wheel_fname, filt_func = None):
""" Return analysis of library dependencies with a Python wheel
Use this routine for a dump of the dependency tree.
Parameters
----------
wheel_fname : str
Filename of wheel
filt_func : None or callable, optional
If None, inspect a... | python | def wheel_libs(wheel_fname, filt_func = None):
with TemporaryDirectory() as tmpdir:
zip2dir(wheel_fname, tmpdir)
lib_dict = tree_libs(tmpdir, filt_func)
return stripped_lib_dict(lib_dict, realpath(tmpdir) + os.path.sep) | [
"def",
"wheel_libs",
"(",
"wheel_fname",
",",
"filt_func",
"=",
"None",
")",
":",
"with",
"TemporaryDirectory",
"(",
")",
"as",
"tmpdir",
":",
"zip2dir",
"(",
"wheel_fname",
",",
"tmpdir",
")",
"lib_dict",
"=",
"tree_libs",
"(",
"tmpdir",
",",
"filt_func",
... | Return analysis of library dependencies with a Python wheel
Use this routine for a dump of the dependency tree.
Parameters
----------
wheel_fname : str
Filename of wheel
filt_func : None or callable, optional
If None, inspect all files for library dependencies. If callable,
... | [
"Return",
"analysis",
"of",
"library",
"dependencies",
"with",
"a",
"Python",
"wheel"
] | ed48de15fce31c3f52f1a9f32cae1b02fc55aa60 | https://github.com/matthew-brett/delocate/blob/ed48de15fce31c3f52f1a9f32cae1b02fc55aa60/delocate/libsana.py#L178-L205 |
478 | matthew-brett/delocate | delocate/wheeltools.py | rewrite_record | def rewrite_record(bdist_dir):
""" Rewrite RECORD file with hashes for all files in `wheel_sdir`
Copied from :method:`wheel.bdist_wheel.bdist_wheel.write_record`
Will also unsign wheel
Parameters
----------
bdist_dir : str
Path of unpacked wheel file
"""
info_dirs = glob.glob(... | python | def rewrite_record(bdist_dir):
info_dirs = glob.glob(pjoin(bdist_dir, '*.dist-info'))
if len(info_dirs) != 1:
raise WheelToolsError("Should be exactly one `*.dist_info` directory")
record_path = pjoin(info_dirs[0], 'RECORD')
record_relpath = relpath(record_path, bdist_dir)
# Unsign wheel - b... | [
"def",
"rewrite_record",
"(",
"bdist_dir",
")",
":",
"info_dirs",
"=",
"glob",
".",
"glob",
"(",
"pjoin",
"(",
"bdist_dir",
",",
"'*.dist-info'",
")",
")",
"if",
"len",
"(",
"info_dirs",
")",
"!=",
"1",
":",
"raise",
"WheelToolsError",
"(",
"\"Should be ex... | Rewrite RECORD file with hashes for all files in `wheel_sdir`
Copied from :method:`wheel.bdist_wheel.bdist_wheel.write_record`
Will also unsign wheel
Parameters
----------
bdist_dir : str
Path of unpacked wheel file | [
"Rewrite",
"RECORD",
"file",
"with",
"hashes",
"for",
"all",
"files",
"in",
"wheel_sdir"
] | ed48de15fce31c3f52f1a9f32cae1b02fc55aa60 | https://github.com/matthew-brett/delocate/blob/ed48de15fce31c3f52f1a9f32cae1b02fc55aa60/delocate/wheeltools.py#L35-L81 |
479 | matthew-brett/delocate | delocate/wheeltools.py | add_platforms | def add_platforms(in_wheel, platforms, out_path=None, clobber=False):
""" Add platform tags `platforms` to `in_wheel` filename and WHEEL tags
Add any platform tags in `platforms` that are missing from `in_wheel`
filename.
Add any platform tags in `platforms` that are missing from `in_wheel`
``WHEE... | python | def add_platforms(in_wheel, platforms, out_path=None, clobber=False):
in_wheel = abspath(in_wheel)
out_path = dirname(in_wheel) if out_path is None else abspath(out_path)
wf = WheelFile(in_wheel)
info_fname = _get_wheelinfo_name(wf)
# Check what tags we have
in_fname_tags = wf.parsed_filename.gr... | [
"def",
"add_platforms",
"(",
"in_wheel",
",",
"platforms",
",",
"out_path",
"=",
"None",
",",
"clobber",
"=",
"False",
")",
":",
"in_wheel",
"=",
"abspath",
"(",
"in_wheel",
")",
"out_path",
"=",
"dirname",
"(",
"in_wheel",
")",
"if",
"out_path",
"is",
"... | Add platform tags `platforms` to `in_wheel` filename and WHEEL tags
Add any platform tags in `platforms` that are missing from `in_wheel`
filename.
Add any platform tags in `platforms` that are missing from `in_wheel`
``WHEEL`` file.
Parameters
----------
in_wheel : str
Filename o... | [
"Add",
"platform",
"tags",
"platforms",
"to",
"in_wheel",
"filename",
"and",
"WHEEL",
"tags"
] | ed48de15fce31c3f52f1a9f32cae1b02fc55aa60 | https://github.com/matthew-brett/delocate/blob/ed48de15fce31c3f52f1a9f32cae1b02fc55aa60/delocate/wheeltools.py#L162-L222 |
480 | wiheto/teneto | teneto/networkmeasures/temporal_betweenness_centrality.py | temporal_betweenness_centrality | def temporal_betweenness_centrality(tnet=None, paths=None, calc='time'):
'''
Returns temporal betweenness centrality per node.
Parameters
-----------
Input should be *either* tnet or paths.
data : array or dict
Temporal network input (graphlet or contact). nettype: 'bu', 'bd'.
c... | python | def temporal_betweenness_centrality(tnet=None, paths=None, calc='time'):
'''
Returns temporal betweenness centrality per node.
Parameters
-----------
Input should be *either* tnet or paths.
data : array or dict
Temporal network input (graphlet or contact). nettype: 'bu', 'bd'.
c... | [
"def",
"temporal_betweenness_centrality",
"(",
"tnet",
"=",
"None",
",",
"paths",
"=",
"None",
",",
"calc",
"=",
"'time'",
")",
":",
"if",
"tnet",
"is",
"not",
"None",
"and",
"paths",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"'Only network or ... | Returns temporal betweenness centrality per node.
Parameters
-----------
Input should be *either* tnet or paths.
data : array or dict
Temporal network input (graphlet or contact). nettype: 'bu', 'bd'.
calc : str
either 'global' or 'time'
paths : pandas dataframe
O... | [
"Returns",
"temporal",
"betweenness",
"centrality",
"per",
"node",
"."
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/networkmeasures/temporal_betweenness_centrality.py#L9-L72 |
481 | wiheto/teneto | teneto/temporalcommunity/allegiance.py | allegiance | def allegiance(community):
"""
Computes the allegiance matrix with values representing the probability that
nodes i and j were assigned to the same community by time-varying clustering methods.
parameters
----------
community : array
array of community assignment of size node,time
... | python | def allegiance(community):
N = community.shape[0]
C = community.shape[1]
T = P = np.zeros([N, N])
for t in range(len(community[0, :])):
for i in range(len(community[:, 0])):
for j in range(len(community[:, 0])):
if i == j:
continue
... | [
"def",
"allegiance",
"(",
"community",
")",
":",
"N",
"=",
"community",
".",
"shape",
"[",
"0",
"]",
"C",
"=",
"community",
".",
"shape",
"[",
"1",
"]",
"T",
"=",
"P",
"=",
"np",
".",
"zeros",
"(",
"[",
"N",
",",
"N",
"]",
")",
"for",
"t",
... | Computes the allegiance matrix with values representing the probability that
nodes i and j were assigned to the same community by time-varying clustering methods.
parameters
----------
community : array
array of community assignment of size node,time
returns
-------
P : array
... | [
"Computes",
"the",
"allegiance",
"matrix",
"with",
"values",
"representing",
"the",
"probability",
"that",
"nodes",
"i",
"and",
"j",
"were",
"assigned",
"to",
"the",
"same",
"community",
"by",
"time",
"-",
"varying",
"clustering",
"methods",
"."
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/temporalcommunity/allegiance.py#L3-L39 |
482 | wiheto/teneto | teneto/generatenetwork/rand_poisson.py | rand_poisson | def rand_poisson(nnodes, ncontacts, lam=1, nettype='bu', netinfo=None, netrep='graphlet'):
"""
Generate a random network where intervals between contacts are distributed by a poisson distribution
Parameters
----------
nnodes : int
Number of nodes in networks
ncontacts : int or list
... | python | def rand_poisson(nnodes, ncontacts, lam=1, nettype='bu', netinfo=None, netrep='graphlet'):
if isinstance(ncontacts, list):
if len(ncontacts) != nnodes:
raise ValueError(
'Number of contacts, if a list, should be one per node')
if isinstance(lam, list):
if len(lam) != ... | [
"def",
"rand_poisson",
"(",
"nnodes",
",",
"ncontacts",
",",
"lam",
"=",
"1",
",",
"nettype",
"=",
"'bu'",
",",
"netinfo",
"=",
"None",
",",
"netrep",
"=",
"'graphlet'",
")",
":",
"if",
"isinstance",
"(",
"ncontacts",
",",
"list",
")",
":",
"if",
"le... | Generate a random network where intervals between contacts are distributed by a poisson distribution
Parameters
----------
nnodes : int
Number of nodes in networks
ncontacts : int or list
Number of expected contacts (i.e. edges). If list, number of contacts for each node.
Any ... | [
"Generate",
"a",
"random",
"network",
"where",
"intervals",
"between",
"contacts",
"are",
"distributed",
"by",
"a",
"poisson",
"distribution"
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/generatenetwork/rand_poisson.py#L9-L92 |
483 | wiheto/teneto | teneto/networkmeasures/temporal_efficiency.py | temporal_efficiency | def temporal_efficiency(tnet=None, paths=None, calc='global'):
r"""
Returns temporal efficiency estimate. BU networks only.
Parameters
----------
Input should be *either* tnet or paths.
data : array or dict
Temporal network input (graphlet or contact). nettype: 'bu', 'bd'.
paths ... | python | def temporal_efficiency(tnet=None, paths=None, calc='global'):
r"""
Returns temporal efficiency estimate. BU networks only.
Parameters
----------
Input should be *either* tnet or paths.
data : array or dict
Temporal network input (graphlet or contact). nettype: 'bu', 'bd'.
paths ... | [
"def",
"temporal_efficiency",
"(",
"tnet",
"=",
"None",
",",
"paths",
"=",
"None",
",",
"calc",
"=",
"'global'",
")",
":",
"if",
"tnet",
"is",
"not",
"None",
"and",
"paths",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"'Only network or path input... | r"""
Returns temporal efficiency estimate. BU networks only.
Parameters
----------
Input should be *either* tnet or paths.
data : array or dict
Temporal network input (graphlet or contact). nettype: 'bu', 'bd'.
paths : pandas dataframe
Output of TenetoBIDS.networkmeasure.sho... | [
"r",
"Returns",
"temporal",
"efficiency",
"estimate",
".",
"BU",
"networks",
"only",
"."
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/networkmeasures/temporal_efficiency.py#L9-L60 |
484 | wiheto/teneto | teneto/classes/network.py | TemporalNetwork.network_from_array | def network_from_array(self, array):
"""impo
Defines a network from an array.
Parameters
----------
array : array
3D numpy array.
"""
if len(array.shape) == 2:
array = np.array(array, ndmin=3).transpose([1, 2, 0])
teneto.utils.chec... | python | def network_from_array(self, array):
if len(array.shape) == 2:
array = np.array(array, ndmin=3).transpose([1, 2, 0])
teneto.utils.check_TemporalNetwork_input(array, 'array')
uvals = np.unique(array)
if len(uvals) == 2 and 1 in uvals and 0 in uvals:
i, j, t = np.wh... | [
"def",
"network_from_array",
"(",
"self",
",",
"array",
")",
":",
"if",
"len",
"(",
"array",
".",
"shape",
")",
"==",
"2",
":",
"array",
"=",
"np",
".",
"array",
"(",
"array",
",",
"ndmin",
"=",
"3",
")",
".",
"transpose",
"(",
"[",
"1",
",",
"... | impo
Defines a network from an array.
Parameters
----------
array : array
3D numpy array. | [
"impo",
"Defines",
"a",
"network",
"from",
"an",
"array",
"."
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/classes/network.py#L179-L202 |
485 | wiheto/teneto | teneto/classes/network.py | TemporalNetwork._drop_duplicate_ij | def _drop_duplicate_ij(self):
"""
Drops duplicate entries from the network dataframe.
"""
self.network['ij'] = list(map(lambda x: tuple(sorted(x)), list(
zip(*[self.network['i'].values, self.network['j'].values]))))
self.network.drop_duplicates(['ij', 't'], inplace=Tr... | python | def _drop_duplicate_ij(self):
self.network['ij'] = list(map(lambda x: tuple(sorted(x)), list(
zip(*[self.network['i'].values, self.network['j'].values]))))
self.network.drop_duplicates(['ij', 't'], inplace=True)
self.network.reset_index(inplace=True, drop=True)
self.network.d... | [
"def",
"_drop_duplicate_ij",
"(",
"self",
")",
":",
"self",
".",
"network",
"[",
"'ij'",
"]",
"=",
"list",
"(",
"map",
"(",
"lambda",
"x",
":",
"tuple",
"(",
"sorted",
"(",
"x",
")",
")",
",",
"list",
"(",
"zip",
"(",
"*",
"[",
"self",
".",
"ne... | Drops duplicate entries from the network dataframe. | [
"Drops",
"duplicate",
"entries",
"from",
"the",
"network",
"dataframe",
"."
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/classes/network.py#L260-L268 |
486 | wiheto/teneto | teneto/classes/network.py | TemporalNetwork._drop_diagonal | def _drop_diagonal(self):
"""
Drops self-contacts from the network dataframe.
"""
self.network = self.network.where(
self.network['i'] != self.network['j']).dropna()
self.network.reset_index(inplace=True, drop=True) | python | def _drop_diagonal(self):
self.network = self.network.where(
self.network['i'] != self.network['j']).dropna()
self.network.reset_index(inplace=True, drop=True) | [
"def",
"_drop_diagonal",
"(",
"self",
")",
":",
"self",
".",
"network",
"=",
"self",
".",
"network",
".",
"where",
"(",
"self",
".",
"network",
"[",
"'i'",
"]",
"!=",
"self",
".",
"network",
"[",
"'j'",
"]",
")",
".",
"dropna",
"(",
")",
"self",
... | Drops self-contacts from the network dataframe. | [
"Drops",
"self",
"-",
"contacts",
"from",
"the",
"network",
"dataframe",
"."
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/classes/network.py#L270-L276 |
487 | wiheto/teneto | teneto/classes/network.py | TemporalNetwork.add_edge | def add_edge(self, edgelist):
"""
Adds an edge from network.
Parameters
----------
edgelist : list
a list (or list of lists) containing the i,j and t indicies to be added. For weighted networks list should also contain a 'weight' key.
Returns
------... | python | def add_edge(self, edgelist):
if not isinstance(edgelist[0], list):
edgelist = [edgelist]
teneto.utils.check_TemporalNetwork_input(edgelist, 'edgelist')
if len(edgelist[0]) == 4:
colnames = ['i', 'j', 't', 'weight']
elif len(edgelist[0]) == 3:
colnames... | [
"def",
"add_edge",
"(",
"self",
",",
"edgelist",
")",
":",
"if",
"not",
"isinstance",
"(",
"edgelist",
"[",
"0",
"]",
",",
"list",
")",
":",
"edgelist",
"=",
"[",
"edgelist",
"]",
"teneto",
".",
"utils",
".",
"check_TemporalNetwork_input",
"(",
"edgelist... | Adds an edge from network.
Parameters
----------
edgelist : list
a list (or list of lists) containing the i,j and t indicies to be added. For weighted networks list should also contain a 'weight' key.
Returns
--------
Updates TenetoBIDS.network datafram... | [
"Adds",
"an",
"edge",
"from",
"network",
"."
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/classes/network.py#L297-L332 |
488 | wiheto/teneto | teneto/classes/network.py | TemporalNetwork.drop_edge | def drop_edge(self, edgelist):
"""
Removes an edge from network.
Parameters
----------
edgelist : list
a list (or list of lists) containing the i,j and t indicies to be removes.
Returns
--------
Updates TenetoBIDS.network dataframe
... | python | def drop_edge(self, edgelist):
if not isinstance(edgelist[0], list):
edgelist = [edgelist]
teneto.utils.check_TemporalNetwork_input(edgelist, 'edgelist')
if self.hdf5:
with pd.HDFStore(self.network) as hdf:
for e in edgelist:
hdf.remove... | [
"def",
"drop_edge",
"(",
"self",
",",
"edgelist",
")",
":",
"if",
"not",
"isinstance",
"(",
"edgelist",
"[",
"0",
"]",
",",
"list",
")",
":",
"edgelist",
"=",
"[",
"edgelist",
"]",
"teneto",
".",
"utils",
".",
"check_TemporalNetwork_input",
"(",
"edgelis... | Removes an edge from network.
Parameters
----------
edgelist : list
a list (or list of lists) containing the i,j and t indicies to be removes.
Returns
--------
Updates TenetoBIDS.network dataframe | [
"Removes",
"an",
"edge",
"from",
"network",
"."
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/classes/network.py#L334-L363 |
489 | wiheto/teneto | teneto/classes/network.py | TemporalNetwork.calc_networkmeasure | def calc_networkmeasure(self, networkmeasure, **measureparams):
"""
Calculate network measure.
Parameters
-----------
networkmeasure : str
Function to call. Functions available are in teneto.networkmeasures
measureparams : kwargs
kwargs for tenet... | python | def calc_networkmeasure(self, networkmeasure, **measureparams):
availablemeasures = [f for f in dir(
teneto.networkmeasures) if not f.startswith('__')]
if networkmeasure not in availablemeasures:
raise ValueError(
'Unknown network measure. Available network measur... | [
"def",
"calc_networkmeasure",
"(",
"self",
",",
"networkmeasure",
",",
"*",
"*",
"measureparams",
")",
":",
"availablemeasures",
"=",
"[",
"f",
"for",
"f",
"in",
"dir",
"(",
"teneto",
".",
"networkmeasures",
")",
"if",
"not",
"f",
".",
"startswith",
"(",
... | Calculate network measure.
Parameters
-----------
networkmeasure : str
Function to call. Functions available are in teneto.networkmeasures
measureparams : kwargs
kwargs for teneto.networkmeasure.[networkmeasure] | [
"Calculate",
"network",
"measure",
"."
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/classes/network.py#L365-L385 |
490 | wiheto/teneto | teneto/classes/network.py | TemporalNetwork.generatenetwork | def generatenetwork(self, networktype, **networkparams):
"""
Generate a network
Parameters
-----------
networktype : str
Function to call. Functions available are in teneto.generatenetwork
measureparams : kwargs
kwargs for teneto.generatenetwork.... | python | def generatenetwork(self, networktype, **networkparams):
availabletypes = [f for f in dir(
teneto.generatenetwork) if not f.startswith('__')]
if networktype not in availabletypes:
raise ValueError(
'Unknown network measure. Available networks to generate are: ' + ... | [
"def",
"generatenetwork",
"(",
"self",
",",
"networktype",
",",
"*",
"*",
"networkparams",
")",
":",
"availabletypes",
"=",
"[",
"f",
"for",
"f",
"in",
"dir",
"(",
"teneto",
".",
"generatenetwork",
")",
"if",
"not",
"f",
".",
"startswith",
"(",
"'__'",
... | Generate a network
Parameters
-----------
networktype : str
Function to call. Functions available are in teneto.generatenetwork
measureparams : kwargs
kwargs for teneto.generatenetwork.[networktype]
Returns
--------
TenetoBIDS.network is... | [
"Generate",
"a",
"network"
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/classes/network.py#L387-L413 |
491 | wiheto/teneto | teneto/classes/network.py | TemporalNetwork.save_aspickle | def save_aspickle(self, fname):
"""
Saves object as pickle.
fname : str
file path.
"""
if fname[-4:] != '.pkl':
fname += '.pkl'
with open(fname, 'wb') as f:
pickle.dump(self, f, pickle.HIGHEST_PROTOCOL) | python | def save_aspickle(self, fname):
if fname[-4:] != '.pkl':
fname += '.pkl'
with open(fname, 'wb') as f:
pickle.dump(self, f, pickle.HIGHEST_PROTOCOL) | [
"def",
"save_aspickle",
"(",
"self",
",",
"fname",
")",
":",
"if",
"fname",
"[",
"-",
"4",
":",
"]",
"!=",
"'.pkl'",
":",
"fname",
"+=",
"'.pkl'",
"with",
"open",
"(",
"fname",
",",
"'wb'",
")",
"as",
"f",
":",
"pickle",
".",
"dump",
"(",
"self",... | Saves object as pickle.
fname : str
file path. | [
"Saves",
"object",
"as",
"pickle",
"."
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/classes/network.py#L441-L451 |
492 | wiheto/teneto | teneto/timeseries/postprocess.py | postpro_fisher | def postpro_fisher(data, report=None):
"""
Performs fisher transform on everything in data.
If report variable is passed, this is added to the report.
"""
if not report:
report = {}
# Due to rounding errors
data[data < -0.99999999999999] = -1
data[data > 0.99999999999999] = 1
... | python | def postpro_fisher(data, report=None):
if not report:
report = {}
# Due to rounding errors
data[data < -0.99999999999999] = -1
data[data > 0.99999999999999] = 1
fisher_data = 0.5 * np.log((1 + data) / (1 - data))
report['fisher'] = {}
report['fisher']['performed'] = 'yes'
#report... | [
"def",
"postpro_fisher",
"(",
"data",
",",
"report",
"=",
"None",
")",
":",
"if",
"not",
"report",
":",
"report",
"=",
"{",
"}",
"# Due to rounding errors",
"data",
"[",
"data",
"<",
"-",
"0.99999999999999",
"]",
"=",
"-",
"1",
"data",
"[",
"data",
">"... | Performs fisher transform on everything in data.
If report variable is passed, this is added to the report. | [
"Performs",
"fisher",
"transform",
"on",
"everything",
"in",
"data",
"."
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/timeseries/postprocess.py#L10-L25 |
493 | wiheto/teneto | teneto/timeseries/postprocess.py | postpro_boxcox | def postpro_boxcox(data, report=None):
"""
Performs box cox transform on everything in data.
If report variable is passed, this is added to the report.
"""
if not report:
report = {}
# Note the min value of all time series will now be at least 1.
mindata = 1 - np.nanmin(data)
da... | python | def postpro_boxcox(data, report=None):
if not report:
report = {}
# Note the min value of all time series will now be at least 1.
mindata = 1 - np.nanmin(data)
data = data + mindata
ind = np.triu_indices(data.shape[0], k=1)
boxcox_list = np.array([sp.stats.boxcox(np.squeeze(
dat... | [
"def",
"postpro_boxcox",
"(",
"data",
",",
"report",
"=",
"None",
")",
":",
"if",
"not",
"report",
":",
"report",
"=",
"{",
"}",
"# Note the min value of all time series will now be at least 1.",
"mindata",
"=",
"1",
"-",
"np",
".",
"nanmin",
"(",
"data",
")",... | Performs box cox transform on everything in data.
If report variable is passed, this is added to the report. | [
"Performs",
"box",
"cox",
"transform",
"on",
"everything",
"in",
"data",
"."
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/timeseries/postprocess.py#L28-L78 |
494 | wiheto/teneto | teneto/utils/utils.py | binarize_rdp | def binarize_rdp(netin, level, sign='pos', axis='time'):
"""
Binarizes a network based on RDP compression.
Parameters
----------
netin : array or dict
Network (graphlet or contact representation),
level : float
Delta parameter which is the tolorated error in RDP compression.
... | python | def binarize_rdp(netin, level, sign='pos', axis='time'):
netin, netinfo = process_input(netin, ['C', 'G', 'TO'])
trajectory = rdp(netin, level)
contacts = []
# Use the trajectory points as threshold
for n in range(trajectory['index'].shape[0]):
if sign == 'pos':
sel = trajectory... | [
"def",
"binarize_rdp",
"(",
"netin",
",",
"level",
",",
"sign",
"=",
"'pos'",
",",
"axis",
"=",
"'time'",
")",
":",
"netin",
",",
"netinfo",
"=",
"process_input",
"(",
"netin",
",",
"[",
"'C'",
",",
"'G'",
",",
"'TO'",
"]",
")",
"trajectory",
"=",
... | Binarizes a network based on RDP compression.
Parameters
----------
netin : array or dict
Network (graphlet or contact representation),
level : float
Delta parameter which is the tolorated error in RDP compression.
sign : str, default='pos'
States the sign of the thresholdi... | [
"Binarizes",
"a",
"network",
"based",
"on",
"RDP",
"compression",
"."
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/utils/utils.py#L283-L335 |
495 | wiheto/teneto | teneto/utils/utils.py | binarize | def binarize(netin, threshold_type, threshold_level, sign='pos', axis='time'):
"""
Binarizes a network, returning the network. General wrapper function for different binarization functions.
Parameters
----------
netin : array or dict
Network (graphlet or contact representation),
thresh... | python | def binarize(netin, threshold_type, threshold_level, sign='pos', axis='time'):
if threshold_type == 'percent':
netout = binarize_percent(netin, threshold_level, sign, axis)
elif threshold_type == 'magnitude':
netout = binarize_magnitude(netin, threshold_level, sign)
elif threshold_type == 'r... | [
"def",
"binarize",
"(",
"netin",
",",
"threshold_type",
",",
"threshold_level",
",",
"sign",
"=",
"'pos'",
",",
"axis",
"=",
"'time'",
")",
":",
"if",
"threshold_type",
"==",
"'percent'",
":",
"netout",
"=",
"binarize_percent",
"(",
"netin",
",",
"threshold_... | Binarizes a network, returning the network. General wrapper function for different binarization functions.
Parameters
----------
netin : array or dict
Network (graphlet or contact representation),
threshold_type : str
What type of thresholds to make binarization. Options: 'rdp', 'perce... | [
"Binarizes",
"a",
"network",
"returning",
"the",
"network",
".",
"General",
"wrapper",
"function",
"for",
"different",
"binarization",
"functions",
"."
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/utils/utils.py#L382-L422 |
496 | wiheto/teneto | teneto/utils/utils.py | process_input | def process_input(netIn, allowedformats, outputformat='G'):
"""
Takes input network and checks what the input is.
Parameters
----------
netIn : array, dict, or TemporalNetwork
Network (graphlet, contact or object)
allowedformats : str
Which format of network objects that are al... | python | def process_input(netIn, allowedformats, outputformat='G'):
inputtype = checkInput(netIn)
# Convert TN to G representation
if inputtype == 'TN' and 'TN' in allowedformats and outputformat != 'TN':
G = netIn.df_to_array()
netInfo = {'nettype': netIn.nettype, 'netshape': netIn.netshape}
el... | [
"def",
"process_input",
"(",
"netIn",
",",
"allowedformats",
",",
"outputformat",
"=",
"'G'",
")",
":",
"inputtype",
"=",
"checkInput",
"(",
"netIn",
")",
"# Convert TN to G representation",
"if",
"inputtype",
"==",
"'TN'",
"and",
"'TN'",
"in",
"allowedformats",
... | Takes input network and checks what the input is.
Parameters
----------
netIn : array, dict, or TemporalNetwork
Network (graphlet, contact or object)
allowedformats : str
Which format of network objects that are allowed. Options: 'C', 'TN', 'G'.
outputformat: str, default=G
... | [
"Takes",
"input",
"network",
"and",
"checks",
"what",
"the",
"input",
"is",
"."
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/utils/utils.py#L575-L646 |
497 | wiheto/teneto | teneto/utils/utils.py | clean_community_indexes | def clean_community_indexes(communityID):
"""
Takes input of community assignments. Returns reindexed community assignment by using smallest numbers possible.
Parameters
----------
communityID : array-like
list or array of integers. Output from community detection algorithems.
Returns... | python | def clean_community_indexes(communityID):
communityID = np.array(communityID)
cid_shape = communityID.shape
if len(cid_shape) > 1:
communityID = communityID.flatten()
new_communityID = np.zeros(len(communityID))
for i, n in enumerate(np.unique(communityID)):
new_communityID[community... | [
"def",
"clean_community_indexes",
"(",
"communityID",
")",
":",
"communityID",
"=",
"np",
".",
"array",
"(",
"communityID",
")",
"cid_shape",
"=",
"communityID",
".",
"shape",
"if",
"len",
"(",
"cid_shape",
")",
">",
"1",
":",
"communityID",
"=",
"communityI... | Takes input of community assignments. Returns reindexed community assignment by using smallest numbers possible.
Parameters
----------
communityID : array-like
list or array of integers. Output from community detection algorithems.
Returns
-------
new_communityID : array
clea... | [
"Takes",
"input",
"of",
"community",
"assignments",
".",
"Returns",
"reindexed",
"community",
"assignment",
"by",
"using",
"smallest",
"numbers",
"possible",
"."
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/utils/utils.py#L649-L680 |
498 | wiheto/teneto | teneto/utils/utils.py | multiple_contacts_get_values | def multiple_contacts_get_values(C):
"""
Given an contact representation with repeated contacts, this function removes duplicates and creates a value
Parameters
----------
C : dict
contact representation with multiple repeated contacts.
Returns
-------
:C_out: dict
... | python | def multiple_contacts_get_values(C):
d = collections.OrderedDict()
for c in C['contacts']:
ct = tuple(c)
if ct in d:
d[ct] += 1
else:
d[ct] = 1
new_contacts = []
new_values = []
for (key, value) in d.items():
new_values.append(value)
n... | [
"def",
"multiple_contacts_get_values",
"(",
"C",
")",
":",
"d",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"for",
"c",
"in",
"C",
"[",
"'contacts'",
"]",
":",
"ct",
"=",
"tuple",
"(",
"c",
")",
"if",
"ct",
"in",
"d",
":",
"d",
"[",
"ct",
"... | Given an contact representation with repeated contacts, this function removes duplicates and creates a value
Parameters
----------
C : dict
contact representation with multiple repeated contacts.
Returns
-------
:C_out: dict
Contact representation with duplicate contacts re... | [
"Given",
"an",
"contact",
"representation",
"with",
"repeated",
"contacts",
"this",
"function",
"removes",
"duplicates",
"and",
"creates",
"a",
"value"
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/utils/utils.py#L683-L718 |
499 | wiheto/teneto | teneto/utils/utils.py | check_distance_funciton_input | def check_distance_funciton_input(distance_func_name, netinfo):
"""
Funciton checks distance_func_name, if it is specified as 'default'. Then given the type of the network selects a default distance function.
Parameters
----------
distance_func_name : str
distance function name.
netin... | python | def check_distance_funciton_input(distance_func_name, netinfo):
if distance_func_name == 'default' and netinfo['nettype'][0] == 'b':
print('Default distance funciton specified. As network is binary, using Hamming')
distance_func_name = 'hamming'
elif distance_func_name == 'default' and netinfo['... | [
"def",
"check_distance_funciton_input",
"(",
"distance_func_name",
",",
"netinfo",
")",
":",
"if",
"distance_func_name",
"==",
"'default'",
"and",
"netinfo",
"[",
"'nettype'",
"]",
"[",
"0",
"]",
"==",
"'b'",
":",
"print",
"(",
"'Default distance funciton specified.... | Funciton checks distance_func_name, if it is specified as 'default'. Then given the type of the network selects a default distance function.
Parameters
----------
distance_func_name : str
distance function name.
netinfo : dict
the output of utils.process_input
Returns
-------... | [
"Funciton",
"checks",
"distance_func_name",
"if",
"it",
"is",
"specified",
"as",
"default",
".",
"Then",
"given",
"the",
"type",
"of",
"the",
"network",
"selects",
"a",
"default",
"distance",
"function",
"."
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/utils/utils.py#L757-L786 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.