Search is not available for this dataset
text stringlengths 75 104k |
|---|
def write_bel_namespace(self, file: TextIO, use_names: bool = False) -> None:
"""Write as a BEL namespace file."""
if not self.is_populated():
self.populate()
if use_names and not self.has_names:
raise ValueError
values = (
self._get_namespace_name_t... |
def write_bel_annotation(self, file: TextIO) -> None:
"""Write as a BEL annotation file."""
if not self.is_populated():
self.populate()
values = self._get_namespace_name_to_encoding(desc='writing names')
write_annotation(
keyword=self._get_namespace_keyword(),
... |
def write_bel_namespace_mappings(self, file: TextIO, **kwargs) -> None:
"""Write a BEL namespace mapping file."""
json.dump(self._get_namespace_identifier_to_name(**kwargs), file, indent=2, sort_keys=True) |
def write_directory(self, directory: str) -> bool:
"""Write a BEL namespace for identifiers, names, name hash, and mappings to the given directory."""
current_md5_hash = self.get_namespace_hash()
md5_hash_path = os.path.join(directory, f'{self.module_name}.belns.md5')
if not os.path.exi... |
def get_namespace_hash(self, hash_fn=hashlib.md5) -> str:
"""Get the namespace hash.
Defaults to MD5.
"""
m = hash_fn()
if self.has_names:
items = self._get_namespace_name_to_encoding(desc='getting hash').items()
else:
items = self._get_namespace... |
def get_cli(cls) -> click.Group:
"""Get a :mod:`click` main function with added BEL namespace commands."""
main = super().get_cli()
if cls.is_namespace:
@main.group()
def belns():
"""Manage BEL namespace."""
cls._cli_add_to_bel_namespace(beln... |
def get_long_description():
"""Get the long_description from the README.rst file. Assume UTF-8 encoding."""
with codecs.open(os.path.join(HERE, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
return long_description |
def dropbox_post_factory(request):
"""receives a UUID via the request and returns either a fresh or an existing dropbox
for it"""
try:
max_age = int(request.registry.settings.get('post_token_max_age_seconds'))
except Exception:
max_age = 300
try:
drop_id = parse_post_token(
... |
def dropbox_factory(request):
""" expects the id of an existing dropbox and returns its instance"""
try:
return request.registry.settings['dropbox_container'].get_dropbox(request.matchdict['drop_id'])
except KeyError:
raise HTTPNotFound('no such dropbox') |
def is_equal(a, b):
""" a constant time comparison implementation taken from
http://codahale.com/a-lesson-in-timing-attacks/ and
Django's `util` module https://github.com/django/django/blob/master/django/utils/crypto.py#L82
"""
if len(a) != len(b):
return False
result = 0
fo... |
def dropbox_editor_factory(request):
""" this factory also requires the editor token"""
dropbox = dropbox_factory(request)
if is_equal(dropbox.editor_token, request.matchdict['editor_token'].encode('utf-8')):
return dropbox
else:
raise HTTPNotFound('invalid editor token') |
def get_cli(cls) -> click.Group:
"""Build a :mod:`click` CLI main function.
:param Type[AbstractManager] cls: A Manager class
:return: The main function for click
"""
group_help = 'Default connection at {}\n\nusing Bio2BEL v{}'.format(cls._get_connection(), get_version())
... |
def sanitize_filename(filename):
"""preserve the file ending, but replace the name with a random token """
# TODO: fix broken splitext (it reveals everything of the filename after the first `.` - doh!)
token = generate_drop_id()
name, extension = splitext(filename)
if extension:
return '%s%s... |
def process(self):
""" Calls the external cleanser scripts to (optionally) purge the meta data and then
send the contents of the dropbox via email.
"""
if self.num_attachments > 0:
self.status = u'100 processor running'
fs_dirty_archive = self._create_backup(... |
def cleanup(self):
""" ensures that no data leaks from drop after processing by
removing all data except the status file"""
try:
remove(join(self.fs_path, u'message'))
remove(join(self.fs_path, 'dirty.zip.pgp'))
except OSError:
pass
shutil.rmtr... |
def _create_encrypted_zip(self, source='dirty', fs_target_dir=None):
""" creates a zip file from the drop and encrypts it to the editors.
the encrypted archive is created inside fs_target_dir"""
backup_recipients = [r for r in self.editors if checkRecipient(self.gpg_context, r)]
# this ... |
def _create_archive(self):
""" creates an encrypted archive of the dropbox outside of the drop directory.
"""
self.status = u'270 creating final encrypted backup of cleansed attachments'
return self._create_encrypted_zip(source='clean', fs_target_dir=self.container.fs_archive_cleansed) |
def size_attachments(self):
"""returns the number of bytes that the cleansed attachments take up on disk"""
total_size = 0
for attachment in self.fs_cleansed_attachments:
total_size += stat(attachment).st_size
return total_size |
def replies(self):
""" returns a list of strings """
fs_reply_path = join(self.fs_replies_path, 'message_001.txt')
if exists(fs_reply_path):
return [load(open(fs_reply_path, 'r'))]
else:
return [] |
def message(self):
""" returns the user submitted text
"""
try:
with open(join(self.fs_path, u'message')) as message_file:
return u''.join([line.decode('utf-8') for line in message_file.readlines()])
except IOError:
return u'' |
def fs_dirty_attachments(self):
""" returns a list of absolute paths to the attachements"""
if exists(self.fs_attachment_container):
return [join(self.fs_attachment_container, attachment)
for attachment in listdir(self.fs_attachment_container)]
else:
r... |
def fs_cleansed_attachments(self):
""" returns a list of absolute paths to the cleansed attachements"""
if exists(self.fs_cleansed_attachment_container):
return [join(self.fs_cleansed_attachment_container, attachment)
for attachment in listdir(self.fs_cleansed_attachment_... |
def reset_cleansers(confirm=True):
"""destroys all cleanser slaves and their rollback snapshots, as well as the initial master
snapshot - this allows re-running the jailhost deployment to recreate fresh cleansers."""
if value_asbool(confirm) and not yesno("""\nObacht!
This will destroy any exis... |
def reset_jails(confirm=True, keep_cleanser_master=True):
""" stops, deletes and re-creates all jails.
since the cleanser master is rather large, that one is omitted by default.
"""
if value_asbool(confirm) and not yesno("""\nObacht!
This will destroy all existing and or currently running ja... |
def dict_dumper(provider):
'''
Dump a provider to a format that can be passed to a
:class:`skosprovider.providers.DictionaryProvider`.
:param skosprovider.providers.VocabularyProvider provider: The provider
that wil be turned into a `dict`.
:rtype: A list of dicts.
.. versionadded:: 0.... |
def add_cli_flask(main: click.Group) -> click.Group: # noqa: D202
"""Add a ``web`` comand main :mod:`click` function."""
@main.command()
@click.option('-v', '--debug', is_flag=True)
@click.option('-p', '--port')
@click.option('-h', '--host')
@click.option('-k', '--secret-key', default=os.urand... |
def _add_admin(self, app, **kwargs):
"""Add a Flask Admin interface to an application.
:param flask.Flask app: A Flask application
:param kwargs: Keyword arguments are passed through to :class:`flask_admin.Admin`
:rtype: flask_admin.Admin
"""
from flask_admin import Admi... |
def get_flask_admin_app(self, url: Optional[str] = None, secret_key: Optional[str] = None):
"""Create a Flask application.
:param url: Optional mount point of the admin application. Defaults to ``'/'``.
:rtype: flask.Flask
"""
from flask import Flask
app = Flask(__name_... |
def get_cli(cls) -> click.Group:
"""Add a :mod:`click` main function to use as a command line interface."""
main = super().get_cli()
cls._cli_add_flask(main)
return main |
def _handle_system_status_event(self, event: SystemStatusEvent) -> None:
"""
DISARMED -> ARMED_AWAY -> EXIT_DELAY_START -> EXIT_DELAY_END
(trip): -> ALARM -> OUTPUT_ON -> ALARM_RESTORE
(disarm): -> DISARMED -> OUTPUT_OFF
(disarm): -> DISARMED
(disarm before EXIT_DE... |
def dropbox_form(request):
""" generates a dropbox uid and renders the submission form with a signed version of that id"""
from briefkasten import generate_post_token
token = generate_post_token(secret=request.registry.settings['post_secret'])
return dict(
action=request.route_url('dropbox_form_... |
def dropbox_fileupload(dropbox, request):
""" accepts a single file upload and adds it to the dropbox as attachment"""
attachment = request.POST['attachment']
attached = dropbox.add_attachment(attachment)
return dict(
files=[dict(
name=attached,
type=attachment.type,
... |
def dropbox_submission(dropbox, request):
""" handles the form submission, redirects to the dropbox's status page."""
try:
data = dropbox_schema.deserialize(request.POST)
except Exception:
return HTTPFound(location=request.route_url('dropbox_form'))
# set the message
dropbox.message... |
def make_obo_getter(data_url: str,
data_path: str,
*,
preparsed_path: Optional[str] = None,
) -> Callable[[Optional[str], bool, bool], MultiDiGraph]:
"""Build a function that handles downloading OBO data and parsing it into a NetworkX o... |
def belns(keyword: str, file: TextIO, encoding: Optional[str], use_names: bool):
"""Write as a BEL namespace."""
directory = get_data_dir(keyword)
obo_url = f'http://purl.obolibrary.org/obo/{keyword}.obo'
obo_path = os.path.join(directory, f'{keyword}.obo')
obo_cache_path = os.path.join(directory, f... |
def belanno(keyword: str, file: TextIO):
"""Write as a BEL annotation."""
directory = get_data_dir(keyword)
obo_url = f'http://purl.obolibrary.org/obo/{keyword}.obo'
obo_path = os.path.join(directory, f'{keyword}.obo')
obo_cache_path = os.path.join(directory, f'{keyword}.obo.pickle')
obo_getter... |
def _store_helper(model: Action, session: Optional[Session] = None) -> None:
"""Help store an action."""
if session is None:
session = _make_session()
session.add(model)
session.commit()
session.close() |
def _make_session(connection: Optional[str] = None) -> Session:
"""Make a session."""
if connection is None:
connection = get_global_connection()
engine = create_engine(connection)
create_all(engine)
session_cls = sessionmaker(bind=engine)
session = session_cls()
return session |
def create_all(engine, checkfirst=True):
"""Create the tables for Bio2BEL."""
Base.metadata.create_all(bind=engine, checkfirst=checkfirst) |
def store_populate(cls, resource: str, session: Optional[Session] = None) -> 'Action':
"""Store a "populate" event.
:param resource: The normalized name of the resource to store
Example:
>>> from bio2bel.models import Action
>>> Action.store_populate('hgnc')
"""
... |
def store_populate_failed(cls, resource: str, session: Optional[Session] = None) -> 'Action':
"""Store a "populate failed" event.
:param resource: The normalized name of the resource to store
Example:
>>> from bio2bel.models import Action
>>> Action.store_populate_failed('hgnc... |
def store_drop(cls, resource: str, session: Optional[Session] = None) -> 'Action':
"""Store a "drop" event.
:param resource: The normalized name of the resource to store
Example:
>>> from bio2bel.models import Action
>>> Action.store_drop('hgnc')
"""
action = c... |
def ls(cls, session: Optional[Session] = None) -> List['Action']:
"""Get all actions."""
if session is None:
session = _make_session()
actions = session.query(cls).order_by(cls.created.desc()).all()
session.close()
return actions |
def count(cls, session: Optional[Session] = None) -> int:
"""Count all actions."""
if session is None:
session = _make_session()
count = session.query(cls).count()
session.close()
return count |
def get_data_dir(module_name: str) -> str:
"""Ensure the appropriate Bio2BEL data directory exists for the given module, then returns the file path.
:param module_name: The name of the module. Ex: 'chembl'
:return: The module's data directory
"""
module_name = module_name.lower()
data_dir = os.... |
def get_module_config_cls(module_name: str) -> Type[_AbstractModuleConfig]: # noqa: D202
"""Build a module configuration class."""
class ModuleConfig(_AbstractModuleConfig):
NAME = f'bio2bel:{module_name}'
FILES = DEFAULT_CONFIG_PATHS + [
os.path.join(DEFAULT_CONFIG_DIRECTORY, modu... |
def get_connection(module_name: str, connection: Optional[str] = None) -> str:
"""Return the SQLAlchemy connection string if it is set.
Order of operations:
1. Return the connection if given as a parameter
2. Check the environment for BIO2BEL_{module_name}_CONNECTION
3. Look in the bio2bel config ... |
def get_modules() -> Mapping:
"""Get all Bio2BEL modules."""
modules = {}
for entry_point in iter_entry_points(group='bio2bel', name=None):
entry = entry_point.name
try:
modules[entry] = entry_point.load()
except VersionConflict as exc:
log.warning('Version ... |
def clear_cache(module_name: str, keep_database: bool = True) -> None:
"""Clear all downloaded files."""
data_dir = get_data_dir(module_name)
if not os.path.exists(data_dir):
return
for name in os.listdir(data_dir):
if name in {'config.ini', 'cfg.ini'}:
continue
if na... |
def add_cli_populate(main: click.Group) -> click.Group: # noqa: D202
"""Add a ``populate`` command to main :mod:`click` function."""
@main.command()
@click.option('--reset', is_flag=True, help='Nuke database first')
@click.option('--force', is_flag=True, help='Force overwrite if already populated')
... |
def add_cli_drop(main: click.Group) -> click.Group: # noqa: D202
"""Add a ``drop`` command to main :mod:`click` function."""
@main.command()
@click.confirmation_option(prompt='Are you sure you want to drop the db?')
@click.pass_obj
def drop(manager):
"""Drop the database."""
manage... |
def add_cli_cache(main: click.Group) -> click.Group: # noqa: D202
"""Add several commands to main :mod:`click` function for handling the cache."""
@main.group()
def cache():
"""Manage cached data."""
@cache.command()
@click.pass_obj
def locate(manager):
"""Print the location o... |
def add_cli_summarize(main: click.Group) -> click.Group: # noqa: D202
"""Add a ``summarize`` command to main :mod:`click` function."""
@main.command()
@click.pass_obj
def summarize(manager: AbstractManager):
"""Summarize the contents of the database."""
if not manager.is_populated():
... |
def create_all(self, check_first: bool = True):
"""Create the empty database (tables).
:param bool check_first: Defaults to True, don't issue CREATEs for tables already present
in the target database. Defers to :meth:`sqlalchemy.sql.schema.MetaData.create_all`
"""
self._metadat... |
def drop_all(self, check_first: bool = True):
"""Drop all tables from the database.
:param bool check_first: Defaults to True, only issue DROPs for tables confirmed to be
present in the target database. Defers to :meth:`sqlalchemy.sql.schema.MetaData.drop_all`
"""
self._metada... |
def get_cli(cls) -> click.Group:
"""Get the :mod:`click` main function to use as a command line interface."""
main = super().get_cli()
cls._cli_add_populate(main)
cls._cli_add_drop(main)
cls._cli_add_cache(main)
cls._cli_add_summarize(main)
return main |
def label(labels=[], language='any', sortLabel=False):
'''
Provide a label for a list of labels.
The items in the list of labels are assumed to be either instances of
:class:`Label`, or dicts with at least the key `label` in them. These will
be passed to the :func:`dict_to_label` function.
Thi... |
def find_best_label_for_type(labels, language, labeltype):
'''
Find the best label for a certain labeltype.
:param list labels: A list of :class:`Label`.
:param str language: An IANA language string, eg. `nl` or `nl-BE`.
:param str labeltype: Type of label to look for, eg. `prefLabel`.
'''
... |
def filter_labels_by_language(labels, language, broader=False):
'''
Filter a list of labels, leaving only labels of a certain language.
:param list labels: A list of :class:`Label`.
:param str language: An IANA language string, eg. `nl` or `nl-BE`.
:param boolean broader: When true, will also match... |
def dict_to_label(dict):
'''
Transform a dict with keys `label`, `type` and `language` into a
:class:`Label`.
Only the `label` key is mandatory. If `type` is not present, it will
default to `prefLabel`. If `language` is not present, it will default
to `und`.
If the argument passed is not a... |
def dict_to_note(dict):
'''
Transform a dict with keys `note`, `type` and `language` into a
:class:`Note`.
Only the `note` key is mandatory. If `type` is not present, it will
default to `note`. If `language` is not present, it will default to `und`.
If `markup` is not present it will default to... |
def dict_to_source(dict):
'''
Transform a dict with key 'citation' into a :class:`Source`.
If the argument passed is already a :class:`Source`, this method just
returns the argument.
'''
if isinstance(dict, Source):
return dict
return Source(
dict['citation'],
dict.... |
def _sortkey(self, key='uri', language='any'):
'''
Provide a single sortkey for this conceptscheme.
:param string key: Either `uri`, `label` or `sortlabel`.
:param string language: The preferred language to receive the label in
if key is `label` or `sortlabel`. This should b... |
def _iterate_managers(connection, skip):
"""Iterate over instantiated managers."""
for idx, name, manager_cls in _iterate_manage_classes(skip):
if name in skip:
continue
try:
manager = manager_cls(connection=connection)
except TypeError as e:
click.se... |
def populate(connection, reset, force, skip):
"""Populate all."""
for idx, name, manager in _iterate_managers(connection, skip):
click.echo(
click.style(f'[{idx}/{len(MANAGERS)}] ', fg='blue', bold=True) +
click.style(f'populating {name}', fg='cyan', bold=True)
)
... |
def drop(connection, skip):
"""Drop all."""
for idx, name, manager in _iterate_managers(connection, skip):
click.secho(f'dropping {name}', fg='cyan', bold=True)
manager.drop_all() |
def clear(skip):
"""Clear all caches."""
for name in sorted(MODULES):
if name in skip:
continue
click.secho(f'clearing cache for {name}', fg='cyan', bold=True)
clear_cache(name) |
def summarize(connection, skip):
"""Summarize all."""
for idx, name, manager in _iterate_managers(connection, skip):
click.secho(name, fg='cyan', bold=True)
if not manager.is_populated():
click.echo('👎 unpopulated')
continue
if isinstance(manager, BELNamespaceMa... |
def sheet(connection, skip, file: TextIO):
"""Generate a summary sheet."""
from tabulate import tabulate
header = ['', 'Name', 'Description', 'Terms', 'Relations']
rows = []
for i, (idx, name, manager) in enumerate(_iterate_managers(connection, skip), start=1):
try:
if not manag... |
def write(connection, skip, directory, force):
"""Write a BEL namespace names/identifiers to terminology store."""
os.makedirs(directory, exist_ok=True)
from .manager.namespace_manager import BELNamespaceManagerMixin
for idx, name, manager in _iterate_managers(connection, skip):
if not (isinstan... |
def write(connection, skip, directory, force):
"""Write all as BEL."""
os.makedirs(directory, exist_ok=True)
from .manager.bel_manager import BELManagerMixin
import pybel
for idx, name, manager in _iterate_managers(connection, skip):
if not isinstance(manager, BELManagerMixin):
c... |
def web(connection, host, port):
"""Run a combine web interface."""
from bio2bel.web.application import create_application
app = create_application(connection=connection)
app.run(host=host, port=port) |
def actions(connection):
"""List all actions."""
session = _make_session(connection=connection)
for action in Action.ls(session=session):
click.echo(f'{action.created} {action.action} {action.resource}') |
def add_cli_to_bel(main: click.Group) -> click.Group: # noqa: D202
"""Add several command to main :mod:`click` function related to export to BEL."""
@main.command()
@click.option('-o', '--output', type=click.File('w'), default=sys.stdout)
@click.option('-f', '--fmt', default='bel', show_default=True, ... |
def add_cli_upload_bel(main: click.Group) -> click.Group: # noqa: D202
"""Add several command to main :mod:`click` function related to export to BEL."""
@main.command()
@host_option
@click.pass_obj
def upload(manager: BELManagerMixin, host: str):
"""Upload BEL to BEL Commons."""
gr... |
def count_relations(self) -> int:
"""Count the number of BEL relations generated."""
if self.edge_model is ...:
raise Bio2BELMissingEdgeModelError('edge_edge model is undefined/count_bel_relations is not overridden')
elif isinstance(self.edge_model, list):
return sum(self... |
def to_indra_statements(self, *args, **kwargs):
"""Dump as a list of INDRA statements.
:rtype: List[indra.Statement]
"""
graph = self.to_bel(*args, **kwargs)
return to_indra_statements(graph) |
def get_cli(cls) -> click.Group:
"""Get a :mod:`click` main function with added BEL commands."""
main = super().get_cli()
@main.group()
def bel():
"""Manage BEL."""
cls._cli_add_to_bel(bel)
cls._cli_add_upload_bel(bel)
return main |
def exebench(width):
"""
benchorg.jpg is
'http://upload.wikimedia.org/wikipedia/commons/d/df/SAND_LUE.jpg'
"""
height = width * 2 / 3
with Benchmarker(width=30, loop=N) as bm:
for i in bm('kaa.imlib2'):
imlib2_scale('benchorg.jpg', width, height)
for i in bm("PIL"):
... |
def _convert_coordinatelist(input_obj):
"""convert from 'list' or 'tuple' object to pgmagick.CoordinateList.
:type input_obj: list or tuple
"""
cdl = pgmagick.CoordinateList()
for obj in input_obj:
cdl.append(pgmagick.Coordinate(obj[0], obj[1]))
return cdl |
def _convert_vpathlist(input_obj):
"""convert from 'list' or 'tuple' object to pgmagick.VPathList.
:type input_obj: list or tuple
"""
vpl = pgmagick.VPathList()
for obj in input_obj:
# FIXME
obj = pgmagick.PathMovetoAbs(pgmagick.Coordinate(obj[0], obj[1]))
vpl.append(obj)
... |
def get_exif_info(self):
"""return exif-tag dict
"""
_dict = {}
for tag in _EXIF_TAGS:
ret = self.img.attribute("EXIF:%s" % tag)
if ret and ret != 'unknown':
_dict[tag] = ret
return _dict |
def bezier(self, points):
"""Draw a Bezier-curve.
:param points: ex.) ((5, 5), (6, 6), (7, 7))
:type points: list
"""
coordinates = pgmagick.CoordinateList()
for point in points:
x, y = float(point[0]), float(point[1])
coordinates.append(pgmagick.... |
def color(self, x, y, paint_method):
"""
:param paint_method: 'point' or 'replace' or 'floodfill' or
'filltoborder' or 'reset'
:type paint_method: str or pgmagick.PaintMethod
"""
paint_method = _convert_paintmethod(paint_method)
color = pgmagi... |
def ellipse(self, org_x, org_y, radius_x, radius_y, arc_start, arc_end):
"""
:param org_x: origination x axis
:param org_y: origination y axis
:param radius_x: radius x axis
:param radius_y: radius y axis
:param arc_start: arc start angle
:param arc_end: arc end a... |
def fill_opacity(self, opacity):
"""
:param opacity: 0.0 ~ 1.0
"""
opacity = pgmagick.DrawableFillOpacity(float(opacity))
self.drawer.append(opacity) |
def matte(self, x, y, paint_method):
"""
:param paint_method: 'point' or 'replace' or 'floodfill' or
'filltoborder' or 'reset'
:type paint_method: str or pgmagick.PaintMethod
"""
paint_method = _convert_paintmethod(paint_method)
self.drawer.ap... |
def scaling(self, x, y):
"""Scaling Draw Object
:param x: 0.0 ~ 1.0
:param y: 0.0 ~ 1.0
"""
self.drawer.append(pgmagick.DrawableScaling(float(x), float(y))) |
def stroke_antialias(self, flag=True):
"""stroke antialias
:param flag: True or False. (default is True)
:type flag: bool
"""
antialias = pgmagick.DrawableStrokeAntialias(flag)
self.drawer.append(antialias) |
def stroke_linecap(self, linecap):
"""set to stroke linecap.
:param linecap: 'undefined', 'butt', 'round', 'square'
:type linecap: str
"""
linecap = getattr(pgmagick.LineCap, "%sCap" % linecap.title())
linecap = pgmagick.DrawableStrokeLineCap(linecap)
self.drawer... |
def stroke_linejoin(self, linejoin):
"""set to stroke linejoin.
:param linejoin: 'undefined', 'miter', 'round', 'bevel'
:type linejoin: str
"""
linejoin = getattr(pgmagick.LineJoin, "%sJoin" % linejoin.title())
linejoin = pgmagick.DrawableStrokeLineJoin(linejoin)
... |
def text_antialias(self, flag=True):
"""text antialias
:param flag: True or False. (default is True)
:type flag: bool
"""
antialias = pgmagick.DrawableTextAntialias(flag)
self.drawer.append(antialias) |
def text_decoration(self, decoration):
"""text decoration
:param decoration: 'no', 'underline', 'overline', 'linethrough'
:type decoration: str
"""
if decoration.lower() == 'linethrough':
d = pgmagick.DecorationType.LineThroughDecoration
else:
dec... |
def get_version_from_pc(search_dirs, target):
"""similar to 'pkg-config --modversion GraphicsMagick++'"""
for dirname in search_dirs:
for root, dirs, files in os.walk(dirname):
for f in files:
if f == target:
file_path = os.path.join(root, target)
... |
def library_supports_api(library_version, api_version, different_major_breaks_support=True):
"""
Returns whether api_version is supported by given library version.
E. g. library_version (1,3,21) returns True for api_version (1,3,21), (1,3,19), (1,3,'x'), (1,2,'x'), (1, 'x')
False for (1,3,24), (... |
def version():
"""Return version string."""
with io.open('pgmagick/_version.py') as input_file:
for line in input_file:
if line.startswith('__version__'):
return ast.parse(line).body[0].value.s |
def post_license_request(request):
"""Submission to create a license acceptance request."""
uuid_ = request.matchdict['uuid']
posted_data = request.json
license_url = posted_data.get('license_url')
licensors = posted_data.get('licensors', [])
with db_connect() as db_conn:
with db_conn.c... |
def delete_license_request(request):
"""Submission to remove a license acceptance request."""
uuid_ = request.matchdict['uuid']
posted_uids = [x['uid'] for x in request.json.get('licensors', [])]
with db_connect() as db_conn:
with db_conn.cursor() as cursor:
remove_license_requests(... |
def get_roles_request(request):
"""Returns a list of accepting roles."""
uuid_ = request.matchdict['uuid']
user_id = request.matchdict.get('uid')
args = [uuid_]
if user_id is not None:
fmt_conditional = "AND user_id = %s"
args.append(user_id)
else:
fmt_conditional = ""
... |
def post_roles_request(request):
"""Submission to create a role acceptance request."""
uuid_ = request.matchdict['uuid']
posted_roles = request.json
with db_connect() as db_conn:
with db_conn.cursor() as cursor:
cursor.execute("""\
SELECT TRUE FROM document_controls WHERE uuid = %s:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.