_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q15000 | pack_mac | train | def pack_mac(macstr):
"""Converts a mac address given in colon delimited notation to a
six byte string in network byte order.
>>> pack_mac("30:31:32:33:34:35") == b'012345'
True
>>> pack_mac("bad")
Traceback (most recent call last):
...
ValueError: given mac addresses has an invalid number of colons
@type m... | python | {
"resource": ""
} |
q15001 | unpack_mac | train | def unpack_mac(sixbytes):
"""Converts a mac address given in a six byte string in network
byte order to a string in colon delimited notation.
>>> unpack_mac(b"012345")
'30:31:32:33:34:35'
>>> unpack_mac(b"bad")
Traceback (most recent call last):
...
ValueError: given buffer is not exactly six bytes long
@typ... | python | {
"resource": ""
} |
q15002 | OmapiStartupMessage.validate | train | def validate(self):
"""Checks whether this OmapiStartupMessage matches the implementation.
@raises OmapiError:
"""
if self.implemented_protocol_version != self.protocol_version:
raise OmapiError("protocol mismatch")
if self.implemented_header_size != self.header_size:
raise OmapiError("header size misma... | python | {
"resource": ""
} |
q15003 | OmapiStartupMessage.serialize | train | def serialize(self, outbuffer):
"""Serialize this OmapiStartupMessage to the given outbuffer.
@type outbuffer: OutBuffer
"""
outbuffer.add_net32int(self.protocol_version)
outbuffer.add_net32int(self.header_size) | python | {
"resource": ""
} |
q15004 | OmapiMessage.sign | train | def sign(self, authenticator):
"""Sign this OMAPI message.
@type authenticator: OmapiAuthenticatorBase
"""
self.authid = authenticator.authid
self.signature = b"\0" * authenticator.authlen # provide authlen
self.signature = authenticator.sign(self.as_string(forsigning=True))
assert len(self.signature) ==... | python | {
"resource": ""
} |
q15005 | OmapiMessage.verify | train | def verify(self, authenticators):
"""Verify this OMAPI message.
>>> a1 = OmapiHMACMD5Authenticator(b"egg", b"spam")
>>> a2 = OmapiHMACMD5Authenticator(b"egg", b"tomatoes")
>>> a1.authid = a2.authid = 5
>>> m = OmapiMessage.open(b"host")
>>> m.verify({a1.authid: a1})
False
>>> m.sign(a1)
>>> m.verify(... | python | {
"resource": ""
} |
q15006 | OmapiMessage.open | train | def open(cls, typename):
"""Create an OMAPI open message with given typename.
@type typename: bytes
@rtype: OmapiMessage
"""
return cls(opcode=OMAPI_OP_OPEN, message=[(b"type", typename)], tid=-1) | python | {
"resource": ""
} |
q15007 | InBuffer.parse_startup_message | train | def parse_startup_message(self):
"""results in an OmapiStartupMessage
>>> d = b"\\0\\0\\0\\x64\\0\\0\\0\\x18"
>>> next(InBuffer(d).parse_startup_message()).validate()
"""
return parse_map(lambda args: OmapiStartupMessage(*args), parse_chain(self.parse_net32int, lambda _: self.parse_net32int())) | python | {
"resource": ""
} |
q15008 | InBuffer.parse_message | train | def parse_message(self):
"""results in an OmapiMessage"""
parser = parse_chain(self.parse_net32int, # authid
lambda *_: self.parse_net32int(), # authlen
lambda *_: self.parse_net32int(), # opcode
lambda *_: self.parse_net32int(), # handle
lambda *_: self.parse_net32int(), # tid
... | python | {
"resource": ""
} |
q15009 | TCPClientTransport.fill_inbuffer | train | def fill_inbuffer(self):
"""Read bytes from the connection and hand them to the protocol.
@raises OmapiError:
@raises socket.error:
"""
if not self.connection:
raise OmapiError("not connected")
try:
data = self.connection.recv(2048)
except socket.error:
self.close()
raise
if not data:
sel... | python | {
"resource": ""
} |
q15010 | TCPClientTransport.write | train | def write(self, data):
"""Send all of data to the connection.
@type data: bytes
@raises socket.error:
"""
try:
self.connection.sendall(data)
except socket.error:
self.close()
raise | python | {
"resource": ""
} |
q15011 | OmapiProtocol.send_message | train | def send_message(self, message, sign=True):
"""Send the given message to the connection.
@type message: OmapiMessage
@param sign: whether the message needs to be signed
@raises OmapiError:
@raises socket.error:
"""
if sign:
message.sign(self.authenticators[self.defauth])
logger.debug("sending %s", L... | python | {
"resource": ""
} |
q15012 | Omapi.receive_message | train | def receive_message(self):
"""Read the next message from the connection.
@rtype: OmapiMessage
@raises OmapiError:
@raises socket.error:
"""
while not self.recv_message_queue:
self.transport.fill_inbuffer()
message = self.recv_message_queue.pop(0)
assert message is not None
if not message.verify(sel... | python | {
"resource": ""
} |
q15013 | Omapi.receive_response | train | def receive_response(self, message, insecure=False):
"""Read the response for the given message.
@type message: OmapiMessage
@type insecure: bool
@param insecure: avoid an OmapiError about a wrong authenticator
@rtype: OmapiMessage
@raises OmapiError:
@raises socket.error:
"""
response = self.receive_... | python | {
"resource": ""
} |
q15014 | Omapi.send_message | train | def send_message(self, message, sign=True):
"""Sends the given message to the connection.
@type message: OmapiMessage
@type sign: bool
@param sign: whether the message needs to be signed
@raises OmapiError:
@raises socket.error:
"""
self.check_connected()
self.protocol.send_message(message, sign) | python | {
"resource": ""
} |
q15015 | Omapi.lookup_ip_host | train | def lookup_ip_host(self, mac):
"""Lookup a host object with with given mac address.
@type mac: str
@raises ValueError:
@raises OmapiError:
@raises OmapiErrorNotFound: if no lease object with the given mac could be found
@raises OmapiErrorAttributeNotFound: if lease could be found, but objects lacks a ip
... | python | {
"resource": ""
} |
q15016 | Omapi.lookup_ip | train | def lookup_ip(self, mac):
"""Look for a lease object with given mac address and return the
assigned ip address.
@type mac: str
@rtype: str or None
@raises ValueError:
@raises OmapiError:
@raises OmapiErrorNotFound: if no lease object with the given mac could be found
@raises OmapiErrorAttributeNotFound... | python | {
"resource": ""
} |
q15017 | Omapi.lookup_mac | train | def lookup_mac(self, ip):
"""Look up a lease object with given ip address and return the
associated mac address.
@type ip: str
@rtype: str or None
@raises ValueError:
@raises OmapiError:
@raises OmapiErrorNotFound: if no lease object with the given ip could be found
@raises OmapiErrorAttributeNotFound:... | python | {
"resource": ""
} |
q15018 | Omapi.lookup_host | train | def lookup_host(self, name):
"""Look for a host object with given name and return the
name, mac, and ip address
@type name: str
@rtype: dict or None
@raises ValueError:
@raises OmapiError:
@raises OmapiErrorNotFound: if no host object with the given name could be found
@raises OmapiErrorAttributeNotFou... | python | {
"resource": ""
} |
q15019 | Omapi.lookup_host_host | train | def lookup_host_host(self, mac):
"""Look for a host object with given mac address and return the
name, mac, and ip address
@type mac: str
@rtype: dict or None
@raises ValueError:
@raises OmapiError:
@raises OmapiErrorNotFound: if no host object with the given mac address could be found
@raises OmapiErr... | python | {
"resource": ""
} |
q15020 | Omapi.lookup_hostname | train | def lookup_hostname(self, ip):
"""Look up a lease object with given ip address and return the associated client hostname.
@type ip: str
@rtype: str or None
@raises ValueError:
@raises OmapiError:
@raises OmapiErrorNotFound: if no lease object with the given ip address could be found
@raises OmapiErrorAtt... | python | {
"resource": ""
} |
q15021 | Omapi.__lookup | train | def __lookup(self, ltype, **kwargs):
"""Generic Lookup function
@type ltype: str
@type rvalues: list
@type ip: str
@type mac: str
@type name: str
@rtype: dict or str (if len(rvalues) == 1) or None
@raises ValueError:
@raises OmapiError:
@raises OmapiErrorNotFound: if no host object with the given n... | python | {
"resource": ""
} |
q15022 | Omapi.add_host | train | def add_host(self, ip, mac):
"""Create a host object with given ip address and and mac address.
@type ip: str
@type mac: str
@raises ValueError:
@raises OmapiError:
@raises socket.error:
"""
msg = OmapiMessage.open(b"host")
msg.message.append((b"create", struct.pack("!I", 1)))
msg.message.append((b... | python | {
"resource": ""
} |
q15023 | Omapi.add_host_supersede_name | train | def add_host_supersede_name(self, ip, mac, name): # pylint:disable=E0213
"""Add a host with a fixed-address and override its hostname with the given name.
@type self: Omapi
@type ip: str
@type mac: str
@type name: str
@raises ValueError:
@raises OmapiError:
@raises socket.error:
"""
msg = OmapiMess... | python | {
"resource": ""
} |
q15024 | Omapi.add_host_supersede | train | def add_host_supersede(self, ip, mac, name, hostname=None, router=None, domain=None): # pylint:disable=too-many-arguments
"""Create a host object with given ip, mac, name, hostname, router and
domain. hostname, router and domain are optional arguments.
@type ip: str
@type mac: str
@type name: str
@type ho... | python | {
"resource": ""
} |
q15025 | Omapi.del_host | train | def del_host(self, mac):
"""Delete a host object with with given mac address.
@type mac: str
@raises ValueError:
@raises OmapiError:
@raises OmapiErrorNotFound: if no lease object with the given
mac address could be found
@raises socket.error:
"""
msg = OmapiMessage.open(b"host")
msg.obj.append((... | python | {
"resource": ""
} |
q15026 | Omapi.add_group | train | def add_group(self, groupname, statements):
"""
Adds a group
@type groupname: bytes
@type statements: str
"""
msg = OmapiMessage.open(b"group")
msg.message.append(("create", struct.pack("!I", 1)))
msg.obj.append(("name", groupname))
msg.obj.append(("statements", statements))
response = self.query_se... | python | {
"resource": ""
} |
q15027 | Omapi.add_host_with_group | train | def add_host_with_group(self, ip, mac, groupname):
"""
Adds a host with given ip and mac in a group named groupname
@type ip: str
@type mac: str
@type groupname: str
"""
msg = OmapiMessage.open(b"host")
msg.message.append(("create", struct.pack("!I", 1)))
msg.message.append(("exclusive", struct.pack("... | python | {
"resource": ""
} |
q15028 | Omapi.change_group | train | def change_group(self, name, group):
"""Change the group of a host given the name of the host.
@type name: str
@type group: str
"""
m1 = OmapiMessage.open(b"host")
m1.update_object(dict(name=name))
r1 = self.query_server(m1)
if r1.opcode != OMAPI_OP_UPDATE:
raise OmapiError("opening host %s failed" %... | python | {
"resource": ""
} |
q15029 | Resource._query | train | def _query(cls, **kwargs):
"""
Generic query implementation that is used
by the resources.
"""
from sevenbridges.models.link import Link
from sevenbridges.meta.collection import Collection
api = kwargs.pop('api', cls._API)
url = kwargs.pop('url')
... | python | {
"resource": ""
} |
q15030 | Resource.delete | train | def delete(self):
"""
Deletes the resource on the server.
"""
if 'delete' in self._URL:
extra = {'resource': self.__class__.__name__, 'query': {
'id': self.id}}
logger.info("Deleting {} resource.".format(self), extra=extra)
self._api.de... | python | {
"resource": ""
} |
q15031 | Resource.reload | train | def reload(self):
"""
Refreshes the resource with the data from the server.
"""
try:
if hasattr(self, 'href'):
data = self._api.get(self.href, append_base=False).json()
resource = self.__class__(api=self._api, **data)
elif hasattr(s... | python | {
"resource": ""
} |
q15032 | RecordConverter.convert | train | def convert(cls, record):
"""
Converts a single dictionary or list of dictionaries into converted list of dictionaries.
"""
if isinstance(record, list):
return [cls._convert(r) for r in record]
else:
return [cls._convert(record)] | python | {
"resource": ""
} |
q15033 | RecordConverter._convert_internal | train | def _convert_internal(cls, record):
"""
Converts a single dictionary into converted dictionary or list of dictionaries into converted
list of dictionaries. Used while passing dictionaries to another converter.
"""
if isinstance(record, list):
return [cls._convert(r) f... | python | {
"resource": ""
} |
q15034 | RecordConverter._convert | train | def _convert(cls, record):
"""
Core method of the converter. Converts a single dictionary into another dictionary.
"""
if not record:
return {}
converted_dict = {}
for field in cls.conversion:
key = field[0]
if len(field) >= 2 and fiel... | python | {
"resource": ""
} |
q15035 | create_room | train | def create_room(room):
"""Creates a MUC room on the XMPP server."""
if room.custom_server:
return
def _create_room(xmpp):
muc = xmpp.plugin['xep_0045']
muc.joinMUC(room.jid, xmpp.requested_jid.user)
muc.configureRoom(room.jid, _set_form_values(xmpp, room))
current_plug... | python | {
"resource": ""
} |
q15036 | update_room | train | def update_room(room):
"""Updates a MUC room on the XMPP server."""
if room.custom_server:
return
def _update_room(xmpp):
muc = xmpp.plugin['xep_0045']
muc.joinMUC(room.jid, xmpp.requested_jid.user)
muc.configureRoom(room.jid, _set_form_values(xmpp, room, muc.getRoomConfig(... | python | {
"resource": ""
} |
q15037 | delete_room | train | def delete_room(room, reason=''):
"""Deletes a MUC room from the XMPP server."""
if room.custom_server:
return
def _delete_room(xmpp):
muc = xmpp.plugin['xep_0045']
muc.destroy(room.jid, reason=reason)
current_plugin.logger.info('Deleting room %s', room.jid)
_execute_xmpp(... | python | {
"resource": ""
} |
q15038 | get_room_config | train | def get_room_config(jid):
"""Retrieves basic data of a MUC room from the XMPP server.
:return: dict containing name, description and password of the room
"""
mapping = {
'name': 'muc#roomconfig_roomname',
'description': 'muc#roomconfig_roomdesc',
'password': 'muc#roomconfig_roo... | python | {
"resource": ""
} |
q15039 | room_exists | train | def room_exists(jid):
"""Checks if a MUC room exists on the server."""
def _room_exists(xmpp):
disco = xmpp.plugin['xep_0030']
try:
disco.get_info(jid)
except IqError as e:
if e.condition == 'item-not-found':
return False
raise
... | python | {
"resource": ""
} |
q15040 | sanitize_jid | train | def sanitize_jid(s):
"""Generates a valid JID node identifier from a string"""
jid = unicode_to_ascii(s).lower()
jid = WHITESPACE.sub('-', jid)
jid = INVALID_JID_CHARS.sub('', jid)
return jid.strip()[:256] | python | {
"resource": ""
} |
q15041 | generate_jid | train | def generate_jid(name, append_date=None):
"""Generates a v alid JID based on the room name.
:param append_date: appends the given date to the JID
"""
if not append_date:
return sanitize_jid(name)
return '{}-{}'.format(sanitize_jid(name), append_date.strftime('%Y-%m-%d')) | python | {
"resource": ""
} |
q15042 | _execute_xmpp | train | def _execute_xmpp(connected_callback):
"""Connects to the XMPP server and executes custom code
:param connected_callback: function to execute after connecting
:return: return value of the callback
"""
from indico_chat.plugin import ChatPlugin
check_config()
jid = ChatPlugin.settings.get('b... | python | {
"resource": ""
} |
q15043 | retrieve_logs | train | def retrieve_logs(room, start_date=None, end_date=None):
"""Retrieves chat logs
:param room: the `Chatroom`
:param start_date: the earliest date to get logs for
:param end_date: the latest date to get logs for
:return: logs in html format
"""
from indico_chat.plugin import ChatPlugin
b... | python | {
"resource": ""
} |
q15044 | delete_logs | train | def delete_logs(room):
"""Deletes chat logs"""
from indico_chat.plugin import ChatPlugin
base_url = ChatPlugin.settings.get('log_url')
if not base_url or room.custom_server:
return
try:
response = requests.get(posixpath.join(base_url, 'delete'), params={'cr': room.jid}).json()
... | python | {
"resource": ""
} |
q15045 | Project.create_task | train | def create_task(self, name, app, revision=None, batch_input=None,
batch_by=None, inputs=None, description=None, run=False,
disable_batch=False, interruptible=True,
execution_settings=None):
"""
Creates a task for this project.
:param n... | python | {
"resource": ""
} |
q15046 | validate_business | train | def validate_business(form, field):
"""Valiates a PayPal business string.
It can either be an email address or a paypal business account ID.
"""
if not is_valid_mail(field.data, multi=False) and not re.match(r'^[a-zA-Z0-9]{13}$', field.data):
raise ValidationError(_('Invalid email address / pay... | python | {
"resource": ""
} |
q15047 | DPartedFile.submit | train | def submit(self):
"""
Partitions the file into chunks and submits them into group of 4
for download on the api download pool.
"""
futures = []
while self.submitted < 4 and not self.done():
part = self.parts.pop(0)
futures.append(
se... | python | {
"resource": ""
} |
q15048 | DPartedFile.get_parts | train | def get_parts(self):
"""
Partitions the file and saves the part information in memory.
"""
parts = []
start_b = 0
end_byte = start_b + PartSize.DOWNLOAD_MINIMUM_PART_SIZE - 1
for i in range(self.total):
parts.append([start_b, end_byte])
sta... | python | {
"resource": ""
} |
q15049 | LiveSyncBackendBase.run | train | def run(self):
"""Runs the livesync export"""
if self.uploader is None: # pragma: no cover
raise NotImplementedError
records = self.fetch_records()
uploader = self.uploader(self)
LiveSyncPlugin.logger.info('Uploading %d records', len(records))
uploader.run(r... | python | {
"resource": ""
} |
q15050 | LiveSyncBackendBase.run_initial_export | train | def run_initial_export(self, events):
"""Runs the initial export.
This process is expected to take a very long time.
:param events: iterable of all events in this indico instance
"""
if self.uploader is None: # pragma: no cover
raise NotImplementedError
up... | python | {
"resource": ""
} |
q15051 | check_config | train | def check_config(quiet=False):
"""Checks if all required config options are set
:param quiet: if True, return the result as a bool, otherwise
raise `IndicoError` if any setting is missing
"""
from indico_chat.plugin import ChatPlugin
settings = ChatPlugin.settings.get_all()
mi... | python | {
"resource": ""
} |
q15052 | is_chat_admin | train | def is_chat_admin(user):
"""Checks if a user is a chat admin"""
from indico_chat.plugin import ChatPlugin
return ChatPlugin.settings.acls.contains_user('admins', user) | python | {
"resource": ""
} |
q15053 | inplace_reload | train | def inplace_reload(method):
"""
Executes the wrapped function and reloads the object
with data returned from the server.
"""
# noinspection PyProtectedMember
def wrapped(obj, *args, **kwargs):
in_place = True if kwargs.get('inplace') in (True, None) else False
api_object = metho... | python | {
"resource": ""
} |
q15054 | retry_on_excs | train | def retry_on_excs(excs, retry_count=3, delay=5):
"""Retry decorator used to retry callables on for specific exceptions.
:param excs: Exceptions tuple.
:param retry_count: Retry count.
:param delay: Delay in seconds between retries.
:return: Wrapped function object.
"""
def wrapper(f):
... | python | {
"resource": ""
} |
q15055 | retry | train | def retry(retry_count):
"""
Retry decorator used during file upload and download.
"""
def func(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
for backoff in range(retry_count):
try:
return f(*args, **kwargs)
except E... | python | {
"resource": ""
} |
q15056 | check_for_error | train | def check_for_error(func):
"""
Executes the wrapped function and inspects the response object
for specific errors.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
response = func(*args, **kwargs)
status_code = response.status_code
if sta... | python | {
"resource": ""
} |
q15057 | ReportBase.get | train | def get(cls, *args, **kwargs):
"""Create and return a serializable Report object, retrieved from cache if possible"""
from indico_piwik.plugin import PiwikPlugin
if not PiwikPlugin.settings.get('cache_enabled'):
return cls(*args, **kwargs).to_serializable()
cache = Generic... | python | {
"resource": ""
} |
q15058 | ReportBase._init_date_range | train | def _init_date_range(self, start_date=None, end_date=None):
"""Set date range defaults if no dates are passed"""
self.end_date = end_date
self.start_date = start_date
if self.end_date is None:
today = now_utc().date()
end_date = self.event.end_dt.date()
... | python | {
"resource": ""
} |
q15059 | ReportGeneral._build_report | train | def _build_report(self):
"""Build the report by performing queries to Piwik"""
self.metrics = {}
queries = {'visits': PiwikQueryReportEventMetricVisits(**self.params),
'unique_visits': PiwikQueryReportEventMetricUniqueVisits(**self.params),
'visit_duration':... | python | {
"resource": ""
} |
q15060 | ReportGeneral._fetch_contribution_info | train | def _fetch_contribution_info(self):
"""Build the list of information entries for contributions of the event"""
self.contributions = {}
query = (Contribution.query
.with_parent(self.event)
.options(joinedload('legacy_mapping'),
joinedloa... | python | {
"resource": ""
} |
q15061 | DeconzDevice.remove_callback | train | def remove_callback(self, callback):
"""Remove callback previously registered."""
if callback in self._async_callbacks:
self._async_callbacks.remove(callback) | python | {
"resource": ""
} |
q15062 | DeconzDevice.update_attr | train | def update_attr(self, attr):
"""Update input attr in self.
Return list of attributes with changed values.
"""
changed_attr = []
for key, value in attr.items():
if value is None:
continue
if getattr(self, "_{0}".format(key), None) != value:... | python | {
"resource": ""
} |
q15063 | DeconzGroup.async_set_state | train | async def async_set_state(self, data):
"""Set state of light group.
{
"on": true,
"bri": 180,
"hue": 43680,
"sat": 255,
"transitiontime": 10
}
Also update local values of group since websockets doesn't.
"""
fie... | python | {
"resource": ""
} |
q15064 | DeconzGroup.async_add_scenes | train | def async_add_scenes(self, scenes, async_set_state_callback):
"""Add scenes belonging to group."""
self._scenes = {
scene['id']: DeconzScene(self, scene, async_set_state_callback)
for scene in scenes
if scene['id'] not in self._scenes
} | python | {
"resource": ""
} |
q15065 | DeconzGroup.update_color_state | train | def update_color_state(self, light):
"""Sync color state with light."""
x, y = light.xy or (None, None)
self.async_update({
'state': {
'bri': light.brightness,
'hue': light.hue,
'sat': light.sat,
'ct': light.ct,
... | python | {
"resource": ""
} |
q15066 | DeconzScene.async_set_state | train | async def async_set_state(self, data):
"""Recall scene to group."""
field = self._deconz_id + '/recall'
await self._async_set_state_callback(field, data) | python | {
"resource": ""
} |
q15067 | DeconzLightBase.async_update | train | def async_update(self, event):
"""New event for light.
Check that state is part of event.
Signal that light has updated state.
"""
self.update_attr(event.get('state', {}))
super().async_update(event) | python | {
"resource": ""
} |
q15068 | File.upload | train | def upload(cls, path, project=None, parent=None, file_name=None,
overwrite=False, retry=5, timeout=10,
part_size=PartSize.UPLOAD_MINIMUM_PART_SIZE, wait=True,
api=None):
"""
Uploads a file using multipart upload and returns an upload handle
if the wai... | python | {
"resource": ""
} |
q15069 | File.reload | train | def reload(self):
"""
Refreshes the file with the data from the server.
"""
try:
data = self._api.get(self.href, append_base=False).json()
resource = File(api=self._api, **data)
except Exception:
try:
data = self._api.get(
... | python | {
"resource": ""
} |
q15070 | File.content | train | def content(self, path=None, overwrite=True, encoding='utf-8'):
"""
Downloads file to the specified path or as temporary file
and reads the file content in memory.
Should not be used on very large files.
:param path: Path for file download If omitted tmp file will be used.
... | python | {
"resource": ""
} |
q15071 | get_json_from_remote_server | train | def get_json_from_remote_server(func, **kwargs):
"""
Safely manage calls to the remote server by encapsulating JSON creation
from Piwik data.
"""
rawjson = func(**kwargs)
if rawjson is None:
# If the request failed we already logged in in PiwikRequest;
# no need to get into the e... | python | {
"resource": ""
} |
q15072 | reduce_json | train | def reduce_json(data):
"""Reduce a JSON object"""
return reduce(lambda x, y: int(x) + int(y), data.values()) | python | {
"resource": ""
} |
q15073 | stringify_seconds | train | def stringify_seconds(seconds=0):
"""
Takes time as a value of seconds and deduces the delta in human-readable
HHh MMm SSs format.
"""
seconds = int(seconds)
minutes = seconds / 60
ti = {'h': 0, 'm': 0, 's': 0}
if seconds > 0:
ti['s'] = seconds % 60
ti['m'] = minutes % 6... | python | {
"resource": ""
} |
q15074 | create_sensor | train | def create_sensor(sensor_id, sensor, async_set_state_callback):
"""Simplify creating sensor by not needing to know type."""
if sensor['type'] in CONSUMPTION:
return Consumption(sensor_id, sensor)
if sensor['type'] in CARBONMONOXIDE:
return CarbonMonoxide(sensor_id, sensor)
if sensor['typ... | python | {
"resource": ""
} |
q15075 | supported_sensor | train | def supported_sensor(sensor):
"""Check if sensor is supported by pydeconz."""
if sensor['type'] in DECONZ_BINARY_SENSOR + DECONZ_SENSOR + OTHER_SENSOR:
return True
_LOGGER.info('Unsupported sensor type %s (%s)',
sensor['type'], sensor['name'])
return False | python | {
"resource": ""
} |
q15076 | DeconzSensor.async_update | train | def async_update(self, event, reason={}):
"""New event for sensor.
Check if state or config is part of event.
Signal that sensor has updated attributes.
Inform what attributes got changed values.
"""
reason['attr'] = []
for data in ['state', 'config']:
... | python | {
"resource": ""
} |
q15077 | Daylight.status | train | def status(self):
"""Return the daylight status string."""
if self._status == 100:
return "nadir"
elif self._status == 110:
return "night_end"
elif self._status == 120:
return "nautical_dawn"
elif self._status == 130:
return "dawn"
... | python | {
"resource": ""
} |
q15078 | Thermostat.async_set_config | train | async def async_set_config(self, data):
"""Set config of thermostat.
{
"mode": "auto",
"heatsetpoint": 180,
}
"""
field = self.deconz_id + '/config'
await self._async_set_state_callback(field, data) | python | {
"resource": ""
} |
q15079 | _metric_value | train | def _metric_value(value_str, metric_type):
"""
Return a Python-typed metric value from a metric value string.
"""
if metric_type in (int, float):
try:
return metric_type(value_str)
except ValueError:
raise ValueError("Invalid {} metric value: {!r}".
... | python | {
"resource": ""
} |
q15080 | _metric_unit_from_name | train | def _metric_unit_from_name(metric_name):
"""
Return a metric unit string for human consumption, that is inferred from
the metric name.
If a unit cannot be inferred, `None` is returned.
"""
for item in _PATTERN_UNIT_LIST:
pattern, unit = item
if pattern.match(metric_name):
... | python | {
"resource": ""
} |
q15081 | MetricsContext._setup_metric_group_definitions | train | def _setup_metric_group_definitions(self):
"""
Return the dict of MetricGroupDefinition objects for this metrics
context, by processing its 'metric-group-infos' property.
"""
# Dictionary of MetricGroupDefinition objects, by metric group name
metric_group_definitions = di... | python | {
"resource": ""
} |
q15082 | MetricsResponse._setup_metric_group_values | train | def _setup_metric_group_values(self):
"""
Return the list of MetricGroupValues objects for this metrics response,
by processing its metrics response string.
The lines in the metrics response string are::
MetricsResponse: MetricsGroup{0,*}
<empty... | python | {
"resource": ""
} |
q15083 | IdPool._expand | train | def _expand(self):
"""
Expand the free pool, if possible.
If out of capacity w.r.t. the defined ID value range, ValueError is
raised.
"""
assert not self._free # free pool is empty
expand_end = self._expand_start + self._expand_len
if expand_end > self._... | python | {
"resource": ""
} |
q15084 | IdPool.alloc | train | def alloc(self):
"""
Allocate an ID value and return it.
Raises:
ValueError: Out of capacity in ID pool.
"""
if not self._free:
self._expand()
id = self._free.pop()
self._used.add(id)
return id | python | {
"resource": ""
} |
q15085 | NicManager.create | train | def create(self, properties):
"""
Create and configure a NIC in this Partition.
The NIC must be backed by an adapter port (on an OSA, ROCE, or
Hipersockets adapter).
The way the backing adapter port is specified in the "properties"
parameter of this method depends on th... | python | {
"resource": ""
} |
q15086 | Nic.delete | train | def delete(self):
"""
Delete this NIC.
Authorization requirements:
* Object-access permission to the Partition containing this HBA.
* Task permission to the "Partition Details" task.
Raises:
:exc:`~zhmcclient.HTTPError`
:exc:`~zhmcclient.ParseError... | python | {
"resource": ""
} |
q15087 | Nic.update_properties | train | def update_properties(self, properties):
"""
Update writeable properties of this NIC.
Authorization requirements:
* Object-access permission to the Partition containing this NIC.
* Object-access permission to the backing Adapter for this NIC.
* Task permission to the "P... | python | {
"resource": ""
} |
q15088 | _NameUriCache.get | train | def get(self, name):
"""
Get the resource URI for a specified resource name.
If an entry for the specified resource name does not exist in the
Name-URI cache, the cache is refreshed from the HMC with all resources
of the manager holding this cache.
If an entry for the s... | python | {
"resource": ""
} |
q15089 | _NameUriCache.auto_invalidate | train | def auto_invalidate(self):
"""
Invalidate the cache if the current time is past the time to live.
"""
current = datetime.now()
if current > self._invalidated + timedelta(seconds=self._timetolive):
self.invalidate() | python | {
"resource": ""
} |
q15090 | _NameUriCache.refresh | train | def refresh(self):
"""
Refresh the Name-URI cache from the HMC.
This is done by invalidating the cache, listing the resources of this
manager from the HMC, and populating the cache with that information.
"""
self.invalidate()
full = not self._manager._list_has_na... | python | {
"resource": ""
} |
q15091 | _NameUriCache.update_from | train | def update_from(self, res_list):
"""
Update the Name-URI cache from the provided resource list.
This is done by going through the resource list and updating any cache
entries for non-empty resource names in that list. Other cache entries
remain unchanged.
"""
for... | python | {
"resource": ""
} |
q15092 | BaseManager._divide_filter_args | train | def _divide_filter_args(self, filter_args):
"""
Divide the filter arguments into filter query parameters for filtering
on the server side, and the remaining client-side filters.
Parameters:
filter_args (dict):
Filter arguments that narrow the list of returned reso... | python | {
"resource": ""
} |
q15093 | BaseManager._matches_filters | train | def _matches_filters(self, obj, filter_args):
"""
Return a boolean indicating whether a resource object matches a set
of filter arguments.
This is used for client-side filtering.
Depending on the properties specified in the filter arguments, this
method retrieves the res... | python | {
"resource": ""
} |
q15094 | BaseManager._matches_prop | train | def _matches_prop(self, obj, prop_name, prop_match):
"""
Return a boolean indicating whether a resource object matches with
a single property against a property match value.
This is used for client-side filtering.
Depending on the specified property, this method retrieves the re... | python | {
"resource": ""
} |
q15095 | BaseManager.resource_object | train | def resource_object(self, uri_or_oid, props=None):
"""
Return a minimalistic Python resource object for this resource class,
that is scoped to this manager.
This method is an internal helper function and is not normally called
by users.
The returned resource object will... | python | {
"resource": ""
} |
q15096 | FakedBaseResource.add_resources | train | def add_resources(self, resources):
"""
Add faked child resources to this resource, from the provided resource
definitions.
Duplicate resource names in the same scope are not permitted.
Although this method is typically used to initially load the faked
HMC with resource... | python | {
"resource": ""
} |
q15097 | FakedBaseManager.add | train | def add(self, properties):
"""
Add a faked resource to this manager.
For URI-based lookup, the resource is also added to the faked HMC.
Parameters:
properties (dict):
Resource properties. If the URI property (e.g. 'object-uri') or the
object ID proper... | python | {
"resource": ""
} |
q15098 | FakedBaseManager.remove | train | def remove(self, oid):
"""
Remove a faked resource from this manager.
Parameters:
oid (string):
The object ID of the resource (e.g. value of the 'object-uri'
property).
"""
uri = self._resources[oid].uri
del self._resources[oid]
... | python | {
"resource": ""
} |
q15099 | FakedBaseManager.list | train | def list(self, filter_args=None):
"""
List the faked resources of this manager.
Parameters:
filter_args (dict):
Filter arguments. `None` causes no filtering to happen. See
:meth:`~zhmcclient.BaseManager.list()` for details.
Returns:
list of ... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.