code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
def is_void(func): try: source = dedent(inspect.getsource(func)) except (OSError, IOError): return False fdef = next(ast.iter_child_nodes(ast.parse(source))) return ( type(fdef) is ast.FunctionDef and len(fdef.body) == 1 and type(fdef.body[0]) is ast.Expr and type(...
Determines if a function is a void function, i.e., one whose body contains nothing but a docstring or an ellipsis. A void function can be used to introduce an overloaded function without actually registering an implementation.
def update_docstring(dispatcher, func=None): doc = dispatcher.__doc__ or '' if inspect.cleandoc(doc).startswith('%s(' % dispatcher.__name__): return sig = '(...)' if func and func.__code__.co_argcount: argspec = inspect.getfullargspec(func) # pylint: disable=deprecated-method ...
Inserts a call signature at the beginning of the docstring on `dispatcher`. The signature is taken from `func` if provided; otherwise `(...)` is used.
def derive_configuration(cls): base_params = cls.base.__parameters__ if hasattr(cls.type, '__args__'): # typing as of commit abefbe4 tvars = {p: p for p in base_params} types = {} for t in iter_generic_bases(cls.type): if t is cls....
Collect the nearest type variables and effective parameters from the type, its bases, and their origins as necessary.
def nfa_complementation(nfa: dict) -> dict: determinized_nfa = nfa_determinization(nfa) return DFA.dfa_complementation(determinized_nfa)
Returns a DFA reading the complemented language read by input NFA. Complement a nondeterministic automaton is possible complementing the determinization of it. The construction is effective, but it involves an exponential blow-up, since determinization involves an unavoidable exponential blow-u...
def nfa_nonemptiness_check(nfa: dict) -> bool: # BFS queue = list() visited = set() for state in nfa['initial_states']: visited.add(state) queue.append(state) while queue: state = queue.pop(0) visited.add(state) for a in nfa['alphabet']: if (s...
Checks if the input NFA reads any language other than the empty one, returning True/False. The language L(A) recognized by the automaton A is nonempty iff there are states :math:`s ∈ S_0` and :math:`t ∈ F` such that t is connected to s. Thus, automata nonemptiness is equivalent to graph reachabilit...
def nfa_nonuniversality_check(nfa: dict) -> bool: # NAIVE Very inefficient (exponential space) : simply # construct Ā and then test its nonemptiness complemented_nfa = nfa_complementation(nfa) return DFA.dfa_nonemptiness_check(complemented_nfa)
Checks if the language read by the input NFA is different from Σ∗ (i.e. contains all possible words), returning True/False. To test nfa A for nonuniversality, it suffices to test Ā ( complementary automaton of A) for nonemptiness :param dict nfa: input NFA. :return: *(bool)*, True if input nfa...
def nfa_word_acceptance(nfa: dict, word: list) -> bool: current_level = set() current_level = current_level.union(nfa['initial_states']) next_level = set() for action in word: for state in current_level: if (state, action) in nfa['transitions']: next_level.update...
Checks if a given word is accepted by a NFA. The word w is accepted by a NFA if exists at least an accepting run on w. :param dict nfa: input NFA; :param list word: list of symbols ∈ nfa['alphabet']; :return: *(bool)*, True if the word is accepted, False otherwise.
def rename_nfa_states(nfa: dict, suffix: str): conversion_dict = {} new_states = set() new_initials = set() new_accepting = set() for state in nfa['states']: conversion_dict[state] = '' + suffix + state new_states.add('' + suffix + state) if state in nfa['initial_states'...
Side effect on input! Renames all the states of the NFA adding a **suffix**. It is an utility function to be used to avoid automata to have states with names in common. Avoid suffix that can lead to special name like "as", "and",... :param dict nfa: input NFA. :param str suffix: string to be ...
def overwrite_view_source(project, dir_path): project_html_location = dir_path / project / HTML_LOCATION if not project_html_location.exists(): return files_to_overwrite = [ f for f in project_html_location.iterdir() if "html" in f.suffix ] for html_file in files_to_overwrite...
In the project's index.html built file, replace the top "source" link with a link to the documentation's home, which is mkdoc's home Args: project (str): project to update dir_path (pathlib.Path): this file's path
def get_listed_projects(): index_path = Path().resolve() / "docs" / "index.md" with open(index_path, "r") as index_file: lines = index_file.readlines() listed_projects = set() project_section = False for _, l in enumerate(lines): idx = l.find(PROJECT_KEY) if idx >= 0: ...
Find the projects listed in the Home Documentation's index.md file Returns: set(str): projects' names, with the '/' in their beginings
def set_routes(): os.system("pwd") dir_path = Path(os.getcwd()).absolute() projects = get_listed_projects() routes = [ [p if p[0] == "/" else "/" + p, str(dir_path) + "{}/build/html".format(p)] for p in projects ] os.environ["MKINX_ROUTES"] = json.dumps(routes)
Set the MKINX_ROUTES environment variable with a serialized list of list of routes, one route being: [pattern to look for, absolute location]
def make_offline(): dir_path = Path(os.getcwd()).absolute() css_path = dir_path / "site" / "assets" / "stylesheets" material_css = css_path / "material-style.css" if not material_css.exists(): file_path = Path(__file__).resolve().parent copyfile(file_path / "material-style.css", ma...
Deletes references to the external google fonts in the Home Documentation's index.html file
def _filenames_from_arg(filename): if isinstance(filename, string_types): filenames = [filename] elif isinstance(filename, (list, tuple)): filenames = filename else: raise Exception('filename argument must be string, list or tuple') for fn in filenames: if not os.pat...
Utility function to deal with polymorphic filenames argument.
def _mk_cache_fn(vcf_fn, array_type, region=None, cachedir=None, compress=False): # ensure cache dir exists if cachedir is None: # use the VCF file name as the base for a directory name cachedir = vcf_fn + config.CACHEDIR_SUFFIX if not os.path.exists(cachedir): ...
Utility function to construct a filename for a cache file, given a VCF file name (where the original data came from) and other parameters.
def _get_cache(vcf_fn, array_type, region, cachedir, compress, log): # guard condition if isinstance(vcf_fn, (list, tuple)): raise Exception( 'caching only supported when loading from a single VCF file' ) # create cache file name cache_fn = _mk_cache_fn(vcf_fn, array_t...
Utility function to obtain a cache file name and determine whether or not a fresh cache file is available.
def _variants_fields(fields, exclude_fields, info_ids): if fields is None: # no fields specified by user # by default extract all standard and INFO fields fields = config.STANDARD_VARIANT_FIELDS + info_ids else: # fields have been specified for f in fields: ...
Utility function to determine which fields to extract when loading variants.
def _variants_arities(fields, arities, info_counts): if arities is None: # no arities specified by user arities = dict() for f, vcf_count in zip(fields, info_counts): if f == 'FILTER': arities[f] = 1 # force one value for the FILTER field elif f not in arities: ...
Utility function to determine arities (i.e., number of values to expect) for variants fields.
def _variants_fills(fields, fills, info_types): if fills is None: # no fills specified by user fills = dict() for f, vcf_type in zip(fields, info_types): if f == 'FILTER': fills[f] = False elif f not in fills: if f in config.STANDARD_VARIANT_FIELDS: ...
Utility function to determine fill values for variants fields with missing values.
def _info_transformers(fields, transformers): if transformers is None: # no transformers specified by user transformers = dict() for f in fields: if f not in transformers: transformers[f] = config.DEFAULT_TRANSFORMER.get(f, None) return tuple(transformers[f] for f in...
Utility function to determine transformer functions for variants fields.
def _variants_dtype(fields, dtypes, arities, filter_ids, flatten_filter, info_types): dtype = list() for f, n, vcf_type in zip(fields, arities, info_types): if f == 'FILTER' and flatten_filter: # split FILTER into multiple boolean fields for flt in filter...
Utility function to build a numpy dtype for a variants array, given user arguments and information available from VCF header.
def _fromiter(it, dtype, count, progress, log): if progress > 0: it = _iter_withprogress(it, progress, log) if count is not None: a = np.fromiter(it, dtype=dtype, count=count) else: a = np.fromiter(it, dtype=dtype) return a
Utility function to load an array from an iterator.
def _iter_withprogress(iterable, progress, log): before_all = time.time() before = before_all n = 0 for i, o in enumerate(iterable): yield o n = i+1 if n % progress == 0: after = time.time() log('%s rows in %.2fs; batch in %.2fs (%d rows/s)' ...
Utility function to load an array from an iterator, reporting progress as we go.
def _calldata_fields(fields, exclude_fields, format_ids): if fields is None: # no fields specified by user # default to all standard fields plus all FORMAT fields in VCF header fields = config.STANDARD_CALLDATA_FIELDS + format_ids else: # fields specified by user for...
Utility function to determine which calldata (i.e., FORMAT) fields to extract.
def _datetime_to_timestamp(self, v): # stole from https://docs.python.org/3/library/datetime.html#datetime.datetime.timestamp if timezone.is_aware(v): return (v - timezone.datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds() else: return (v - timezone.date...
Py2 doesn't supports timestamp()
def get_datetimenow(self): value = timezone.datetime.utcnow() if settings.USE_TZ: value = timezone.localtime( timezone.make_aware(value, timezone.utc), timezone.get_default_timezone() ) return value
get datetime now according to USE_TZ and default time
def to_timestamp(self, value): if isinstance(value, (six.integer_types, float, six.string_types)): try: return float(value) except ValueError: value = self.datetime_str_to_datetime(value) if isinstance(value, datetime.datetime): ...
from value to timestamp format(float)
def to_utc_datetime(self, value): value = self.to_naive_datetime(value) if timezone.is_naive(value): value = timezone.make_aware(value, timezone.utc) else: value = timezone.localtime(value, timezone.utc) return value
from value to datetime with tzinfo format (datetime.datetime instance)
def to_default_timezone_datetime(self, value): return timezone.localtime(self.to_utc_datetime(value), timezone.get_default_timezone())
convert to default timezone datetime
def to_timestamp(self, value): if isinstance(value, (six.integer_types, float, six.string_types)): try: return int(value) except ValueError: value = self.datetime_str_to_datetime(value) if isinstance(value, datetime.datetime): ...
from value to ordinal timestamp format(int)
def to_naive_datetime(self, value): if isinstance(value, (six.integer_types, float, six.string_types)): try: return self.from_number(value) except ValueError: return self.datetime_str_to_datetime(value) if isinstance(value, datetime.datet...
from value to datetime with tzinfo format (datetime.datetime instance)
def to_utc_datetime(self, value): if isinstance(value, (six.integer_types, float, six.string_types)): value = self.to_naive_datetime(value) if isinstance(value, datetime.datetime): if timezone.is_naive(value): value = timezone.make_aware(value, timezone....
from value to datetime with tzinfo format (datetime.datetime instance)
def __replace_all(repls: dict, input: str) -> str: return re.sub('|'.join(re.escape(key) for key in repls.keys()), lambda k: repls[k.group(0)], input)
Replaces from a string **input** all the occurrences of some symbols according to mapping **repls**. :param dict repls: where #key is the old character and #value is the one to substitute with; :param str input: original string where to apply the replacements; :return: *(str)* the string with t...
def dfa_json_importer(input_file: str) -> dict: file = open(input_file) json_file = json.load(file) transitions = {} # key [state ∈ states, action ∈ alphabet] # value [arriving state ∈ states] for (origin, action, destination) in json_file['transitions']: transitions...
Imports a DFA from a JSON file. :param str input_file: path + filename to json file; :return: *(dict)* representing a DFA.
def dfa_to_json(dfa: dict, name: str, path: str = './'): out = { 'alphabet': list(dfa['alphabet']), 'states': list(dfa['states']), 'initial_state': dfa['initial_state'], 'accepting_states': list(dfa['accepting_states']), 'transitions': list() } for t in dfa['tra...
Exports a DFA to a JSON file. If *path* do not exists, it will be created. :param dict dfa: DFA to export; :param str name: name of the output file; :param str path: path where to save the JSON file (default: working directory)
def dfa_to_dot(dfa: dict, name: str, path: str = './'): g = graphviz.Digraph(format='svg') g.node('fake', style='invisible') for state in dfa['states']: if state == dfa['initial_state']: if state in dfa['accepting_states']: g.node(str(state), root='true', ...
Generates a DOT file and a relative SVG image in **path** folder of the input DFA using graphviz library. :param dict dfa: DFA to export; :param str name: name of the output file; :param str path: path where to save the DOT/SVG files (default: working directory)
def nfa_json_importer(input_file: str) -> dict: file = open(input_file) json_file = json.load(file) transitions = {} # key [state in states, action in alphabet] # value [Set of arriving states in states] for p in json_file['transitions']: transitions.setdefault((p[0]...
Imports a NFA from a JSON file. :param str input_file: path+filename to JSON file; :return: *(dict)* representing a NFA.
def nfa_to_json(nfa: dict, name: str, path: str = './'): transitions = list() # key[state in states, action in alphabet] # value [Set of arriving states in states] for p in nfa['transitions']: for dest in nfa['transitions'][p]: transitions.append([p[0], p[1], ...
Exports a NFA to a JSON file. :param dict nfa: NFA to export; :param str name: name of the output file; :param str path: path where to save the JSON file (default: working directory).
def nfa_to_dot(nfa: dict, name: str, path: str = './'): g = graphviz.Digraph(format='svg') fakes = [] for i in range(len(nfa['initial_states'])): fakes.append('fake' + str(i)) g.node('fake' + str(i), style='invisible') for state in nfa['states']: if state in nfa['initial_s...
Generates a DOT file and a relative SVG image in **path** folder of the input NFA using graphviz library. :param dict nfa: input NFA; :param str name: string with the name of the output file; :param str path: path where to save the DOT/SVG files (default: working directory).
def afw_json_importer(input_file: str) -> dict: file = open(input_file) json_file = json.load(file) transitions = {} # key [state in states, action in alphabet] # value [string representing boolean expression] for p in json_file['transitions']: transitions[p[0], p[1]] = p[2] # r...
Imports a AFW from a JSON file. :param str input_file: path+filename to input JSON file; :return: *(dict)* representing a AFW.
def __recursive_acceptance(afw, state, remaining_word): # the word is accepted only if all the final states are # accepting states if len(remaining_word) == 0: if state in afw['accepting_states']: return True else: return False action = remaining_word[0] ...
Recursive call for word acceptance. :param dict afw: input AFW; :param str state: current state; :param list remaining_word: list containing the remaining words. :return: *(bool)*, True if the word is accepted, false otherwise.
def afw_word_acceptance(afw: dict, word: list) -> bool: return __recursive_acceptance(afw, afw['initial_state'], word)
Checks if a **word** is accepted by input AFW, returning True/False. The word w is accepted by a AFW if exists at least an accepting run on w. A run for AFWs is a tree and an alternating automaton can have multiple runs on a given input. A run is accepting if all the leaf nodes are accepting st...
def afw_completion(afw): for state in afw['states']: for a in afw['alphabet']: if (state, a) not in afw['transitions']: afw['transitions'][state, a] = 'False' return afw
Side effect on input! Complete the afw adding not present transitions and marking them as False. :param dict afw: input AFW.
def formula_dual(input_formula: str) -> str: conversion_dictionary = { 'and': 'or', 'or': 'and', 'True': 'False', 'False': 'True' } return re.sub( '|'.join(re.escape(key) for key in conversion_dictionary.keys()), lambda k: conversion_dictionary[k.group(0...
Returns the dual of the input formula. The dual operation on formulas in :math:`B^+(X)` is defined as: the dual :math:`\overline{θ}` of a formula :math:`θ` is obtained from θ by switching :math:`∧` and :math:`∨`, and by switching :math:`true` and :math:`false`. :param str input_formula: original s...
def afw_complementation(afw: dict) -> dict: completed_input = afw_completion(deepcopy(afw)) complemented_afw = { 'alphabet': completed_input['alphabet'], 'states': completed_input['states'], 'initial_state': completed_input['initial_state'], 'accepting_states': ...
Returns a AFW reading the complemented language read by input AFW. Let :math:`A = (Σ, S, s^0 , ρ, F )`. Define :math:`Ā = (Σ, S, s^0 , \overline{ρ}, S − F )`, where :math:`\overline{ρ}(s, a) = \overline{ρ(s, a)}` for all :math:`s ∈ S` and :math:`a ∈ Σ`. That is, :math:`\overline{ρ}` is the dual...
def rename_afw_states(afw: dict, suffix: str): conversion_dict = {} new_states = set() new_accepting = set() for state in afw['states']: conversion_dict[state] = '' + suffix + state new_states.add('' + suffix + state) if state in afw['accepting_states']: new_acce...
Side effect on input! Renames all the states of the AFW adding a **suffix**. It is an utility function used during testing to avoid automata to have states with names in common. Avoid suffix that can lead to special name like "as", "and",... :param dict afw: input AFW. :param str suffix: stri...
def afw_nonemptiness_check(afw: dict) -> bool: nfa = afw_to_nfa_conversion(afw) return NFA.nfa_nonemptiness_check(nfa)
Checks if the input AFW reads any language other than the empty one, returning True/False. The afw is translated into a nfa and then its nonemptiness is checked. :param dict afw: input AFW. :return: *(bool)*, True if input afw is nonempty, False otherwise.
def afw_nonuniversality_check(afw: dict) -> bool: nfa = afw_to_nfa_conversion(afw) return NFA.nfa_nonuniversality_check(nfa)
Checks if the language read by the input AFW is different from Σ∗, returning True/False. The afw is translated into a nfa and then its nonuniversality is checked. :param dict afw: input AFW. :return: *(bool)*, True if input afw is nonuniversal, False otherwise.
def translate_to_dbus_type(typeof, value): if ((isinstance(value, types.UnicodeType) or isinstance(value, str)) and typeof is not dbus.String): # FIXME: This is potentially dangerous since it evaluates # a string in-situ return typeof(eval(value)) else: return typeo...
Helper function to map values from their native Python types to Dbus types. :param type typeof: Target for type conversion e.g., 'dbus.Dictionary' :param value: Value to assign using type 'typeof' :return: 'value' converted to type 'typeof' :rtype: typeof
def signal_handler(self, *args): self.user_callback(self.signal, self.user_arg, *args)
Method to call in order to invoke the user callback. :param args: list of signal-dependent arguments :return:
def add_signal_receiver(self, callback_fn, signal, user_arg): if (signal in self._signal_names): s = Signal(signal, callback_fn, user_arg) self._signals[signal] = s self._bus.add_signal_receiver(s.signal_handler, signal, ...
Add a signal receiver callback with user argument See also :py:meth:`remove_signal_receiver`, :py:exc:`.BTSignalNameNotRecognisedException` :param func callback_fn: User-defined callback function to call when signal triggers :param str signal: Signal name e.g., ...
def get_property(self, name=None): if (name): return self._interface.GetProperties()[name] else: return self._interface.GetProperties()
Helper to get a property value by name or all properties as a dictionary. See also :py:meth:`set_property` :param str name: defaults to None which means all properties in the object's dictionary are returned as a dict. Otherwise, the property name key is used and its va...
def set_property(self, name, value): typeof = type(self.get_property(name)) self._interface.SetProperty(name, translate_to_dbus_type(typeof, value))
Helper to set a property value by name, translating to correct dbus type See also :py:meth:`get_property` :param str name: The property name in the object's dictionary whose value shall be set. :param value: Properties new value to be assigned. :return: :rai...
def set_mode(self, mode): values = {"desired_state": {"mode": mode}} response = self.api_interface.set_device_state(self, values) self._update_state_from_response(response)
:param mode: a str, one of [home, away, night] :return: nothing
def set_privacy(self, state): values = {"desired_state": {"private": state}} response = self.api_interface.set_device_state(self, values) self._update_state_from_response(response)
:param state: True or False :return: nothing
def default(self, o): if isinstance(o, (datetime.datetime, datetime.date, datetime.time)): return o.isoformat() if isinstance(o, decimal.Decimal): return float(o) return json.JSONEncoder.default(self, o)
Encode JSON. :return str: A JSON encoded string
def _update_state_from_response(self, response_json): _response_json = response_json.get('data') if _response_json is not None: self.json_state = _response_json return True return False
:param response_json: the json obj returned from query :return:
def _cached(f): attr_name = '_cached_' + f.__name__ def wrapper(obj, *args, **kwargs): if not hasattr(obj, attr_name): setattr(obj, attr_name, f(obj, *args, **kwargs)) return getattr(obj, attr_name) return wrapper
Decorator that makes a method cached.
def _filter_child_model_fields(cls, fields): indexes_to_remove = set([]) for index1, field1 in enumerate(fields): for index2, field2 in enumerate(fields): if index1 < index2 and index1 not in indexes_to_remove and\ index2 not in indexes_to_rem...
Keep only related model fields. Example: Inherited models: A -> B -> C B has one-to-many relationship to BMany. after inspection BMany would have links to B and C. Keep only B. Parent model A could not be used (It would not be in fields) :param list fields: model fields. ...
def major_service_class(self): major_service = [] for i in BTCoD._MAJOR_SERVICE_CLASS.keys(): if (self.cod & i): major_service.append(BTCoD._MAJOR_SERVICE_CLASS[i]) return major_service
Return the major service class property decoded e.g., Audio, Telephony, etc
def minor_device_class(self): minor_device = [] minor_lookup = BTCoD._MINOR_DEVICE_CLASS.get(self.cod & BTCoD._MAJOR_DEVICE_MASK, []) for i in minor_lookup: minor_value ...
Return the minor device class property decoded e.g., Scanner, Printer, Loudspeaker, Camera, etc.
def post_session(): url_string = "{}/users/me/session".format(WinkApiInterface.BASE_URL) nonce = ''.join([str(random.randint(0, 9)) for i in range(9)]) _json = {"nonce": str(nonce)} try: arequest = requests.post(url_string, data=json.dumps(_json), ...
This endpoint appears to be required in order to keep pubnub updates flowing for some user. This just posts a random nonce to the /users/me/session endpoint and returns the result.
def get_devices_from_response_dict(response_dict, device_type): items = response_dict.get('data') devices = [] api_interface = WinkApiInterface() check_list = isinstance(device_type, (list,)) for item in items: if (check_list and get_object_type(item) in device_type) or \ ...
:rtype: list of WinkDevice
def set_device_state(self, device, state, id_override=None, type_override=None): _LOGGER.info("Setting state via online API") object_id = id_override or device.object_id() object_type = type_override or device.object_type() url_string = "{}/{}s/{}".format(self.BASE_URL, ...
Set device state via online API. Args: device (WinkDevice): The device the change is being requested for. state (Dict): The state being requested. id_override (String, optional): A device ID used to override the passed in device's ID. Used to make changes on ...
def get_device_state(self, device, id_override=None, type_override=None): _LOGGER.info("Getting state via online API") object_id = id_override or device.object_id() object_type = type_override or device.object_type() url_string = "{}/{}s/{}".format(self.BASE_URL, ...
Get device state via online API. Args: device (WinkDevice): The device the change is being requested for. id_override (String, optional): A device ID used to override the passed in device's ID. Used to make changes on sub-devices. i.e. Outlet in a Powerst...
def update_firmware(self, device, id_override=None, type_override=None): object_id = id_override or device.object_id() object_type = type_override or device.object_type() url_string = "{}/{}s/{}/update_firmware".format(self.BASE_URL, ...
Make a call to the update_firmware endpoint. As far as I know this is only valid for Wink hubs. Args: device (WinkDevice): The device the change is being requested for. id_override (String, optional): A device ID used to override the passed in device's ID. Used t...
def remove_device(self, device, id_override=None, type_override=None): object_id = id_override or device.object_id() object_type = type_override or device.object_type() url_string = "{}/{}s/{}".format(self.BASE_URL, object_type, ...
Remove a device. Args: device (WinkDevice): The device the change is being requested for. id_override (String, optional): A device ID used to override the passed in device's ID. Used to make changes on sub-devices. i.e. Outlet in a Powerstrip. The Parent ...
def create_lock_key(self, device, new_device_json, id_override=None, type_override=None): object_id = id_override or device.object_id() object_type = type_override or device.object_type() url_string = "{}/{}s/{}/keys".format(self.BASE_URL, ob...
Create a new lock key code. Args: device (WinkDevice): The device the change is being requested for. new_device_json (String): The JSON string required to create the device. id_override (String, optional): A device ID used to override the passed in device's I...
def piggy_bank_deposit(self, device, _json): url_string = "{}/{}s/{}/deposits".format(self.BASE_URL, device.object_type(), device.object_id()) try: arequest = requests.post(url_string, ...
Args: device (WinkPorkfolioBalanceSensor): The piggy bank device to deposit to/withdrawal from. _json (String): The JSON string to perform the deposit/withdrawal. Returns: response_json (Dict): The API's response in dictionary format
def get_concrete_model(model): if not(inspect.isclass(model) and issubclass(model, models.Model)): model = get_model_by_name(model) return model
Get model defined in Meta. :param str or django.db.models.Model model: :return: model or None :rtype django.db.models.Model or None: :raise ValueError: model is not found or abstract
def get_resource_name(meta): if meta.name is None and not meta.is_model: msg = "Either name or model for resource.Meta shoud be provided" raise ValueError(msg) name = meta.name or get_model_name(get_concrete_model(meta.model)) return name
Define resource name based on Meta information. :param Resource.Meta meta: resource meta information :return: name of resource :rtype: str :raises ValueError:
def merge_metas(*metas): metadict = {} for meta in metas: metadict.update(meta.__dict__) metadict = {k: v for k, v in metadict.items() if not k.startswith('__')} return type('Meta', (object, ), metadict)
Merge meta parameters. next meta has priority over current, it will overwrite attributes. :param class or None meta: class with properties. :return class: merged meta.
def set_state(self, state, speed=None): speed = speed or self.current_fan_speed() if state: desired_state = {"powered": state, "mode": speed} else: desired_state = {"powered": state} response = self.api_interface.set_device_state(self, { "des...
:param state: bool :param speed: a string one of ["lowest", "low", "medium", "high", "auto"] defaults to last speed :return: nothing
def set_fan_direction(self, direction): desired_state = {"direction": direction} response = self.api_interface.set_device_state(self, { "desired_state": desired_state }) self._update_state_from_response(response)
:param direction: a string one of ["forward", "reverse"] :return: nothing
def set_fan_timer(self, timer): desired_state = {"timer": timer} resp = self.api_interface.set_device_state(self, { "desired_state": desired_state }) self._update_state_from_response(resp)
:param timer: an int between fan_timer_range :return: nothing
def set_state(self, state, speed=None): desired_state = {"powered": state} if state: brightness = self._to_brightness.get(speed or self.current_fan_speed(), 0.33) desired_state.update({'brightness': brightness}) response = self.api_interface.set_device_state(sel...
:param state: bool :param speed: a string one of ["lowest", "low", "medium", "high", "auto"] defaults to last speed :return: nothing
def activate(self): response = self.api_interface.set_device_state(self, None) self._update_state_from_response(response)
Activate the scene.
def get_model_by_name(model_name): if isinstance(model_name, six.string_types) and \ len(model_name.split('.')) == 2: app_name, model_name = model_name.split('.') if django.VERSION[:2] < (1, 8): model = models.get_model(app_name, model_name) else: fr...
Get model by its name. :param str model_name: name of model. :return django.db.models.Model: Example: get_concrete_model_by_name('auth.User') django.contrib.auth.models.User
def get_model_name(model): opts = model._meta if django.VERSION[:2] < (1, 7): model_name = opts.module_name else: model_name = opts.model_name return model_name
Get model name for the field. Django 1.5 uses module_name, does not support model_name Django 1.6 uses module_name and model_name DJango 1.7 uses model_name, module_name raises RemovedInDjango18Warning
def clear_app_cache(app_name): loading_cache = django.db.models.loading.cache if django.VERSION[:2] < (1, 7): loading_cache.app_models[app_name].clear() else: loading_cache.all_models[app_name].clear()
Clear django cache for models. :param str ap_name: name of application to clear model cache
def set_state(self, color_hex): root_name = self.json_state.get('piggy_bank_id', self.name()) response = self.api_interface.set_device_state(self, { "nose_color": color_hex }, root_name) self._update_state_from_response(response)
:param color_hex: a hex string indicating the color of the porkfolio nose :return: nothing From the api... "the color of the nose is not in the desired_state but on the object itself."
def deposit(self, amount): _json = {"amount": amount} self.api_interface.piggy_bank_deposit(self, _json)
:param amount: (int +/-) amount to be deposited or withdrawn in cents
def encode(self, fd, mtu, data): self.codec.rtp_sbc_encode_to_fd(self.config, ffi.new('char[]', data), len(data), mtu, ...
Encode the supplied data (byte array) and write to the media transport file descriptor encapsulated as RTP packets. The encoder will calculate the required number of SBC frames and encapsulate as RTP to fit the MTU size. :param int fd: Media transport file descriptor :p...
def decode(self, fd, mtu, max_len=2560): output_buffer = ffi.new('char[]', max_len) sz = self.codec.rtp_sbc_decode_from_fd(self.config, output_buffer, max_len, ...
Read the media transport descriptor, depay the RTP payload and decode the SBC frames into a byte array. The maximum number of bytes to be returned may be passed as an argument and all available bytes are returned to the caller. :param int fd: Media transport file descriptor ...
def gff3_parse_attributes(attributes_string): attributes = dict() fields = attributes_string.split(';') for f in fields: if '=' in f: key, value = f.split('=') attributes[unquote_plus(key).strip()] = unquote_plus(value.strip()) elif len(f) > 0: #...
Parse a string of GFF3 attributes ('key=value' pairs delimited by ';') and return a dictionary.
def _transport_ready_handler(self, fd, cb_condition): if(self.user_cb): self.user_cb(self.user_arg) return True
Wrapper for calling user callback routine to notify when transport data is ready to read
def register_transport_ready_event(self, user_cb, user_arg): self.user_cb = user_cb self.user_arg = user_arg
Register for transport ready events. The `transport ready` event is raised via a user callback. If the endpoint is configured as a source, then the user may then call :py:meth:`write_transport` in order to send data to the associated sink. Otherwise, if the endpoint is configur...
def read_transport(self): if ('r' not in self.access_type): raise BTIncompatibleTransportAccessType return self.codec.decode(self.fd, self.read_mtu)
Read data from media transport. The returned data payload is SBC decoded and has all RTP encapsulation removed. :return data: Payload data that has been decoded, with RTP encapsulation removed. :rtype: array{byte}
def write_transport(self, data): if ('w' not in self.access_type): raise BTIncompatibleTransportAccessType return self.codec.encode(self.fd, self.write_mtu, data)
Write data to media transport. The data is encoded using the SBC codec and RTP encapsulated before being written to the transport file descriptor. :param array{byte} data: Payload data to encode, encapsulate and send.
def close_transport(self): if (self.path): self._release_media_transport(self.path, self.access_type) self.path = None
Forcibly close previously acquired media transport. .. note:: The user should first make sure any transport event handlers are unregistered first.
def _acquire_media_transport(self, path, access_type): transport = BTMediaTransport(path=path) (fd, read_mtu, write_mtu) = transport.acquire(access_type) self.fd = fd.take() # We must do the clean-up later self.write_mtu = write_mtu self.read_mtu = read_mtu sel...
Should be called by subclass when it is ready to acquire the media transport file descriptor
def _release_media_transport(self, path, access_type): try: self._uninstall_transport_ready() os.close(self.fd) # Clean-up previously taken fd transport = BTMediaTransport(path=path) transport.release(access_type) except: pass
Should be called by subclass when it is finished with the media transport file descriptor
def _make_config(config): # The SBC config encoding is taken from a2dp_codecs.h, in particular, # the a2dp_sbc_t type is converted into a 4-byte array: # uint8_t channel_mode:4 # uint8_t frequency:4 # uint8_t allocation_method:2 # uint8_t subbands:2 ...
Helper to turn SBC codec configuration params into a a2dp_sbc_t structure usable by bluez
def _parse_config(config): frequency = config[0] >> 4 channel_mode = config[0] & 0xF allocation_method = config[1] & 0x03 subbands = (config[1] >> 2) & 0x03 block_length = (config[1] >> 4) & 0x0F min_bitpool = config[2] max_bitpool = config[3] ret...
Helper to turn a2dp_sbc_t structure into a more usable set of SBC codec configuration params
def _property_change_event_handler(self, signal, transport, *args): current_state = self.source.State if (self.state == 'connected' and current_state == 'playing'): self._acquire_media_transport(transport, 'r') elif (self.state == 'playing' and current_state == 'connected'):...
Handler for property change event. We catch certain state transitions in order to trigger media transport acquisition/release
def _notify_media_transport_available(self, path, transport): self.source = BTAudioSource(dev_path=path) self.state = self.source.State self.source.add_signal_receiver(self._property_change_event_handler, BTAudioSource.SIGNAL_PROPERTY_CHANGED, # ...
Called by the endpoint when a new media transport is available
def _notify_media_transport_available(self, path, transport): self.sink = BTAudioSink(dev_path=path) self.state = self.sink.State self.sink.add_signal_receiver(self._property_change_event_handler, BTAudioSource.SIGNAL_PROPERTY_CHANGED, # noqa ...
Called by the endpoint when a new media transport is available
def set_operation_mode(self, mode): if mode == "off": desired_state = {"powered": False} else: desired_state = {"powered": True, "mode": mode} response = self.api_interface.set_device_state(self, { "desired_state": desired_state }) s...
:param mode: a string one of self.modes() :return: nothing
def set_temperature(self, set_point): response = self.api_interface.set_device_state(self, { "desired_state": {'set_point': set_point} }) self._update_state_from_response(response)
:param set_point: a float for the set point value in celsius :return: nothing
def set_vacation_mode(self, state): values = {"desired_state": {"vacation_mode": state}} response = self.api_interface.local_set_state(self, values) self._update_state_from_response(response)
:param state: a boolean of ture (on) or false ('off') :return: nothing
def sort(key=None, reverse=False, buffersize=None): return SortComponent(key=key, reverse=reverse, buffersize=buffersize)
Sort rows based on some key field or fields. E.g.:: >>> from petlx.push import sort, tocsv >>> p = sort('foo') >>> p.pipe(tocsv('sorted_by_foo.csv')) >>> p.push(sometable)