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
jvarho/pylibscrypt
pylibscrypt/pylibscrypt.py
scrypt_mcf
python
def scrypt_mcf(password, salt=None, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, prefix=SCRYPT_MCF_PREFIX_DEFAULT): if (prefix != SCRYPT_MCF_PREFIX_s1 and prefix != SCRYPT_MCF_PREFIX_ANY): return mcf_mod.scrypt_mcf(scrypt, password, salt, N, r, p, prefix) if isinstance(password, unicode): ...
Derives a Modular Crypt Format hash using the scrypt KDF Parameter space is smaller than for scrypt(): N must be a power of two larger than 1 but no larger than 2 ** 31 r and p must be positive numbers between 1 and 255 Salt must be a byte string 1-16 bytes long. If no salt is given, a random salt...
train
https://github.com/jvarho/pylibscrypt/blob/f2ff02e49f44aa620e308a4a64dd8376b9510f99/pylibscrypt/pylibscrypt.py#L101-L142
[ "def scrypt_mcf(scrypt, password, salt=None, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p,\n prefix=SCRYPT_MCF_PREFIX_DEFAULT):\n \"\"\"Derives a Modular Crypt Format hash using the scrypt KDF given\n\n Expects the signature:\n scrypt(password, salt, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, olen=64)\n\n ...
# Copyright (c) 2014-2018, Jan Varho # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL...
jvarho/pylibscrypt
pylibscrypt/pylibscrypt.py
scrypt_mcf_check
python
def scrypt_mcf_check(mcf, password): if not isinstance(mcf, bytes): raise TypeError('MCF must be a byte string') if isinstance(password, unicode): password = password.encode('utf8') elif not isinstance(password, bytes): raise TypeError('password must be a unicode or byte string') ...
Returns True if the password matches the given MCF hash
train
https://github.com/jvarho/pylibscrypt/blob/f2ff02e49f44aa620e308a4a64dd8376b9510f99/pylibscrypt/pylibscrypt.py#L145-L161
[ "def scrypt_mcf_check(scrypt, mcf, password):\n \"\"\"Returns True if the password matches the given MCF hash\n\n Supports both the libscrypt $s1$ format and the $7$ format.\n \"\"\"\n if not isinstance(mcf, bytes):\n raise TypeError('MCF must be a byte string')\n if isinstance(password, unico...
# Copyright (c) 2014-2018, Jan Varho # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL...
JarryShaw/DictDumper
src/plist.py
PLIST._append_value
python
def _append_value(self, value, _file, _name): _tabs = '\t' * self._tctr _keys = '{tabs}<key>{name}</key>\n'.format(tabs=_tabs, name=_name) _file.seek(self._sptr, os.SEEK_SET) _file.write(_keys) self._append_dict(value, _file)
Call this function to write contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file * _name - str, name of current content dict
train
https://github.com/JarryShaw/DictDumper/blob/430efcfdff18bb2421c3f27059ff94c93e621483/src/plist.py#L151-L165
null
class PLIST(XML): """Dump Apple property list (PLIST) format file. Usage: >>> dumper = PLIST(file_name) >>> dumper(content_dict_1, name=content_name_1) >>> dumper(content_dict_2, name=content_name_2) ............ Properties: * kind - str, return 'plist' Methods...
JarryShaw/DictDumper
src/plist.py
PLIST._append_array
python
def _append_array(self, value, _file): _tabs = '\t' * self._tctr _labs = '{tabs}<array>\n'.format(tabs=_tabs) _file.write(_labs) self._tctr += 1 for _item in value: if _item is None: continue _item = self.object_hook(_item) _ty...
Call this function to write array contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file
train
https://github.com/JarryShaw/DictDumper/blob/430efcfdff18bb2421c3f27059ff94c93e621483/src/plist.py#L167-L190
null
class PLIST(XML): """Dump Apple property list (PLIST) format file. Usage: >>> dumper = PLIST(file_name) >>> dumper(content_dict_1, name=content_name_1) >>> dumper(content_dict_2, name=content_name_2) ............ Properties: * kind - str, return 'plist' Methods...
JarryShaw/DictDumper
src/plist.py
PLIST._append_dict
python
def _append_dict(self, value, _file): _tabs = '\t' * self._tctr _labs = '{tabs}<dict>\n'.format(tabs=_tabs) _file.write(_labs) self._tctr += 1 for (_item, _text) in value.items(): if _text is None: continue _tabs = '\t' * self._tctr ...
Call this function to write dict contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file
train
https://github.com/JarryShaw/DictDumper/blob/430efcfdff18bb2421c3f27059ff94c93e621483/src/plist.py#L192-L220
null
class PLIST(XML): """Dump Apple property list (PLIST) format file. Usage: >>> dumper = PLIST(file_name) >>> dumper(content_dict_1, name=content_name_1) >>> dumper(content_dict_2, name=content_name_2) ............ Properties: * kind - str, return 'plist' Methods...
JarryShaw/DictDumper
src/plist.py
PLIST._append_data
python
def _append_data(self, value, _file): # binascii.b2a_base64(value) -> plistlib.Data # binascii.a2b_base64(Data) -> value(bytes) _tabs = '\t' * self._tctr _text = base64.b64encode(value).decode() # value.hex() # str(value)[2:-1] _labs = '{tabs}<data>{text}</data>\n'.format(tabs=...
Call this function to write data contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file
train
https://github.com/JarryShaw/DictDumper/blob/430efcfdff18bb2421c3f27059ff94c93e621483/src/plist.py#L235-L262
null
class PLIST(XML): """Dump Apple property list (PLIST) format file. Usage: >>> dumper = PLIST(file_name) >>> dumper(content_dict_1, name=content_name_1) >>> dumper(content_dict_2, name=content_name_2) ............ Properties: * kind - str, return 'plist' Methods...
JarryShaw/DictDumper
src/plist.py
PLIST._append_date
python
def _append_date(self, value, _file): _tabs = '\t' * self._tctr _text = value.strftime('%Y-%m-%dT%H:%M:%S.%fZ') _labs = '{tabs}<date>{text}</date>\n'.format(tabs=_tabs, text=_text) _file.write(_labs)
Call this function to write date contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file
train
https://github.com/JarryShaw/DictDumper/blob/430efcfdff18bb2421c3f27059ff94c93e621483/src/plist.py#L264-L275
null
class PLIST(XML): """Dump Apple property list (PLIST) format file. Usage: >>> dumper = PLIST(file_name) >>> dumper(content_dict_1, name=content_name_1) >>> dumper(content_dict_2, name=content_name_2) ............ Properties: * kind - str, return 'plist' Methods...
JarryShaw/DictDumper
src/plist.py
PLIST._append_integer
python
def _append_integer(self, value, _file): _tabs = '\t' * self._tctr _text = value _labs = '{tabs}<integer>{text}</integer>\n'.format(tabs=_tabs, text=_text) _file.write(_labs)
Call this function to write integer contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file
train
https://github.com/JarryShaw/DictDumper/blob/430efcfdff18bb2421c3f27059ff94c93e621483/src/plist.py#L277-L288
null
class PLIST(XML): """Dump Apple property list (PLIST) format file. Usage: >>> dumper = PLIST(file_name) >>> dumper(content_dict_1, name=content_name_1) >>> dumper(content_dict_2, name=content_name_2) ............ Properties: * kind - str, return 'plist' Methods...
JarryShaw/DictDumper
src/dumper.py
Dumper._dump_header
python
def _dump_header(self): with open(self._file, 'w') as _file: _file.write(self._hsrt) self._sptr = _file.tell() _file.write(self._hend)
Initially dump file heads and tails.
train
https://github.com/JarryShaw/DictDumper/blob/430efcfdff18bb2421c3f27059ff94c93e621483/src/dumper.py#L116-L121
null
class Dumper(object): # pylint:disable= metaclass-assignment,useless-object-inheritance """Abstract base class of all dumpers. Usage: >>> dumper = Dumper(file_name) >>> dumper(content_dict_1, name=content_name_1) >>> dumper(content_dict_2, name=content_name_2) ............ ...
JarryShaw/DictDumper
src/tree.py
Tree._append_value
python
def _append_value(self, value, _file, _name): if self._flag: _keys = _name + '\n' else: _keys = '\n' + _name + '\n' _file.seek(self._sptr, os.SEEK_SET) _file.write(_keys) self._bctr = collections.defaultdict(int) # blank branch counter dict sel...
Call this function to write contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file * _name - str, name of current content dict
train
https://github.com/JarryShaw/DictDumper/blob/430efcfdff18bb2421c3f27059ff94c93e621483/src/tree.py#L169-L186
null
class Tree(Dumper): """Dump a tree-view text (TXT) format file. Usage: >>> dumper = Tree(file_name) >>> dumper(content_dict_1, name=content_name_1) >>> dumper(content_dict_2, name=content_name_2) ............ Properties: * kind - str, return 'plist' Methods: ...
JarryShaw/DictDumper
src/tree.py
Tree._append_array
python
def _append_array(self, value, _file): if not value: self._append_none(None, _file) return _bptr = '' _tabs = '' _tlen = len(value) - 1 if _tlen: _bptr = ' |-->' for _ in range(self._tctr + 1): _tabs += _TEMP_SPACE...
Call this function to write array contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file
train
https://github.com/JarryShaw/DictDumper/blob/430efcfdff18bb2421c3f27059ff94c93e621483/src/tree.py#L188-L219
null
class Tree(Dumper): """Dump a tree-view text (TXT) format file. Usage: >>> dumper = Tree(file_name) >>> dumper(content_dict_1, name=content_name_1) >>> dumper(content_dict_2, name=content_name_2) ............ Properties: * kind - str, return 'plist' Methods: ...
JarryShaw/DictDumper
src/tree.py
Tree._append_branch
python
def _append_branch(self, value, _file): if not value: return # return self._append_none(None, _file) self._tctr += 1 _vlen = len(value) for (_vctr, (_item, _text)) in enumerate(value.items()): _text = self.object_hook(_text) _type = type(_...
Call this function to write branch contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file
train
https://github.com/JarryShaw/DictDumper/blob/430efcfdff18bb2421c3f27059ff94c93e621483/src/tree.py#L221-L264
null
class Tree(Dumper): """Dump a tree-view text (TXT) format file. Usage: >>> dumper = Tree(file_name) >>> dumper(content_dict_1, name=content_name_1) >>> dumper(content_dict_2, name=content_name_2) ............ Properties: * kind - str, return 'plist' Methods: ...
JarryShaw/DictDumper
src/tree.py
Tree._append_bytes
python
def _append_bytes(self, value, _file): # binascii.b2a_base64(value) -> plistlib.Data # binascii.a2b_base64(Data) -> value(bytes) if not value: self._append_none(None, _file) return if len(value) > 16: _tabs = '' for _ in range(self._tctr +...
Call this function to write bytes contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file
train
https://github.com/JarryShaw/DictDumper/blob/430efcfdff18bb2421c3f27059ff94c93e621483/src/tree.py#L282-L311
null
class Tree(Dumper): """Dump a tree-view text (TXT) format file. Usage: >>> dumper = Tree(file_name) >>> dumper(content_dict_1, name=content_name_1) >>> dumper(content_dict_2, name=content_name_2) ............ Properties: * kind - str, return 'plist' Methods: ...
JarryShaw/DictDumper
src/tree.py
Tree._append_number
python
def _append_number(self, value, _file): # pylint: disable=no-self-use _text = value _labs = ' {text}'.format(text=_text) _file.write(_labs)
Call this function to write number contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file
train
https://github.com/JarryShaw/DictDumper/blob/430efcfdff18bb2421c3f27059ff94c93e621483/src/tree.py#L325-L335
null
class Tree(Dumper): """Dump a tree-view text (TXT) format file. Usage: >>> dumper = Tree(file_name) >>> dumper(content_dict_1, name=content_name_1) >>> dumper(content_dict_2, name=content_name_2) ............ Properties: * kind - str, return 'plist' Methods: ...
JarryShaw/DictDumper
src/json.py
JSON._append_value
python
def _append_value(self, value, _file, _name): _tabs = '\t' * self._tctr _cmma = ',\n' if self._vctr[self._tctr] else '' _keys = '{cmma}{tabs}"{name}" :'.format(cmma=_cmma, tabs=_tabs, name=_name) _file.seek(self._sptr, os.SEEK_SET) _file.write(_keys) self._vctr[self._tc...
Call this function to write contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file * _name - str, name of current content dict
train
https://github.com/JarryShaw/DictDumper/blob/430efcfdff18bb2421c3f27059ff94c93e621483/src/json.py#L143-L160
null
class JSON(Dumper): """Dump JavaScript object notation (JSON) format file. Usage: >>> dumper = JSON(file_name) >>> dumper(content_dict_1, name=content_name_1) >>> dumper(content_dict_2, name=content_name_2) ............ Properties: * kind - str, return 'json' M...
JarryShaw/DictDumper
src/json.py
JSON._append_array
python
def _append_array(self, value, _file): _labs = ' [' _file.write(_labs) self._tctr += 1 for _item in value: _cmma = ',' if self._vctr[self._tctr] else '' _file.write(_cmma) self._vctr[self._tctr] += 1 _item = self.object_hook(_item) ...
Call this function to write array contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file
train
https://github.com/JarryShaw/DictDumper/blob/430efcfdff18bb2421c3f27059ff94c93e621483/src/json.py#L166-L193
null
class JSON(Dumper): """Dump JavaScript object notation (JSON) format file. Usage: >>> dumper = JSON(file_name) >>> dumper(content_dict_1, name=content_name_1) >>> dumper(content_dict_2, name=content_name_2) ............ Properties: * kind - str, return 'json' M...
JarryShaw/DictDumper
src/json.py
JSON._append_object
python
def _append_object(self, value, _file): _labs = ' {' _file.write(_labs) self._tctr += 1 for (_item, _text) in value.items(): _tabs = '\t' * self._tctr _cmma = ',' if self._vctr[self._tctr] else '' _keys = '{cmma}\n{tabs}"{item}" :'.format(cmma=_cmma, ...
Call this function to write object contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file
train
https://github.com/JarryShaw/DictDumper/blob/430efcfdff18bb2421c3f27059ff94c93e621483/src/json.py#L195-L223
null
class JSON(Dumper): """Dump JavaScript object notation (JSON) format file. Usage: >>> dumper = JSON(file_name) >>> dumper(content_dict_1, name=content_name_1) >>> dumper(content_dict_2, name=content_name_2) ............ Properties: * kind - str, return 'json' M...
JarryShaw/DictDumper
src/json.py
JSON._append_string
python
def _append_string(self, value, _file): # pylint: disable=no-self-use _text = str(value).replace('"', '\\"') _labs = ' "{text}"'.format(text=_text) _file.write(_labs)
Call this function to write string contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file
train
https://github.com/JarryShaw/DictDumper/blob/430efcfdff18bb2421c3f27059ff94c93e621483/src/json.py#L225-L235
null
class JSON(Dumper): """Dump JavaScript object notation (JSON) format file. Usage: >>> dumper = JSON(file_name) >>> dumper(content_dict_1, name=content_name_1) >>> dumper(content_dict_2, name=content_name_2) ............ Properties: * kind - str, return 'json' M...
JarryShaw/DictDumper
src/json.py
JSON._append_bytes
python
def _append_bytes(self, value, _file): # pylint: disable=no-self-use # binascii.b2a_base64(value) -> plistlib.Data # binascii.a2b_base64(Data) -> value(bytes) _text = ' '.join(textwrap.wrap(value.hex(), 2)) # _data = [H for H in iter( # functools.partial(io.StringIO(val...
Call this function to write bytes contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file
train
https://github.com/JarryShaw/DictDumper/blob/430efcfdff18bb2421c3f27059ff94c93e621483/src/json.py#L237-L253
null
class JSON(Dumper): """Dump JavaScript object notation (JSON) format file. Usage: >>> dumper = JSON(file_name) >>> dumper(content_dict_1, name=content_name_1) >>> dumper(content_dict_2, name=content_name_2) ............ Properties: * kind - str, return 'json' M...
JarryShaw/DictDumper
src/json.py
JSON._append_date
python
def _append_date(self, value, _file): # pylint: disable=no-self-use _text = value.strftime('%Y-%m-%dT%H:%M:%S.%fZ') _labs = ' "{text}"'.format(text=_text) _file.write(_labs)
Call this function to write date contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file
train
https://github.com/JarryShaw/DictDumper/blob/430efcfdff18bb2421c3f27059ff94c93e621483/src/json.py#L255-L265
null
class JSON(Dumper): """Dump JavaScript object notation (JSON) format file. Usage: >>> dumper = JSON(file_name) >>> dumper(content_dict_1, name=content_name_1) >>> dumper(content_dict_2, name=content_name_2) ............ Properties: * kind - str, return 'json' M...
sprockets/sprockets-dynamodb
sprockets_dynamodb/mixin.py
DynamoDBMixin._on_dynamodb_exception
python
def _on_dynamodb_exception(self, error): if isinstance(error, exceptions.ConditionalCheckFailedException): raise web.HTTPError(409, reason='Condition Check Failure') elif isinstance(error, exceptions.NoCredentialsError): if _no_creds_should_return_429(): raise web...
Dynamically handle DynamoDB exceptions, returning HTTP error responses. :param exceptions.DynamoDBException error:
train
https://github.com/sprockets/sprockets-dynamodb/blob/2e202bcb01f23f828f91299599311007054de4aa/sprockets_dynamodb/mixin.py#L39-L56
null
class DynamoDBMixin(object): """The DynamoDBMixin is an opinionated :class:`~tornado.web.RequestHandler` mixin class that """ def initialize(self): super(DynamoDBMixin, self).initialize() self.application.dynamodb.set_error_callback( self._on_dynamodb_exception) if i...
sprockets/sprockets-dynamodb
sprockets_dynamodb/utils.py
marshall
python
def marshall(values): serialized = {} for key in values: serialized[key] = _marshall_value(values[key]) return serialized
Marshall a `dict` into something DynamoDB likes. :param dict values: The values to marshall :rtype: dict :raises ValueError: if an unsupported type is encountered Return the values in a nested dict structure that is required for writing the values to DynamoDB.
train
https://github.com/sprockets/sprockets-dynamodb/blob/2e202bcb01f23f828f91299599311007054de4aa/sprockets_dynamodb/utils.py#L40-L55
[ "def _marshall_value(value):\n \"\"\"\n Recursively transform `value` into an AttributeValue `dict`\n\n :param mixed value: The value to encode\n :rtype: dict\n :raises ValueError: for unsupported types\n\n Return the value as dict indicating the data type and transform or\n recursively process...
""" Utilities for working with DynamoDB. - :func:`.marshall` - :func:`.unmarshal` This module contains some helpers that make working with the Amazon DynamoDB API a little less painful. Data is encoded as `AttributeValue`_ structures in the JSON payloads and this module defines functions that will handle the transco...
sprockets/sprockets-dynamodb
sprockets_dynamodb/utils.py
unmarshall
python
def unmarshall(values): unmarshalled = {} for key in values: unmarshalled[key] = _unmarshall_dict(values[key]) return unmarshalled
Transform a response payload from DynamoDB to a native dict :param dict values: The response payload from DynamoDB :rtype: dict :raises ValueError: if an unsupported type code is encountered
train
https://github.com/sprockets/sprockets-dynamodb/blob/2e202bcb01f23f828f91299599311007054de4aa/sprockets_dynamodb/utils.py#L58-L70
[ "def _unmarshall_dict(value):\n \"\"\"Unmarshall a single dict value from a row that was returned from\n DynamoDB, returning the value as a normal Python dict.\n\n :param dict value: The value to unmarshall\n :rtype: mixed\n :raises ValueError: if an unsupported type code is encountered\n\n \"\"\"...
""" Utilities for working with DynamoDB. - :func:`.marshall` - :func:`.unmarshal` This module contains some helpers that make working with the Amazon DynamoDB API a little less painful. Data is encoded as `AttributeValue`_ structures in the JSON payloads and this module defines functions that will handle the transco...
sprockets/sprockets-dynamodb
sprockets_dynamodb/utils.py
_marshall_value
python
def _marshall_value(value): if PYTHON3 and isinstance(value, bytes): return {'B': base64.b64encode(value).decode('ascii')} elif PYTHON3 and isinstance(value, str): return {'S': value} elif not PYTHON3 and isinstance(value, str): if is_binary(value): return {'B': base64.b...
Recursively transform `value` into an AttributeValue `dict` :param mixed value: The value to encode :rtype: dict :raises ValueError: for unsupported types Return the value as dict indicating the data type and transform or recursively process the value if required.
train
https://github.com/sprockets/sprockets-dynamodb/blob/2e202bcb01f23f828f91299599311007054de4aa/sprockets_dynamodb/utils.py#L83-L134
[ "def marshall(values):\n \"\"\"\n Marshall a `dict` into something DynamoDB likes.\n\n :param dict values: The values to marshall\n :rtype: dict\n :raises ValueError: if an unsupported type is encountered\n\n Return the values in a nested dict structure that is required for\n writing the values...
""" Utilities for working with DynamoDB. - :func:`.marshall` - :func:`.unmarshal` This module contains some helpers that make working with the Amazon DynamoDB API a little less painful. Data is encoded as `AttributeValue`_ structures in the JSON payloads and this module defines functions that will handle the transco...
sprockets/sprockets-dynamodb
sprockets_dynamodb/utils.py
_unmarshall_dict
python
def _unmarshall_dict(value): key = list(value.keys()).pop() if key == 'B': return base64.b64decode(value[key].encode('ascii')) elif key == 'BS': return set([base64.b64decode(v.encode('ascii')) for v in value[key]]) elif key == 'BOOL': return value[key] eli...
Unmarshall a single dict value from a row that was returned from DynamoDB, returning the value as a normal Python dict. :param dict value: The value to unmarshall :rtype: mixed :raises ValueError: if an unsupported type code is encountered
train
https://github.com/sprockets/sprockets-dynamodb/blob/2e202bcb01f23f828f91299599311007054de4aa/sprockets_dynamodb/utils.py#L148-L179
[ "def unmarshall(values):\n \"\"\"\n Transform a response payload from DynamoDB to a native dict\n\n :param dict values: The response payload from DynamoDB\n :rtype: dict\n :raises ValueError: if an unsupported type code is encountered\n\n \"\"\"\n unmarshalled = {}\n for key in values:\n ...
""" Utilities for working with DynamoDB. - :func:`.marshall` - :func:`.unmarshal` This module contains some helpers that make working with the Amazon DynamoDB API a little less painful. Data is encoded as `AttributeValue`_ structures in the JSON payloads and this module defines functions that will handle the transco...
sprockets/sprockets-dynamodb
sprockets_dynamodb/client.py
_unwrap_result
python
def _unwrap_result(action, result): if not result: return elif action in {'DeleteItem', 'PutItem', 'UpdateItem'}: return _unwrap_delete_put_update_item(result) elif action == 'GetItem': return _unwrap_get_item(result) elif action == 'Query' or action == 'Scan': return _un...
Unwrap a request response and return only the response data. :param str action: The action name :param result: The result of the action :type: result: list or dict :rtype: dict | None
train
https://github.com/sprockets/sprockets-dynamodb/blob/2e202bcb01f23f828f91299599311007054de4aa/sprockets_dynamodb/client.py#L943-L964
null
""" DynamoDB Client =============== """ import collections import json import logging import os import select as _select import socket import ssl import time from tornado import concurrent, gen, httpclient, ioloop import tornado_aws from tornado_aws import exceptions as aws_exceptions from sprockets_dynamodb import ...
sprockets/sprockets-dynamodb
sprockets_dynamodb/client.py
Client.list_tables
python
def list_tables(self, exclusive_start_table_name=None, limit=None): payload = {} if exclusive_start_table_name: payload['ExclusiveStartTableName'] = exclusive_start_table_name if limit: payload['Limit'] = limit return self.execute('ListTables', payload)
Invoke the `ListTables`_ function. Returns an array of table names associated with the current account and endpoint. The output from *ListTables* is paginated, with each page returning a maximum of ``100`` table names. :param str exclusive_start_table_name: The first table name that th...
train
https://github.com/sprockets/sprockets-dynamodb/blob/2e202bcb01f23f828f91299599311007054de4aa/sprockets_dynamodb/client.py#L176-L200
null
class Client(object): """ Asynchronous DynamoDB Client :keyword str region: AWS region to send requests to :keyword str access_key: AWS access key. If unspecified, this defaults to the :envvar:`AWS_ACCESS_KEY_ID` environment variable and will fall back to using the AWS CLI credentials ...
sprockets/sprockets-dynamodb
sprockets_dynamodb/client.py
Client.put_item
python
def put_item(self, table_name, item, condition_expression=None, expression_attribute_names=None, expression_attribute_values=None, return_consumed_capacity=None, return_item_collection_metrics=None, return_values=None)...
Invoke the `PutItem`_ function, creating a new item, or replaces an old item with a new item. If an item that has the same primary key as the new item already exists in the specified table, the new item completely replaces the existing item. You can perform a conditional put operation (a...
train
https://github.com/sprockets/sprockets-dynamodb/blob/2e202bcb01f23f828f91299599311007054de4aa/sprockets_dynamodb/client.py#L202-L276
[ "def marshall(values):\n \"\"\"\n Marshall a `dict` into something DynamoDB likes.\n\n :param dict values: The values to marshall\n :rtype: dict\n :raises ValueError: if an unsupported type is encountered\n\n Return the values in a nested dict structure that is required for\n writing the values...
class Client(object): """ Asynchronous DynamoDB Client :keyword str region: AWS region to send requests to :keyword str access_key: AWS access key. If unspecified, this defaults to the :envvar:`AWS_ACCESS_KEY_ID` environment variable and will fall back to using the AWS CLI credentials ...
sprockets/sprockets-dynamodb
sprockets_dynamodb/client.py
Client.get_item
python
def get_item(self, table_name, key_dict, consistent_read=False, expression_attribute_names=None, projection_expression=None, return_consumed_capacity=None): payload = {'TableName': table_name, 'Key': utils.marshall(key_dict),...
Invoke the `GetItem`_ function. :param str table_name: table to retrieve the item from :param dict key_dict: key to use for retrieval. This will be marshalled for you so a native :class:`dict` works. :param bool consistent_read: Determines the read consistency model: If ...
train
https://github.com/sprockets/sprockets-dynamodb/blob/2e202bcb01f23f828f91299599311007054de4aa/sprockets_dynamodb/client.py#L278-L331
[ "def marshall(values):\n \"\"\"\n Marshall a `dict` into something DynamoDB likes.\n\n :param dict values: The values to marshall\n :rtype: dict\n :raises ValueError: if an unsupported type is encountered\n\n Return the values in a nested dict structure that is required for\n writing the values...
class Client(object): """ Asynchronous DynamoDB Client :keyword str region: AWS region to send requests to :keyword str access_key: AWS access key. If unspecified, this defaults to the :envvar:`AWS_ACCESS_KEY_ID` environment variable and will fall back to using the AWS CLI credentials ...
sprockets/sprockets-dynamodb
sprockets_dynamodb/client.py
Client.update_item
python
def update_item(self, table_name, key_dict, condition_expression=None, update_expression=None, expression_attribute_names=None, expression_attribute_values=None, return_consumed_capacity=None, return_...
Invoke the `UpdateItem`_ function. Edits an existing item's attributes, or adds a new item to the table if it does not already exist. You can put, delete, or add attribute values. You can also perform a conditional update on an existing item (insert a new attribute name-value pair if it...
train
https://github.com/sprockets/sprockets-dynamodb/blob/2e202bcb01f23f828f91299599311007054de4aa/sprockets_dynamodb/client.py#L333-L411
[ "def marshall(values):\n \"\"\"\n Marshall a `dict` into something DynamoDB likes.\n\n :param dict values: The values to marshall\n :rtype: dict\n :raises ValueError: if an unsupported type is encountered\n\n Return the values in a nested dict structure that is required for\n writing the values...
class Client(object): """ Asynchronous DynamoDB Client :keyword str region: AWS region to send requests to :keyword str access_key: AWS access key. If unspecified, this defaults to the :envvar:`AWS_ACCESS_KEY_ID` environment variable and will fall back to using the AWS CLI credentials ...
sprockets/sprockets-dynamodb
sprockets_dynamodb/client.py
Client.query
python
def query(self, table_name, index_name=None, consistent_read=None, key_condition_expression=None, filter_expression=None, expression_attribute_names=None, expression_attribute_values=None, projection_expression=None, ...
A `Query`_ operation uses the primary key of a table or a secondary index to directly access items from that table or index. :param str table_name: The name of the table containing the requested items. :param bool consistent_read: Determines the read consistency model: If ...
train
https://github.com/sprockets/sprockets-dynamodb/blob/2e202bcb01f23f828f91299599311007054de4aa/sprockets_dynamodb/client.py#L502-L653
[ "def marshall(values):\n \"\"\"\n Marshall a `dict` into something DynamoDB likes.\n\n :param dict values: The values to marshall\n :rtype: dict\n :raises ValueError: if an unsupported type is encountered\n\n Return the values in a nested dict structure that is required for\n writing the values...
class Client(object): """ Asynchronous DynamoDB Client :keyword str region: AWS region to send requests to :keyword str access_key: AWS access key. If unspecified, this defaults to the :envvar:`AWS_ACCESS_KEY_ID` environment variable and will fall back to using the AWS CLI credentials ...
sprockets/sprockets-dynamodb
sprockets_dynamodb/client.py
Client.scan
python
def scan(self, table_name, index_name=None, consistent_read=None, projection_expression=None, filter_expression=None, expression_attribute_names=None, expression_attribute_values=None, segment=None, tota...
The `Scan`_ operation returns one or more items and item attributes by accessing every item in a table or a secondary index. If the total number of scanned items exceeds the maximum data set size limit of 1 MB, the scan stops and results are returned to the user as a ``LastEvaluatedKey`...
train
https://github.com/sprockets/sprockets-dynamodb/blob/2e202bcb01f23f828f91299599311007054de4aa/sprockets_dynamodb/client.py#L655-L726
[ "def marshall(values):\n \"\"\"\n Marshall a `dict` into something DynamoDB likes.\n\n :param dict values: The values to marshall\n :rtype: dict\n :raises ValueError: if an unsupported type is encountered\n\n Return the values in a nested dict structure that is required for\n writing the values...
class Client(object): """ Asynchronous DynamoDB Client :keyword str region: AWS region to send requests to :keyword str access_key: AWS access key. If unspecified, this defaults to the :envvar:`AWS_ACCESS_KEY_ID` environment variable and will fall back to using the AWS CLI credentials ...
sprockets/sprockets-dynamodb
sprockets_dynamodb/client.py
Client.execute
python
def execute(self, action, parameters): measurements = collections.deque([], self._max_retries) for attempt in range(1, self._max_retries + 1): try: result = yield self._execute( action, parameters, attempt, measurements) except (exceptions.Inte...
Execute a DynamoDB action with the given parameters. The method will retry requests that failed due to OS level errors or when being throttled by DynamoDB. :param str action: DynamoDB action to invoke :param dict parameters: parameters to send into the action :rtype: tornado.con...
train
https://github.com/sprockets/sprockets-dynamodb/blob/2e202bcb01f23f828f91299599311007054de4aa/sprockets_dynamodb/client.py#L729-L790
[ "def _unwrap_result(action, result):\n \"\"\"Unwrap a request response and return only the response data.\n\n :param str action: The action name\n :param result: The result of the action\n :type: result: list or dict\n :rtype: dict | None\n\n \"\"\"\n if not result:\n return\n elif ac...
class Client(object): """ Asynchronous DynamoDB Client :keyword str region: AWS region to send requests to :keyword str access_key: AWS access key. If unspecified, this defaults to the :envvar:`AWS_ACCESS_KEY_ID` environment variable and will fall back to using the AWS CLI credentials ...
sprockets/sprockets-dynamodb
sprockets_dynamodb/client.py
Client.set_error_callback
python
def set_error_callback(self, callback): self.logger.debug('Setting error callback: %r', callback) self._on_error = callback
Assign a method to invoke when a request has encountered an unrecoverable error in an action execution. :param method callback: The method to invoke
train
https://github.com/sprockets/sprockets-dynamodb/blob/2e202bcb01f23f828f91299599311007054de4aa/sprockets_dynamodb/client.py#L792-L800
null
class Client(object): """ Asynchronous DynamoDB Client :keyword str region: AWS region to send requests to :keyword str access_key: AWS access key. If unspecified, this defaults to the :envvar:`AWS_ACCESS_KEY_ID` environment variable and will fall back to using the AWS CLI credentials ...
sprockets/sprockets-dynamodb
sprockets_dynamodb/client.py
Client.set_instrumentation_callback
python
def set_instrumentation_callback(self, callback): self.logger.debug('Setting instrumentation callback: %r', callback) self._instrumentation_callback = callback
Assign a method to invoke when a request has completed gathering measurements. :param method callback: The method to invoke
train
https://github.com/sprockets/sprockets-dynamodb/blob/2e202bcb01f23f828f91299599311007054de4aa/sprockets_dynamodb/client.py#L802-L810
null
class Client(object): """ Asynchronous DynamoDB Client :keyword str region: AWS region to send requests to :keyword str access_key: AWS access key. If unspecified, this defaults to the :envvar:`AWS_ACCESS_KEY_ID` environment variable and will fall back to using the AWS CLI credentials ...
sprockets/sprockets-dynamodb
sprockets_dynamodb/client.py
Client._execute
python
def _execute(self, action, parameters, attempt, measurements): future = concurrent.Future() start = time.time() def handle_response(request): """Invoked by the IOLoop when fetch has a response to process. :param tornado.concurrent.Future request: The request future ...
Invoke a DynamoDB action :param str action: DynamoDB action to invoke :param dict parameters: parameters to send into the action :param int attempt: Which attempt number this is :param list measurements: A list for accumulating request measurements :rtype: tornado.concurrent.Fut...
train
https://github.com/sprockets/sprockets-dynamodb/blob/2e202bcb01f23f828f91299599311007054de4aa/sprockets_dynamodb/client.py#L812-L842
null
class Client(object): """ Asynchronous DynamoDB Client :keyword str region: AWS region to send requests to :keyword str access_key: AWS access key. If unspecified, this defaults to the :envvar:`AWS_ACCESS_KEY_ID` environment variable and will fall back to using the AWS CLI credentials ...
sprockets/sprockets-dynamodb
sprockets_dynamodb/client.py
Client._on_response
python
def _on_response(self, action, table, attempt, start, response, future, measurements): self.logger.debug('%s on %s request #%i = %r', action, table, attempt, response) now, exception = time.time(), None try: future.set_result(self._proce...
Invoked when the HTTP request to the DynamoDB has returned and is responsible for setting the future result or exception based upon the HTTP response provided. :param str action: The action that was taken :param str table: The table name the action was made against :param int at...
train
https://github.com/sprockets/sprockets-dynamodb/blob/2e202bcb01f23f828f91299599311007054de4aa/sprockets_dynamodb/client.py#L855-L907
null
class Client(object): """ Asynchronous DynamoDB Client :keyword str region: AWS region to send requests to :keyword str access_key: AWS access key. If unspecified, this defaults to the :envvar:`AWS_ACCESS_KEY_ID` environment variable and will fall back to using the AWS CLI credentials ...
sprockets/sprockets-dynamodb
sprockets_dynamodb/client.py
Client._process_response
python
def _process_response(response): error = response.exception() if error: if isinstance(error, aws_exceptions.AWSError): if error.args[1]['type'] in exceptions.MAP: raise exceptions.MAP[error.args[1]['type']]( error.args[1]['message']...
Process the raw AWS response, returning either the mapped exception or deserialized response. :param tornado.concurrent.Future response: The request future :rtype: dict or list :raises: sprockets_dynamodb.exceptions.DynamoDBException
train
https://github.com/sprockets/sprockets-dynamodb/blob/2e202bcb01f23f828f91299599311007054de4aa/sprockets_dynamodb/client.py#L910-L929
null
class Client(object): """ Asynchronous DynamoDB Client :keyword str region: AWS region to send requests to :keyword str access_key: AWS access key. If unspecified, this defaults to the :envvar:`AWS_ACCESS_KEY_ID` environment variable and will fall back to using the AWS CLI credentials ...
Danielhiversen/pymill
mill/__init__.py
set_heater_values
python
async def set_heater_values(heater_data, heater): heater.current_temp = heater_data.get('currentTemp') heater.device_status = heater_data.get('deviceStatus') heater.available = heater.device_status == 0 heater.name = heater_data.get('deviceName') heater.fan_status = heater_data.get('fanStatus') ...
Set heater values from heater data
train
https://github.com/Danielhiversen/pymill/blob/f091385914b53682012d0948c549beb4a5a96794/mill/__init__.py#L445-L488
null
"""Library to handle connection with mill.""" # Based on https://pastebin.com/53Nk0wJA and Postman capturing from the app # All requests are send unencrypted from the app :( import asyncio import datetime as dt import hashlib import json import logging import random import string import time import aiohttp import asyn...
Danielhiversen/pymill
mill/__init__.py
Mill.connect
python
async def connect(self, retry=2): # pylint: disable=too-many-return-statements url = API_ENDPOINT_1 + 'login' headers = { "Content-Type": "application/x-zc-object", "Connection": "Keep-Alive", "X-Zc-Major-Domain": "seanywell", "X-Zc-Msg-Name": "mil...
Connect to Mill.
train
https://github.com/Danielhiversen/pymill/blob/f091385914b53682012d0948c549beb4a5a96794/mill/__init__.py#L52-L100
[ "async def connect(self, retry=2):\n \"\"\"Connect to Mill.\"\"\"\n # pylint: disable=too-many-return-statements\n url = API_ENDPOINT_1 + 'login'\n headers = {\n \"Content-Type\": \"application/x-zc-object\",\n \"Connection\": \"Keep-Alive\",\n \"X-Zc-Major-Domain\": \"seanywell\",\...
class Mill: """Class to comunicate with the Mill api.""" # pylint: disable=too-many-instance-attributes, too-many-public-methods def __init__(self, username, password, timeout=DEFAULT_TIMEOUT, websession=None): """Initialize the Mill connection.""" if webs...
Danielhiversen/pymill
mill/__init__.py
Mill.sync_connect
python
def sync_connect(self): loop = asyncio.get_event_loop() task = loop.create_task(self.connect()) loop.run_until_complete(task)
Close the Mill connection.
train
https://github.com/Danielhiversen/pymill/blob/f091385914b53682012d0948c549beb4a5a96794/mill/__init__.py#L102-L106
[ "async def connect(self, retry=2):\n \"\"\"Connect to Mill.\"\"\"\n # pylint: disable=too-many-return-statements\n url = API_ENDPOINT_1 + 'login'\n headers = {\n \"Content-Type\": \"application/x-zc-object\",\n \"Connection\": \"Keep-Alive\",\n \"X-Zc-Major-Domain\": \"seanywell\",\...
class Mill: """Class to comunicate with the Mill api.""" # pylint: disable=too-many-instance-attributes, too-many-public-methods def __init__(self, username, password, timeout=DEFAULT_TIMEOUT, websession=None): """Initialize the Mill connection.""" if webs...
Danielhiversen/pymill
mill/__init__.py
Mill.sync_close_connection
python
def sync_close_connection(self): loop = asyncio.get_event_loop() task = loop.create_task(self.close_connection()) loop.run_until_complete(task)
Close the Mill connection.
train
https://github.com/Danielhiversen/pymill/blob/f091385914b53682012d0948c549beb4a5a96794/mill/__init__.py#L112-L116
[ "async def close_connection(self):\n \"\"\"Close the Mill connection.\"\"\"\n await self.websession.close()\n" ]
class Mill: """Class to comunicate with the Mill api.""" # pylint: disable=too-many-instance-attributes, too-many-public-methods def __init__(self, username, password, timeout=DEFAULT_TIMEOUT, websession=None): """Initialize the Mill connection.""" if webs...
Danielhiversen/pymill
mill/__init__.py
Mill.request
python
async def request(self, command, payload, retry=3): # pylint: disable=too-many-return-statements if self._token is None: _LOGGER.error("No token") return None _LOGGER.debug(command, payload) nonce = ''.join(random.choice(string.ascii_uppercase + string.digits) ...
Request data.
train
https://github.com/Danielhiversen/pymill/blob/f091385914b53682012d0948c549beb4a5a96794/mill/__init__.py#L118-L191
[ "async def request(self, command, payload, retry=3):\n \"\"\"Request data.\"\"\"\n # pylint: disable=too-many-return-statements\n\n if self._token is None:\n _LOGGER.error(\"No token\")\n return None\n\n _LOGGER.debug(command, payload)\n\n nonce = ''.join(random.choice(string.ascii_uppe...
class Mill: """Class to comunicate with the Mill api.""" # pylint: disable=too-many-instance-attributes, too-many-public-methods def __init__(self, username, password, timeout=DEFAULT_TIMEOUT, websession=None): """Initialize the Mill connection.""" if webs...
Danielhiversen/pymill
mill/__init__.py
Mill.sync_request
python
def sync_request(self, command, payload, retry=2): loop = asyncio.get_event_loop() task = loop.create_task(self.request(command, payload, retry)) return loop.run_until_complete(task)
Request data.
train
https://github.com/Danielhiversen/pymill/blob/f091385914b53682012d0948c549beb4a5a96794/mill/__init__.py#L193-L197
[ "async def request(self, command, payload, retry=3):\n \"\"\"Request data.\"\"\"\n # pylint: disable=too-many-return-statements\n\n if self._token is None:\n _LOGGER.error(\"No token\")\n return None\n\n _LOGGER.debug(command, payload)\n\n nonce = ''.join(random.choice(string.ascii_uppe...
class Mill: """Class to comunicate with the Mill api.""" # pylint: disable=too-many-instance-attributes, too-many-public-methods def __init__(self, username, password, timeout=DEFAULT_TIMEOUT, websession=None): """Initialize the Mill connection.""" if webs...
Danielhiversen/pymill
mill/__init__.py
Mill.update_rooms
python
async def update_rooms(self): homes = await self.get_home_list() for home in homes: payload = {"homeId": home.get("homeId"), "timeZoneNum": "+01:00"} data = await self.request("selectRoombyHome", payload) rooms = data.get('roomInfo', []) for _room in rooms...
Request data.
train
https://github.com/Danielhiversen/pymill/blob/f091385914b53682012d0948c549beb4a5a96794/mill/__init__.py#L206-L241
[ "async def request(self, command, payload, retry=3):\n \"\"\"Request data.\"\"\"\n # pylint: disable=too-many-return-statements\n\n if self._token is None:\n _LOGGER.error(\"No token\")\n return None\n\n _LOGGER.debug(command, payload)\n\n nonce = ''.join(random.choice(string.ascii_uppe...
class Mill: """Class to comunicate with the Mill api.""" # pylint: disable=too-many-instance-attributes, too-many-public-methods def __init__(self, username, password, timeout=DEFAULT_TIMEOUT, websession=None): """Initialize the Mill connection.""" if webs...
Danielhiversen/pymill
mill/__init__.py
Mill.sync_update_rooms
python
def sync_update_rooms(self): loop = asyncio.get_event_loop() task = loop.create_task(self.update_rooms()) return loop.run_until_complete(task)
Request data.
train
https://github.com/Danielhiversen/pymill/blob/f091385914b53682012d0948c549beb4a5a96794/mill/__init__.py#L243-L247
[ "async def update_rooms(self):\n \"\"\"Request data.\"\"\"\n homes = await self.get_home_list()\n for home in homes:\n payload = {\"homeId\": home.get(\"homeId\"), \"timeZoneNum\": \"+01:00\"}\n data = await self.request(\"selectRoombyHome\", payload)\n rooms = data.get('roomInfo', [])...
class Mill: """Class to comunicate with the Mill api.""" # pylint: disable=too-many-instance-attributes, too-many-public-methods def __init__(self, username, password, timeout=DEFAULT_TIMEOUT, websession=None): """Initialize the Mill connection.""" if webs...
Danielhiversen/pymill
mill/__init__.py
Mill.set_room_temperatures_by_name
python
async def set_room_temperatures_by_name(self, room_name, sleep_temp=None, comfort_temp=None, away_temp=None): if sleep_temp is None and comfort_temp is None and away_temp is None: return for room_id, _room in self.rooms.items(): if _roo...
Set room temps by name.
train
https://github.com/Danielhiversen/pymill/blob/f091385914b53682012d0948c549beb4a5a96794/mill/__init__.py#L249-L259
[ "async def set_room_temperatures(self, room_id, sleep_temp=None,\n comfort_temp=None, away_temp=None):\n \"\"\"Set room temps.\"\"\"\n if sleep_temp is None and comfort_temp is None and away_temp is None:\n return\n room = self.rooms.get(room_id)\n if room is None:\...
class Mill: """Class to comunicate with the Mill api.""" # pylint: disable=too-many-instance-attributes, too-many-public-methods def __init__(self, username, password, timeout=DEFAULT_TIMEOUT, websession=None): """Initialize the Mill connection.""" if webs...
Danielhiversen/pymill
mill/__init__.py
Mill.set_room_temperatures
python
async def set_room_temperatures(self, room_id, sleep_temp=None, comfort_temp=None, away_temp=None): if sleep_temp is None and comfort_temp is None and away_temp is None: return room = self.rooms.get(room_id) if room is None: _LOGGER.err...
Set room temps.
train
https://github.com/Danielhiversen/pymill/blob/f091385914b53682012d0948c549beb4a5a96794/mill/__init__.py#L261-L279
[ "async def request(self, command, payload, retry=3):\n \"\"\"Request data.\"\"\"\n # pylint: disable=too-many-return-statements\n\n if self._token is None:\n _LOGGER.error(\"No token\")\n return None\n\n _LOGGER.debug(command, payload)\n\n nonce = ''.join(random.choice(string.ascii_uppe...
class Mill: """Class to comunicate with the Mill api.""" # pylint: disable=too-many-instance-attributes, too-many-public-methods def __init__(self, username, password, timeout=DEFAULT_TIMEOUT, websession=None): """Initialize the Mill connection.""" if webs...
Danielhiversen/pymill
mill/__init__.py
Mill.update_heaters
python
async def update_heaters(self): homes = await self.get_home_list() for home in homes: payload = {"homeId": home.get("homeId")} data = await self.request("getIndependentDevices", payload) if data is None: continue heater_data = data.get('dev...
Request data.
train
https://github.com/Danielhiversen/pymill/blob/f091385914b53682012d0948c549beb4a5a96794/mill/__init__.py#L281-L308
[ "async def request(self, command, payload, retry=3):\n \"\"\"Request data.\"\"\"\n # pylint: disable=too-many-return-statements\n\n if self._token is None:\n _LOGGER.error(\"No token\")\n return None\n\n _LOGGER.debug(command, payload)\n\n nonce = ''.join(random.choice(string.ascii_uppe...
class Mill: """Class to comunicate with the Mill api.""" # pylint: disable=too-many-instance-attributes, too-many-public-methods def __init__(self, username, password, timeout=DEFAULT_TIMEOUT, websession=None): """Initialize the Mill connection.""" if webs...
Danielhiversen/pymill
mill/__init__.py
Mill.sync_update_heaters
python
def sync_update_heaters(self): loop = asyncio.get_event_loop() task = loop.create_task(self.update_heaters()) loop.run_until_complete(task)
Request data.
train
https://github.com/Danielhiversen/pymill/blob/f091385914b53682012d0948c549beb4a5a96794/mill/__init__.py#L310-L314
[ "async def update_heaters(self):\n \"\"\"Request data.\"\"\"\n homes = await self.get_home_list()\n for home in homes:\n payload = {\"homeId\": home.get(\"homeId\")}\n data = await self.request(\"getIndependentDevices\", payload)\n if data is None:\n continue\n heater...
class Mill: """Class to comunicate with the Mill api.""" # pylint: disable=too-many-instance-attributes, too-many-public-methods def __init__(self, username, password, timeout=DEFAULT_TIMEOUT, websession=None): """Initialize the Mill connection.""" if webs...
Danielhiversen/pymill
mill/__init__.py
Mill.throttle_update_heaters
python
async def throttle_update_heaters(self): if (self._throttle_time is not None and dt.datetime.now() - self._throttle_time < MIN_TIME_BETWEEN_UPDATES): return self._throttle_time = dt.datetime.now() await self.update_heaters()
Throttle update device.
train
https://github.com/Danielhiversen/pymill/blob/f091385914b53682012d0948c549beb4a5a96794/mill/__init__.py#L316-L322
[ "async def update_heaters(self):\n \"\"\"Request data.\"\"\"\n homes = await self.get_home_list()\n for home in homes:\n payload = {\"homeId\": home.get(\"homeId\")}\n data = await self.request(\"getIndependentDevices\", payload)\n if data is None:\n continue\n heater...
class Mill: """Class to comunicate with the Mill api.""" # pylint: disable=too-many-instance-attributes, too-many-public-methods def __init__(self, username, password, timeout=DEFAULT_TIMEOUT, websession=None): """Initialize the Mill connection.""" if webs...
Danielhiversen/pymill
mill/__init__.py
Mill.throttle_update_all_heaters
python
async def throttle_update_all_heaters(self): if (self._throttle_all_time is not None and dt.datetime.now() - self._throttle_all_time < MIN_TIME_BETWEEN_UPDATES): return self._throttle_all_time = dt.datetime.now() await self.find_all_heaters()
Throttle update all devices and rooms.
train
https://github.com/Danielhiversen/pymill/blob/f091385914b53682012d0948c549beb4a5a96794/mill/__init__.py#L324-L331
[ "async def find_all_heaters(self):\n \"\"\"Find all heaters.\"\"\"\n await self.update_rooms()\n await self.update_heaters()\n" ]
class Mill: """Class to comunicate with the Mill api.""" # pylint: disable=too-many-instance-attributes, too-many-public-methods def __init__(self, username, password, timeout=DEFAULT_TIMEOUT, websession=None): """Initialize the Mill connection.""" if webs...
Danielhiversen/pymill
mill/__init__.py
Mill.heater_control
python
async def heater_control(self, device_id, fan_status=None, power_status=None): heater = self.heaters.get(device_id) if heater is None: _LOGGER.error("No such device") return if fan_status is None: fan_status = heater.fan_status ...
Set heater temps.
train
https://github.com/Danielhiversen/pymill/blob/f091385914b53682012d0948c549beb4a5a96794/mill/__init__.py#L343-L364
[ "async def request(self, command, payload, retry=3):\n \"\"\"Request data.\"\"\"\n # pylint: disable=too-many-return-statements\n\n if self._token is None:\n _LOGGER.error(\"No token\")\n return None\n\n _LOGGER.debug(command, payload)\n\n nonce = ''.join(random.choice(string.ascii_uppe...
class Mill: """Class to comunicate with the Mill api.""" # pylint: disable=too-many-instance-attributes, too-many-public-methods def __init__(self, username, password, timeout=DEFAULT_TIMEOUT, websession=None): """Initialize the Mill connection.""" if webs...
Danielhiversen/pymill
mill/__init__.py
Mill.sync_heater_control
python
def sync_heater_control(self, device_id, fan_status=None, power_status=None): loop = asyncio.get_event_loop() task = loop.create_task(self.heater_control(device_id, fan_status, ...
Set heater temps.
train
https://github.com/Danielhiversen/pymill/blob/f091385914b53682012d0948c549beb4a5a96794/mill/__init__.py#L366-L373
[ "async def heater_control(self, device_id, fan_status=None,\n power_status=None):\n \"\"\"Set heater temps.\"\"\"\n heater = self.heaters.get(device_id)\n if heater is None:\n _LOGGER.error(\"No such device\")\n return\n if fan_status is None:\n fan_status = ...
class Mill: """Class to comunicate with the Mill api.""" # pylint: disable=too-many-instance-attributes, too-many-public-methods def __init__(self, username, password, timeout=DEFAULT_TIMEOUT, websession=None): """Initialize the Mill connection.""" if webs...
Danielhiversen/pymill
mill/__init__.py
Mill.set_heater_temp
python
async def set_heater_temp(self, device_id, set_temp): payload = {"homeType": 0, "timeZoneNum": "+02:00", "deviceId": device_id, "value": int(set_temp), "key": "holidayTemp"} await self.request("changeDeviceInfo", payload)
Set heater temp.
train
https://github.com/Danielhiversen/pymill/blob/f091385914b53682012d0948c549beb4a5a96794/mill/__init__.py#L375-L382
[ "async def request(self, command, payload, retry=3):\n \"\"\"Request data.\"\"\"\n # pylint: disable=too-many-return-statements\n\n if self._token is None:\n _LOGGER.error(\"No token\")\n return None\n\n _LOGGER.debug(command, payload)\n\n nonce = ''.join(random.choice(string.ascii_uppe...
class Mill: """Class to comunicate with the Mill api.""" # pylint: disable=too-many-instance-attributes, too-many-public-methods def __init__(self, username, password, timeout=DEFAULT_TIMEOUT, websession=None): """Initialize the Mill connection.""" if webs...
Danielhiversen/pymill
mill/__init__.py
Mill.sync_set_heater_temp
python
def sync_set_heater_temp(self, device_id, set_temp): loop = asyncio.get_event_loop() task = loop.create_task(self.set_heater_temp(device_id, set_temp)) loop.run_until_complete(task)
Set heater temps.
train
https://github.com/Danielhiversen/pymill/blob/f091385914b53682012d0948c549beb4a5a96794/mill/__init__.py#L384-L388
[ "async def set_heater_temp(self, device_id, set_temp):\n \"\"\"Set heater temp.\"\"\"\n payload = {\"homeType\": 0,\n \"timeZoneNum\": \"+02:00\",\n \"deviceId\": device_id,\n \"value\": int(set_temp),\n \"key\": \"holidayTemp\"}\n await self.request(...
class Mill: """Class to comunicate with the Mill api.""" # pylint: disable=too-many-instance-attributes, too-many-public-methods def __init__(self, username, password, timeout=DEFAULT_TIMEOUT, websession=None): """Initialize the Mill connection.""" if webs...
internetarchive/warc
warc/__init__.py
open
python
def open(filename, mode="rb", format = None): if format == "auto" or format == None: format = detect_format(filename) if format == "warc": return WARCFile(filename, mode) elif format == "arc": return ARCFile(filename, mode) else: raise IOError("Don't know how to open '%s...
Shorthand for WARCFile(filename, mode). Auto detects file and opens it.
train
https://github.com/internetarchive/warc/blob/8f05a000a23bbd6501217e37cfd862ffdf19da7f/warc/__init__.py#L24-L38
[ "def detect_format(filename):\n \"\"\"Tries to figure out the type of the file. Return 'warc' for\n WARC files and 'arc' for ARC files\"\"\"\n\n if \".arc\" in filename:\n return \"arc\"\n if \".warc\" in filename:\n return \"warc\"\n\n return \"unknown\"\n" ]
""" warc ~~~~ Python library to work with WARC files. :copyright: (c) 2012 Internet Archive """ from .arc import ARCFile, ARCRecord, ARCHeader from .warc import WARCFile, WARCRecord, WARCHeader, WARCReader def detect_format(filename): """Tries to figure out the type of the file. Return 'warc' for WARC files...
internetarchive/warc
warc/warc.py
WARCHeader.init_defaults
python
def init_defaults(self): if "WARC-Record-ID" not in self: self['WARC-Record-ID'] = "<urn:uuid:%s>" % uuid.uuid1() if "WARC-Date" not in self: self['WARC-Date'] = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ') if "Content-Type" not in self: self['Con...
Initializes important headers to default values, if not already specified. The WARC-Record-ID header is set to a newly generated UUID. The WARC-Date header is set to the current datetime. The Content-Type is set based on the WARC-Type header. The Content-Length is initialized to...
train
https://github.com/internetarchive/warc/blob/8f05a000a23bbd6501217e37cfd862ffdf19da7f/warc/warc.py#L75-L88
null
class WARCHeader(CaseInsensitiveDict): """The WARC Header object represents the headers of a WARC record. It provides dictionary like interface for accessing the headers. The following mandatory fields are accessible also as attributes. * h.record_id == h['WARC-Record-ID'] * h.content...
internetarchive/warc
warc/warc.py
WARCHeader.write_to
python
def write_to(self, f): f.write(self.version + "\r\n") for name, value in self.items(): name = name.title() # Use standard forms for commonly used patterns name = name.replace("Warc-", "WARC-").replace("-Ip-", "-IP-").replace("-Id", "-ID").replace("-Uri", "-URI") ...
Writes this header to a file, in the format specified by WARC.
train
https://github.com/internetarchive/warc/blob/8f05a000a23bbd6501217e37cfd862ffdf19da7f/warc/warc.py#L90-L104
null
class WARCHeader(CaseInsensitiveDict): """The WARC Header object represents the headers of a WARC record. It provides dictionary like interface for accessing the headers. The following mandatory fields are accessible also as attributes. * h.record_id == h['WARC-Record-ID'] * h.content...
internetarchive/warc
warc/warc.py
WARCRecord.from_response
python
def from_response(response): # Get the httplib.HTTPResponse object http_response = response.raw._original_response # HTTP status line, headers and body as strings status_line = "HTTP/1.1 %d %s" % (http_response.status, http_response.reason) headers = str(http_response.ms...
Creates a WARCRecord from given response object. This must be called before reading the response. The response can be read after this method is called. :param response: An instance of :class:`requests.models.Response`.
train
https://github.com/internetarchive/warc/blob/8f05a000a23bbd6501217e37cfd862ffdf19da7f/warc/warc.py#L216-L242
null
class WARCRecord(object): """The WARCRecord object represents a WARC Record. """ def __init__(self, header=None, payload=None, headers={}, defaults=True): """Creates a new WARC record. """ if header is None and defaults is True: headers.setdefault("WARC-Type", "respons...
internetarchive/warc
warc/warc.py
WARCFile.write_record
python
def write_record(self, warc_record): warc_record.write_to(self.fileobj) # Each warc record is written as separate member in the gzip file # so that each record can be read independetly. if isinstance(self.fileobj, gzip2.GzipFile): self.fileobj.close_member()
Adds a warc record to this WARC file.
train
https://github.com/internetarchive/warc/blob/8f05a000a23bbd6501217e37cfd862ffdf19da7f/warc/warc.py#L265-L272
[ "def close_member(self):\n \"\"\"Closes the current member being written.\n \"\"\"\n # The new member is not yet started, no need to close\n if self._new_member:\n return\n\n self.fileobj.write(self.compress.flush())\n write32u(self.fileobj, self.crc)\n # self.size may exceed 2GB, or eve...
class WARCFile: def __init__(self, filename=None, mode=None, fileobj=None, compress=None): if fileobj is None: fileobj = __builtin__.open(filename, mode or "rb") mode = fileobj.mode # initiaize compress based on filename, if not already specified if compress is None a...
internetarchive/warc
warc/warc.py
WARCFile.browse
python
def browse(self): offset = 0 for record in self.reader: # Just read the first 1MB of the payload. # This will make sure memory consuption is under control and it # is possible to look at the first MB of the payload, which is # typically sufficient to rea...
Utility to browse through the records in the warc file. This returns an iterator over (record, offset, size) for each record in the file. If the file is gzip compressed, the offset and size will corresponds to the compressed file. The payload of each record is limite...
train
https://github.com/internetarchive/warc/blob/8f05a000a23bbd6501217e37cfd862ffdf19da7f/warc/warc.py#L284-L304
[ "def tell(self):\n \"\"\"Returns the file offset. If this is a compressed file, then the \n offset in the compressed file is returned.\n \"\"\"\n if isinstance(self.fileobj, gzip2.GzipFile):\n return self.fileobj.fileobj.tell()\n else:\n return self.fileobj.tell() \n" ]
class WARCFile: def __init__(self, filename=None, mode=None, fileobj=None, compress=None): if fileobj is None: fileobj = __builtin__.open(filename, mode or "rb") mode = fileobj.mode # initiaize compress based on filename, if not already specified if compress is None a...
internetarchive/warc
warc/warc.py
WARCFile.tell
python
def tell(self): if isinstance(self.fileobj, gzip2.GzipFile): return self.fileobj.fileobj.tell() else: return self.fileobj.tell()
Returns the file offset. If this is a compressed file, then the offset in the compressed file is returned.
train
https://github.com/internetarchive/warc/blob/8f05a000a23bbd6501217e37cfd862ffdf19da7f/warc/warc.py#L306-L313
null
class WARCFile: def __init__(self, filename=None, mode=None, fileobj=None, compress=None): if fileobj is None: fileobj = __builtin__.open(filename, mode or "rb") mode = fileobj.mode # initiaize compress based on filename, if not already specified if compress is None a...
internetarchive/warc
warc/gzip2.py
GzipFile.close_member
python
def close_member(self): # The new member is not yet started, no need to close if self._new_member: return self.fileobj.write(self.compress.flush()) write32u(self.fileobj, self.crc) # self.size may exceed 2GB, or even 4GB write32u(self.fileobj, sel...
Closes the current member being written.
train
https://github.com/internetarchive/warc/blob/8f05a000a23bbd6501217e37cfd862ffdf19da7f/warc/gzip2.py#L42-L59
null
class GzipFile(BaseGzipFile): """GzipFile with support for multi-member gzip files. """ def __init__(self, filename=None, mode=None, compresslevel=9, fileobj=None): BaseGzipFile.__init__(self, filename=filename, mode=mode, compresslevel=compres...
internetarchive/warc
warc/gzip2.py
GzipFile._start_member
python
def _start_member(self): if self._new_member: self._init_write(self.name) self._write_gzip_header() self._new_member = False
Starts writing a new member if required.
train
https://github.com/internetarchive/warc/blob/8f05a000a23bbd6501217e37cfd862ffdf19da7f/warc/gzip2.py#L61-L67
null
class GzipFile(BaseGzipFile): """GzipFile with support for multi-member gzip files. """ def __init__(self, filename=None, mode=None, compresslevel=9, fileobj=None): BaseGzipFile.__init__(self, filename=filename, mode=mode, compresslevel=compres...
internetarchive/warc
warc/gzip2.py
GzipFile.close
python
def close(self): if self.fileobj is None: return if self.mode == WRITE: self.close_member() self.fileobj = None elif self.mode == READ: self.fileobj = None if self.myfileobj: self.myfileobj.close() self....
Closes the gzip with care to handle multiple members.
train
https://github.com/internetarchive/warc/blob/8f05a000a23bbd6501217e37cfd862ffdf19da7f/warc/gzip2.py#L73-L86
[ "def close_member(self):\n \"\"\"Closes the current member being written.\n \"\"\"\n # The new member is not yet started, no need to close\n if self._new_member:\n return\n\n self.fileobj.write(self.compress.flush())\n write32u(self.fileobj, self.crc)\n # self.size may exceed 2GB, or eve...
class GzipFile(BaseGzipFile): """GzipFile with support for multi-member gzip files. """ def __init__(self, filename=None, mode=None, compresslevel=9, fileobj=None): BaseGzipFile.__init__(self, filename=filename, mode=mode, compresslevel=compres...
internetarchive/warc
warc/gzip2.py
GzipFile.read_member
python
def read_member(self): if self._member_lock is False: self._member_lock = True if self._new_member: try: # Read one byte to move to the next member BaseGzipFile._read(self, 1) assert self._new_member is False except EOF...
Returns a file-like object to read one member from the gzip file.
train
https://github.com/internetarchive/warc/blob/8f05a000a23bbd6501217e37cfd862ffdf19da7f/warc/gzip2.py#L95-L109
null
class GzipFile(BaseGzipFile): """GzipFile with support for multi-member gzip files. """ def __init__(self, filename=None, mode=None, compresslevel=9, fileobj=None): BaseGzipFile.__init__(self, filename=filename, mode=mode, compresslevel=compres...
internetarchive/warc
warc/gzip2.py
GzipFile.write_member
python
def write_member(self, data): if isinstance(data, basestring): self.write(data) else: for text in data: self.write(text) self.close_member()
Writes the given data as one gzip member. The data can be a string, an iterator that gives strings or a file-like object.
train
https://github.com/internetarchive/warc/blob/8f05a000a23bbd6501217e37cfd862ffdf19da7f/warc/gzip2.py#L111-L121
[ "def write(self, data):\n self._start_member()\n BaseGzipFile.write(self, data)\n", "def close_member(self):\n \"\"\"Closes the current member being written.\n \"\"\"\n # The new member is not yet started, no need to close\n if self._new_member:\n return\n\n self.fileobj.write(self.com...
class GzipFile(BaseGzipFile): """GzipFile with support for multi-member gzip files. """ def __init__(self, filename=None, mode=None, compresslevel=9, fileobj=None): BaseGzipFile.__init__(self, filename=filename, mode=mode, compresslevel=compres...
internetarchive/warc
warc/arc.py
ARCHeader.write_to
python
def write_to(self, f, version = None): if not version: version = self.version if version == 1: header = "%(url)s %(ip_address)s %(date)s %(content_type)s %(length)s" elif version == 2: header = "%(url)s %(ip_address)s %(date)s %(content_type)s %(result_code)s ...
Writes out the arc header to the file like object `f`. If the version field is 1, it writes out an arc v1 header, otherwise (and this is default), it outputs a v2 header.
train
https://github.com/internetarchive/warc/blob/8f05a000a23bbd6501217e37cfd862ffdf19da7f/warc/arc.py#L69-L94
null
class ARCHeader(CaseInsensitiveDict): """ Holds fields from an ARC V1 or V2 header. V1 header fields are * url * ip_address * date * content_type * length (length of the n/w doc in bytes) V2 header fields are * url * ip_address * date (...
internetarchive/warc
warc/arc.py
ARCRecord.from_string
python
def from_string(cls, string, version): header, payload = string.split("\n",1) if payload[0] == '\n': # There's an extra payload = payload[1:] if int(version) == 1: arc_header_re = ARC1_HEADER_RE elif int(version) == 2: arc_header_re = ARC2_HEADER_RE ...
Constructs an ARC record from a string and returns it. TODO: It might be best to merge this with the _read_arc_record function rather than reimplement the functionality here.
train
https://github.com/internetarchive/warc/blob/8f05a000a23bbd6501217e37cfd862ffdf19da7f/warc/arc.py#L161-L179
null
class ARCRecord(object): def __init__(self, header = None, payload = None, headers = {}, version = None): if not (header or headers): raise TypeError("Can't write create an ARC1 record without a header") self.header = header or ARCHeader(version = version, **headers) self.payload...
internetarchive/warc
warc/arc.py
ARCFile._write_header
python
def _write_header(self): "Writes out an ARC header" if "org" not in self.file_headers: warnings.warn("Using 'unknown' for Archiving organisation name") self.file_headers['org'] = "Unknown" if "date" not in self.file_headers: now = datetime.datetime.utcnow() ...
Writes out an ARC header
train
https://github.com/internetarchive/warc/blob/8f05a000a23bbd6501217e37cfd862ffdf19da7f/warc/arc.py#L264-L295
[ "def write(self, arc_record):\n \"Writes out the given arc record to the file\"\n if not self.version:\n self.version = 2\n if not self.header_written:\n self.header_written = True\n self._write_header()\n arc_record.write_to(self.fileobj, self.version)\n self.fileobj.write(\"\\n...
class ARCFile(object): def __init__(self, filename=None, mode=None, fileobj=None, version = None, file_headers = {}): """ Initialises a file like object that can be used to read or write Arc files. Works for both version 1 or version 2. This can be called similar to the builtin `fil...
internetarchive/warc
warc/arc.py
ARCFile.write
python
def write(self, arc_record): "Writes out the given arc record to the file" if not self.version: self.version = 2 if not self.header_written: self.header_written = True self._write_header() arc_record.write_to(self.fileobj, self.version) self.fi...
Writes out the given arc record to the file
train
https://github.com/internetarchive/warc/blob/8f05a000a23bbd6501217e37cfd862ffdf19da7f/warc/arc.py#L297-L305
[ "def write_to(self, f, version = None):\n version = version or self.version or 2\n self.header.write_to(f, version)\n f.write(\"\\n\") # This separates the header and the body\n if isinstance(self.payload, str): #Usually used for small payloads\n f.write(self.payload)\n elif hasattr(self.paylo...
class ARCFile(object): def __init__(self, filename=None, mode=None, fileobj=None, version = None, file_headers = {}): """ Initialises a file like object that can be used to read or write Arc files. Works for both version 1 or version 2. This can be called similar to the builtin `fil...
internetarchive/warc
warc/arc.py
ARCFile._read_file_header
python
def _read_file_header(self): header = self.fileobj.readline() payload1 = self.fileobj.readline() payload2 = self.fileobj.readline() version, reserved, organisation = payload1.split(None, 2) self.fileobj.readline() # Lose the separator newline self.header_read = True ...
Reads out the file header for the arc file. If version was not provided, this will autopopulate it.
train
https://github.com/internetarchive/warc/blob/8f05a000a23bbd6501217e37cfd862ffdf19da7f/warc/arc.py#L307-L335
null
class ARCFile(object): def __init__(self, filename=None, mode=None, fileobj=None, version = None, file_headers = {}): """ Initialises a file like object that can be used to read or write Arc files. Works for both version 1 or version 2. This can be called similar to the builtin `fil...
internetarchive/warc
warc/arc.py
ARCFile._read_arc_record
python
def _read_arc_record(self): "Reads out an arc record, formats it and returns it" #XXX:Noufal Stream payload here rather than just read it # r = self.fileobj.readline() # Drop the initial newline # if r == "": # return None # header = self.fileobj.readline() #...
Reads out an arc record, formats it and returns it
train
https://github.com/internetarchive/warc/blob/8f05a000a23bbd6501217e37cfd862ffdf19da7f/warc/arc.py#L337-L366
null
class ARCFile(object): def __init__(self, filename=None, mode=None, fileobj=None, version = None, file_headers = {}): """ Initialises a file like object that can be used to read or write Arc files. Works for both version 1 or version 2. This can be called similar to the builtin `fil...
peterldowns/lggr
lggr/__init__.py
Printer
python
def Printer(open_file=sys.stdout, closing=False): try: while True: logstr = (yield) open_file.write(logstr) open_file.write('\n') # new line except GeneratorExit: if closing: try: open_file.close() except: pass
Prints items with a timestamp.
train
https://github.com/peterldowns/lggr/blob/622968f17133e02d9a46a4900dd20fb3b19fe961/lggr/__init__.py#L322-L332
null
# coding: utf-8 """ TODO: add a docstring. """ import os import sys import time import inspect import traceback from lggr.coroutine import coroutine, coroutine_process, coroutine_thread __version__ = '0.2.2' DEBUG = 'DEBUG' INFO = 'INFO' WARNING = 'WARNING' ERROR = 'ERROR' CRITICAL = 'CRITICAL' ALL = (DEBUG, INFO, W...
peterldowns/lggr
lggr/__init__.py
FilePrinter
python
def FilePrinter(filename, mode='a', closing=True): path = os.path.abspath(os.path.expanduser(filename)) f = open(path, mode) return Printer(f, closing)
Opens the given file and returns a printer to it.
train
https://github.com/peterldowns/lggr/blob/622968f17133e02d9a46a4900dd20fb3b19fe961/lggr/__init__.py#L338-L342
[ "def wrapper(*args, **kwargs):\n cp = CoroutineProcess(func)\n cp = cp(*args, **kwargs)\n # XXX(todo): use @CoroutineProcess on an individual function, then wrap\n # with @coroutine, too. Don't start until .next().\n return cp\n" ]
# coding: utf-8 """ TODO: add a docstring. """ import os import sys import time import inspect import traceback from lggr.coroutine import coroutine, coroutine_process, coroutine_thread __version__ = '0.2.2' DEBUG = 'DEBUG' INFO = 'INFO' WARNING = 'WARNING' ERROR = 'ERROR' CRITICAL = 'CRITICAL' ALL = (DEBUG, INFO, W...
peterldowns/lggr
lggr/__init__.py
SocketWriter
python
def SocketWriter(host, port, af=None, st=None): import socket if af is None: af = socket.AF_INET if st is None: st = socket.SOCK_STREAM message = '({0}): {1}' s = socket.socket(af, st) s.connect(host, port) try: while True: logstr = (yield) s.s...
Writes messages to a socket/host.
train
https://github.com/peterldowns/lggr/blob/622968f17133e02d9a46a4900dd20fb3b19fe961/lggr/__init__.py#L345-L360
null
# coding: utf-8 """ TODO: add a docstring. """ import os import sys import time import inspect import traceback from lggr.coroutine import coroutine, coroutine_process, coroutine_thread __version__ = '0.2.2' DEBUG = 'DEBUG' INFO = 'INFO' WARNING = 'WARNING' ERROR = 'ERROR' CRITICAL = 'CRITICAL' ALL = (DEBUG, INFO, W...
peterldowns/lggr
lggr/__init__.py
Emailer
python
def Emailer(recipients, sender=None): import smtplib hostname = socket.gethostname() if not sender: sender = 'lggr@{0}'.format(hostname) smtp = smtplib.SMTP('localhost') try: while True: logstr = (yield) try: smtp.sendmail(sender, recipients, l...
Sends messages as emails to the given list of recipients.
train
https://github.com/peterldowns/lggr/blob/622968f17133e02d9a46a4900dd20fb3b19fe961/lggr/__init__.py#L363-L379
null
# coding: utf-8 """ TODO: add a docstring. """ import os import sys import time import inspect import traceback from lggr.coroutine import coroutine, coroutine_process, coroutine_thread __version__ = '0.2.2' DEBUG = 'DEBUG' INFO = 'INFO' WARNING = 'WARNING' ERROR = 'ERROR' CRITICAL = 'CRITICAL' ALL = (DEBUG, INFO, W...
peterldowns/lggr
lggr/__init__.py
GMailer
python
def GMailer(recipients, username, password, subject='Log message from lggr.py'): import smtplib srvr = smtplib.SMTP('smtp.gmail.com', 587) srvr.ehlo() srvr.starttls() srvr.ehlo() srvr.login(username, password) if not (isinstance(recipients, list) or isinstance(recipients, tuple)): r...
Sends messages as emails to the given list of recipients, from a GMail account.
train
https://github.com/peterldowns/lggr/blob/622968f17133e02d9a46a4900dd20fb3b19fe961/lggr/__init__.py#L382-L407
null
# coding: utf-8 """ TODO: add a docstring. """ import os import sys import time import inspect import traceback from lggr.coroutine import coroutine, coroutine_process, coroutine_thread __version__ = '0.2.2' DEBUG = 'DEBUG' INFO = 'INFO' WARNING = 'WARNING' ERROR = 'ERROR' CRITICAL = 'CRITICAL' ALL = (DEBUG, INFO, W...
peterldowns/lggr
lggr/__init__.py
Lggr.add
python
def add(self, levels, logger): if isinstance(levels, (list, tuple)): for lvl in levels: self.config[lvl].add(logger) else: self.config[levels].add(logger)
Given a list or tuple of logging levels, add a logger instance to each.
train
https://github.com/peterldowns/lggr/blob/622968f17133e02d9a46a4900dd20fb3b19fe961/lggr/__init__.py#L84-L91
null
class Lggr(): """ Simplified logging. Dispatches messages to any type of logging function you want to write, all it has to support is send() and close(). """ def __init__(self, defaultfmt=None, keep_history=False, suppress_errors=True): self.default...
peterldowns/lggr
lggr/__init__.py
Lggr.remove
python
def remove(self, level, logger): self.config[level].discard(logger) logger.close()
Given a level, remove a given logger function if it is a member of that level, closing the logger function either way.
train
https://github.com/peterldowns/lggr/blob/622968f17133e02d9a46a4900dd20fb3b19fe961/lggr/__init__.py#L93-L98
null
class Lggr(): """ Simplified logging. Dispatches messages to any type of logging function you want to write, all it has to support is send() and close(). """ def __init__(self, defaultfmt=None, keep_history=False, suppress_errors=True): self.default...
peterldowns/lggr
lggr/__init__.py
Lggr.clear
python
def clear(self, level): for item in self.config[level]: item.close() self.config[level].clear()
Remove all logger functions from a given level.
train
https://github.com/peterldowns/lggr/blob/622968f17133e02d9a46a4900dd20fb3b19fe961/lggr/__init__.py#L100-L104
null
class Lggr(): """ Simplified logging. Dispatches messages to any type of logging function you want to write, all it has to support is send() and close(). """ def __init__(self, defaultfmt=None, keep_history=False, suppress_errors=True): self.default...
peterldowns/lggr
lggr/__init__.py
Lggr._make_record
python
def _make_record(self, level, fmt, args, extra, exc_info, inc_stackinfo, inc_multiproc): fn = fname = '(unknown file)' lno = 0 func = '(unknown func...
Create a 'record' (a dictionary) with information to be logged.
train
https://github.com/peterldowns/lggr/blob/622968f17133e02d9a46a4900dd20fb3b19fe961/lggr/__init__.py#L106-L199
null
class Lggr(): """ Simplified logging. Dispatches messages to any type of logging function you want to write, all it has to support is send() and close(). """ def __init__(self, defaultfmt=None, keep_history=False, suppress_errors=True): self.default...
peterldowns/lggr
lggr/__init__.py
Lggr._log
python
def _log(self, level, fmt, args=None, extra=None, exc_info=None, inc_stackinfo=False, inc_multiproc=False): if not self.enabled: return # Fail silently so that logging can easily be removed log_record...
Send a log message to all of the logging functions for a given level as well as adding the message to this logger instance's history.
train
https://github.com/peterldowns/lggr/blob/622968f17133e02d9a46a4900dd20fb3b19fe961/lggr/__init__.py#L201-L234
[ "def remove(self, level, logger):\n \"\"\" Given a level, remove a given logger function\n if it is a member of that level, closing the logger\n function either way.\"\"\"\n self.config[level].discard(logger)\n logger.close()\n", "def _make_record(self,\n level,\n ...
class Lggr(): """ Simplified logging. Dispatches messages to any type of logging function you want to write, all it has to support is send() and close(). """ def __init__(self, defaultfmt=None, keep_history=False, suppress_errors=True): self.default...
peterldowns/lggr
lggr/__init__.py
Lggr.log
python
def log(self, *args, **kwargs): if self.suppress_errors: try: self._log(*args, **kwargs) return True except: return False else: self._log(*args, **kwargs) return True
Do logging, but handle error suppression.
train
https://github.com/peterldowns/lggr/blob/622968f17133e02d9a46a4900dd20fb3b19fe961/lggr/__init__.py#L236-L246
[ "def _log(self,\n level,\n fmt,\n args=None,\n extra=None,\n exc_info=None,\n inc_stackinfo=False,\n inc_multiproc=False):\n \"\"\" Send a log message to all of the logging functions\n for a given level as well as adding the\n message to this ...
class Lggr(): """ Simplified logging. Dispatches messages to any type of logging function you want to write, all it has to support is send() and close(). """ def __init__(self, defaultfmt=None, keep_history=False, suppress_errors=True): self.default...
peterldowns/lggr
lggr/__init__.py
Lggr.debug
python
def debug(self, msg, *args, **kwargs): kwargs.setdefault('inc_stackinfo', True) self.log(DEBUG, msg, args, **kwargs)
Log a message with DEBUG level. Automatically includes stack info unless it is specifically not included.
train
https://github.com/peterldowns/lggr/blob/622968f17133e02d9a46a4900dd20fb3b19fe961/lggr/__init__.py#L257-L261
[ "def log(self, *args, **kwargs):\n \"\"\" Do logging, but handle error suppression. \"\"\"\n if self.suppress_errors:\n try:\n self._log(*args, **kwargs)\n return True\n except:\n return False\n else:\n self._log(*args, **kwargs)\n return True\n"...
class Lggr(): """ Simplified logging. Dispatches messages to any type of logging function you want to write, all it has to support is send() and close(). """ def __init__(self, defaultfmt=None, keep_history=False, suppress_errors=True): self.default...
peterldowns/lggr
lggr/__init__.py
Lggr.error
python
def error(self, msg, *args, **kwargs): kwargs.setdefault('inc_stackinfo', True) kwargs.setdefault('inc_multiproc', True) self.log(ERROR, msg, args, **kwargs)
Log a message with ERROR level. Automatically includes stack and process info unless they are specifically not included.
train
https://github.com/peterldowns/lggr/blob/622968f17133e02d9a46a4900dd20fb3b19fe961/lggr/__init__.py#L263-L268
[ "def log(self, *args, **kwargs):\n \"\"\" Do logging, but handle error suppression. \"\"\"\n if self.suppress_errors:\n try:\n self._log(*args, **kwargs)\n return True\n except:\n return False\n else:\n self._log(*args, **kwargs)\n return True\n"...
class Lggr(): """ Simplified logging. Dispatches messages to any type of logging function you want to write, all it has to support is send() and close(). """ def __init__(self, defaultfmt=None, keep_history=False, suppress_errors=True): self.default...
peterldowns/lggr
lggr/__init__.py
Lggr.critical
python
def critical(self, msg, *args, **kwargs): kwargs.setdefault('inc_stackinfo', True) kwargs.setdefault('inc_multiproc', True) self.log(CRITICAL, msg, args, **kwargs)
Log a message with CRITICAL level. Automatically includes stack and process info unless they are specifically not included.
train
https://github.com/peterldowns/lggr/blob/622968f17133e02d9a46a4900dd20fb3b19fe961/lggr/__init__.py#L270-L275
[ "def log(self, *args, **kwargs):\n \"\"\" Do logging, but handle error suppression. \"\"\"\n if self.suppress_errors:\n try:\n self._log(*args, **kwargs)\n return True\n except:\n return False\n else:\n self._log(*args, **kwargs)\n return True\n"...
class Lggr(): """ Simplified logging. Dispatches messages to any type of logging function you want to write, all it has to support is send() and close(). """ def __init__(self, defaultfmt=None, keep_history=False, suppress_errors=True): self.default...
peterldowns/lggr
lggr/__init__.py
Lggr.multi
python
def multi(self, lvl_list, msg, *args, **kwargs): for level in lvl_list: self.log(level, msg, args, **kwargs)
Log a message at multiple levels
train
https://github.com/peterldowns/lggr/blob/622968f17133e02d9a46a4900dd20fb3b19fe961/lggr/__init__.py#L277-L280
[ "def log(self, *args, **kwargs):\n \"\"\" Do logging, but handle error suppression. \"\"\"\n if self.suppress_errors:\n try:\n self._log(*args, **kwargs)\n return True\n except:\n return False\n else:\n self._log(*args, **kwargs)\n return True\n"...
class Lggr(): """ Simplified logging. Dispatches messages to any type of logging function you want to write, all it has to support is send() and close(). """ def __init__(self, defaultfmt=None, keep_history=False, suppress_errors=True): self.default...
peterldowns/lggr
lggr/__init__.py
Lggr.all
python
def all(self, msg, *args, **kwargs): self.multi(ALL, msg, args, **kwargs)
Log a message at every known log level
train
https://github.com/peterldowns/lggr/blob/622968f17133e02d9a46a4900dd20fb3b19fe961/lggr/__init__.py#L282-L284
[ "def multi(self, lvl_list, msg, *args, **kwargs):\n \"\"\" Log a message at multiple levels\"\"\"\n for level in lvl_list:\n self.log(level, msg, args, **kwargs)\n" ]
class Lggr(): """ Simplified logging. Dispatches messages to any type of logging function you want to write, all it has to support is send() and close(). """ def __init__(self, defaultfmt=None, keep_history=False, suppress_errors=True): self.default...
peterldowns/lggr
lggr/__init__.py
Lggr._find_caller
python
def _find_caller(self): rv = ('(unknown file)', 0, '(unknown function)', '(code not available)', [], None) f = inspect.currentframe() while hasattr(f, 'f_code'): co = f.f_code filename = os.path.normcas...
Find the stack frame of the caller so that we can note the source file name, line number, and function name.
train
https://github.com/peterldowns/lggr/blob/622968f17133e02d9a46a4900dd20fb3b19fe961/lggr/__init__.py#L286-L319
null
class Lggr(): """ Simplified logging. Dispatches messages to any type of logging function you want to write, all it has to support is send() and close(). """ def __init__(self, defaultfmt=None, keep_history=False, suppress_errors=True): self.default...
peterldowns/lggr
lggr/coroutine.py
coroutine
python
def coroutine(func): def wrapper(*args, **kwargs): c = func(*args, **kwargs) c.next() # prime it for iteration return c return wrapper
Decorator for priming co-routines that use (yield)
train
https://github.com/peterldowns/lggr/blob/622968f17133e02d9a46a4900dd20fb3b19fe961/lggr/coroutine.py#L8-L14
null
# coding: utf-8 import sys import time import Queue import threading import multiprocessing class CoroutineProcess(multiprocessing.Process): """ Will run a coroutine in its own process, using the multiprocessing library. The coroutine thread runs as a daemon, and is closed automatically when it is no long...
erikvw/django-collect-offline
django_collect_offline/transaction/transaction_deserializer.py
save
python
def save(obj=None, m2m_data=None): m2m_data = {} if m2m_data is None else m2m_data obj.save_base(raw=True) for attr, values in m2m_data.items(): for value in values: getattr(obj, attr).add(value)
Saves a deserialized model object. Uses save_base to avoid running code in model.save() and to avoid triggering signals (if raw=True).
train
https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/transaction/transaction_deserializer.py#L16-L26
null
import socket from django.apps import apps as django_apps from django_crypto_fields.constants import LOCAL_MODE from django_crypto_fields.cryptor import Cryptor from edc_device.constants import NODE_SERVER, CENTRAL_SERVER from ..constants import DELETE from .deserialize import deserialize class TransactionDeseriali...
erikvw/django-collect-offline
django_collect_offline/transaction/transaction_deserializer.py
TransactionDeserializer.deserialize_transactions
python
def deserialize_transactions(self, transactions=None, deserialize_only=None): if ( not self.allow_self and transactions.filter(producer=socket.gethostname()).exists() ): raise TransactionDeserializerError( f"Not deserializing own transactions. Got " ...
Deserializes the encrypted serialized model instances, tx, in a queryset of transactions. Note: each transaction instance contains encrypted JSON text that represents just ONE model instance.
train
https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/transaction/transaction_deserializer.py#L49-L75
[ "def save(obj=None, m2m_data=None):\n \"\"\"Saves a deserialized model object.\n\n Uses save_base to avoid running code in model.save() and\n to avoid triggering signals (if raw=True).\n \"\"\"\n m2m_data = {} if m2m_data is None else m2m_data\n obj.save_base(raw=True)\n for attr, values in m2m...
class TransactionDeserializer: def __init__(self, using=None, allow_self=None, override_role=None, **kwargs): app_config = django_apps.get_app_config("edc_device") self.aes_decrypt = aes_decrypt self.deserialize = deserialize self.save = save self.allow_self = allow_self ...
erikvw/django-collect-offline
django_collect_offline/transaction/transaction_deserializer.py
TransactionDeserializer.custom_parser
python
def custom_parser(self, json_text=None): app_config = django_apps.get_app_config("django_collect_offline") for json_parser in app_config.custom_json_parsers: json_text = json_parser(json_text) return json_text
Runs json_text thru custom parsers.
train
https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/transaction/transaction_deserializer.py#L77-L83
null
class TransactionDeserializer: def __init__(self, using=None, allow_self=None, override_role=None, **kwargs): app_config = django_apps.get_app_config("edc_device") self.aes_decrypt = aes_decrypt self.deserialize = deserialize self.save = save self.allow_self = allow_self ...
erikvw/django-collect-offline
django_collect_offline/site_offline_models.py
SiteOfflineModels.register
python
def register(self, models=None, wrapper_cls=None): self.loaded = True for model in models: model = model.lower() if model not in self.registry: self.registry.update({model: wrapper_cls or self.wrapper_cls}) if self.register_historical: ...
Registers with app_label.modelname, wrapper_cls.
train
https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/site_offline_models.py#L28-L42
null
class SiteOfflineModels: module_name = "offline_models" wrapper_cls = OfflineModel register_historical = True def __init__(self): self.registry = {} self.loaded = False def register_for_app( self, app_label=None, exclude_models=None, exclude_model_classes=None ): ...
erikvw/django-collect-offline
django_collect_offline/site_offline_models.py
SiteOfflineModels.register_for_app
python
def register_for_app( self, app_label=None, exclude_models=None, exclude_model_classes=None ): models = [] exclude_models = exclude_models or [] app_config = django_apps.get_app_config(app_label) for model in app_config.get_models(): if model._meta.label_lower in ...
Registers all models for this app_label.
train
https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/site_offline_models.py#L44-L59
[ "def register(self, models=None, wrapper_cls=None):\n \"\"\"Registers with app_label.modelname, wrapper_cls.\n \"\"\"\n self.loaded = True\n for model in models:\n model = model.lower()\n if model not in self.registry:\n self.registry.update({model: wrapper_cls or self.wrapper_c...
class SiteOfflineModels: module_name = "offline_models" wrapper_cls = OfflineModel register_historical = True def __init__(self): self.registry = {} self.loaded = False def register(self, models=None, wrapper_cls=None): """Registers with app_label.modelname, wrapper_cls. ...
erikvw/django-collect-offline
django_collect_offline/site_offline_models.py
SiteOfflineModels.get_wrapped_instance
python
def get_wrapped_instance(self, instance=None): if instance._meta.label_lower not in self.registry: raise ModelNotRegistered(f"{repr(instance)} is not registered with {self}.") wrapper_cls = self.registry.get(instance._meta.label_lower) or self.wrapper_cls if wrapper_cls: ...
Returns a wrapped model instance.
train
https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/site_offline_models.py#L61-L69
null
class SiteOfflineModels: module_name = "offline_models" wrapper_cls = OfflineModel register_historical = True def __init__(self): self.registry = {} self.loaded = False def register(self, models=None, wrapper_cls=None): """Registers with app_label.modelname, wrapper_cls. ...
erikvw/django-collect-offline
django_collect_offline/site_offline_models.py
SiteOfflineModels.site_models
python
def site_models(self, app_label=None): site_models = {} app_configs = ( django_apps.get_app_configs() if app_label is None else [django_apps.get_app_config(app_label)] ) for app_config in app_configs: model_list = [ model ...
Returns a dictionary of registered models.
train
https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/site_offline_models.py#L71-L89
null
class SiteOfflineModels: module_name = "offline_models" wrapper_cls = OfflineModel register_historical = True def __init__(self): self.registry = {} self.loaded = False def register(self, models=None, wrapper_cls=None): """Registers with app_label.modelname, wrapper_cls. ...
erikvw/django-collect-offline
django_collect_offline/offline_model.py
OfflineModel.has_offline_historical_manager_or_raise
python
def has_offline_historical_manager_or_raise(self): try: model = self.instance.__class__.history.model except AttributeError: model = self.instance.__class__ field = [field for field in model._meta.fields if field.name == "history_id"] if field and not isinstance(f...
Raises an exception if model uses a history manager and historical model history_id is not a UUIDField. Note: expected to use edc_model.HistoricalRecords instead of simple_history.HistoricalRecords.
train
https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/offline_model.py#L71-L91
null
class OfflineModel: """A wrapper for offline model instances to add methods called in signals for synchronization. """ def __init__(self, instance): try: self.is_serialized = settings.ALLOW_MODEL_SERIALIZATION except AttributeError: self.is_serialized = True ...