sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def process_tables(key, value, fmt, meta): """Processes the attributed tables.""" global has_unnumbered_tables # pylint: disable=global-statement # Process block-level Table elements if key == 'Table': # Inspect the table if len(value) == 5: # Unattributed, bail out has_unnumbered_tables = True if fmt in ['latex']: return [RawBlock('tex', r'\begin{no-prefix-table-caption}'), Table(*value), RawBlock('tex', r'\end{no-prefix-table-caption}')] return None # Process the table table = _process_table(value, fmt) # Context-dependent output attrs = table['attrs'] if table['is_unnumbered']: if fmt in ['latex']: return [RawBlock('tex', r'\begin{no-prefix-table-caption}'), AttrTable(*value), RawBlock('tex', r'\end{no-prefix-table-caption}')] elif fmt in ['latex']: if table['is_tagged']: # Code in the tags tex = '\n'.join([r'\let\oldthetable=\thetable', r'\renewcommand\thetable{%s}'%\ references[attrs[0]]]) pre = RawBlock('tex', tex) tex = '\n'.join([r'\let\thetable=\oldthetable', r'\addtocounter{table}{-1}']) post = RawBlock('tex', tex) return [pre, AttrTable(*value), post] elif table['is_unreferenceable']: attrs[0] = '' # The label isn't needed any further elif fmt in ('html', 'html5') and LABEL_PATTERN.match(attrs[0]): # Insert anchor anchor = RawBlock('html', '<a name="%s"></a>'%attrs[0]) return [anchor, AttrTable(*value)] elif fmt == 'docx': # As per http://officeopenxml.com/WPhyperlink.php bookmarkstart = \ RawBlock('openxml', '<w:bookmarkStart w:id="0" w:name="%s"/>' %attrs[0]) bookmarkend = \ RawBlock('openxml', '<w:bookmarkEnd w:id="0"/>') return [bookmarkstart, AttrTable(*value), bookmarkend] return None
Processes the attributed tables.
entailment
def main(): """Filters the document AST.""" # pylint: disable=global-statement global PANDOCVERSION global AttrTable # Get the output format and document fmt = args.fmt doc = json.loads(STDIN.read()) # Initialize pandocxnos # pylint: disable=too-many-function-args PANDOCVERSION = pandocxnos.init(args.pandocversion, doc) # Element primitives AttrTable = elt('Table', 6) # Chop up the doc meta = doc['meta'] if PANDOCVERSION >= '1.18' else doc[0]['unMeta'] blocks = doc['blocks'] if PANDOCVERSION >= '1.18' else doc[1:] # Process the metadata variables process(meta) # First pass detach_attrs_table = detach_attrs_factory(Table) insert_secnos = insert_secnos_factory(Table) delete_secnos = delete_secnos_factory(Table) altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta), [attach_attrs_table, insert_secnos, process_tables, delete_secnos, detach_attrs_table], blocks) # Second pass process_refs = process_refs_factory(references.keys()) replace_refs = replace_refs_factory(references, use_cleveref_default, False, plusname if not capitalize else [name.title() for name in plusname], starname, 'table') altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta), [repair_refs, process_refs, replace_refs], altered) # Insert supporting TeX if fmt in ['latex']: rawblocks = [] if has_unnumbered_tables: rawblocks += [RawBlock('tex', TEX0), RawBlock('tex', TEX1), RawBlock('tex', TEX2)] if captionname != 'Table': rawblocks += [RawBlock('tex', TEX3 % captionname)] insert_rawblocks = insert_rawblocks_factory(rawblocks) altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta), [insert_rawblocks], altered) # Update the doc if PANDOCVERSION >= '1.18': doc['blocks'] = altered else: doc = doc[:1] + altered # Dump the results json.dump(doc, STDOUT) # Flush stdout STDOUT.flush()
Filters the document AST.
entailment
def request(url, xml): """Make a http request to clockwork, using the XML provided Sets sensible headers for the request. If there is a problem with the http connection a clockwork_exceptions.HttpException is raised """ r = _urllib.Request(url, xml) r.add_header('Content-Type', 'application/xml') r.add_header('User-Agent', 'Clockwork Python wrapper/1.0') result = {} try: f = _urllib.urlopen(r) except URLError as error: raise clockwork_exceptions.HttpException("Error connecting to clockwork server: %s" % error) result['data'] = f.read() result['status'] = f.getcode() if hasattr(f, 'headers'): result['etag'] = f.headers.get('ETag') result['lastmodified'] = f.headers.get('Last-Modified') if f.headers.get('content−encoding', '') == 'gzip': result['data'] = gzip.GzipFile(fileobj=StringIO(result['data'])).read() if hasattr(f, 'url'): result['url'] = f.url result['status'] = 200 f.close() if result['status'] != 200: raise clockwork_exceptions.HttpException("Error connecting to clockwork server - status code %s" % result['status']) return result
Make a http request to clockwork, using the XML provided Sets sensible headers for the request. If there is a problem with the http connection a clockwork_exceptions.HttpException is raised
entailment
def get_balance(self): """Check the balance fot this account. Returns a dictionary containing: account_type: The account type balance: The balance remaining on the account currency: The currency used for the account balance. Assume GBP in not set""" xml_root = self.__init_xml('Balance') response = clockwork_http.request(BALANCE_URL, etree.tostring(xml_root, encoding='utf-8')) data_etree = etree.fromstring(response['data']) err_desc = data_etree.find('ErrDesc') if err_desc is not None: raise clockwork_exceptions.ApiException(err_desc.text, data_etree.find('ErrNo').text) result = {} result['account_type'] = data_etree.find('AccountType').text result['balance'] = data_etree.find('Balance').text result['currency'] = data_etree.find('Currency').text return result
Check the balance fot this account. Returns a dictionary containing: account_type: The account type balance: The balance remaining on the account currency: The currency used for the account balance. Assume GBP in not set
entailment
def send(self, messages): """Send a SMS message, or an array of SMS messages""" tmpSms = SMS(to='', message='') if str(type(messages)) == str(type(tmpSms)): messages = [messages] xml_root = self.__init_xml('Message') wrapper_id = 0 for m in messages: m.wrapper_id = wrapper_id msg = self.__build_sms_data(m) sms = etree.SubElement(xml_root, 'SMS') for sms_element in msg: element = etree.SubElement(sms, sms_element) element.text = msg[sms_element] # print etree.tostring(xml_root) response = clockwork_http.request(SMS_URL, etree.tostring(xml_root, encoding='utf-8')) response_data = response['data'] # print response_data data_etree = etree.fromstring(response_data) # Check for general error err_desc = data_etree.find('ErrDesc') if err_desc is not None: raise clockwork_exceptions.ApiException(err_desc.text, data_etree.find('ErrNo').text) # Return a consistent object results = [] for sms in data_etree: matching_sms = next((s for s in messages if str(s.wrapper_id) == sms.find('WrapperID').text), None) new_result = SMSResponse( sms = matching_sms, id = '' if sms.find('MessageID') is None else sms.find('MessageID').text, error_code = 0 if sms.find('ErrNo') is None else sms.find('ErrNo').text, error_message = '' if sms.find('ErrDesc') is None else sms.find('ErrDesc').text, success = True if sms.find('ErrNo') is None else (sms.find('ErrNo').text == 0) ) results.append(new_result) if len(results) > 1: return results return results[0]
Send a SMS message, or an array of SMS messages
entailment
def __init_xml(self, rootElementTag): """Init a etree element and pop a key in there""" xml_root = etree.Element(rootElementTag) key = etree.SubElement(xml_root, "Key") key.text = self.apikey return xml_root
Init a etree element and pop a key in there
entailment
def __build_sms_data(self, message): """Build a dictionary of SMS message elements""" attributes = {} attributes_to_translate = { 'to' : 'To', 'message' : 'Content', 'client_id' : 'ClientID', 'concat' : 'Concat', 'from_name': 'From', 'invalid_char_option' : 'InvalidCharOption', 'truncate' : 'Truncate', 'wrapper_id' : 'WrapperId' } for attr in attributes_to_translate: val_to_use = None if hasattr(message, attr): val_to_use = getattr(message, attr) if val_to_use is None and hasattr(self, attr): val_to_use = getattr(self, attr) if val_to_use is not None: attributes[attributes_to_translate[attr]] = str(val_to_use) return attributes
Build a dictionary of SMS message elements
entailment
def pstats2entries(data): """Helper to convert serialized pstats back to a list of raw entries. Converse operation of cProfile.Profile.snapshot_stats() """ # Each entry's key is a tuple of (filename, line number, function name) entries = {} allcallers = {} # first pass over stats to build the list of entry instances for code_info, call_info in data.stats.items(): # build a fake code object code = Code(*code_info) # build a fake entry object. entry.calls will be filled during the # second pass over stats cc, nc, tt, ct, callers = call_info entry = Entry(code, callcount=cc, reccallcount=nc - cc, inlinetime=tt, totaltime=ct, calls=[]) # collect the new entry entries[code_info] = entry allcallers[code_info] = list(callers.items()) # second pass of stats to plug callees into callers for entry in entries.values(): entry_label = cProfile.label(entry.code) entry_callers = allcallers.get(entry_label, []) for entry_caller, call_info in entry_callers: cc, nc, tt, ct = call_info subentry = Subentry(entry.code, callcount=cc, reccallcount=nc - cc, inlinetime=tt, totaltime=ct) # entry_caller has the same form as code_info entries[entry_caller].calls.append(subentry) return list(entries.values())
Helper to convert serialized pstats back to a list of raw entries. Converse operation of cProfile.Profile.snapshot_stats()
entailment
def is_installed(prog): """Return whether or not a given executable is installed on the machine.""" with open(os.devnull, 'w') as devnull: try: if os.name == 'nt': retcode = subprocess.call(['where', prog], stdout=devnull) else: retcode = subprocess.call(['which', prog], stdout=devnull) except OSError as e: # If where or which doesn't exist, a "ENOENT" error will occur (The # FileNotFoundError subclass on Python 3). if e.errno != errno.ENOENT: raise retcode = 1 return retcode == 0
Return whether or not a given executable is installed on the machine.
entailment
def main(): """Execute the converter using parameters provided on the command line""" parser = argparse.ArgumentParser() parser.add_argument('-o', '--outfile', metavar='output_file_path', help="Save calltree stats to <outfile>") parser.add_argument('-i', '--infile', metavar='input_file_path', help="Read Python stats from <infile>") parser.add_argument('-k', '--kcachegrind', help="Run the kcachegrind tool on the converted data", action="store_true") parser.add_argument('-r', '--run-script', nargs=argparse.REMAINDER, metavar=('scriptfile', 'args'), dest='script', help="Name of the Python script to run to collect" " profiling data") args = parser.parse_args() outfile = args.outfile if args.script is not None: # collect profiling data by running the given script if not args.outfile: outfile = '%s.log' % os.path.basename(args.script[0]) fd, tmp_path = tempfile.mkstemp(suffix='.prof', prefix='pyprof2calltree') os.close(fd) try: cmd = [ sys.executable, '-m', 'cProfile', '-o', tmp_path, ] cmd.extend(args.script) subprocess.check_call(cmd) kg = CalltreeConverter(tmp_path) finally: os.remove(tmp_path) elif args.infile is not None: # use the profiling data from some input file if not args.outfile: outfile = '%s.log' % os.path.basename(args.infile) if args.infile == outfile: # prevent name collisions by appending another extension outfile += ".log" kg = CalltreeConverter(pstats.Stats(args.infile)) else: # at least an input file or a script to run is required parser.print_usage() sys.exit(2) if args.outfile is not None or not args.kcachegrind: # user either explicitly required output file or requested by not # explicitly asking to launch kcachegrind sys.stderr.write("writing converted data to: %s\n" % outfile) with open(outfile, 'w') as f: kg.output(f) if args.kcachegrind: sys.stderr.write("launching kcachegrind\n") kg.visualize()
Execute the converter using parameters provided on the command line
entailment
def convert(profiling_data, outputfile): """convert `profiling_data` to calltree format and dump it to `outputfile` `profiling_data` can either be: - a pstats.Stats instance - the filename of a pstats.Stats dump - the result of a call to cProfile.Profile.getstats() `outputfile` can either be: - a file() instance open in write mode - a filename """ converter = CalltreeConverter(profiling_data) if is_basestring(outputfile): with open(outputfile, "w") as f: converter.output(f) else: converter.output(outputfile)
convert `profiling_data` to calltree format and dump it to `outputfile` `profiling_data` can either be: - a pstats.Stats instance - the filename of a pstats.Stats dump - the result of a call to cProfile.Profile.getstats() `outputfile` can either be: - a file() instance open in write mode - a filename
entailment
def output(self, out_file): """Write the converted entries to out_file""" self.out_file = out_file out_file.write('event: ns : Nanoseconds\n') out_file.write('events: ns\n') self._output_summary() for entry in sorted(self.entries, key=_entry_sort_key): self._output_entry(entry)
Write the converted entries to out_file
entailment
def visualize(self): """Launch kcachegrind on the converted entries. One of the executables listed in KCACHEGRIND_EXECUTABLES must be present in the system path. """ available_cmd = None for cmd in KCACHEGRIND_EXECUTABLES: if is_installed(cmd): available_cmd = cmd break if available_cmd is None: sys.stderr.write("Could not find kcachegrind. Tried: %s\n" % ", ".join(KCACHEGRIND_EXECUTABLES)) return if self.out_file is None: fd, outfile = tempfile.mkstemp(".log", "pyprof2calltree") use_temp_file = True else: outfile = self.out_file.name use_temp_file = False try: if use_temp_file: with io.open(fd, "w") as f: self.output(f) subprocess.call([available_cmd, outfile]) finally: # clean the temporary file if use_temp_file: os.remove(outfile) self.out_file = None
Launch kcachegrind on the converted entries. One of the executables listed in KCACHEGRIND_EXECUTABLES must be present in the system path.
entailment
def get_app(self, reference_app=None): """Helper method that implements the logic to look up an application.""" if reference_app is not None: return reference_app if self.app is not None: return self.app ctx = stack.top if ctx is not None: return ctx.app raise RuntimeError('Application not registered on Bouncer' ' instance and no application bound' ' to current context')
Helper method that implements the logic to look up an application.
entailment
def init_app(self, app, **kwargs): """ Initializes the Flask-Bouncer extension for the specified application. :param app: The application. """ self.app = app self._init_extension() self.app.before_request(self.check_implicit_rules) if kwargs.get('ensure_authorization', False): self.app.after_request(self.check_authorization)
Initializes the Flask-Bouncer extension for the specified application. :param app: The application.
entailment
def check_authorization(self, response): """checks that an authorization call has been made during the request""" if not hasattr(request, '_authorized'): raise Unauthorized elif not request._authorized: raise Unauthorized return response
checks that an authorization call has been made during the request
entailment
def check_implicit_rules(self): """ if you are using flask classy are using the standard index,new,put,post, etc ... type routes, we will automatically check the permissions for you """ if not self.request_is_managed_by_flask_classy(): return if self.method_is_explictly_overwritten(): return class_name, action = request.endpoint.split(':') clazz = [classy_class for classy_class in self.flask_classy_classes if classy_class.__name__ == class_name][0] Condition(action, clazz.__target_model__).test()
if you are using flask classy are using the standard index,new,put,post, etc ... type routes, we will automatically check the permissions for you
entailment
def rotate_texture(texture, rotation, x_offset=0.5, y_offset=0.5): """Rotates the given texture by a given angle. Args: texture (texture): the texture to rotate rotation (float): the angle of rotation in degrees x_offset (float): the x component of the center of rotation (optional) y_offset (float): the y component of the center of rotation (optional) Returns: texture: A texture. """ x, y = texture x = x.copy() - x_offset y = y.copy() - y_offset angle = np.radians(rotation) x_rot = x * np.cos(angle) + y * np.sin(angle) y_rot = x * -np.sin(angle) + y * np.cos(angle) return x_rot + x_offset, y_rot + y_offset
Rotates the given texture by a given angle. Args: texture (texture): the texture to rotate rotation (float): the angle of rotation in degrees x_offset (float): the x component of the center of rotation (optional) y_offset (float): the y component of the center of rotation (optional) Returns: texture: A texture.
entailment
def fit_texture(layer): """Fits a layer into a texture by scaling each axis to (0, 1). Does not preserve aspect ratio (TODO: make this an option). Args: layer (layer): the layer to scale Returns: texture: A texture. """ x, y = layer x = (x - np.nanmin(x)) / (np.nanmax(x) - np.nanmin(x)) y = (y - np.nanmin(y)) / (np.nanmax(y) - np.nanmin(y)) return x, y
Fits a layer into a texture by scaling each axis to (0, 1). Does not preserve aspect ratio (TODO: make this an option). Args: layer (layer): the layer to scale Returns: texture: A texture.
entailment
def check_valid_solution(solution, graph): """Check that the solution is valid: every path is visited exactly once.""" expected = Counter( i for (i, _) in graph.iter_starts_with_index() if i < graph.get_disjoint(i) ) actual = Counter( min(i, graph.get_disjoint(i)) for i in solution ) difference = Counter(expected) difference.subtract(actual) difference = {k: v for k, v in difference.items() if v != 0} if difference: print('Solution is not valid!' 'Difference in node counts (expected - actual): {}'.format(difference)) return False return True
Check that the solution is valid: every path is visited exactly once.
entailment
def get_route_from_solution(solution, graph): """Converts a solution (a list of node indices) into a list of paths suitable for rendering.""" # As a guard against comparing invalid "solutions", # ensure that this solution is valid. assert check_valid_solution(solution, graph) return [graph.get_path(i) for i in solution]
Converts a solution (a list of node indices) into a list of paths suitable for rendering.
entailment
def branching_turtle_generator(turtle_program, turn_amount=DEFAULT_TURN, initial_angle=DEFAULT_INITIAL_ANGLE, resolution=1): """Given a turtle program, creates a generator of turtle positions. The state of the turtle consists of its position and angle. The turtle starts at the position ``(0, 0)`` facing up. Each character in the turtle program is processed in order and causes an update to the state. The position component of the state is yielded at each state change. A ``(nan, nan)`` separator is emitted between state changes for which no line should be drawn. The turtle program consists of the following commands: - Any letter in ``ABCDEFGHIJ`` means "move forward one unit and draw a path" - Any letter in ``abcdefghij`` means "move forward" (no path) - The character ``-`` means "move counter-clockwise" - The character ``+`` means "move clockwise" - The character ``[`` means "push a copy of the current state to the stack" - The character ``]`` means "pop a state from the stack and return there" - All other characters are silently ignored (this is useful when producing programs with L-Systems) Args: turtle_program (str): a string or generator representing the turtle program turn_amount (float): how much the turn commands should change the angle initial_angle (float): if provided, the turtle starts at this angle (degrees) resolution (int): if provided, interpolate this many points along each visible line Yields: pair: The next coordinate pair, or ``(nan, nan)`` as a path separator. """ saved_states = list() state = (0, 0, DEFAULT_INITIAL_ANGLE) yield (0, 0) for command in turtle_program: x, y, angle = state if command in FORWARD_COMMANDS: new_x = x - np.cos(np.radians(angle)) new_y = y + np.sin(np.radians(angle)) state = (new_x, new_y, angle) if command not in VISIBLE_FORWARD_COMMANDS: yield (np.nan, np.nan) yield (state[0], state[1]) else: dx = new_x - x dy = new_y - y for frac in (1 - np.flipud(np.linspace(0, 1, resolution, False))): yield (x + frac * dx, y + frac * dy) elif command == CW_TURN_COMMAND: state = (x, y, angle + turn_amount) elif command == CCW_TURN_COMMAND: state = (x, y, angle - turn_amount) elif command == PUSH_STATE_COMMAND: saved_states.append(state) elif command == POP_STATE_COMMAND: state = saved_states.pop() yield (np.nan, np.nan) x, y, _ = state yield (x, y)
Given a turtle program, creates a generator of turtle positions. The state of the turtle consists of its position and angle. The turtle starts at the position ``(0, 0)`` facing up. Each character in the turtle program is processed in order and causes an update to the state. The position component of the state is yielded at each state change. A ``(nan, nan)`` separator is emitted between state changes for which no line should be drawn. The turtle program consists of the following commands: - Any letter in ``ABCDEFGHIJ`` means "move forward one unit and draw a path" - Any letter in ``abcdefghij`` means "move forward" (no path) - The character ``-`` means "move counter-clockwise" - The character ``+`` means "move clockwise" - The character ``[`` means "push a copy of the current state to the stack" - The character ``]`` means "pop a state from the stack and return there" - All other characters are silently ignored (this is useful when producing programs with L-Systems) Args: turtle_program (str): a string or generator representing the turtle program turn_amount (float): how much the turn commands should change the angle initial_angle (float): if provided, the turtle starts at this angle (degrees) resolution (int): if provided, interpolate this many points along each visible line Yields: pair: The next coordinate pair, or ``(nan, nan)`` as a path separator.
entailment
def turtle_to_texture(turtle_program, turn_amount=DEFAULT_TURN, initial_angle=DEFAULT_INITIAL_ANGLE, resolution=1): """Makes a texture from a turtle program. Args: turtle_program (str): a string representing the turtle program; see the docstring of `branching_turtle_generator` for more details turn_amount (float): amount to turn in degrees initial_angle (float): initial orientation of the turtle resolution (int): if provided, interpolation amount for visible lines Returns: texture: A texture. """ generator = branching_turtle_generator( turtle_program, turn_amount, initial_angle, resolution) return texture_from_generator(generator)
Makes a texture from a turtle program. Args: turtle_program (str): a string representing the turtle program; see the docstring of `branching_turtle_generator` for more details turn_amount (float): amount to turn in degrees initial_angle (float): initial orientation of the turtle resolution (int): if provided, interpolation amount for visible lines Returns: texture: A texture.
entailment
def transform_sequence(sequence, transformations): """Applies a given set of substitution rules to the given string or generator. For more background see: https://en.wikipedia.org/wiki/L-system Args: sequence (str): a string or generator onto which transformations are applied transformations (dict): a dictionary mapping each char to the string that is substituted for it when the rule is applied Yields: str: the next character in the output sequence. Examples: >>> ''.join(transform_sequence('ABC', {})) 'ABC' >>> ''.join(transform_sequence('ABC', {'A': 'AC', 'C': 'D'})) 'ACBD' """ for c in sequence: for k in transformations.get(c, c): yield k
Applies a given set of substitution rules to the given string or generator. For more background see: https://en.wikipedia.org/wiki/L-system Args: sequence (str): a string or generator onto which transformations are applied transformations (dict): a dictionary mapping each char to the string that is substituted for it when the rule is applied Yields: str: the next character in the output sequence. Examples: >>> ''.join(transform_sequence('ABC', {})) 'ABC' >>> ''.join(transform_sequence('ABC', {'A': 'AC', 'C': 'D'})) 'ACBD'
entailment
def transform_multiple(sequence, transformations, iterations): """Chains a transformation a given number of times. Args: sequence (str): a string or generator onto which transformations are applied transformations (dict): a dictionary mapping each char to the string that is substituted for it when the rule is applied iterations (int): how many times to repeat the transformation Yields: str: the next character in the output sequence. """ for _ in range(iterations): sequence = transform_sequence(sequence, transformations) return sequence
Chains a transformation a given number of times. Args: sequence (str): a string or generator onto which transformations are applied transformations (dict): a dictionary mapping each char to the string that is substituted for it when the rule is applied iterations (int): how many times to repeat the transformation Yields: str: the next character in the output sequence.
entailment
def l_system(axiom, transformations, iterations=1, angle=45, resolution=1): """Generates a texture by running transformations on a turtle program. First, the given transformations are applied to the axiom. This is repeated `iterations` times. Then, the output is run as a turtle program to get a texture, which is returned. For more background see: https://en.wikipedia.org/wiki/L-system Args: axiom (str): the axiom of the Lindenmeyer system (a string) transformations (dict): a dictionary mapping each char to the string that is substituted for it when the rule is applied iterations (int): the number of times to apply the transformations angle (float): the angle to use for turns when interpreting the string as a turtle graphics program resolution (int): the number of midpoints to create in each turtle step Returns: A texture """ turtle_program = transform_multiple(axiom, transformations, iterations) return turtle_to_texture(turtle_program, angle, resolution=resolution)
Generates a texture by running transformations on a turtle program. First, the given transformations are applied to the axiom. This is repeated `iterations` times. Then, the output is run as a turtle program to get a texture, which is returned. For more background see: https://en.wikipedia.org/wiki/L-system Args: axiom (str): the axiom of the Lindenmeyer system (a string) transformations (dict): a dictionary mapping each char to the string that is substituted for it when the rule is applied iterations (int): the number of times to apply the transformations angle (float): the angle to use for turns when interpreting the string as a turtle graphics program resolution (int): the number of midpoints to create in each turtle step Returns: A texture
entailment
def get_path(self, i): """Returns the path corresponding to the node i.""" index = (i - 1) // 2 reverse = (i - 1) % 2 path = self.paths[index] if reverse: return path.reversed() else: return path
Returns the path corresponding to the node i.
entailment
def cost(self, i, j): """Returns the distance between the end of path i and the start of path j.""" return dist(self.endpoints[i][1], self.endpoints[j][0])
Returns the distance between the end of path i and the start of path j.
entailment
def get_coordinates(self, i, end=False): """Returns the starting coordinates of node i as a pair, or the end coordinates iff end is True.""" if end: endpoint = self.endpoints[i][1] else: endpoint = self.endpoints[i][0] return (endpoint.real, endpoint.imag)
Returns the starting coordinates of node i as a pair, or the end coordinates iff end is True.
entailment
def iter_starts_with_index(self): """Returns a generator over (index, start coordinate) pairs, excluding the origin.""" for i in range(1, len(self.endpoints)): yield i, self.get_coordinates(i)
Returns a generator over (index, start coordinate) pairs, excluding the origin.
entailment
def iter_disjunctions(self): """Returns a generator over 2-element lists of indexes which must be mutually exclusive in a solution (i.e. pairs of nodes which represent the same path in opposite directions.)""" for i in range(1, len(self.endpoints), 2): yield [i, self.get_disjoint(i)]
Returns a generator over 2-element lists of indexes which must be mutually exclusive in a solution (i.e. pairs of nodes which represent the same path in opposite directions.)
entailment
def show_plot(plot, width=PREVIEW_WIDTH, height=PREVIEW_HEIGHT): """Preview a plot in a jupyter notebook. Args: plot (list): the plot to display (list of layers) width (int): the width of the preview height (int): the height of the preview Returns: An object that renders in Jupyter as the provided plot """ return SVG(data=plot_to_svg(plot, width, height))
Preview a plot in a jupyter notebook. Args: plot (list): the plot to display (list of layers) width (int): the width of the preview height (int): the height of the preview Returns: An object that renders in Jupyter as the provided plot
entailment
def calculate_view_box(layers, aspect_ratio, margin=DEFAULT_VIEW_BOX_MARGIN): """Calculates the size of the SVG viewBox to use. Args: layers (list): the layers in the image aspect_ratio (float): the height of the output divided by the width margin (float): minimum amount of buffer to add around the image, relative to the total dimensions Returns: tuple: a 4-tuple of floats representing the viewBox according to SVG specifications ``(x, y, width, height)``. """ min_x = min(np.nanmin(x) for x, y in layers) max_x = max(np.nanmax(x) for x, y in layers) min_y = min(np.nanmin(y) for x, y in layers) max_y = max(np.nanmax(y) for x, y in layers) height = max_y - min_y width = max_x - min_x if height > width * aspect_ratio: adj_height = height * (1. + margin) adj_width = adj_height / aspect_ratio else: adj_width = width * (1. + margin) adj_height = adj_width * aspect_ratio width_buffer = (adj_width - width) / 2. height_buffer = (adj_height - height) / 2. return ( min_x - width_buffer, min_y - height_buffer, adj_width, adj_height )
Calculates the size of the SVG viewBox to use. Args: layers (list): the layers in the image aspect_ratio (float): the height of the output divided by the width margin (float): minimum amount of buffer to add around the image, relative to the total dimensions Returns: tuple: a 4-tuple of floats representing the viewBox according to SVG specifications ``(x, y, width, height)``.
entailment
def _layer_to_path_gen(layer): """Generates an SVG path from a given layer. Args: layer (layer): the layer to convert Yields: str: the next component of the path """ draw = False for x, y in zip(*layer): if np.isnan(x) or np.isnan(y): draw = False elif not draw: yield 'M {} {}'.format(x, y) draw = True else: yield 'L {} {}'.format(x, y)
Generates an SVG path from a given layer. Args: layer (layer): the layer to convert Yields: str: the next component of the path
entailment
def plot_to_svg(plot, width, height, unit=''): """Converts a plot (list of layers) into an SVG document. Args: plot (list): list of layers that make up the plot width (float): the width of the resulting image height (float): the height of the resulting image unit (str): the units of the resulting image if not pixels Returns: str: A stringified XML document representing the image """ flipped_plot = [(x, -y) for x, y in plot] aspect_ratio = height / width view_box = calculate_view_box(flipped_plot, aspect_ratio=aspect_ratio) view_box_str = '{} {} {} {}'.format(*view_box) stroke_thickness = STROKE_THICKNESS * (view_box[2]) svg = ET.Element('svg', attrib={ 'xmlns': 'http://www.w3.org/2000/svg', 'xmlns:inkscape': 'http://www.inkscape.org/namespaces/inkscape', 'width': '{}{}'.format(width, unit), 'height': '{}{}'.format(height, unit), 'viewBox': view_box_str}) for i, layer in enumerate(flipped_plot): group = ET.SubElement(svg, 'g', attrib={ 'inkscape:label': '{}-layer'.format(i), 'inkscape:groupmode': 'layer', }) color = PLOT_COLORS[i % len(PLOT_COLORS)] ET.SubElement(group, 'path', attrib={ 'style': 'stroke-width: {}; stroke: {};'.format(stroke_thickness, color), 'fill': 'none', 'd': layer_to_path(layer) }) try: return ET.tostring(svg, encoding='unicode') except LookupError: # Python 2.x return ET.tostring(svg)
Converts a plot (list of layers) into an SVG document. Args: plot (list): list of layers that make up the plot width (float): the width of the resulting image height (float): the height of the resulting image unit (str): the units of the resulting image if not pixels Returns: str: A stringified XML document representing the image
entailment
def write_plot(plot, filename, width=DEFAULT_PAGE_WIDTH, height=DEFAULT_PAGE_HEIGHT, unit=DEFAULT_PAGE_UNIT): """Writes a plot SVG to a file. Args: plot (list): a list of layers to plot filename (str): the name of the file to write width (float): the width of the output SVG height (float): the height of the output SVG unit (str): the unit of the height and width """ svg = plot_to_svg(plot, width, height, unit) with open(filename, 'w') as outfile: outfile.write(svg)
Writes a plot SVG to a file. Args: plot (list): a list of layers to plot filename (str): the name of the file to write width (float): the width of the output SVG height (float): the height of the output SVG unit (str): the unit of the height and width
entailment
def draw_layer(ax, layer): """Draws a layer on the given matplotlib axis. Args: ax (axis): the matplotlib axis to draw on layer (layer): the layers to plot """ ax.set_aspect('equal', 'datalim') ax.plot(*layer) ax.axis('off')
Draws a layer on the given matplotlib axis. Args: ax (axis): the matplotlib axis to draw on layer (layer): the layers to plot
entailment
def map_texture_to_surface(texture, surface): """Returns values on a surface for points on a texture. Args: texture (texture): the texture to trace over the surface surface (surface): the surface to trace along Returns: an array of surface heights for each point in the texture. Line separators (i.e. values that are ``nan`` in the texture) will be ``nan`` in the output, so the output will have the same dimensions as the x/y axes in the input texture. """ texture_x, texture_y = texture surface_h, surface_w = surface.shape surface_x = np.clip( np.int32(surface_w * texture_x - 1e-9), 0, surface_w - 1) surface_y = np.clip( np.int32(surface_h * texture_y - 1e-9), 0, surface_h - 1) surface_z = surface[surface_y, surface_x] return surface_z
Returns values on a surface for points on a texture. Args: texture (texture): the texture to trace over the surface surface (surface): the surface to trace along Returns: an array of surface heights for each point in the texture. Line separators (i.e. values that are ``nan`` in the texture) will be ``nan`` in the output, so the output will have the same dimensions as the x/y axes in the input texture.
entailment
def project_texture(texture_xy, texture_z, angle=DEFAULT_ANGLE): """Creates a texture by adding z-values to an existing texture and projecting. When working with surfaces there are two ways to accomplish the same thing: 1. project the surface and map a texture to the projected surface 2. map a texture to the surface, and then project the result The first method, which does not use this function, is preferred because it is easier to do occlusion removal that way. This function is provided for cases where you do not wish to generate a surface (and don't care about occlusion removal.) Args: texture_xy (texture): the texture to project texture_z (np.array): the Z-values to use in the projection angle (float): the angle to project at, in degrees (0 = overhead, 90 = side view) Returns: layer: A layer. """ z_coef = np.sin(np.radians(angle)) y_coef = np.cos(np.radians(angle)) surface_x, surface_y = texture return (surface_x, -surface_y * y_coef + surface_z * z_coef)
Creates a texture by adding z-values to an existing texture and projecting. When working with surfaces there are two ways to accomplish the same thing: 1. project the surface and map a texture to the projected surface 2. map a texture to the surface, and then project the result The first method, which does not use this function, is preferred because it is easier to do occlusion removal that way. This function is provided for cases where you do not wish to generate a surface (and don't care about occlusion removal.) Args: texture_xy (texture): the texture to project texture_z (np.array): the Z-values to use in the projection angle (float): the angle to project at, in degrees (0 = overhead, 90 = side view) Returns: layer: A layer.
entailment
def project_surface(surface, angle=DEFAULT_ANGLE): """Returns the height of the surface when projected at the given angle. Args: surface (surface): the surface to project angle (float): the angle at which to project the surface Returns: surface: A projected surface. """ z_coef = np.sin(np.radians(angle)) y_coef = np.cos(np.radians(angle)) surface_height, surface_width = surface.shape slope = np.tile(np.linspace(0., 1., surface_height), [surface_width, 1]).T return slope * y_coef + surface * z_coef
Returns the height of the surface when projected at the given angle. Args: surface (surface): the surface to project angle (float): the angle at which to project the surface Returns: surface: A projected surface.
entailment
def project_texture_on_surface(texture, surface, angle=DEFAULT_ANGLE): """Maps a texture onto a surface, then projects to 2D and returns a layer. Args: texture (texture): the texture to project surface (surface): the surface to project onto angle (float): the projection angle in degrees (0 = top-down, 90 = side view) Returns: layer: A layer. """ projected_surface = project_surface(surface, angle) texture_x, _ = texture texture_y = map_texture_to_surface(texture, projected_surface) return texture_x, texture_y
Maps a texture onto a surface, then projects to 2D and returns a layer. Args: texture (texture): the texture to project surface (surface): the surface to project onto angle (float): the projection angle in degrees (0 = top-down, 90 = side view) Returns: layer: A layer.
entailment
def _remove_hidden_parts(projected_surface): """Removes parts of a projected surface that are not visible. Args: projected_surface (surface): the surface to use Returns: surface: A projected surface. """ surface = np.copy(projected_surface) surface[~_make_occlusion_mask(projected_surface)] = np.nan return surface
Removes parts of a projected surface that are not visible. Args: projected_surface (surface): the surface to use Returns: surface: A projected surface.
entailment
def project_and_occlude_texture(texture, surface, angle=DEFAULT_ANGLE): """Projects a texture onto a surface with occluded areas removed. Args: texture (texture): the texture to map to the projected surface surface (surface): the surface to project angle (float): the angle to project at, in degrees (0 = overhead, 90 = side view) Returns: layer: A layer. """ projected_surface = project_surface(surface, angle) projected_surface = _remove_hidden_parts(projected_surface) texture_y = map_texture_to_surface(texture, projected_surface) texture_x, _ = texture return texture_x, texture_y
Projects a texture onto a surface with occluded areas removed. Args: texture (texture): the texture to map to the projected surface surface (surface): the surface to project angle (float): the angle to project at, in degrees (0 = overhead, 90 = side view) Returns: layer: A layer.
entailment
def make_lines_texture(num_lines=10, resolution=50): """Makes a texture consisting of a given number of horizontal lines. Args: num_lines (int): the number of lines to draw resolution (int): the number of midpoints on each line Returns: A texture. """ x, y = np.meshgrid( np.hstack([np.linspace(0, 1, resolution), np.nan]), np.linspace(0, 1, num_lines), ) y[np.isnan(x)] = np.nan return x.flatten(), y.flatten()
Makes a texture consisting of a given number of horizontal lines. Args: num_lines (int): the number of lines to draw resolution (int): the number of midpoints on each line Returns: A texture.
entailment
def make_grid_texture(num_h_lines=10, num_v_lines=10, resolution=50): """Makes a texture consisting of a grid of vertical and horizontal lines. Args: num_h_lines (int): the number of horizontal lines to draw num_v_lines (int): the number of vertical lines to draw resolution (int): the number of midpoints to draw on each line Returns: A texture. """ x_h, y_h = make_lines_texture(num_h_lines, resolution) y_v, x_v = make_lines_texture(num_v_lines, resolution) return np.concatenate([x_h, x_v]), np.concatenate([y_h, y_v])
Makes a texture consisting of a grid of vertical and horizontal lines. Args: num_h_lines (int): the number of horizontal lines to draw num_v_lines (int): the number of vertical lines to draw resolution (int): the number of midpoints to draw on each line Returns: A texture.
entailment
def make_spiral_texture(spirals=6.0, ccw=False, offset=0.0, resolution=1000): """Makes a texture consisting of a spiral from the origin. Args: spirals (float): the number of rotations to make ccw (bool): make spirals counter-clockwise (default is clockwise) offset (float): if non-zero, spirals start offset by this amount resolution (int): number of midpoints along the spiral Returns: A texture. """ dist = np.sqrt(np.linspace(0., 1., resolution)) if ccw: direction = 1. else: direction = -1. angle = dist * spirals * np.pi * 2. * direction spiral_texture = ( (np.cos(angle) * dist / 2.) + 0.5, (np.sin(angle) * dist / 2.) + 0.5 ) return spiral_texture
Makes a texture consisting of a spiral from the origin. Args: spirals (float): the number of rotations to make ccw (bool): make spirals counter-clockwise (default is clockwise) offset (float): if non-zero, spirals start offset by this amount resolution (int): number of midpoints along the spiral Returns: A texture.
entailment
def make_hex_texture(grid_size = 2, resolution=1): """Makes a texture consisting on a grid of hexagons. Args: grid_size (int): the number of hexagons along each dimension of the grid resolution (int): the number of midpoints along the line of each hexagon Returns: A texture. """ grid_x, grid_y = np.meshgrid( np.arange(grid_size), np.arange(grid_size) ) ROOT_3_OVER_2 = np.sqrt(3) / 2 ONE_HALF = 0.5 grid_x = (grid_x * np.sqrt(3) + (grid_y % 2) * ROOT_3_OVER_2).flatten() grid_y = grid_y.flatten() * 1.5 grid_points = grid_x.shape[0] x_offsets = np.interp(np.arange(4 * resolution), np.arange(4) * resolution, [ ROOT_3_OVER_2, 0., -ROOT_3_OVER_2, -ROOT_3_OVER_2, ]) y_offsets = np.interp(np.arange(4 * resolution), np.arange(4) * resolution, [ -ONE_HALF, -1., -ONE_HALF, ONE_HALF ]) tmx = 4 * resolution x_t = np.tile(grid_x, (tmx, 1)) + x_offsets.reshape((tmx, 1)) y_t = np.tile(grid_y, (tmx, 1)) + y_offsets.reshape((tmx, 1)) x_t = np.vstack([x_t, np.tile(np.nan, (1, grid_x.size))]) y_t = np.vstack([y_t, np.tile(np.nan, (1, grid_y.size))]) return fit_texture((x_t.flatten('F'), y_t.flatten('F')))
Makes a texture consisting on a grid of hexagons. Args: grid_size (int): the number of hexagons along each dimension of the grid resolution (int): the number of midpoints along the line of each hexagon Returns: A texture.
entailment
def make_noise_surface(dims=DEFAULT_DIMS, blur=10, seed=None): """Makes a surface by generating random noise and blurring it. Args: dims (pair): the dimensions of the surface to create blur (float): the amount of Gaussian blur to apply seed (int): a random seed to use (optional) Returns: surface: A surface. """ if seed is not None: np.random.seed(seed) return gaussian_filter(np.random.normal(size=dims), blur)
Makes a surface by generating random noise and blurring it. Args: dims (pair): the dimensions of the surface to create blur (float): the amount of Gaussian blur to apply seed (int): a random seed to use (optional) Returns: surface: A surface.
entailment
def make_gradients(dims=DEFAULT_DIMS): """Makes a pair of gradients to generate textures from numpy primitives. Args: dims (pair): the dimensions of the surface to create Returns: pair: A pair of surfaces. """ return np.meshgrid( np.linspace(0.0, 1.0, dims[0]), np.linspace(0.0, 1.0, dims[1]) )
Makes a pair of gradients to generate textures from numpy primitives. Args: dims (pair): the dimensions of the surface to create Returns: pair: A pair of surfaces.
entailment
def make_sine_surface(dims=DEFAULT_DIMS, offset=0.5, scale=1.0): """Makes a surface from the 3D sine function. Args: dims (pair): the dimensions of the surface to create offset (float): an offset applied to the function scale (float): a scale applied to the sine frequency Returns: surface: A surface. """ gradients = (np.array(make_gradients(dims)) - offset) * scale * np.pi return np.sin(np.linalg.norm(gradients, axis=0))
Makes a surface from the 3D sine function. Args: dims (pair): the dimensions of the surface to create offset (float): an offset applied to the function scale (float): a scale applied to the sine frequency Returns: surface: A surface.
entailment
def make_bubble_surface(dims=DEFAULT_DIMS, repeat=3): """Makes a surface from the product of sine functions on each axis. Args: dims (pair): the dimensions of the surface to create repeat (int): the frequency of the waves is set to ensure this many repetitions of the function Returns: surface: A surface. """ gradients = make_gradients(dims) return ( np.sin((gradients[0] - 0.5) * repeat * np.pi) * np.sin((gradients[1] - 0.5) * repeat * np.pi))
Makes a surface from the product of sine functions on each axis. Args: dims (pair): the dimensions of the surface to create repeat (int): the frequency of the waves is set to ensure this many repetitions of the function Returns: surface: A surface.
entailment
def vrp_solver(path_graph, initial_solution=None, runtime_seconds=60): """Solve a path using or-tools' Vehicle Routing Problem solver. Params: path_graph the PathGraph representing the problem initial_solution a solution to start with (list of indices, not including the origin) runtime_seconds how long to search before returning Returns: an ordered list of indices in the graph representing a solution. """ # Create the VRP routing model. The 1 means we are only looking # for a single path. routing = pywrapcp.RoutingModel(path_graph.num_nodes(), 1, path_graph.ORIGIN) # For every path node, add a disjunction so that we do not also # draw its reverse. for disjunction in path_graph.iter_disjunctions(): routing.AddDisjunction(disjunction) # Wrap the distance function so that it converts to an integer, # as or-tools requires. Values are multiplied by COST_MULTIPLIER # prior to conversion to reduce the loss of precision. COST_MULTIPLIER = 1e4 def distance(i, j): return int(path_graph.cost(i, j) * COST_MULTIPLIER) routing.SetArcCostEvaluatorOfAllVehicles(distance) start_time = time() def found_solution(): t = time() - start_time cost = routing.CostVar().Max() / COST_MULTIPLIER print('\rBest solution at {} seconds has cost {} '.format( int(t), cost), end='') routing.AddAtSolutionCallback(found_solution) # If we weren't supplied with a solution initially, construct one by taking # all of the paths in their original direction, in their original order. if not initial_solution: initial_solution = [i for i, _ in path_graph.iter_disjunctions()] # Compute the cost of the initial solution. This is the number we hope to # improve on. initial_assignment = routing.ReadAssignmentFromRoutes([initial_solution], True) # print('Initial distance:', # initial_assignment.ObjectiveValue() / COST_MULTIPLIER) # Set the parameters of the search. search_parameters = pywrapcp.RoutingModel.DefaultSearchParameters() search_parameters.time_limit_ms = runtime_seconds * 1000 search_parameters.local_search_metaheuristic = ( routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH) # Run the optimizer and report the final distance. assignment = routing.SolveFromAssignmentWithParameters(initial_assignment, search_parameters) print() #print('Final distance:', assignment.ObjectiveValue() / COST_MULTIPLIER) # Iterate over the result to produce a list to return as the solution. solution = [] index = routing.Start(0) while not routing.IsEnd(index): index = assignment.Value(routing.NextVar(index)) node = routing.IndexToNode(index) if node != 0: # For compatibility with the greedy solution, exclude the origin. solution.append(node) return solution
Solve a path using or-tools' Vehicle Routing Problem solver. Params: path_graph the PathGraph representing the problem initial_solution a solution to start with (list of indices, not including the origin) runtime_seconds how long to search before returning Returns: an ordered list of indices in the graph representing a solution.
entailment
def init_controller(url): """Initialize a controller. Provides a single global controller for applications that can't do this themselves """ # pylint: disable=global-statement global _VERA_CONTROLLER created = False if _VERA_CONTROLLER is None: _VERA_CONTROLLER = VeraController(url) created = True _VERA_CONTROLLER.start() return [_VERA_CONTROLLER, created]
Initialize a controller. Provides a single global controller for applications that can't do this themselves
entailment
def data_request(self, payload, timeout=TIMEOUT): """Perform a data_request and return the result.""" request_url = self.base_url + "/data_request" return requests.get(request_url, timeout=timeout, params=payload)
Perform a data_request and return the result.
entailment
def get_simple_devices_info(self): """Get basic device info from Vera.""" j = self.data_request({'id': 'sdata'}).json() self.scenes = [] items = j.get('scenes') for item in items: self.scenes.append(VeraScene(item, self)) if j.get('temperature'): self.temperature_units = j.get('temperature') self.categories = {} cats = j.get('categories') for cat in cats: self.categories[cat.get('id')] = cat.get('name') self.device_id_map = {} devs = j.get('devices') for dev in devs: dev['categoryName'] = self.categories.get(dev.get('category')) self.device_id_map[dev.get('id')] = dev
Get basic device info from Vera.
entailment
def get_device_by_name(self, device_name): """Search the list of connected devices by name. device_name param is the string name of the device """ # Find the device for the vera device name we are interested in found_device = None for device in self.get_devices(): if device.name == device_name: found_device = device # found the first (and should be only) one so we will finish break if found_device is None: logger.debug('Did not find device with {}'.format(device_name)) return found_device
Search the list of connected devices by name. device_name param is the string name of the device
entailment
def get_device_by_id(self, device_id): """Search the list of connected devices by ID. device_id param is the integer ID of the device """ # Find the device for the vera device name we are interested in found_device = None for device in self.get_devices(): if device.device_id == device_id: found_device = device # found the first (and should be only) one so we will finish break if found_device is None: logger.debug('Did not find device with {}'.format(device_id)) return found_device
Search the list of connected devices by ID. device_id param is the integer ID of the device
entailment
def get_devices(self, category_filter=''): """Get list of connected devices. category_filter param is an array of strings """ # pylint: disable=too-many-branches # the Vera rest API is a bit rough so we need to make 2 calls to get # all the info e need self.get_simple_devices_info() j = self.data_request({'id': 'status', 'output_format': 'json'}).json() self.devices = [] items = j.get('devices') for item in items: item['deviceInfo'] = self.device_id_map.get(item.get('id')) if item.get('deviceInfo'): device_category = item.get('deviceInfo').get('category') if device_category == CATEGORY_DIMMER: device = VeraDimmer(item, self) elif ( device_category == CATEGORY_SWITCH or device_category == CATEGORY_VERA_SIREN): device = VeraSwitch(item, self) elif device_category == CATEGORY_THERMOSTAT: device = VeraThermostat(item, self) elif device_category == CATEGORY_LOCK: device = VeraLock(item, self) elif device_category == CATEGORY_CURTAIN: device = VeraCurtain(item, self) elif device_category == CATEGORY_ARMABLE: device = VeraBinarySensor(item, self) elif (device_category == CATEGORY_SENSOR or device_category == CATEGORY_HUMIDITY_SENSOR or device_category == CATEGORY_TEMPERATURE_SENSOR or device_category == CATEGORY_LIGHT_SENSOR or device_category == CATEGORY_POWER_METER or device_category == CATEGORY_UV_SENSOR): device = VeraSensor(item, self) elif (device_category == CATEGORY_SCENE_CONTROLLER or device_category == CATEGORY_REMOTE): device = VeraSceneController(item, self) elif device_category == CATEGORY_GARAGE_DOOR: device = VeraGarageDoor(item, self) else: device = VeraDevice(item, self) self.devices.append(device) if (device.is_armable and not ( device_category == CATEGORY_SWITCH or device_category == CATEGORY_VERA_SIREN or device_category == CATEGORY_CURTAIN or device_category == CATEGORY_GARAGE_DOOR)): self.devices.append(VeraArmableDevice(item, self)) else: self.devices.append(VeraDevice(item, self)) if not category_filter: return self.devices devices = [] for device in self.devices: if (device.category_name is not None and device.category_name != '' and device.category_name in category_filter): devices.append(device) return devices
Get list of connected devices. category_filter param is an array of strings
entailment
def refresh_data(self): """Refresh data from Vera device.""" j = self.data_request({'id': 'sdata'}).json() self.temperature_units = j.get('temperature', 'C') self.model = j.get('model') self.version = j.get('version') self.serial_number = j.get('serial_number') categories = {} cats = j.get('categories') for cat in cats: categories[cat.get('id')] = cat.get('name') device_id_map = {} devs = j.get('devices') for dev in devs: dev['categoryName'] = categories.get(dev.get('category')) device_id_map[dev.get('id')] = dev return device_id_map
Refresh data from Vera device.
entailment
def map_services(self): """Get full Vera device service info.""" # the Vera rest API is a bit rough so we need to make 2 calls # to get all the info e need self.get_simple_devices_info() j = self.data_request({'id': 'status', 'output_format': 'json'}).json() service_map = {} items = j.get('devices') for item in items: service_map[item.get('id')] = item.get('states') self.device_services_map = service_map
Get full Vera device service info.
entailment
def get_changed_devices(self, timestamp): """Get data since last timestamp. This is done via a blocking call, pass NONE for initial state. """ if timestamp is None: payload = {} else: payload = { 'timeout': SUBSCRIPTION_WAIT, 'minimumdelay': SUBSCRIPTION_MIN_WAIT } payload.update(timestamp) # double the timeout here so requests doesn't timeout before vera payload.update({ 'id': 'lu_sdata', }) logger.debug("get_changed_devices() requesting payload %s", str(payload)) r = self.data_request(payload, TIMEOUT*2) r.raise_for_status() # If the Vera disconnects before writing a full response (as lu_sdata # will do when interrupted by a Luup reload), the requests module will # happily return 200 with an empty string. So, test for empty response, # so we don't rely on the JSON parser to throw an exception. if r.text == "": raise PyveraError("Empty response from Vera") # Catch a wide swath of what the JSON parser might throw, within # reason. Unfortunately, some parsers don't specifically return # json.decode.JSONDecodeError, but so far most seem to derive what # they do throw from ValueError, so that's helpful. try: result = r.json() except ValueError as ex: raise PyveraError("JSON decode error: " + str(ex)) if not ( type(result) is dict and 'loadtime' in result and 'dataversion' in result ): raise PyveraError("Unexpected/garbled response from Vera") # At this point, all good. Update timestamp and return change data. device_data = result.get('devices') timestamp = { 'loadtime': result.get('loadtime'), 'dataversion': result.get('dataversion') } return [device_data, timestamp]
Get data since last timestamp. This is done via a blocking call, pass NONE for initial state.
entailment
def vera_request(self, **kwargs): """Perfom a vera_request for this device.""" request_payload = { 'output_format': 'json', 'DeviceNum': self.device_id, } request_payload.update(kwargs) return self.vera_controller.data_request(request_payload)
Perfom a vera_request for this device.
entailment
def set_service_value(self, service_id, set_name, parameter_name, value): """Set a variable on the vera device. This will call the Vera api to change device state. """ payload = { 'id': 'lu_action', 'action': 'Set' + set_name, 'serviceId': service_id, parameter_name: value } result = self.vera_request(**payload) logger.debug("set_service_value: " "result of vera_request with payload %s: %s", payload, result.text)
Set a variable on the vera device. This will call the Vera api to change device state.
entailment
def call_service(self, service_id, action): """Call a Vera service. This will call the Vera api to change device state. """ result = self.vera_request(id='action', serviceId=service_id, action=action) logger.debug("call_service: " "result of vera_request with id %s: %s", service_id, result.text) return result
Call a Vera service. This will call the Vera api to change device state.
entailment
def set_cache_value(self, name, value): """Set a variable in the local state dictionary. This does not change the physical device. Useful if you want the device state to refect a new value which has not yet updated drom Vera. """ dev_info = self.json_state.get('deviceInfo') if dev_info.get(name.lower()) is None: logger.error("Could not set %s for %s (key does not exist).", name, self.name) logger.error("- dictionary %s", dev_info) return dev_info[name.lower()] = str(value)
Set a variable in the local state dictionary. This does not change the physical device. Useful if you want the device state to refect a new value which has not yet updated drom Vera.
entailment
def set_cache_complex_value(self, name, value): """Set a variable in the local complex state dictionary. This does not change the physical device. Useful if you want the device state to refect a new value which has not yet updated from Vera. """ for item in self.json_state.get('states'): if item.get('variable') == name: item['value'] = str(value)
Set a variable in the local complex state dictionary. This does not change the physical device. Useful if you want the device state to refect a new value which has not yet updated from Vera.
entailment
def get_complex_value(self, name): """Get a value from the service dictionaries. It's best to use get_value if it has the data you require since the vera subscription only updates data in dev_info. """ for item in self.json_state.get('states'): if item.get('variable') == name: return item.get('value') return None
Get a value from the service dictionaries. It's best to use get_value if it has the data you require since the vera subscription only updates data in dev_info.
entailment
def get_strict_value(self, name): """Get a case-sensitive keys value from the dev_info area. """ dev_info = self.json_state.get('deviceInfo') return dev_info.get(name, None)
Get a case-sensitive keys value from the dev_info area.
entailment
def refresh_complex_value(self, name): """Refresh a value from the service dictionaries. It's best to use get_value / refresh if it has the data you need. """ for item in self.json_state.get('states'): if item.get('variable') == name: service_id = item.get('service') result = self.vera_request(**{ 'id': 'variableget', 'output_format': 'json', 'DeviceNum': self.device_id, 'serviceId': service_id, 'Variable': name }) item['value'] = result.text return item.get('value') return None
Refresh a value from the service dictionaries. It's best to use get_value / refresh if it has the data you need.
entailment
def refresh(self): """Refresh the dev_info data used by get_value. Only needed if you're not using subscriptions. """ j = self.vera_request(id='sdata', output_format='json').json() devices = j.get('devices') for device_data in devices: if device_data.get('id') == self.device_id: self.update(device_data)
Refresh the dev_info data used by get_value. Only needed if you're not using subscriptions.
entailment
def update(self, params): """Update the dev_info data from a dictionary. Only updates if it already exists in the device. """ dev_info = self.json_state.get('deviceInfo') dev_info.update({k: params[k] for k in params if dev_info.get(k)})
Update the dev_info data from a dictionary. Only updates if it already exists in the device.
entailment
def level(self): """Get level from vera.""" # Used for dimmers, curtains # Have seen formats of 10, 0.0 and "0%"! level = self.get_value('level') try: return int(float(level)) except (TypeError, ValueError): pass try: return int(level.strip('%')) except (TypeError, AttributeError, ValueError): pass return 0
Get level from vera.
entailment
def set_switch_state(self, state): """Set the switch state, also update local state.""" self.set_service_value( self.switch_service, 'Target', 'newTargetValue', state) self.set_cache_value('Status', state)
Set the switch state, also update local state.
entailment
def is_switched_on(self, refresh=False): """Get dimmer state. Refresh data from Vera if refresh is True, otherwise use local cache. Refresh is only needed if you're not using subscriptions. """ if refresh: self.refresh() return self.get_brightness(refresh) > 0
Get dimmer state. Refresh data from Vera if refresh is True, otherwise use local cache. Refresh is only needed if you're not using subscriptions.
entailment
def get_brightness(self, refresh=False): """Get dimmer brightness. Refresh data from Vera if refresh is True, otherwise use local cache. Refresh is only needed if you're not using subscriptions. Converts the Vera level property for dimmable lights from a percentage to the 0 - 255 scale used by HA. """ if refresh: self.refresh() brightness = 0 percent = self.level if percent > 0: brightness = round(percent * 2.55) return int(brightness)
Get dimmer brightness. Refresh data from Vera if refresh is True, otherwise use local cache. Refresh is only needed if you're not using subscriptions. Converts the Vera level property for dimmable lights from a percentage to the 0 - 255 scale used by HA.
entailment
def set_brightness(self, brightness): """Set dimmer brightness. Converts the Vera level property for dimmable lights from a percentage to the 0 - 255 scale used by HA. """ percent = 0 if brightness > 0: percent = round(brightness / 2.55) self.set_service_value( self.dimmer_service, 'LoadLevelTarget', 'newLoadlevelTarget', percent) self.set_cache_value('level', percent)
Set dimmer brightness. Converts the Vera level property for dimmable lights from a percentage to the 0 - 255 scale used by HA.
entailment
def get_color_index(self, colors, refresh=False): """Get color index. Refresh data from Vera if refresh is True, otherwise use local cache. """ if refresh: self.refresh_complex_value('SupportedColors') sup = self.get_complex_value('SupportedColors') if sup is None: return None sup = sup.split(',') if not set(colors).issubset(sup): return None return [sup.index(c) for c in colors]
Get color index. Refresh data from Vera if refresh is True, otherwise use local cache.
entailment
def get_color(self, refresh=False): """Get color. Refresh data from Vera if refresh is True, otherwise use local cache. """ if refresh: self.refresh_complex_value('CurrentColor') ci = self.get_color_index(['R', 'G', 'B'], refresh) cur = self.get_complex_value('CurrentColor') if ci is None or cur is None: return None try: val = [cur.split(',')[c] for c in ci] return [int(v.split('=')[1]) for v in val] except IndexError: return None
Get color. Refresh data from Vera if refresh is True, otherwise use local cache.
entailment
def set_color(self, rgb): """Set dimmer color. """ target = ','.join([str(c) for c in rgb]) self.set_service_value( self.color_service, 'ColorRGB', 'newColorRGBTarget', target) rgbi = self.get_color_index(['R', 'G', 'B']) if rgbi is None: return target = ('0=0,1=0,' + str(rgbi[0]) + '=' + str(rgb[0]) + ',' + str(rgbi[1]) + '=' + str(rgb[1]) + ',' + str(rgbi[2]) + '=' + str(rgb[2])) self.set_cache_complex_value("CurrentColor", target)
Set dimmer color.
entailment
def set_armed_state(self, state): """Set the armed state, also update local state.""" self.set_service_value( self.security_sensor_service, 'Armed', 'newArmedValue', state) self.set_cache_value('Armed', state)
Set the armed state, also update local state.
entailment
def is_switched_on(self, refresh=False): """Get armed state. Refresh data from Vera if refresh is True, otherwise use local cache. Refresh is only needed if you're not using subscriptions. """ if refresh: self.refresh() val = self.get_value('Armed') return val == '1'
Get armed state. Refresh data from Vera if refresh is True, otherwise use local cache. Refresh is only needed if you're not using subscriptions.
entailment
def is_open(self, refresh=False): """Get curtains state. Refresh data from Vera if refresh is True, otherwise use local cache. Refresh is only needed if you're not using subscriptions. """ if refresh: self.refresh() return self.get_level(refresh) > 0
Get curtains state. Refresh data from Vera if refresh is True, otherwise use local cache. Refresh is only needed if you're not using subscriptions.
entailment
def set_level(self, level): """Set open level of the curtains. Scale is 0-100 """ self.set_service_value( self.dimmer_service, 'LoadLevelTarget', 'newLoadlevelTarget', level) self.set_cache_value('level', level)
Set open level of the curtains. Scale is 0-100
entailment
def get_last_user(self, refresh=False): """Get the last used PIN user id""" if refresh: self.refresh_complex_value('sl_UserCode') val = self.get_complex_value("sl_UserCode") # Syntax string: UserID="<pin_slot>" UserName="<pin_code_name>" # See http://wiki.micasaverde.com/index.php/Luup_UPnP_Variables_and_Actions#DoorLock1 try: # Get the UserID="" and UserName="" fields separately raw_userid, raw_username = val.split(' ') # Get the right hand value without quotes of UserID="<here>" userid = raw_userid.split('=')[1].split('"')[1] # Get the right hand value without quotes of UserName="<here>" username = raw_username.split('=')[1].split('"')[1] except Exception as ex: logger.error('Got unsupported user string {}: {}'.format(val, ex)) return None return ( userid, username )
Get the last used PIN user id
entailment
def get_pin_codes(self, refresh=False): """Get the list of PIN codes Codes can also be found with self.get_complex_value('PinCodes') """ if refresh: self.refresh() val = self.get_value("pincodes") # val syntax string: <VERSION=3>next_available_user_code_id\tuser_code_id,active,date_added,date_used,PIN_code,name;\t... # See (outdated) http://wiki.micasaverde.com/index.php/Luup_UPnP_Variables_and_Actions#DoorLock1 # Remove the trailing tab # ignore the version and next available at the start # and split out each set of code attributes raw_code_list = [] try: raw_code_list = val.rstrip().split('\t')[1:] except Exception as ex: logger.error('Got unsupported string {}: {}'.format(val, ex)) # Loop to create a list of codes codes = [] for code in raw_code_list: try: # Strip off trailing semicolon # Create a list from csv code_addrs = code.split(';')[0].split(',') # Get the code ID (slot) and see if it should have values slot, active = code_addrs[:2] if active != '0': # Since it has additional attributes, get the remaining ones _, _, pin, name = code_addrs[2:] # And add them as a tuple to the list codes.append((slot, name, pin)) except Exception as ex: logger.error('Problem parsing pin code string {}: {}'.format(code, ex)) return codes
Get the list of PIN codes Codes can also be found with self.get_complex_value('PinCodes')
entailment
def set_temperature(self, temp): """Set current goal temperature / setpoint""" self.set_service_value( self.thermostat_setpoint, 'CurrentSetpoint', 'NewCurrentSetpoint', temp) self.set_cache_value('setpoint', temp)
Set current goal temperature / setpoint
entailment
def get_current_goal_temperature(self, refresh=False): """Get current goal temperature / setpoint""" if refresh: self.refresh() try: return float(self.get_value('setpoint')) except (TypeError, ValueError): return None
Get current goal temperature / setpoint
entailment
def get_current_temperature(self, refresh=False): """Get current temperature""" if refresh: self.refresh() try: return float(self.get_value('temperature')) except (TypeError, ValueError): return None
Get current temperature
entailment
def set_hvac_mode(self, mode): """Set the hvac mode""" self.set_service_value( self.thermostat_operating_service, 'ModeTarget', 'NewModeTarget', mode) self.set_cache_value('mode', mode)
Set the hvac mode
entailment
def set_fan_mode(self, mode): """Set the fan mode""" self.set_service_value( self.thermostat_fan_service, 'Mode', 'NewMode', mode) self.set_cache_value('fanmode', mode)
Set the fan mode
entailment
def get_last_scene_id(self, refresh=False): """Get last scene id. Refresh data from Vera if refresh is True, otherwise use local cache. Refresh is only needed if you're not using subscriptions. """ if refresh: self.refresh_complex_value('LastSceneID') self.refresh_complex_value('sl_CentralScene') val = self.get_complex_value('LastSceneID') or self.get_complex_value('sl_CentralScene') return val
Get last scene id. Refresh data from Vera if refresh is True, otherwise use local cache. Refresh is only needed if you're not using subscriptions.
entailment
def get_last_scene_time(self, refresh=False): """Get last scene time. Refresh data from Vera if refresh is True, otherwise use local cache. Refresh is only needed if you're not using subscriptions. """ if refresh: self.refresh_complex_value('LastSceneTime') val = self.get_complex_value('LastSceneTime') return val
Get last scene time. Refresh data from Vera if refresh is True, otherwise use local cache. Refresh is only needed if you're not using subscriptions.
entailment
def vera_request(self, **kwargs): """Perfom a vera_request for this scene.""" request_payload = { 'output_format': 'json', 'SceneNum': self.scene_id, } request_payload.update(kwargs) return self.vera_controller.data_request(request_payload)
Perfom a vera_request for this scene.
entailment
def activate(self): """Activate a Vera scene. This will call the Vera api to activate a scene. """ payload = { 'id': 'lu_action', 'action': 'RunScene', 'serviceId': self.scene_service } result = self.vera_request(**payload) logger.debug("activate: " "result of vera_request with payload %s: %s", payload, result.text) self._active = True
Activate a Vera scene. This will call the Vera api to activate a scene.
entailment
def refresh(self): """Refresh the data used by get_value. Only needed if you're not using subscriptions. """ j = self.vera_request(id='sdata', output_format='json').json() scenes = j.get('scenes') for scene_data in scenes: if scene_data.get('id') == self.scene_id: self.update(scene_data)
Refresh the data used by get_value. Only needed if you're not using subscriptions.
entailment
def register(self, device, callback): """Register a callback. device: device to be updated by subscription callback: callback for notification of changes """ if not device: logger.error("Received an invalid device: %r", device) return logger.debug("Subscribing to events for %s", device.name) self._devices[device.vera_device_id].append(device) self._callbacks[device].append(callback)
Register a callback. device: device to be updated by subscription callback: callback for notification of changes
entailment
def unregister(self, device, callback): """Remove a registered a callback. device: device that has the subscription callback: callback used in original registration """ if not device: logger.error("Received an invalid device: %r", device) return logger.debug("Removing subscription for {}".format(device.name)) self._callbacks[device].remove(callback) self._devices[device.vera_device_id].remove(device)
Remove a registered a callback. device: device that has the subscription callback: callback used in original registration
entailment
def start(self): """Start a thread to handle Vera blocked polling.""" self._poll_thread = threading.Thread(target=self._run_poll_server, name='Vera Poll Thread') self._poll_thread.deamon = True self._poll_thread.start()
Start a thread to handle Vera blocked polling.
entailment
def format_timestamp(ts): """ Format the UTC timestamp for Elasticsearch eg. 2014-07-09T08:37:18.000Z @see https://docs.python.org/2/library/time.html#time.strftime """ tz_info = tz.tzutc() return datetime.fromtimestamp(ts, tz=tz_info).strftime("%Y-%m-%dT%H:%M:%S.000Z")
Format the UTC timestamp for Elasticsearch eg. 2014-07-09T08:37:18.000Z @see https://docs.python.org/2/library/time.html#time.strftime
entailment
def _pick_level(cls, btc_amount): """ Choose between small, medium, large, ... depending on the amount specified. """ for size, level in cls.TICKER_LEVEL: if btc_amount < size: return level return cls.TICKER_LEVEL[-1][1]
Choose between small, medium, large, ... depending on the amount specified.
entailment