repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
knipknap/exscript
Exscript/util/cast.py
to_hosts
def to_hosts(hosts, default_protocol='telnet', default_domain=''): """ Given a string or a Host object, or a list of strings or Host objects, this function returns a list of Host objects. :type hosts: string|Host|list(string)|list(Host) :param hosts: One or more hosts or hostnames. :type default_protocol: str :param default_protocol: Passed to the Host constructor. :type default_domain: str :param default_domain: Appended to each hostname that has no domain. :rtype: list[Host] :return: A list of Host objects. """ return [to_host(h, default_protocol, default_domain) for h in to_list(hosts)]
python
def to_hosts(hosts, default_protocol='telnet', default_domain=''): """ Given a string or a Host object, or a list of strings or Host objects, this function returns a list of Host objects. :type hosts: string|Host|list(string)|list(Host) :param hosts: One or more hosts or hostnames. :type default_protocol: str :param default_protocol: Passed to the Host constructor. :type default_domain: str :param default_domain: Appended to each hostname that has no domain. :rtype: list[Host] :return: A list of Host objects. """ return [to_host(h, default_protocol, default_domain) for h in to_list(hosts)]
[ "def", "to_hosts", "(", "hosts", ",", "default_protocol", "=", "'telnet'", ",", "default_domain", "=", "''", ")", ":", "return", "[", "to_host", "(", "h", ",", "default_protocol", ",", "default_domain", ")", "for", "h", "in", "to_list", "(", "hosts", ")", ...
Given a string or a Host object, or a list of strings or Host objects, this function returns a list of Host objects. :type hosts: string|Host|list(string)|list(Host) :param hosts: One or more hosts or hostnames. :type default_protocol: str :param default_protocol: Passed to the Host constructor. :type default_domain: str :param default_domain: Appended to each hostname that has no domain. :rtype: list[Host] :return: A list of Host objects.
[ "Given", "a", "string", "or", "a", "Host", "object", "or", "a", "list", "of", "strings", "or", "Host", "objects", "this", "function", "returns", "a", "list", "of", "Host", "objects", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/cast.py#L69-L84
train
213,200
knipknap/exscript
Exscript/util/cast.py
to_regex
def to_regex(regex, flags=0): """ Given a string, this function returns a new re.RegexObject. Given a re.RegexObject, this function just returns the same object. :type regex: string|re.RegexObject :param regex: A regex or a re.RegexObject :type flags: int :param flags: See Python's re.compile(). :rtype: re.RegexObject :return: The Python regex object. """ if regex is None: raise TypeError('None can not be cast to re.RegexObject') if hasattr(regex, 'match'): return regex return re.compile(regex, flags)
python
def to_regex(regex, flags=0): """ Given a string, this function returns a new re.RegexObject. Given a re.RegexObject, this function just returns the same object. :type regex: string|re.RegexObject :param regex: A regex or a re.RegexObject :type flags: int :param flags: See Python's re.compile(). :rtype: re.RegexObject :return: The Python regex object. """ if regex is None: raise TypeError('None can not be cast to re.RegexObject') if hasattr(regex, 'match'): return regex return re.compile(regex, flags)
[ "def", "to_regex", "(", "regex", ",", "flags", "=", "0", ")", ":", "if", "regex", "is", "None", ":", "raise", "TypeError", "(", "'None can not be cast to re.RegexObject'", ")", "if", "hasattr", "(", "regex", ",", "'match'", ")", ":", "return", "regex", "re...
Given a string, this function returns a new re.RegexObject. Given a re.RegexObject, this function just returns the same object. :type regex: string|re.RegexObject :param regex: A regex or a re.RegexObject :type flags: int :param flags: See Python's re.compile(). :rtype: re.RegexObject :return: The Python regex object.
[ "Given", "a", "string", "this", "function", "returns", "a", "new", "re", ".", "RegexObject", ".", "Given", "a", "re", ".", "RegexObject", "this", "function", "just", "returns", "the", "same", "object", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/cast.py#L87-L103
train
213,201
knipknap/exscript
Exscript/util/ipv4.py
is_ip
def is_ip(string): """ Returns True if the given string is an IPv4 address, False otherwise. :type string: string :param string: Any string. :rtype: bool :return: True if the string is an IP address, False otherwise. """ mo = re.match(r'(\d+)\.(\d+)\.(\d+)\.(\d+)', string) if mo is None: return False for group in mo.groups(): if int(group) not in list(range(0, 256)): return False return True
python
def is_ip(string): """ Returns True if the given string is an IPv4 address, False otherwise. :type string: string :param string: Any string. :rtype: bool :return: True if the string is an IP address, False otherwise. """ mo = re.match(r'(\d+)\.(\d+)\.(\d+)\.(\d+)', string) if mo is None: return False for group in mo.groups(): if int(group) not in list(range(0, 256)): return False return True
[ "def", "is_ip", "(", "string", ")", ":", "mo", "=", "re", ".", "match", "(", "r'(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)'", ",", "string", ")", "if", "mo", "is", "None", ":", "return", "False", "for", "group", "in", "mo", ".", "groups", "(", ")", ":", "if", ...
Returns True if the given string is an IPv4 address, False otherwise. :type string: string :param string: Any string. :rtype: bool :return: True if the string is an IP address, False otherwise.
[ "Returns", "True", "if", "the", "given", "string", "is", "an", "IPv4", "address", "False", "otherwise", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/ipv4.py#L54-L69
train
213,202
knipknap/exscript
Exscript/util/ipv4.py
network
def network(prefix, default_length=24): """ Given a prefix, this function returns the corresponding network address. :type prefix: string :param prefix: An IP prefix. :type default_length: long :param default_length: The default ip prefix length. :rtype: string :return: The IP network address. """ address, pfxlen = parse_prefix(prefix, default_length) ip = ip2int(address) return int2ip(ip & pfxlen2mask_int(pfxlen))
python
def network(prefix, default_length=24): """ Given a prefix, this function returns the corresponding network address. :type prefix: string :param prefix: An IP prefix. :type default_length: long :param default_length: The default ip prefix length. :rtype: string :return: The IP network address. """ address, pfxlen = parse_prefix(prefix, default_length) ip = ip2int(address) return int2ip(ip & pfxlen2mask_int(pfxlen))
[ "def", "network", "(", "prefix", ",", "default_length", "=", "24", ")", ":", "address", ",", "pfxlen", "=", "parse_prefix", "(", "prefix", ",", "default_length", ")", "ip", "=", "ip2int", "(", "address", ")", "return", "int2ip", "(", "ip", "&", "pfxlen2m...
Given a prefix, this function returns the corresponding network address. :type prefix: string :param prefix: An IP prefix. :type default_length: long :param default_length: The default ip prefix length. :rtype: string :return: The IP network address.
[ "Given", "a", "prefix", "this", "function", "returns", "the", "corresponding", "network", "address", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/ipv4.py#L187-L201
train
213,203
knipknap/exscript
Exscript/util/ipv4.py
matches_prefix
def matches_prefix(ip, prefix): """ Returns True if the given IP address is part of the given network, returns False otherwise. :type ip: string :param ip: An IP address. :type prefix: string :param prefix: An IP prefix. :rtype: bool :return: True if the IP is in the prefix, False otherwise. """ ip_int = ip2int(ip) network, pfxlen = parse_prefix(prefix) network_int = ip2int(network) mask_int = pfxlen2mask_int(pfxlen) return ip_int&mask_int == network_int&mask_int
python
def matches_prefix(ip, prefix): """ Returns True if the given IP address is part of the given network, returns False otherwise. :type ip: string :param ip: An IP address. :type prefix: string :param prefix: An IP prefix. :rtype: bool :return: True if the IP is in the prefix, False otherwise. """ ip_int = ip2int(ip) network, pfxlen = parse_prefix(prefix) network_int = ip2int(network) mask_int = pfxlen2mask_int(pfxlen) return ip_int&mask_int == network_int&mask_int
[ "def", "matches_prefix", "(", "ip", ",", "prefix", ")", ":", "ip_int", "=", "ip2int", "(", "ip", ")", "network", ",", "pfxlen", "=", "parse_prefix", "(", "prefix", ")", "network_int", "=", "ip2int", "(", "network", ")", "mask_int", "=", "pfxlen2mask_int", ...
Returns True if the given IP address is part of the given network, returns False otherwise. :type ip: string :param ip: An IP address. :type prefix: string :param prefix: An IP prefix. :rtype: bool :return: True if the IP is in the prefix, False otherwise.
[ "Returns", "True", "if", "the", "given", "IP", "address", "is", "part", "of", "the", "given", "network", "returns", "False", "otherwise", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/ipv4.py#L238-L254
train
213,204
knipknap/exscript
Exscript/util/ipv4.py
is_private
def is_private(ip): """ Returns True if the given IP address is private, returns False otherwise. :type ip: string :param ip: An IP address. :rtype: bool :return: True if the IP is private, False otherwise. """ if matches_prefix(ip, '10.0.0.0/8'): return True if matches_prefix(ip, '172.16.0.0/12'): return True if matches_prefix(ip, '192.168.0.0/16'): return True return False
python
def is_private(ip): """ Returns True if the given IP address is private, returns False otherwise. :type ip: string :param ip: An IP address. :rtype: bool :return: True if the IP is private, False otherwise. """ if matches_prefix(ip, '10.0.0.0/8'): return True if matches_prefix(ip, '172.16.0.0/12'): return True if matches_prefix(ip, '192.168.0.0/16'): return True return False
[ "def", "is_private", "(", "ip", ")", ":", "if", "matches_prefix", "(", "ip", ",", "'10.0.0.0/8'", ")", ":", "return", "True", "if", "matches_prefix", "(", "ip", ",", "'172.16.0.0/12'", ")", ":", "return", "True", "if", "matches_prefix", "(", "ip", ",", "...
Returns True if the given IP address is private, returns False otherwise. :type ip: string :param ip: An IP address. :rtype: bool :return: True if the IP is private, False otherwise.
[ "Returns", "True", "if", "the", "given", "IP", "address", "is", "private", "returns", "False", "otherwise", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/ipv4.py#L257-L273
train
213,205
knipknap/exscript
Exscript/util/ipv4.py
sort
def sort(iterable): """ Given an IP address list, this function sorts the list. :type iterable: Iterator :param iterable: An IP address list. :rtype: list :return: The sorted IP address list. """ ips = sorted(normalize_ip(ip) for ip in iterable) return [clean_ip(ip) for ip in ips]
python
def sort(iterable): """ Given an IP address list, this function sorts the list. :type iterable: Iterator :param iterable: An IP address list. :rtype: list :return: The sorted IP address list. """ ips = sorted(normalize_ip(ip) for ip in iterable) return [clean_ip(ip) for ip in ips]
[ "def", "sort", "(", "iterable", ")", ":", "ips", "=", "sorted", "(", "normalize_ip", "(", "ip", ")", "for", "ip", "in", "iterable", ")", "return", "[", "clean_ip", "(", "ip", ")", "for", "ip", "in", "ips", "]" ]
Given an IP address list, this function sorts the list. :type iterable: Iterator :param iterable: An IP address list. :rtype: list :return: The sorted IP address list.
[ "Given", "an", "IP", "address", "list", "this", "function", "sorts", "the", "list", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/ipv4.py#L276-L286
train
213,206
knipknap/exscript
Exscript/servers/httpd.py
_parse_url
def _parse_url(path): """Given a urlencoded path, returns the path and the dictionary of query arguments, all in Unicode.""" # path changes from bytes to Unicode in going from Python 2 to # Python 3. if sys.version_info[0] < 3: o = urlparse(urllib.parse.unquote_plus(path).decode('utf8')) else: o = urlparse(urllib.parse.unquote_plus(path)) path = o.path args = {} # Convert parse_qs' str --> [str] dictionary to a str --> str # dictionary since we never use multi-value GET arguments # anyway. multiargs = parse_qs(o.query, keep_blank_values=True) for arg, value in list(multiargs.items()): args[arg] = value[0] return path, args
python
def _parse_url(path): """Given a urlencoded path, returns the path and the dictionary of query arguments, all in Unicode.""" # path changes from bytes to Unicode in going from Python 2 to # Python 3. if sys.version_info[0] < 3: o = urlparse(urllib.parse.unquote_plus(path).decode('utf8')) else: o = urlparse(urllib.parse.unquote_plus(path)) path = o.path args = {} # Convert parse_qs' str --> [str] dictionary to a str --> str # dictionary since we never use multi-value GET arguments # anyway. multiargs = parse_qs(o.query, keep_blank_values=True) for arg, value in list(multiargs.items()): args[arg] = value[0] return path, args
[ "def", "_parse_url", "(", "path", ")", ":", "# path changes from bytes to Unicode in going from Python 2 to", "# Python 3.", "if", "sys", ".", "version_info", "[", "0", "]", "<", "3", ":", "o", "=", "urlparse", "(", "urllib", ".", "parse", ".", "unquote_plus", "...
Given a urlencoded path, returns the path and the dictionary of query arguments, all in Unicode.
[ "Given", "a", "urlencoded", "path", "returns", "the", "path", "and", "the", "dictionary", "of", "query", "arguments", "all", "in", "Unicode", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/servers/httpd.py#L50-L71
train
213,207
knipknap/exscript
Exscript/servers/httpd.py
_require_authenticate
def _require_authenticate(func): '''A decorator to add digest authorization checks to HTTP Request Handlers''' def wrapped(self): if not hasattr(self, 'authenticated'): self.authenticated = None if self.authenticated: return func(self) auth = self.headers.get(u'Authorization') if auth is None: msg = u"You are not allowed to access this page. Please login first!" return _error_401(self, msg) token, fields = auth.split(' ', 1) if token != 'Digest': return _error_401(self, 'Unsupported authentication type') # Check the header fields of the request. cred = parse_http_list(fields) cred = parse_keqv_list(cred) keys = u'realm', u'username', u'nonce', u'uri', u'response' if not all(cred.get(key) for key in keys): return _error_401(self, 'Incomplete authentication header') if cred['realm'] != self.server.realm: return _error_401(self, 'Incorrect realm') if 'qop' in cred and ('nc' not in cred or 'cnonce' not in cred): return _error_401(self, 'qop with missing nc or cnonce') # Check the username. username = cred['username'] password = self.server.get_password(username) if not username or password is None: return _error_401(self, 'Invalid username or password') # Check the digest string. location = u'%s:%s' % (self.command, self.path) location = md5hex(location.encode('utf8')) pwhash = md5hex('%s:%s:%s' % (username, self.server.realm, password)) if 'qop' in cred: info = (cred['nonce'], cred['nc'], cred['cnonce'], cred['qop'], location) else: info = cred['nonce'], location expect = u'%s:%s' % (pwhash, ':'.join(info)) expect = md5hex(expect.encode('utf8')) if expect != cred['response']: return _error_401(self, 'Invalid username or password') # Success! self.authenticated = True return func(self) return wrapped
python
def _require_authenticate(func): '''A decorator to add digest authorization checks to HTTP Request Handlers''' def wrapped(self): if not hasattr(self, 'authenticated'): self.authenticated = None if self.authenticated: return func(self) auth = self.headers.get(u'Authorization') if auth is None: msg = u"You are not allowed to access this page. Please login first!" return _error_401(self, msg) token, fields = auth.split(' ', 1) if token != 'Digest': return _error_401(self, 'Unsupported authentication type') # Check the header fields of the request. cred = parse_http_list(fields) cred = parse_keqv_list(cred) keys = u'realm', u'username', u'nonce', u'uri', u'response' if not all(cred.get(key) for key in keys): return _error_401(self, 'Incomplete authentication header') if cred['realm'] != self.server.realm: return _error_401(self, 'Incorrect realm') if 'qop' in cred and ('nc' not in cred or 'cnonce' not in cred): return _error_401(self, 'qop with missing nc or cnonce') # Check the username. username = cred['username'] password = self.server.get_password(username) if not username or password is None: return _error_401(self, 'Invalid username or password') # Check the digest string. location = u'%s:%s' % (self.command, self.path) location = md5hex(location.encode('utf8')) pwhash = md5hex('%s:%s:%s' % (username, self.server.realm, password)) if 'qop' in cred: info = (cred['nonce'], cred['nc'], cred['cnonce'], cred['qop'], location) else: info = cred['nonce'], location expect = u'%s:%s' % (pwhash, ':'.join(info)) expect = md5hex(expect.encode('utf8')) if expect != cred['response']: return _error_401(self, 'Invalid username or password') # Success! self.authenticated = True return func(self) return wrapped
[ "def", "_require_authenticate", "(", "func", ")", ":", "def", "wrapped", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'authenticated'", ")", ":", "self", ".", "authenticated", "=", "None", "if", "self", ".", "authenticated", ":", "re...
A decorator to add digest authorization checks to HTTP Request Handlers
[ "A", "decorator", "to", "add", "digest", "authorization", "checks", "to", "HTTP", "Request", "Handlers" ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/servers/httpd.py#L90-L148
train
213,208
knipknap/exscript
Exscript/servers/httpd.py
RequestHandler._do_POSTGET
def _do_POSTGET(self, handler): """handle an HTTP request""" # at first, assume that the given path is the actual path and there are # no arguments self.server._dbg(self.path) self.path, self.args = _parse_url(self.path) # Extract POST data, if any. Clumsy syntax due to Python 2 and # 2to3's lack of a byte literal. self.data = u"".encode() length = self.headers.get('Content-Length') if length and length.isdigit(): self.data = self.rfile.read(int(length)) # POST data gets automatically decoded into Unicode. The bytestring # will still be available in the bdata attribute. self.bdata = self.data try: self.data = self.data.decode('utf8') except UnicodeDecodeError: self.data = None # Run the handler. try: handler() except: self.send_response(500) self.end_headers() self.wfile.write(format_exc().encode('utf8'))
python
def _do_POSTGET(self, handler): """handle an HTTP request""" # at first, assume that the given path is the actual path and there are # no arguments self.server._dbg(self.path) self.path, self.args = _parse_url(self.path) # Extract POST data, if any. Clumsy syntax due to Python 2 and # 2to3's lack of a byte literal. self.data = u"".encode() length = self.headers.get('Content-Length') if length and length.isdigit(): self.data = self.rfile.read(int(length)) # POST data gets automatically decoded into Unicode. The bytestring # will still be available in the bdata attribute. self.bdata = self.data try: self.data = self.data.decode('utf8') except UnicodeDecodeError: self.data = None # Run the handler. try: handler() except: self.send_response(500) self.end_headers() self.wfile.write(format_exc().encode('utf8'))
[ "def", "_do_POSTGET", "(", "self", ",", "handler", ")", ":", "# at first, assume that the given path is the actual path and there are", "# no arguments", "self", ".", "server", ".", "_dbg", "(", "self", ".", "path", ")", "self", ".", "path", ",", "self", ".", "arg...
handle an HTTP request
[ "handle", "an", "HTTP", "request" ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/servers/httpd.py#L220-L249
train
213,209
knipknap/exscript
Exscript/util/buffer.py
MonitoredBuffer.head
def head(self, bytes): """ Returns the number of given bytes from the head of the buffer. The buffer remains unchanged. :type bytes: int :param bytes: The number of bytes to return. """ oldpos = self.io.tell() self.io.seek(0) head = self.io.read(bytes) self.io.seek(oldpos) return head
python
def head(self, bytes): """ Returns the number of given bytes from the head of the buffer. The buffer remains unchanged. :type bytes: int :param bytes: The number of bytes to return. """ oldpos = self.io.tell() self.io.seek(0) head = self.io.read(bytes) self.io.seek(oldpos) return head
[ "def", "head", "(", "self", ",", "bytes", ")", ":", "oldpos", "=", "self", ".", "io", ".", "tell", "(", ")", "self", ".", "io", ".", "seek", "(", "0", ")", "head", "=", "self", ".", "io", ".", "read", "(", "bytes", ")", "self", ".", "io", "...
Returns the number of given bytes from the head of the buffer. The buffer remains unchanged. :type bytes: int :param bytes: The number of bytes to return.
[ "Returns", "the", "number", "of", "given", "bytes", "from", "the", "head", "of", "the", "buffer", ".", "The", "buffer", "remains", "unchanged", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/buffer.py#L71-L83
train
213,210
knipknap/exscript
Exscript/util/buffer.py
MonitoredBuffer.tail
def tail(self, bytes): """ Returns the number of given bytes from the tail of the buffer. The buffer remains unchanged. :type bytes: int :param bytes: The number of bytes to return. """ self.io.seek(max(0, self.size() - bytes)) return self.io.read()
python
def tail(self, bytes): """ Returns the number of given bytes from the tail of the buffer. The buffer remains unchanged. :type bytes: int :param bytes: The number of bytes to return. """ self.io.seek(max(0, self.size() - bytes)) return self.io.read()
[ "def", "tail", "(", "self", ",", "bytes", ")", ":", "self", ".", "io", ".", "seek", "(", "max", "(", "0", ",", "self", ".", "size", "(", ")", "-", "bytes", ")", ")", "return", "self", ".", "io", ".", "read", "(", ")" ]
Returns the number of given bytes from the tail of the buffer. The buffer remains unchanged. :type bytes: int :param bytes: The number of bytes to return.
[ "Returns", "the", "number", "of", "given", "bytes", "from", "the", "tail", "of", "the", "buffer", ".", "The", "buffer", "remains", "unchanged", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/buffer.py#L85-L94
train
213,211
knipknap/exscript
Exscript/util/buffer.py
MonitoredBuffer.append
def append(self, data): """ Appends the given data to the buffer, and triggers all connected monitors, if any of them match the buffer content. :type data: str :param data: The data that is appended. """ self.io.write(data) if not self.monitors: return # Check whether any of the monitoring regular expressions matches. # If it does, we need to disable that monitor until the matching # data is no longer in the buffer. We accomplish this by keeping # track of the position of the last matching byte. buf = str(self) for item in self.monitors: regex_list, callback, bytepos, limit = item bytepos = max(bytepos, len(buf) - limit) for i, regex in enumerate(regex_list): match = regex.search(buf, bytepos) if match is not None: item[2] = match.end() callback(i, match)
python
def append(self, data): """ Appends the given data to the buffer, and triggers all connected monitors, if any of them match the buffer content. :type data: str :param data: The data that is appended. """ self.io.write(data) if not self.monitors: return # Check whether any of the monitoring regular expressions matches. # If it does, we need to disable that monitor until the matching # data is no longer in the buffer. We accomplish this by keeping # track of the position of the last matching byte. buf = str(self) for item in self.monitors: regex_list, callback, bytepos, limit = item bytepos = max(bytepos, len(buf) - limit) for i, regex in enumerate(regex_list): match = regex.search(buf, bytepos) if match is not None: item[2] = match.end() callback(i, match)
[ "def", "append", "(", "self", ",", "data", ")", ":", "self", ".", "io", ".", "write", "(", "data", ")", "if", "not", "self", ".", "monitors", ":", "return", "# Check whether any of the monitoring regular expressions matches.", "# If it does, we need to disable that mo...
Appends the given data to the buffer, and triggers all connected monitors, if any of them match the buffer content. :type data: str :param data: The data that is appended.
[ "Appends", "the", "given", "data", "to", "the", "buffer", "and", "triggers", "all", "connected", "monitors", "if", "any", "of", "them", "match", "the", "buffer", "content", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/buffer.py#L111-L135
train
213,212
knipknap/exscript
Exscript/util/buffer.py
MonitoredBuffer.clear
def clear(self): """ Removes all data from the buffer. """ self.io.seek(0) self.io.truncate() for item in self.monitors: item[2] = 0
python
def clear(self): """ Removes all data from the buffer. """ self.io.seek(0) self.io.truncate() for item in self.monitors: item[2] = 0
[ "def", "clear", "(", "self", ")", ":", "self", ".", "io", ".", "seek", "(", "0", ")", "self", ".", "io", ".", "truncate", "(", ")", "for", "item", "in", "self", ".", "monitors", ":", "item", "[", "2", "]", "=", "0" ]
Removes all data from the buffer.
[ "Removes", "all", "data", "from", "the", "buffer", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/buffer.py#L137-L144
train
213,213
knipknap/exscript
Exscript/util/buffer.py
MonitoredBuffer.add_monitor
def add_monitor(self, pattern, callback, limit=80): """ Calls the given function whenever the given pattern matches the buffer. Arguments passed to the callback are the index of the match, and the match object of the regular expression. :type pattern: str|re.RegexObject|list(str|re.RegexObject) :param pattern: One or more regular expressions. :type callback: callable :param callback: The function that is called. :type limit: int :param limit: The maximum size of the tail of the buffer that is searched, in number of bytes. """ self.monitors.append([to_regexs(pattern), callback, 0, limit])
python
def add_monitor(self, pattern, callback, limit=80): """ Calls the given function whenever the given pattern matches the buffer. Arguments passed to the callback are the index of the match, and the match object of the regular expression. :type pattern: str|re.RegexObject|list(str|re.RegexObject) :param pattern: One or more regular expressions. :type callback: callable :param callback: The function that is called. :type limit: int :param limit: The maximum size of the tail of the buffer that is searched, in number of bytes. """ self.monitors.append([to_regexs(pattern), callback, 0, limit])
[ "def", "add_monitor", "(", "self", ",", "pattern", ",", "callback", ",", "limit", "=", "80", ")", ":", "self", ".", "monitors", ".", "append", "(", "[", "to_regexs", "(", "pattern", ")", ",", "callback", ",", "0", ",", "limit", "]", ")" ]
Calls the given function whenever the given pattern matches the buffer. Arguments passed to the callback are the index of the match, and the match object of the regular expression. :type pattern: str|re.RegexObject|list(str|re.RegexObject) :param pattern: One or more regular expressions. :type callback: callable :param callback: The function that is called. :type limit: int :param limit: The maximum size of the tail of the buffer that is searched, in number of bytes.
[ "Calls", "the", "given", "function", "whenever", "the", "given", "pattern", "matches", "the", "buffer", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/buffer.py#L146-L162
train
213,214
knipknap/exscript
Exscript/util/mail.py
from_template_string
def from_template_string(string, **kwargs): """ Reads the given SMTP formatted template, and creates a new Mail object using the information. :type string: str :param string: The SMTP formatted template. :type kwargs: str :param kwargs: Variables to replace in the template. :rtype: Mail :return: The resulting mail. """ tmpl = _render_template(string, **kwargs) mail = Mail() mail.set_from_template_string(tmpl) return mail
python
def from_template_string(string, **kwargs): """ Reads the given SMTP formatted template, and creates a new Mail object using the information. :type string: str :param string: The SMTP formatted template. :type kwargs: str :param kwargs: Variables to replace in the template. :rtype: Mail :return: The resulting mail. """ tmpl = _render_template(string, **kwargs) mail = Mail() mail.set_from_template_string(tmpl) return mail
[ "def", "from_template_string", "(", "string", ",", "*", "*", "kwargs", ")", ":", "tmpl", "=", "_render_template", "(", "string", ",", "*", "*", "kwargs", ")", "mail", "=", "Mail", "(", ")", "mail", ".", "set_from_template_string", "(", "tmpl", ")", "retu...
Reads the given SMTP formatted template, and creates a new Mail object using the information. :type string: str :param string: The SMTP formatted template. :type kwargs: str :param kwargs: Variables to replace in the template. :rtype: Mail :return: The resulting mail.
[ "Reads", "the", "given", "SMTP", "formatted", "template", "and", "creates", "a", "new", "Mail", "object", "using", "the", "information", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/mail.py#L399-L414
train
213,215
knipknap/exscript
Exscript/util/mail.py
send
def send(mail, server='localhost'): """ Sends the given mail. :type mail: Mail :param mail: The mail object. :type server: string :param server: The address of the mailserver. """ sender = mail.get_sender() rcpt = mail.get_receipients() session = smtplib.SMTP(server) message = MIMEMultipart() message['Subject'] = mail.get_subject() message['From'] = mail.get_sender() message['To'] = ', '.join(mail.get_to()) message['Cc'] = ', '.join(mail.get_cc()) message.preamble = 'Your mail client is not MIME aware.' body = MIMEText(mail.get_body().encode("utf-8"), "plain", "utf-8") body.add_header('Content-Disposition', 'inline') message.attach(body) for filename in mail.get_attachments(): message.attach(_get_mime_object(filename)) session.sendmail(sender, rcpt, message.as_string())
python
def send(mail, server='localhost'): """ Sends the given mail. :type mail: Mail :param mail: The mail object. :type server: string :param server: The address of the mailserver. """ sender = mail.get_sender() rcpt = mail.get_receipients() session = smtplib.SMTP(server) message = MIMEMultipart() message['Subject'] = mail.get_subject() message['From'] = mail.get_sender() message['To'] = ', '.join(mail.get_to()) message['Cc'] = ', '.join(mail.get_cc()) message.preamble = 'Your mail client is not MIME aware.' body = MIMEText(mail.get_body().encode("utf-8"), "plain", "utf-8") body.add_header('Content-Disposition', 'inline') message.attach(body) for filename in mail.get_attachments(): message.attach(_get_mime_object(filename)) session.sendmail(sender, rcpt, message.as_string())
[ "def", "send", "(", "mail", ",", "server", "=", "'localhost'", ")", ":", "sender", "=", "mail", ".", "get_sender", "(", ")", "rcpt", "=", "mail", ".", "get_receipients", "(", ")", "session", "=", "smtplib", ".", "SMTP", "(", "server", ")", "message", ...
Sends the given mail. :type mail: Mail :param mail: The mail object. :type server: string :param server: The address of the mailserver.
[ "Sends", "the", "given", "mail", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/mail.py#L462-L488
train
213,216
knipknap/exscript
Exscript/util/mail.py
Mail.get_smtp_header
def get_smtp_header(self): """ Returns the SMTP formatted header of the line. :rtype: string :return: The SMTP header. """ header = "From: %s\r\n" % self.get_sender() header += "To: %s\r\n" % ',\r\n '.join(self.get_to()) header += "Cc: %s\r\n" % ',\r\n '.join(self.get_cc()) header += "Bcc: %s\r\n" % ',\r\n '.join(self.get_bcc()) header += "Subject: %s\r\n" % self.get_subject() return header
python
def get_smtp_header(self): """ Returns the SMTP formatted header of the line. :rtype: string :return: The SMTP header. """ header = "From: %s\r\n" % self.get_sender() header += "To: %s\r\n" % ',\r\n '.join(self.get_to()) header += "Cc: %s\r\n" % ',\r\n '.join(self.get_cc()) header += "Bcc: %s\r\n" % ',\r\n '.join(self.get_bcc()) header += "Subject: %s\r\n" % self.get_subject() return header
[ "def", "get_smtp_header", "(", "self", ")", ":", "header", "=", "\"From: %s\\r\\n\"", "%", "self", ".", "get_sender", "(", ")", "header", "+=", "\"To: %s\\r\\n\"", "%", "',\\r\\n '", ".", "join", "(", "self", ".", "get_to", "(", ")", ")", "header", "+=", ...
Returns the SMTP formatted header of the line. :rtype: string :return: The SMTP header.
[ "Returns", "the", "SMTP", "formatted", "header", "of", "the", "line", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/mail.py#L355-L367
train
213,217
knipknap/exscript
Exscript/util/mail.py
Mail.get_smtp_mail
def get_smtp_mail(self): """ Returns the SMTP formatted email, as it may be passed to sendmail. :rtype: string :return: The SMTP formatted mail. """ header = self.get_smtp_header() body = self.get_body().replace('\n', '\r\n') return header + '\r\n' + body + '\r\n'
python
def get_smtp_mail(self): """ Returns the SMTP formatted email, as it may be passed to sendmail. :rtype: string :return: The SMTP formatted mail. """ header = self.get_smtp_header() body = self.get_body().replace('\n', '\r\n') return header + '\r\n' + body + '\r\n'
[ "def", "get_smtp_mail", "(", "self", ")", ":", "header", "=", "self", ".", "get_smtp_header", "(", ")", "body", "=", "self", ".", "get_body", "(", ")", ".", "replace", "(", "'\\n'", ",", "'\\r\\n'", ")", "return", "header", "+", "'\\r\\n'", "+", "body"...
Returns the SMTP formatted email, as it may be passed to sendmail. :rtype: string :return: The SMTP formatted mail.
[ "Returns", "the", "SMTP", "formatted", "email", "as", "it", "may", "be", "passed", "to", "sendmail", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/mail.py#L369-L378
train
213,218
knipknap/exscript
Exscript/util/report.py
status
def status(logger): """ Creates a one-line summary on the actions that were logged by the given Logger. :type logger: Logger :param logger: The logger that recorded what happened in the queue. :rtype: string :return: A string summarizing the status. """ aborted = logger.get_aborted_actions() succeeded = logger.get_succeeded_actions() total = aborted + succeeded if total == 0: return 'No actions done' elif total == 1 and succeeded == 1: return 'One action done (succeeded)' elif total == 1 and succeeded == 0: return 'One action done (failed)' elif total == succeeded: return '%d actions total (all succeeded)' % total elif succeeded == 0: return '%d actions total (all failed)' % total else: msg = '%d actions total (%d failed, %d succeeded)' return msg % (total, aborted, succeeded)
python
def status(logger): """ Creates a one-line summary on the actions that were logged by the given Logger. :type logger: Logger :param logger: The logger that recorded what happened in the queue. :rtype: string :return: A string summarizing the status. """ aborted = logger.get_aborted_actions() succeeded = logger.get_succeeded_actions() total = aborted + succeeded if total == 0: return 'No actions done' elif total == 1 and succeeded == 1: return 'One action done (succeeded)' elif total == 1 and succeeded == 0: return 'One action done (failed)' elif total == succeeded: return '%d actions total (all succeeded)' % total elif succeeded == 0: return '%d actions total (all failed)' % total else: msg = '%d actions total (%d failed, %d succeeded)' return msg % (total, aborted, succeeded)
[ "def", "status", "(", "logger", ")", ":", "aborted", "=", "logger", ".", "get_aborted_actions", "(", ")", "succeeded", "=", "logger", ".", "get_succeeded_actions", "(", ")", "total", "=", "aborted", "+", "succeeded", "if", "total", "==", "0", ":", "return"...
Creates a one-line summary on the actions that were logged by the given Logger. :type logger: Logger :param logger: The logger that recorded what happened in the queue. :rtype: string :return: A string summarizing the status.
[ "Creates", "a", "one", "-", "line", "summary", "on", "the", "actions", "that", "were", "logged", "by", "the", "given", "Logger", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/report.py#L32-L57
train
213,219
knipknap/exscript
Exscript/util/report.py
summarize
def summarize(logger): """ Creates a short summary on the actions that were logged by the given Logger. :type logger: Logger :param logger: The logger that recorded what happened in the queue. :rtype: string :return: A string summarizing the status of every performed task. """ summary = [] for log in logger.get_logs(): thestatus = log.has_error() and log.get_error(False) or 'ok' name = log.get_name() summary.append(name + ': ' + thestatus) return '\n'.join(summary)
python
def summarize(logger): """ Creates a short summary on the actions that were logged by the given Logger. :type logger: Logger :param logger: The logger that recorded what happened in the queue. :rtype: string :return: A string summarizing the status of every performed task. """ summary = [] for log in logger.get_logs(): thestatus = log.has_error() and log.get_error(False) or 'ok' name = log.get_name() summary.append(name + ': ' + thestatus) return '\n'.join(summary)
[ "def", "summarize", "(", "logger", ")", ":", "summary", "=", "[", "]", "for", "log", "in", "logger", ".", "get_logs", "(", ")", ":", "thestatus", "=", "log", ".", "has_error", "(", ")", "and", "log", ".", "get_error", "(", "False", ")", "or", "'ok'...
Creates a short summary on the actions that were logged by the given Logger. :type logger: Logger :param logger: The logger that recorded what happened in the queue. :rtype: string :return: A string summarizing the status of every performed task.
[ "Creates", "a", "short", "summary", "on", "the", "actions", "that", "were", "logged", "by", "the", "given", "Logger", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/report.py#L60-L75
train
213,220
knipknap/exscript
Exscript/util/report.py
format
def format(logger, show_successful=True, show_errors=True, show_traceback=True): """ Prints a report of the actions that were logged by the given Logger. The report contains a list of successful actions, as well as the full error message on failed actions. :type logger: Logger :param logger: The logger that recorded what happened in the queue. :rtype: string :return: A string summarizing the status of every performed task. """ output = [] # Print failed actions. errors = logger.get_aborted_actions() if show_errors and errors: output += _underline('Failed actions:') for log in logger.get_aborted_logs(): if show_traceback: output.append(log.get_name() + ':') output.append(log.get_error()) else: output.append(log.get_name() + ': ' + log.get_error(False)) output.append('') # Print successful actions. if show_successful: output += _underline('Successful actions:') for log in logger.get_succeeded_logs(): output.append(log.get_name()) output.append('') return '\n'.join(output).strip()
python
def format(logger, show_successful=True, show_errors=True, show_traceback=True): """ Prints a report of the actions that were logged by the given Logger. The report contains a list of successful actions, as well as the full error message on failed actions. :type logger: Logger :param logger: The logger that recorded what happened in the queue. :rtype: string :return: A string summarizing the status of every performed task. """ output = [] # Print failed actions. errors = logger.get_aborted_actions() if show_errors and errors: output += _underline('Failed actions:') for log in logger.get_aborted_logs(): if show_traceback: output.append(log.get_name() + ':') output.append(log.get_error()) else: output.append(log.get_name() + ': ' + log.get_error(False)) output.append('') # Print successful actions. if show_successful: output += _underline('Successful actions:') for log in logger.get_succeeded_logs(): output.append(log.get_name()) output.append('') return '\n'.join(output).strip()
[ "def", "format", "(", "logger", ",", "show_successful", "=", "True", ",", "show_errors", "=", "True", ",", "show_traceback", "=", "True", ")", ":", "output", "=", "[", "]", "# Print failed actions.", "errors", "=", "logger", ".", "get_aborted_actions", "(", ...
Prints a report of the actions that were logged by the given Logger. The report contains a list of successful actions, as well as the full error message on failed actions. :type logger: Logger :param logger: The logger that recorded what happened in the queue. :rtype: string :return: A string summarizing the status of every performed task.
[ "Prints", "a", "report", "of", "the", "actions", "that", "were", "logged", "by", "the", "given", "Logger", ".", "The", "report", "contains", "a", "list", "of", "successful", "actions", "as", "well", "as", "the", "full", "error", "message", "on", "failed", ...
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/report.py#L78-L113
train
213,221
knipknap/exscript
Exscript/interpreter/scope.py
Scope.get_vars
def get_vars(self): """ Returns a complete dict of all variables that are defined in this scope, including the variables of the parent. """ if self.parent is None: vars = {} vars.update(self.variables) return vars vars = self.parent.get_vars() vars.update(self.variables) return vars
python
def get_vars(self): """ Returns a complete dict of all variables that are defined in this scope, including the variables of the parent. """ if self.parent is None: vars = {} vars.update(self.variables) return vars vars = self.parent.get_vars() vars.update(self.variables) return vars
[ "def", "get_vars", "(", "self", ")", ":", "if", "self", ".", "parent", "is", "None", ":", "vars", "=", "{", "}", "vars", ".", "update", "(", "self", ".", "variables", ")", "return", "vars", "vars", "=", "self", ".", "parent", ".", "get_vars", "(", ...
Returns a complete dict of all variables that are defined in this scope, including the variables of the parent.
[ "Returns", "a", "complete", "dict", "of", "all", "variables", "that", "are", "defined", "in", "this", "scope", "including", "the", "variables", "of", "the", "parent", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/interpreter/scope.py#L62-L73
train
213,222
knipknap/exscript
Exscript/workqueue/pipeline.py
Pipeline.get_from_name
def get_from_name(self, name): """ Returns the item with the given name, or None if no such item is known. """ with self.condition: try: item_id = self.name2id[name] except KeyError: return None return self.id2item[item_id] return None
python
def get_from_name(self, name): """ Returns the item with the given name, or None if no such item is known. """ with self.condition: try: item_id = self.name2id[name] except KeyError: return None return self.id2item[item_id] return None
[ "def", "get_from_name", "(", "self", ",", "name", ")", ":", "with", "self", ".", "condition", ":", "try", ":", "item_id", "=", "self", ".", "name2id", "[", "name", "]", "except", "KeyError", ":", "return", "None", "return", "self", ".", "id2item", "[",...
Returns the item with the given name, or None if no such item is known.
[ "Returns", "the", "item", "with", "the", "given", "name", "or", "None", "if", "no", "such", "item", "is", "known", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/workqueue/pipeline.py#L72-L83
train
213,223
knipknap/exscript
Exscript/workqueue/pipeline.py
Pipeline.append
def append(self, item, name=None): """ Adds the given item to the end of the pipeline. """ with self.condition: self.queue.append(item) uuid = self._register_item(name, item) self.condition.notify_all() return uuid
python
def append(self, item, name=None): """ Adds the given item to the end of the pipeline. """ with self.condition: self.queue.append(item) uuid = self._register_item(name, item) self.condition.notify_all() return uuid
[ "def", "append", "(", "self", ",", "item", ",", "name", "=", "None", ")", ":", "with", "self", ".", "condition", ":", "self", ".", "queue", ".", "append", "(", "item", ")", "uuid", "=", "self", ".", "_register_item", "(", "name", ",", "item", ")", ...
Adds the given item to the end of the pipeline.
[ "Adds", "the", "given", "item", "to", "the", "end", "of", "the", "pipeline", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/workqueue/pipeline.py#L112-L120
train
213,224
knipknap/exscript
Exscript/workqueue/pipeline.py
Pipeline.prioritize
def prioritize(self, item, force=False): """ Moves the item to the very left of the queue. """ with self.condition: # If the job is already running (or about to be forced), # there is nothing to be done. if item in self.working or item in self.force: return self.queue.remove(item) if force: self.force.append(item) else: self.queue.appendleft(item) self.condition.notify_all()
python
def prioritize(self, item, force=False): """ Moves the item to the very left of the queue. """ with self.condition: # If the job is already running (or about to be forced), # there is nothing to be done. if item in self.working or item in self.force: return self.queue.remove(item) if force: self.force.append(item) else: self.queue.appendleft(item) self.condition.notify_all()
[ "def", "prioritize", "(", "self", ",", "item", ",", "force", "=", "False", ")", ":", "with", "self", ".", "condition", ":", "# If the job is already running (or about to be forced),", "# there is nothing to be done.", "if", "item", "in", "self", ".", "working", "or"...
Moves the item to the very left of the queue.
[ "Moves", "the", "item", "to", "the", "very", "left", "of", "the", "queue", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/workqueue/pipeline.py#L132-L146
train
213,225
knipknap/exscript
Exscript/util/file.py
get_hosts_from_file
def get_hosts_from_file(filename, default_protocol='telnet', default_domain='', remove_duplicates=False, encoding='utf-8'): """ Reads a list of hostnames from the file with the given name. :type filename: string :param filename: A full filename. :type default_protocol: str :param default_protocol: Passed to the Host constructor. :type default_domain: str :param default_domain: Appended to each hostname that has no domain. :type remove_duplicates: bool :param remove_duplicates: Whether duplicates are removed. :type encoding: str :param encoding: The encoding of the file. :rtype: list[Host] :return: The newly created host instances. """ # Open the file. if not os.path.exists(filename): raise IOError('No such file: %s' % filename) # Read the hostnames. have = set() hosts = [] with codecs.open(filename, 'r', encoding) as file_handle: for line in file_handle: hostname = line.split('#')[0].strip() if hostname == '': continue if remove_duplicates and hostname in have: continue have.add(hostname) hosts.append(to_host(hostname, default_protocol, default_domain)) return hosts
python
def get_hosts_from_file(filename, default_protocol='telnet', default_domain='', remove_duplicates=False, encoding='utf-8'): """ Reads a list of hostnames from the file with the given name. :type filename: string :param filename: A full filename. :type default_protocol: str :param default_protocol: Passed to the Host constructor. :type default_domain: str :param default_domain: Appended to each hostname that has no domain. :type remove_duplicates: bool :param remove_duplicates: Whether duplicates are removed. :type encoding: str :param encoding: The encoding of the file. :rtype: list[Host] :return: The newly created host instances. """ # Open the file. if not os.path.exists(filename): raise IOError('No such file: %s' % filename) # Read the hostnames. have = set() hosts = [] with codecs.open(filename, 'r', encoding) as file_handle: for line in file_handle: hostname = line.split('#')[0].strip() if hostname == '': continue if remove_duplicates and hostname in have: continue have.add(hostname) hosts.append(to_host(hostname, default_protocol, default_domain)) return hosts
[ "def", "get_hosts_from_file", "(", "filename", ",", "default_protocol", "=", "'telnet'", ",", "default_domain", "=", "''", ",", "remove_duplicates", "=", "False", ",", "encoding", "=", "'utf-8'", ")", ":", "# Open the file.", "if", "not", "os", ".", "path", "....
Reads a list of hostnames from the file with the given name. :type filename: string :param filename: A full filename. :type default_protocol: str :param default_protocol: Passed to the Host constructor. :type default_domain: str :param default_domain: Appended to each hostname that has no domain. :type remove_duplicates: bool :param remove_duplicates: Whether duplicates are removed. :type encoding: str :param encoding: The encoding of the file. :rtype: list[Host] :return: The newly created host instances.
[ "Reads", "a", "list", "of", "hostnames", "from", "the", "file", "with", "the", "given", "name", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/file.py#L75-L113
train
213,226
knipknap/exscript
Exscript/util/log.py
log_to
def log_to(logger): """ Wraps a function that has a connection passed such that everything that happens on the connection is logged using the given logger. :type logger: Logger :param logger: The logger that handles the logging. """ logger_id = id(logger) def decorator(function): func = add_label(function, 'log_to', logger_id=logger_id) return func return decorator
python
def log_to(logger): """ Wraps a function that has a connection passed such that everything that happens on the connection is logged using the given logger. :type logger: Logger :param logger: The logger that handles the logging. """ logger_id = id(logger) def decorator(function): func = add_label(function, 'log_to', logger_id=logger_id) return func return decorator
[ "def", "log_to", "(", "logger", ")", ":", "logger_id", "=", "id", "(", "logger", ")", "def", "decorator", "(", "function", ")", ":", "func", "=", "add_label", "(", "function", ",", "'log_to'", ",", "logger_id", "=", "logger_id", ")", "return", "func", ...
Wraps a function that has a connection passed such that everything that happens on the connection is logged using the given logger. :type logger: Logger :param logger: The logger that handles the logging.
[ "Wraps", "a", "function", "that", "has", "a", "connection", "passed", "such", "that", "everything", "that", "happens", "on", "the", "connection", "is", "logged", "using", "the", "given", "logger", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/log.py#L32-L45
train
213,227
knipknap/exscript
Exscript/protocols/telnetlib.py
Telnet.msg
def msg(self, msg, *args): """Print a debug message, when the debug level is > 0. If extra arguments are present, they are substituted in the message using the standard string formatting operator. """ if self.debuglevel > 0: self.stderr.write('Telnet(%s,%d): ' % (self.host, self.port)) if args: self.stderr.write(msg % args) else: self.stderr.write(msg) self.stderr.write('\n')
python
def msg(self, msg, *args): """Print a debug message, when the debug level is > 0. If extra arguments are present, they are substituted in the message using the standard string formatting operator. """ if self.debuglevel > 0: self.stderr.write('Telnet(%s,%d): ' % (self.host, self.port)) if args: self.stderr.write(msg % args) else: self.stderr.write(msg) self.stderr.write('\n')
[ "def", "msg", "(", "self", ",", "msg", ",", "*", "args", ")", ":", "if", "self", ".", "debuglevel", ">", "0", ":", "self", ".", "stderr", ".", "write", "(", "'Telnet(%s,%d): '", "%", "(", "self", ".", "host", ",", "self", ".", "port", ")", ")", ...
Print a debug message, when the debug level is > 0. If extra arguments are present, they are substituted in the message using the standard string formatting operator.
[ "Print", "a", "debug", "message", "when", "the", "debug", "level", "is", ">", "0", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/protocols/telnetlib.py#L259-L272
train
213,228
knipknap/exscript
Exscript/protocols/telnetlib.py
Telnet.write
def write(self, buffer): """Write a string to the socket, doubling any IAC characters. Can block if the connection is blocked. May raise socket.error if the connection is closed. """ if type(buffer) == type(0): buffer = chr(buffer) elif not isinstance(buffer, bytes): buffer = buffer.encode(self.encoding) if IAC in buffer: buffer = buffer.replace(IAC, IAC+IAC) self.msg("send %s", repr(buffer)) self.sock.send(buffer)
python
def write(self, buffer): """Write a string to the socket, doubling any IAC characters. Can block if the connection is blocked. May raise socket.error if the connection is closed. """ if type(buffer) == type(0): buffer = chr(buffer) elif not isinstance(buffer, bytes): buffer = buffer.encode(self.encoding) if IAC in buffer: buffer = buffer.replace(IAC, IAC+IAC) self.msg("send %s", repr(buffer)) self.sock.send(buffer)
[ "def", "write", "(", "self", ",", "buffer", ")", ":", "if", "type", "(", "buffer", ")", "==", "type", "(", "0", ")", ":", "buffer", "=", "chr", "(", "buffer", ")", "elif", "not", "isinstance", "(", "buffer", ",", "bytes", ")", ":", "buffer", "=",...
Write a string to the socket, doubling any IAC characters. Can block if the connection is blocked. May raise socket.error if the connection is closed.
[ "Write", "a", "string", "to", "the", "socket", "doubling", "any", "IAC", "characters", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/protocols/telnetlib.py#L297-L311
train
213,229
knipknap/exscript
Exscript/protocols/telnetlib.py
Telnet.read_all
def read_all(self): """Read all data until EOF; block until connection closed.""" self.process_rawq() while not self.eof: self.fill_rawq() self.process_rawq() buf = self.cookedq.getvalue() self.cookedq.seek(0) self.cookedq.truncate() return buf
python
def read_all(self): """Read all data until EOF; block until connection closed.""" self.process_rawq() while not self.eof: self.fill_rawq() self.process_rawq() buf = self.cookedq.getvalue() self.cookedq.seek(0) self.cookedq.truncate() return buf
[ "def", "read_all", "(", "self", ")", ":", "self", ".", "process_rawq", "(", ")", "while", "not", "self", ".", "eof", ":", "self", ".", "fill_rawq", "(", ")", "self", ".", "process_rawq", "(", ")", "buf", "=", "self", ".", "cookedq", ".", "getvalue", ...
Read all data until EOF; block until connection closed.
[ "Read", "all", "data", "until", "EOF", ";", "block", "until", "connection", "closed", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/protocols/telnetlib.py#L313-L322
train
213,230
knipknap/exscript
Exscript/protocols/telnetlib.py
Telnet.read_eager
def read_eager(self): """Read readily available data. Raise EOFError if connection closed and no cooked data available. Return '' if no cooked data available otherwise. Don't block unless in the midst of an IAC sequence. """ self.process_rawq() while self.cookedq.tell() == 0 and not self.eof and self.sock_avail(): self.fill_rawq() self.process_rawq() return self.read_very_lazy()
python
def read_eager(self): """Read readily available data. Raise EOFError if connection closed and no cooked data available. Return '' if no cooked data available otherwise. Don't block unless in the midst of an IAC sequence. """ self.process_rawq() while self.cookedq.tell() == 0 and not self.eof and self.sock_avail(): self.fill_rawq() self.process_rawq() return self.read_very_lazy()
[ "def", "read_eager", "(", "self", ")", ":", "self", ".", "process_rawq", "(", ")", "while", "self", ".", "cookedq", ".", "tell", "(", ")", "==", "0", "and", "not", "self", ".", "eof", "and", "self", ".", "sock_avail", "(", ")", ":", "self", ".", ...
Read readily available data. Raise EOFError if connection closed and no cooked data available. Return '' if no cooked data available otherwise. Don't block unless in the midst of an IAC sequence.
[ "Read", "readily", "available", "data", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/protocols/telnetlib.py#L354-L366
train
213,231
knipknap/exscript
Exscript/protocols/telnetlib.py
Telnet.set_receive_callback
def set_receive_callback(self, callback, *args, **kwargs): """The callback function called after each receipt of any data.""" self.data_callback = callback self.data_callback_kwargs = kwargs
python
def set_receive_callback(self, callback, *args, **kwargs): """The callback function called after each receipt of any data.""" self.data_callback = callback self.data_callback_kwargs = kwargs
[ "def", "set_receive_callback", "(", "self", ",", "callback", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "data_callback", "=", "callback", "self", ".", "data_callback_kwargs", "=", "kwargs" ]
The callback function called after each receipt of any data.
[ "The", "callback", "function", "called", "after", "each", "receipt", "of", "any", "data", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/protocols/telnetlib.py#L393-L396
train
213,232
knipknap/exscript
Exscript/protocols/telnetlib.py
Telnet.set_window_size
def set_window_size(self, rows, cols): """ Change the size of the terminal window, if the remote end supports NAWS. If it doesn't, the method returns silently. """ if not self.can_naws: return self.window_size = rows, cols size = struct.pack('!HH', cols, rows) self.sock.send(IAC + SB + NAWS + size + IAC + SE)
python
def set_window_size(self, rows, cols): """ Change the size of the terminal window, if the remote end supports NAWS. If it doesn't, the method returns silently. """ if not self.can_naws: return self.window_size = rows, cols size = struct.pack('!HH', cols, rows) self.sock.send(IAC + SB + NAWS + size + IAC + SE)
[ "def", "set_window_size", "(", "self", ",", "rows", ",", "cols", ")", ":", "if", "not", "self", ".", "can_naws", ":", "return", "self", ".", "window_size", "=", "rows", ",", "cols", "size", "=", "struct", ".", "pack", "(", "'!HH'", ",", "cols", ",", ...
Change the size of the terminal window, if the remote end supports NAWS. If it doesn't, the method returns silently.
[ "Change", "the", "size", "of", "the", "terminal", "window", "if", "the", "remote", "end", "supports", "NAWS", ".", "If", "it", "doesn", "t", "the", "method", "returns", "silently", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/protocols/telnetlib.py#L398-L407
train
213,233
knipknap/exscript
Exscript/protocols/telnetlib.py
Telnet.interact
def interact(self): """Interaction function, emulates a very dumb telnet client.""" if sys.platform == "win32": self.mt_interact() return while True: rfd, wfd, xfd = select.select([self, sys.stdin], [], []) if self in rfd: try: text = self.read_eager() except EOFError: print('*** Connection closed by remote host ***') break if text: self.stdout.write(text) self.stdout.flush() if sys.stdin in rfd: line = sys.stdin.readline() if not line: break self.write(line)
python
def interact(self): """Interaction function, emulates a very dumb telnet client.""" if sys.platform == "win32": self.mt_interact() return while True: rfd, wfd, xfd = select.select([self, sys.stdin], [], []) if self in rfd: try: text = self.read_eager() except EOFError: print('*** Connection closed by remote host ***') break if text: self.stdout.write(text) self.stdout.flush() if sys.stdin in rfd: line = sys.stdin.readline() if not line: break self.write(line)
[ "def", "interact", "(", "self", ")", ":", "if", "sys", ".", "platform", "==", "\"win32\"", ":", "self", ".", "mt_interact", "(", ")", "return", "while", "True", ":", "rfd", ",", "wfd", ",", "xfd", "=", "select", ".", "select", "(", "[", "self", ","...
Interaction function, emulates a very dumb telnet client.
[ "Interaction", "function", "emulates", "a", "very", "dumb", "telnet", "client", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/protocols/telnetlib.py#L554-L574
train
213,234
knipknap/exscript
Exscript/protocols/telnetlib.py
Telnet.waitfor
def waitfor(self, relist, timeout=None, cleanup=None): """Read until one from a list of a regular expressions matches. The first argument is a list of regular expressions, either compiled (re.RegexObject instances) or uncompiled (strings). The optional second argument is a timeout, in seconds; default is no timeout. Return a tuple of three items: the index in the list of the first regular expression that matches; the match object returned; and the text read up till and including the match. If EOF is read and no text was read, raise EOFError. Otherwise, when nothing matches, return (-1, None, text) where text is the text received so far (may be the empty string if a timeout happened). If a regular expression ends with a greedy match (e.g. '.*') or if more than one expression can match the same input, the results are undeterministic, and may depend on the I/O timing. """ return self._waitfor(relist, timeout, False, cleanup)
python
def waitfor(self, relist, timeout=None, cleanup=None): """Read until one from a list of a regular expressions matches. The first argument is a list of regular expressions, either compiled (re.RegexObject instances) or uncompiled (strings). The optional second argument is a timeout, in seconds; default is no timeout. Return a tuple of three items: the index in the list of the first regular expression that matches; the match object returned; and the text read up till and including the match. If EOF is read and no text was read, raise EOFError. Otherwise, when nothing matches, return (-1, None, text) where text is the text received so far (may be the empty string if a timeout happened). If a regular expression ends with a greedy match (e.g. '.*') or if more than one expression can match the same input, the results are undeterministic, and may depend on the I/O timing. """ return self._waitfor(relist, timeout, False, cleanup)
[ "def", "waitfor", "(", "self", ",", "relist", ",", "timeout", "=", "None", ",", "cleanup", "=", "None", ")", ":", "return", "self", ".", "_waitfor", "(", "relist", ",", "timeout", ",", "False", ",", "cleanup", ")" ]
Read until one from a list of a regular expressions matches. The first argument is a list of regular expressions, either compiled (re.RegexObject instances) or uncompiled (strings). The optional second argument is a timeout, in seconds; default is no timeout. Return a tuple of three items: the index in the list of the first regular expression that matches; the match object returned; and the text read up till and including the match. If EOF is read and no text was read, raise EOFError. Otherwise, when nothing matches, return (-1, None, text) where text is the text received so far (may be the empty string if a timeout happened). If a regular expression ends with a greedy match (e.g. '.*') or if more than one expression can match the same input, the results are undeterministic, and may depend on the I/O timing.
[ "Read", "until", "one", "from", "a", "list", "of", "a", "regular", "expressions", "matches", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/protocols/telnetlib.py#L677-L698
train
213,235
knipknap/exscript
Exscript/util/pidutil.py
read
def read(path): """ Returns the process id from the given file if it exists, or None otherwise. Raises an exception for all other types of OSError while trying to access the file. :type path: str :param path: The name of the pidfile. :rtype: int or None :return: The PID, or none if the file was not found. """ # Try to read the pid from the pidfile. logging.info("Checking pidfile '%s'", path) try: return int(open(path).read()) except IOError as xxx_todo_changeme: (code, text) = xxx_todo_changeme.args if code == errno.ENOENT: # no such file or directory return None raise
python
def read(path): """ Returns the process id from the given file if it exists, or None otherwise. Raises an exception for all other types of OSError while trying to access the file. :type path: str :param path: The name of the pidfile. :rtype: int or None :return: The PID, or none if the file was not found. """ # Try to read the pid from the pidfile. logging.info("Checking pidfile '%s'", path) try: return int(open(path).read()) except IOError as xxx_todo_changeme: (code, text) = xxx_todo_changeme.args if code == errno.ENOENT: # no such file or directory return None raise
[ "def", "read", "(", "path", ")", ":", "# Try to read the pid from the pidfile.", "logging", ".", "info", "(", "\"Checking pidfile '%s'\"", ",", "path", ")", "try", ":", "return", "int", "(", "open", "(", "path", ")", ".", "read", "(", ")", ")", "except", "...
Returns the process id from the given file if it exists, or None otherwise. Raises an exception for all other types of OSError while trying to access the file. :type path: str :param path: The name of the pidfile. :rtype: int or None :return: The PID, or none if the file was not found.
[ "Returns", "the", "process", "id", "from", "the", "given", "file", "if", "it", "exists", "or", "None", "otherwise", ".", "Raises", "an", "exception", "for", "all", "other", "types", "of", "OSError", "while", "trying", "to", "access", "the", "file", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/pidutil.py#L33-L52
train
213,236
knipknap/exscript
Exscript/util/pidutil.py
isalive
def isalive(path): """ Returns True if the file with the given name contains a process id that is still alive. Returns False otherwise. :type path: str :param path: The name of the pidfile. :rtype: bool :return: Whether the process is alive. """ # try to read the pid from the pidfile pid = read(path) if pid is None: return False # Check if a process with the given pid exists. try: os.kill(pid, 0) # Signal 0 does not kill, but check. except OSError as xxx_todo_changeme1: (code, text) = xxx_todo_changeme1.args if code == errno.ESRCH: # No such process. return False return True
python
def isalive(path): """ Returns True if the file with the given name contains a process id that is still alive. Returns False otherwise. :type path: str :param path: The name of the pidfile. :rtype: bool :return: Whether the process is alive. """ # try to read the pid from the pidfile pid = read(path) if pid is None: return False # Check if a process with the given pid exists. try: os.kill(pid, 0) # Signal 0 does not kill, but check. except OSError as xxx_todo_changeme1: (code, text) = xxx_todo_changeme1.args if code == errno.ESRCH: # No such process. return False return True
[ "def", "isalive", "(", "path", ")", ":", "# try to read the pid from the pidfile", "pid", "=", "read", "(", "path", ")", "if", "pid", "is", "None", ":", "return", "False", "# Check if a process with the given pid exists.", "try", ":", "os", ".", "kill", "(", "pi...
Returns True if the file with the given name contains a process id that is still alive. Returns False otherwise. :type path: str :param path: The name of the pidfile. :rtype: bool :return: Whether the process is alive.
[ "Returns", "True", "if", "the", "file", "with", "the", "given", "name", "contains", "a", "process", "id", "that", "is", "still", "alive", ".", "Returns", "False", "otherwise", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/pidutil.py#L55-L78
train
213,237
knipknap/exscript
Exscript/util/pidutil.py
kill
def kill(path): """ Kills the process, if it still exists. :type path: str :param path: The name of the pidfile. """ # try to read the pid from the pidfile pid = read(path) if pid is None: return # Try to kill the process. logging.info("Killing PID %s", pid) try: os.kill(pid, 9) except OSError as xxx_todo_changeme2: # re-raise if the error wasn't "No such process" (code, text) = xxx_todo_changeme2.args # re-raise if the error wasn't "No such process" if code != errno.ESRCH: raise
python
def kill(path): """ Kills the process, if it still exists. :type path: str :param path: The name of the pidfile. """ # try to read the pid from the pidfile pid = read(path) if pid is None: return # Try to kill the process. logging.info("Killing PID %s", pid) try: os.kill(pid, 9) except OSError as xxx_todo_changeme2: # re-raise if the error wasn't "No such process" (code, text) = xxx_todo_changeme2.args # re-raise if the error wasn't "No such process" if code != errno.ESRCH: raise
[ "def", "kill", "(", "path", ")", ":", "# try to read the pid from the pidfile", "pid", "=", "read", "(", "path", ")", "if", "pid", "is", "None", ":", "return", "# Try to kill the process.", "logging", ".", "info", "(", "\"Killing PID %s\"", ",", "pid", ")", "t...
Kills the process, if it still exists. :type path: str :param path: The name of the pidfile.
[ "Kills", "the", "process", "if", "it", "still", "exists", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/pidutil.py#L81-L102
train
213,238
knipknap/exscript
Exscript/util/pidutil.py
write
def write(path): """ Writes the current process id to the given pidfile. :type path: str :param path: The name of the pidfile. """ pid = os.getpid() logging.info("Writing PID %s to '%s'", pid, path) try: pidfile = open(path, 'wb') # get a non-blocking exclusive lock fcntl.flock(pidfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) # clear out the file pidfile.seek(0) pidfile.truncate(0) # write the pid pidfile.write(str(pid)) finally: try: pidfile.close() except: pass
python
def write(path): """ Writes the current process id to the given pidfile. :type path: str :param path: The name of the pidfile. """ pid = os.getpid() logging.info("Writing PID %s to '%s'", pid, path) try: pidfile = open(path, 'wb') # get a non-blocking exclusive lock fcntl.flock(pidfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) # clear out the file pidfile.seek(0) pidfile.truncate(0) # write the pid pidfile.write(str(pid)) finally: try: pidfile.close() except: pass
[ "def", "write", "(", "path", ")", ":", "pid", "=", "os", ".", "getpid", "(", ")", "logging", ".", "info", "(", "\"Writing PID %s to '%s'\"", ",", "pid", ",", "path", ")", "try", ":", "pidfile", "=", "open", "(", "path", ",", "'wb'", ")", "# get a non...
Writes the current process id to the given pidfile. :type path: str :param path: The name of the pidfile.
[ "Writes", "the", "current", "process", "id", "to", "the", "given", "pidfile", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/pidutil.py#L105-L127
train
213,239
knipknap/exscript
Exscript/protocols/protocol.py
Protocol.set_username_prompt
def set_username_prompt(self, regex=None): """ Defines a pattern that is used to monitor the response of the connected host for a username prompt. :type regex: RegEx :param regex: The pattern that, when matched, causes an error. """ if regex is None: self.manual_user_re = regex else: self.manual_user_re = to_regexs(regex)
python
def set_username_prompt(self, regex=None): """ Defines a pattern that is used to monitor the response of the connected host for a username prompt. :type regex: RegEx :param regex: The pattern that, when matched, causes an error. """ if regex is None: self.manual_user_re = regex else: self.manual_user_re = to_regexs(regex)
[ "def", "set_username_prompt", "(", "self", ",", "regex", "=", "None", ")", ":", "if", "regex", "is", "None", ":", "self", ".", "manual_user_re", "=", "regex", "else", ":", "self", ".", "manual_user_re", "=", "to_regexs", "(", "regex", ")" ]
Defines a pattern that is used to monitor the response of the connected host for a username prompt. :type regex: RegEx :param regex: The pattern that, when matched, causes an error.
[ "Defines", "a", "pattern", "that", "is", "used", "to", "monitor", "the", "response", "of", "the", "connected", "host", "for", "a", "username", "prompt", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/protocols/protocol.py#L446-L457
train
213,240
knipknap/exscript
Exscript/protocols/protocol.py
Protocol.set_password_prompt
def set_password_prompt(self, regex=None): """ Defines a pattern that is used to monitor the response of the connected host for a password prompt. :type regex: RegEx :param regex: The pattern that, when matched, causes an error. """ if regex is None: self.manual_password_re = regex else: self.manual_password_re = to_regexs(regex)
python
def set_password_prompt(self, regex=None): """ Defines a pattern that is used to monitor the response of the connected host for a password prompt. :type regex: RegEx :param regex: The pattern that, when matched, causes an error. """ if regex is None: self.manual_password_re = regex else: self.manual_password_re = to_regexs(regex)
[ "def", "set_password_prompt", "(", "self", ",", "regex", "=", "None", ")", ":", "if", "regex", "is", "None", ":", "self", ".", "manual_password_re", "=", "regex", "else", ":", "self", ".", "manual_password_re", "=", "to_regexs", "(", "regex", ")" ]
Defines a pattern that is used to monitor the response of the connected host for a password prompt. :type regex: RegEx :param regex: The pattern that, when matched, causes an error.
[ "Defines", "a", "pattern", "that", "is", "used", "to", "monitor", "the", "response", "of", "the", "connected", "host", "for", "a", "password", "prompt", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/protocols/protocol.py#L471-L482
train
213,241
knipknap/exscript
Exscript/protocols/protocol.py
Protocol.set_login_error_prompt
def set_login_error_prompt(self, error=None): """ Defines a pattern that is used to monitor the response of the connected host during the authentication procedure. If the pattern matches an error is raised. :type error: RegEx :param error: The pattern that, when matched, causes an error. """ if error is None: self.manual_login_error_re = error else: self.manual_login_error_re = to_regexs(error)
python
def set_login_error_prompt(self, error=None): """ Defines a pattern that is used to monitor the response of the connected host during the authentication procedure. If the pattern matches an error is raised. :type error: RegEx :param error: The pattern that, when matched, causes an error. """ if error is None: self.manual_login_error_re = error else: self.manual_login_error_re = to_regexs(error)
[ "def", "set_login_error_prompt", "(", "self", ",", "error", "=", "None", ")", ":", "if", "error", "is", "None", ":", "self", ".", "manual_login_error_re", "=", "error", "else", ":", "self", ".", "manual_login_error_re", "=", "to_regexs", "(", "error", ")" ]
Defines a pattern that is used to monitor the response of the connected host during the authentication procedure. If the pattern matches an error is raised. :type error: RegEx :param error: The pattern that, when matched, causes an error.
[ "Defines", "a", "pattern", "that", "is", "used", "to", "monitor", "the", "response", "of", "the", "connected", "host", "during", "the", "authentication", "procedure", ".", "If", "the", "pattern", "matches", "an", "error", "is", "raised", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/protocols/protocol.py#L550-L562
train
213,242
knipknap/exscript
Exscript/protocols/protocol.py
Protocol.connect
def connect(self, hostname=None, port=None): """ Opens the connection to the remote host or IP address. :type hostname: string :param hostname: The remote host or IP address. :type port: int :param port: The remote TCP port number. """ if hostname is not None: self.host = hostname conn = self._connect_hook(self.host, port) self.os_guesser.protocol_info(self.get_remote_version()) self.auto_driver = driver_map[self.guess_os()] if self.get_banner(): self.os_guesser.data_received(self.get_banner(), False) return conn
python
def connect(self, hostname=None, port=None): """ Opens the connection to the remote host or IP address. :type hostname: string :param hostname: The remote host or IP address. :type port: int :param port: The remote TCP port number. """ if hostname is not None: self.host = hostname conn = self._connect_hook(self.host, port) self.os_guesser.protocol_info(self.get_remote_version()) self.auto_driver = driver_map[self.guess_os()] if self.get_banner(): self.os_guesser.data_received(self.get_banner(), False) return conn
[ "def", "connect", "(", "self", ",", "hostname", "=", "None", ",", "port", "=", "None", ")", ":", "if", "hostname", "is", "not", "None", ":", "self", ".", "host", "=", "hostname", "conn", "=", "self", ".", "_connect_hook", "(", "self", ".", "host", ...
Opens the connection to the remote host or IP address. :type hostname: string :param hostname: The remote host or IP address. :type port: int :param port: The remote TCP port number.
[ "Opens", "the", "connection", "to", "the", "remote", "host", "or", "IP", "address", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/protocols/protocol.py#L620-L636
train
213,243
knipknap/exscript
Exscript/protocols/protocol.py
Protocol.protocol_authenticate
def protocol_authenticate(self, account=None): """ Low-level API to perform protocol-level authentication on protocols that support it. .. HINT:: In most cases, you want to use the login() method instead, as it automatically chooses the best login method for each protocol. :type account: Account :param account: An account object, like login(). """ with self._get_account(account) as account: user = account.get_name() password = account.get_password() key = account.get_key() if key is None: self._dbg(1, "Attempting to authenticate %s." % user) self._protocol_authenticate(user, password) else: self._dbg(1, "Authenticate %s with key." % user) self._protocol_authenticate_by_key(user, key) self.proto_authenticated = True
python
def protocol_authenticate(self, account=None): """ Low-level API to perform protocol-level authentication on protocols that support it. .. HINT:: In most cases, you want to use the login() method instead, as it automatically chooses the best login method for each protocol. :type account: Account :param account: An account object, like login(). """ with self._get_account(account) as account: user = account.get_name() password = account.get_password() key = account.get_key() if key is None: self._dbg(1, "Attempting to authenticate %s." % user) self._protocol_authenticate(user, password) else: self._dbg(1, "Authenticate %s with key." % user) self._protocol_authenticate_by_key(user, key) self.proto_authenticated = True
[ "def", "protocol_authenticate", "(", "self", ",", "account", "=", "None", ")", ":", "with", "self", ".", "_get_account", "(", "account", ")", "as", "account", ":", "user", "=", "account", ".", "get_name", "(", ")", "password", "=", "account", ".", "get_p...
Low-level API to perform protocol-level authentication on protocols that support it. .. HINT:: In most cases, you want to use the login() method instead, as it automatically chooses the best login method for each protocol. :type account: Account :param account: An account object, like login().
[ "Low", "-", "level", "API", "to", "perform", "protocol", "-", "level", "authentication", "on", "protocols", "that", "support", "it", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/protocols/protocol.py#L709-L731
train
213,244
knipknap/exscript
Exscript/protocols/protocol.py
Protocol.app_authenticate
def app_authenticate(self, account=None, flush=True, bailout=False): """ Attempt to perform application-level authentication. Application level authentication is needed on devices where the username and password are requested from the user after the connection was already accepted by the remote device. The difference between app-level authentication and protocol-level authentication is that in the latter case, the prompting is handled by the client, whereas app-level authentication is handled by the remote device. App-level authentication comes in a large variety of forms, and while this method tries hard to support them all, there is no guarantee that it will always work. We attempt to smartly recognize the user and password prompts; for a list of supported operating systems please check the Exscript.protocols.drivers module. Returns upon finding the first command line prompt. Depending on whether the flush argument is True, it also removes the prompt from the incoming buffer. :type account: Account :param account: An account object, like login(). :type flush: bool :param flush: Whether to flush the last prompt from the buffer. :type bailout: bool :param bailout: Whether to wait for a prompt after sending the password. """ with self._get_account(account) as account: user = account.get_name() password = account.get_password() self._dbg(1, "Attempting to app-authenticate %s." % user) self._app_authenticate(account, password, flush, bailout) self.app_authenticated = True
python
def app_authenticate(self, account=None, flush=True, bailout=False): """ Attempt to perform application-level authentication. Application level authentication is needed on devices where the username and password are requested from the user after the connection was already accepted by the remote device. The difference between app-level authentication and protocol-level authentication is that in the latter case, the prompting is handled by the client, whereas app-level authentication is handled by the remote device. App-level authentication comes in a large variety of forms, and while this method tries hard to support them all, there is no guarantee that it will always work. We attempt to smartly recognize the user and password prompts; for a list of supported operating systems please check the Exscript.protocols.drivers module. Returns upon finding the first command line prompt. Depending on whether the flush argument is True, it also removes the prompt from the incoming buffer. :type account: Account :param account: An account object, like login(). :type flush: bool :param flush: Whether to flush the last prompt from the buffer. :type bailout: bool :param bailout: Whether to wait for a prompt after sending the password. """ with self._get_account(account) as account: user = account.get_name() password = account.get_password() self._dbg(1, "Attempting to app-authenticate %s." % user) self._app_authenticate(account, password, flush, bailout) self.app_authenticated = True
[ "def", "app_authenticate", "(", "self", ",", "account", "=", "None", ",", "flush", "=", "True", ",", "bailout", "=", "False", ")", ":", "with", "self", ".", "_get_account", "(", "account", ")", "as", "account", ":", "user", "=", "account", ".", "get_na...
Attempt to perform application-level authentication. Application level authentication is needed on devices where the username and password are requested from the user after the connection was already accepted by the remote device. The difference between app-level authentication and protocol-level authentication is that in the latter case, the prompting is handled by the client, whereas app-level authentication is handled by the remote device. App-level authentication comes in a large variety of forms, and while this method tries hard to support them all, there is no guarantee that it will always work. We attempt to smartly recognize the user and password prompts; for a list of supported operating systems please check the Exscript.protocols.drivers module. Returns upon finding the first command line prompt. Depending on whether the flush argument is True, it also removes the prompt from the incoming buffer. :type account: Account :param account: An account object, like login(). :type flush: bool :param flush: Whether to flush the last prompt from the buffer. :type bailout: bool :param bailout: Whether to wait for a prompt after sending the password.
[ "Attempt", "to", "perform", "application", "-", "level", "authentication", ".", "Application", "level", "authentication", "is", "needed", "on", "devices", "where", "the", "username", "and", "password", "are", "requested", "from", "the", "user", "after", "the", "...
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/protocols/protocol.py#L835-L871
train
213,245
knipknap/exscript
Exscript/protocols/protocol.py
Protocol.add_monitor
def add_monitor(self, pattern, callback, limit=80): """ Calls the given function whenever the given pattern matches the incoming data. .. HINT:: If you want to catch all incoming data regardless of a pattern, use the Protocol.data_received_event event instead. Arguments passed to the callback are the protocol instance, the index of the match, and the match object of the regular expression. :type pattern: str|re.RegexObject|list(str|re.RegexObject) :param pattern: One or more regular expressions. :type callback: callable :param callback: The function that is called. :type limit: int :param limit: The maximum size of the tail of the buffer that is searched, in number of bytes. """ self.buffer.add_monitor(pattern, partial(callback, self), limit)
python
def add_monitor(self, pattern, callback, limit=80): """ Calls the given function whenever the given pattern matches the incoming data. .. HINT:: If you want to catch all incoming data regardless of a pattern, use the Protocol.data_received_event event instead. Arguments passed to the callback are the protocol instance, the index of the match, and the match object of the regular expression. :type pattern: str|re.RegexObject|list(str|re.RegexObject) :param pattern: One or more regular expressions. :type callback: callable :param callback: The function that is called. :type limit: int :param limit: The maximum size of the tail of the buffer that is searched, in number of bytes. """ self.buffer.add_monitor(pattern, partial(callback, self), limit)
[ "def", "add_monitor", "(", "self", ",", "pattern", ",", "callback", ",", "limit", "=", "80", ")", ":", "self", ".", "buffer", ".", "add_monitor", "(", "pattern", ",", "partial", "(", "callback", ",", "self", ")", ",", "limit", ")" ]
Calls the given function whenever the given pattern matches the incoming data. .. HINT:: If you want to catch all incoming data regardless of a pattern, use the Protocol.data_received_event event instead. Arguments passed to the callback are the protocol instance, the index of the match, and the match object of the regular expression. :type pattern: str|re.RegexObject|list(str|re.RegexObject) :param pattern: One or more regular expressions. :type callback: callable :param callback: The function that is called. :type limit: int :param limit: The maximum size of the tail of the buffer that is searched, in number of bytes.
[ "Calls", "the", "given", "function", "whenever", "the", "given", "pattern", "matches", "the", "incoming", "data", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/protocols/protocol.py#L1098-L1118
train
213,246
knipknap/exscript
Exscript/queue.py
_prepare_connection
def _prepare_connection(func): """ A decorator that unpacks the host and connection from the job argument and passes them as separate arguments to the wrapped function. """ def _wrapped(job, *args, **kwargs): job_id = id(job) to_parent = job.data['pipe'] host = job.data['host'] # Create a protocol adapter. mkaccount = partial(_account_factory, to_parent, host) pargs = {'account_factory': mkaccount, 'stdout': job.data['stdout']} pargs.update(host.get_options()) conn = prepare(host, **pargs) # Connect and run the function. log_options = get_label(func, 'log_to') if log_options is not None: # Enable logging. proxy = LoggerProxy(to_parent, log_options['logger_id']) log_cb = partial(proxy.log, job_id) proxy.add_log(job_id, job.name, job.failures + 1) conn.data_received_event.listen(log_cb) try: conn.connect(host.get_address(), host.get_tcp_port()) result = func(job, host, conn, *args, **kwargs) conn.close(force=True) except: proxy.log_aborted(job_id, serializeable_sys_exc_info()) raise else: proxy.log_succeeded(job_id) finally: conn.data_received_event.disconnect(log_cb) else: conn.connect(host.get_address(), host.get_tcp_port()) result = func(job, host, conn, *args, **kwargs) conn.close(force=True) return result return _wrapped
python
def _prepare_connection(func): """ A decorator that unpacks the host and connection from the job argument and passes them as separate arguments to the wrapped function. """ def _wrapped(job, *args, **kwargs): job_id = id(job) to_parent = job.data['pipe'] host = job.data['host'] # Create a protocol adapter. mkaccount = partial(_account_factory, to_parent, host) pargs = {'account_factory': mkaccount, 'stdout': job.data['stdout']} pargs.update(host.get_options()) conn = prepare(host, **pargs) # Connect and run the function. log_options = get_label(func, 'log_to') if log_options is not None: # Enable logging. proxy = LoggerProxy(to_parent, log_options['logger_id']) log_cb = partial(proxy.log, job_id) proxy.add_log(job_id, job.name, job.failures + 1) conn.data_received_event.listen(log_cb) try: conn.connect(host.get_address(), host.get_tcp_port()) result = func(job, host, conn, *args, **kwargs) conn.close(force=True) except: proxy.log_aborted(job_id, serializeable_sys_exc_info()) raise else: proxy.log_succeeded(job_id) finally: conn.data_received_event.disconnect(log_cb) else: conn.connect(host.get_address(), host.get_tcp_port()) result = func(job, host, conn, *args, **kwargs) conn.close(force=True) return result return _wrapped
[ "def", "_prepare_connection", "(", "func", ")", ":", "def", "_wrapped", "(", "job", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "job_id", "=", "id", "(", "job", ")", "to_parent", "=", "job", ".", "data", "[", "'pipe'", "]", "host", "=", ...
A decorator that unpacks the host and connection from the job argument and passes them as separate arguments to the wrapped function.
[ "A", "decorator", "that", "unpacks", "the", "host", "and", "connection", "from", "the", "job", "argument", "and", "passes", "them", "as", "separate", "arguments", "to", "the", "wrapped", "function", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/queue.py#L64-L106
train
213,247
knipknap/exscript
Exscript/queue.py
Queue.join
def join(self): """ Waits until all jobs are completed. """ self._dbg(2, 'Waiting for the queue to finish.') self.workqueue.wait_until_done() for child in list(self.pipe_handlers.values()): child.join() self._del_status_bar() self._print_status_bar() gc.collect()
python
def join(self): """ Waits until all jobs are completed. """ self._dbg(2, 'Waiting for the queue to finish.') self.workqueue.wait_until_done() for child in list(self.pipe_handlers.values()): child.join() self._del_status_bar() self._print_status_bar() gc.collect()
[ "def", "join", "(", "self", ")", ":", "self", ".", "_dbg", "(", "2", ",", "'Waiting for the queue to finish.'", ")", "self", ".", "workqueue", ".", "wait_until_done", "(", ")", "for", "child", "in", "list", "(", "self", ".", "pipe_handlers", ".", "values",...
Waits until all jobs are completed.
[ "Waits", "until", "all", "jobs", "are", "completed", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/queue.py#L522-L532
train
213,248
knipknap/exscript
Exscript/queue.py
Queue.shutdown
def shutdown(self, force=False): """ Stop executing any further jobs. If the force argument is True, the function does not wait until any queued jobs are completed but stops immediately. After emptying the queue it is restarted, so you may still call run() after using this method. :type force: bool :param force: Whether to wait until all jobs were processed. """ if not force: self.join() self._dbg(2, 'Shutting down queue...') self.workqueue.shutdown(True) self._dbg(2, 'Queue shut down.') self._del_status_bar()
python
def shutdown(self, force=False): """ Stop executing any further jobs. If the force argument is True, the function does not wait until any queued jobs are completed but stops immediately. After emptying the queue it is restarted, so you may still call run() after using this method. :type force: bool :param force: Whether to wait until all jobs were processed. """ if not force: self.join() self._dbg(2, 'Shutting down queue...') self.workqueue.shutdown(True) self._dbg(2, 'Queue shut down.') self._del_status_bar()
[ "def", "shutdown", "(", "self", ",", "force", "=", "False", ")", ":", "if", "not", "force", ":", "self", ".", "join", "(", ")", "self", ".", "_dbg", "(", "2", ",", "'Shutting down queue...'", ")", "self", ".", "workqueue", ".", "shutdown", "(", "True...
Stop executing any further jobs. If the force argument is True, the function does not wait until any queued jobs are completed but stops immediately. After emptying the queue it is restarted, so you may still call run() after using this method. :type force: bool :param force: Whether to wait until all jobs were processed.
[ "Stop", "executing", "any", "further", "jobs", ".", "If", "the", "force", "argument", "is", "True", "the", "function", "does", "not", "wait", "until", "any", "queued", "jobs", "are", "completed", "but", "stops", "immediately", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/queue.py#L534-L552
train
213,249
knipknap/exscript
Exscript/queue.py
Queue.reset
def reset(self): """ Remove all accounts, hosts, etc. """ self._dbg(2, 'Resetting queue...') self.account_manager.reset() self.workqueue.shutdown(True) self.completed = 0 self.total = 0 self.failed = 0 self.status_bar_length = 0 self._dbg(2, 'Queue reset.') self._del_status_bar()
python
def reset(self): """ Remove all accounts, hosts, etc. """ self._dbg(2, 'Resetting queue...') self.account_manager.reset() self.workqueue.shutdown(True) self.completed = 0 self.total = 0 self.failed = 0 self.status_bar_length = 0 self._dbg(2, 'Queue reset.') self._del_status_bar()
[ "def", "reset", "(", "self", ")", ":", "self", ".", "_dbg", "(", "2", ",", "'Resetting queue...'", ")", "self", ".", "account_manager", ".", "reset", "(", ")", "self", ".", "workqueue", ".", "shutdown", "(", "True", ")", "self", ".", "completed", "=", ...
Remove all accounts, hosts, etc.
[ "Remove", "all", "accounts", "hosts", "etc", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/queue.py#L577-L589
train
213,250
knipknap/exscript
Exscript/stdlib/list.py
get
def get(scope, source, index): """ Returns a copy of the list item with the given index. It is an error if an item with teh given index does not exist. :type source: string :param source: A list of strings. :type index: string :param index: A list of strings. :rtype: string :return: The cleaned up list of strings. """ try: index = int(index[0]) except IndexError: raise ValueError('index variable is required') except ValueError: raise ValueError('index is not an integer') try: return [source[index]] except IndexError: raise ValueError('no such item in the list')
python
def get(scope, source, index): """ Returns a copy of the list item with the given index. It is an error if an item with teh given index does not exist. :type source: string :param source: A list of strings. :type index: string :param index: A list of strings. :rtype: string :return: The cleaned up list of strings. """ try: index = int(index[0]) except IndexError: raise ValueError('index variable is required') except ValueError: raise ValueError('index is not an integer') try: return [source[index]] except IndexError: raise ValueError('no such item in the list')
[ "def", "get", "(", "scope", ",", "source", ",", "index", ")", ":", "try", ":", "index", "=", "int", "(", "index", "[", "0", "]", ")", "except", "IndexError", ":", "raise", "ValueError", "(", "'index variable is required'", ")", "except", "ValueError", ":...
Returns a copy of the list item with the given index. It is an error if an item with teh given index does not exist. :type source: string :param source: A list of strings. :type index: string :param index: A list of strings. :rtype: string :return: The cleaned up list of strings.
[ "Returns", "a", "copy", "of", "the", "list", "item", "with", "the", "given", "index", ".", "It", "is", "an", "error", "if", "an", "item", "with", "teh", "given", "index", "does", "not", "exist", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/stdlib/list.py#L49-L70
train
213,251
knipknap/exscript
Exscript/stdlib/mysys.py
execute
def execute(scope, command): """ Executes the given command locally. :type command: string :param command: A shell command. """ process = Popen(command[0], shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) scope.define(__response__=process.stdout.read()) return True
python
def execute(scope, command): """ Executes the given command locally. :type command: string :param command: A shell command. """ process = Popen(command[0], shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) scope.define(__response__=process.stdout.read()) return True
[ "def", "execute", "(", "scope", ",", "command", ")", ":", "process", "=", "Popen", "(", "command", "[", "0", "]", ",", "shell", "=", "True", ",", "stdin", "=", "PIPE", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "STDOUT", ",", "close_fds", "=",...
Executes the given command locally. :type command: string :param command: A shell command.
[ "Executes", "the", "given", "command", "locally", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/stdlib/mysys.py#L41-L55
train
213,252
knipknap/exscript
Exscript/protocols/osguesser.py
OsGuesser.set
def set(self, key, value, confidence=100): """ Defines the given value with the given confidence, unless the same value is already defined with a higher confidence level. """ if value is None: return if key in self.info: old_confidence, old_value = self.info.get(key) if old_confidence >= confidence: return self.info[key] = (confidence, value)
python
def set(self, key, value, confidence=100): """ Defines the given value with the given confidence, unless the same value is already defined with a higher confidence level. """ if value is None: return if key in self.info: old_confidence, old_value = self.info.get(key) if old_confidence >= confidence: return self.info[key] = (confidence, value)
[ "def", "set", "(", "self", ",", "key", ",", "value", ",", "confidence", "=", "100", ")", ":", "if", "value", "is", "None", ":", "return", "if", "key", "in", "self", ".", "info", ":", "old_confidence", ",", "old_value", "=", "self", ".", "info", "."...
Defines the given value with the given confidence, unless the same value is already defined with a higher confidence level.
[ "Defines", "the", "given", "value", "with", "the", "given", "confidence", "unless", "the", "same", "value", "is", "already", "defined", "with", "a", "higher", "confidence", "level", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/protocols/osguesser.py#L54-L65
train
213,253
knipknap/exscript
Exscript/protocols/osguesser.py
OsGuesser.get
def get(self, key, confidence=0): """ Returns the info with the given key, if it has at least the given confidence. Returns None otherwise. """ if key not in self.info: return None conf, value = self.info.get(key) if conf >= confidence: return value return None
python
def get(self, key, confidence=0): """ Returns the info with the given key, if it has at least the given confidence. Returns None otherwise. """ if key not in self.info: return None conf, value = self.info.get(key) if conf >= confidence: return value return None
[ "def", "get", "(", "self", ",", "key", ",", "confidence", "=", "0", ")", ":", "if", "key", "not", "in", "self", ".", "info", ":", "return", "None", "conf", ",", "value", "=", "self", ".", "info", ".", "get", "(", "key", ")", "if", "conf", ">=",...
Returns the info with the given key, if it has at least the given confidence. Returns None otherwise.
[ "Returns", "the", "info", "with", "the", "given", "key", "if", "it", "has", "at", "least", "the", "given", "confidence", ".", "Returns", "None", "otherwise", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/protocols/osguesser.py#L91-L101
train
213,254
knipknap/exscript
Exscript/util/decorator.py
bind
def bind(function, *args, **kwargs): """ Wraps the given function such that when it is called, the given arguments are passed in addition to the connection argument. :type function: function :param function: The function that's ought to be wrapped. :type args: list :param args: Passed on to the called function. :type kwargs: dict :param kwargs: Passed on to the called function. :rtype: function :return: The wrapped function. """ def decorated(*inner_args, **inner_kwargs): kwargs.update(inner_kwargs) return function(*(inner_args + args), **kwargs) copy_labels(function, decorated) return decorated
python
def bind(function, *args, **kwargs): """ Wraps the given function such that when it is called, the given arguments are passed in addition to the connection argument. :type function: function :param function: The function that's ought to be wrapped. :type args: list :param args: Passed on to the called function. :type kwargs: dict :param kwargs: Passed on to the called function. :rtype: function :return: The wrapped function. """ def decorated(*inner_args, **inner_kwargs): kwargs.update(inner_kwargs) return function(*(inner_args + args), **kwargs) copy_labels(function, decorated) return decorated
[ "def", "bind", "(", "function", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "decorated", "(", "*", "inner_args", ",", "*", "*", "inner_kwargs", ")", ":", "kwargs", ".", "update", "(", "inner_kwargs", ")", "return", "function", "(", "*...
Wraps the given function such that when it is called, the given arguments are passed in addition to the connection argument. :type function: function :param function: The function that's ought to be wrapped. :type args: list :param args: Passed on to the called function. :type kwargs: dict :param kwargs: Passed on to the called function. :rtype: function :return: The wrapped function.
[ "Wraps", "the", "given", "function", "such", "that", "when", "it", "is", "called", "the", "given", "arguments", "are", "passed", "in", "addition", "to", "the", "connection", "argument", "." ]
72718eee3e87b345d5a5255be9824e867e42927b
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/decorator.py#L31-L49
train
213,255
iKevinY/EulerPy
EulerPy/utils.py
problem_glob
def problem_glob(extension='.py'): """Returns ProblemFile objects for all valid problem files""" filenames = glob.glob('*[0-9][0-9][0-9]*{}'.format(extension)) return [ProblemFile(file) for file in filenames]
python
def problem_glob(extension='.py'): """Returns ProblemFile objects for all valid problem files""" filenames = glob.glob('*[0-9][0-9][0-9]*{}'.format(extension)) return [ProblemFile(file) for file in filenames]
[ "def", "problem_glob", "(", "extension", "=", "'.py'", ")", ":", "filenames", "=", "glob", ".", "glob", "(", "'*[0-9][0-9][0-9]*{}'", ".", "format", "(", "extension", ")", ")", "return", "[", "ProblemFile", "(", "file", ")", "for", "file", "in", "filenames...
Returns ProblemFile objects for all valid problem files
[ "Returns", "ProblemFile", "objects", "for", "all", "valid", "problem", "files" ]
739c1c67fa7b32af9140ca51e4b4a07733e057a6
https://github.com/iKevinY/EulerPy/blob/739c1c67fa7b32af9140ca51e4b4a07733e057a6/EulerPy/utils.py#L12-L15
train
213,256
iKevinY/EulerPy
EulerPy/utils.py
human_time
def human_time(timespan, precision=3): """Formats the timespan in a human readable format""" if timespan >= 60.0: # Format time greater than one minute in a human-readable format # Idea from http://snipplr.com/view/5713/ def _format_long_time(time): suffixes = ('d', 'h', 'm', 's') lengths = (24*60*60, 60*60, 60, 1) for suffix, length in zip(suffixes, lengths): value = int(time / length) if value > 0: time %= length yield '%i%s' % (value, suffix) if time < 1: break return ' '.join(_format_long_time(timespan)) else: units = ['s', 'ms', 'us', 'ns'] # Attempt to replace 'us' with 'µs' if UTF-8 encoding has been set if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding == 'UTF-8': try: units[2] = b'\xc2\xb5s'.decode('utf-8') except UnicodeEncodeError: pass scale = [1.0, 1e3, 1e6, 1e9] if timespan > 0.0: # Determine scale of timespan (s = 0, ms = 1, µs = 2, ns = 3) order = min(-int(math.floor(math.log10(timespan)) // 3), 3) else: order = 3 return '%.*g %s' % (precision, timespan * scale[order], units[order])
python
def human_time(timespan, precision=3): """Formats the timespan in a human readable format""" if timespan >= 60.0: # Format time greater than one minute in a human-readable format # Idea from http://snipplr.com/view/5713/ def _format_long_time(time): suffixes = ('d', 'h', 'm', 's') lengths = (24*60*60, 60*60, 60, 1) for suffix, length in zip(suffixes, lengths): value = int(time / length) if value > 0: time %= length yield '%i%s' % (value, suffix) if time < 1: break return ' '.join(_format_long_time(timespan)) else: units = ['s', 'ms', 'us', 'ns'] # Attempt to replace 'us' with 'µs' if UTF-8 encoding has been set if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding == 'UTF-8': try: units[2] = b'\xc2\xb5s'.decode('utf-8') except UnicodeEncodeError: pass scale = [1.0, 1e3, 1e6, 1e9] if timespan > 0.0: # Determine scale of timespan (s = 0, ms = 1, µs = 2, ns = 3) order = min(-int(math.floor(math.log10(timespan)) // 3), 3) else: order = 3 return '%.*g %s' % (precision, timespan * scale[order], units[order])
[ "def", "human_time", "(", "timespan", ",", "precision", "=", "3", ")", ":", "if", "timespan", ">=", "60.0", ":", "# Format time greater than one minute in a human-readable format", "# Idea from http://snipplr.com/view/5713/", "def", "_format_long_time", "(", "time", ")", ...
Formats the timespan in a human readable format
[ "Formats", "the", "timespan", "in", "a", "human", "readable", "format" ]
739c1c67fa7b32af9140ca51e4b4a07733e057a6
https://github.com/iKevinY/EulerPy/blob/739c1c67fa7b32af9140ca51e4b4a07733e057a6/EulerPy/utils.py#L41-L81
train
213,257
iKevinY/EulerPy
EulerPy/utils.py
format_time
def format_time(start, end): """Returns string with relevant time information formatted properly""" try: cpu_usr = end[0] - start[0] cpu_sys = end[1] - start[1] except TypeError: # `clock()[1] == None` so subtraction results in a TypeError return 'Time elapsed: {}'.format(human_time(cpu_usr)) else: times = (human_time(x) for x in (cpu_usr, cpu_sys, cpu_usr + cpu_sys)) return 'Time elapsed: user: {}, sys: {}, total: {}'.format(*times)
python
def format_time(start, end): """Returns string with relevant time information formatted properly""" try: cpu_usr = end[0] - start[0] cpu_sys = end[1] - start[1] except TypeError: # `clock()[1] == None` so subtraction results in a TypeError return 'Time elapsed: {}'.format(human_time(cpu_usr)) else: times = (human_time(x) for x in (cpu_usr, cpu_sys, cpu_usr + cpu_sys)) return 'Time elapsed: user: {}, sys: {}, total: {}'.format(*times)
[ "def", "format_time", "(", "start", ",", "end", ")", ":", "try", ":", "cpu_usr", "=", "end", "[", "0", "]", "-", "start", "[", "0", "]", "cpu_sys", "=", "end", "[", "1", "]", "-", "start", "[", "1", "]", "except", "TypeError", ":", "# `clock()[1]...
Returns string with relevant time information formatted properly
[ "Returns", "string", "with", "relevant", "time", "information", "formatted", "properly" ]
739c1c67fa7b32af9140ca51e4b4a07733e057a6
https://github.com/iKevinY/EulerPy/blob/739c1c67fa7b32af9140ca51e4b4a07733e057a6/EulerPy/utils.py#L84-L96
train
213,258
iKevinY/EulerPy
EulerPy/problem.py
Problem.filename
def filename(self, prefix='', suffix='', extension='.py'): """Returns filename padded with leading zeros""" return BASE_NAME.format(prefix, self.num, suffix, extension)
python
def filename(self, prefix='', suffix='', extension='.py'): """Returns filename padded with leading zeros""" return BASE_NAME.format(prefix, self.num, suffix, extension)
[ "def", "filename", "(", "self", ",", "prefix", "=", "''", ",", "suffix", "=", "''", ",", "extension", "=", "'.py'", ")", ":", "return", "BASE_NAME", ".", "format", "(", "prefix", ",", "self", ".", "num", ",", "suffix", ",", "extension", ")" ]
Returns filename padded with leading zeros
[ "Returns", "filename", "padded", "with", "leading", "zeros" ]
739c1c67fa7b32af9140ca51e4b4a07733e057a6
https://github.com/iKevinY/EulerPy/blob/739c1c67fa7b32af9140ca51e4b4a07733e057a6/EulerPy/problem.py#L25-L27
train
213,259
iKevinY/EulerPy
EulerPy/problem.py
Problem.glob
def glob(self): """Returns a sorted glob of files belonging to a given problem""" file_glob = glob.glob(BASE_NAME.format('*', self.num, '*', '.*')) # Sort globbed files by tuple (filename, extension) return sorted(file_glob, key=lambda f: os.path.splitext(f))
python
def glob(self): """Returns a sorted glob of files belonging to a given problem""" file_glob = glob.glob(BASE_NAME.format('*', self.num, '*', '.*')) # Sort globbed files by tuple (filename, extension) return sorted(file_glob, key=lambda f: os.path.splitext(f))
[ "def", "glob", "(", "self", ")", ":", "file_glob", "=", "glob", ".", "glob", "(", "BASE_NAME", ".", "format", "(", "'*'", ",", "self", ".", "num", ",", "'*'", ",", "'.*'", ")", ")", "# Sort globbed files by tuple (filename, extension)", "return", "sorted", ...
Returns a sorted glob of files belonging to a given problem
[ "Returns", "a", "sorted", "glob", "of", "files", "belonging", "to", "a", "given", "problem" ]
739c1c67fa7b32af9140ca51e4b4a07733e057a6
https://github.com/iKevinY/EulerPy/blob/739c1c67fa7b32af9140ca51e4b4a07733e057a6/EulerPy/problem.py#L30-L35
train
213,260
iKevinY/EulerPy
EulerPy/problem.py
Problem.copy_resources
def copy_resources(self): """Copies the relevant resources to a resources subdirectory""" if not os.path.isdir('resources'): os.mkdir('resources') resource_dir = os.path.join(os.getcwd(), 'resources', '') copied_resources = [] for resource in self.resources: src = os.path.join(EULER_DATA, 'resources', resource) if os.path.isfile(src): shutil.copy(src, resource_dir) copied_resources.append(resource) if copied_resources: copied = ', '.join(copied_resources) path = os.path.relpath(resource_dir, os.pardir) msg = "Copied {} to {}.".format(copied, path) click.secho(msg, fg='green')
python
def copy_resources(self): """Copies the relevant resources to a resources subdirectory""" if not os.path.isdir('resources'): os.mkdir('resources') resource_dir = os.path.join(os.getcwd(), 'resources', '') copied_resources = [] for resource in self.resources: src = os.path.join(EULER_DATA, 'resources', resource) if os.path.isfile(src): shutil.copy(src, resource_dir) copied_resources.append(resource) if copied_resources: copied = ', '.join(copied_resources) path = os.path.relpath(resource_dir, os.pardir) msg = "Copied {} to {}.".format(copied, path) click.secho(msg, fg='green')
[ "def", "copy_resources", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "'resources'", ")", ":", "os", ".", "mkdir", "(", "'resources'", ")", "resource_dir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", ...
Copies the relevant resources to a resources subdirectory
[ "Copies", "the", "relevant", "resources", "to", "a", "resources", "subdirectory" ]
739c1c67fa7b32af9140ca51e4b4a07733e057a6
https://github.com/iKevinY/EulerPy/blob/739c1c67fa7b32af9140ca51e4b4a07733e057a6/EulerPy/problem.py#L58-L77
train
213,261
iKevinY/EulerPy
EulerPy/problem.py
Problem.solution
def solution(self): """Returns the answer to a given problem""" num = self.num solution_file = os.path.join(EULER_DATA, 'solutions.txt') solution_line = linecache.getline(solution_file, num) try: answer = solution_line.split('. ')[1].strip() except IndexError: answer = None if answer: return answer else: msg = 'Answer for problem %i not found in solutions.txt.' % num click.secho(msg, fg='red') click.echo('If you have an answer, consider submitting a pull ' 'request to EulerPy on GitHub.') sys.exit(1)
python
def solution(self): """Returns the answer to a given problem""" num = self.num solution_file = os.path.join(EULER_DATA, 'solutions.txt') solution_line = linecache.getline(solution_file, num) try: answer = solution_line.split('. ')[1].strip() except IndexError: answer = None if answer: return answer else: msg = 'Answer for problem %i not found in solutions.txt.' % num click.secho(msg, fg='red') click.echo('If you have an answer, consider submitting a pull ' 'request to EulerPy on GitHub.') sys.exit(1)
[ "def", "solution", "(", "self", ")", ":", "num", "=", "self", ".", "num", "solution_file", "=", "os", ".", "path", ".", "join", "(", "EULER_DATA", ",", "'solutions.txt'", ")", "solution_line", "=", "linecache", ".", "getline", "(", "solution_file", ",", ...
Returns the answer to a given problem
[ "Returns", "the", "answer", "to", "a", "given", "problem" ]
739c1c67fa7b32af9140ca51e4b4a07733e057a6
https://github.com/iKevinY/EulerPy/blob/739c1c67fa7b32af9140ca51e4b4a07733e057a6/EulerPy/problem.py#L80-L99
train
213,262
iKevinY/EulerPy
EulerPy/problem.py
Problem.text
def text(self): """Parses problems.txt and returns problem text""" def _problem_iter(problem_num): problem_file = os.path.join(EULER_DATA, 'problems.txt') with open(problem_file) as f: is_problem = False last_line = '' for line in f: if line.strip() == 'Problem %i' % problem_num: is_problem = True if is_problem: if line == last_line == '\n': break else: yield line[:-1] last_line = line problem_lines = [line for line in _problem_iter(self.num)] if problem_lines: # First three lines are the problem number, the divider line, # and a newline, so don't include them in the returned string. # Also, strip the final newline. return '\n'.join(problem_lines[3:-1]) else: msg = 'Problem %i not found in problems.txt.' % self.num click.secho(msg, fg='red') click.echo('If this problem exists on Project Euler, consider ' 'submitting a pull request to EulerPy on GitHub.') sys.exit(1)
python
def text(self): """Parses problems.txt and returns problem text""" def _problem_iter(problem_num): problem_file = os.path.join(EULER_DATA, 'problems.txt') with open(problem_file) as f: is_problem = False last_line = '' for line in f: if line.strip() == 'Problem %i' % problem_num: is_problem = True if is_problem: if line == last_line == '\n': break else: yield line[:-1] last_line = line problem_lines = [line for line in _problem_iter(self.num)] if problem_lines: # First three lines are the problem number, the divider line, # and a newline, so don't include them in the returned string. # Also, strip the final newline. return '\n'.join(problem_lines[3:-1]) else: msg = 'Problem %i not found in problems.txt.' % self.num click.secho(msg, fg='red') click.echo('If this problem exists on Project Euler, consider ' 'submitting a pull request to EulerPy on GitHub.') sys.exit(1)
[ "def", "text", "(", "self", ")", ":", "def", "_problem_iter", "(", "problem_num", ")", ":", "problem_file", "=", "os", ".", "path", ".", "join", "(", "EULER_DATA", ",", "'problems.txt'", ")", "with", "open", "(", "problem_file", ")", "as", "f", ":", "i...
Parses problems.txt and returns problem text
[ "Parses", "problems", ".", "txt", "and", "returns", "problem", "text" ]
739c1c67fa7b32af9140ca51e4b4a07733e057a6
https://github.com/iKevinY/EulerPy/blob/739c1c67fa7b32af9140ca51e4b4a07733e057a6/EulerPy/problem.py#L102-L134
train
213,263
iKevinY/EulerPy
EulerPy/euler.py
cheat
def cheat(num): """View the answer to a problem.""" # Define solution before echoing in case solution does not exist solution = click.style(Problem(num).solution, bold=True) click.confirm("View answer to problem %i?" % num, abort=True) click.echo("The answer to problem {} is {}.".format(num, solution))
python
def cheat(num): """View the answer to a problem.""" # Define solution before echoing in case solution does not exist solution = click.style(Problem(num).solution, bold=True) click.confirm("View answer to problem %i?" % num, abort=True) click.echo("The answer to problem {} is {}.".format(num, solution))
[ "def", "cheat", "(", "num", ")", ":", "# Define solution before echoing in case solution does not exist", "solution", "=", "click", ".", "style", "(", "Problem", "(", "num", ")", ".", "solution", ",", "bold", "=", "True", ")", "click", ".", "confirm", "(", "\"...
View the answer to a problem.
[ "View", "the", "answer", "to", "a", "problem", "." ]
739c1c67fa7b32af9140ca51e4b4a07733e057a6
https://github.com/iKevinY/EulerPy/blob/739c1c67fa7b32af9140ca51e4b4a07733e057a6/EulerPy/euler.py#L16-L21
train
213,264
iKevinY/EulerPy
EulerPy/euler.py
generate
def generate(num, prompt_default=True): """Generates Python file for a problem.""" p = Problem(num) problem_text = p.text msg = "Generate file for problem %i?" % num click.confirm(msg, default=prompt_default, abort=True) # Allow skipped problem files to be recreated if p.glob: filename = str(p.file) msg = '"{}" already exists. Overwrite?'.format(filename) click.confirm(click.style(msg, fg='red'), abort=True) else: # Try to keep prefix consistent with existing files previous_file = Problem(num - 1).file prefix = previous_file.prefix if previous_file else '' filename = p.filename(prefix=prefix) header = 'Project Euler Problem %i' % num divider = '=' * len(header) text = '\n'.join([header, divider, '', problem_text]) content = '\n'.join(['"""', text, '"""']) with open(filename, 'w') as f: f.write(content + '\n\n\n') click.secho('Successfully created "{}".'.format(filename), fg='green') # Copy over problem resources if required if p.resources: p.copy_resources()
python
def generate(num, prompt_default=True): """Generates Python file for a problem.""" p = Problem(num) problem_text = p.text msg = "Generate file for problem %i?" % num click.confirm(msg, default=prompt_default, abort=True) # Allow skipped problem files to be recreated if p.glob: filename = str(p.file) msg = '"{}" already exists. Overwrite?'.format(filename) click.confirm(click.style(msg, fg='red'), abort=True) else: # Try to keep prefix consistent with existing files previous_file = Problem(num - 1).file prefix = previous_file.prefix if previous_file else '' filename = p.filename(prefix=prefix) header = 'Project Euler Problem %i' % num divider = '=' * len(header) text = '\n'.join([header, divider, '', problem_text]) content = '\n'.join(['"""', text, '"""']) with open(filename, 'w') as f: f.write(content + '\n\n\n') click.secho('Successfully created "{}".'.format(filename), fg='green') # Copy over problem resources if required if p.resources: p.copy_resources()
[ "def", "generate", "(", "num", ",", "prompt_default", "=", "True", ")", ":", "p", "=", "Problem", "(", "num", ")", "problem_text", "=", "p", ".", "text", "msg", "=", "\"Generate file for problem %i?\"", "%", "num", "click", ".", "confirm", "(", "msg", ",...
Generates Python file for a problem.
[ "Generates", "Python", "file", "for", "a", "problem", "." ]
739c1c67fa7b32af9140ca51e4b4a07733e057a6
https://github.com/iKevinY/EulerPy/blob/739c1c67fa7b32af9140ca51e4b4a07733e057a6/EulerPy/euler.py#L25-L57
train
213,265
iKevinY/EulerPy
EulerPy/euler.py
preview
def preview(num): """Prints the text of a problem.""" # Define problem_text before echoing in case problem does not exist problem_text = Problem(num).text click.secho("Project Euler Problem %i" % num, bold=True) click.echo(problem_text)
python
def preview(num): """Prints the text of a problem.""" # Define problem_text before echoing in case problem does not exist problem_text = Problem(num).text click.secho("Project Euler Problem %i" % num, bold=True) click.echo(problem_text)
[ "def", "preview", "(", "num", ")", ":", "# Define problem_text before echoing in case problem does not exist", "problem_text", "=", "Problem", "(", "num", ")", ".", "text", "click", ".", "secho", "(", "\"Project Euler Problem %i\"", "%", "num", ",", "bold", "=", "Tr...
Prints the text of a problem.
[ "Prints", "the", "text", "of", "a", "problem", "." ]
739c1c67fa7b32af9140ca51e4b4a07733e057a6
https://github.com/iKevinY/EulerPy/blob/739c1c67fa7b32af9140ca51e4b4a07733e057a6/EulerPy/euler.py#L61-L66
train
213,266
iKevinY/EulerPy
EulerPy/euler.py
skip
def skip(num): """Generates Python file for the next problem.""" click.echo("Current problem is problem %i." % num) generate(num + 1, prompt_default=False) Problem(num).file.change_suffix('-skipped')
python
def skip(num): """Generates Python file for the next problem.""" click.echo("Current problem is problem %i." % num) generate(num + 1, prompt_default=False) Problem(num).file.change_suffix('-skipped')
[ "def", "skip", "(", "num", ")", ":", "click", ".", "echo", "(", "\"Current problem is problem %i.\"", "%", "num", ")", "generate", "(", "num", "+", "1", ",", "prompt_default", "=", "False", ")", "Problem", "(", "num", ")", ".", "file", ".", "change_suffi...
Generates Python file for the next problem.
[ "Generates", "Python", "file", "for", "the", "next", "problem", "." ]
739c1c67fa7b32af9140ca51e4b4a07733e057a6
https://github.com/iKevinY/EulerPy/blob/739c1c67fa7b32af9140ca51e4b4a07733e057a6/EulerPy/euler.py#L70-L74
train
213,267
iKevinY/EulerPy
EulerPy/euler.py
verify
def verify(num, filename=None, exit=True): """Verifies the solution to a problem.""" p = Problem(num) filename = filename or p.filename() if not os.path.isfile(filename): # Attempt to verify the first problem file matched by glob if p.glob: filename = str(p.file) else: click.secho('No file found for problem %i.' % p.num, fg='red') sys.exit(1) solution = p.solution click.echo('Checking "{}" against solution: '.format(filename), nl=False) cmd = (sys.executable or 'python', filename) start = clock() proc = subprocess.Popen(cmd, stdout=subprocess.PIPE) stdout = proc.communicate()[0] end = clock() time_info = format_time(start, end) # Return value of anything other than 0 indicates an error if proc.poll() != 0: click.secho('Error calling "{}".'.format(filename), fg='red') click.secho(time_info, fg='cyan') # Return None if option is not --verify-all, otherwise exit return sys.exit(1) if exit else None # Decode output if returned as bytes (Python 3) if isinstance(stdout, bytes): output = stdout.decode('ascii') # Split output lines into array; make empty output more readable output_lines = output.splitlines() if output else ['[no output]'] # If output is multi-lined, print the first line of the output on a # separate line from the "checking against solution" message, and # skip the solution check (multi-line solution won't be correct) if len(output_lines) > 1: is_correct = False click.echo() # force output to start on next line click.secho('\n'.join(output_lines), bold=True, fg='red') else: is_correct = output_lines[0] == solution fg_colour = 'green' if is_correct else 'red' click.secho(output_lines[0], bold=True, fg=fg_colour) click.secho(time_info, fg='cyan') # Remove any suffix from the filename if its solution is correct if is_correct: p.file.change_suffix('') # Exit here if answer was incorrect, otherwise return is_correct value return sys.exit(1) if exit and not is_correct else is_correct
python
def verify(num, filename=None, exit=True): """Verifies the solution to a problem.""" p = Problem(num) filename = filename or p.filename() if not os.path.isfile(filename): # Attempt to verify the first problem file matched by glob if p.glob: filename = str(p.file) else: click.secho('No file found for problem %i.' % p.num, fg='red') sys.exit(1) solution = p.solution click.echo('Checking "{}" against solution: '.format(filename), nl=False) cmd = (sys.executable or 'python', filename) start = clock() proc = subprocess.Popen(cmd, stdout=subprocess.PIPE) stdout = proc.communicate()[0] end = clock() time_info = format_time(start, end) # Return value of anything other than 0 indicates an error if proc.poll() != 0: click.secho('Error calling "{}".'.format(filename), fg='red') click.secho(time_info, fg='cyan') # Return None if option is not --verify-all, otherwise exit return sys.exit(1) if exit else None # Decode output if returned as bytes (Python 3) if isinstance(stdout, bytes): output = stdout.decode('ascii') # Split output lines into array; make empty output more readable output_lines = output.splitlines() if output else ['[no output]'] # If output is multi-lined, print the first line of the output on a # separate line from the "checking against solution" message, and # skip the solution check (multi-line solution won't be correct) if len(output_lines) > 1: is_correct = False click.echo() # force output to start on next line click.secho('\n'.join(output_lines), bold=True, fg='red') else: is_correct = output_lines[0] == solution fg_colour = 'green' if is_correct else 'red' click.secho(output_lines[0], bold=True, fg=fg_colour) click.secho(time_info, fg='cyan') # Remove any suffix from the filename if its solution is correct if is_correct: p.file.change_suffix('') # Exit here if answer was incorrect, otherwise return is_correct value return sys.exit(1) if exit and not is_correct else is_correct
[ "def", "verify", "(", "num", ",", "filename", "=", "None", ",", "exit", "=", "True", ")", ":", "p", "=", "Problem", "(", "num", ")", "filename", "=", "filename", "or", "p", ".", "filename", "(", ")", "if", "not", "os", ".", "path", ".", "isfile",...
Verifies the solution to a problem.
[ "Verifies", "the", "solution", "to", "a", "problem", "." ]
739c1c67fa7b32af9140ca51e4b4a07733e057a6
https://github.com/iKevinY/EulerPy/blob/739c1c67fa7b32af9140ca51e4b4a07733e057a6/EulerPy/euler.py#L78-L136
train
213,268
iKevinY/EulerPy
EulerPy/euler.py
verify_all
def verify_all(num): """ Verifies all problem files in the current directory and prints an overview of the status of each problem. """ # Define various problem statuses keys = ('correct', 'incorrect', 'error', 'skipped', 'missing') symbols = ('C', 'I', 'E', 'S', '.') colours = ('green', 'red', 'yellow', 'cyan', 'white') status = OrderedDict( (key, click.style(symbol, fg=colour, bold=True)) for key, symbol, colour in zip(keys, symbols, colours) ) overview = {} # Search through problem files using glob module files = problem_glob() # No Project Euler files in the current directory if not files: click.echo("No Project Euler files found in the current directory.") sys.exit(1) for file in files: # Catch KeyboardInterrupt during verification to allow the user to # skip the verification of a specific problem if it takes too long try: is_correct = verify(file.num, filename=str(file), exit=False) except KeyboardInterrupt: overview[file.num] = status['skipped'] else: if is_correct is None: # error was returned by problem file overview[file.num] = status['error'] elif is_correct: overview[file.num] = status['correct'] elif not is_correct: overview[file.num] = status['incorrect'] # Attempt to add "skipped" suffix to the filename if the # problem file is not the current problem. This is useful # when the --verify-all is used in a directory containing # files generated pre-v1.1 (before files with suffixes) if file.num != num: file.change_suffix('-skipped') # Separate each verification with a newline click.echo() # Print overview of the status of each problem legend = ', '.join('{} = {}'.format(v, k) for k, v in status.items()) click.echo('-' * 63) click.echo(legend + '\n') # Rows needed for overview is based on the current problem number num_of_rows = (num + 19) // 20 for row in range(1, num_of_rows + 1): low, high = (row * 20) - 19, (row * 20) click.echo("Problems {:03d}-{:03d}: ".format(low, high), nl=False) for problem in range(low, high + 1): # Add missing status to problems with no corresponding file status = overview[problem] if problem in overview else '.' # Separate problem indicators into groups of 5 spacer = ' ' if (problem % 5 == 0) else ' ' # Start a new line at the end of each row click.secho(status + spacer, nl=(problem % 20 == 0)) click.echo()
python
def verify_all(num): """ Verifies all problem files in the current directory and prints an overview of the status of each problem. """ # Define various problem statuses keys = ('correct', 'incorrect', 'error', 'skipped', 'missing') symbols = ('C', 'I', 'E', 'S', '.') colours = ('green', 'red', 'yellow', 'cyan', 'white') status = OrderedDict( (key, click.style(symbol, fg=colour, bold=True)) for key, symbol, colour in zip(keys, symbols, colours) ) overview = {} # Search through problem files using glob module files = problem_glob() # No Project Euler files in the current directory if not files: click.echo("No Project Euler files found in the current directory.") sys.exit(1) for file in files: # Catch KeyboardInterrupt during verification to allow the user to # skip the verification of a specific problem if it takes too long try: is_correct = verify(file.num, filename=str(file), exit=False) except KeyboardInterrupt: overview[file.num] = status['skipped'] else: if is_correct is None: # error was returned by problem file overview[file.num] = status['error'] elif is_correct: overview[file.num] = status['correct'] elif not is_correct: overview[file.num] = status['incorrect'] # Attempt to add "skipped" suffix to the filename if the # problem file is not the current problem. This is useful # when the --verify-all is used in a directory containing # files generated pre-v1.1 (before files with suffixes) if file.num != num: file.change_suffix('-skipped') # Separate each verification with a newline click.echo() # Print overview of the status of each problem legend = ', '.join('{} = {}'.format(v, k) for k, v in status.items()) click.echo('-' * 63) click.echo(legend + '\n') # Rows needed for overview is based on the current problem number num_of_rows = (num + 19) // 20 for row in range(1, num_of_rows + 1): low, high = (row * 20) - 19, (row * 20) click.echo("Problems {:03d}-{:03d}: ".format(low, high), nl=False) for problem in range(low, high + 1): # Add missing status to problems with no corresponding file status = overview[problem] if problem in overview else '.' # Separate problem indicators into groups of 5 spacer = ' ' if (problem % 5 == 0) else ' ' # Start a new line at the end of each row click.secho(status + spacer, nl=(problem % 20 == 0)) click.echo()
[ "def", "verify_all", "(", "num", ")", ":", "# Define various problem statuses", "keys", "=", "(", "'correct'", ",", "'incorrect'", ",", "'error'", ",", "'skipped'", ",", "'missing'", ")", "symbols", "=", "(", "'C'", ",", "'I'", ",", "'E'", ",", "'S'", ",",...
Verifies all problem files in the current directory and prints an overview of the status of each problem.
[ "Verifies", "all", "problem", "files", "in", "the", "current", "directory", "and", "prints", "an", "overview", "of", "the", "status", "of", "each", "problem", "." ]
739c1c67fa7b32af9140ca51e4b4a07733e057a6
https://github.com/iKevinY/EulerPy/blob/739c1c67fa7b32af9140ca51e4b4a07733e057a6/EulerPy/euler.py#L140-L214
train
213,269
iKevinY/EulerPy
EulerPy/euler.py
euler_options
def euler_options(fn): """Decorator to link CLI options with their appropriate functions""" euler_functions = cheat, generate, preview, skip, verify, verify_all # Reverse functions to print help page options in alphabetical order for option in reversed(euler_functions): name, docstring = option.__name__, option.__doc__ kwargs = {'flag_value': option, 'help': docstring} # Apply flag(s) depending on whether or not name is a single word flag = '--%s' % name.replace('_', '-') flags = [flag] if '_' in name else [flag, '-%s' % name[0]] fn = click.option('option', *flags, **kwargs)(fn) return fn
python
def euler_options(fn): """Decorator to link CLI options with their appropriate functions""" euler_functions = cheat, generate, preview, skip, verify, verify_all # Reverse functions to print help page options in alphabetical order for option in reversed(euler_functions): name, docstring = option.__name__, option.__doc__ kwargs = {'flag_value': option, 'help': docstring} # Apply flag(s) depending on whether or not name is a single word flag = '--%s' % name.replace('_', '-') flags = [flag] if '_' in name else [flag, '-%s' % name[0]] fn = click.option('option', *flags, **kwargs)(fn) return fn
[ "def", "euler_options", "(", "fn", ")", ":", "euler_functions", "=", "cheat", ",", "generate", ",", "preview", ",", "skip", ",", "verify", ",", "verify_all", "# Reverse functions to print help page options in alphabetical order", "for", "option", "in", "reversed", "("...
Decorator to link CLI options with their appropriate functions
[ "Decorator", "to", "link", "CLI", "options", "with", "their", "appropriate", "functions" ]
739c1c67fa7b32af9140ca51e4b4a07733e057a6
https://github.com/iKevinY/EulerPy/blob/739c1c67fa7b32af9140ca51e4b4a07733e057a6/EulerPy/euler.py#L217-L232
train
213,270
iKevinY/EulerPy
EulerPy/euler.py
main
def main(option, problem): """Python-based Project Euler command line tool.""" # No problem given (or given option ignores the problem argument) if problem == 0 or option in {skip, verify_all}: # Determine the highest problem number in the current directory files = problem_glob() problem = max(file.num for file in files) if files else 0 # No Project Euler files in current directory (no glob results) if problem == 0: # Generate the first problem file if option is appropriate if option not in {cheat, preview, verify_all}: msg = "No Project Euler files found in the current directory." click.echo(msg) option = generate # Set problem number to 1 problem = 1 # --preview and no problem; preview the next problem elif option is preview: problem += 1 # No option and no problem; generate next file if answer is # correct (verify() will exit if the solution is incorrect) if option is None: verify(problem) problem += 1 option = generate # Problem given but no option; decide between generate and verify elif option is None: option = verify if Problem(problem).glob else generate # Execute function based on option option(problem) sys.exit(0)
python
def main(option, problem): """Python-based Project Euler command line tool.""" # No problem given (or given option ignores the problem argument) if problem == 0 or option in {skip, verify_all}: # Determine the highest problem number in the current directory files = problem_glob() problem = max(file.num for file in files) if files else 0 # No Project Euler files in current directory (no glob results) if problem == 0: # Generate the first problem file if option is appropriate if option not in {cheat, preview, verify_all}: msg = "No Project Euler files found in the current directory." click.echo(msg) option = generate # Set problem number to 1 problem = 1 # --preview and no problem; preview the next problem elif option is preview: problem += 1 # No option and no problem; generate next file if answer is # correct (verify() will exit if the solution is incorrect) if option is None: verify(problem) problem += 1 option = generate # Problem given but no option; decide between generate and verify elif option is None: option = verify if Problem(problem).glob else generate # Execute function based on option option(problem) sys.exit(0)
[ "def", "main", "(", "option", ",", "problem", ")", ":", "# No problem given (or given option ignores the problem argument)", "if", "problem", "==", "0", "or", "option", "in", "{", "skip", ",", "verify_all", "}", ":", "# Determine the highest problem number in the current ...
Python-based Project Euler command line tool.
[ "Python", "-", "based", "Project", "Euler", "command", "line", "tool", "." ]
739c1c67fa7b32af9140ca51e4b4a07733e057a6
https://github.com/iKevinY/EulerPy/blob/739c1c67fa7b32af9140ca51e4b4a07733e057a6/EulerPy/euler.py#L239-L275
train
213,271
danielperna84/pyhomematic
pyhomematic/connection.py
HMConnection.start
def start(self, *args, **kwargs): """ Start the server thread if it wasn't created with autostart = True. """ if args: LOG.debug("args: %s" % str(args)) if kwargs: LOG.debug("kwargs: %s" % str(kwargs)) try: self._server.start() self._server.proxyInit() return True except Exception as err: LOG.critical("Failed to start server") LOG.debug(str(err)) self._server.stop() return False
python
def start(self, *args, **kwargs): """ Start the server thread if it wasn't created with autostart = True. """ if args: LOG.debug("args: %s" % str(args)) if kwargs: LOG.debug("kwargs: %s" % str(kwargs)) try: self._server.start() self._server.proxyInit() return True except Exception as err: LOG.critical("Failed to start server") LOG.debug(str(err)) self._server.stop() return False
[ "def", "start", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "args", ":", "LOG", ".", "debug", "(", "\"args: %s\"", "%", "str", "(", "args", ")", ")", "if", "kwargs", ":", "LOG", ".", "debug", "(", "\"kwargs: %s\"", "%"...
Start the server thread if it wasn't created with autostart = True.
[ "Start", "the", "server", "thread", "if", "it", "wasn", "t", "created", "with", "autostart", "=", "True", "." ]
8b91f3e84c83f05d289c740d507293a0d6759d8e
https://github.com/danielperna84/pyhomematic/blob/8b91f3e84c83f05d289c740d507293a0d6759d8e/pyhomematic/connection.py#L64-L80
train
213,272
danielperna84/pyhomematic
pyhomematic/connection.py
HMConnection.stop
def stop(self, *args, **kwargs): """ Stop the server thread. """ if args: LOG.debug("args: %s" % str(args)) if kwargs: LOG.debug("kwargs: %s" % str(kwargs)) try: self._server.stop() self._server = None # Device-storage clear self.devices.clear() self.devices_all.clear() self.devices_raw.clear() self.devices_raw_dict.clear() return True except Exception as err: LOG.critical("Failed to stop server") LOG.debug(str(err)) return False
python
def stop(self, *args, **kwargs): """ Stop the server thread. """ if args: LOG.debug("args: %s" % str(args)) if kwargs: LOG.debug("kwargs: %s" % str(kwargs)) try: self._server.stop() self._server = None # Device-storage clear self.devices.clear() self.devices_all.clear() self.devices_raw.clear() self.devices_raw_dict.clear() return True except Exception as err: LOG.critical("Failed to stop server") LOG.debug(str(err)) return False
[ "def", "stop", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "args", ":", "LOG", ".", "debug", "(", "\"args: %s\"", "%", "str", "(", "args", ")", ")", "if", "kwargs", ":", "LOG", ".", "debug", "(", "\"kwargs: %s\"", "%",...
Stop the server thread.
[ "Stop", "the", "server", "thread", "." ]
8b91f3e84c83f05d289c740d507293a0d6759d8e
https://github.com/danielperna84/pyhomematic/blob/8b91f3e84c83f05d289c740d507293a0d6759d8e/pyhomematic/connection.py#L82-L104
train
213,273
danielperna84/pyhomematic
pyhomematic/connection.py
HMConnection.getMetadata
def getMetadata(self, remote, address, key): """Get metadata of device""" if self._server is not None: # pylint: disable=E1121 return self._server.getAllMetadata(remote, address, key)
python
def getMetadata(self, remote, address, key): """Get metadata of device""" if self._server is not None: # pylint: disable=E1121 return self._server.getAllMetadata(remote, address, key)
[ "def", "getMetadata", "(", "self", ",", "remote", ",", "address", ",", "key", ")", ":", "if", "self", ".", "_server", "is", "not", "None", ":", "# pylint: disable=E1121", "return", "self", ".", "_server", ".", "getAllMetadata", "(", "remote", ",", "address...
Get metadata of device
[ "Get", "metadata", "of", "device" ]
8b91f3e84c83f05d289c740d507293a0d6759d8e
https://github.com/danielperna84/pyhomematic/blob/8b91f3e84c83f05d289c740d507293a0d6759d8e/pyhomematic/connection.py#L156-L160
train
213,274
danielperna84/pyhomematic
pyhomematic/devicetypes/actors.py
ColorEffectLight.get_hs_color
def get_hs_color(self): """ Return the color of the light as HSV color without the "value" component for the brightness. Returns (hue, saturation) tuple with values in range of 0-1, representing the H and S component of the HSV color system. """ # Get the color from homematic. In general this is just the hue parameter. hm_color = self.getCachedOrUpdatedValue("COLOR", channel=self._color_channel) if hm_color >= 200: # 200 is a special case (white), so we have a saturation of 0. # Larger values are undefined. For the sake of robustness we return "white" anyway. return 0, 0 # For all other colors we assume saturation of 1 return hm_color/200, 1
python
def get_hs_color(self): """ Return the color of the light as HSV color without the "value" component for the brightness. Returns (hue, saturation) tuple with values in range of 0-1, representing the H and S component of the HSV color system. """ # Get the color from homematic. In general this is just the hue parameter. hm_color = self.getCachedOrUpdatedValue("COLOR", channel=self._color_channel) if hm_color >= 200: # 200 is a special case (white), so we have a saturation of 0. # Larger values are undefined. For the sake of robustness we return "white" anyway. return 0, 0 # For all other colors we assume saturation of 1 return hm_color/200, 1
[ "def", "get_hs_color", "(", "self", ")", ":", "# Get the color from homematic. In general this is just the hue parameter.", "hm_color", "=", "self", ".", "getCachedOrUpdatedValue", "(", "\"COLOR\"", ",", "channel", "=", "self", ".", "_color_channel", ")", "if", "hm_color"...
Return the color of the light as HSV color without the "value" component for the brightness. Returns (hue, saturation) tuple with values in range of 0-1, representing the H and S component of the HSV color system.
[ "Return", "the", "color", "of", "the", "light", "as", "HSV", "color", "without", "the", "value", "component", "for", "the", "brightness", "." ]
8b91f3e84c83f05d289c740d507293a0d6759d8e
https://github.com/danielperna84/pyhomematic/blob/8b91f3e84c83f05d289c740d507293a0d6759d8e/pyhomematic/devicetypes/actors.py#L516-L532
train
213,275
danielperna84/pyhomematic
pyhomematic/devicetypes/actors.py
ColorEffectLight.set_hs_color
def set_hs_color(self, hue: float, saturation: float): """ Set a fixed color and also turn off effects in order to see the color. :param hue: Hue component (range 0-1) :param saturation: Saturation component (range 0-1). Yields white for values near 0, other values are interpreted as 100% saturation. The input values are the components of an HSV color without the value/brightness component. Example colors: * Green: set_hs_color(120/360, 1) * Blue: set_hs_color(240/360, 1) * Yellow: set_hs_color(60/360, 1) * White: set_hs_color(0, 0) """ self.turn_off_effect() if saturation < 0.1: # Special case (white) hm_color = 200 else: hm_color = int(round(max(min(hue, 1), 0) * 199)) self.setValue(key="COLOR", channel=self._color_channel, value=hm_color)
python
def set_hs_color(self, hue: float, saturation: float): """ Set a fixed color and also turn off effects in order to see the color. :param hue: Hue component (range 0-1) :param saturation: Saturation component (range 0-1). Yields white for values near 0, other values are interpreted as 100% saturation. The input values are the components of an HSV color without the value/brightness component. Example colors: * Green: set_hs_color(120/360, 1) * Blue: set_hs_color(240/360, 1) * Yellow: set_hs_color(60/360, 1) * White: set_hs_color(0, 0) """ self.turn_off_effect() if saturation < 0.1: # Special case (white) hm_color = 200 else: hm_color = int(round(max(min(hue, 1), 0) * 199)) self.setValue(key="COLOR", channel=self._color_channel, value=hm_color)
[ "def", "set_hs_color", "(", "self", ",", "hue", ":", "float", ",", "saturation", ":", "float", ")", ":", "self", ".", "turn_off_effect", "(", ")", "if", "saturation", "<", "0.1", ":", "# Special case (white)", "hm_color", "=", "200", "else", ":", "hm_color...
Set a fixed color and also turn off effects in order to see the color. :param hue: Hue component (range 0-1) :param saturation: Saturation component (range 0-1). Yields white for values near 0, other values are interpreted as 100% saturation. The input values are the components of an HSV color without the value/brightness component. Example colors: * Green: set_hs_color(120/360, 1) * Blue: set_hs_color(240/360, 1) * Yellow: set_hs_color(60/360, 1) * White: set_hs_color(0, 0)
[ "Set", "a", "fixed", "color", "and", "also", "turn", "off", "effects", "in", "order", "to", "see", "the", "color", "." ]
8b91f3e84c83f05d289c740d507293a0d6759d8e
https://github.com/danielperna84/pyhomematic/blob/8b91f3e84c83f05d289c740d507293a0d6759d8e/pyhomematic/devicetypes/actors.py#L534-L556
train
213,276
danielperna84/pyhomematic
pyhomematic/devicetypes/actors.py
ColorEffectLight.get_effect
def get_effect(self) -> str: """Return the current color change program of the light.""" effect_value = self.getCachedOrUpdatedValue("PROGRAM", channel=self._effect_channel) try: return self._light_effect_list[effect_value] except IndexError: LOG.error("Unexpected color effect returned by CCU") return "Unknown"
python
def get_effect(self) -> str: """Return the current color change program of the light.""" effect_value = self.getCachedOrUpdatedValue("PROGRAM", channel=self._effect_channel) try: return self._light_effect_list[effect_value] except IndexError: LOG.error("Unexpected color effect returned by CCU") return "Unknown"
[ "def", "get_effect", "(", "self", ")", "->", "str", ":", "effect_value", "=", "self", ".", "getCachedOrUpdatedValue", "(", "\"PROGRAM\"", ",", "channel", "=", "self", ".", "_effect_channel", ")", "try", ":", "return", "self", ".", "_light_effect_list", "[", ...
Return the current color change program of the light.
[ "Return", "the", "current", "color", "change", "program", "of", "the", "light", "." ]
8b91f3e84c83f05d289c740d507293a0d6759d8e
https://github.com/danielperna84/pyhomematic/blob/8b91f3e84c83f05d289c740d507293a0d6759d8e/pyhomematic/devicetypes/actors.py#L562-L570
train
213,277
danielperna84/pyhomematic
pyhomematic/devicetypes/actors.py
ColorEffectLight.set_effect
def set_effect(self, effect_name: str): """Sets the color change program of the light.""" try: effect_index = self._light_effect_list.index(effect_name) except ValueError: LOG.error("Trying to set unknown light effect") return False return self.setValue(key="PROGRAM", channel=self._effect_channel, value=effect_index)
python
def set_effect(self, effect_name: str): """Sets the color change program of the light.""" try: effect_index = self._light_effect_list.index(effect_name) except ValueError: LOG.error("Trying to set unknown light effect") return False return self.setValue(key="PROGRAM", channel=self._effect_channel, value=effect_index)
[ "def", "set_effect", "(", "self", ",", "effect_name", ":", "str", ")", ":", "try", ":", "effect_index", "=", "self", ".", "_light_effect_list", ".", "index", "(", "effect_name", ")", "except", "ValueError", ":", "LOG", ".", "error", "(", "\"Trying to set unk...
Sets the color change program of the light.
[ "Sets", "the", "color", "change", "program", "of", "the", "light", "." ]
8b91f3e84c83f05d289c740d507293a0d6759d8e
https://github.com/danielperna84/pyhomematic/blob/8b91f3e84c83f05d289c740d507293a0d6759d8e/pyhomematic/devicetypes/actors.py#L572-L580
train
213,278
danielperna84/pyhomematic
pyhomematic/_hm.py
make_http_credentials
def make_http_credentials(username=None, password=None): """Build auth part for api_url.""" credentials = '' if username is None: return credentials if username is not None: if ':' in username: return credentials credentials += username if credentials and password is not None: credentials += ":%s" % password return "%s@" % credentials
python
def make_http_credentials(username=None, password=None): """Build auth part for api_url.""" credentials = '' if username is None: return credentials if username is not None: if ':' in username: return credentials credentials += username if credentials and password is not None: credentials += ":%s" % password return "%s@" % credentials
[ "def", "make_http_credentials", "(", "username", "=", "None", ",", "password", "=", "None", ")", ":", "credentials", "=", "''", "if", "username", "is", "None", ":", "return", "credentials", "if", "username", "is", "not", "None", ":", "if", "':'", "in", "...
Build auth part for api_url.
[ "Build", "auth", "part", "for", "api_url", "." ]
8b91f3e84c83f05d289c740d507293a0d6759d8e
https://github.com/danielperna84/pyhomematic/blob/8b91f3e84c83f05d289c740d507293a0d6759d8e/pyhomematic/_hm.py#L50-L61
train
213,279
danielperna84/pyhomematic
pyhomematic/_hm.py
build_api_url
def build_api_url(host=REMOTES['default']['ip'], port=REMOTES['default']['port'], path=REMOTES['default']['path'], username=None, password=None, ssl=False): """Build API URL from components.""" credentials = make_http_credentials(username, password) scheme = 'http' if not path: path = '' if path and not path.startswith('/'): path = "/%s" % path if ssl: scheme += 's' return "%s://%s%s:%i%s" % (scheme, credentials, host, port, path)
python
def build_api_url(host=REMOTES['default']['ip'], port=REMOTES['default']['port'], path=REMOTES['default']['path'], username=None, password=None, ssl=False): """Build API URL from components.""" credentials = make_http_credentials(username, password) scheme = 'http' if not path: path = '' if path and not path.startswith('/'): path = "/%s" % path if ssl: scheme += 's' return "%s://%s%s:%i%s" % (scheme, credentials, host, port, path)
[ "def", "build_api_url", "(", "host", "=", "REMOTES", "[", "'default'", "]", "[", "'ip'", "]", ",", "port", "=", "REMOTES", "[", "'default'", "]", "[", "'port'", "]", ",", "path", "=", "REMOTES", "[", "'default'", "]", "[", "'path'", "]", ",", "userna...
Build API URL from components.
[ "Build", "API", "URL", "from", "components", "." ]
8b91f3e84c83f05d289c740d507293a0d6759d8e
https://github.com/danielperna84/pyhomematic/blob/8b91f3e84c83f05d289c740d507293a0d6759d8e/pyhomematic/_hm.py#L64-L79
train
213,280
danielperna84/pyhomematic
pyhomematic/_hm.py
RPCFunctions.createDeviceObjects
def createDeviceObjects(self, interface_id): """Transform the raw device descriptions into instances of devicetypes.generic.HMDevice or availabe subclass.""" global WORKING WORKING = True remote = interface_id.split('-')[-1] LOG.debug( "RPCFunctions.createDeviceObjects: iterating interface_id = %s" % (remote, )) # First create parent object for dev in self._devices_raw[remote]: if not dev['PARENT']: if dev['ADDRESS'] not in self.devices_all[remote]: try: if dev['TYPE'] in devicetypes.SUPPORTED: deviceObject = devicetypes.SUPPORTED[dev['TYPE']]( dev, self._proxies[interface_id], self.resolveparamsets) LOG.debug("RPCFunctions.createDeviceObjects: created %s as SUPPORTED device for %s" % ( dev['ADDRESS'], dev['TYPE'])) else: deviceObject = devicetypes.UNSUPPORTED( dev, self._proxies[interface_id], self.resolveparamsets) LOG.debug("RPCFunctions.createDeviceObjects: created %s as UNSUPPORTED device for %s" % ( dev['ADDRESS'], dev['TYPE'])) LOG.debug( "RPCFunctions.createDeviceObjects: adding to self.devices_all") self.devices_all[remote][dev['ADDRESS']] = deviceObject LOG.debug( "RPCFunctions.createDeviceObjects: adding to self.devices") self.devices[remote][dev['ADDRESS']] = deviceObject except Exception as err: LOG.critical( "RPCFunctions.createDeviceObjects: Parent: %s", str(err)) # Then create all children for parent for dev in self._devices_raw[remote]: if dev['PARENT']: try: if dev['ADDRESS'] not in self.devices_all[remote]: deviceObject = HMChannel( dev, self._proxies[interface_id], self.resolveparamsets) self.devices_all[remote][dev['ADDRESS']] = deviceObject self.devices[remote][dev['PARENT']].CHANNELS[ dev['INDEX']] = deviceObject except Exception as err: LOG.critical( "RPCFunctions.createDeviceObjects: Child: %s", str(err)) if self.devices_all[remote] and self.remotes[remote].get('resolvenames', False): self.addDeviceNames(remote) WORKING = False if self.systemcallback: self.systemcallback('createDeviceObjects') return True
python
def createDeviceObjects(self, interface_id): """Transform the raw device descriptions into instances of devicetypes.generic.HMDevice or availabe subclass.""" global WORKING WORKING = True remote = interface_id.split('-')[-1] LOG.debug( "RPCFunctions.createDeviceObjects: iterating interface_id = %s" % (remote, )) # First create parent object for dev in self._devices_raw[remote]: if not dev['PARENT']: if dev['ADDRESS'] not in self.devices_all[remote]: try: if dev['TYPE'] in devicetypes.SUPPORTED: deviceObject = devicetypes.SUPPORTED[dev['TYPE']]( dev, self._proxies[interface_id], self.resolveparamsets) LOG.debug("RPCFunctions.createDeviceObjects: created %s as SUPPORTED device for %s" % ( dev['ADDRESS'], dev['TYPE'])) else: deviceObject = devicetypes.UNSUPPORTED( dev, self._proxies[interface_id], self.resolveparamsets) LOG.debug("RPCFunctions.createDeviceObjects: created %s as UNSUPPORTED device for %s" % ( dev['ADDRESS'], dev['TYPE'])) LOG.debug( "RPCFunctions.createDeviceObjects: adding to self.devices_all") self.devices_all[remote][dev['ADDRESS']] = deviceObject LOG.debug( "RPCFunctions.createDeviceObjects: adding to self.devices") self.devices[remote][dev['ADDRESS']] = deviceObject except Exception as err: LOG.critical( "RPCFunctions.createDeviceObjects: Parent: %s", str(err)) # Then create all children for parent for dev in self._devices_raw[remote]: if dev['PARENT']: try: if dev['ADDRESS'] not in self.devices_all[remote]: deviceObject = HMChannel( dev, self._proxies[interface_id], self.resolveparamsets) self.devices_all[remote][dev['ADDRESS']] = deviceObject self.devices[remote][dev['PARENT']].CHANNELS[ dev['INDEX']] = deviceObject except Exception as err: LOG.critical( "RPCFunctions.createDeviceObjects: Child: %s", str(err)) if self.devices_all[remote] and self.remotes[remote].get('resolvenames', False): self.addDeviceNames(remote) WORKING = False if self.systemcallback: self.systemcallback('createDeviceObjects') return True
[ "def", "createDeviceObjects", "(", "self", ",", "interface_id", ")", ":", "global", "WORKING", "WORKING", "=", "True", "remote", "=", "interface_id", ".", "split", "(", "'-'", ")", "[", "-", "1", "]", "LOG", ".", "debug", "(", "\"RPCFunctions.createDeviceObj...
Transform the raw device descriptions into instances of devicetypes.generic.HMDevice or availabe subclass.
[ "Transform", "the", "raw", "device", "descriptions", "into", "instances", "of", "devicetypes", ".", "generic", ".", "HMDevice", "or", "availabe", "subclass", "." ]
8b91f3e84c83f05d289c740d507293a0d6759d8e
https://github.com/danielperna84/pyhomematic/blob/8b91f3e84c83f05d289c740d507293a0d6759d8e/pyhomematic/_hm.py#L147-L196
train
213,281
danielperna84/pyhomematic
pyhomematic/_hm.py
RPCFunctions.event
def event(self, interface_id, address, value_key, value): """If a device emits some sort event, we will handle it here.""" LOG.debug("RPCFunctions.event: interface_id = %s, address = %s, value_key = %s, value = %s" % ( interface_id, address, value_key.upper(), str(value))) self.devices_all[interface_id.split( '-')[-1]][address].event(interface_id, value_key.upper(), value) if self.eventcallback: self.eventcallback(interface_id=interface_id, address=address, value_key=value_key.upper(), value=value) return True
python
def event(self, interface_id, address, value_key, value): """If a device emits some sort event, we will handle it here.""" LOG.debug("RPCFunctions.event: interface_id = %s, address = %s, value_key = %s, value = %s" % ( interface_id, address, value_key.upper(), str(value))) self.devices_all[interface_id.split( '-')[-1]][address].event(interface_id, value_key.upper(), value) if self.eventcallback: self.eventcallback(interface_id=interface_id, address=address, value_key=value_key.upper(), value=value) return True
[ "def", "event", "(", "self", ",", "interface_id", ",", "address", ",", "value_key", ",", "value", ")", ":", "LOG", ".", "debug", "(", "\"RPCFunctions.event: interface_id = %s, address = %s, value_key = %s, value = %s\"", "%", "(", "interface_id", ",", "address", ",", ...
If a device emits some sort event, we will handle it here.
[ "If", "a", "device", "emits", "some", "sort", "event", "we", "will", "handle", "it", "here", "." ]
8b91f3e84c83f05d289c740d507293a0d6759d8e
https://github.com/danielperna84/pyhomematic/blob/8b91f3e84c83f05d289c740d507293a0d6759d8e/pyhomematic/_hm.py#L222-L231
train
213,282
danielperna84/pyhomematic
pyhomematic/_hm.py
LockingServerProxy.__request
def __request(self, *args, **kwargs): """ Call method on server side """ with self.lock: parent = xmlrpc.client.ServerProxy # pylint: disable=E1101 return parent._ServerProxy__request(self, *args, **kwargs)
python
def __request(self, *args, **kwargs): """ Call method on server side """ with self.lock: parent = xmlrpc.client.ServerProxy # pylint: disable=E1101 return parent._ServerProxy__request(self, *args, **kwargs)
[ "def", "__request", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "self", ".", "lock", ":", "parent", "=", "xmlrpc", ".", "client", ".", "ServerProxy", "# pylint: disable=E1101", "return", "parent", ".", "_ServerProxy__request", ...
Call method on server side
[ "Call", "method", "on", "server", "side" ]
8b91f3e84c83f05d289c740d507293a0d6759d8e
https://github.com/danielperna84/pyhomematic/blob/8b91f3e84c83f05d289c740d507293a0d6759d8e/pyhomematic/_hm.py#L457-L465
train
213,283
danielperna84/pyhomematic
pyhomematic/_hm.py
ServerThread.parseCCUSysVar
def parseCCUSysVar(self, data): """Helper to parse type of system variables of CCU""" if data['type'] == 'LOGIC': return data['name'], data['value'] == 'true' elif data['type'] == 'NUMBER': return data['name'], float(data['value']) elif data['type'] == 'LIST': return data['name'], int(data['value']) else: return data['name'], data['value']
python
def parseCCUSysVar(self, data): """Helper to parse type of system variables of CCU""" if data['type'] == 'LOGIC': return data['name'], data['value'] == 'true' elif data['type'] == 'NUMBER': return data['name'], float(data['value']) elif data['type'] == 'LIST': return data['name'], int(data['value']) else: return data['name'], data['value']
[ "def", "parseCCUSysVar", "(", "self", ",", "data", ")", ":", "if", "data", "[", "'type'", "]", "==", "'LOGIC'", ":", "return", "data", "[", "'name'", "]", ",", "data", "[", "'value'", "]", "==", "'true'", "elif", "data", "[", "'type'", "]", "==", "...
Helper to parse type of system variables of CCU
[ "Helper", "to", "parse", "type", "of", "system", "variables", "of", "CCU" ]
8b91f3e84c83f05d289c740d507293a0d6759d8e
https://github.com/danielperna84/pyhomematic/blob/8b91f3e84c83f05d289c740d507293a0d6759d8e/pyhomematic/_hm.py#L639-L648
train
213,284
danielperna84/pyhomematic
pyhomematic/_hm.py
ServerThread.jsonRpcLogin
def jsonRpcLogin(self, remote): """Login to CCU and return session""" session = False try: params = {"username": self.remotes[remote][ 'username'], "password": self.remotes[remote]['password']} response = self._rpcfunctions.jsonRpcPost( self.remotes[remote]['ip'], self.remotes[remote].get('jsonport', DEFAULT_JSONPORT), "Session.login", params) if response['error'] is None and response['result']: session = response['result'] if not session: LOG.warning( "ServerThread.jsonRpcLogin: Unable to open session.") except Exception as err: LOG.debug( "ServerThread.jsonRpcLogin: Exception while logging in via JSON-RPC: %s" % str(err)) return session
python
def jsonRpcLogin(self, remote): """Login to CCU and return session""" session = False try: params = {"username": self.remotes[remote][ 'username'], "password": self.remotes[remote]['password']} response = self._rpcfunctions.jsonRpcPost( self.remotes[remote]['ip'], self.remotes[remote].get('jsonport', DEFAULT_JSONPORT), "Session.login", params) if response['error'] is None and response['result']: session = response['result'] if not session: LOG.warning( "ServerThread.jsonRpcLogin: Unable to open session.") except Exception as err: LOG.debug( "ServerThread.jsonRpcLogin: Exception while logging in via JSON-RPC: %s" % str(err)) return session
[ "def", "jsonRpcLogin", "(", "self", ",", "remote", ")", ":", "session", "=", "False", "try", ":", "params", "=", "{", "\"username\"", ":", "self", ".", "remotes", "[", "remote", "]", "[", "'username'", "]", ",", "\"password\"", ":", "self", ".", "remot...
Login to CCU and return session
[ "Login", "to", "CCU", "and", "return", "session" ]
8b91f3e84c83f05d289c740d507293a0d6759d8e
https://github.com/danielperna84/pyhomematic/blob/8b91f3e84c83f05d289c740d507293a0d6759d8e/pyhomematic/_hm.py#L650-L667
train
213,285
danielperna84/pyhomematic
pyhomematic/_hm.py
ServerThread.jsonRpcLogout
def jsonRpcLogout(self, remote, session): """Logout of CCU""" logout = False try: params = {"_session_id_": session} response = self._rpcfunctions.jsonRpcPost( self.remotes[remote]['ip'], self.remotes[remote].get('jsonport', DEFAULT_JSONPORT), "Session.logout", params) if response['error'] is None and response['result']: logout = response['result'] except Exception as err: LOG.debug( "ServerThread.jsonRpcLogout: Exception while logging in via JSON-RPC: %s" % str(err)) return logout
python
def jsonRpcLogout(self, remote, session): """Logout of CCU""" logout = False try: params = {"_session_id_": session} response = self._rpcfunctions.jsonRpcPost( self.remotes[remote]['ip'], self.remotes[remote].get('jsonport', DEFAULT_JSONPORT), "Session.logout", params) if response['error'] is None and response['result']: logout = response['result'] except Exception as err: LOG.debug( "ServerThread.jsonRpcLogout: Exception while logging in via JSON-RPC: %s" % str(err)) return logout
[ "def", "jsonRpcLogout", "(", "self", ",", "remote", ",", "session", ")", ":", "logout", "=", "False", "try", ":", "params", "=", "{", "\"_session_id_\"", ":", "session", "}", "response", "=", "self", ".", "_rpcfunctions", ".", "jsonRpcPost", "(", "self", ...
Logout of CCU
[ "Logout", "of", "CCU" ]
8b91f3e84c83f05d289c740d507293a0d6759d8e
https://github.com/danielperna84/pyhomematic/blob/8b91f3e84c83f05d289c740d507293a0d6759d8e/pyhomematic/_hm.py#L669-L681
train
213,286
danielperna84/pyhomematic
pyhomematic/_hm.py
ServerThread.homegearCheckInit
def homegearCheckInit(self, remote): """Check if proxy is still initialized""" rdict = self.remotes.get(remote) if not rdict: return False if rdict.get('type') != BACKEND_HOMEGEAR: return False try: interface_id = "%s-%s" % (self._interface_id, remote) return self.proxies[interface_id].clientServerInitialized(interface_id) except Exception as err: LOG.debug( "ServerThread.homegearCheckInit: Exception: %s" % str(err)) return False
python
def homegearCheckInit(self, remote): """Check if proxy is still initialized""" rdict = self.remotes.get(remote) if not rdict: return False if rdict.get('type') != BACKEND_HOMEGEAR: return False try: interface_id = "%s-%s" % (self._interface_id, remote) return self.proxies[interface_id].clientServerInitialized(interface_id) except Exception as err: LOG.debug( "ServerThread.homegearCheckInit: Exception: %s" % str(err)) return False
[ "def", "homegearCheckInit", "(", "self", ",", "remote", ")", ":", "rdict", "=", "self", ".", "remotes", ".", "get", "(", "remote", ")", "if", "not", "rdict", ":", "return", "False", "if", "rdict", ".", "get", "(", "'type'", ")", "!=", "BACKEND_HOMEGEAR...
Check if proxy is still initialized
[ "Check", "if", "proxy", "is", "still", "initialized" ]
8b91f3e84c83f05d289c740d507293a0d6759d8e
https://github.com/danielperna84/pyhomematic/blob/8b91f3e84c83f05d289c740d507293a0d6759d8e/pyhomematic/_hm.py#L895-L908
train
213,287
danielperna84/pyhomematic
pyhomematic/devicetypes/helper.py
HelperActionOnTime.set_ontime
def set_ontime(self, ontime): """Set duration th switch stays on when toggled. """ try: ontime = float(ontime) except Exception as err: LOG.debug("SwitchPowermeter.set_ontime: Exception %s" % (err,)) return False self.actionNodeData("ON_TIME", ontime)
python
def set_ontime(self, ontime): """Set duration th switch stays on when toggled. """ try: ontime = float(ontime) except Exception as err: LOG.debug("SwitchPowermeter.set_ontime: Exception %s" % (err,)) return False self.actionNodeData("ON_TIME", ontime)
[ "def", "set_ontime", "(", "self", ",", "ontime", ")", ":", "try", ":", "ontime", "=", "float", "(", "ontime", ")", "except", "Exception", "as", "err", ":", "LOG", ".", "debug", "(", "\"SwitchPowermeter.set_ontime: Exception %s\"", "%", "(", "err", ",", ")"...
Set duration th switch stays on when toggled.
[ "Set", "duration", "th", "switch", "stays", "on", "when", "toggled", "." ]
8b91f3e84c83f05d289c740d507293a0d6759d8e
https://github.com/danielperna84/pyhomematic/blob/8b91f3e84c83f05d289c740d507293a0d6759d8e/pyhomematic/devicetypes/helper.py#L206-L214
train
213,288
danielperna84/pyhomematic
pyhomematic/devicetypes/generic.py
HMGeneric.event
def event(self, interface_id, key, value): """ Handle the event received by server. """ LOG.info( "HMGeneric.event: address=%s, interface_id=%s, key=%s, value=%s" % (self._ADDRESS, interface_id, key, value)) self._VALUES[key] = value # Cache the value for callback in self._eventcallbacks: LOG.debug("HMGeneric.event: Using callback %s " % str(callback)) callback(self._ADDRESS, interface_id, key, value)
python
def event(self, interface_id, key, value): """ Handle the event received by server. """ LOG.info( "HMGeneric.event: address=%s, interface_id=%s, key=%s, value=%s" % (self._ADDRESS, interface_id, key, value)) self._VALUES[key] = value # Cache the value for callback in self._eventcallbacks: LOG.debug("HMGeneric.event: Using callback %s " % str(callback)) callback(self._ADDRESS, interface_id, key, value)
[ "def", "event", "(", "self", ",", "interface_id", ",", "key", ",", "value", ")", ":", "LOG", ".", "info", "(", "\"HMGeneric.event: address=%s, interface_id=%s, key=%s, value=%s\"", "%", "(", "self", ".", "_ADDRESS", ",", "interface_id", ",", "key", ",", "value",...
Handle the event received by server.
[ "Handle", "the", "event", "received", "by", "server", "." ]
8b91f3e84c83f05d289c740d507293a0d6759d8e
https://github.com/danielperna84/pyhomematic/blob/8b91f3e84c83f05d289c740d507293a0d6759d8e/pyhomematic/devicetypes/generic.py#L54-L66
train
213,289
danielperna84/pyhomematic
pyhomematic/devicetypes/generic.py
HMGeneric.getParamsetDescription
def getParamsetDescription(self, paramset): """ Descriptions for paramsets are available to determine what can be don with the device. """ try: self._PARAMSET_DESCRIPTIONS[paramset] = self._proxy.getParamsetDescription(self._ADDRESS, paramset) except Exception as err: LOG.error("HMGeneric.getParamsetDescription: Exception: " + str(err)) return False
python
def getParamsetDescription(self, paramset): """ Descriptions for paramsets are available to determine what can be don with the device. """ try: self._PARAMSET_DESCRIPTIONS[paramset] = self._proxy.getParamsetDescription(self._ADDRESS, paramset) except Exception as err: LOG.error("HMGeneric.getParamsetDescription: Exception: " + str(err)) return False
[ "def", "getParamsetDescription", "(", "self", ",", "paramset", ")", ":", "try", ":", "self", ".", "_PARAMSET_DESCRIPTIONS", "[", "paramset", "]", "=", "self", ".", "_proxy", ".", "getParamsetDescription", "(", "self", ".", "_ADDRESS", ",", "paramset", ")", "...
Descriptions for paramsets are available to determine what can be don with the device.
[ "Descriptions", "for", "paramsets", "are", "available", "to", "determine", "what", "can", "be", "don", "with", "the", "device", "." ]
8b91f3e84c83f05d289c740d507293a0d6759d8e
https://github.com/danielperna84/pyhomematic/blob/8b91f3e84c83f05d289c740d507293a0d6759d8e/pyhomematic/devicetypes/generic.py#L68-L76
train
213,290
danielperna84/pyhomematic
pyhomematic/devicetypes/generic.py
HMGeneric.updateParamset
def updateParamset(self, paramset): """ Devices should not update their own paramsets. They rely on the state of the server. Hence we pull the specified paramset. """ try: if paramset: if self._proxy: returnset = self._proxy.getParamset(self._ADDRESS, paramset) if returnset: self._paramsets[paramset] = returnset if self.PARAMSETS: if self.PARAMSETS.get(PARAMSET_VALUES): self._VALUES[PARAM_UNREACH] = self.PARAMSETS.get(PARAMSET_VALUES).get(PARAM_UNREACH) return True return False except Exception as err: LOG.debug("HMGeneric.updateParamset: Exception: %s, %s, %s" % (str(err), str(self._ADDRESS), str(paramset))) return False
python
def updateParamset(self, paramset): """ Devices should not update their own paramsets. They rely on the state of the server. Hence we pull the specified paramset. """ try: if paramset: if self._proxy: returnset = self._proxy.getParamset(self._ADDRESS, paramset) if returnset: self._paramsets[paramset] = returnset if self.PARAMSETS: if self.PARAMSETS.get(PARAMSET_VALUES): self._VALUES[PARAM_UNREACH] = self.PARAMSETS.get(PARAMSET_VALUES).get(PARAM_UNREACH) return True return False except Exception as err: LOG.debug("HMGeneric.updateParamset: Exception: %s, %s, %s" % (str(err), str(self._ADDRESS), str(paramset))) return False
[ "def", "updateParamset", "(", "self", ",", "paramset", ")", ":", "try", ":", "if", "paramset", ":", "if", "self", ".", "_proxy", ":", "returnset", "=", "self", ".", "_proxy", ".", "getParamset", "(", "self", ".", "_ADDRESS", ",", "paramset", ")", "if",...
Devices should not update their own paramsets. They rely on the state of the server. Hence we pull the specified paramset.
[ "Devices", "should", "not", "update", "their", "own", "paramsets", ".", "They", "rely", "on", "the", "state", "of", "the", "server", ".", "Hence", "we", "pull", "the", "specified", "paramset", "." ]
8b91f3e84c83f05d289c740d507293a0d6759d8e
https://github.com/danielperna84/pyhomematic/blob/8b91f3e84c83f05d289c740d507293a0d6759d8e/pyhomematic/devicetypes/generic.py#L78-L96
train
213,291
danielperna84/pyhomematic
pyhomematic/devicetypes/generic.py
HMGeneric.updateParamsets
def updateParamsets(self): """ Devices should update their own paramsets. They rely on the state of the server. Hence we pull all paramsets. """ try: for ps in self._PARAMSETS: self.updateParamset(ps) return True except Exception as err: LOG.error("HMGeneric.updateParamsets: Exception: " + str(err)) return False
python
def updateParamsets(self): """ Devices should update their own paramsets. They rely on the state of the server. Hence we pull all paramsets. """ try: for ps in self._PARAMSETS: self.updateParamset(ps) return True except Exception as err: LOG.error("HMGeneric.updateParamsets: Exception: " + str(err)) return False
[ "def", "updateParamsets", "(", "self", ")", ":", "try", ":", "for", "ps", "in", "self", ".", "_PARAMSETS", ":", "self", ".", "updateParamset", "(", "ps", ")", "return", "True", "except", "Exception", "as", "err", ":", "LOG", ".", "error", "(", "\"HMGen...
Devices should update their own paramsets. They rely on the state of the server. Hence we pull all paramsets.
[ "Devices", "should", "update", "their", "own", "paramsets", ".", "They", "rely", "on", "the", "state", "of", "the", "server", ".", "Hence", "we", "pull", "all", "paramsets", "." ]
8b91f3e84c83f05d289c740d507293a0d6759d8e
https://github.com/danielperna84/pyhomematic/blob/8b91f3e84c83f05d289c740d507293a0d6759d8e/pyhomematic/devicetypes/generic.py#L98-L108
train
213,292
danielperna84/pyhomematic
pyhomematic/devicetypes/generic.py
HMGeneric.putParamset
def putParamset(self, paramset, data={}): """ Some devices act upon changes to paramsets. A "putted" paramset must not contain all keys available in the specified paramset, just the ones which are writable and should be changed. """ try: if paramset in self._PARAMSETS and data: self._proxy.putParamset(self._ADDRESS, paramset, data) # We update all paramsets to at least have a temporarily accurate state for the device. # This might not be true for tasks that take long to complete (lifting a rollershutter completely etc.). # For this the server-process has to call the updateParamsets-method when it receives events for the device. self.updateParamsets() return True else: return False except Exception as err: LOG.error("HMGeneric.putParamset: Exception: " + str(err)) return False
python
def putParamset(self, paramset, data={}): """ Some devices act upon changes to paramsets. A "putted" paramset must not contain all keys available in the specified paramset, just the ones which are writable and should be changed. """ try: if paramset in self._PARAMSETS and data: self._proxy.putParamset(self._ADDRESS, paramset, data) # We update all paramsets to at least have a temporarily accurate state for the device. # This might not be true for tasks that take long to complete (lifting a rollershutter completely etc.). # For this the server-process has to call the updateParamsets-method when it receives events for the device. self.updateParamsets() return True else: return False except Exception as err: LOG.error("HMGeneric.putParamset: Exception: " + str(err)) return False
[ "def", "putParamset", "(", "self", ",", "paramset", ",", "data", "=", "{", "}", ")", ":", "try", ":", "if", "paramset", "in", "self", ".", "_PARAMSETS", "and", "data", ":", "self", ".", "_proxy", ".", "putParamset", "(", "self", ".", "_ADDRESS", ",",...
Some devices act upon changes to paramsets. A "putted" paramset must not contain all keys available in the specified paramset, just the ones which are writable and should be changed.
[ "Some", "devices", "act", "upon", "changes", "to", "paramsets", ".", "A", "putted", "paramset", "must", "not", "contain", "all", "keys", "available", "in", "the", "specified", "paramset", "just", "the", "ones", "which", "are", "writable", "and", "should", "b...
8b91f3e84c83f05d289c740d507293a0d6759d8e
https://github.com/danielperna84/pyhomematic/blob/8b91f3e84c83f05d289c740d507293a0d6759d8e/pyhomematic/devicetypes/generic.py#L110-L128
train
213,293
danielperna84/pyhomematic
pyhomematic/devicetypes/generic.py
HMChannel.getCachedOrUpdatedValue
def getCachedOrUpdatedValue(self, key): """ Gets the device's value with the given key. If the key is not found in the cache, the value is queried from the host. """ try: return self._VALUES[key] except KeyError: return self.getValue(key)
python
def getCachedOrUpdatedValue(self, key): """ Gets the device's value with the given key. If the key is not found in the cache, the value is queried from the host. """ try: return self._VALUES[key] except KeyError: return self.getValue(key)
[ "def", "getCachedOrUpdatedValue", "(", "self", ",", "key", ")", ":", "try", ":", "return", "self", ".", "_VALUES", "[", "key", "]", "except", "KeyError", ":", "return", "self", ".", "getValue", "(", "key", ")" ]
Gets the device's value with the given key. If the key is not found in the cache, the value is queried from the host.
[ "Gets", "the", "device", "s", "value", "with", "the", "given", "key", "." ]
8b91f3e84c83f05d289c740d507293a0d6759d8e
https://github.com/danielperna84/pyhomematic/blob/8b91f3e84c83f05d289c740d507293a0d6759d8e/pyhomematic/devicetypes/generic.py#L159-L167
train
213,294
danielperna84/pyhomematic
pyhomematic/devicetypes/generic.py
HMDevice.getCachedOrUpdatedValue
def getCachedOrUpdatedValue(self, key, channel=None): """ Gets the channel's value with the given key. If the key is not found in the cache, the value is queried from the host. If 'channel' is given, the respective channel's value is returned. """ if channel: return self._hmchannels[channel].getCachedOrUpdatedValue(key) try: return self._VALUES[key] except KeyError: value = self._VALUES[key] = self.getValue(key) return value
python
def getCachedOrUpdatedValue(self, key, channel=None): """ Gets the channel's value with the given key. If the key is not found in the cache, the value is queried from the host. If 'channel' is given, the respective channel's value is returned. """ if channel: return self._hmchannels[channel].getCachedOrUpdatedValue(key) try: return self._VALUES[key] except KeyError: value = self._VALUES[key] = self.getValue(key) return value
[ "def", "getCachedOrUpdatedValue", "(", "self", ",", "key", ",", "channel", "=", "None", ")", ":", "if", "channel", ":", "return", "self", ".", "_hmchannels", "[", "channel", "]", ".", "getCachedOrUpdatedValue", "(", "key", ")", "try", ":", "return", "self"...
Gets the channel's value with the given key. If the key is not found in the cache, the value is queried from the host. If 'channel' is given, the respective channel's value is returned.
[ "Gets", "the", "channel", "s", "value", "with", "the", "given", "key", "." ]
8b91f3e84c83f05d289c740d507293a0d6759d8e
https://github.com/danielperna84/pyhomematic/blob/8b91f3e84c83f05d289c740d507293a0d6759d8e/pyhomematic/devicetypes/generic.py#L254-L267
train
213,295
danielperna84/pyhomematic
pyhomematic/devicetypes/generic.py
HMDevice.UNREACH
def UNREACH(self): """ Returns true if the device or any children is not reachable """ if self._VALUES.get(PARAM_UNREACH, False): return True else: for device in self._hmchannels.values(): if device.UNREACH: return True return False
python
def UNREACH(self): """ Returns true if the device or any children is not reachable """ if self._VALUES.get(PARAM_UNREACH, False): return True else: for device in self._hmchannels.values(): if device.UNREACH: return True return False
[ "def", "UNREACH", "(", "self", ")", ":", "if", "self", ".", "_VALUES", ".", "get", "(", "PARAM_UNREACH", ",", "False", ")", ":", "return", "True", "else", ":", "for", "device", "in", "self", ".", "_hmchannels", ".", "values", "(", ")", ":", "if", "...
Returns true if the device or any children is not reachable
[ "Returns", "true", "if", "the", "device", "or", "any", "children", "is", "not", "reachable" ]
8b91f3e84c83f05d289c740d507293a0d6759d8e
https://github.com/danielperna84/pyhomematic/blob/8b91f3e84c83f05d289c740d507293a0d6759d8e/pyhomematic/devicetypes/generic.py#L270-L278
train
213,296
danielperna84/pyhomematic
pyhomematic/devicetypes/generic.py
HMDevice.getAttributeData
def getAttributeData(self, name, channel=None): """ Returns a attribut """ return self._getNodeData(name, self._ATTRIBUTENODE, channel)
python
def getAttributeData(self, name, channel=None): """ Returns a attribut """ return self._getNodeData(name, self._ATTRIBUTENODE, channel)
[ "def", "getAttributeData", "(", "self", ",", "name", ",", "channel", "=", "None", ")", ":", "return", "self", ".", "_getNodeData", "(", "name", ",", "self", ".", "_ATTRIBUTENODE", ",", "channel", ")" ]
Returns a attribut
[ "Returns", "a", "attribut" ]
8b91f3e84c83f05d289c740d507293a0d6759d8e
https://github.com/danielperna84/pyhomematic/blob/8b91f3e84c83f05d289c740d507293a0d6759d8e/pyhomematic/devicetypes/generic.py#L308-L310
train
213,297
danielperna84/pyhomematic
pyhomematic/devicetypes/generic.py
HMDevice.getBinaryData
def getBinaryData(self, name, channel=None): """ Returns a binary node """ return self._getNodeData(name, self._BINARYNODE, channel)
python
def getBinaryData(self, name, channel=None): """ Returns a binary node """ return self._getNodeData(name, self._BINARYNODE, channel)
[ "def", "getBinaryData", "(", "self", ",", "name", ",", "channel", "=", "None", ")", ":", "return", "self", ".", "_getNodeData", "(", "name", ",", "self", ".", "_BINARYNODE", ",", "channel", ")" ]
Returns a binary node
[ "Returns", "a", "binary", "node" ]
8b91f3e84c83f05d289c740d507293a0d6759d8e
https://github.com/danielperna84/pyhomematic/blob/8b91f3e84c83f05d289c740d507293a0d6759d8e/pyhomematic/devicetypes/generic.py#L312-L314
train
213,298
danielperna84/pyhomematic
pyhomematic/devicetypes/thermostats.py
HMThermostat.set_temperature
def set_temperature(self, target_temperature): """ Set the target temperature. """ try: target_temperature = float(target_temperature) except Exception as err: LOG.debug("Thermostat.set_temperature: Exception %s" % (err,)) return False self.writeNodeData("SET_TEMPERATURE", target_temperature)
python
def set_temperature(self, target_temperature): """ Set the target temperature. """ try: target_temperature = float(target_temperature) except Exception as err: LOG.debug("Thermostat.set_temperature: Exception %s" % (err,)) return False self.writeNodeData("SET_TEMPERATURE", target_temperature)
[ "def", "set_temperature", "(", "self", ",", "target_temperature", ")", ":", "try", ":", "target_temperature", "=", "float", "(", "target_temperature", ")", "except", "Exception", "as", "err", ":", "LOG", ".", "debug", "(", "\"Thermostat.set_temperature: Exception %s...
Set the target temperature.
[ "Set", "the", "target", "temperature", "." ]
8b91f3e84c83f05d289c740d507293a0d6759d8e
https://github.com/danielperna84/pyhomematic/blob/8b91f3e84c83f05d289c740d507293a0d6759d8e/pyhomematic/devicetypes/thermostats.py#L36-L43
train
213,299