code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
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.username or default_u... | 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 | 2.350061 | 2.426436 | 0.968524 |
value = 'http%s' % url[5:] if url[:5] == 'postgresql' else url
parsed = _urlparse.urlparse(value)
path, query = parsed.path, parsed.query
hostname = parsed.hostname if parsed.hostname else ''
return PARSED(parsed.scheme.replace('http', 'postgresql'),
parsed.netloc,
... | def urlparse(url) | Parse the URL in a Python2/3 independent fashion.
:param str url: The URL to parse
:rtype: Parsed | 3.465995 | 3.988016 | 0.869103 |
self._freed = True
self._cleanup(self.cursor, self._fd) | def free(self) | Release the results and connection lock from the TornadoSession
object. This **must** be called after you finish processing the results
from :py:meth:`TornadoSession.query <queries.TornadoSession.query>` or
:py:meth:`TornadoSession.callproc <queries.TornadoSession.callproc>`
or the conne... | 17.509333 | 18.454742 | 0.948771 |
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) | Create the pool in the pool manager if it does not exist. | 6.306632 | 4.699572 | 1.341959 |
future = concurrent.Future()
# Attempt to get a cached connection from the connection pool
try:
connection = self._pool_manager.get(self.pid, self)
self._connections[connection.fileno()] = connection
future.set_result(connection)
# Add t... | def _connect(self) | Connect to PostgreSQL, either by reusing a connection from the pool
if possible, or by creating the new connection.
:rtype: psycopg2.extensions.connection
:raises: pool.NoIdleConnectionsError | 4.911685 | 4.113703 | 1.193981 |
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.error) as error:
fut... | def _create_connection(self, future) | Create a new PostgreSQL connection
:param tornado.concurrent.Future future: future for new conn result | 4.434087 | 4.421162 | 1.002923 |
future = concurrent.Future()
def on_connected(cf):
if cf.exception():
future.set_exception(cf.exception())
return
# Get the psycopg2 connection object and cursor
conn = cf.result()
cursor = self._get_... | def _execute(self, method, query, parameters=None) | Issue a query asynchronously on the server, mogrifying the
parameters against the sql statement and yielding the results
as a :py:class:`Results <queries.tornado_session.Results>` object.
This function reduces duplicate code for callproc and query by getting
the class attribute for the ... | 4.039534 | 3.96846 | 1.01791 |
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 callback exists, remove it
... | 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 | 3.880496 | 3.763165 | 1.031179 |
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._connections[fd].close()
... | 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 | 3.421891 | 3.297422 | 1.037748 |
self._pool_manager.get_connection(self.pid, conn).exceptions += 1 | def _incr_exceptions(self, conn) | Increment the number of exceptions for the current connection.
:param psycopg2.extensions.connection conn: the psycopg2 connection | 15.214023 | 19.648876 | 0.774295 |
self._pool_manager.get_connection(self.pid, conn).executions += 1 | def _incr_executions(self, conn) | Increment the number of executions for the current connection.
:param psycopg2.extensions.connection conn: the psycopg2 connection | 16.988785 | 21.24884 | 0.799516 |
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) | 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 | 6.705866 | 9.816114 | 0.683149 |
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(
psycopg2.Operation... | 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 | 1.883603 | 1.879013 | 1.002443 |
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() | Setup.py entry point. | 2.912986 | 2.857394 | 1.019455 |
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 != -1, (pos_begin, ... | def _do_readme_update(self) | Patch README.rst to reflect the data files used in release. | 2.741024 | 2.594478 | 1.056484 |
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, date, table) | def _do_east_asian(self) | Fetch and update east-asian tables. | 6.576388 | 5.819427 | 1.130075 |
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, table) | def _do_zero_width(self) | Fetch and update zero width tables. | 9.998808 | 8.828263 | 1.132591 |
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()
if end == value ... | def _make_table(values) | Return a tuple of lookup tables for given values. | 3.003666 | 2.73174 | 1.099543 |
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(url))
r... | def _do_retrieve(url, fname) | Retrieve given url to target filepath fname. | 2.62775 | 2.586979 | 1.01576 |
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()
continue
elif date i... | def _parse_east_asian(fname, properties=(u'W', u'F',)) | Parse unicode east-asian width tables. | 2.834951 | 2.806762 | 1.010043 |
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()
continue
elif date i... | def _parse_category(fname, categories) | Parse unicode category tables. | 2.99987 | 2.811601 | 1.066961 |
# 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()
indent = 4
with open(fname, 'w') as fout:... | def _do_write(fname, variable, version, date, table) | Write combining tables to filesystem as python code. | 3.270136 | 3.22011 | 1.015535 |
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={} {}"
" ".format(wcwidth_libc, wcwidth_local, uc... | 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 character length.
:type comb_wc: int
:rtype: unicode | 10.285552 | 9.091536 | 1.131333 |
all_ucs = (ucs for ucs in
[unichr(val) for val in range(sys.maxunicode)]
if is_named(ucs) and isnt_combining(ucs))
libc_name = ctypes.util.find_library('c')
if not libc_name:
raise ImportError("Can't find C library.")
libc = ctypes.cdll.LoadLibrary(libc_name)... | def main(using_locale=('en_US', 'UTF-8',)) | Program entry point.
Load the entire Unicode table into memory, excluding those that:
- are not named (func unicodedata.name returns empty string),
- are combining characters.
Using ``locale``, for each unicode character string compare libc's
wcwidth with local wcwidth.wcwidth() function;... | 3.173612 | 2.918585 | 1.087381 |
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']
opts['--wide'] = int(op... | def validate_args(opts) | Validate and return options provided by docopt parsing. | 3.658015 | 3.618355 | 1.010961 |
term = Terminal()
style = Style()
# if the terminal supports colors, use a Style instance with some
# standout colors (magenta, cyan).
if term.number_of_colors:
style = Style(attr_major=term.magenta,
attr_minor=term.bright_cyan,
alignment=opt... | def main(opts) | Program entry point. | 8.042543 | 7.779984 | 1.033748 |
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) | Width of a column segment. | 15.951753 | 14.903624 | 1.070327 |
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 self.style.a... | def head_item(self) | Text of a single column heading. | 6.104243 | 6.052117 | 1.008613 |
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) | Introductory message disabled above heading. | 13.813111 | 12.839695 | 1.075813 |
if self.term.is_a_tty:
return self.term.width // self.hint_width
return 1 | def num_columns(self) | Number of columns displayed. | 13.668602 | 8.479787 | 1.611904 |
# 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 small {}, must be at le... | def on_resize(self, *args) | Signal handler callback for SIGWINCH. | 6.986864 | 6.219445 | 1.12339 |
self.last_page = (len(self._page_data) - 1) // self.screen.page_size | def _set_lastpage(self) | Calculate value of class attribute ``last_page``. | 6.631663 | 4.681802 | 1.416477 |
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.term.center(
... | def display_initialize(self) | Display 'please wait' message, and narrow build warning. | 8.088936 | 7.904029 | 1.023394 |
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))
except StopIteration:
... | def initialize_page_data(self) | Initialize the page data for the given screen. | 9.03126 | 8.126624 | 1.111318 |
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 = 0
idx = min(max(... | 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)``
:rtype: list[(unicode, unicode)] | 3.13719 | 3.20839 | 0.977808 |
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
self.dirty = self.S... | def _run_notty(self, writer) | Pager run method for terminals that are not a tty. | 6.723699 | 6.232821 | 1.078757 |
# 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,
page_idx,
... | def _run_tty(self, writer, reader) | Pager run method for terminals that are a tty. | 4.446747 | 4.282129 | 1.038443 |
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) | 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... | 6.304342 | 5.840881 | 1.079348 |
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) | 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: ... | 4.456269 | 4.09636 | 1.087861 |
if inp in (u'1', u'2'):
# chose 1 or 2-character wide
if int(inp) != self.screen.wide:
self.screen.wide = int(inp)
self.on_resize(None, None)
elif inp in (u'_', u'-'):
# adjust name length -2
nlen = max(1, self.scre... | def _process_keystroke_commands(self, inp) | Process keystrokes that issue commands (side effects). | 2.503141 | 2.533008 | 0.988209 |
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,
term.KE... | def _process_keystroke_movement(self, inp, idx, offset) | Process keystrokes that adjust index and offset. | 2.145597 | 2.108073 | 1.0178 |
# 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.dirty = self.STATE_CLEAN
... | 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 current page.
:type offset: int
:returns:... | 13.142763 | 12.497894 | 1.051598 |
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) | 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... | 9.684248 | 6.352306 | 1.524525 |
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_end = u'/{0}'.format(self.la... | 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 | 5.526968 | 5.213851 | 1.060055 |
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 and row, where colum... | 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 | 6.285541 | 5.577068 | 1.127033 |
style = self.screen.style
if len(name) > style.name_len:
idx = max(0, style.name_len - len(style.continuation))
name = u''.join((name[:idx], style.continuation if idx else u''))
if style.alignment == 'right':
fmt = u' '.join(('0x{val:0>{ucs_printlen}x... | def text_entry(self, ucs, name) | Display a single column segment row describing ``(ucs, name)``.
:param ucs: target unicode point character string.
:param name: name of unicode point.
:rtype: unicode | 4.902145 | 4.779487 | 1.025663 |
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
cmd_str = ' '.join(cmd) if cmd_is_seq else cmd
if re... | 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, return stderr in addition to stdout. If False, just return
stdout... | 2.169631 | 2.305852 | 0.940924 |
uniques = []
for element in sequence:
if element not in uniques:
uniques.append(element)
return uniques | 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` | 2.267486 | 2.836766 | 0.799321 |
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(filename, *args, **kwargs)
fina... | 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. | 2.979243 | 2.604473 | 1.143895 |
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] == install_id
return... | 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
-------
install_names : tuple
tuple of inst... | 4.798578 | 5.231236 | 0.917293 |
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].strip() | 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 `filename`, or None if no install id | 5.304718 | 5.506626 | 0.963334 |
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) | 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` | 3.447337 | 4.04857 | 0.851495 |
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) | 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 | 5.568525 | 6.894362 | 0.807692 |
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):
line = lines[line_no]
... | 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` | 3.723567 | 3.912677 | 0.951667 |
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 permissions, but allow copy
... | 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
----------
in_dir : str
Director... | 2.899804 | 2.936224 | 0.987596 |
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) | 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... | 2.8266 | 2.874171 | 0.983449 |
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) | 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 ... | 2.326733 | 2.371452 | 0.981143 |
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, output from lipo -i... | 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
of 'ppc', 'ppc64', 'i386... | 3.969168 | 3.872916 | 1.024853 |
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, and adding a new one isn't nec... | 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
----------
filename : str
Filepath to a... | 9.292333 | 9.78694 | 0.949463 |
if not path:
raise ValueError("no path specified")
start_list = [x for x in os.path.abspath(start).split(os.path.sep) if x]
path_list = [x for x in os.path.abspath(path).split(os.path.sep) if x]
# Work out how much of the filepath is shared by start and path.
i = len(os.path.commonpr... | def os_path_relpath(path, start=os.path.curdir) | Return a relative version of a path | 1.326522 | 1.270488 | 1.044104 |
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 = pjoin(to_dirpath, dirname)
if not exists(to_path):
... | 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.tools.lipo_fuse` to fuse the
two libraries together and write into `to_tre... | 2.921226 | 2.918797 | 1.000832 |
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')
rewrite_record('to_wheel')
dir2zip('to... | 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 fusion of `to_wheel` and `from_wheel` | 3.525126 | 3.996774 | 0.881993 |
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 lib_dict.items():
if required.startswith('... | 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 `lib_path`. Fix up the rpaths and install
names in the re... | 4.365513 | 4.30743 | 1.013484 |
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 = len(copied_libs) == in_len
return copied_libs | 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 dependencies that match the filter `copy_filt_func`. It also
adjusts the dependin... | 2.54252 | 2.622015 | 0.969681 |
# 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)
for required, requirings in lib_dict.items():
... | 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
----------
lib_path : str
Directory containing libraries
co... | 6.334229 | 5.91127 | 1.071551 |
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)
if not copy_filt_func is None:
lib_dict = dict((key, value) for key, value in lib_dict.items()
... | 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
lib_path : str
Directory into which we copy required libraries
lib_filt_func : None or str or callable, optional
If None,... | 2.950115 | 2.866607 | 1.029131 |
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) | Merges lib_dict `d2` into lib_dict `d1` | 3.808742 | 3.401402 | 1.119756 |
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".format(patch_fname))
with InWheel(in_wheel, ou... | 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_fname : str
Filename of patch file. Will be applied with ... | 2.083468 | 2.24162 | 0.929447 |
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_dict in copied_libs.items():
depended_archs = get_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 real path
that has been copied during delocation, and ``dependings... | 2.409355 | 1.944581 | 1.23901 |
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("{0} needs {1} {2} missing from {3}".... | 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 ``depending_lib``. A length 3 tuple
is o... | 2.796139 | 2.235158 | 1.25098 |
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
rpaths = get_rpaths(depending_... | 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 for library dependencies. If callable,
acc... | 2.540508 | 2.228515 | 1.14 |
if not lib_path.startswith('@rpath/'):
return lib_path
lib_rpath = lib_path.split('/', 1)[1]
for rpath in rpaths:
rpath_lib = realpath(pjoin(rpath, lib_rpath))
if os.path.exists(rpath_lib):
return rpath_lib
warnings.warn(
"Couldn't find {0} on paths:\n\... | def resolve_rpath(lib_path, rpaths) | Return `lib_path` with its `@rpath` resolved
If the `lib_path` doesn't have `@rpath` then it's returned as is.
If `lib_path` has `@rpath` then returns the first `rpaths`/`lib_path`
combination found. If the library can't be found in `rpaths` then a
detailed warning is printed and `lib_path` is return... | 2.451395 | 2.355479 | 1.04072 |
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) | 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... | 2.986485 | 4.894447 | 0.610178 |
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)] = install_name
relative_dict[stri... | 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 analyzing.
Parameters
----------
lib_dict : dic... | 3.680371 | 3.963366 | 0.928597 |
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) | 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,
... | 6.124689 | 7.709787 | 0.794404 |
if sys.version_info[0] < 3:
return open_rw(name, mode + 'b')
return open_rw(name, mode, newline='', encoding='utf-8') | def _open_for_csv(name, mode) | Deal with Python 2/3 open API differences | 3.33038 | 2.853034 | 1.167312 |
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 - because we're invalidating ... | 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 | 3.162329 | 3.031854 | 1.043035 |
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.groupdict()['plat'].split('.')
extra_fname_tags = [tag for tag ... | 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`
``WHEEL`` file.
Parameters
----------
in_wheel : str
Filename o... | 3.399784 | 3.41975 | 0.994162 |
'''
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 datafram... | 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'.
calc : str
either 'global' or 'time'
paths : pandas dataframe
O... | 5.136067 | 2.174543 | 2.361907 |
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
# T_ij indicates the ... | 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
returns
-------
P : array
... | 4.341524 | 3.232135 | 1.343237 |
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) != nnodes:
raise ValueError(
'Lambda value of Poisson distri... | 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
Number of expected contacts (i.e. edges). If list, number of contacts for each node.
Any ... | 2.343398 | 2.287699 | 1.024347 |
r
if tnet is not None and paths is not None:
raise ValueError('Only network or path input allowed.')
if tnet is None and paths is None:
raise ValueError('No input.')
# if shortest paths are not calculated, calculate them
if tnet is not None:
paths = shortest_temporal_path(tn... | 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 : pandas dataframe
Output of TenetoBIDS.networkmeasure.sho... | 3.28549 | 3.10582 | 1.057849 |
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.where(array == 1)
... | def network_from_array(self, array) | impo
Defines a network from an array.
Parameters
----------
array : array
3D numpy array. | 2.907504 | 2.946008 | 0.98693 |
teneto.utils.check_TemporalNetwork_input(df, 'df')
self.network = df
self._update_network() | def network_from_df(self, df) | Defines a network from an array.
Parameters
----------
array : array
Pandas dataframe. Should have columns: \'i\', \'j\', \'t\' where i and j are node indicies and t is the temporal index.
If weighted, should also include \'weight\'. Each row is an edge. | 19.128666 | 22.856434 | 0.836905 |
teneto.utils.check_TemporalNetwork_input(edgelist, 'edgelist')
if len(edgelist[0]) == 4:
colnames = ['i', 'j', 't', 'weight']
elif len(edgelist[0]) == 3:
colnames = ['i', 'j', 't']
self.network = pd.DataFrame(edgelist, columns=colnames)
self._upda... | def network_from_edgelist(self, edgelist) | Defines a network from an array.
Parameters
----------
edgelist : list of lists.
A list of lists which are 3 or 4 in length. For binary networks each sublist should be [i, j ,t] where i and j are node indicies and t is the temporal index.
For weighted networks each subli... | 3.601045 | 3.452473 | 1.043034 |
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.drop('ij', inplace=Tru... | def _drop_duplicate_ij(self) | Drops duplicate entries from the network dataframe. | 3.032341 | 2.372205 | 1.278279 |
self.network = self.network.where(
self.network['i'] != self.network['j']).dropna()
self.network.reset_index(inplace=True, drop=True) | def _drop_diagonal(self) | Drops self-contacts from the network dataframe. | 4.037416 | 2.706006 | 1.49202 |
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 = ['i', 'j', 't']
... | 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
--------
Updates TenetoBIDS.network datafram... | 2.439584 | 2.226959 | 1.095478 |
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) | 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 | 3.399093 | 3.002503 | 1.132086 |
availablemeasures = [f for f in dir(
teneto.networkmeasures) if not f.startswith('__')]
if networkmeasure not in availablemeasures:
raise ValueError(
'Unknown network measure. Available network measures are: ' + ', '.join(availablemeasures))
funs ... | 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 teneto.networkmeasure.[networkmeasure] | 2.793876 | 2.548067 | 1.096469 |
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: ' + ', '.join(availabletypes))
funs = inspec... | 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.[networktype]
Returns
--------
TenetoBIDS.network is... | 4.846408 | 4.341258 | 1.11636 |
if fname[-4:] != '.pkl':
fname += '.pkl'
with open(fname, 'wb') as f:
pickle.dump(self, f, pickle.HIGHEST_PROTOCOL) | def save_aspickle(self, fname) | Saves object as pickle.
fname : str
file path. | 1.898882 | 2.123991 | 0.894016 |
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['fisher']['diagonal'] = 'zeroed'
... | def postpro_fisher(data, report=None) | Performs fisher transform on everything in data.
If report variable is passed, this is added to the report. | 3.069094 | 2.92538 | 1.049127 |
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(
data[ind[0][n], ind[1][n], :])) for n... | 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. | 3.859484 | 3.796534 | 1.016581 |
if not report:
report = {}
# First make dim 1 = time.
data = np.transpose(data, [2, 0, 1])
standardized_data = (data - data.mean(axis=0)) / data.std(axis=0)
standardized_data = np.transpose(standardized_data, [1, 2, 0])
report['standardize'] = {}
report['standardize']['performed... | def postpro_standardize(data, report=None) | Standardizes everything in data (along axis -1).
If report variable is passed, this is added to the report. | 3.97132 | 3.979377 | 0.997975 |
weights = np.ones([T, T])
np.fill_diagonal(weights, 0)
report['method'] = 'jackknife'
report['jackknife'] = ''
return weights, report | def _weightfun_jackknife(T, report) | Creates the weights for the jackknife method. See func: teneto.derive.derive. | 4.540163 | 4.203338 | 1.080133 |
weightat0 = np.zeros(T)
weightat0[0:params['windowsize']] = np.ones(params['windowsize'])
weights = np.array([np.roll(weightat0, i)
for i in range(0, T + 1 - params['windowsize'])])
report['method'] = 'slidingwindow'
report['slidingwindow'] = params
report['slidingwi... | def _weightfun_sliding_window(T, params, report) | Creates the weights for the sliding window method. See func: teneto.derive.derive. | 4.12341 | 4.035889 | 1.021686 |
x = np.arange(-(params['windowsize'] - 1) / 2, (params['windowsize']) / 2)
distribution_parameters = ','.join(map(str, params['distribution_params']))
taper = eval('sps.' + params['distribution'] +
'.pdf(x,' + distribution_parameters + ')')
weightat0 = np.zeros(T)
... | def _weightfun_tapered_sliding_window(T, params, report) | Creates the weights for the tapered method. See func: teneto.derive.derive. | 3.73615 | 3.713936 | 1.005981 |
distance = getDistanceFunction(params['distance'])
weights = np.array([distance(data[n, :], data[t, :]) for n in np.arange(
0, data.shape[0]) for t in np.arange(0, data.shape[0])])
weights = np.reshape(weights, [data.shape[0], data.shape[0]])
np.fill_diagonal(weights, np.nan)
weights = ... | def _weightfun_spatial_distance(data, params, report) | Creates the weights for the spatial distance method. See func: teneto.derive.derive. | 2.366621 | 2.372177 | 0.997658 |
# Data should be timexnode
report = {}
# Derivative
tdat = data[1:, :] - data[:-1, :]
# Normalize
tdat = tdat / np.std(tdat, axis=0)
# Coupling
coupling = np.array([tdat[:, i] * tdat[:, j] for i in np.arange(0,
tda... | def _temporal_derivative(data, params, report) | Performs mtd method. See func: teneto.derive.derive. | 3.043904 | 3.043396 | 1.000167 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.