repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
tomduck/pandoc-tablenos
pandoc_tablenos.py
process_tables
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
python
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
[ "def", "process_tables", "(", "key", ",", "value", ",", "fmt", ",", "meta", ")", ":", "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.
[ "Processes", "the", "attributed", "tables", "." ]
train
https://github.com/tomduck/pandoc-tablenos/blob/b3c7b6a259eec5fb7c8420033d05b32640f1f266/pandoc_tablenos.py#L195-L249
tomduck/pandoc-tablenos
pandoc_tablenos.py
main
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()
python
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()
[ "def", "main", "(", ")", ":", "# 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.
[ "Filters", "the", "document", "AST", "." ]
train
https://github.com/tomduck/pandoc-tablenos/blob/b3c7b6a259eec5fb7c8420033d05b32640f1f266/pandoc_tablenos.py#L368-L441
mediaburst/clockwork-python
clockwork/clockwork_http.py
request
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
python
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
[ "def", "request", "(", "url", ",", "xml", ")", ":", "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', ", "'", ") ", "=", " '", "zip':", "", "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
[ "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" ]
train
https://github.com/mediaburst/clockwork-python/blob/7f8368bbed1fcb5218584fbc5094d93c6aa365d1/clockwork/clockwork_http.py#L11-L44
mediaburst/clockwork-python
clockwork/clockwork.py
API.get_balance
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
python
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
[ "def", "get_balance", "(", "self", ")", ":", "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
[ "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" ]
train
https://github.com/mediaburst/clockwork-python/blob/7f8368bbed1fcb5218584fbc5094d93c6aa365d1/clockwork/clockwork.py#L47-L67
mediaburst/clockwork-python
clockwork/clockwork.py
API.send
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]
python
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]
[ "def", "send", "(", "self", ",", "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
[ "Send", "a", "SMS", "message", "or", "an", "array", "of", "SMS", "messages" ]
train
https://github.com/mediaburst/clockwork-python/blob/7f8368bbed1fcb5218584fbc5094d93c6aa365d1/clockwork/clockwork.py#L69-L115
mediaburst/clockwork-python
clockwork/clockwork.py
API.__init_xml
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
python
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
[ "def", "__init_xml", "(", "self", ",", "rootElementTag", ")", ":", "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
[ "Init", "a", "etree", "element", "and", "pop", "a", "key", "in", "there" ]
train
https://github.com/mediaburst/clockwork-python/blob/7f8368bbed1fcb5218584fbc5094d93c6aa365d1/clockwork/clockwork.py#L117-L122
mediaburst/clockwork-python
clockwork/clockwork.py
API.__build_sms_data
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
python
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
[ "def", "__build_sms_data", "(", "self", ",", "message", ")", ":", "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
[ "Build", "a", "dictionary", "of", "SMS", "message", "elements" ]
train
https://github.com/mediaburst/clockwork-python/blob/7f8368bbed1fcb5218584fbc5094d93c6aa365d1/clockwork/clockwork.py#L125-L150
pwaller/pyprof2calltree
pyprof2calltree.py
pstats2entries
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())
python
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())
[ "def", "pstats2entries", "(", "data", ")", ":", "# 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()
[ "Helper", "to", "convert", "serialized", "pstats", "back", "to", "a", "list", "of", "raw", "entries", "." ]
train
https://github.com/pwaller/pyprof2calltree/blob/62b99c7b366ad317d3d5e21fb73466c8baea670e/pyprof2calltree.py#L106-L141
pwaller/pyprof2calltree
pyprof2calltree.py
is_installed
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
python
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
[ "def", "is_installed", "(", "prog", ")", ":", "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.
[ "Return", "whether", "or", "not", "a", "given", "executable", "is", "installed", "on", "the", "machine", "." ]
train
https://github.com/pwaller/pyprof2calltree/blob/62b99c7b366ad317d3d5e21fb73466c8baea670e/pyprof2calltree.py#L144-L159
pwaller/pyprof2calltree
pyprof2calltree.py
main
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()
python
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()
[ "def", "main", "(", ")", ":", "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
[ "Execute", "the", "converter", "using", "parameters", "provided", "on", "the", "command", "line" ]
train
https://github.com/pwaller/pyprof2calltree/blob/62b99c7b366ad317d3d5e21fb73466c8baea670e/pyprof2calltree.py#L289-L355
pwaller/pyprof2calltree
pyprof2calltree.py
convert
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)
python
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)
[ "def", "convert", "(", "profiling_data", ",", "outputfile", ")", ":", "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
[ "convert", "profiling_data", "to", "calltree", "format", "and", "dump", "it", "to", "outputfile" ]
train
https://github.com/pwaller/pyprof2calltree/blob/62b99c7b366ad317d3d5e21fb73466c8baea670e/pyprof2calltree.py#L370-L387
pwaller/pyprof2calltree
pyprof2calltree.py
CalltreeConverter.output
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)
python
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)
[ "def", "output", "(", "self", ",", "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
[ "Write", "the", "converted", "entries", "to", "out_file" ]
train
https://github.com/pwaller/pyprof2calltree/blob/62b99c7b366ad317d3d5e21fb73466c8baea670e/pyprof2calltree.py#L204-L211
pwaller/pyprof2calltree
pyprof2calltree.py
CalltreeConverter.visualize
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
python
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
[ "def", "visualize", "(", "self", ")", ":", "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.
[ "Launch", "kcachegrind", "on", "the", "converted", "entries", "." ]
train
https://github.com/pwaller/pyprof2calltree/blob/62b99c7b366ad317d3d5e21fb73466c8baea670e/pyprof2calltree.py#L213-L247
bouncer-app/flask-bouncer
flask_bouncer.py
Bouncer.get_app
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')
python
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')
[ "def", "get_app", "(", "self", ",", "reference_app", "=", "None", ")", ":", "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.
[ "Helper", "method", "that", "implements", "the", "logic", "to", "look", "up", "an", "application", "." ]
train
https://github.com/bouncer-app/flask-bouncer/blob/41a8763520cca7d7ff1b247ab6eb3383281f5ab7/flask_bouncer.py#L80-L96
bouncer-app/flask-bouncer
flask_bouncer.py
Bouncer.init_app
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)
python
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)
[ "def", "init_app", "(", "self", ",", "app", ",", "*", "*", "kwargs", ")", ":", "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.
[ "Initializes", "the", "Flask", "-", "Bouncer", "extension", "for", "the", "specified", "application", "." ]
train
https://github.com/bouncer-app/flask-bouncer/blob/41a8763520cca7d7ff1b247ab6eb3383281f5ab7/flask_bouncer.py#L98-L110
bouncer-app/flask-bouncer
flask_bouncer.py
Bouncer.check_authorization
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
python
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
[ "def", "check_authorization", "(", "self", ",", "response", ")", ":", "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
[ "checks", "that", "an", "authorization", "call", "has", "been", "made", "during", "the", "request" ]
train
https://github.com/bouncer-app/flask-bouncer/blob/41a8763520cca7d7ff1b247ab6eb3383281f5ab7/flask_bouncer.py#L118-L124
bouncer-app/flask-bouncer
flask_bouncer.py
Bouncer.check_implicit_rules
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()
python
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()
[ "def", "check_implicit_rules", "(", "self", ")", ":", "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
[ "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" ]
train
https://github.com/bouncer-app/flask-bouncer/blob/41a8763520cca7d7ff1b247ab6eb3383281f5ab7/flask_bouncer.py#L126-L138
paulgb/penkit
penkit/textures/util.py
rotate_texture
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
python
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
[ "def", "rotate_texture", "(", "texture", ",", "rotation", ",", "x_offset", "=", "0.5", ",", "y_offset", "=", "0.5", ")", ":", "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.
[ "Rotates", "the", "given", "texture", "by", "a", "given", "angle", "." ]
train
https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/textures/util.py#L6-L24
paulgb/penkit
penkit/textures/util.py
fit_texture
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
python
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
[ "def", "fit_texture", "(", "layer", ")", ":", "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.
[ "Fits", "a", "layer", "into", "a", "texture", "by", "scaling", "each", "axis", "to", "(", "0", "1", ")", "." ]
train
https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/textures/util.py#L27-L41
paulgb/penkit
optimizer/penkit_optimize/route_util.py
check_valid_solution
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
python
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
[ "def", "check_valid_solution", "(", "solution", ",", "graph", ")", ":", "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.
[ "Check", "that", "the", "solution", "is", "valid", ":", "every", "path", "is", "visited", "exactly", "once", "." ]
train
https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/optimizer/penkit_optimize/route_util.py#L5-L23
paulgb/penkit
optimizer/penkit_optimize/route_util.py
get_route_from_solution
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]
python
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]
[ "def", "get_route_from_solution", "(", "solution", ",", "graph", ")", ":", "# 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.
[ "Converts", "a", "solution", "(", "a", "list", "of", "node", "indices", ")", "into", "a", "list", "of", "paths", "suitable", "for", "rendering", "." ]
train
https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/optimizer/penkit_optimize/route_util.py#L26-L34
paulgb/penkit
penkit/turtle.py
branching_turtle_generator
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)
python
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)
[ "def", "branching_turtle_generator", "(", "turtle_program", ",", "turn_amount", "=", "DEFAULT_TURN", ",", "initial_angle", "=", "DEFAULT_INITIAL_ANGLE", ",", "resolution", "=", "1", ")", ":", "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.
[ "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", "." ]
train
https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/turtle.py#L23-L89
paulgb/penkit
penkit/turtle.py
turtle_to_texture
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)
python
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)
[ "def", "turtle_to_texture", "(", "turtle_program", ",", "turn_amount", "=", "DEFAULT_TURN", ",", "initial_angle", "=", "DEFAULT_INITIAL_ANGLE", ",", "resolution", "=", "1", ")", ":", "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.
[ "Makes", "a", "texture", "from", "a", "turtle", "program", "." ]
train
https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/turtle.py#L104-L120
paulgb/penkit
penkit/fractal/l_systems.py
transform_sequence
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
python
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
[ "def", "transform_sequence", "(", "sequence", ",", "transformations", ")", ":", "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'
[ "Applies", "a", "given", "set", "of", "substitution", "rules", "to", "the", "given", "string", "or", "generator", ".", "For", "more", "background", "see", ":", "https", ":", "//", "en", ".", "wikipedia", ".", "org", "/", "wiki", "/", "L", "-", "system" ]
train
https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/fractal/l_systems.py#L10-L31
paulgb/penkit
penkit/fractal/l_systems.py
transform_multiple
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
python
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
[ "def", "transform_multiple", "(", "sequence", ",", "transformations", ",", "iterations", ")", ":", "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.
[ "Chains", "a", "transformation", "a", "given", "number", "of", "times", "." ]
train
https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/fractal/l_systems.py#L34-L48
paulgb/penkit
penkit/fractal/l_systems.py
l_system
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)
python
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)
[ "def", "l_system", "(", "axiom", ",", "transformations", ",", "iterations", "=", "1", ",", "angle", "=", "45", ",", "resolution", "=", "1", ")", ":", "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
[ "Generates", "a", "texture", "by", "running", "transformations", "on", "a", "turtle", "program", "." ]
train
https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/fractal/l_systems.py#L51-L73
paulgb/penkit
optimizer/penkit_optimize/path_graph.py
PathGraph.get_path
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
python
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
[ "def", "get_path", "(", "self", ",", "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.
[ "Returns", "the", "path", "corresponding", "to", "the", "node", "i", "." ]
train
https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/optimizer/penkit_optimize/path_graph.py#L22-L30
paulgb/penkit
optimizer/penkit_optimize/path_graph.py
PathGraph.cost
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])
python
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])
[ "def", "cost", "(", "self", ",", "i", ",", "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.
[ "Returns", "the", "distance", "between", "the", "end", "of", "path", "i", "and", "the", "start", "of", "path", "j", "." ]
train
https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/optimizer/penkit_optimize/path_graph.py#L32-L35
paulgb/penkit
optimizer/penkit_optimize/path_graph.py
PathGraph.get_coordinates
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)
python
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)
[ "def", "get_coordinates", "(", "self", ",", "i", ",", "end", "=", "False", ")", ":", "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.
[ "Returns", "the", "starting", "coordinates", "of", "node", "i", "as", "a", "pair", "or", "the", "end", "coordinates", "iff", "end", "is", "True", "." ]
train
https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/optimizer/penkit_optimize/path_graph.py#L37-L44
paulgb/penkit
optimizer/penkit_optimize/path_graph.py
PathGraph.iter_starts_with_index
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)
python
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)
[ "def", "iter_starts_with_index", "(", "self", ")", ":", "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.
[ "Returns", "a", "generator", "over", "(", "index", "start", "coordinate", ")", "pairs", "excluding", "the", "origin", "." ]
train
https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/optimizer/penkit_optimize/path_graph.py#L46-L50
paulgb/penkit
optimizer/penkit_optimize/path_graph.py
PathGraph.iter_disjunctions
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)]
python
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)]
[ "def", "iter_disjunctions", "(", "self", ")", ":", "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.)
[ "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", ".", ")" ]
train
https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/optimizer/penkit_optimize/path_graph.py#L57-L62
paulgb/penkit
penkit/preview.py
show_plot
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))
python
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))
[ "def", "show_plot", "(", "plot", ",", "width", "=", "PREVIEW_WIDTH", ",", "height", "=", "PREVIEW_HEIGHT", ")", ":", "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
[ "Preview", "a", "plot", "in", "a", "jupyter", "notebook", "." ]
train
https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/preview.py#L28-L39
paulgb/penkit
penkit/write.py
calculate_view_box
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 )
python
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 )
[ "def", "calculate_view_box", "(", "layers", ",", "aspect_ratio", ",", "margin", "=", "DEFAULT_VIEW_BOX_MARGIN", ")", ":", "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)``.
[ "Calculates", "the", "size", "of", "the", "SVG", "viewBox", "to", "use", "." ]
train
https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/write.py#L15-L50
paulgb/penkit
penkit/write.py
_layer_to_path_gen
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)
python
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)
[ "def", "_layer_to_path_gen", "(", "layer", ")", ":", "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
[ "Generates", "an", "SVG", "path", "from", "a", "given", "layer", "." ]
train
https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/write.py#L53-L70
paulgb/penkit
penkit/write.py
plot_to_svg
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)
python
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)
[ "def", "plot_to_svg", "(", "plot", ",", "width", ",", "height", ",", "unit", "=", "''", ")", ":", "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
[ "Converts", "a", "plot", "(", "list", "of", "layers", ")", "into", "an", "SVG", "document", "." ]
train
https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/write.py#L85-L127
paulgb/penkit
penkit/write.py
write_plot
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)
python
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)
[ "def", "write_plot", "(", "plot", ",", "filename", ",", "width", "=", "DEFAULT_PAGE_WIDTH", ",", "height", "=", "DEFAULT_PAGE_HEIGHT", ",", "unit", "=", "DEFAULT_PAGE_UNIT", ")", ":", "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
[ "Writes", "a", "plot", "SVG", "to", "a", "file", "." ]
train
https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/write.py#L147-L159
paulgb/penkit
penkit/mpl_preview.py
draw_layer
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')
python
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')
[ "def", "draw_layer", "(", "ax", ",", "layer", ")", ":", "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
[ "Draws", "a", "layer", "on", "the", "given", "matplotlib", "axis", "." ]
train
https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/mpl_preview.py#L9-L18
paulgb/penkit
penkit/projection.py
map_texture_to_surface
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
python
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
[ "def", "map_texture_to_surface", "(", "texture", ",", "surface", ")", ":", "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.
[ "Returns", "values", "on", "a", "surface", "for", "points", "on", "a", "texture", "." ]
train
https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/projection.py#L10-L33
paulgb/penkit
penkit/projection.py
project_texture
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)
python
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)
[ "def", "project_texture", "(", "texture_xy", ",", "texture_z", ",", "angle", "=", "DEFAULT_ANGLE", ")", ":", "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.
[ "Creates", "a", "texture", "by", "adding", "z", "-", "values", "to", "an", "existing", "texture", "and", "projecting", "." ]
train
https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/projection.py#L36-L60
paulgb/penkit
penkit/projection.py
project_surface
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
python
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
[ "def", "project_surface", "(", "surface", ",", "angle", "=", "DEFAULT_ANGLE", ")", ":", "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.
[ "Returns", "the", "height", "of", "the", "surface", "when", "projected", "at", "the", "given", "angle", "." ]
train
https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/projection.py#L63-L79
paulgb/penkit
penkit/projection.py
project_texture_on_surface
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
python
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
[ "def", "project_texture_on_surface", "(", "texture", ",", "surface", ",", "angle", "=", "DEFAULT_ANGLE", ")", ":", "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.
[ "Maps", "a", "texture", "onto", "a", "surface", "then", "projects", "to", "2D", "and", "returns", "a", "layer", "." ]
train
https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/projection.py#L82-L96
paulgb/penkit
penkit/projection.py
_remove_hidden_parts
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
python
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
[ "def", "_remove_hidden_parts", "(", "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.
[ "Removes", "parts", "of", "a", "projected", "surface", "that", "are", "not", "visible", "." ]
train
https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/projection.py#L114-L125
paulgb/penkit
penkit/projection.py
project_and_occlude_texture
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
python
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
[ "def", "project_and_occlude_texture", "(", "texture", ",", "surface", ",", "angle", "=", "DEFAULT_ANGLE", ")", ":", "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.
[ "Projects", "a", "texture", "onto", "a", "surface", "with", "occluded", "areas", "removed", "." ]
train
https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/projection.py#L128-L143
paulgb/penkit
penkit/textures/__init__.py
make_lines_texture
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()
python
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()
[ "def", "make_lines_texture", "(", "num_lines", "=", "10", ",", "resolution", "=", "50", ")", ":", "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.
[ "Makes", "a", "texture", "consisting", "of", "a", "given", "number", "of", "horizontal", "lines", "." ]
train
https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/textures/__init__.py#L9-L25
paulgb/penkit
penkit/textures/__init__.py
make_grid_texture
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])
python
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])
[ "def", "make_grid_texture", "(", "num_h_lines", "=", "10", ",", "num_v_lines", "=", "10", ",", "resolution", "=", "50", ")", ":", "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.
[ "Makes", "a", "texture", "consisting", "of", "a", "grid", "of", "vertical", "and", "horizontal", "lines", "." ]
train
https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/textures/__init__.py#L28-L41
paulgb/penkit
penkit/textures/__init__.py
make_spiral_texture
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
python
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
[ "def", "make_spiral_texture", "(", "spirals", "=", "6.0", ",", "ccw", "=", "False", ",", "offset", "=", "0.0", ",", "resolution", "=", "1000", ")", ":", "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.
[ "Makes", "a", "texture", "consisting", "of", "a", "spiral", "from", "the", "origin", "." ]
train
https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/textures/__init__.py#L44-L66
paulgb/penkit
penkit/textures/__init__.py
make_hex_texture
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')))
python
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')))
[ "def", "make_hex_texture", "(", "grid_size", "=", "2", ",", "resolution", "=", "1", ")", ":", "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.
[ "Makes", "a", "texture", "consisting", "on", "a", "grid", "of", "hexagons", "." ]
train
https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/textures/__init__.py#L69-L113
paulgb/penkit
penkit/surfaces.py
make_noise_surface
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)
python
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)
[ "def", "make_noise_surface", "(", "dims", "=", "DEFAULT_DIMS", ",", "blur", "=", "10", ",", "seed", "=", "None", ")", ":", "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.
[ "Makes", "a", "surface", "by", "generating", "random", "noise", "and", "blurring", "it", "." ]
train
https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/surfaces.py#L10-L24
paulgb/penkit
penkit/surfaces.py
make_gradients
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]) )
python
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]) )
[ "def", "make_gradients", "(", "dims", "=", "DEFAULT_DIMS", ")", ":", "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.
[ "Makes", "a", "pair", "of", "gradients", "to", "generate", "textures", "from", "numpy", "primitives", "." ]
train
https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/surfaces.py#L27-L39
paulgb/penkit
penkit/surfaces.py
make_sine_surface
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))
python
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))
[ "def", "make_sine_surface", "(", "dims", "=", "DEFAULT_DIMS", ",", "offset", "=", "0.5", ",", "scale", "=", "1.0", ")", ":", "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.
[ "Makes", "a", "surface", "from", "the", "3D", "sine", "function", "." ]
train
https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/surfaces.py#L42-L54
paulgb/penkit
penkit/surfaces.py
make_bubble_surface
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))
python
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))
[ "def", "make_bubble_surface", "(", "dims", "=", "DEFAULT_DIMS", ",", "repeat", "=", "3", ")", ":", "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.
[ "Makes", "a", "surface", "from", "the", "product", "of", "sine", "functions", "on", "each", "axis", "." ]
train
https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/surfaces.py#L57-L71
paulgb/penkit
optimizer/penkit_optimize/vrp_solver.py
vrp_solver
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
python
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
[ "def", "vrp_solver", "(", "path_graph", ",", "initial_solution", "=", "None", ",", "runtime_seconds", "=", "60", ")", ":", "# 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.
[ "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" ]
train
https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/optimizer/penkit_optimize/vrp_solver.py#L6-L78
pavoni/pyvera
pyvera/__init__.py
init_controller
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]
python
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]
[ "def", "init_controller", "(", "url", ")", ":", "# 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
[ "Initialize", "a", "controller", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L55-L68
pavoni/pyvera
pyvera/__init__.py
VeraController.data_request
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)
python
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)
[ "def", "data_request", "(", "self", ",", "payload", ",", "timeout", "=", "TIMEOUT", ")", ":", "request_url", "=", "self", ".", "base_url", "+", "\"/data_request\"", "return", "requests", ".", "get", "(", "request_url", ",", "timeout", "=", "timeout", ",", "params", "=", "payload", ")" ]
Perform a data_request and return the result.
[ "Perform", "a", "data_request", "and", "return", "the", "result", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L99-L102
pavoni/pyvera
pyvera/__init__.py
VeraController.get_simple_devices_info
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
python
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
[ "def", "get_simple_devices_info", "(", "self", ")", ":", "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.
[ "Get", "basic", "device", "info", "from", "Vera", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L104-L128
pavoni/pyvera
pyvera/__init__.py
VeraController.get_device_by_name
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
python
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
[ "def", "get_device_by_name", "(", "self", ",", "device_name", ")", ":", "# 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
[ "Search", "the", "list", "of", "connected", "devices", "by", "name", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L137-L154
pavoni/pyvera
pyvera/__init__.py
VeraController.get_device_by_id
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
python
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
[ "def", "get_device_by_id", "(", "self", ",", "device_id", ")", ":", "# 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
[ "Search", "the", "list", "of", "connected", "devices", "by", "ID", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L156-L173
pavoni/pyvera
pyvera/__init__.py
VeraController.get_devices
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
python
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
[ "def", "get_devices", "(", "self", ",", "category_filter", "=", "''", ")", ":", "# 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
[ "Get", "list", "of", "connected", "devices", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L175-L241
pavoni/pyvera
pyvera/__init__.py
VeraController.refresh_data
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
python
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
[ "def", "refresh_data", "(", "self", ")", ":", "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.
[ "Refresh", "data", "from", "Vera", "device", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L243-L265
pavoni/pyvera
pyvera/__init__.py
VeraController.map_services
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
python
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
[ "def", "map_services", "(", "self", ")", ":", "# 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.
[ "Get", "full", "Vera", "device", "service", "info", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L267-L282
pavoni/pyvera
pyvera/__init__.py
VeraController.get_changed_devices
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]
python
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]
[ "def", "get_changed_devices", "(", "self", ",", "timestamp", ")", ":", "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.
[ "Get", "data", "since", "last", "timestamp", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L284-L332
pavoni/pyvera
pyvera/__init__.py
VeraDevice.vera_request
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)
python
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)
[ "def", "vera_request", "(", "self", ",", "*", "*", "kwargs", ")", ":", "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.
[ "Perfom", "a", "vera_request", "for", "this", "device", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L445-L453
pavoni/pyvera
pyvera/__init__.py
VeraDevice.set_service_value
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)
python
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)
[ "def", "set_service_value", "(", "self", ",", "service_id", ",", "set_name", ",", "parameter_name", ",", "value", ")", ":", "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.
[ "Set", "a", "variable", "on", "the", "vera", "device", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L455-L469
pavoni/pyvera
pyvera/__init__.py
VeraDevice.call_service
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
python
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
[ "def", "call_service", "(", "self", ",", "service_id", ",", "action", ")", ":", "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.
[ "Call", "a", "Vera", "service", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L471-L481
pavoni/pyvera
pyvera/__init__.py
VeraDevice.set_cache_value
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)
python
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)
[ "def", "set_cache_value", "(", "self", ",", "name", ",", "value", ")", ":", "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.
[ "Set", "a", "variable", "in", "the", "local", "state", "dictionary", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L483-L496
pavoni/pyvera
pyvera/__init__.py
VeraDevice.set_cache_complex_value
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)
python
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)
[ "def", "set_cache_complex_value", "(", "self", ",", "name", ",", "value", ")", ":", "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.
[ "Set", "a", "variable", "in", "the", "local", "complex", "state", "dictionary", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L498-L507
pavoni/pyvera
pyvera/__init__.py
VeraDevice.get_complex_value
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
python
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
[ "def", "get_complex_value", "(", "self", ",", "name", ")", ":", "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.
[ "Get", "a", "value", "from", "the", "service", "dictionaries", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L509-L518
pavoni/pyvera
pyvera/__init__.py
VeraDevice.get_strict_value
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)
python
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)
[ "def", "get_strict_value", "(", "self", ",", "name", ")", ":", "dev_info", "=", "self", ".", "json_state", ".", "get", "(", "'deviceInfo'", ")", "return", "dev_info", ".", "get", "(", "name", ",", "None", ")" ]
Get a case-sensitive keys value from the dev_info area.
[ "Get", "a", "case", "-", "sensitive", "keys", "value", "from", "the", "dev_info", "area", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L537-L541
pavoni/pyvera
pyvera/__init__.py
VeraDevice.refresh_complex_value
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
python
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
[ "def", "refresh_complex_value", "(", "self", ",", "name", ")", ":", "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.
[ "Refresh", "a", "value", "from", "the", "service", "dictionaries", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L543-L560
pavoni/pyvera
pyvera/__init__.py
VeraDevice.refresh
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)
python
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)
[ "def", "refresh", "(", "self", ")", ":", "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.
[ "Refresh", "the", "dev_info", "data", "used", "by", "get_value", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L562-L571
pavoni/pyvera
pyvera/__init__.py
VeraDevice.update
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)})
python
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)})
[ "def", "update", "(", "self", ",", "params", ")", ":", "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.
[ "Update", "the", "dev_info", "data", "from", "a", "dictionary", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L573-L579
pavoni/pyvera
pyvera/__init__.py
VeraDevice.level
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
python
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
[ "def", "level", "(", "self", ")", ":", "# 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.
[ "Get", "level", "from", "vera", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L628-L641
pavoni/pyvera
pyvera/__init__.py
VeraSwitch.set_switch_state
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)
python
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)
[ "def", "set_switch_state", "(", "self", ",", "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.
[ "Set", "the", "switch", "state", "also", "update", "local", "state", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L690-L697
pavoni/pyvera
pyvera/__init__.py
VeraDimmer.is_switched_on
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
python
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
[ "def", "is_switched_on", "(", "self", ",", "refresh", "=", "False", ")", ":", "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.
[ "Get", "dimmer", "state", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L730-L739
pavoni/pyvera
pyvera/__init__.py
VeraDimmer.get_brightness
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)
python
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)
[ "def", "get_brightness", "(", "self", ",", "refresh", "=", "False", ")", ":", "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.
[ "Get", "dimmer", "brightness", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L741-L755
pavoni/pyvera
pyvera/__init__.py
VeraDimmer.set_brightness
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)
python
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)
[ "def", "set_brightness", "(", "self", ",", "brightness", ")", ":", "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.
[ "Set", "dimmer", "brightness", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L757-L772
pavoni/pyvera
pyvera/__init__.py
VeraDimmer.get_color_index
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]
python
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]
[ "def", "get_color_index", "(", "self", ",", "colors", ",", "refresh", "=", "False", ")", ":", "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.
[ "Get", "color", "index", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L774-L790
pavoni/pyvera
pyvera/__init__.py
VeraDimmer.get_color
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
python
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
[ "def", "get_color", "(", "self", ",", "refresh", "=", "False", ")", ":", "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.
[ "Get", "color", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L792-L809
pavoni/pyvera
pyvera/__init__.py
VeraDimmer.set_color
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)
python
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)
[ "def", "set_color", "(", "self", ",", "rgb", ")", ":", "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.
[ "Set", "dimmer", "color", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L811-L830
pavoni/pyvera
pyvera/__init__.py
VeraArmableDevice.set_armed_state
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)
python
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)
[ "def", "set_armed_state", "(", "self", ",", "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.
[ "Set", "the", "armed", "state", "also", "update", "local", "state", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L836-L843
pavoni/pyvera
pyvera/__init__.py
VeraArmableDevice.is_switched_on
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'
python
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'
[ "def", "is_switched_on", "(", "self", ",", "refresh", "=", "False", ")", ":", "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.
[ "Get", "armed", "state", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L853-L862
pavoni/pyvera
pyvera/__init__.py
VeraCurtain.is_open
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
python
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
[ "def", "is_open", "(", "self", ",", "refresh", "=", "False", ")", ":", "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.
[ "Get", "curtains", "state", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L902-L910
pavoni/pyvera
pyvera/__init__.py
VeraCurtain.set_level
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)
python
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)
[ "def", "set_level", "(", "self", ",", "level", ")", ":", "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
[ "Set", "open", "level", "of", "the", "curtains", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L923-L934
pavoni/pyvera
pyvera/__init__.py
VeraLock.get_last_user
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 )
python
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 )
[ "def", "get_last_user", "(", "self", ",", "refresh", "=", "False", ")", ":", "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
[ "Get", "the", "last", "used", "PIN", "user", "id" ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L967-L986
pavoni/pyvera
pyvera/__init__.py
VeraLock.get_pin_codes
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
python
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
[ "def", "get_pin_codes", "(", "self", ",", "refresh", "=", "False", ")", ":", "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')
[ "Get", "the", "list", "of", "PIN", "codes" ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L1006-L1046
pavoni/pyvera
pyvera/__init__.py
VeraThermostat.set_temperature
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)
python
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)
[ "def", "set_temperature", "(", "self", ",", "temp", ")", ":", "self", ".", "set_service_value", "(", "self", ".", "thermostat_setpoint", ",", "'CurrentSetpoint'", ",", "'NewCurrentSetpoint'", ",", "temp", ")", "self", ".", "set_cache_value", "(", "'setpoint'", ",", "temp", ")" ]
Set current goal temperature / setpoint
[ "Set", "current", "goal", "temperature", "/", "setpoint" ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L1056-L1065
pavoni/pyvera
pyvera/__init__.py
VeraThermostat.get_current_goal_temperature
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
python
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
[ "def", "get_current_goal_temperature", "(", "self", ",", "refresh", "=", "False", ")", ":", "if", "refresh", ":", "self", ".", "refresh", "(", ")", "try", ":", "return", "float", "(", "self", ".", "get_value", "(", "'setpoint'", ")", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "return", "None" ]
Get current goal temperature / setpoint
[ "Get", "current", "goal", "temperature", "/", "setpoint" ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L1067-L1074
pavoni/pyvera
pyvera/__init__.py
VeraThermostat.get_current_temperature
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
python
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
[ "def", "get_current_temperature", "(", "self", ",", "refresh", "=", "False", ")", ":", "if", "refresh", ":", "self", ".", "refresh", "(", ")", "try", ":", "return", "float", "(", "self", ".", "get_value", "(", "'temperature'", ")", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "return", "None" ]
Get current temperature
[ "Get", "current", "temperature" ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L1076-L1083
pavoni/pyvera
pyvera/__init__.py
VeraThermostat.set_hvac_mode
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)
python
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)
[ "def", "set_hvac_mode", "(", "self", ",", "mode", ")", ":", "self", ".", "set_service_value", "(", "self", ".", "thermostat_operating_service", ",", "'ModeTarget'", ",", "'NewModeTarget'", ",", "mode", ")", "self", ".", "set_cache_value", "(", "'mode'", ",", "mode", ")" ]
Set the hvac mode
[ "Set", "the", "hvac", "mode" ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L1085-L1092
pavoni/pyvera
pyvera/__init__.py
VeraThermostat.set_fan_mode
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)
python
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)
[ "def", "set_fan_mode", "(", "self", ",", "mode", ")", ":", "self", ".", "set_service_value", "(", "self", ".", "thermostat_fan_service", ",", "'Mode'", ",", "'NewMode'", ",", "mode", ")", "self", ".", "set_cache_value", "(", "'fanmode'", ",", "mode", ")" ]
Set the fan mode
[ "Set", "the", "fan", "mode" ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L1116-L1123
pavoni/pyvera
pyvera/__init__.py
VeraSceneController.get_last_scene_id
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
python
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
[ "def", "get_last_scene_id", "(", "self", ",", "refresh", "=", "False", ")", ":", "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.
[ "Get", "last", "scene", "id", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L1157-L1167
pavoni/pyvera
pyvera/__init__.py
VeraSceneController.get_last_scene_time
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
python
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
[ "def", "get_last_scene_time", "(", "self", ",", "refresh", "=", "False", ")", ":", "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.
[ "Get", "last", "scene", "time", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L1169-L1178
pavoni/pyvera
pyvera/__init__.py
VeraScene.vera_request
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)
python
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)
[ "def", "vera_request", "(", "self", ",", "*", "*", "kwargs", ")", ":", "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.
[ "Perfom", "a", "vera_request", "for", "this", "scene", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L1225-L1233
pavoni/pyvera
pyvera/__init__.py
VeraScene.activate
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
python
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
[ "def", "activate", "(", "self", ")", ":", "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.
[ "Activate", "a", "Vera", "scene", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L1235-L1250
pavoni/pyvera
pyvera/__init__.py
VeraScene.refresh
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)
python
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)
[ "def", "refresh", "(", "self", ")", ":", "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.
[ "Refresh", "the", "data", "used", "by", "get_value", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L1255-L1264
pavoni/pyvera
pyvera/subscribe.py
SubscriptionRegistry.register
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)
python
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)
[ "def", "register", "(", "self", ",", "device", ",", "callback", ")", ":", "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
[ "Register", "a", "callback", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/subscribe.py#L41-L53
pavoni/pyvera
pyvera/subscribe.py
SubscriptionRegistry.unregister
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)
python
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)
[ "def", "unregister", "(", "self", ",", "device", ",", "callback", ")", ":", "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
[ "Remove", "a", "registered", "a", "callback", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/subscribe.py#L55-L67
pavoni/pyvera
pyvera/subscribe.py
SubscriptionRegistry.start
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()
python
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()
[ "def", "start", "(", "self", ")", ":", "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.
[ "Start", "a", "thread", "to", "handle", "Vera", "blocked", "polling", "." ]
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/subscribe.py#L129-L134
macbre/data-flow-graph
sources/elasticsearch/logs2dataflow.py
format_timestamp
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")
python
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")
[ "def", "format_timestamp", "(", "ts", ")", ":", "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
[ "Format", "the", "UTC", "timestamp", "for", "Elasticsearch", "eg", ".", "2014", "-", "07", "-", "09T08", ":", "37", ":", "18", ".", "000Z" ]
train
https://github.com/macbre/data-flow-graph/blob/16164c3860f3defe3354c19b8536ed01b3bfdb61/sources/elasticsearch/logs2dataflow.py#L45-L52
dursk/bitcoin-price-api
exchanges/coinapult.py
Coinapult._pick_level
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]
python
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]
[ "def", "_pick_level", "(", "cls", ",", "btc_amount", ")", ":", "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.
[ "Choose", "between", "small", "medium", "large", "...", "depending", "on", "the", "amount", "specified", "." ]
train
https://github.com/dursk/bitcoin-price-api/blob/abc186041d7041c9465f476bade589da042f6d6d/exchanges/coinapult.py#L41-L49