code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
self.send(command + '\r')
return self.expect_prompt(consume) | def execute(self, command, consume=True) | Sends the given data to the remote host (with a newline appended)
and waits for a prompt in the response. The prompt attempts to use
a sane default that works with many devices running Unix, IOS,
IOS-XR, or Junos and others. If that fails, a custom prompt may
also be defined using the set_prompt() method.
This method also modifies the value of the response (self.response)
attribute, for details please see the documentation of the
expect() method.
:type command: string
:param command: The data that is sent to the remote host.
:type consume: boolean (Default: True)
:param consume: Whether to consume the prompt from the buffer or not.
:rtype: int, re.MatchObject
:return: The index of the prompt regular expression that matched,
and the match object. | 6.775596 | 7.865004 | 0.861487 |
while True:
try:
result = self._waitfor(prompt)
except DriverReplacedException:
continue # retry
return result | def waitfor(self, prompt) | Monitors the data received from the remote host and waits until
the response matches the given prompt.
Once a match has been found, the buffer containing incoming data
is NOT changed. In other words, consecutive calls to this function
will always work, e.g.::
conn.waitfor('myprompt>')
conn.waitfor('myprompt>')
conn.waitfor('myprompt>')
will always work. Hence in most cases, you probably want to use
expect() instead.
This method also stores the received data in the response
attribute (self.response).
Returns the index of the regular expression that matched.
:type prompt: str|re.RegexObject|list(str|re.RegexObject)
:param prompt: One or more regular expressions.
:rtype: int, re.MatchObject
:return: The index of the regular expression that matched,
and the match object.
@raise TimeoutException: raised if the timeout was reached.
@raise ExpectCancelledException: raised when cancel_expect() was
called in a callback.
@raise ProtocolException: on other internal errors.
@raise Exception: May raise other exceptions that are caused
within the underlying protocol implementations. | 8.165363 | 12.607833 | 0.647642 |
while True:
try:
result = self._expect(prompt)
except DriverReplacedException:
continue # retry
return result | def expect(self, prompt) | Like waitfor(), but also removes the matched string from the buffer
containing the incoming data. In other words, the following may not
alway complete::
conn.expect('myprompt>')
conn.expect('myprompt>') # timeout
Returns the index of the regular expression that matched.
.. HINT::
May raise the same exceptions as :class:`waitfor`.
:type prompt: str|re.RegexObject|list(str|re.RegexObject)
:param prompt: One or more regular expressions.
:rtype: int, re.MatchObject
:return: The index of the regular expression that matched,
and the match object. | 9.439586 | 12.758564 | 0.739863 |
if consume:
result = self.expect(self.get_prompt())
else:
self._dbg(1, "DO NOT CONSUME PROMPT!")
result = self.waitfor(self.get_prompt())
# We skip the first line because it contains the echo of the command
# sent.
self._dbg(5, "Checking %s for errors" % repr(self.response))
for line in self.response.split('\n')[1:]:
for prompt in self.get_error_prompt():
if not prompt.search(line):
continue
args = repr(prompt.pattern), repr(line)
self._dbg(5, "error prompt (%s) matches %s" % args)
raise InvalidCommandException('Device said:\n' + self.response)
return result | def expect_prompt(self, consume=True) | Monitors the data received from the remote host and waits for a
prompt in the response. The prompt attempts to use
a sane default that works with many devices running Unix, IOS,
IOS-XR, or Junos and others. If that fails, a custom prompt may
also be defined using the set_prompt() method.
This method also stores the received data in the response
attribute (self.response).
:type consume: boolean (Default: True)
:param consume: Whether to consume the prompt from the buffer or not.
:rtype: int, re.MatchObject
:return: The index of the prompt regular expression that matched,
and the match object. | 4.981421 | 4.74966 | 1.048795 |
self.buffer.add_monitor(pattern, partial(callback, self), limit) | 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. | 7.502758 | 11.239036 | 0.667562 |
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) | A decorator that unpacks the host and connection from the job argument
and passes them as separate arguments to the wrapped function. | 4.181403 | 4.110487 | 1.017252 |
child = _PipeHandler(self.account_manager)
self.pipe_handlers[id(child)] = child
child.start()
return child.to_parent | def _create_pipe(self) | Creates a new pipe and returns the child end of the connection.
To request an account from the pipe, use::
pipe = queue._create_pipe()
# Let the account manager choose an account.
pipe.send(('acquire-account-for-host', host))
account = pipe.recv()
...
pipe.send(('release-account', account.id()))
# Or acquire a specific account.
pipe.send(('acquire-account', account.id()))
account = pipe.recv()
...
pipe.send(('release-account', account.id()))
pipe.close() | 9.860322 | 6.454923 | 1.527566 |
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) | Waits until all jobs are completed. | 9.572633 | 7.923719 | 1.208098 |
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) | 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. | 7.842403 | 8.954217 | 0.875833 |
try:
if not force:
self.join()
finally:
self._dbg(2, 'Destroying queue...')
self.workqueue.destroy()
self.account_manager.reset()
self.completed = 0
self.total = 0
self.failed = 0
self.status_bar_length = 0
self._dbg(2, 'Queue destroyed.')
self._del_status_bar() | def destroy(self, force=False) | Like shutdown(), but also removes all accounts, hosts, etc., and
does not restart the queue. In other words, the queue can no longer
be used after calling this method.
:type force: bool
:param force: Whether to wait until all jobs were processed. | 5.747964 | 5.079363 | 1.131631 |
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) | Remove all accounts, hosts, etc. | 6.449563 | 5.710743 | 1.129374 |
return self._run(hosts, function, self.workqueue.enqueue, attempts) | def run(self, hosts, function, attempts=1) | Add the given function to a queue, and call it once for each host
according to the threading options.
Use decorators.bind() if you also want to pass additional
arguments to the callback function.
Returns an object that represents the queued task, and that may be
passed to is_completed() to check the status.
:type hosts: string|list(string)|Host|list(Host)
:param hosts: A hostname or Host object, or a list of them.
:type function: function
:param function: The function to execute.
:type attempts: int
:param attempts: The number of attempts on failure.
:rtype: object
:return: An object representing the task. | 9.894024 | 15.474791 | 0.639364 |
return self._run(hosts,
function,
self.workqueue.enqueue_or_ignore,
attempts) | def run_or_ignore(self, hosts, function, attempts=1) | Like run(), but only appends hosts that are not already in the
queue.
:type hosts: string|list(string)|Host|list(Host)
:param hosts: A hostname or Host object, or a list of them.
:type function: function
:param function: The function to execute.
:type attempts: int
:param attempts: The number of attempts on failure.
:rtype: object
:return: A task object, or None if all hosts were duplicates. | 7.514676 | 11.050659 | 0.680021 |
return self._run(hosts,
function,
self.workqueue.priority_enqueue,
False,
attempts) | def priority_run(self, hosts, function, attempts=1) | Like run(), but adds the task to the front of the queue.
:type hosts: string|list(string)|Host|list(Host)
:param hosts: A hostname or Host object, or a list of them.
:type function: function
:param function: The function to execute.
:type attempts: int
:param attempts: The number of attempts on failure.
:rtype: object
:return: An object representing the task. | 8.002048 | 12.264682 | 0.652446 |
return self._run(hosts,
function,
self.workqueue.priority_enqueue_or_raise,
False,
attempts) | def priority_run_or_raise(self, hosts, function, attempts=1) | Like priority_run(), but if a host is already in the queue, the
existing host is moved to the top of the queue instead of enqueuing
the new one.
:type hosts: string|list(string)|Host|list(Host)
:param hosts: A hostname or Host object, or a list of them.
:type function: function
:param function: The function to execute.
:type attempts: int
:param attempts: The number of attempts on failure.
:rtype: object
:return: A task object, or None if all hosts were duplicates. | 7.391005 | 9.285846 | 0.795943 |
return self._run(hosts,
function,
self.workqueue.priority_enqueue,
True,
attempts) | def force_run(self, hosts, function, attempts=1) | Like priority_run(), but starts the task immediately even if that
max_threads is exceeded.
:type hosts: string|list(string)|Host|list(Host)
:param hosts: A hostname or Host object, or a list of them.
:type function: function
:param function: The function to execute.
:type attempts: int
:param attempts: The number of attempts on failure.
:rtype: object
:return: An object representing the task. | 10.987137 | 12.598451 | 0.872102 |
self.total += 1
task = Task(self.workqueue)
job_id = self.workqueue.enqueue(function, name, attempts)
if job_id is not None:
task.add_job_id(job_id)
self._dbg(2, 'Function enqueued.')
return task | def enqueue(self, function, name=None, attempts=1) | Places the given function in the queue and calls it as soon
as a thread is available. To pass additional arguments to the
callback, use Python's functools.partial().
:type function: function
:param function: The function to execute.
:type name: string
:param name: A name for the task.
:type attempts: int
:param attempts: The number of attempts on failure.
:rtype: object
:return: An object representing the task. | 5.237683 | 5.69069 | 0.920395 |
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) | 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. | 3.499927 | 3.670142 | 0.953622 |
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) | Executes the given command locally.
:type command: string
:param command: A shell command. | 4.415292 | 5.5237 | 0.799336 |
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) | Defines the given value with the given confidence, unless the same
value is already defined with a higher confidence level. | 2.641137 | 2.420066 | 1.091349 |
for item in regex_list:
if hasattr(item, '__call__'):
self.set(key, *item(string))
else:
regex, value, confidence = item
if regex.search(string):
self.set(key, value, confidence) | def set_from_match(self, key, regex_list, string) | Given a list of functions or three-tuples (regex, value, confidence),
this function walks through them and checks whether any of the
items in the list matches the given string.
If the list item is a function, it must have the following
signature::
func(string) : (string, int)
Where the return value specifies the resulting value and the
confidence of the match.
If a match is found, and the confidence level is higher
than the currently defined one, the given value is defined with
the given confidence. | 3.149477 | 2.537163 | 1.241338 |
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) | Returns the info with the given key, if it has at least the given
confidence. Returns None otherwise. | 3.58077 | 2.85045 | 1.256212 |
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) | 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. | 3.723978 | 5.143423 | 0.724027 |
def decorated(job, host, conn, *args, **kwargs):
os = conn.guess_os()
func = map.get(os)
if func is None:
raise Exception('No handler for %s found.' % os)
return func(job, host, conn, *args, **kwargs)
return decorated | def os_function_mapper(map) | When called with an open connection, this function uses the
conn.guess_os() function to guess the operating system
of the connected host.
It then uses the given map to look up a function name that corresponds
to the operating system, and calls it. Example::
def ios_xr(job, host, conn):
pass # Do something.
def junos(job, host, conn):
pass # Do something else.
def shell(job, host, conn):
pass # Do something else.
Exscript.util.start.quickrun('myhost', os_function_mapper(globals()))
An exception is raised if a matching function is not found in the map.
:type conn: Exscript.protocols.Protocol
:param conn: The open connection.
:type map: dict
:param map: A dictionary mapping operating system name to a function.
:type args: list
:param args: Passed on to the called function.
:type kwargs: dict
:param kwargs: Passed on to the called function.
:rtype: object
:return: The return value of the called function. | 3.665 | 2.548639 | 1.438022 |
def decorator(function):
def decorated(job, host, conn, *args, **kwargs):
failed = 0
while True:
try:
if only_authenticate:
conn.authenticate(flush=flush)
else:
conn.login(flush=flush)
except LoginFailure as e:
failed += 1
if failed >= attempts:
raise
continue
break
return function(job, host, conn, *args, **kwargs)
copy_labels(function, decorated)
return decorated
return decorator | def _decorate(flush=True, attempts=1, only_authenticate=False) | Wraps the given function such that conn.login() or conn.authenticate() is
executed.
Doing the real work for autologin and autoauthenticate to minimize code
duplication.
:type flush: bool
:param flush: Whether to flush the last prompt from the buffer.
:type attempts: int
:param attempts: The number of login attempts if login fails.
:type only_authenticate: bool
:param only_authenticate: login or only authenticate (don't authorize)?
:rtype: function
:return: The wrapped function. | 3.068224 | 3.064545 | 1.001201 |
filenames = glob.glob('*[0-9][0-9][0-9]*{}'.format(extension))
return [ProblemFile(file) for file in filenames] | def problem_glob(extension='.py') | Returns ProblemFile objects for all valid problem files | 4.343687 | 3.432436 | 1.265482 |
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) | Formats the timespan in a human readable format | 2.603289 | 2.61454 | 0.995697 |
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) | Returns string with relevant time information formatted properly | 5.242653 | 5.214347 | 1.005428 |
return BASE_NAME.format(prefix, self.num, suffix, extension) | def filename(self, prefix='', suffix='', extension='.py') | Returns filename padded with leading zeros | 10.927979 | 10.288557 | 1.062149 |
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) | Returns a sorted glob of files belonging to a given problem | 8.391771 | 7.3434 | 1.142764 |
with open(os.path.join(EULER_DATA, 'resources.json')) as data_file:
data = json.load(data_file)
problem_num = str(self.num)
if problem_num in data:
files = data[problem_num]
# Ensure a list of files is returned
return files if isinstance(files, list) else [files]
else:
return None | def resources(self) | Returns a list of resources related to the problem (or None) | 4.069951 | 3.403391 | 1.195852 |
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) | Copies the relevant resources to a resources subdirectory | 2.80626 | 2.657732 | 1.055885 |
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) | Returns the answer to a given problem | 4.559518 | 4.305327 | 1.059041 |
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) | Parses problems.txt and returns problem text | 3.800548 | 3.511314 | 1.082372 |
# 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) | View the answer to a problem. | 9.456609 | 7.849786 | 1.204696 |
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([''])
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) | Generates Python file for a problem. | 4.349226 | 4.067303 | 1.069315 |
# 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) | Prints the text of a problem. | 10.785984 | 9.273178 | 1.163138 |
click.echo("Current problem is problem %i." % num)
generate(num + 1, prompt_default=False)
Problem(num).file.change_suffix('-skipped') | def skip(num) | Generates Python file for the next problem. | 25.898985 | 18.872099 | 1.372343 |
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) | Verifies the solution to a problem. | 4.279765 | 4.159884 | 1.028818 |
# 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) | Verifies all problem files in the current directory and
prints an overview of the status of each problem. | 4.330664 | 4.153478 | 1.04266 |
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) | Decorator to link CLI options with their appropriate functions | 7.534934 | 7.01301 | 1.074422 |
# 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) | Python-based Project Euler command line tool. | 8.068006 | 8.108301 | 0.99503 |
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) | Start the server thread if it wasn't created with autostart = True. | 3.129369 | 3.102875 | 1.008539 |
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) | Stop the server thread. | 3.643628 | 3.515683 | 1.036393 |
if self._server is not None:
return self._server.getSystemVariable(remote, name) | def getSystemVariable(self, remote, name) | Get single system variable from CCU / Homegear | 4.138834 | 4.165806 | 0.993525 |
if self._server is not None:
return self._server.deleteSystemVariable(remote, name) | def deleteSystemVariable(self, remote, name) | Delete a system variable from CCU / Homegear | 3.972191 | 4.452857 | 0.892054 |
if self._server is not None:
return self._server.setSystemVariable(remote, name, value) | def setSystemVariable(self, remote, name, value) | Set a system variable on CCU / Homegear | 3.509069 | 3.725778 | 0.941835 |
if self._server is not None:
return self._server.setInstallMode(remote, on, t, mode, address) | def setInstallMode(self, remote, on=True, t=60, mode=1, address=None) | Activate or deactivate installmode on CCU / Homegear | 3.139735 | 3.291096 | 0.954009 |
if self._server is not None:
return self._server.getAllMetadata(remote, address) | def getAllMetadata(self, remote, address) | Get all metadata of device | 4.428295 | 4.481161 | 0.988203 |
if self._server is not None:
# pylint: disable=E1121
return self._server.getAllMetadata(remote, address, key) | def getMetadata(self, remote, address, key) | Get metadata of device | 5.077655 | 4.935849 | 1.02873 |
if self._server is not None:
# pylint: disable=E1121
return self._server.getAllMetadata(remote, address, key, value) | def setMetadata(self, remote, address, key, value) | Set metadata of device | 5.166449 | 5.419097 | 0.953378 |
if self._server is not None:
# pylint: disable=E1121
return self._server.deleteMetadata(remote, address, key) | def deleteMetadata(self, remote, address, key) | Delete metadata of device | 3.974434 | 4.12992 | 0.962351 |
if self._server is not None:
return self._server.putParamset(remote, address, paramset, value) | def putParamset(self, remote, address, paramset, value) | Set paramsets manually | 3.017649 | 3.067502 | 0.983748 |
# 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) | 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. | 11.261121 | 9.967656 | 1.129766 |
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) | 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) | 6.699022 | 6.518687 | 1.027664 |
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 | Return the current color change program of the light. | 14.938404 | 10.391086 | 1.437617 |
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) | Sets the color change program of the light. | 6.481349 | 5.260895 | 1.231986 |
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) | Build auth part for api_url. | 3.958515 | 3.707673 | 1.067655 |
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'],
username=None,
password=None,
ssl=False) | Build API URL from components. | 3.044144 | 3.157381 | 0.964136 |
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) | Transform the raw device descriptions into instances of devicetypes.generic.HMDevice or availabe subclass. | 2.961842 | 2.898009 | 1.022026 |
LOG.debug("RPCFunctions.error: interface_id = %s, errorcode = %i, message = %s" % (
interface_id, int(errorcode), str(msg)))
if self.systemcallback:
self.systemcallback('error', interface_id, errorcode, msg)
return True | def error(self, interface_id, errorcode, msg) | When some error occurs the CCU / Homegear will send it's error message here | 4.288979 | 4.398615 | 0.975075 |
LOG.debug("RPCFunctions.saveDevices: devicefile: %s, _devices_raw: %s" % (
self.devicefile, str(self._devices_raw[remote])))
if self.devicefile:
try:
with open(self.devicefile, 'w') as df:
df.write(json.dumps(self._devices_raw[remote]))
return True
except Exception as err:
LOG.warning(
"RPCFunctions.saveDevices: Exception saving _devices_raw: %s", str(err))
return False
else:
return True | def saveDevices(self, remote) | We save known devices into a json-file so we don't have to work through the whole list of devices the CCU / Homegear presents us | 3.180217 | 3.168874 | 1.003579 |
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) | If a device emits some sort event, we will handle it here. | 3.266316 | 3.10838 | 1.05081 |
LOG.debug("RPCFunctions.listDevices: interface_id = %s, _devices_raw = %s" % (
interface_id, str(self._devices_raw)))
remote = interface_id.split('-')[-1]
if remote not in self._devices_raw:
self._devices_raw[remote] = []
if self.systemcallback:
self.systemcallback('listDevices', interface_id)
return self._devices_raw[remote] | def listDevices(self, interface_id) | The CCU / Homegear asks for devices known to our XML-RPC server. We respond to that request using this method. | 3.952434 | 3.937009 | 1.003918 |
LOG.debug("RPCFunctions.newDevices: interface_id = %s, dev_descriptions = %s" % (
interface_id, str(dev_descriptions)))
remote = interface_id.split('-')[-1]
if remote not in self._devices_raw:
self._devices_raw[remote] = []
if remote not in self._devices_raw_dict:
self._devices_raw_dict[remote] = {}
for d in dev_descriptions:
self._devices_raw[remote].append(d)
self._devices_raw_dict[remote][d['ADDRESS']] = d
self.saveDevices(remote)
self.createDeviceObjects(interface_id)
if self.systemcallback:
self.systemcallback('newDevices', interface_id, dev_descriptions)
return True | def newDevices(self, interface_id, dev_descriptions) | The CCU / Homegear informs us about newly added devices. We react on that and add those devices as well. | 2.93447 | 2.935207 | 0.999749 |
LOG.debug("RPCFunctions.deleteDevices: interface_id = %s, addresses = %s" % (
interface_id, str(addresses)))
# TODO: remove known device objects as well
remote = interface_id.split('-')[-1]
self._devices_raw[remote] = [device for device in self._devices_raw[
remote] if not device['ADDRESS'] in addresses]
self.saveDevices(remote)
if self.systemcallback:
self.systemcallback('deleteDevice', interface_id, addresses)
return True | def deleteDevices(self, interface_id, addresses) | The CCU / Homegear informs us about removed devices. We react on that and remove those devices as well. | 5.472089 | 5.320801 | 1.028433 |
with self.lock:
parent = xmlrpc.client.ServerProxy
# pylint: disable=E1101
return parent._ServerProxy__request(self, *args, **kwargs) | def __request(self, *args, **kwargs) | Call method on server side | 5.473078 | 5.087612 | 1.075766 |
# Call init() with local XML RPC config and interface_id (the name of
# the receiver) to receive events. XML RPC server has to be running.
for interface_id, proxy in self.proxies.items():
if proxy._skipinit:
continue
if proxy._callbackip and proxy._callbackport:
callbackip = proxy._callbackip
callbackport = proxy._callbackport
else:
callbackip = proxy._localip
callbackport = self._localport
LOG.debug("ServerThread.proxyInit: init('http://%s:%i', '%s')" %
(callbackip, callbackport, interface_id))
try:
proxy.init("http://%s:%i" %
(callbackip, callbackport), interface_id)
LOG.info("Proxy initialized")
except Exception as err:
LOG.debug("proxyInit: Exception: %s" % str(err))
LOG.warning("Failed to initialize proxy")
self.failed_inits.append(interface_id) | def proxyInit(self) | To receive events the proxy has to tell the CCU / Homegear where to send the events. For that we call the init-method. | 4.678587 | 4.490756 | 1.041826 |
stopped = []
for interface_id, proxy in self.proxies.items():
if interface_id in self.failed_inits:
LOG.warning("ServerThread.stop: Not performing de-init for %s" % interface_id)
continue
if proxy._callbackip and proxy._callbackport:
callbackip = proxy._callbackip
callbackport = proxy._callbackport
else:
callbackip = proxy._localip
callbackport = self._localport
remote = "http://%s:%i" % (callbackip, callbackport)
LOG.debug("ServerThread.stop: init('%s')" % remote)
if not callbackip in stopped:
try:
proxy.init(remote)
stopped.append(callbackip)
LOG.info("Proxy de-initialized: %s" % remote)
except Exception as err:
LOG.debug("proxyInit: Exception: %s" % str(err))
LOG.warning("Failed to de-initialize proxy")
self.proxies.clear()
LOG.info("Shutting down server")
self.server.shutdown()
LOG.debug("ServerThread.stop: Stopping ServerThread")
self.server.server_close()
LOG.info("Server stopped") | def stop(self) | To stop the server we de-init from the CCU / Homegear, then shut down our XML-RPC server. | 3.755166 | 3.48266 | 1.078247 |
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) | Helper to parse type of system variables of CCU | 2.365262 | 2.35002 | 1.006486 |
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) | Login to CCU and return session | 4.155441 | 4.068149 | 1.021457 |
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 of CCU | 5.520819 | 5.626939 | 0.981141 |
variables = {}
if self.remotes[remote]['username'] and self.remotes[remote]['password']:
LOG.debug(
"ServerThread.getAllSystemVariables: Getting all System variables via JSON-RPC")
session = self.jsonRpcLogin(remote)
if not session:
return
try:
params = {"_session_id_": session}
response = self._rpcfunctions.jsonRpcPost(
self.remotes[remote]['ip'], self.remotes[remote].get('jsonport', DEFAULT_JSONPORT), "SysVar.getAll", params)
if response['error'] is None and response['result']:
for var in response['result']:
key, value = self.parseCCUSysVar(var)
variables[key] = value
self.jsonRpcLogout(remote, session)
except Exception as err:
self.jsonRpcLogout(remote, session)
LOG.warning(
"ServerThread.getAllSystemVariables: Exception: %s" % str(err))
else:
try:
variables = self.proxies[
"%s-%s" % (self._interface_id, remote)].getAllSystemVariables()
except Exception as err:
LOG.debug(
"ServerThread.getAllSystemVariables: Exception: %s" % str(err))
return variables | def getAllSystemVariables(self, remote) | Get all system variables from CCU / Homegear | 3.944904 | 3.789227 | 1.041084 |
var = None
if self.remotes[remote]['username'] and self.remotes[remote]['password']:
LOG.debug(
"ServerThread.getSystemVariable: Getting System variable via JSON-RPC")
session = self.jsonRpcLogin(remote)
if not session:
return
try:
params = {"_session_id_": session, "name": name}
response = self._rpcfunctions.jsonRpcPost(
self.remotes[remote]['ip'], self.remotes[remote].get('jsonport', DEFAULT_JSONPORT), "SysVar.getValueByName", params)
if response['error'] is None and response['result']:
try:
var = float(response['result'])
except Exception as err:
var = response['result'] == 'true'
self.jsonRpcLogout(remote, session)
except Exception as err:
self.jsonRpcLogout(remote, session)
LOG.warning(
"ServerThread.getSystemVariable: Exception: %s" % str(err))
else:
try:
var = self.proxies[
"%s-%s" % (self._interface_id, remote)].getSystemVariable(name)
except Exception as err:
LOG.debug(
"ServerThread.getSystemVariable: Exception: %s" % str(err))
return var | def getSystemVariable(self, remote, name) | Get single system variable from CCU / Homegear | 3.807494 | 3.7867 | 1.005491 |
if self.remotes[remote]['username'] and self.remotes[remote]['password']:
LOG.debug(
"ServerThread.setSystemVariable: Setting System variable via JSON-RPC")
session = self.jsonRpcLogin(remote)
if not session:
return
try:
params = {"_session_id_": session,
"name": name, "value": value}
if value is True or value is False:
params['value'] = int(value)
response = self._rpcfunctions.jsonRpcPost(
self.remotes[remote]['ip'], self.remotes[remote].get('jsonport', DEFAULT_JSONPORT), "SysVar.setBool", params)
else:
response = self._rpcfunctions.jsonRpcPost(
self.remotes[remote]['ip'], self.remotes[remote].get('jsonport', DEFAULT_JSONPORT), "SysVar.setFloat", params)
if response['error'] is None and response['result']:
res = response['result']
LOG.debug(
"ServerThread.setSystemVariable: Result while setting variable: %s" % str(res))
else:
if response['error']:
LOG.debug("ServerThread.setSystemVariable: Error while setting variable: %s" % str(
response['error']))
self.jsonRpcLogout(remote, session)
except Exception as err:
self.jsonRpcLogout(remote, session)
LOG.warning(
"ServerThread.setSystemVariable: Exception: %s" % str(err))
else:
try:
return self.proxies["%s-%s" % (self._interface_id, remote)].setSystemVariable(name, value)
except Exception as err:
LOG.debug(
"ServerThread.setSystemVariable: Exception: %s" % str(err)) | def setSystemVariable(self, remote, name, value) | Set a system variable on CCU / Homegear | 2.865275 | 2.907077 | 0.985621 |
try:
return self.proxies["%s-%s" % (self._interface_id, remote)].getServiceMessages()
except Exception as err:
LOG.debug("ServerThread.getServiceMessages: Exception: %s" % str(err)) | def getServiceMessages(self, remote) | Get service messages from CCU / Homegear | 6.392394 | 6.555017 | 0.975191 |
try:
args = [on]
if on and t:
args.append(t)
if address:
args.append(address)
else:
args.append(mode)
return self.proxies["%s-%s" % (self._interface_id, remote)].setInstallMode(*args)
except Exception as err:
LOG.debug("ServerThread.setInstallMode: Exception: %s" % str(err)) | def setInstallMode(self, remote, on=True, t=60, mode=1, address=None) | Activate or deactivate installmode on CCU / Homegear | 4.585223 | 4.780379 | 0.959176 |
try:
return self.proxies["%s-%s" % (self._interface_id, remote)].getAllMetadata(address)
except Exception as err:
LOG.debug("ServerThread.getAllMetadata: Exception: %s" % str(err)) | def getAllMetadata(self, remote, address) | Get all metadata of device | 6.207148 | 6.506536 | 0.953986 |
try:
return self.proxies["%s-%s" % (self._interface_id, remote)].setMetadata(address, key, value)
except Exception as err:
LOG.debug("ServerThread.setMetadata: Exception: %s" % str(err)) | def setMetadata(self, remote, address, key, value) | Set metadata of device | 5.498408 | 5.874935 | 0.93591 |
try:
return self.proxies["%s-%s" % (self._interface_id, remote)].deleteMetadata(address, key)
except Exception as err:
LOG.debug("ServerThread.deleteMetadata: Exception: %s" % str(err)) | def deleteMetadata(self, remote, address, key) | Delete metadata of device | 5.929313 | 6.310308 | 0.939623 |
try:
self.proxies["%s-%s" % (self._interface_id, remote)].ping("%s-%s" % (self._interface_id, remote))
except Exception as err:
LOG.warning("ServerThread.ping: Exception: %s" % str(err)) | def ping(self, remote) | Send ping to CCU/Homegear to generate PONG event | 5.608125 | 5.210025 | 1.07641 |
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) | Check if proxy is still initialized | 5.187469 | 4.917534 | 1.054892 |
try:
return self.proxies["%s-%s" % (self._interface_id, remote)].putParamset(address, paramset, value)
except Exception as err:
LOG.debug("ServerThread.putParamset: Exception: %s" % str(err)) | def putParamset(self, remote, address, paramset, value) | Set paramsets manually | 4.864731 | 5.003531 | 0.97226 |
try:
onoff = bool(onoff)
except Exception as err:
LOG.debug("HelperActorState.set_state: Exception %s" % (err,))
return False
self.writeNodeData("STATE", onoff, channel) | def set_state(self, onoff, channel=None) | Turn state on/off | 7.944035 | 8.058569 | 0.985787 |
try:
position = float(position)
except Exception as err:
LOG.debug("HelperLevel.set_level: Exception %s" % (err,))
return False
self.writeNodeData("LEVEL", position, channel) | def set_level(self, position, channel=None) | Seek a specific value by specifying a float() from 0.0 to 1.0. | 7.84626 | 7.220794 | 1.08662 |
try:
position = float(position)
except Exception as err:
LOG.debug("HelperActorBlindTilt.set_level_2: Exception %s" % (err,))
return False
level = self.getWriteData("LEVEL", channel)
self.writeNodeData("LEVEL_2", position, channel)
# set level after level_2 to have level_2 updated
self.writeNodeData("LEVEL", level, channel) | def set_cover_tilt_position(self, position, channel=None) | Seek a specific value by specifying a float() from 0.0 to 1.0. | 9.309401 | 9.351502 | 0.995498 |
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) | Set duration th switch stays on when toggled. | 7.566016 | 7.166175 | 1.055796 |
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) | Handle the event received by server. | 4.243492 | 4.167161 | 1.018317 |
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) | Descriptions for paramsets are available to determine what can be don with the device. | 6.699501 | 6.003196 | 1.115989 |
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) | Devices should not update their own paramsets. They rely on the state of the server.
Hence we pull the specified paramset. | 4.430854 | 4.116646 | 1.076326 |
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) | Devices should update their own paramsets. They rely on the state of the server. Hence we pull all paramsets. | 5.681743 | 5.145294 | 1.10426 |
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={}) | 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. | 10.553376 | 9.943285 | 1.061357 |
try:
return self._VALUES[key]
except KeyError:
return self.getValue(key) | 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. | 4.722265 | 5.738872 | 0.822856 |
LOG.debug("HMGeneric.setValue: address = '%s', key = '%s' value = '%s'" % (self._ADDRESS, key, value))
try:
self._proxy.setValue(self._ADDRESS, key, value)
return True
except Exception as err:
LOG.error("HMGeneric.setValue: %s on %s Exception: %s", key,
self._ADDRESS, err)
return False | def setValue(self, key, value) | Some devices allow to directly set values to perform a specific task. | 4.456363 | 4.190911 | 1.06334 |
LOG.debug("HMGeneric.getValue: address = '%s', key = '%s'" % (self._ADDRESS, key))
try:
returnvalue = self._proxy.getValue(self._ADDRESS, key)
self._VALUES[key] = returnvalue
return returnvalue
except Exception as err:
LOG.warning("HMGeneric.getValue: %s on %s Exception: %s", key,
self._ADDRESS, err)
return False | def getValue(self, key) | Some devices allow to directly get values for specific parameters. | 5.257188 | 4.913586 | 1.069929 |
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) | 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. | 4.12174 | 4.625749 | 0.891043 |
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) | Returns true if the device or any children is not reachable | 8.679077 | 7.065465 | 1.22838 |
return self._getNodeData(name, self._ATTRIBUTENODE, channel) | def getAttributeData(self, name, channel=None) | Returns a attribut | 12.344096 | 14.206456 | 0.868907 |
return self._getNodeData(name, self._BINARYNODE, channel) | def getBinaryData(self, name, channel=None) | Returns a binary node | 13.230759 | 10.40585 | 1.271473 |
return self._getNodeData(name, self._SENSORNODE, channel) | def getSensorData(self, name, channel=None) | Returns a sensor node | 12.563524 | 11.555659 | 1.087218 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.