repository_name stringclasses 316
values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1
value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1
value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
ttroy50/pyephember | pyephember/pyephember.py | EphEmber._request_token | python | def _request_token(self, force=False):
if self.login_data is None:
raise RuntimeError("Don't have a token to refresh")
if not force:
if not self._requires_refresh_token():
# no need to refresh as token is valid
return True
headers = {
... | Request a new auth token | train | https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L41-L75 | null | class EphEmber:
"""Interacts with a EphEmber thermostat via API.
Example usage: t = EphEmber('me@somewhere.com', 'mypasswd')
t.getZoneTemperature('myzone') # Get temperature
"""
# pylint: disable=too-many-instance-attributes
def _requires_refresh_token(self):
"""
... |
ttroy50/pyephember | pyephember/pyephember.py | EphEmber._login | python | def _login(self):
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json"
}
url = self.api_base_url + "account/directlogin"
data = {'Email': self.username,
'Password': self.password,
'Remember... | Login using username / password and get the first auth token | train | https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L77-L109 | null | class EphEmber:
"""Interacts with a EphEmber thermostat via API.
Example usage: t = EphEmber('me@somewhere.com', 'mypasswd')
t.getZoneTemperature('myzone') # Get temperature
"""
# pylint: disable=too-many-instance-attributes
def _requires_refresh_token(self):
"""
... |
ttroy50/pyephember | pyephember/pyephember.py | EphEmber.get_home | python | def get_home(self, home_id=None):
now = datetime.datetime.utcnow()
if self.home and now < self.home_refresh_at:
return self.home
if not self._do_auth():
raise RuntimeError("Unable to login")
if home_id is None:
home_id = self.home_id
url = s... | Get the data about a home | train | https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L121-L162 | [
"def _do_auth(self):\n \"\"\"\n Do authentication to the system (if required)\n \"\"\"\n if self.login_data is None:\n return self._login()\n\n return self._request_token()\n"
] | class EphEmber:
"""Interacts with a EphEmber thermostat via API.
Example usage: t = EphEmber('me@somewhere.com', 'mypasswd')
t.getZoneTemperature('myzone') # Get temperature
"""
# pylint: disable=too-many-instance-attributes
def _requires_refresh_token(self):
"""
... |
ttroy50/pyephember | pyephember/pyephember.py | EphEmber.get_zones | python | def get_zones(self):
home_data = self.get_home()
if not home_data['isSuccess']:
return []
zones = []
for receiver in home_data['data']['receivers']:
for zone in receiver['zones']:
zones.append(zone)
return zones | Get all zones | train | https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L164-L178 | [
"def get_home(self, home_id=None):\n \"\"\"\n Get the data about a home\n \"\"\"\n now = datetime.datetime.utcnow()\n if self.home and now < self.home_refresh_at:\n return self.home\n\n if not self._do_auth():\n raise RuntimeError(\"Unable to login\")\n\n if home_id is None:\n ... | class EphEmber:
"""Interacts with a EphEmber thermostat via API.
Example usage: t = EphEmber('me@somewhere.com', 'mypasswd')
t.getZoneTemperature('myzone') # Get temperature
"""
# pylint: disable=too-many-instance-attributes
def _requires_refresh_token(self):
"""
... |
ttroy50/pyephember | pyephember/pyephember.py | EphEmber.get_zone_names | python | def get_zone_names(self):
zone_names = []
for zone in self.get_zones():
zone_names.append(zone['name'])
return zone_names | Get the name of all zones | train | https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L180-L188 | [
"def get_zones(self):\n \"\"\"\n Get all zones\n \"\"\"\n home_data = self.get_home()\n if not home_data['isSuccess']:\n return []\n\n zones = []\n\n for receiver in home_data['data']['receivers']:\n for zone in receiver['zones']:\n zones.append(zone)\n\n return zone... | class EphEmber:
"""Interacts with a EphEmber thermostat via API.
Example usage: t = EphEmber('me@somewhere.com', 'mypasswd')
t.getZoneTemperature('myzone') # Get temperature
"""
# pylint: disable=too-many-instance-attributes
def _requires_refresh_token(self):
"""
... |
ttroy50/pyephember | pyephember/pyephember.py | EphEmber.get_zone | python | def get_zone(self, zone_name):
for zone in self.get_zones():
if zone_name == zone['name']:
return zone
raise RuntimeError("Unknown zone") | Get the information about a particular zone | train | https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L190-L198 | [
"def get_zones(self):\n \"\"\"\n Get all zones\n \"\"\"\n home_data = self.get_home()\n if not home_data['isSuccess']:\n return []\n\n zones = []\n\n for receiver in home_data['data']['receivers']:\n for zone in receiver['zones']:\n zones.append(zone)\n\n return zone... | class EphEmber:
"""Interacts with a EphEmber thermostat via API.
Example usage: t = EphEmber('me@somewhere.com', 'mypasswd')
t.getZoneTemperature('myzone') # Get temperature
"""
# pylint: disable=too-many-instance-attributes
def _requires_refresh_token(self):
"""
... |
ttroy50/pyephember | pyephember/pyephember.py | EphEmber.is_zone_active | python | def is_zone_active(self, zone_name):
zone = self.get_zone(zone_name)
if zone is None:
raise RuntimeError("Unable to get zone")
return zone['isCurrentlyActive'] | Check if a zone is active | train | https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L200-L208 | [
"def get_zone(self, zone_name):\n \"\"\"\n Get the information about a particular zone\n \"\"\"\n for zone in self.get_zones():\n if zone_name == zone['name']:\n return zone\n\n raise RuntimeError(\"Unknown zone\")\n"
] | class EphEmber:
"""Interacts with a EphEmber thermostat via API.
Example usage: t = EphEmber('me@somewhere.com', 'mypasswd')
t.getZoneTemperature('myzone') # Get temperature
"""
# pylint: disable=too-many-instance-attributes
def _requires_refresh_token(self):
"""
... |
ttroy50/pyephember | pyephember/pyephember.py | EphEmber.get_zone_temperature | python | def get_zone_temperature(self, zone_name):
zone = self.get_zone(zone_name)
if zone is None:
raise RuntimeError("Unknown zone")
return zone['currentTemperature'] | Get the temperature for a zone | train | https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L210-L219 | [
"def get_zone(self, zone_name):\n \"\"\"\n Get the information about a particular zone\n \"\"\"\n for zone in self.get_zones():\n if zone_name == zone['name']:\n return zone\n\n raise RuntimeError(\"Unknown zone\")\n"
] | class EphEmber:
"""Interacts with a EphEmber thermostat via API.
Example usage: t = EphEmber('me@somewhere.com', 'mypasswd')
t.getZoneTemperature('myzone') # Get temperature
"""
# pylint: disable=too-many-instance-attributes
def _requires_refresh_token(self):
"""
... |
ttroy50/pyephember | pyephember/pyephember.py | EphEmber.is_boost_active | python | def is_boost_active(self, zone_name):
zone = self.get_zone(zone_name)
if zone is None:
raise RuntimeError("Unknown zone")
return zone['isBoostActive'] | Check if a zone is active | train | https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L221-L230 | [
"def get_zone(self, zone_name):\n \"\"\"\n Get the information about a particular zone\n \"\"\"\n for zone in self.get_zones():\n if zone_name == zone['name']:\n return zone\n\n raise RuntimeError(\"Unknown zone\")\n"
] | class EphEmber:
"""Interacts with a EphEmber thermostat via API.
Example usage: t = EphEmber('me@somewhere.com', 'mypasswd')
t.getZoneTemperature('myzone') # Get temperature
"""
# pylint: disable=too-many-instance-attributes
def _requires_refresh_token(self):
"""
... |
ttroy50/pyephember | pyephember/pyephember.py | EphEmber.is_target_temperature_reached | python | def is_target_temperature_reached(self, zone_name):
zone = self.get_zone(zone_name)
if zone is None:
raise RuntimeError("Unknown zone")
return zone['isTargetTemperatureReached'] | Check if a zone is active | train | https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L232-L241 | [
"def get_zone(self, zone_name):\n \"\"\"\n Get the information about a particular zone\n \"\"\"\n for zone in self.get_zones():\n if zone_name == zone['name']:\n return zone\n\n raise RuntimeError(\"Unknown zone\")\n"
] | class EphEmber:
"""Interacts with a EphEmber thermostat via API.
Example usage: t = EphEmber('me@somewhere.com', 'mypasswd')
t.getZoneTemperature('myzone') # Get temperature
"""
# pylint: disable=too-many-instance-attributes
def _requires_refresh_token(self):
"""
... |
ttroy50/pyephember | pyephember/pyephember.py | EphEmber.set_target_temperature_by_id | python | def set_target_temperature_by_id(self, zone_id, target_temperature):
if not self._do_auth():
raise RuntimeError("Unable to login")
data = {
"ZoneId": zone_id,
"TargetTemperature": target_temperature
}
headers = {
"Accept": "application/js... | Set the target temperature for a zone by id | train | https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L243-L272 | [
"def _do_auth(self):\n \"\"\"\n Do authentication to the system (if required)\n \"\"\"\n if self.login_data is None:\n return self._login()\n\n return self._request_token()\n"
] | class EphEmber:
"""Interacts with a EphEmber thermostat via API.
Example usage: t = EphEmber('me@somewhere.com', 'mypasswd')
t.getZoneTemperature('myzone') # Get temperature
"""
# pylint: disable=too-many-instance-attributes
def _requires_refresh_token(self):
"""
... |
ttroy50/pyephember | pyephember/pyephember.py | EphEmber.set_target_temperture_by_name | python | def set_target_temperture_by_name(self, zone_name, target_temperature):
zone = self.get_zone(zone_name)
if zone is None:
raise RuntimeError("Unknown zone")
return self.set_target_temperature_by_id(zone["zoneId"],
target_temperature) | Set the target temperature for a zone by name | train | https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L274-L284 | [
"def get_zone(self, zone_name):\n \"\"\"\n Get the information about a particular zone\n \"\"\"\n for zone in self.get_zones():\n if zone_name == zone['name']:\n return zone\n\n raise RuntimeError(\"Unknown zone\")\n",
"def set_target_temperature_by_id(self, zone_id, target_temper... | class EphEmber:
"""Interacts with a EphEmber thermostat via API.
Example usage: t = EphEmber('me@somewhere.com', 'mypasswd')
t.getZoneTemperature('myzone') # Get temperature
"""
# pylint: disable=too-many-instance-attributes
def _requires_refresh_token(self):
"""
... |
ttroy50/pyephember | pyephember/pyephember.py | EphEmber.activate_boost_by_id | python | def activate_boost_by_id(self, zone_id, target_temperature, num_hours=1):
if not self._do_auth():
raise RuntimeError("Unable to login")
zones = [zone_id]
data = {
"ZoneIds": zones,
"NumberOfHours": num_hours,
"TargetTemperature": target_temperatur... | Activate boost for a zone based on the numeric id | train | https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L286-L317 | [
"def _do_auth(self):\n \"\"\"\n Do authentication to the system (if required)\n \"\"\"\n if self.login_data is None:\n return self._login()\n\n return self._request_token()\n"
] | class EphEmber:
"""Interacts with a EphEmber thermostat via API.
Example usage: t = EphEmber('me@somewhere.com', 'mypasswd')
t.getZoneTemperature('myzone') # Get temperature
"""
# pylint: disable=too-many-instance-attributes
def _requires_refresh_token(self):
"""
... |
ttroy50/pyephember | pyephember/pyephember.py | EphEmber.activate_boost_by_name | python | def activate_boost_by_name(self,
zone_name,
target_temperature,
num_hours=1):
zone = self.get_zone(zone_name)
if zone is None:
raise RuntimeError("Unknown zone")
return self.activate_boost_... | Activate boost by the name of the zone | train | https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L319-L332 | [
"def get_zone(self, zone_name):\n \"\"\"\n Get the information about a particular zone\n \"\"\"\n for zone in self.get_zones():\n if zone_name == zone['name']:\n return zone\n\n raise RuntimeError(\"Unknown zone\")\n",
"def activate_boost_by_id(self, zone_id, target_temperature, n... | class EphEmber:
"""Interacts with a EphEmber thermostat via API.
Example usage: t = EphEmber('me@somewhere.com', 'mypasswd')
t.getZoneTemperature('myzone') # Get temperature
"""
# pylint: disable=too-many-instance-attributes
def _requires_refresh_token(self):
"""
... |
ttroy50/pyephember | pyephember/pyephember.py | EphEmber.deactivate_boost_by_name | python | def deactivate_boost_by_name(self, zone_name):
zone = self.get_zone(zone_name)
if zone is None:
raise RuntimeError("Unknown zone")
return self.deactivate_boost_by_id(zone["zoneId"]) | Deactivate boost by the name of the zone | train | https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L362-L371 | [
"def get_zone(self, zone_name):\n \"\"\"\n Get the information about a particular zone\n \"\"\"\n for zone in self.get_zones():\n if zone_name == zone['name']:\n return zone\n\n raise RuntimeError(\"Unknown zone\")\n",
"def deactivate_boost_by_id(self, zone_id):\n \"\"\"\n D... | class EphEmber:
"""Interacts with a EphEmber thermostat via API.
Example usage: t = EphEmber('me@somewhere.com', 'mypasswd')
t.getZoneTemperature('myzone') # Get temperature
"""
# pylint: disable=too-many-instance-attributes
def _requires_refresh_token(self):
"""
... |
ttroy50/pyephember | pyephember/pyephember.py | EphEmber.set_mode_by_id | python | def set_mode_by_id(self, zone_id, mode):
if not self._do_auth():
raise RuntimeError("Unable to login")
data = {
"ZoneId": zone_id,
"mode": mode.value
}
headers = {
"Accept": "application/json",
"Content-Type": "application/jso... | Set the mode by using the zone id
Supported zones are available in the enum Mode | train | https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L373-L402 | [
"def _do_auth(self):\n \"\"\"\n Do authentication to the system (if required)\n \"\"\"\n if self.login_data is None:\n return self._login()\n\n return self._request_token()\n"
] | class EphEmber:
"""Interacts with a EphEmber thermostat via API.
Example usage: t = EphEmber('me@somewhere.com', 'mypasswd')
t.getZoneTemperature('myzone') # Get temperature
"""
# pylint: disable=too-many-instance-attributes
def _requires_refresh_token(self):
"""
... |
ttroy50/pyephember | pyephember/pyephember.py | EphEmber.set_mode_by_name | python | def set_mode_by_name(self, zone_name, mode):
zone = self.get_zone(zone_name)
if zone is None:
raise RuntimeError("Unknown zone")
return self.set_mode_by_id(zone["zoneId"], mode) | Set the mode by using the name of the zone | train | https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L404-L412 | [
"def get_zone(self, zone_name):\n \"\"\"\n Get the information about a particular zone\n \"\"\"\n for zone in self.get_zones():\n if zone_name == zone['name']:\n return zone\n\n raise RuntimeError(\"Unknown zone\")\n",
"def set_mode_by_id(self, zone_id, mode):\n \"\"\"\n Set... | class EphEmber:
"""Interacts with a EphEmber thermostat via API.
Example usage: t = EphEmber('me@somewhere.com', 'mypasswd')
t.getZoneTemperature('myzone') # Get temperature
"""
# pylint: disable=too-many-instance-attributes
def _requires_refresh_token(self):
"""
... |
ttroy50/pyephember | pyephember/pyephember.py | EphEmber.get_zone_mode | python | def get_zone_mode(self, zone_name):
zone = self.get_zone(zone_name)
if zone is None:
raise RuntimeError("Unknown zone")
return ZoneMode(zone['mode']) | Get the mode for a zone | train | https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L414-L423 | [
"def get_zone(self, zone_name):\n \"\"\"\n Get the information about a particular zone\n \"\"\"\n for zone in self.get_zones():\n if zone_name == zone['name']:\n return zone\n\n raise RuntimeError(\"Unknown zone\")\n"
] | class EphEmber:
"""Interacts with a EphEmber thermostat via API.
Example usage: t = EphEmber('me@somewhere.com', 'mypasswd')
t.getZoneTemperature('myzone') # Get temperature
"""
# pylint: disable=too-many-instance-attributes
def _requires_refresh_token(self):
"""
... |
textbook/atmdb | atmdb/core.py | Service.url_builder | python | def url_builder(self, endpoint, *, root=None, params=None, url_params=None):
if root is None:
root = self.ROOT
return ''.join([
root,
endpoint,
'?' + urlencode(url_params) if url_params else '',
]).format(**params or {}) | Create a URL for the specified endpoint.
Arguments:
endpoint (:py:class:`str`): The API endpoint to access.
root: (:py:class:`str`, optional): The root URL for the
service API.
params: (:py:class:`dict`, optional): The values for format
into the created URL... | train | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/core.py#L40-L62 | null | class Service(metaclass=ABCMeta):
"""Abstract base class for API wrapper services."""
REQUIRED = set()
""":py:class:`set`: The service's required configuration keys."""
ROOT = ''
""":py:class:`str`: The root URL for the API."""
@abstractmethod
def __init__(self, *_, **kwargs):
sel... |
textbook/atmdb | atmdb/core.py | Service.calculate_timeout | python | def calculate_timeout(http_date):
try:
return int(http_date)
except ValueError:
date_after = parse(http_date)
utc_now = datetime.now(tz=timezone.utc)
return int((date_after - utc_now).total_seconds()) | Extract request timeout from e.g. ``Retry-After`` header.
Notes:
Per :rfc:`2616#section-14.37`, the ``Retry-After`` header can
be either an integer number of seconds or an HTTP date. This
function can handle either.
Arguments:
http_date (:py:class:`str`): The da... | train | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/core.py#L65-L85 | null | class Service(metaclass=ABCMeta):
"""Abstract base class for API wrapper services."""
REQUIRED = set()
""":py:class:`set`: The service's required configuration keys."""
ROOT = ''
""":py:class:`str`: The root URL for the API."""
@abstractmethod
def __init__(self, *_, **kwargs):
sel... |
textbook/atmdb | atmdb/core.py | TokenAuthMixin.from_env | python | def from_env(cls):
token = getenv(cls.TOKEN_ENV_VAR)
if token is None:
msg = 'missing environment variable: {!r}'.format(cls.TOKEN_ENV_VAR)
raise ValueError(msg)
return cls(api_token=token) | Create a service instance from an environment variable. | train | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/core.py#L104-L110 | null | class TokenAuthMixin:
"""Mix-in class for implementing token authentication.
Arguments:
api_token (:py:class:`str`): A valid API token.
"""
TOKEN_ENV_VAR = None
""":py:class:`str`: The environment variable holding the token."""
def __init__(self, *, api_token, **kwargs):
self.a... |
textbook/atmdb | atmdb/core.py | UrlParamMixin.url_builder | python | def url_builder(self, endpoint, params=None, url_params=None):
if url_params is None:
url_params = OrderedDict()
url_params[self.AUTH_PARAM] = self.api_token
return super().url_builder(
endpoint,
params=params,
url_params=url_params,
) | Add authentication URL parameter. | train | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/core.py#L119-L128 | null | class UrlParamMixin(TokenAuthMixin):
"""Mix-in class for implementing URL parameter authentication."""
AUTH_PARAM = None
""":py:class:`str`: The name of the URL parameter."""
|
textbook/atmdb | atmdb/models.py | BaseModel._create_image_url | python | def _create_image_url(self, file_path, type_, target_size):
if self.image_config is None:
logger.warning('no image configuration available')
return
return ''.join([
self.image_config['secure_base_url'],
self._image_size(self.image_config, type_, target_siz... | The the closest available size for specified image type.
Arguments:
file_path (:py:class:`str`): The image file path.
type_ (:py:class:`str`): The type of image to create a URL
for, (``'poster'`` or ``'profile'``).
target_size (:py:class:`int`): The size of image to ai... | train | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/models.py#L65-L83 | [
"def _image_size(image_config, type_, target_size):\n \"\"\"Find the closest available size for specified image type.\n\n Arguments:\n image_config (:py:class:`dict`): The image config data.\n type_ (:py:class:`str`): The type of image to create a URL\n for, (``'poster'`` or ``'profile'``).\n... | class BaseModel:
"""Base TMDb model functionality.
Arguments:
id_ (:py:class:`int`): The TMDb ID of the object.
image_path (:py:class:`str`): The short path to the image.
Attributes:
image_url (:py:class:`str`): The fully-qualified image URL.
"""
CONTAINS = None
""":py:clas... |
textbook/atmdb | atmdb/models.py | BaseModel.from_json | python | def from_json(cls, json, image_config=None):
cls.image_config = image_config
return cls(**{
attr: json.get(attr if key is None else key)
for attr, key in cls.JSON_MAPPING.items()
}) | Create a model instance
Arguments:
json (:py:class:`dict`): The parsed JSON data.
image_config (:py:class:`dict`): The API image configuration
data.
Returns:
:py:class:`BaseModel`: The model instance. | train | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/models.py#L86-L102 | null | class BaseModel:
"""Base TMDb model functionality.
Arguments:
id_ (:py:class:`int`): The TMDb ID of the object.
image_path (:py:class:`str`): The short path to the image.
Attributes:
image_url (:py:class:`str`): The fully-qualified image URL.
"""
CONTAINS = None
""":py:clas... |
textbook/atmdb | atmdb/models.py | BaseModel._image_size | python | def _image_size(image_config, type_, target_size):
return min(
image_config['{}_sizes'.format(type_)],
key=lambda size: (abs(target_size - int(size[1:]))
if size.startswith('w') or size.startswith('h')
else 999),
) | Find the closest available size for specified image type.
Arguments:
image_config (:py:class:`dict`): The image config data.
type_ (:py:class:`str`): The type of image to create a URL
for, (``'poster'`` or ``'profile'``).
target_size (:py:class:`int`): The size of imag... | train | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/models.py#L105-L121 | null | class BaseModel:
"""Base TMDb model functionality.
Arguments:
id_ (:py:class:`int`): The TMDb ID of the object.
image_path (:py:class:`str`): The short path to the image.
Attributes:
image_url (:py:class:`str`): The fully-qualified image URL.
"""
CONTAINS = None
""":py:clas... |
textbook/atmdb | atmdb/client.py | TMDbClient._update_config | python | async def _update_config(self):
if self.config['data'] is None or self.config_expired:
data = await self.get_data(self.url_builder('configuration'))
self.config = dict(data=data, last_update=datetime.now()) | Update configuration data if required.
Notes:
Per `the documentation`_, this updates the API configuration
data *"every few days"*.
.. _the documentation:
http://docs.themoviedb.apiary.io/#reference/configuration | train | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/client.py#L44-L57 | null | class TMDbClient(UrlParamMixin, Service):
"""Simple wrapper for the `TMDb`_ API.
.. _TMDb: https://www.themoviedb.org/
"""
AUTH_PARAM = 'api_key'
ROOT = 'https://api.themoviedb.org/3/'
TOKEN_ENV_VAR = 'TMDB_API_TOKEN'
def __init__(self, *, api_token=None, **kwargs):
super().__i... |
textbook/atmdb | atmdb/client.py | TMDbClient.get_data | python | async def get_data(self, url):
logger.debug('making request to %r', url)
with aiohttp.ClientSession() as session:
async with session.get(url, headers=self.headers) as response:
body = json.loads((await response.read()).decode('utf-8'))
if response.status == HT... | Get data from the TMDb API via :py:func:`aiohttp.get`.
Notes:
Updates configuration (if required) on successful requests.
Arguments:
url (:py:class:`str`): The endpoint URL and params.
Returns:
:py:class:`dict`: The parsed JSON result. | train | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/client.py#L59-L94 | null | class TMDbClient(UrlParamMixin, Service):
"""Simple wrapper for the `TMDb`_ API.
.. _TMDb: https://www.themoviedb.org/
"""
AUTH_PARAM = 'api_key'
ROOT = 'https://api.themoviedb.org/3/'
TOKEN_ENV_VAR = 'TMDB_API_TOKEN'
def __init__(self, *, api_token=None, **kwargs):
super().__i... |
textbook/atmdb | atmdb/client.py | TMDbClient.find_movie | python | async def find_movie(self, query):
params = OrderedDict([
('query', query), ('include_adult', False),
])
url = self.url_builder('search/movie', {}, params)
data = await self.get_data(url)
if data is None:
return
return [
Movie.from_json... | Retrieve movie data by search query.
Arguments:
query (:py:class:`str`): Query to search for.
Returns:
:py:class:`list`: Possible matches. | train | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/client.py#L96-L116 | [
"async def get_data(self, url):\n \"\"\"Get data from the TMDb API via :py:func:`aiohttp.get`.\n\n Notes:\n Updates configuration (if required) on successful requests.\n\n Arguments:\n url (:py:class:`str`): The endpoint URL and params.\n\n Returns:\n :py:class:`dict`: The parsed JSON res... | class TMDbClient(UrlParamMixin, Service):
"""Simple wrapper for the `TMDb`_ API.
.. _TMDb: https://www.themoviedb.org/
"""
AUTH_PARAM = 'api_key'
ROOT = 'https://api.themoviedb.org/3/'
TOKEN_ENV_VAR = 'TMDB_API_TOKEN'
def __init__(self, *, api_token=None, **kwargs):
super().__i... |
textbook/atmdb | atmdb/client.py | TMDbClient.find_person | python | async def find_person(self, query):
url = self.url_builder(
'search/person',
dict(),
url_params=OrderedDict([
('query', query), ('include_adult', False)
]),
)
data = await self.get_data(url)
if data is None:
retu... | Retrieve person data by search query.
Arguments:
query (:py:class:`str`): Query to search for.
Returns:
:py:class:`list`: Possible matches. | train | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/client.py#L118-L141 | [
"async def get_data(self, url):\n \"\"\"Get data from the TMDb API via :py:func:`aiohttp.get`.\n\n Notes:\n Updates configuration (if required) on successful requests.\n\n Arguments:\n url (:py:class:`str`): The endpoint URL and params.\n\n Returns:\n :py:class:`dict`: The parsed JSON res... | class TMDbClient(UrlParamMixin, Service):
"""Simple wrapper for the `TMDb`_ API.
.. _TMDb: https://www.themoviedb.org/
"""
AUTH_PARAM = 'api_key'
ROOT = 'https://api.themoviedb.org/3/'
TOKEN_ENV_VAR = 'TMDB_API_TOKEN'
def __init__(self, *, api_token=None, **kwargs):
super().__i... |
textbook/atmdb | atmdb/client.py | TMDbClient.get_movie | python | async def get_movie(self, id_):
url = self.url_builder(
'movie/{movie_id}',
dict(movie_id=id_),
url_params=OrderedDict(append_to_response='credits'),
)
data = await self.get_data(url)
if data is None:
return
return Movie.from_json(d... | Retrieve movie data by ID.
Arguments:
id_ (:py:class:`int`): The movie's TMDb ID.
Returns:
:py:class:`~.Movie`: The requested movie. | train | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/client.py#L143-L161 | [
"async def get_data(self, url):\n \"\"\"Get data from the TMDb API via :py:func:`aiohttp.get`.\n\n Notes:\n Updates configuration (if required) on successful requests.\n\n Arguments:\n url (:py:class:`str`): The endpoint URL and params.\n\n Returns:\n :py:class:`dict`: The parsed JSON res... | class TMDbClient(UrlParamMixin, Service):
"""Simple wrapper for the `TMDb`_ API.
.. _TMDb: https://www.themoviedb.org/
"""
AUTH_PARAM = 'api_key'
ROOT = 'https://api.themoviedb.org/3/'
TOKEN_ENV_VAR = 'TMDB_API_TOKEN'
def __init__(self, *, api_token=None, **kwargs):
super().__i... |
textbook/atmdb | atmdb/client.py | TMDbClient.get_person | python | async def get_person(self, id_):
data = await self._get_person_json(
id_,
OrderedDict(append_to_response='movie_credits')
)
return Person.from_json(data, self.config['data'].get('images')) | Retrieve person data by ID.
Arguments:
id_ (:py:class:`int`): The person's TMDb ID.
Returns:
:py:class:`~.Person`: The requested person. | train | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/client.py#L163-L177 | [
"async def _get_person_json(self, id_, url_params=None):\n \"\"\"Retrieve raw person JSON by ID.\n\n Arguments:\n id_ (:py:class:`int`): The person's TMDb ID.\n url_params (:py:class:`dict`): Any additional URL parameters.\n\n Returns:\n :py:class:`dict`: The JSON data.\n\n \"\"\"\n ur... | class TMDbClient(UrlParamMixin, Service):
"""Simple wrapper for the `TMDb`_ API.
.. _TMDb: https://www.themoviedb.org/
"""
AUTH_PARAM = 'api_key'
ROOT = 'https://api.themoviedb.org/3/'
TOKEN_ENV_VAR = 'TMDB_API_TOKEN'
def __init__(self, *, api_token=None, **kwargs):
super().__i... |
textbook/atmdb | atmdb/client.py | TMDbClient._get_person_json | python | async def _get_person_json(self, id_, url_params=None):
url = self.url_builder(
'person/{person_id}',
dict(person_id=id_),
url_params=url_params or OrderedDict(),
)
data = await self.get_data(url)
return data | Retrieve raw person JSON by ID.
Arguments:
id_ (:py:class:`int`): The person's TMDb ID.
url_params (:py:class:`dict`): Any additional URL parameters.
Returns:
:py:class:`dict`: The JSON data. | train | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/client.py#L179-L196 | [
"async def get_data(self, url):\n \"\"\"Get data from the TMDb API via :py:func:`aiohttp.get`.\n\n Notes:\n Updates configuration (if required) on successful requests.\n\n Arguments:\n url (:py:class:`str`): The endpoint URL and params.\n\n Returns:\n :py:class:`dict`: The parsed JSON res... | class TMDbClient(UrlParamMixin, Service):
"""Simple wrapper for the `TMDb`_ API.
.. _TMDb: https://www.themoviedb.org/
"""
AUTH_PARAM = 'api_key'
ROOT = 'https://api.themoviedb.org/3/'
TOKEN_ENV_VAR = 'TMDB_API_TOKEN'
def __init__(self, *, api_token=None, **kwargs):
super().__i... |
textbook/atmdb | atmdb/client.py | TMDbClient.get_random_popular_person | python | async def get_random_popular_person(self, limit=500):
index = random.randrange(limit)
data = await self._get_popular_people_page()
if data is None:
return
if index >= len(data['results']):
# result is not on first page
page, index = self._calculate_pag... | Randomly select a popular person.
Notes:
Requires at least two API calls. May require three API calls
if the randomly-selected index isn't within the first page of
required data.
Arguments:
limit (:py:class:`int`, optional): How many of the most
popu... | train | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/client.py#L198-L228 | [
"async def _get_popular_people_page(self, page=1):\n \"\"\"Get a specific page of popular person data.\n\n Arguments:\n page (:py:class:`int`, optional): The page to get.\n\n Returns:\n :py:class:`dict`: The page data.\n\n \"\"\"\n return await self.get_data(self.url_builder(\n 'pers... | class TMDbClient(UrlParamMixin, Service):
"""Simple wrapper for the `TMDb`_ API.
.. _TMDb: https://www.themoviedb.org/
"""
AUTH_PARAM = 'api_key'
ROOT = 'https://api.themoviedb.org/3/'
TOKEN_ENV_VAR = 'TMDB_API_TOKEN'
def __init__(self, *, api_token=None, **kwargs):
super().__i... |
textbook/atmdb | atmdb/client.py | TMDbClient._get_popular_people_page | python | async def _get_popular_people_page(self, page=1):
return await self.get_data(self.url_builder(
'person/popular',
url_params=OrderedDict(page=page),
)) | Get a specific page of popular person data.
Arguments:
page (:py:class:`int`, optional): The page to get.
Returns:
:py:class:`dict`: The page data. | train | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/client.py#L230-L243 | [
"async def get_data(self, url):\n \"\"\"Get data from the TMDb API via :py:func:`aiohttp.get`.\n\n Notes:\n Updates configuration (if required) on successful requests.\n\n Arguments:\n url (:py:class:`str`): The endpoint URL and params.\n\n Returns:\n :py:class:`dict`: The parsed JSON res... | class TMDbClient(UrlParamMixin, Service):
"""Simple wrapper for the `TMDb`_ API.
.. _TMDb: https://www.themoviedb.org/
"""
AUTH_PARAM = 'api_key'
ROOT = 'https://api.themoviedb.org/3/'
TOKEN_ENV_VAR = 'TMDB_API_TOKEN'
def __init__(self, *, api_token=None, **kwargs):
super().__i... |
textbook/atmdb | atmdb/client.py | TMDbClient._calculate_page_index | python | def _calculate_page_index(index, data):
if index > data['total_results']:
raise ValueError('index not in paged data')
page_length = len(data['results'])
return (index // page_length) + 1, (index % page_length) - 1 | Determine the location of a given index in paged data.
Arguments:
index (:py:class:`int`): The overall index.
data: (:py:class:`dict`) The first page of data.
Returns:
:py:class:`tuple`: The location of that index, in the format
``(page, index_in_page)``. | train | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/client.py#L246-L261 | null | class TMDbClient(UrlParamMixin, Service):
"""Simple wrapper for the `TMDb`_ API.
.. _TMDb: https://www.themoviedb.org/
"""
AUTH_PARAM = 'api_key'
ROOT = 'https://api.themoviedb.org/3/'
TOKEN_ENV_VAR = 'TMDB_API_TOKEN'
def __init__(self, *, api_token=None, **kwargs):
super().__i... |
textbook/atmdb | atmdb/utils.py | _overlap | python | async def _overlap(items, overlap_attr, client=None, get_method=None):
overlap = set.intersection(*(getattr(item, overlap_attr) for item in items))
if client is None or get_method is None:
return overlap
results = []
for item in overlap:
result = await getattr(client, get_method)(id_=ite... | Generic overlap implementation.
Arguments:
item (:py:class:`collections.abc.Sequence`): The objects to
find overlaps for.
overlap_attr (:py:class:`str`): The attribute of the items to use
as input for the overlap.
client (:py:class:`~.TMDbClient`, optional): The TMDb client
... | train | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/utils.py#L77-L101 | null | """Utilities for working with TMDb models."""
async def overlapping_movies(people, client=None):
"""Find movies that the same people have been in.
Arguments:
people (:py:class:`collections.abc.Sequence`): The
:py:class:`~.Person` objects to find overlapping movies for.
client (:py:class:`... |
textbook/atmdb | atmdb/utils.py | _find_overlap | python | async def _find_overlap(queries, client, find_method, get_method,
overlap_function):
results = []
for query in queries:
candidates = await getattr(client, find_method)(query)
if not candidates:
raise ValueError('no result found for {!r}'.format(query))
... | Generic find and overlap implementation.
Arguments
names (:py:class:`collections.abc.Sequence`): The queries of the
people to find overlaps for.
client (:py:class:`~.TMDbClient`): The TMDb client.
find_method (:py:class:`str`): The name of the client method to
use for finding cand... | train | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/utils.py#L104-L127 | [
"async def overlapping_actors(movies, client=None):\n \"\"\"Find actors that appear in the same movies.\n\n Arguments:\n movies (:py:class:`collections.abc.Sequence`): The\n :py:class:`~.Movie` objects to find overlapping actors for.\n client (:py:class:`~.TMDbClient`, optional): The TMDb cli... | """Utilities for working with TMDb models."""
async def overlapping_movies(people, client=None):
"""Find movies that the same people have been in.
Arguments:
people (:py:class:`collections.abc.Sequence`): The
:py:class:`~.Person` objects to find overlapping movies for.
client (:py:class:`... |
by46/simplekit | simplekit/url/omdict1D.py | omdict1D._bin_update_items | python | def _bin_update_items(self, items, replace_at_most_one,
replacements, leftovers):
for key, values in items:
# <values> is not a list or an empty list.
like_list_not_str = self._quacks_like_a_list_but_not_str(values)
if not like_list_not_str or (like_... | Subclassed from omdict._bin_update_items() to make update() and
updateall() process lists of values as multiple values.
<replacements and <leftovers> are modified directly, ala pass by
reference. | train | https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/url/omdict1D.py#L62-L104 | null | class omdict1D(omdict):
"""
One dimensional ordered multivalue dictionary. Whenever a list of
values is passed to set(), __setitem__(), add(), update(), or
updateall(), it's treated as multiple values and the appropriate
'list' method is called on that list, like setlist() or
addlist(). For exa... |
by46/simplekit | simplekit/config/__init__.py | import_string | python | def import_string(import_name, silent=False):
"""Imports an object based on a string. This is useful if you want to
use import paths as endpoints or something similar. An import path can
be specified either in dotted notation (``xml.sax.saxutils.escape``)
or with a colon as object delimiter (``xml... | Imports an object based on a string. This is useful if you want to
use import paths as endpoints or something similar. An import path can
be specified either in dotted notation (``xml.sax.saxutils.escape``)
or with a colon as object delimiter (``xml.sax.saxutils:escape``).
If `silent` is True th... | train | https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/config/__init__.py#L15-L56 | [
"def import_string(import_name, silent=False):\n \"\"\"Imports an object based on a string. This is useful if you want to\n use import paths as endpoints or something similar. An import path can\n be specified either in dotted notation (``xml.sax.saxutils.escape``)\n or with a colon as object delimite... | import errno
import functools
import json
import logging
import os.path
import sqlite3
import sys
import types
import six
__author__ = 'benjamin.c.yan'
def import_string(import_name, silent=False):
"""Imports an object based on a string. This is useful if you want to
use import paths as endpoints or someth... |
by46/simplekit | simplekit/config/__init__.py | Config.from_mapping | python | def from_mapping(self, *mapping, **kwargs):
"""Updates the config like :meth:`update` ignoring items with non-upper
keys.
"""
mappings = []
if len(mapping) == 1:
if hasattr(mapping[0], 'items'):
mappings.append(mapping[0].items())
e... | Updates the config like :meth:`update` ignoring items with non-upper
keys. | train | https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/config/__init__.py#L141-L159 | null | class Config(dict):
def __init__(self, root_path, default=None):
dict.__init__(self, default or {})
self.root_path = root_path
def from_pyfile(self, filename, silent=False):
"""Updates the values in the config from a Python file. This function
behaves as if the file was importe... |
by46/simplekit | simplekit/config/__init__.py | Config.get_namespace | python | def get_namespace(self, namespace, lowercase=True, trim_namespace=True):
"""Returns a dictionary containing a subset of configuration options
that match the specified namespace/prefix. Example usage:
app.config['IMAGE_STORE_TYPE']='fs'
app.config['IMAGE_STORE_PATH']='/var/app... | Returns a dictionary containing a subset of configuration options
that match the specified namespace/prefix. Example usage:
app.config['IMAGE_STORE_TYPE']='fs'
app.config['IMAGE_STORE_PATH']='/var/app/images'
app.config['IMAGE_STORE_BASE_URL']='http://img.website.com'
... | train | https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/config/__init__.py#L161-L194 | null | class Config(dict):
def __init__(self, root_path, default=None):
dict.__init__(self, default or {})
self.root_path = root_path
def from_pyfile(self, filename, silent=False):
"""Updates the values in the config from a Python file. This function
behaves as if the file was importe... |
by46/simplekit | simplekit/objson/dolphin2.py | dumps | python | def dumps(obj, *args, **kwargs):
kwargs['default'] = object2dict
return json.dumps(obj, *args, **kwargs) | Serialize a object to string
Basic Usage:
>>> import simplekit.objson
>>> obj = {'name':'wendy'}
>>> print simplekit.objson.dumps(obj)
:param obj: a object which need to dump
:param args: Optional arguments that :func:`json.dumps` takes.
:param kwargs: Keys arguments that :py:func:`json.... | train | https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/objson/dolphin2.py#L78-L95 | null | import functools
import json
import re
from keyword import iskeyword
__author__ = 'benjamin.c.yan'
_re_encode = re.compile('[^a-zA-Z0-9]', re.MULTILINE)
def object2dict(obj):
return obj.__dict__
def object_hook(obj):
return Dolphin(obj)
def empty(other=None):
"""
new an empty object
basic us... |
by46/simplekit | simplekit/objson/dolphin2.py | dump | python | def dump(obj, fp, *args, **kwargs):
kwargs['default'] = object2dict
json.dump(obj, fp, *args, **kwargs) | Serialize a object to a file object.
Basic Usage:
>>> import simplekit.objson
>>> from cStringIO import StringIO
>>> obj = {'name': 'wendy'}
>>> io = StringIO()
>>> simplekit.objson.dump(obj, io)
>>> print io.getvalue()
:param obj: a object which need to dump
:param fp: a instance... | train | https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/objson/dolphin2.py#L98-L118 | null | import functools
import json
import re
from keyword import iskeyword
__author__ = 'benjamin.c.yan'
_re_encode = re.compile('[^a-zA-Z0-9]', re.MULTILINE)
def object2dict(obj):
return obj.__dict__
def object_hook(obj):
return Dolphin(obj)
def empty(other=None):
"""
new an empty object
basic us... |
by46/simplekit | simplekit/docker/utils.py | request | python | def request(method='GET'):
"""send restful post http request decorator
Provide a brief way to manipulate restful api,
:param method: :class:`str`,
:return: :class:`func`
"""
def decorator(func):
@functools.wraps(func)
def action(self, *args, **kwargs):
... | send restful post http request decorator
Provide a brief way to manipulate restful api,
:param method: :class:`str`,
:return: :class:`func` | train | https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/docker/utils.py#L11-L45 | null | import functools
import httplib
from furl import furl
from .rest import send_rest
__author__ = 'benjamin.c.yan'
def request(method='GET'):
"""send restful post http request decorator
Provide a brief way to manipulate restful api,
:param method: :class:`str`,
:return: :class:`func`
"""
d... |
by46/simplekit | simplekit/docker/utils.py | parse_image_name | python | def parse_image_name(name):
"""
parse the image name into three element tuple, like below:
(repository, name, version)
:param name: `class`:`str`, name
:return: (repository, name, version)
"""
name = name or ""
if '/' in name:
repository, other = name.split('/')
els... | parse the image name into three element tuple, like below:
(repository, name, version)
:param name: `class`:`str`, name
:return: (repository, name, version) | train | https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/docker/utils.py#L48-L66 | null | import functools
import httplib
from furl import furl
from .rest import send_rest
__author__ = 'benjamin.c.yan'
def request(method='GET'):
"""send restful post http request decorator
Provide a brief way to manipulate restful api,
:param method: :class:`str`,
:return: :class:`func`
"""
d... |
by46/simplekit | simplekit/objson/dynamic_class.py | make_dynamic_class | python | def make_dynamic_class(typename, field_names):
if isinstance(field_names, basestring):
field_names = field_names.replace(",", " ").split()
field_names = map(str, field_names)
safe_fields_names = map(_encode_property_name, field_names)
attr = dict((safe_name, _property(name)) for name, safe_nam... | a factory function to create type dynamically
The factory function is used by :func:`objson.load` and :func:`objson.loads`.
Creating the object deserialize from json string. The inspiration come from
:func:`collections.namedtuple`. the difference is that I don't your the class
template to define a dyna... | train | https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/objson/dynamic_class.py#L46-L113 | null | import re
from keyword import iskeyword as _iskeyword
__author__ = 'benjamin.c.yan@newegg.com'
_re_encode = re.compile('[^a-zA-z0-9_]', re.MULTILINE)
def _item_setter(key):
def _setter(item, value):
item[key] = value
return _setter
def _item_getter(key):
def _getter(item):
return item... |
by46/simplekit | simplekit/docker/docker.py | Docker.pull_image | python | def pull_image(self, name, tag='latest'):
"""pull the image from repository
:param name: `class`:`str`, without docker.neg prefix, invalid like: 'centos'
:param tag: `class`:`str`, special the image's version
:return: (`class`:`int`, `class`:`object`)
"""
name = "... | pull the image from repository
:param name: `class`:`str`, without docker.neg prefix, invalid like: 'centos'
:param tag: `class`:`str`, special the image's version
:return: (`class`:`int`, `class`:`object`) | train | https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/docker/docker.py#L66-L74 | null | class Docker(object):
"""Docker client
"""
LoggerName = 'Docker'
def __init__(self, server, port=8500):
self.logger = logging.getLogger('negowl')
self._session = requests.session()
self._host = server
self._port = port
self._server = 'http://{host}:{port}'.format... |
by46/simplekit | simplekit/docker/docker.py | Docker.create_container | python | def create_container(self, name, image, hostname='dfis', networkmode='bridge', ports=None, volumes=None, env=None,
restartpolicy='no', restartretrycount='2', command=""):
"""testing
:param name:
:param image:
:param hostname:
:param networkmode: `... | testing
:param name:
:param image:
:param hostname:
:param networkmode: `class`:`str`, host | bridge
:param ports: `class`:`list`, [{'type':'tcp', 'publicport':8080, 'privateport':80, 'ip':'0.0.0.0}]
:param volumes: `class`:`list`, [{"containervolume":"/app-conf",... | train | https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/docker/docker.py#L77-L105 | [
"def parse_image_name(name):\n \"\"\"\n parse the image name into three element tuple, like below:\n (repository, name, version)\n :param name: `class`:`str`, name\n :return: (repository, name, version)\n \"\"\"\n name = name or \"\"\n if '/' in name:\n repository, other = name.split(... | class Docker(object):
"""Docker client
"""
LoggerName = 'Docker'
def __init__(self, server, port=8500):
self.logger = logging.getLogger('negowl')
self._session = requests.session()
self._host = server
self._port = port
self._server = 'http://{host}:{port}'.format... |
by46/simplekit | simplekit/docker/docker.py | Docker.get_containers_by_name | python | def get_containers_by_name(self, name):
"""
get all task which relative with task name
:param name: :class:`str`, task name
:return: :class:`list`, container list
"""
code, containers = self.get_containers()
if code != httplib.OK:
return []
... | get all task which relative with task name
:param name: :class:`str`, task name
:return: :class:`list`, container list | train | https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/docker/docker.py#L126-L138 | null | class Docker(object):
"""Docker client
"""
LoggerName = 'Docker'
def __init__(self, server, port=8500):
self.logger = logging.getLogger('negowl')
self._session = requests.session()
self._host = server
self._port = port
self._server = 'http://{host}:{port}'.format... |
by46/simplekit | simplekit/docker/docker.py | Docker.delete_container_2 | python | def delete_container_2(self, name):
"""
:param name: `class`:`str`, container name
:return: `class`:`bool`, return True if delete success, otherwise return False
"""
code, container = self.get_container(name)
if code == httplib.NOT_FOUND:
return True
... | :param name: `class`:`str`, container name
:return: `class`:`bool`, return True if delete success, otherwise return False | train | https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/docker/docker.py#L143-L168 | [
"def dumps(obj, *args, **kwargs):\n \"\"\"Serialize a object to string\n\n Basic Usage:\n\n >>> import simplekit.objson\n >>> obj = {'name':'wendy'}\n >>> print simplekit.objson.dumps(obj)\n\n\n :param obj: a object which need to dump\n :param args: Optional arguments that :func:`json.dumps` ta... | class Docker(object):
"""Docker client
"""
LoggerName = 'Docker'
def __init__(self, server, port=8500):
self.logger = logging.getLogger('negowl')
self._session = requests.session()
self._host = server
self._port = port
self._server = 'http://{host}:{port}'.format... |
by46/simplekit | simplekit/docker/docker.py | Docker.update_image | python | def update_image(self, container_name, image_name):
"""
update a container's image,
:param container_name: `class`:`str`, container name
:param image_name: `class`:`str`, the full image name, like alpine:3.3
:return: `class`:`bool`, True if success, otherwise False.
... | update a container's image,
:param container_name: `class`:`str`, container name
:param image_name: `class`:`str`, the full image name, like alpine:3.3
:return: `class`:`bool`, True if success, otherwise False. | train | https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/docker/docker.py#L178-L211 | [
"def parse_image_name(name):\n \"\"\"\n parse the image name into three element tuple, like below:\n (repository, name, version)\n :param name: `class`:`str`, name\n :return: (repository, name, version)\n \"\"\"\n name = name or \"\"\n if '/' in name:\n repository, other = name.split(... | class Docker(object):
"""Docker client
"""
LoggerName = 'Docker'
def __init__(self, server, port=8500):
self.logger = logging.getLogger('negowl')
self._session = requests.session()
self._host = server
self._port = port
self._server = 'http://{host}:{port}'.format... |
by46/simplekit | simplekit/docker/docker.py | Docker.update_image_2 | python | def update_image_2(self, container_name, image_name):
"""
update a container's image,
:param container_name: `class`:`str`, container name
:param image_name: `class`:`str`, the full image name, like alpine:3.3
:return: `class`:`bool`, True if success, otherwise False.
... | update a container's image,
:param container_name: `class`:`str`, container name
:param image_name: `class`:`str`, the full image name, like alpine:3.3
:return: `class`:`bool`, True if success, otherwise False. | train | https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/docker/docker.py#L213-L247 | [
"def parse_image_name(name):\n \"\"\"\n parse the image name into three element tuple, like below:\n (repository, name, version)\n :param name: `class`:`str`, name\n :return: (repository, name, version)\n \"\"\"\n name = name or \"\"\n if '/' in name:\n repository, other = name.split(... | class Docker(object):
"""Docker client
"""
LoggerName = 'Docker'
def __init__(self, server, port=8500):
self.logger = logging.getLogger('negowl')
self._session = requests.session()
self._host = server
self._port = port
self._server = 'http://{host}:{port}'.format... |
by46/simplekit | simplekit/docker/repository.py | Repository.image_exists | python | def image_exists(self, image_name, tag='latest'):
"""
:param image_name:
:return: True the image_name location in docker.neg pos
"""
code, image = self.image_tags(image_name)
if code != httplib.OK:
return False
tag = tag.lower()
retu... | :param image_name:
:return: True the image_name location in docker.neg pos | train | https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/docker/repository.py#L27-L37 | null | class Repository(object):
"""It's used to retrieve docker information from BTS's docker repository
"""
def __init__(self, base):
self.server = base.strip("/")
self.session = requests.session()
self.headers = {}
self.logger = logging.getLogger("negowl")
@request(method='... |
by46/simplekit | simplekit/url/path.py | remove_path_segments | python | def remove_path_segments(segments, removes):
if segments == ['']:
segments.append('')
if removes == ['']:
removes.append('')
if segments == removes:
ret = []
elif len(removes) > len(segments):
ret = segments
else:
# TODO(benjamin): incomplete
removes... | Removes the removes from the tail of segments.
Examples::
>>> # '/a/b/c' - 'b/c' == '/a/'
>>> assert remove_path_segments(['', 'a', 'b', 'c'], ['b', 'c']) == ['', 'a', '']
>>> # '/a/b/c' - '/b/c' == '/a
>>> assert remove_path_segments(['', 'a', 'b', 'c'], ['', 'b', 'c']) == ['', 'a'... | train | https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/url/path.py#L9-L48 | null | from posixpath import normpath
import six
from six.moves.urllib.parse import quote, unquote
__author__ = 'benjamin.c.yan'
# TODO(benjamin): incomplete
def join_path_segments(*args):
"""Join multiple list of path segments
This function is not encoding aware, it does not test for, or changed the
encodin... |
by46/simplekit | simplekit/url/path.py | join_path_segments | python | def join_path_segments(*args):
finals = []
for segments in args:
if not segments or segments[0] == ['']:
continue
elif not finals:
finals.extend(segments)
else:
# Example #1: ['a',''] + ['b'] == ['a','b']
# Example #2: ['a',''] + ['','b'] =... | Join multiple list of path segments
This function is not encoding aware, it does not test for, or changed the
encoding of the path segments it's passed.
Example::
>>> assert join_path_segments(['a'], ['b']) == ['a','b']
>>> assert join_path_segments(['a',''], ['b']) == ['a','b']
>>... | train | https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/url/path.py#L52-L83 | null | from posixpath import normpath
import six
from six.moves.urllib.parse import quote, unquote
__author__ = 'benjamin.c.yan'
def remove_path_segments(segments, removes):
"""Removes the removes from the tail of segments.
Examples::
>>> # '/a/b/c' - 'b/c' == '/a/'
>>> assert remove_path_segments... |
by46/simplekit | simplekit/url/path.py | Path.normalize | python | def normalize(self):
if str(self):
normalized = normpath(str(self)) + ('/' * self.is_dir)
if normalized.startswith('//'): # http://bugs.python.org/636648
normalized = '/' + normalized.lstrip('/')
self.load(normalized)
return self | Normalize the path. Turn /file/title/../author to /file/author
:return: <self> | train | https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/url/path.py#L115-L126 | null | class Path(object):
def __init__(self, path):
self.segments = []
self.is_absolute = True
self.load(path)
@property
def is_dir(self):
return (self.segments == [] or
(self.segments and self.segments[-1] == ''))
@property
def is_file(self):
retu... |
dalloriam/engel | engel/widgets/structure.py | Head.load_stylesheet | python | def load_stylesheet(self, id, path):
self.add_child(HeadLink(id=id, link_type="stylesheet", path=path)) | Proper way to dynamically inject a stylesheet in a page.
:param path: Path of the stylesheet to inject. | train | https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/widgets/structure.py#L31-L37 | [
"def add_child(self, child):\n \"\"\"\n Add a new child element to this widget.\n\n :param child: Object inheriting :class:`BaseElement`.\n \"\"\"\n self.children.append(child)\n child.parent = self\n\n if self.view and self.view.is_loaded:\n self.view.dispatch({\n 'name': 'ap... | class Head(BaseContainer):
html_tag = "head"
def load_script(self, path):
"""
Proper way to dynamically inject a script in a page.
:param path: Path of the script to inject.
"""
self.view.dispatch({'name': 'script', 'path': path})
|
dalloriam/engel | engel/widgets/structure.py | List.add_child | python | def add_child(self, widget):
li_itm = _li(id=self.id + str(self._count))
li_itm.add_child(widget)
super(List, self).add_child(li_itm)
self._items.append((widget, li_itm))
self._count += 1 | Append a widget to the list.
:param widget: Object inheriting :class:`~.widgets.base.BaseElement` | train | https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/widgets/structure.py#L70-L81 | [
"def add_child(self, child):\n \"\"\"\n Add a new child element to this widget.\n\n :param child: Object inheriting :class:`BaseElement`.\n \"\"\"\n self.children.append(child)\n child.parent = self\n\n if self.view and self.view.is_loaded:\n self.view.dispatch({\n 'name': 'ap... | class List(BaseContainer):
"""
Bridges python and HTML lists. :class:`List` exposes an interface similar to
python lists and takes care of updating the corresponding HTML ``<ul>`` when the python object is updated.
"""
html_tag = "ul"
def __init__(self, id, classname=None, parent=None, **kwar... |
dalloriam/engel | engel/widgets/structure.py | List.remove_child | python | def remove_child(self, widget):
raw = list(filter(lambda x: x[0] == widget, self._items))
if raw:
itm, wrapped = raw[0]
self._items.remove(raw[0])
super(List, self).remove_child(wrapped)
else:
raise ValueError("Child not in list.") | Remove a widget from the list.
:param widget: Object inheriting :class:`~.widgets.base.BaseElement` | train | https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/widgets/structure.py#L83-L95 | [
"def remove_child(self, child):\n \"\"\"\n Remove a child widget from this widget.\n\n :param child: Object inheriting :class:`BaseElement`\n \"\"\"\n self.children.remove(child)\n child.parent = None\n\n if self.view and self.view.is_loaded:\n self.view.dispatch({\n 'name': '... | class List(BaseContainer):
"""
Bridges python and HTML lists. :class:`List` exposes an interface similar to
python lists and takes care of updating the corresponding HTML ``<ul>`` when the python object is updated.
"""
html_tag = "ul"
def __init__(self, id, classname=None, parent=None, **kwar... |
dalloriam/engel | engel/widgets/abstract.py | HeadLink.build | python | def build(self, link_type, path):
super(HeadLink, self).build()
self.target = path
self.link_type = link_type
self.autoclosing = True | :param link_type: Link type
:param target: Link target | train | https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/widgets/abstract.py#L30-L38 | [
"def build(self, **kwargs):\n \"\"\"\n Gets called before the widget gets attached to a view. Override this\n to define your widget's specific traits.\n \"\"\"\n pass\n"
] | class HeadLink(BaseElement):
"""
Widget representing links described in the ``<head>`` section of a typical HTML document.
This widget is used by the framework to generate links to stylesheets and auto-generated javascript files.
"""
html_tag = "link"
target = html_property('href')
"""
F... |
dalloriam/engel | engel/widgets/abstract.py | PageTitle.build | python | def build(self, text):
super(PageTitle, self).build()
self.content = text | :param text: Page title | train | https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/widgets/abstract.py#L49-L54 | [
"def build(self, **kwargs):\n \"\"\"\n Gets called before the widget gets attached to a view. Override this\n to define your widget's specific traits.\n \"\"\"\n pass\n"
] | class PageTitle(BaseElement):
"""
Widget representing the title of the page.
This widget is used by :meth:`~.application.View.render`.
"""
html_tag = "title"
|
dalloriam/engel | engel/widgets/abstract.py | Script.build | python | def build(self, js_path):
super(Script, self).build()
self.source = js_path | :param js_path: Javascript source code. | train | https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/widgets/abstract.py#L69-L74 | [
"def build(self, **kwargs):\n \"\"\"\n Gets called before the widget gets attached to a view. Override this\n to define your widget's specific traits.\n \"\"\"\n pass\n"
] | class Script(BaseElement):
"""
Widget representing a script element.
"""
html_tag = "script"
source = html_property('src')
"""
Location of the script
"""
|
dalloriam/engel | engel/application.py | Application.start | python | def start(self, on_exit_callback=None):
# TODO: Support params for services by mapping {servicename: {class,
# params}}?
for service in self.services.keys():
self.services[service] = self.services[service]()
self.server.start(on_exit_callback) | Start the Engel application by initializing all registered services and starting an Autobahn IOLoop.
:param on_exit_callback: Callback triggered on application exit | train | https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/application.py#L59-L70 | null | class Application(object):
"""
The ``Application`` abstract class represents the entirety of
an Engel application.
Your application should inherit from this class and redefine the
specifics, like Views, Services, and any additional logic
required by your project.
"""
base_title = None
... |
dalloriam/engel | engel/application.py | Application.register | python | def register(self, event, callback, selector=None):
self.processor.register(event, callback, selector) | Resister an event that you want to monitor.
:param event: Name of the event to monitor
:param callback: Callback function for when the event is received (Params: event, interface).
:param selector: `(Optional)` CSS selector for the element(s) you want to monitor. | train | https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/application.py#L72-L80 | [
"def register(self, event, callback, selector=None):\n logging.debug('Registering: ' + str(event))\n\n if selector:\n key = str(id(callback))\n else:\n key = '_'\n\n self.handlers[event][key].append(callback)\n\n if event not in ('init', 'load', 'close'):\n capture = False\n ... | class Application(object):
"""
The ``Application`` abstract class represents the entirety of
an Engel application.
Your application should inherit from this class and redefine the
specifics, like Views, Services, and any additional logic
required by your project.
"""
base_title = None
... |
dalloriam/engel | engel/application.py | Application.unregister | python | def unregister(self, event, callback, selector=None):
self.processor.unregister(event, callback, selector) | Unregisters an event that was being monitored.
:param event: Name of the event to monitor
:param callback: Callback function for when the event is received (Params: event, interface).
:param selector: `(Optional)` CSS selector for the element(s) you want to monitor | train | https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/application.py#L82-L90 | null | class Application(object):
"""
The ``Application`` abstract class represents the entirety of
an Engel application.
Your application should inherit from this class and redefine the
specifics, like Views, Services, and any additional logic
required by your project.
"""
base_title = None
... |
dalloriam/engel | engel/application.py | View.on | python | def on(self, event, callback, selector=None):
cbk = asyncio.coroutine(callback)
self._event_cache.append(
{'event': event, 'callback': cbk, 'selector': selector})
if self.is_loaded:
self.context.register(event, cbk, selector) | Wrapper around :meth:`~.application.Application.register`.
If :meth:`~.application.View.on` is called, for instance, during :meth:`~.application.View.build`,
the event handlers will be enqueued and registered when the view is loaded. Similarly,
if :meth:`~.application.View.on` is called once the... | train | https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/application.py#L177-L193 | null | class View(object):
title = None
"""
Title of the view.
"""
stylesheet = None
"""
Stylesheet of the view.
"""
libraries = []
"""
List of modules encapsulating the javascript libraries used by the view.
"""
def __init__(self, context):
"""
Constructor of the vi... |
dalloriam/engel | engel/application.py | View.unload | python | def unload(self):
self.is_loaded = False
for evt in self._event_cache:
self.context.unregister(
evt['event'], evt['callback'], evt['selector'])
self._event_cache = {} | Overridable method called when a view is unloaded (either on view change or on application shutdown).
Handles by default the unregistering of all event handlers previously registered by
the view. | train | https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/application.py#L210-L220 | null | class View(object):
title = None
"""
Title of the view.
"""
stylesheet = None
"""
Stylesheet of the view.
"""
libraries = []
"""
List of modules encapsulating the javascript libraries used by the view.
"""
def __init__(self, context):
"""
Constructor of the vi... |
dalloriam/engel | engel/libraries/bootstrap4/widgets/structure.py | ImageCard.build | python | def build(self, title, text, img_url):
super(ImageCard, self).build()
self.title = Title(id=self.id + "-title", text=title, classname="card-title", size=3, parent=self)
self.block = Panel(id=self.id + "-block", classname="card-block", parent=self)
self.image = Image(id=self.id + "-imag... | :param title: Title of the card
:param text: Description of the card
:param img_url: Image of the card | train | https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/libraries/bootstrap4/widgets/structure.py#L32-L44 | [
"def build(self):\n super(BaseCard, self).build()\n self.add_class('card')\n"
] | class ImageCard(BaseCard):
"""
Image card, with a title and short description.
"""
|
dalloriam/engel | engel/widgets/base.py | BaseContainer.add_child | python | def add_child(self, child):
self.children.append(child)
child.parent = self
if self.view and self.view.is_loaded:
self.view.dispatch({
'name': 'append',
'html': child.compile(),
'selector': '#' + str(self.id)
}) | Add a new child element to this widget.
:param child: Object inheriting :class:`BaseElement`. | train | https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/widgets/base.py#L166-L180 | [
"def compile(self):\n \"\"\"\n Generate the HTML representing this widget.\n\n :returns: HTML string representing this widget.\n \"\"\"\n return self._generate_html()\n",
"def compile(self):\n \"\"\"\n Recursively compile this widget as well as all of its children to HTML.\n\n :returns: HT... | class BaseContainer(BaseElement):
"""
Base class common to all widgets that can contain other widgets.
"""
@BaseElement.parent.setter
def parent(self, value):
self._set_parent(value)
if value is not None:
for child in self.children:
child.view = self.view... |
dalloriam/engel | engel/widgets/base.py | BaseContainer.remove_child | python | def remove_child(self, child):
self.children.remove(child)
child.parent = None
if self.view and self.view.is_loaded:
self.view.dispatch({
'name': 'remove',
'selector': '#' + child.id
}) | Remove a child widget from this widget.
:param child: Object inheriting :class:`BaseElement` | train | https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/widgets/base.py#L182-L195 | null | class BaseContainer(BaseElement):
"""
Base class common to all widgets that can contain other widgets.
"""
@BaseElement.parent.setter
def parent(self, value):
self._set_parent(value)
if value is not None:
for child in self.children:
child.view = self.view... |
dalloriam/engel | engel/widgets/base.py | BaseContainer.compile | python | def compile(self):
self.content = "".join(map(lambda x: x.compile(), self.children))
return self._generate_html() | Recursively compile this widget as well as all of its children to HTML.
:returns: HTML string representation of this widget. | train | https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/widgets/base.py#L220-L227 | [
"def _generate_html(self):\n if self.autoclosing:\n return \"<{0}{1}>\".format(self._get_html_tag(), self._format_attributes())\n else:\n return \"<{0}{1}>{2}</{0}>\".format(self._get_html_tag(), self._format_attributes(), self.content)\n"
] | class BaseContainer(BaseElement):
"""
Base class common to all widgets that can contain other widgets.
"""
@BaseElement.parent.setter
def parent(self, value):
self._set_parent(value)
if value is not None:
for child in self.children:
child.view = self.view... |
dalloriam/engel | engel/widgets/text.py | Title.build | python | def build(self, text, size=1):
super(Title, self).build()
self.content = text
self.size = size | :param text: Text of the widget
:param size: Size of the text (Higher size = smaller title) | train | https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/widgets/text.py#L11-L18 | [
"def build(self, **kwargs):\n \"\"\"\n Gets called before the widget gets attached to a view. Override this\n to define your widget's specific traits.\n \"\"\"\n pass\n"
] | class Title(BaseElement):
"""
Title widget analogous to the HTML <h{n}> elements.
"""
def _get_html_tag(self):
return "h{0}".format(self.size)
|
dalloriam/engel | engel/widgets/text.py | Paragraph.build | python | def build(self, text):
super(Paragraph, self).build()
self.content = text | :param text: Content of the paragraph | train | https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/widgets/text.py#L31-L36 | [
"def build(self, **kwargs):\n \"\"\"\n Gets called before the widget gets attached to a view. Override this\n to define your widget's specific traits.\n \"\"\"\n pass\n"
] | class Paragraph(BaseElement):
"""
Simple paragraph widget
"""
html_tag = "p"
|
dalloriam/engel | engel/widgets/text.py | Span.build | python | def build(self, text):
super(Span, self).build()
self.content = text | :param text: Content of the span | train | https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/widgets/text.py#L46-L51 | [
"def build(self, **kwargs):\n \"\"\"\n Gets called before the widget gets attached to a view. Override this\n to define your widget's specific traits.\n \"\"\"\n pass\n"
] | class Span(BaseElement):
"""
Simple span widget
"""
html_tag = "span"
|
dalloriam/engel | engel/widgets/text.py | TextLink.build | python | def build(self, text, url):
super(TextLink, self).build()
self.target = url
self.content = text | :param text: Text of the link
:param url: Target URL | train | https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/widgets/text.py#L66-L73 | [
"def build(self, **kwargs):\n \"\"\"\n Gets called before the widget gets attached to a view. Override this\n to define your widget's specific traits.\n \"\"\"\n pass\n"
] | class TextLink(BaseElement):
"""
Text widget linking to an external URL.
"""
html_tag = "a"
target = html_property('href')
"""
Target of the link
"""
|
JoaoFelipe/pyposast | pyposast/__init__.py | parse | python | def parse(code, filename='<unknown>', mode='exec', tree=None):
visitor = Visitor(code, filename, mode, tree=tree)
return visitor.tree | Parse the source into an AST node with PyPosAST.
Enhance nodes with positions
Arguments:
code -- code text
Keyword Arguments:
filename -- code path
mode -- execution mode (exec, eval, single)
tree -- current tree, if it was optimized | train | https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/__init__.py#L12-L27 | null | # Copyright (c) 2016 Universidade Federal Fluminense (UFF)
# This file is part of PyPosAST.
# Please, consult the license terms in the LICENSE file.
"""PyPosAST Module"""
from __future__ import (absolute_import, division)
import ast
from .visitor import LineProvenanceVisitor as Visitor, extract_code
from .cross_versio... |
JoaoFelipe/pyposast | pyposast/__init__.py | get_nodes | python | def get_nodes(code, desired_type, path="__main__", mode="exec", tree=None):
return _GetVisitor(parse(code, path, mode, tree), desired_type).result | Find all nodes of a given type
Arguments:
code -- code text
desired_type -- ast Node or tuple
Keyword Arguments:
path -- code path
mode -- execution mode (exec, eval, single)
tree -- current tree, if it was optimized | train | https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/__init__.py#L44-L58 | [
"def parse(code, filename='<unknown>', mode='exec', tree=None):\n \"\"\"Parse the source into an AST node with PyPosAST.\n Enhance nodes with positions\n\n\n Arguments:\n code -- code text\n\n\n Keyword Arguments:\n filename -- code path\n mode -- execution mode (exec, eval, single)\n tree -... | # Copyright (c) 2016 Universidade Federal Fluminense (UFF)
# This file is part of PyPosAST.
# Please, consult the license terms in the LICENSE file.
"""PyPosAST Module"""
from __future__ import (absolute_import, division)
import ast
from .visitor import LineProvenanceVisitor as Visitor, extract_code
from .cross_versio... |
JoaoFelipe/pyposast | pyposast/visitor.py | extract_code | python | def extract_code(lines, node, lstrip="", ljoin="\n", strip=""):
first_line, first_col = node.first_line - 1, node.first_col
last_line, last_col = node.last_line - 1, node.last_col
if first_line == last_line:
return lines[first_line][first_col:last_col].strip(strip)
result = []
# Add first l... | Get corresponding text in the code
Arguments:
lines -- code splitted by linebreak
node -- PyPosAST enhanced node
Keyword Arguments:
lstrip -- During extraction, strip lines with this arg (default="")
ljoin -- During extraction, join lines with this arg (default="\n")
strip -- After extra... | train | https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/visitor.py#L30-L58 | null | # Copyright (c) 2016 Universidade Federal Fluminense (UFF)
# This file is part of PyPosAST.
# Please, consult the license terms in the LICENSE file.
from __future__ import (absolute_import, division)
import ast
from copy import copy
from operator import sub
from functools import wraps
from .cross_version import on... |
JoaoFelipe/pyposast | pyposast/visitor.py | LineProvenanceVisitor.dnode | python | def dnode(self, node):
new_node = copy(node)
new_node.lineno += self.dline
new_node.col_offset += self.dcol
return new_node | Duplicate node and adjust it for deslocated line and column | train | https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/visitor.py#L119-L124 | null | class LineProvenanceVisitor(ast.NodeVisitor):
# pylint: disable=invalid-name, missing-docstring
# pylint: disable=too-many-instance-attributes, too-many-public-methods
# pylint: disable=no-self-use
def __init__(self, code, path, mode='exec', tree=None):
code = native_decode_source(code)
... |
JoaoFelipe/pyposast | pyposast/visitor.py | LineProvenanceVisitor.dposition | python | def dposition(self, node, dcol=0):
nnode = self.dnode(node)
return (nnode.lineno, nnode.col_offset + dcol) | Return deslocated line and column | train | https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/visitor.py#L126-L129 | [
"def dnode(self, node):\n \"\"\"Duplicate node and adjust it for deslocated line and column\"\"\"\n new_node = copy(node)\n new_node.lineno += self.dline\n new_node.col_offset += self.dcol\n return new_node\n"
] | class LineProvenanceVisitor(ast.NodeVisitor):
# pylint: disable=invalid-name, missing-docstring
# pylint: disable=too-many-instance-attributes, too-many-public-methods
# pylint: disable=no-self-use
def __init__(self, code, path, mode='exec', tree=None):
code = native_decode_source(code)
... |
JoaoFelipe/pyposast | pyposast/visitor.py | LineProvenanceVisitor.calculate_infixop | python | def calculate_infixop(self, node, previous, next_node):
previous_position = (previous.last_line, previous.last_col - 1)
position = (next_node.first_line, next_node.first_col + 1)
possible = []
for ch in OPERATORS[node.__class__]:
try:
pos = self.operators[ch].... | Create new node for infixop | train | https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/visitor.py#L131-L150 | null | class LineProvenanceVisitor(ast.NodeVisitor):
# pylint: disable=invalid-name, missing-docstring
# pylint: disable=too-many-instance-attributes, too-many-public-methods
# pylint: disable=no-self-use
def __init__(self, code, path, mode='exec', tree=None):
code = native_decode_source(code)
... |
JoaoFelipe/pyposast | pyposast/visitor.py | LineProvenanceVisitor.calculate_unaryop | python | def calculate_unaryop(self, node, next_node):
position = (next_node.first_line, next_node.first_col + 1)
possible = []
for ch in OPERATORS[node.__class__]:
try:
pos = self.operators[ch].find_previous(position)
if pos[1] < position:
... | Create new node for unaryop | train | https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/visitor.py#L152-L166 | null | class LineProvenanceVisitor(ast.NodeVisitor):
# pylint: disable=invalid-name, missing-docstring
# pylint: disable=too-many-instance-attributes, too-many-public-methods
# pylint: disable=no-self-use
def __init__(self, code, path, mode='exec', tree=None):
code = native_decode_source(code)
... |
JoaoFelipe/pyposast | pyposast/visitor.py | LineProvenanceVisitor.uid_something_colon | python | def uid_something_colon(self, node):
node.op_pos = [
NodeWithPosition(node.uid, (node.first_line, node.first_col))
]
position = (node.body[0].first_line, node.body[0].first_col)
last, first = self.operators[':'].find_previous(position)
node.op_pos.append(NodeWithPosit... | Creates op_pos for node from uid to colon | train | https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/visitor.py#L168-L176 | null | class LineProvenanceVisitor(ast.NodeVisitor):
# pylint: disable=invalid-name, missing-docstring
# pylint: disable=too-many-instance-attributes, too-many-public-methods
# pylint: disable=no-self-use
def __init__(self, code, path, mode='exec', tree=None):
code = native_decode_source(code)
... |
JoaoFelipe/pyposast | pyposast/visitor.py | LineProvenanceVisitor.optional_else | python | def optional_else(self, node, last):
if node.orelse:
min_first_max_last(node, node.orelse[-1])
if 'else' in self.operators:
position = (node.orelse[0].first_line, node.orelse[0].first_col)
_, efirst = self.operators['else'].find_previous(position)
... | Create op_pos for optional else | train | https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/visitor.py#L178-L187 | [
"def min_first_max_last(node, other):\n node.first_line, node.first_col = min(\n (node.first_line, node.first_col),\n (other.first_line, other.first_col))\n node.last_line, node.last_col = max(\n (node.last_line, node.last_col),\n (other.last_line, other.last_col))\n"
] | class LineProvenanceVisitor(ast.NodeVisitor):
# pylint: disable=invalid-name, missing-docstring
# pylint: disable=too-many-instance-attributes, too-many-public-methods
# pylint: disable=no-self-use
def __init__(self, code, path, mode='exec', tree=None):
code = native_decode_source(code)
... |
JoaoFelipe/pyposast | pyposast/visitor.py | LineProvenanceVisitor.comma_separated_list | python | def comma_separated_list(self, node, subnodes):
for item in subnodes:
position = (item.last_line, item.last_col)
first, last = find_next_comma(self.lcode, position)
if first: # comma exists
node.op_pos.append(NodeWithPosition(last, first)) | Process comma separated list | train | https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/visitor.py#L189-L195 | [
"def find_next_comma(code, position):\n \"\"\"Find next comman and return its first and last positions\"\"\"\n return find_next_character(code, position, ',')\n"
] | class LineProvenanceVisitor(ast.NodeVisitor):
# pylint: disable=invalid-name, missing-docstring
# pylint: disable=too-many-instance-attributes, too-many-public-methods
# pylint: disable=no-self-use
def __init__(self, code, path, mode='exec', tree=None):
code = native_decode_source(code)
... |
JoaoFelipe/pyposast | pyposast/visitor.py | LineProvenanceVisitor.visit_Constant | python | def visit_Constant(self, node):
nnode = self.dnode(node)
node.first_line, node.first_col = ast_pos(nnode, self.bytes_pos_to_utf8)
node.last_line = node.first_line
node.last_col = node.first_col + len(repr(node.value))
node.uid = (node.last_line, node.last_col) | PEP 511: Constants are generated by optimizers | train | https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/visitor.py#L245-L251 | [
"def ast_pos(node, bytes_pos_to_utf8):\n bytes_pos = bytes_pos_to_utf8[node.lineno - 1]\n return node.lineno, bytes_pos.get(node.col_offset)\n",
"def dnode(self, node):\n \"\"\"Duplicate node and adjust it for deslocated line and column\"\"\"\n new_node = copy(node)\n new_node.lineno += self.dline\... | class LineProvenanceVisitor(ast.NodeVisitor):
# pylint: disable=invalid-name, missing-docstring
# pylint: disable=too-many-instance-attributes, too-many-public-methods
# pylint: disable=no-self-use
def __init__(self, code, path, mode='exec', tree=None):
code = native_decode_source(code)
... |
JoaoFelipe/pyposast | pyposast/visitor.py | LineProvenanceVisitor.visit_Repr | python | def visit_Repr(self, node):
position = (node.value.last_line, node.value.last_col + 1)
r_set_pos(node, *self.operators['`'].find_next(position))
position = (node.value.first_line, node.value.first_col + 1)
first = self.operators['`'].find_previous(position)[1]
node.first_line, no... | Python 2 | train | https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/visitor.py#L396-L406 | [
"def r_set_pos(node, last, first):\n node.first_line, node.first_col = first\n node.uid = node.last_line, node.last_col = last\n"
] | class LineProvenanceVisitor(ast.NodeVisitor):
# pylint: disable=invalid-name, missing-docstring
# pylint: disable=too-many-instance-attributes, too-many-public-methods
# pylint: disable=no-self-use
def __init__(self, code, path, mode='exec', tree=None):
code = native_decode_source(code)
... |
JoaoFelipe/pyposast | pyposast/visitor.py | LineProvenanceVisitor.find_next_comma | python | def find_next_comma(self, node, sub):
position = (sub.last_line, sub.last_col)
first, last = find_next_comma(self.lcode, position)
if first: # comma exists
node.op_pos.append(NodeWithPosition(last, first)) | Find comma after sub andd add NodeWithPosition in node | train | https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/visitor.py#L586-L591 | [
"def find_next_comma(code, position):\n \"\"\"Find next comman and return its first and last positions\"\"\"\n return find_next_character(code, position, ',')\n"
] | class LineProvenanceVisitor(ast.NodeVisitor):
# pylint: disable=invalid-name, missing-docstring
# pylint: disable=too-many-instance-attributes, too-many-public-methods
# pylint: disable=no-self-use
def __init__(self, code, path, mode='exec', tree=None):
code = native_decode_source(code)
... |
JoaoFelipe/pyposast | pyposast/visitor.py | LineProvenanceVisitor.visit_Starred | python | def visit_Starred(self, node):
position = (node.value.first_line, node.value.first_col + 1)
r_set_pos(node, *self.operators['*'].find_previous(position))
last = node.value
node.last_line, node.last_col = last.last_line, last.last_col
node.op_pos = [
NodeWithPosition(n... | Python 3 | train | https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/visitor.py#L706-L714 | [
"def dec_tuple(tup):\n return (tup[0], tup[1] - 1)\n",
"def r_set_pos(node, last, first):\n node.first_line, node.first_col = first\n node.uid = node.last_line, node.last_col = last\n"
] | class LineProvenanceVisitor(ast.NodeVisitor):
# pylint: disable=invalid-name, missing-docstring
# pylint: disable=too-many-instance-attributes, too-many-public-methods
# pylint: disable=no-self-use
def __init__(self, code, path, mode='exec', tree=None):
code = native_decode_source(code)
... |
JoaoFelipe/pyposast | pyposast/visitor.py | LineProvenanceVisitor.visit_NameConstant | python | def visit_NameConstant(self, node):
nnode = self.dnode(node)
copy_from_lineno_col_offset(
nnode, str(node.value), self.bytes_pos_to_utf8, to=node) | Python 3 | train | https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/visitor.py#L717-L721 | [
"def copy_from_lineno_col_offset(node, identifier, bytes_pos_to_utf8, to=None):\n if to is None:\n to = node\n to.first_line, to.first_col = ast_pos(node, bytes_pos_to_utf8)\n to.last_line = node.lineno\n len_id = len(identifier)\n to.last_col = to.first_col + len_id\n to.uid = (to.last_lin... | class LineProvenanceVisitor(ast.NodeVisitor):
# pylint: disable=invalid-name, missing-docstring
# pylint: disable=too-many-instance-attributes, too-many-public-methods
# pylint: disable=no-self-use
def __init__(self, code, path, mode='exec', tree=None):
code = native_decode_source(code)
... |
JoaoFelipe/pyposast | pyposast/visitor.py | LineProvenanceVisitor.visit_Print | python | def visit_Print(self, node):
start_by_keyword(node, self.operators['print'], self.bytes_pos_to_utf8)
node.op_pos = [
NodeWithPosition(node.uid, (node.first_line, node.first_col))
]
subnodes = []
if node.dest:
min_first_max_last(node, node.dest)
... | Python 2 | train | https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/visitor.py#L1054-L1071 | [
"def min_first_max_last(node, other):\n node.first_line, node.first_col = min(\n (node.first_line, node.first_col),\n (other.first_line, other.first_col))\n node.last_line, node.last_col = max(\n (node.last_line, node.last_col),\n (other.last_line, other.last_col))\n",
"def start... | class LineProvenanceVisitor(ast.NodeVisitor):
# pylint: disable=invalid-name, missing-docstring
# pylint: disable=too-many-instance-attributes, too-many-public-methods
# pylint: disable=no-self-use
def __init__(self, code, path, mode='exec', tree=None):
code = native_decode_source(code)
... |
JoaoFelipe/pyposast | setup.py | get_version | python | def get_version():
proc = subprocess.Popen(
("git", "describe", "--tag", "--always"),
stdout=subprocess.PIPE, stderr=subprocess.STDOUT
)
output, _ = proc.communicate()
result = output.decode("utf-8").strip()
if proc.returncode != 0:
sys.stderr.write(
">>> Git Des... | Use git describe to get version from tag | train | https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/setup.py#L6-L28 | null | #!/usr/bin/env python
import subprocess
import sys
from setuptools import setup, find_packages
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except (IOError, ImportError):
sys.stderr.write(
">>> Please verify the pypandoc installation.\n"
)
long_description =... |
JoaoFelipe/pyposast | pyposast/utils.py | find_next_character | python | def find_next_character(code, position, char):
end = LineCol(code, *position)
while not end.eof and end.char() in WHITESPACE:
end.inc()
if not end.eof and end.char() == char:
return end.tuple(), inc_tuple(end.tuple())
return None, None | Find next char and return its first and last positions | train | https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/utils.py#L132-L140 | [
"def inc_tuple(tup):\n return (tup[0], tup[1] + 1)\n",
"def char(self):\n try:\n return self.code[self.line - 1][self.col]\n except IndexError as e:\n raise IndexError(\n str(e) +\n (\": self.code[self.line - 1][self.col] with \\n\"\n \"self.line = {}; self... | # Copyright (c) 2015 Universidade Federal Fluminense (UFF)
# This file is part of PyPosAST.
# Please, consult the license terms in the LICENSE file.
from __future__ import (absolute_import, division)
from .constants import WHITESPACE
def pairwise(iterable):
it = iter(iterable)
a = next(it)
for b in it:... |
JoaoFelipe/pyposast | pyposast/cross_version.py | native_decode_source | python | def native_decode_source(text):
if ((only_python3 and isinstance(text, bytes))
or (only_python2 and isinstance(text, str))):
text = decode_source_to_unicode(text)
if only_python2:
return text.encode('ascii', 'replace')
return text | Use codec specified in file to decode to unicode
Then, encode unicode to native str:
Python 2: bytes
Python 3: unicode | train | https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/cross_version.py#L136-L147 | [
"def decode_source_to_unicode(source_bytes):\n encoding = detect_encoding(readlines(source_bytes.splitlines(True)))\n return source_bytes.decode(encoding[0], 'replace')\n"
] | # Copyright (c) 2016 Universidade Federal Fluminense (UFF)
# This file is part of PyPosAST.
# Please, consult the license terms in the LICENSE file.
import sys
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
class SelectVersion(object):
def __init__(self, compare_func):
... |
anlutro/russell | russell/content.py | Entry.from_string | python | def from_string(cls, contents, **kwargs):
lines = contents.splitlines()
title = None
description = None
line = lines.pop(0)
while line != '':
if not title and line.startswith('#'):
title = line[1:].strip()
elif line.startswith('title:'):
title = line[6:].strip()
elif line.startswith('descrip... | Given a markdown string, create an Entry object.
Usually subclasses will want to customize the parts of the markdown
where you provide values for attributes like public - this can be done
by overriding the process_meta method. | train | https://github.com/anlutro/russell/blob/6e4a95929f031926d3acd5d9e6c9ca7bb896b1b5/russell/content.py#L107-L148 | [
"def render_markdown(md):\n\textensions = ['markdown.extensions.fenced_code']\n\treturn markdown.markdown(md, extensions=extensions)\n",
"def _get_excerpt(body):\n\texcerpt_parts = []\n\t# iterate through lines until we find an empty line, which would indicate\n\t# two newlines in a row\n\tfor line in body.splitl... | class Entry(Content):
"""
Abstract class for text content.
"""
def __init__(self, title, body, slug=None, subtitle=None, description=None, public=True):
"""
Constructor.
Args:
title (str): Title.
body (str): Markdown body of the entry.
slug (str): Optional slug for the entry. If not provided, sulg... |
anlutro/russell | russell/content.py | Entry.process_meta | python | def process_meta(cls, line, kwargs):
if line.startswith('slug:'):
kwargs['slug'] = line[5:].strip()
elif line.startswith('public:'):
try:
kwargs['public'] = _str_to_bool(line[7:])
except ValueError:
LOG.warning('invalid boolean value for public', exc_info=True)
elif line.startswith('private:'):... | Process a line of metadata found in the markdown.
Lines are usually in the format of "key: value".
Modify the kwargs dict in order to change or add new kwargs that should
be passed to the class's constructor. | train | https://github.com/anlutro/russell/blob/6e4a95929f031926d3acd5d9e6c9ca7bb896b1b5/russell/content.py#L151-L173 | null | class Entry(Content):
"""
Abstract class for text content.
"""
def __init__(self, title, body, slug=None, subtitle=None, description=None, public=True):
"""
Constructor.
Args:
title (str): Title.
body (str): Markdown body of the entry.
slug (str): Optional slug for the entry. If not provided, sulg... |
anlutro/russell | russell/content.py | Entry.from_file | python | def from_file(cls, path, **kwargs):
LOG.debug('creating %s from "%s"', cls, path)
# the filename will be the default slug - can be overridden later
kwargs['slug'] = os.path.splitext(os.path.basename(path))[0]
# TODO: ideally this should be part of the Post class.
# if a pubdate isn't explicitly passed, get ... | Given a markdown file, get an Entry object. | train | https://github.com/anlutro/russell/blob/6e4a95929f031926d3acd5d9e6c9ca7bb896b1b5/russell/content.py#L176-L201 | null | class Entry(Content):
"""
Abstract class for text content.
"""
def __init__(self, title, body, slug=None, subtitle=None, description=None, public=True):
"""
Constructor.
Args:
title (str): Title.
body (str): Markdown body of the entry.
slug (str): Optional slug for the entry. If not provided, sulg... |
anlutro/russell | russell/content.py | Post.make_tag | python | def make_tag(cls, tag_name):
if cls.cm:
return cls.cm.make_tag(tag_name)
return Tag(tag_name.strip()) | Make a Tag object from a tag name. Registers it with the content manager
if possible. | train | https://github.com/anlutro/russell/blob/6e4a95929f031926d3acd5d9e6c9ca7bb896b1b5/russell/content.py#L244-L251 | null | class Post(Entry):
def __init__(self, *args, pubdate=None, excerpt=None, tags=None, allow_comments=True, **kwargs):
"""
Constructor. Also see Entry.__init__.
Args:
pubdate (datetime): When the post was published.
excerpt (str): An excerpt of the post body.
tags (list): A list of Tag objects associat... |
anlutro/russell | russell/engine.py | make_link | python | def make_link(title, url, blank=False):
attrs = 'href="%s"' % url
if blank:
attrs += ' target="_blank" rel="noopener noreferrer"'
return '<a %s>%s</a>' % (attrs, title) | Make a HTML link out of an URL.
Args:
title (str): Text to show for the link.
url (str): URL the link will point to.
blank (bool): If True, appends target=_blank, noopener and noreferrer to
the <a> element. Defaults to False. | train | https://github.com/anlutro/russell/blob/6e4a95929f031926d3acd5d9e6c9ca7bb896b1b5/russell/engine.py#L27-L40 | null | from datetime import datetime
import hashlib
import logging
import os
import os.path
import shutil
import jinja2
import russell.content
import russell.feed
import russell.sitemap
LOG = logging.getLogger(__name__)
def _listfiles(root_dir):
results = set()
for root, _, files in os.walk(root_dir):
for file in fi... |
anlutro/russell | russell/engine.py | BlogEngine.get_asset_url | python | def get_asset_url(self, path):
url = self.root_url + '/assets/' + path
if path in self.asset_hash:
url += '?' + self.asset_hash[path]
return url | Get the URL of an asset. If asset hashes are added and one exists for
the path, it will be appended as a query string.
Args:
path (str): Path to the file, relative to your "assets" directory. | train | https://github.com/anlutro/russell/blob/6e4a95929f031926d3acd5d9e6c9ca7bb896b1b5/russell/engine.py#L85-L96 | null | class BlogEngine:
"""
The main instance that contains blog configuration and content, as well as
generating end results.
"""
def __init__(self, root_path, root_url, site_title, site_desc=None):
"""
Constructor.
Args:
root_path (str): Full path to the directory which contains the posts,
pages, temp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.