sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def index_from_id(self,Id):
"""Return the row of given Id if it'exists, otherwise None. Only works with pseudo-acces"""
try:
return [a.Id for a in self].index(Id)
except IndexError:
return | Return the row of given Id if it'exists, otherwise None. Only works with pseudo-acces | entailment |
def append(self, acces, **kwargs):
"""Append acces to list. Quite slow since it checks uniqueness.
kwargs may set `info` for this acces.
"""
if acces.Id in set(ac.Id for ac in self):
raise ValueError("Acces id already in list !")
list.append(self, acces)
if kw... | Append acces to list. Quite slow since it checks uniqueness.
kwargs may set `info` for this acces. | entailment |
def remove_id(self,key):
"""Suppress acces with id = key"""
self.infos.pop(key, "")
new_l = [a for a in self if not (a.Id == key)]
list.__init__(self, new_l) | Suppress acces with id = key | entailment |
def get_info(self, key=None, Id=None) -> dict:
"""Returns information associated with Id or list index"""
if key is not None:
Id = self[key].Id
return self.infos.get(Id,{}) | Returns information associated with Id or list index | entailment |
def recherche(self, pattern, entete):
"""Performs a search field by field, using functions defined in formats.
Matchs are marked with info[`font`]
:param pattern: String to look for
:param entete: Fields to look into
:return: Nothing. The collection is changed in place
"... | Performs a search field by field, using functions defined in formats.
Matchs are marked with info[`font`]
:param pattern: String to look for
:param entete: Fields to look into
:return: Nothing. The collection is changed in place | entailment |
def extend(self, collection):
"""Merges collections. Ensure uniqueness of ids"""
l_ids = set([a.Id for a in self])
for acces in collection:
if not acces.Id in l_ids:
list.append(self,acces)
info = collection.get_info(Id=acces.Id)
if inf... | Merges collections. Ensure uniqueness of ids | entailment |
def isotime(at=None, subsecond=False):
"""Stringify time in ISO 8601 format."""
if not at:
at = utcnow()
st = at.strftime(_ISO8601_TIME_FORMAT
if not subsecond
else _ISO8601_TIME_FORMAT_SUBSECOND)
tz = at.tzinfo.tzname(None) if at.tzinfo else 'UTC'
s... | Stringify time in ISO 8601 format. | entailment |
def parse_isotime(timestr):
"""Parse time from ISO 8601 format."""
try:
return iso8601.parse_date(timestr)
except iso8601.ParseError as e:
raise ValueError(six.text_type(e))
except TypeError as e:
raise ValueError(six.text_type(e)) | Parse time from ISO 8601 format. | entailment |
def strtime(at=None, fmt=PERFECT_TIME_FORMAT):
"""Returns formatted utcnow."""
if not at:
at = utcnow()
return at.strftime(fmt) | Returns formatted utcnow. | entailment |
def normalize_time(timestamp):
"""Normalize time in arbitrary timezone to UTC naive object."""
offset = timestamp.utcoffset()
if offset is None:
return timestamp
return timestamp.replace(tzinfo=None) - offset | Normalize time in arbitrary timezone to UTC naive object. | entailment |
def is_older_than(before, seconds):
"""Return True if before is older than seconds."""
if isinstance(before, six.string_types):
before = parse_strtime(before).replace(tzinfo=None)
else:
before = before.replace(tzinfo=None)
return utcnow() - before > datetime.timedelta(seconds=seconds) | Return True if before is older than seconds. | entailment |
def is_newer_than(after, seconds):
"""Return True if after is newer than seconds."""
if isinstance(after, six.string_types):
after = parse_strtime(after).replace(tzinfo=None)
else:
after = after.replace(tzinfo=None)
return after - utcnow() > datetime.timedelta(seconds=seconds) | Return True if after is newer than seconds. | entailment |
def utcnow_ts():
"""Timestamp version of our utcnow function."""
if utcnow.override_time is None:
# NOTE(kgriffs): This is several times faster
# than going through calendar.timegm(...)
return int(time.time())
return calendar.timegm(utcnow().timetuple()) | Timestamp version of our utcnow function. | entailment |
def utcnow():
"""Overridable version of utils.utcnow."""
if utcnow.override_time:
try:
return utcnow.override_time.pop(0)
except AttributeError:
return utcnow.override_time
return datetime.datetime.utcnow() | Overridable version of utils.utcnow. | entailment |
def advance_time_delta(timedelta):
"""Advance overridden time using a datetime.timedelta."""
assert(utcnow.override_time is not None)
try:
for dt in utcnow.override_time:
dt += timedelta
except TypeError:
utcnow.override_time += timedelta | Advance overridden time using a datetime.timedelta. | entailment |
def marshall_now(now=None):
"""Make an rpc-safe datetime with microseconds.
Note: tzinfo is stripped, but not required for relative times.
"""
if not now:
now = utcnow()
return dict(day=now.day, month=now.month, year=now.year, hour=now.hour,
minute=now.minute, second=now.sec... | Make an rpc-safe datetime with microseconds.
Note: tzinfo is stripped, but not required for relative times. | entailment |
def unmarshall_time(tyme):
"""Unmarshall a datetime dict."""
return datetime.datetime(day=tyme['day'],
month=tyme['month'],
year=tyme['year'],
hour=tyme['hour'],
minute=tyme['minute'],
... | Unmarshall a datetime dict. | entailment |
def total_seconds(delta):
"""Return the total seconds of datetime.timedelta object.
Compute total seconds of datetime.timedelta, datetime.timedelta
doesn't have method total_seconds in Python2.6, calculate it manually.
"""
try:
return delta.total_seconds()
except AttributeError:
... | Return the total seconds of datetime.timedelta object.
Compute total seconds of datetime.timedelta, datetime.timedelta
doesn't have method total_seconds in Python2.6, calculate it manually. | entailment |
def is_soon(dt, window):
"""Determines if time is going to happen in the next window seconds.
:params dt: the time
:params window: minimum seconds to remain to consider the time not soon
:return: True if expiration is within the given duration
"""
soon = (utcnow() + datetime.timedelta(seconds=... | Determines if time is going to happen in the next window seconds.
:params dt: the time
:params window: minimum seconds to remain to consider the time not soon
:return: True if expiration is within the given duration | entailment |
def download_file_powershell(url, target):
'''
Download the file at url to target using Powershell (which will validate
trust). Raise an exception if the command cannot complete.
'''
target = os.path.abspath(target)
cmd = [
'powershell',
'-Command',
'(new-object System.Ne... | Download the file at url to target using Powershell (which will validate
trust). Raise an exception if the command cannot complete. | entailment |
def download_file_insecure(url, target):
'''
Use Python to download the file, even though it cannot authenticate the
connection.
'''
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
src = dst = None
try:
src = urlopen(url)
... | Use Python to download the file, even though it cannot authenticate the
connection. | entailment |
def _build_install_args(options):
'''
Build the arguments to 'python setup.py install' on the setuptools package
'''
install_args = []
if options.user_install:
if sys.version_info < (2, 6):
log.warn('--user requires Python 2.6 or later')
raise SystemExit(1)
in... | Build the arguments to 'python setup.py install' on the setuptools package | entailment |
def write(name, value):
"""Temporarily change or set the environment variable during the execution of a function.
Args:
name: The name of the environment variable
value: A value to set for the environment variable
Returns:
The function return value.
"""
def wrapped(func):
... | Temporarily change or set the environment variable during the execution of a function.
Args:
name: The name of the environment variable
value: A value to set for the environment variable
Returns:
The function return value. | entailment |
def isset(name):
"""Only execute the function if the variable is set.
Args:
name: The name of the environment variable
Returns:
The function return value or `None` if the function was skipped.
"""
def wrapped(func):
@functools.wraps(func)
def _decorator(*args, **kwa... | Only execute the function if the variable is set.
Args:
name: The name of the environment variable
Returns:
The function return value or `None` if the function was skipped. | entailment |
def bool(name, execute_bool=True, default=None):
"""Only execute the function if the boolean variable is set.
Args:
name: The name of the environment variable
execute_bool: The boolean value to execute the function on
default: The default value if the environment variable is not set (re... | Only execute the function if the boolean variable is set.
Args:
name: The name of the environment variable
execute_bool: The boolean value to execute the function on
default: The default value if the environment variable is not set (respects `execute_bool`)
Returns:
The functio... | entailment |
def read_cell(self, x, y):
"""
Reads the cell at position x+1 and y+1; return value
:param x: line index
:param y: coll index
:return: {header: value}
"""
if isinstance(self.header[y], tuple):
header = self.header[y][0]
else:
header... | Reads the cell at position x+1 and y+1; return value
:param x: line index
:param y: coll index
:return: {header: value} | entailment |
def write_cell(self, x, y, value):
"""
Writing value in the cell of x+1 and y+1 position
:param x: line index
:param y: coll index
:param value: value to be written
:return:
"""
x += 1
y += 1
self._sheet.update_cell(x, y, value) | Writing value in the cell of x+1 and y+1 position
:param x: line index
:param y: coll index
:param value: value to be written
:return: | entailment |
def _open(self):
"""
Open the file; get sheets
:return:
"""
if not hasattr(self, '_file'):
self._file = self.gc.open(self.name)
self.sheet_names = self._file.worksheets() | Open the file; get sheets
:return: | entailment |
def _open_sheet(self):
"""
Read the sheet, get value the header, get number columns and rows
:return:
"""
if self.sheet_name and not self.header:
self._sheet = self._file.worksheet(self.sheet_name.title)
self.ncols = self._sheet.col_count
self.... | Read the sheet, get value the header, get number columns and rows
:return: | entailment |
def _import(self):
"""
Makes imports
:return:
"""
import os.path
import gspread
self.path = os.path
self.gspread = gspread
self._login() | Makes imports
:return: | entailment |
def _login(self):
"""
Login with your Google account
:return:
"""
# TODO(dmvieira) login changed to oauth2
self.gc = self.gspread.login(self.email, self.password) | Login with your Google account
:return: | entailment |
def flags(self, index: QModelIndex):
"""All fields are selectable"""
if self.IS_EDITABLE and self.header[index.column()] in self.EDITABLE_FIELDS:
return Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsEditable
else:
return super().flags(index) | Qt.ItemIsSelectable | All fields are selectable | entailment |
def sort(self, section: int, order=None):
"""Order is defined by the current state of sorting"""
attr = self.header[section]
old_i, old_sort = self.sort_state
self.beginResetModel()
if section == old_i:
self.collection.sort(attr, not old_sort)
self.sort_st... | Order is defined by the current state of sorting | entailment |
def remove_line(self, section):
"""Base implementation just pops the item from collection.
Re-implements to add global behaviour
"""
self.beginResetModel()
self.collection.pop(section)
self.endResetModel() | Base implementation just pops the item from collection.
Re-implements to add global behaviour | entailment |
def _update(self):
"""Emit dataChanged signal on all cells"""
self.dataChanged.emit(self.createIndex(0, 0), self.createIndex(
len(self.collection), len(self.header))) | Emit dataChanged signal on all cells | entailment |
def get_item(self, index):
""" Acces shortcut
:param index: Number of row or index of cell
:return: Dict-like item
"""
row = index.row() if hasattr(index, "row") else index
try:
return self.collection[row]
except IndexError: # invalid index for exemp... | Acces shortcut
:param index: Number of row or index of cell
:return: Dict-like item | entailment |
def set_collection(self, collection):
"""Reset sort state, set collection and emit resetModel signal"""
self.beginResetModel()
self.collection = collection
self.sort_state = (-1, False)
self.endResetModel() | Reset sort state, set collection and emit resetModel signal | entailment |
def set_item(self, index, new_item):
""" Changes item at index in collection. Emit dataChanged signal.
:param index: Number of row or index of cell
:param new_item: Dict-like object
"""
row = index.row() if hasattr(index, "row") else index
self.collection[row] = new_item... | Changes item at index in collection. Emit dataChanged signal.
:param index: Number of row or index of cell
:param new_item: Dict-like object | entailment |
def set_data(self, index, value):
"""Uses given data setter, and emit modelReset signal"""
acces, field = self.get_item(index), self.header[index.column()]
self.beginResetModel()
self.set_data_hook(acces, field, value)
self.endResetModel() | Uses given data setter, and emit modelReset signal | entailment |
def _set_id(self, Id, is_added, index):
"""Update selected_ids and emit dataChanged"""
if is_added:
self.selected_ids.add(Id)
else:
self.selected_ids.remove(Id)
self.dataChanged.emit(index, index) | Update selected_ids and emit dataChanged | entailment |
def setData(self, index: QModelIndex, value, role=None):
"""Update selected_ids on click on index cell."""
if not (index.isValid() and role == Qt.CheckStateRole):
return False
c_id = self.get_item(index).Id
self._set_id(c_id, value == Qt.Checked, index)
return True | Update selected_ids on click on index cell. | entailment |
def set_by_Id(self, Id, is_added):
"""Update selected_ids with given Id"""
row = self.collection.index_from_id(Id)
if row is None:
return
self._set_id(Id, is_added, self.index(row, 0)) | Update selected_ids with given Id | entailment |
def _setup_delegate(self):
"""Add resize behavior on edit"""
delegate = self.DELEGATE_CLASS(self)
self.setItemDelegate(delegate)
delegate.sizeHintChanged.connect(
lambda index: self.resizeRowToContents(index.row()))
if self.RESIZE_COLUMN:
delegate.sizeHint... | Add resize behavior on edit | entailment |
def _draw_placeholder(self):
"""To be used in QTreeView"""
if self.model().rowCount() == 0:
painter = QPainter(self.viewport())
painter.setFont(_custom_font(is_italic=True))
painter.drawText(self.rect().adjusted(0, 0, -5, -5), Qt.AlignCenter | Qt.TextWordWrap,
... | To be used in QTreeView | entailment |
def get_current_item(self):
"""Returns (first) selected item or None"""
l = self.selectedIndexes()
if len(l) > 0:
return self.model().get_item(l[0]) | Returns (first) selected item or None | entailment |
def model_from_list(l, header):
"""Return a model with a collection from a list of entry"""
col = groups.sortableListe(PseudoAccesCategorie(n) for n in l)
return MultiSelectModel(col, header) | Return a model with a collection from a list of entry | entailment |
def _parse_status_code(response):
"""
Return error string code if the response is an error, otherwise ``"OK"``
"""
# This happens when a status response is expected
if isinstance(response, string_types):
return response
# This happens when a list of structs are expected
is_single_l... | Return error string code if the response is an error, otherwise ``"OK"`` | entailment |
def remove_zone_record(self, id, domain, subdomain=None):
"""
Remove the zone record with the given ID that belongs to the given
domain and sub domain. If no sub domain is given the wildcard sub-domain
is assumed.
"""
if subdomain is None:
subdomain = "@"
... | Remove the zone record with the given ID that belongs to the given
domain and sub domain. If no sub domain is given the wildcard sub-domain
is assumed. | entailment |
def parse_module_class(self):
"""Parse the module and class name part of the fully qualifed class name.
"""
cname = self.class_name
match = re.match(self.CLASS_REGEX, cname)
if not match:
raise ValueError(f'not a fully qualified class name: {cname}')
return m... | Parse the module and class name part of the fully qualifed class name. | entailment |
def get_module_class(self):
"""Return the module and class as a tuple of the given class in the
initializer.
:param reload: if ``True`` then reload the module before returning the
class
"""
pkg, cname = self.parse_module_class()
logger.debug(f'pkg: {pkg}, class:... | Return the module and class as a tuple of the given class in the
initializer.
:param reload: if ``True`` then reload the module before returning the
class | entailment |
def instance(self, *args, **kwargs):
"""Create an instance of the specified class in the initializer.
:param args: the arguments given to the initializer of the new class
:param kwargs: the keyword arguments given to the initializer of the
new class
"""
mod... | Create an instance of the specified class in the initializer.
:param args: the arguments given to the initializer of the new class
:param kwargs: the keyword arguments given to the initializer of the
new class | entailment |
def set_log_level(self, level=logging.INFO):
"""Convenciene method to set the log level of the module given in the
initializer of this class.
:param level: and instance of ``logging.<level>``
"""
mod, cls = self.parse_module_class()
logging.getLogger(mod).setLevel(level) | Convenciene method to set the log level of the module given in the
initializer of this class.
:param level: and instance of ``logging.<level>`` | entailment |
def register(cls, instance_class, name=None):
"""Register a class with the factory.
:param instance_class: the class to register with the factory (not a
string)
:param name: the name to use as the key for instance class lookups;
defaults to the name of the class
... | Register a class with the factory.
:param instance_class: the class to register with the factory (not a
string)
:param name: the name to use as the key for instance class lookups;
defaults to the name of the class | entailment |
def _find_class(self, class_name):
"Resolve the class from the name."
classes = {}
classes.update(globals())
classes.update(self.INSTANCE_CLASSES)
logger.debug(f'looking up class: {class_name}')
cls = classes[class_name]
logger.debug(f'found class: {cls}')
... | Resolve the class from the name. | entailment |
def _class_name_params(self, name):
"Get the class name and parameters to use for ``__init__``."
sec = self.pattern.format(**{'name': name})
logger.debug(f'section: {sec}')
params = {}
params.update(self.config.populate({}, section=sec))
class_name = params['class_name']
... | Get the class name and parameters to use for ``__init__``. | entailment |
def _has_init_config(self, cls):
"""Return whether the class has a ``config`` parameter in the ``__init__``
method.
"""
args = inspect.signature(cls.__init__)
return self.config_param_name in args.parameters | Return whether the class has a ``config`` parameter in the ``__init__``
method. | entailment |
def _has_init_name(self, cls):
"""Return whether the class has a ``name`` parameter in the ``__init__``
method.
"""
args = inspect.signature(cls.__init__)
return self.name_param_name in args.parameters | Return whether the class has a ``name`` parameter in the ``__init__``
method. | entailment |
def _instance(self, cls, *args, **kwargs):
"""Return the instance.
:param cls: the class to create the instance from
:param args: given to the ``__init__`` method
:param kwargs: given to the ``__init__`` method
"""
logger.debug(f'args: {args}, kwargs: {kwargs}')
... | Return the instance.
:param cls: the class to create the instance from
:param args: given to the ``__init__`` method
:param kwargs: given to the ``__init__`` method | entailment |
def instance(self, name=None, *args, **kwargs):
"""Create a new instance using key ``name``.
:param name: the name of the class (by default) or the key name of the
class used to find the class
:param args: given to the ``__init__`` method
:param kwargs: given to the ``__init... | Create a new instance using key ``name``.
:param name: the name of the class (by default) or the key name of the
class used to find the class
:param args: given to the ``__init__`` method
:param kwargs: given to the ``__init__`` method | entailment |
def load(self, name=None, *args, **kwargs):
"Load the instance of the object from the stash."
inst = self.stash.load(name)
if inst is None:
inst = self.instance(name, *args, **kwargs)
logger.debug(f'loaded (conf mng) instance: {inst}')
return inst | Load the instance of the object from the stash. | entailment |
def dump(self, name: str, inst):
"Save the object instance to the stash."
self.stash.dump(name, inst) | Save the object instance to the stash. | entailment |
def from_env(cls, default_timeout=DEFAULT_TIMEOUT_SECONDS):
"""Return a client configured from environment variables.
Essentially copying this:
https://github.com/docker/docker-py/blob/master/docker/client.py#L43.
The environment variables looked for are the following:
.. envv... | Return a client configured from environment variables.
Essentially copying this:
https://github.com/docker/docker-py/blob/master/docker/client.py#L43.
The environment variables looked for are the following:
.. envvar:: SALTANT_API_URL
The URL of the saltant API. For examp... | entailment |
def clear_global(self):
"""Clear only any cached global data.
"""
vname = self.varname
logger.debug(f'global clearning {vname}')
if vname in globals():
logger.debug('removing global instance var: {}'.format(vname))
del globals()[vname] | Clear only any cached global data. | entailment |
def clear(self):
"""Clear the data, and thus, force it to be created on the next fetch. This is
done by removing the attribute from ``owner``, deleting it from globals
and removing the file from the disk.
"""
vname = self.varname
if self.path.exists():
logge... | Clear the data, and thus, force it to be created on the next fetch. This is
done by removing the attribute from ``owner``, deleting it from globals
and removing the file from the disk. | entailment |
def _load_or_create(self, *argv, **kwargs):
"""Invoke the file system operations to get the data, or create work.
If the file does not exist, calling ``__do_work__`` and save it.
"""
if self.path.exists():
self._info('loading work from {}'.format(self.path))
with... | Invoke the file system operations to get the data, or create work.
If the file does not exist, calling ``__do_work__`` and save it. | entailment |
def has_data(self):
"""Return whether or not the stash has any data available or not."""
if not hasattr(self, '_has_data'):
try:
next(iter(self.delegate.keys()))
self._has_data = True
except StopIteration:
self._has_data = False
... | Return whether or not the stash has any data available or not. | entailment |
def _get_instance_path(self, name):
"Return a path to the pickled data with key ``name``."
fname = self.pattern.format(**{'name': name})
logger.debug(f'path {self.create_path}: {self.create_path.exists()}')
self._create_path_dir()
return Path(self.create_path, fname) | Return a path to the pickled data with key ``name``. | entailment |
def shelve(self):
"""Return an opened shelve object.
"""
logger.info('creating shelve data')
fname = str(self.create_path.absolute())
inst = sh.open(fname, writeback=self.writeback)
self.is_open = True
return inst | Return an opened shelve object. | entailment |
def delete(self, name=None):
"Delete the shelve data file."
logger.info('clearing shelve data')
self.close()
for path in Path(self.create_path.parent, self.create_path.name), \
Path(self.create_path.parent, self.create_path.name + '.db'):
logger.debug(f'clearing {... | Delete the shelve data file. | entailment |
def close(self):
"Close the shelve object, which is needed for data consistency."
if self.is_open:
logger.info('closing shelve data')
try:
self.shelve.close()
self._shelve.clear()
except Exception:
self.is_open = False | Close the shelve object, which is needed for data consistency. | entailment |
def _map(self, data_item):
"Map ``data_item`` separately in each thread."
delegate = self.delegate
logger.debug(f'mapping: {data_item}')
if self.clobber or not self.exists(data_item.id):
logger.debug(f'exist: {data_item.id}: {self.exists(data_item.id)}')
delegate.... | Map ``data_item`` separately in each thread. | entailment |
def load_all(self, workers=None, limit=None, n_expected=None):
"""Load all instances witih multiple threads.
:param workers: number of workers to use to load instances, which
defaults to what was given in the class initializer
:param limit: return a maximum, which defaul... | Load all instances witih multiple threads.
:param workers: number of workers to use to load instances, which
defaults to what was given in the class initializer
:param limit: return a maximum, which defaults to no limit
:param n_expected: rerun the iteration on the data... | entailment |
def _make_persistent(self, model_name, pkg_name):
"""Monkey-patch object persistence (ex: to/from database) into a
bravado-core model class"""
#
# WARNING: ugly piece of monkey-patching below. Hopefully will replace
# with native bravado-core code in the future...
#
... | Monkey-patch object persistence (ex: to/from database) into a
bravado-core model class | entailment |
def spawn_api(self, app, decorator=None):
"""Auto-generate server endpoints implementing the API into this Flask app"""
if decorator:
assert type(decorator).__name__ == 'function'
self.is_server = True
self.app = app
if self.local:
# Re-generate client ca... | Auto-generate server endpoints implementing the API into this Flask app | entailment |
def json_to_model(self, model_name, j, validate=False):
"""Take a json strust and a model name, and return a model instance"""
if validate:
self.api_spec.validate(model_name, j)
return self.api_spec.json_to_model(model_name, j) | Take a json strust and a model name, and return a model instance | entailment |
def assemble(
iterable, patterns=None, minimum_items=2, case_sensitive=True,
assume_padded_when_ambiguous=False
):
'''Assemble items in *iterable* into discreet collections.
*patterns* may be specified as a list of regular expressions to limit
the returned collection possibilities. Use this when in... | Assemble items in *iterable* into discreet collections.
*patterns* may be specified as a list of regular expressions to limit
the returned collection possibilities. Use this when interested in
collections that only match specific patterns. Each pattern must contain
the expression from :py:data:`DIGITS_... | entailment |
def parse(value, pattern='{head}{padding}{tail} [{ranges}]'):
'''Parse *value* into a :py:class:`~clique.collection.Collection`.
Use *pattern* to extract information from *value*. It may make use of the
following keys:
* *head* - Common leading part of the collection.
* *tail* - Common tra... | Parse *value* into a :py:class:`~clique.collection.Collection`.
Use *pattern* to extract information from *value*. It may make use of the
following keys:
* *head* - Common leading part of the collection.
* *tail* - Common trailing part of the collection.
* *padding* - Padding value in ... | entailment |
def add(self, item):
'''Add *item*.'''
if not item in self:
index = bisect.bisect_right(self._members, item)
self._members.insert(index, item) | Add *item*. | entailment |
def discard(self, item):
'''Remove *item*.'''
index = self._index(item)
if index >= 0:
del self._members[index] | Remove *item*. | entailment |
def _index(self, item):
'''Return index of *item* in member list or -1 if not present.'''
index = bisect.bisect_left(self._members, item)
if index != len(self) and self._members[index] == item:
return index
return -1 | Return index of *item* in member list or -1 if not present. | entailment |
def _update_expression(self):
'''Update internal expression.'''
self._expression = re.compile(
'^{0}(?P<index>(?P<padding>0*)\d+?){1}$'
.format(re.escape(self.head), re.escape(self.tail))
) | Update internal expression. | entailment |
def match(self, item):
'''Return whether *item* matches this collection expression.
If a match is successful return data about the match otherwise return
None.
'''
match = self._expression.match(item)
if not match:
return None
index = match.group('i... | Return whether *item* matches this collection expression.
If a match is successful return data about the match otherwise return
None. | entailment |
def add(self, item):
'''Add *item* to collection.
raise :py:class:`~clique.error.CollectionError` if *item* cannot be
added to the collection.
'''
match = self.match(item)
if match is None:
raise clique.error.CollectionError(
'Item does not m... | Add *item* to collection.
raise :py:class:`~clique.error.CollectionError` if *item* cannot be
added to the collection. | entailment |
def remove(self, item):
'''Remove *item* from collection.
raise :py:class:`~clique.error.CollectionError` if *item* cannot be
removed from the collection.
'''
match = self.match(item)
if match is None:
raise clique.error.CollectionError(
'Ite... | Remove *item* from collection.
raise :py:class:`~clique.error.CollectionError` if *item* cannot be
removed from the collection. | entailment |
def format(self, pattern='{head}{padding}{tail} [{ranges}]'):
'''Return string representation as specified by *pattern*.
Pattern can be any format accepted by Python's standard format function
and will receive the following keyword arguments as context:
* *head* - Common leading pa... | Return string representation as specified by *pattern*.
Pattern can be any format accepted by Python's standard format function
and will receive the following keyword arguments as context:
* *head* - Common leading part of the collection.
* *tail* - Common trailing part of the ... | entailment |
def is_contiguous(self):
'''Return whether entire collection is contiguous.'''
previous = None
for index in self.indexes:
if previous is None:
previous = index
continue
if index != (previous + 1):
return False
... | Return whether entire collection is contiguous. | entailment |
def holes(self):
'''Return holes in collection.
Return :py:class:`~clique.collection.Collection` of missing indexes.
'''
missing = set([])
previous = None
for index in self.indexes:
if previous is None:
previous = index
contin... | Return holes in collection.
Return :py:class:`~clique.collection.Collection` of missing indexes. | entailment |
def is_compatible(self, collection):
'''Return whether *collection* is compatible with this collection.
To be compatible *collection* must have the same head, tail and padding
properties as this collection.
'''
return all([
isinstance(collection, Collection),
... | Return whether *collection* is compatible with this collection.
To be compatible *collection* must have the same head, tail and padding
properties as this collection. | entailment |
def merge(self, collection):
'''Merge *collection* into this collection.
If the *collection* is compatible with this collection then update
indexes with all indexes in *collection*.
raise :py:class:`~clique.error.CollectionError` if *collection* is not
compatible with this coll... | Merge *collection* into this collection.
If the *collection* is compatible with this collection then update
indexes with all indexes in *collection*.
raise :py:class:`~clique.error.CollectionError` if *collection* is not
compatible with this collection. | entailment |
def separate(self):
'''Return contiguous parts of collection as separate collections.
Return as list of :py:class:`~clique.collection.Collection` instances.
'''
collections = []
start = None
end = None
for index in self.indexes:
if start is None:
... | Return contiguous parts of collection as separate collections.
Return as list of :py:class:`~clique.collection.Collection` instances. | entailment |
def format_check(settings):
"""
Check the format of a osmnet_config object.
Parameters
----------
settings : dict
osmnet_config as a dictionary
Returns
-------
Nothing
"""
valid_keys = ['logs_folder', 'log_file', 'log_console', 'log_name',
'log_filenam... | Check the format of a osmnet_config object.
Parameters
----------
settings : dict
osmnet_config as a dictionary
Returns
-------
Nothing | entailment |
def to_dict(self):
"""
Return a dict representation of an osmnet osmnet_config instance.
"""
return {'logs_folder': self.logs_folder,
'log_file': self.log_file,
'log_console': self.log_console,
'log_name': self.log_name,
'lo... | Return a dict representation of an osmnet osmnet_config instance. | entailment |
def great_circle_dist(lat1, lon1, lat2, lon2):
"""
Get the distance (in meters) between two lat/lon points
via the Haversine formula.
Parameters
----------
lat1, lon1, lat2, lon2 : float
Latitude and longitude in degrees.
Returns
-------
dist : float
Distance in met... | Get the distance (in meters) between two lat/lon points
via the Haversine formula.
Parameters
----------
lat1, lon1, lat2, lon2 : float
Latitude and longitude in degrees.
Returns
-------
dist : float
Distance in meters. | entailment |
def osm_filter(network_type):
"""
Create a filter to query Overpass API for the specified OSM network type.
Parameters
----------
network_type : string, {'walk', 'drive'} denoting the type of street
network to extract
Returns
-------
osm_filter : string
"""
filters = {}
... | Create a filter to query Overpass API for the specified OSM network type.
Parameters
----------
network_type : string, {'walk', 'drive'} denoting the type of street
network to extract
Returns
-------
osm_filter : string | entailment |
def osm_net_download(lat_min=None, lng_min=None, lat_max=None, lng_max=None,
network_type='walk', timeout=180, memory=None,
max_query_area_size=50*1000*50*1000,
custom_osm_filter=None):
"""
Download OSM ways and nodes within a bounding box from the ... | Download OSM ways and nodes within a bounding box from the Overpass API.
Parameters
----------
lat_min : float
southern latitude of bounding box
lng_min : float
eastern longitude of bounding box
lat_max : float
northern latitude of bounding box
lng_max : float
we... | entailment |
def overpass_request(data, pause_duration=None, timeout=180,
error_pause_duration=None):
"""
Send a request to the Overpass API via HTTP POST and return the
JSON response
Parameters
----------
data : dict or OrderedDict
key-value pairs of parameters to post to Overp... | Send a request to the Overpass API via HTTP POST and return the
JSON response
Parameters
----------
data : dict or OrderedDict
key-value pairs of parameters to post to Overpass API
pause_duration : int
how long to pause in seconds before requests, if None, will query
Overpas... | entailment |
def get_pause_duration(recursive_delay=5, default_duration=10):
"""
Check the Overpass API status endpoint to determine how long to wait until
next slot is available.
Parameters
----------
recursive_delay : int
how long to wait between recursive calls if server is currently
runn... | Check the Overpass API status endpoint to determine how long to wait until
next slot is available.
Parameters
----------
recursive_delay : int
how long to wait between recursive calls if server is currently
running a query
default_duration : int
if fatal error, function fall... | entailment |
def consolidate_subdivide_geometry(geometry, max_query_area_size):
"""
Consolidate a geometry into a convex hull, then subdivide it into
smaller sub-polygons if its area exceeds max size (in geometry's units).
Parameters
----------
geometry : shapely Polygon or MultiPolygon
the geometry... | Consolidate a geometry into a convex hull, then subdivide it into
smaller sub-polygons if its area exceeds max size (in geometry's units).
Parameters
----------
geometry : shapely Polygon or MultiPolygon
the geometry to consolidate and subdivide
max_query_area_size : float
max area ... | entailment |
def quadrat_cut_geometry(geometry, quadrat_width, min_num=3,
buffer_amount=1e-9):
"""
Split a Polygon or MultiPolygon up into sub-polygons of a specified size,
using quadrats.
Parameters
----------
geometry : shapely Polygon or MultiPolygon
the geometry to split... | Split a Polygon or MultiPolygon up into sub-polygons of a specified size,
using quadrats.
Parameters
----------
geometry : shapely Polygon or MultiPolygon
the geometry to split up into smaller sub-polygons
quadrat_width : float
the linear width of the quadrats with which to cut up t... | entailment |
def project_geometry(geometry, crs, to_latlong=False):
"""
Project a shapely Polygon or MultiPolygon from WGS84 to UTM, or vice-versa
Parameters
----------
geometry : shapely Polygon or MultiPolygon
the geometry to project
crs : int
the starting coordinate reference system of th... | Project a shapely Polygon or MultiPolygon from WGS84 to UTM, or vice-versa
Parameters
----------
geometry : shapely Polygon or MultiPolygon
the geometry to project
crs : int
the starting coordinate reference system of the passed-in geometry
to_latlong : bool
if True, project... | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.