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
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
kstaniek/condoor
condoor/drivers/IOS.py
Driver.enable
def enable(self, enable_password): """Change to the privilege mode.""" if self.device.prompt[-1] == '#': self.log("Device is already in privileged mode") return events = [self.password_re, self.device.prompt_re, pexpect.TIMEOUT, pexpect.EOF] transitions = [ (self.password_re, [0], 1, partial(a_send_password, enable_password), 10), (self.password_re, [1], -1, ConnectionAuthenticationError("Incorrect enable password", self.device.hostname), 0), (self.device.prompt_re, [0, 1, 2, 3], -1, a_expected_prompt, 0), (pexpect.TIMEOUT, [0, 1, 2], -1, ConnectionAuthenticationError("Unable to get privileged mode", self.device.hostname), 0), (pexpect.EOF, [0, 1, 2], -1, ConnectionError("Device disconnected"), 0) ] self.device.ctrl.send_command(self.enable_cmd) fsm = FSM("IOS-ENABLE", self.device, events, transitions, timeout=10, max_transitions=5) fsm.run() if self.device.prompt[-1] != '#': raise ConnectionAuthenticationError("Privileged mode not set", self.device.hostname)
python
def enable(self, enable_password): """Change to the privilege mode.""" if self.device.prompt[-1] == '#': self.log("Device is already in privileged mode") return events = [self.password_re, self.device.prompt_re, pexpect.TIMEOUT, pexpect.EOF] transitions = [ (self.password_re, [0], 1, partial(a_send_password, enable_password), 10), (self.password_re, [1], -1, ConnectionAuthenticationError("Incorrect enable password", self.device.hostname), 0), (self.device.prompt_re, [0, 1, 2, 3], -1, a_expected_prompt, 0), (pexpect.TIMEOUT, [0, 1, 2], -1, ConnectionAuthenticationError("Unable to get privileged mode", self.device.hostname), 0), (pexpect.EOF, [0, 1, 2], -1, ConnectionError("Device disconnected"), 0) ] self.device.ctrl.send_command(self.enable_cmd) fsm = FSM("IOS-ENABLE", self.device, events, transitions, timeout=10, max_transitions=5) fsm.run() if self.device.prompt[-1] != '#': raise ConnectionAuthenticationError("Privileged mode not set", self.device.hostname)
[ "def", "enable", "(", "self", ",", "enable_password", ")", ":", "if", "self", ".", "device", ".", "prompt", "[", "-", "1", "]", "==", "'#'", ":", "self", ".", "log", "(", "\"Device is already in privileged mode\"", ")", "return", "events", "=", "[", "self", ".", "password_re", ",", "self", ".", "device", ".", "prompt_re", ",", "pexpect", ".", "TIMEOUT", ",", "pexpect", ".", "EOF", "]", "transitions", "=", "[", "(", "self", ".", "password_re", ",", "[", "0", "]", ",", "1", ",", "partial", "(", "a_send_password", ",", "enable_password", ")", ",", "10", ")", ",", "(", "self", ".", "password_re", ",", "[", "1", "]", ",", "-", "1", ",", "ConnectionAuthenticationError", "(", "\"Incorrect enable password\"", ",", "self", ".", "device", ".", "hostname", ")", ",", "0", ")", ",", "(", "self", ".", "device", ".", "prompt_re", ",", "[", "0", ",", "1", ",", "2", ",", "3", "]", ",", "-", "1", ",", "a_expected_prompt", ",", "0", ")", ",", "(", "pexpect", ".", "TIMEOUT", ",", "[", "0", ",", "1", ",", "2", "]", ",", "-", "1", ",", "ConnectionAuthenticationError", "(", "\"Unable to get privileged mode\"", ",", "self", ".", "device", ".", "hostname", ")", ",", "0", ")", ",", "(", "pexpect", ".", "EOF", ",", "[", "0", ",", "1", ",", "2", "]", ",", "-", "1", ",", "ConnectionError", "(", "\"Device disconnected\"", ")", ",", "0", ")", "]", "self", ".", "device", ".", "ctrl", ".", "send_command", "(", "self", ".", "enable_cmd", ")", "fsm", "=", "FSM", "(", "\"IOS-ENABLE\"", ",", "self", ".", "device", ",", "events", ",", "transitions", ",", "timeout", "=", "10", ",", "max_transitions", "=", "5", ")", "fsm", ".", "run", "(", ")", "if", "self", ".", "device", ".", "prompt", "[", "-", "1", "]", "!=", "'#'", ":", "raise", "ConnectionAuthenticationError", "(", "\"Privileged mode not set\"", ",", "self", ".", "device", ".", "hostname", ")" ]
Change to the privilege mode.
[ "Change", "to", "the", "privilege", "mode", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/drivers/IOS.py#L48-L68
train
OnroerendErfgoed/language-tags
language_tags/tags.py
tags.description
def description(tag): """ Gets a list of descriptions given the tag. :param str tag: (hyphen-separated) tag. :return: list of string descriptions. The return list can be empty. """ tag_object = Tag(tag) results = [] results.extend(tag_object.descriptions) subtags = tag_object.subtags for subtag in subtags: results += subtag.description return results
python
def description(tag): """ Gets a list of descriptions given the tag. :param str tag: (hyphen-separated) tag. :return: list of string descriptions. The return list can be empty. """ tag_object = Tag(tag) results = [] results.extend(tag_object.descriptions) subtags = tag_object.subtags for subtag in subtags: results += subtag.description return results
[ "def", "description", "(", "tag", ")", ":", "tag_object", "=", "Tag", "(", "tag", ")", "results", "=", "[", "]", "results", ".", "extend", "(", "tag_object", ".", "descriptions", ")", "subtags", "=", "tag_object", ".", "subtags", "for", "subtag", "in", "subtags", ":", "results", "+=", "subtag", ".", "description", "return", "results" ]
Gets a list of descriptions given the tag. :param str tag: (hyphen-separated) tag. :return: list of string descriptions. The return list can be empty.
[ "Gets", "a", "list", "of", "descriptions", "given", "the", "tag", "." ]
acb91e5458d22617f344e2eefaba9a9865373fdd
https://github.com/OnroerendErfgoed/language-tags/blob/acb91e5458d22617f344e2eefaba9a9865373fdd/language_tags/tags.py#L117-L131
train
bfarr/kombine
examples/twoD.py
Posterior.prior_draw
def prior_draw(self, N=1): """ Draw ``N`` samples from the prior. """ p = np.random.ranf(size=(N, self.ndim)) p = (self._upper_right - self._lower_left) * p + self._lower_left return p
python
def prior_draw(self, N=1): """ Draw ``N`` samples from the prior. """ p = np.random.ranf(size=(N, self.ndim)) p = (self._upper_right - self._lower_left) * p + self._lower_left return p
[ "def", "prior_draw", "(", "self", ",", "N", "=", "1", ")", ":", "p", "=", "np", ".", "random", ".", "ranf", "(", "size", "=", "(", "N", ",", "self", ".", "ndim", ")", ")", "p", "=", "(", "self", ".", "_upper_right", "-", "self", ".", "_lower_left", ")", "*", "p", "+", "self", ".", "_lower_left", "return", "p" ]
Draw ``N`` samples from the prior.
[ "Draw", "N", "samples", "from", "the", "prior", "." ]
50c946dee5da33e7baab71d9bd6c265ff02ffb13
https://github.com/bfarr/kombine/blob/50c946dee5da33e7baab71d9bd6c265ff02ffb13/examples/twoD.py#L49-L55
train
bfarr/kombine
examples/twoD.py
Posterior.lnprior
def lnprior(self, X): """ Use a uniform, bounded prior. """ if np.any(X < self._lower_left) or np.any(X > self._upper_right): return -np.inf else: return 0.0
python
def lnprior(self, X): """ Use a uniform, bounded prior. """ if np.any(X < self._lower_left) or np.any(X > self._upper_right): return -np.inf else: return 0.0
[ "def", "lnprior", "(", "self", ",", "X", ")", ":", "if", "np", ".", "any", "(", "X", "<", "self", ".", "_lower_left", ")", "or", "np", ".", "any", "(", "X", ">", "self", ".", "_upper_right", ")", ":", "return", "-", "np", ".", "inf", "else", ":", "return", "0.0" ]
Use a uniform, bounded prior.
[ "Use", "a", "uniform", "bounded", "prior", "." ]
50c946dee5da33e7baab71d9bd6c265ff02ffb13
https://github.com/bfarr/kombine/blob/50c946dee5da33e7baab71d9bd6c265ff02ffb13/examples/twoD.py#L57-L64
train
bfarr/kombine
examples/twoD.py
Posterior.lnlike
def lnlike(self, X): """ Use a softened version of the interpolant as a likelihood. """ return -3.5*np.log(self._interpolant(X[0], X[1], grid=False))
python
def lnlike(self, X): """ Use a softened version of the interpolant as a likelihood. """ return -3.5*np.log(self._interpolant(X[0], X[1], grid=False))
[ "def", "lnlike", "(", "self", ",", "X", ")", ":", "return", "-", "3.5", "*", "np", ".", "log", "(", "self", ".", "_interpolant", "(", "X", "[", "0", "]", ",", "X", "[", "1", "]", ",", "grid", "=", "False", ")", ")" ]
Use a softened version of the interpolant as a likelihood.
[ "Use", "a", "softened", "version", "of", "the", "interpolant", "as", "a", "likelihood", "." ]
50c946dee5da33e7baab71d9bd6c265ff02ffb13
https://github.com/bfarr/kombine/blob/50c946dee5da33e7baab71d9bd6c265ff02ffb13/examples/twoD.py#L66-L70
train
kstaniek/condoor
condoor/__main__.py
echo_info
def echo_info(conn): """Print detected information.""" click.echo("General information:") click.echo(" Hostname: {}".format(conn.hostname)) click.echo(" HW Family: {}".format(conn.family)) click.echo(" HW Platform: {}".format(conn.platform)) click.echo(" SW Type: {}".format(conn.os_type)) click.echo(" SW Version: {}".format(conn.os_version)) click.echo(" Prompt: {}".format(conn.prompt)) click.echo(" Console connection: {}".format(conn.is_console)) click.echo("\nUDI:") click.echo(" PID: {}".format(conn.pid)) click.echo(" Description: {}".format(conn.description)) click.echo(" Name: {}".format(conn.name)) click.echo(" SN: {}".format(conn.sn)) click.echo(" VID: {}".format(conn.vid))
python
def echo_info(conn): """Print detected information.""" click.echo("General information:") click.echo(" Hostname: {}".format(conn.hostname)) click.echo(" HW Family: {}".format(conn.family)) click.echo(" HW Platform: {}".format(conn.platform)) click.echo(" SW Type: {}".format(conn.os_type)) click.echo(" SW Version: {}".format(conn.os_version)) click.echo(" Prompt: {}".format(conn.prompt)) click.echo(" Console connection: {}".format(conn.is_console)) click.echo("\nUDI:") click.echo(" PID: {}".format(conn.pid)) click.echo(" Description: {}".format(conn.description)) click.echo(" Name: {}".format(conn.name)) click.echo(" SN: {}".format(conn.sn)) click.echo(" VID: {}".format(conn.vid))
[ "def", "echo_info", "(", "conn", ")", ":", "click", ".", "echo", "(", "\"General information:\"", ")", "click", ".", "echo", "(", "\" Hostname: {}\"", ".", "format", "(", "conn", ".", "hostname", ")", ")", "click", ".", "echo", "(", "\" HW Family: {}\"", ".", "format", "(", "conn", ".", "family", ")", ")", "click", ".", "echo", "(", "\" HW Platform: {}\"", ".", "format", "(", "conn", ".", "platform", ")", ")", "click", ".", "echo", "(", "\" SW Type: {}\"", ".", "format", "(", "conn", ".", "os_type", ")", ")", "click", ".", "echo", "(", "\" SW Version: {}\"", ".", "format", "(", "conn", ".", "os_version", ")", ")", "click", ".", "echo", "(", "\" Prompt: {}\"", ".", "format", "(", "conn", ".", "prompt", ")", ")", "click", ".", "echo", "(", "\" Console connection: {}\"", ".", "format", "(", "conn", ".", "is_console", ")", ")", "click", ".", "echo", "(", "\"\\nUDI:\"", ")", "click", ".", "echo", "(", "\" PID: {}\"", ".", "format", "(", "conn", ".", "pid", ")", ")", "click", ".", "echo", "(", "\" Description: {}\"", ".", "format", "(", "conn", ".", "description", ")", ")", "click", ".", "echo", "(", "\" Name: {}\"", ".", "format", "(", "conn", ".", "name", ")", ")", "click", ".", "echo", "(", "\" SN: {}\"", ".", "format", "(", "conn", ".", "sn", ")", ")", "click", ".", "echo", "(", "\" VID: {}\"", ".", "format", "(", "conn", ".", "vid", ")", ")" ]
Print detected information.
[ "Print", "detected", "information", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/__main__.py#L16-L32
train
kstaniek/condoor
condoor/__main__.py
run
def run(url, cmd, log_path, log_level, log_session, force_discovery, print_info): """Run the main function.""" log_level = log_levels[log_level] conn = condoor.Connection("host", list(url), log_session=log_session, log_level=log_level, log_dir=log_path) try: conn.connect(force_discovery=force_discovery) if print_info: echo_info(conn) for command in cmd: result = conn.send(command) print("\nCommand: {}".format(command)) print("Result: \n{}".format(result)) except (condoor.ConnectionError, condoor.ConnectionAuthenticationError, condoor.ConnectionTimeoutError, condoor.InvalidHopInfoError, condoor.CommandSyntaxError, condoor.CommandTimeoutError, condoor.CommandError, condoor.ConnectionError) as excpt: click.echo(excpt) finally: conn.disconnect() return
python
def run(url, cmd, log_path, log_level, log_session, force_discovery, print_info): """Run the main function.""" log_level = log_levels[log_level] conn = condoor.Connection("host", list(url), log_session=log_session, log_level=log_level, log_dir=log_path) try: conn.connect(force_discovery=force_discovery) if print_info: echo_info(conn) for command in cmd: result = conn.send(command) print("\nCommand: {}".format(command)) print("Result: \n{}".format(result)) except (condoor.ConnectionError, condoor.ConnectionAuthenticationError, condoor.ConnectionTimeoutError, condoor.InvalidHopInfoError, condoor.CommandSyntaxError, condoor.CommandTimeoutError, condoor.CommandError, condoor.ConnectionError) as excpt: click.echo(excpt) finally: conn.disconnect() return
[ "def", "run", "(", "url", ",", "cmd", ",", "log_path", ",", "log_level", ",", "log_session", ",", "force_discovery", ",", "print_info", ")", ":", "log_level", "=", "log_levels", "[", "log_level", "]", "conn", "=", "condoor", ".", "Connection", "(", "\"host\"", ",", "list", "(", "url", ")", ",", "log_session", "=", "log_session", ",", "log_level", "=", "log_level", ",", "log_dir", "=", "log_path", ")", "try", ":", "conn", ".", "connect", "(", "force_discovery", "=", "force_discovery", ")", "if", "print_info", ":", "echo_info", "(", "conn", ")", "for", "command", "in", "cmd", ":", "result", "=", "conn", ".", "send", "(", "command", ")", "print", "(", "\"\\nCommand: {}\"", ".", "format", "(", "command", ")", ")", "print", "(", "\"Result: \\n{}\"", ".", "format", "(", "result", ")", ")", "except", "(", "condoor", ".", "ConnectionError", ",", "condoor", ".", "ConnectionAuthenticationError", ",", "condoor", ".", "ConnectionTimeoutError", ",", "condoor", ".", "InvalidHopInfoError", ",", "condoor", ".", "CommandSyntaxError", ",", "condoor", ".", "CommandTimeoutError", ",", "condoor", ".", "CommandError", ",", "condoor", ".", "ConnectionError", ")", "as", "excpt", ":", "click", ".", "echo", "(", "excpt", ")", "finally", ":", "conn", ".", "disconnect", "(", ")", "return" ]
Run the main function.
[ "Run", "the", "main", "function", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/__main__.py#L77-L96
train
kstaniek/condoor
condoor/__main__.py
URL.convert
def convert(self, value, param, ctx): """Convert to URL scheme.""" if not isinstance(value, tuple): parsed = urlparse.urlparse(value) if parsed.scheme not in ('telnet', 'ssh'): self.fail('invalid URL scheme (%s). Only telnet and ssh URLs are ' 'allowed' % parsed, param, ctx) return value
python
def convert(self, value, param, ctx): """Convert to URL scheme.""" if not isinstance(value, tuple): parsed = urlparse.urlparse(value) if parsed.scheme not in ('telnet', 'ssh'): self.fail('invalid URL scheme (%s). Only telnet and ssh URLs are ' 'allowed' % parsed, param, ctx) return value
[ "def", "convert", "(", "self", ",", "value", ",", "param", ",", "ctx", ")", ":", "if", "not", "isinstance", "(", "value", ",", "tuple", ")", ":", "parsed", "=", "urlparse", ".", "urlparse", "(", "value", ")", "if", "parsed", ".", "scheme", "not", "in", "(", "'telnet'", ",", "'ssh'", ")", ":", "self", ".", "fail", "(", "'invalid URL scheme (%s). Only telnet and ssh URLs are '", "'allowed'", "%", "parsed", ",", "param", ",", "ctx", ")", "return", "value" ]
Convert to URL scheme.
[ "Convert", "to", "URL", "scheme", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/__main__.py#L40-L47
train
kstaniek/condoor
condoor/actions.py
a_send_line
def a_send_line(text, ctx): """Send text line to the controller followed by `os.linesep`.""" if hasattr(text, '__iter__'): try: ctx.ctrl.sendline(text.next()) except StopIteration: ctx.finished = True else: ctx.ctrl.sendline(text) return True
python
def a_send_line(text, ctx): """Send text line to the controller followed by `os.linesep`.""" if hasattr(text, '__iter__'): try: ctx.ctrl.sendline(text.next()) except StopIteration: ctx.finished = True else: ctx.ctrl.sendline(text) return True
[ "def", "a_send_line", "(", "text", ",", "ctx", ")", ":", "if", "hasattr", "(", "text", ",", "'__iter__'", ")", ":", "try", ":", "ctx", ".", "ctrl", ".", "sendline", "(", "text", ".", "next", "(", ")", ")", "except", "StopIteration", ":", "ctx", ".", "finished", "=", "True", "else", ":", "ctx", ".", "ctrl", ".", "sendline", "(", "text", ")", "return", "True" ]
Send text line to the controller followed by `os.linesep`.
[ "Send", "text", "line", "to", "the", "controller", "followed", "by", "os", ".", "linesep", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/actions.py#L9-L18
train
kstaniek/condoor
condoor/actions.py
a_send_username
def a_send_username(username, ctx): """Sent the username text.""" if username: ctx.ctrl.sendline(username) return True else: ctx.ctrl.disconnect() raise ConnectionAuthenticationError("Username not provided", ctx.ctrl.hostname)
python
def a_send_username(username, ctx): """Sent the username text.""" if username: ctx.ctrl.sendline(username) return True else: ctx.ctrl.disconnect() raise ConnectionAuthenticationError("Username not provided", ctx.ctrl.hostname)
[ "def", "a_send_username", "(", "username", ",", "ctx", ")", ":", "if", "username", ":", "ctx", ".", "ctrl", ".", "sendline", "(", "username", ")", "return", "True", "else", ":", "ctx", ".", "ctrl", ".", "disconnect", "(", ")", "raise", "ConnectionAuthenticationError", "(", "\"Username not provided\"", ",", "ctx", ".", "ctrl", ".", "hostname", ")" ]
Sent the username text.
[ "Sent", "the", "username", "text", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/actions.py#L29-L36
train
kstaniek/condoor
condoor/actions.py
a_send_password
def a_send_password(password, ctx): """Send the password text. Before sending the password local echo is disabled. If password not provided it disconnects from the device and raises ConnectionAuthenticationError exception. """ if password: ctx.ctrl.send_command(password, password=True) return True else: ctx.ctrl.disconnect() raise ConnectionAuthenticationError("Password not provided", ctx.ctrl.hostname)
python
def a_send_password(password, ctx): """Send the password text. Before sending the password local echo is disabled. If password not provided it disconnects from the device and raises ConnectionAuthenticationError exception. """ if password: ctx.ctrl.send_command(password, password=True) return True else: ctx.ctrl.disconnect() raise ConnectionAuthenticationError("Password not provided", ctx.ctrl.hostname)
[ "def", "a_send_password", "(", "password", ",", "ctx", ")", ":", "if", "password", ":", "ctx", ".", "ctrl", ".", "send_command", "(", "password", ",", "password", "=", "True", ")", "return", "True", "else", ":", "ctx", ".", "ctrl", ".", "disconnect", "(", ")", "raise", "ConnectionAuthenticationError", "(", "\"Password not provided\"", ",", "ctx", ".", "ctrl", ".", "hostname", ")" ]
Send the password text. Before sending the password local echo is disabled. If password not provided it disconnects from the device and raises ConnectionAuthenticationError exception.
[ "Send", "the", "password", "text", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/actions.py#L40-L51
train
kstaniek/condoor
condoor/actions.py
a_standby_console
def a_standby_console(ctx): """Raise ConnectionError exception when connected to standby console.""" ctx.device.is_console = True ctx.ctrl.disconnect() raise ConnectionError("Standby console", ctx.ctrl.hostname)
python
def a_standby_console(ctx): """Raise ConnectionError exception when connected to standby console.""" ctx.device.is_console = True ctx.ctrl.disconnect() raise ConnectionError("Standby console", ctx.ctrl.hostname)
[ "def", "a_standby_console", "(", "ctx", ")", ":", "ctx", ".", "device", ".", "is_console", "=", "True", "ctx", ".", "ctrl", ".", "disconnect", "(", ")", "raise", "ConnectionError", "(", "\"Standby console\"", ",", "ctx", ".", "ctrl", ".", "hostname", ")" ]
Raise ConnectionError exception when connected to standby console.
[ "Raise", "ConnectionError", "exception", "when", "connected", "to", "standby", "console", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/actions.py#L82-L86
train
kstaniek/condoor
condoor/actions.py
a_not_committed
def a_not_committed(ctx): """Provide the message that current software is not committed and reload is not possible.""" ctx.ctrl.sendline('n') ctx.msg = "Some active software packages are not yet committed. Reload may cause software rollback." ctx.device.chain.connection.emit_message(ctx.msg, log_level=logging.ERROR) ctx.failed = True return False
python
def a_not_committed(ctx): """Provide the message that current software is not committed and reload is not possible.""" ctx.ctrl.sendline('n') ctx.msg = "Some active software packages are not yet committed. Reload may cause software rollback." ctx.device.chain.connection.emit_message(ctx.msg, log_level=logging.ERROR) ctx.failed = True return False
[ "def", "a_not_committed", "(", "ctx", ")", ":", "ctx", ".", "ctrl", ".", "sendline", "(", "'n'", ")", "ctx", ".", "msg", "=", "\"Some active software packages are not yet committed. Reload may cause software rollback.\"", "ctx", ".", "device", ".", "chain", ".", "connection", ".", "emit_message", "(", "ctx", ".", "msg", ",", "log_level", "=", "logging", ".", "ERROR", ")", "ctx", ".", "failed", "=", "True", "return", "False" ]
Provide the message that current software is not committed and reload is not possible.
[ "Provide", "the", "message", "that", "current", "software", "is", "not", "committed", "and", "reload", "is", "not", "possible", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/actions.py#L107-L113
train
kstaniek/condoor
condoor/actions.py
a_stays_connected
def a_stays_connected(ctx): """Stay connected.""" ctx.ctrl.connected = True ctx.device.connected = False return True
python
def a_stays_connected(ctx): """Stay connected.""" ctx.ctrl.connected = True ctx.device.connected = False return True
[ "def", "a_stays_connected", "(", "ctx", ")", ":", "ctx", ".", "ctrl", ".", "connected", "=", "True", "ctx", ".", "device", ".", "connected", "=", "False", "return", "True" ]
Stay connected.
[ "Stay", "connected", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/actions.py#L126-L130
train
kstaniek/condoor
condoor/actions.py
a_unexpected_prompt
def a_unexpected_prompt(ctx): """Provide message when received humphost prompt.""" prompt = ctx.ctrl.match.group(0) ctx.msg = "Received the jump host prompt: '{}'".format(prompt) ctx.device.connected = False ctx.finished = True raise ConnectionError("Unable to connect to the device.", ctx.ctrl.hostname)
python
def a_unexpected_prompt(ctx): """Provide message when received humphost prompt.""" prompt = ctx.ctrl.match.group(0) ctx.msg = "Received the jump host prompt: '{}'".format(prompt) ctx.device.connected = False ctx.finished = True raise ConnectionError("Unable to connect to the device.", ctx.ctrl.hostname)
[ "def", "a_unexpected_prompt", "(", "ctx", ")", ":", "prompt", "=", "ctx", ".", "ctrl", ".", "match", ".", "group", "(", "0", ")", "ctx", ".", "msg", "=", "\"Received the jump host prompt: '{}'\"", ".", "format", "(", "prompt", ")", "ctx", ".", "device", ".", "connected", "=", "False", "ctx", ".", "finished", "=", "True", "raise", "ConnectionError", "(", "\"Unable to connect to the device.\"", ",", "ctx", ".", "ctrl", ".", "hostname", ")" ]
Provide message when received humphost prompt.
[ "Provide", "message", "when", "received", "humphost", "prompt", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/actions.py#L134-L140
train
kstaniek/condoor
condoor/actions.py
a_connection_timeout
def a_connection_timeout(ctx): """Check the prompt and update the drivers.""" prompt = ctx.ctrl.after ctx.msg = "Received the jump host prompt: '{}'".format(prompt) ctx.device.connected = False ctx.finished = True raise ConnectionTimeoutError("Unable to connect to the device.", ctx.ctrl.hostname)
python
def a_connection_timeout(ctx): """Check the prompt and update the drivers.""" prompt = ctx.ctrl.after ctx.msg = "Received the jump host prompt: '{}'".format(prompt) ctx.device.connected = False ctx.finished = True raise ConnectionTimeoutError("Unable to connect to the device.", ctx.ctrl.hostname)
[ "def", "a_connection_timeout", "(", "ctx", ")", ":", "prompt", "=", "ctx", ".", "ctrl", ".", "after", "ctx", ".", "msg", "=", "\"Received the jump host prompt: '{}'\"", ".", "format", "(", "prompt", ")", "ctx", ".", "device", ".", "connected", "=", "False", "ctx", ".", "finished", "=", "True", "raise", "ConnectionTimeoutError", "(", "\"Unable to connect to the device.\"", ",", "ctx", ".", "ctrl", ".", "hostname", ")" ]
Check the prompt and update the drivers.
[ "Check", "the", "prompt", "and", "update", "the", "drivers", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/actions.py#L144-L150
train
kstaniek/condoor
condoor/actions.py
a_expected_prompt
def a_expected_prompt(ctx): """Update driver, config mode and hostname when received an expected prompt.""" prompt = ctx.ctrl.match.group(0) ctx.device.update_driver(prompt) ctx.device.update_config_mode() ctx.device.update_hostname() ctx.finished = True return True
python
def a_expected_prompt(ctx): """Update driver, config mode and hostname when received an expected prompt.""" prompt = ctx.ctrl.match.group(0) ctx.device.update_driver(prompt) ctx.device.update_config_mode() ctx.device.update_hostname() ctx.finished = True return True
[ "def", "a_expected_prompt", "(", "ctx", ")", ":", "prompt", "=", "ctx", ".", "ctrl", ".", "match", ".", "group", "(", "0", ")", "ctx", ".", "device", ".", "update_driver", "(", "prompt", ")", "ctx", ".", "device", ".", "update_config_mode", "(", ")", "ctx", ".", "device", ".", "update_hostname", "(", ")", "ctx", ".", "finished", "=", "True", "return", "True" ]
Update driver, config mode and hostname when received an expected prompt.
[ "Update", "driver", "config", "mode", "and", "hostname", "when", "received", "an", "expected", "prompt", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/actions.py#L154-L161
train
kstaniek/condoor
condoor/actions.py
a_return_and_reconnect
def a_return_and_reconnect(ctx): """Send new line and reconnect.""" ctx.ctrl.send("\r") ctx.device.connect(ctx.ctrl) return True
python
def a_return_and_reconnect(ctx): """Send new line and reconnect.""" ctx.ctrl.send("\r") ctx.device.connect(ctx.ctrl) return True
[ "def", "a_return_and_reconnect", "(", "ctx", ")", ":", "ctx", ".", "ctrl", ".", "send", "(", "\"\\r\"", ")", "ctx", ".", "device", ".", "connect", "(", "ctx", ".", "ctrl", ")", "return", "True" ]
Send new line and reconnect.
[ "Send", "new", "line", "and", "reconnect", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/actions.py#L186-L190
train
kstaniek/condoor
condoor/actions.py
a_store_cmd_result
def a_store_cmd_result(ctx): """Store the command result for complex state machines. It is useful when exact command output is embedded in another commands, i.e. admin show inventory in eXR. """ result = ctx.ctrl.before # check if multi line index = result.find('\n') if index > 0: # remove first line result = result[index + 1:] ctx.device.last_command_result = result.replace('\r', '') return True
python
def a_store_cmd_result(ctx): """Store the command result for complex state machines. It is useful when exact command output is embedded in another commands, i.e. admin show inventory in eXR. """ result = ctx.ctrl.before # check if multi line index = result.find('\n') if index > 0: # remove first line result = result[index + 1:] ctx.device.last_command_result = result.replace('\r', '') return True
[ "def", "a_store_cmd_result", "(", "ctx", ")", ":", "result", "=", "ctx", ".", "ctrl", ".", "before", "# check if multi line", "index", "=", "result", ".", "find", "(", "'\\n'", ")", "if", "index", ">", "0", ":", "# remove first line", "result", "=", "result", "[", "index", "+", "1", ":", "]", "ctx", ".", "device", ".", "last_command_result", "=", "result", ".", "replace", "(", "'\\r'", ",", "''", ")", "return", "True" ]
Store the command result for complex state machines. It is useful when exact command output is embedded in another commands, i.e. admin show inventory in eXR.
[ "Store", "the", "command", "result", "for", "complex", "state", "machines", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/actions.py#L194-L206
train
kstaniek/condoor
condoor/actions.py
a_message_callback
def a_message_callback(ctx): """Message the captured pattern.""" message = ctx.ctrl.after.strip().splitlines()[-1] ctx.device.chain.connection.emit_message(message, log_level=logging.INFO) return True
python
def a_message_callback(ctx): """Message the captured pattern.""" message = ctx.ctrl.after.strip().splitlines()[-1] ctx.device.chain.connection.emit_message(message, log_level=logging.INFO) return True
[ "def", "a_message_callback", "(", "ctx", ")", ":", "message", "=", "ctx", ".", "ctrl", ".", "after", ".", "strip", "(", ")", ".", "splitlines", "(", ")", "[", "-", "1", "]", "ctx", ".", "device", ".", "chain", ".", "connection", ".", "emit_message", "(", "message", ",", "log_level", "=", "logging", ".", "INFO", ")", "return", "True" ]
Message the captured pattern.
[ "Message", "the", "captured", "pattern", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/actions.py#L210-L214
train
kstaniek/condoor
condoor/actions.py
a_capture_show_configuration_failed
def a_capture_show_configuration_failed(ctx): """Capture the show configuration failed result.""" result = ctx.device.send("show configuration failed") ctx.device.last_command_result = result index = result.find("SEMANTIC ERRORS") ctx.device.chain.connection.emit_message(result, log_level=logging.ERROR) if index > 0: raise ConfigurationSemanticErrors(result) else: raise ConfigurationErrors(result)
python
def a_capture_show_configuration_failed(ctx): """Capture the show configuration failed result.""" result = ctx.device.send("show configuration failed") ctx.device.last_command_result = result index = result.find("SEMANTIC ERRORS") ctx.device.chain.connection.emit_message(result, log_level=logging.ERROR) if index > 0: raise ConfigurationSemanticErrors(result) else: raise ConfigurationErrors(result)
[ "def", "a_capture_show_configuration_failed", "(", "ctx", ")", ":", "result", "=", "ctx", ".", "device", ".", "send", "(", "\"show configuration failed\"", ")", "ctx", ".", "device", ".", "last_command_result", "=", "result", "index", "=", "result", ".", "find", "(", "\"SEMANTIC ERRORS\"", ")", "ctx", ".", "device", ".", "chain", ".", "connection", ".", "emit_message", "(", "result", ",", "log_level", "=", "logging", ".", "ERROR", ")", "if", "index", ">", "0", ":", "raise", "ConfigurationSemanticErrors", "(", "result", ")", "else", ":", "raise", "ConfigurationErrors", "(", "result", ")" ]
Capture the show configuration failed result.
[ "Capture", "the", "show", "configuration", "failed", "result", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/actions.py#L218-L227
train
kstaniek/condoor
condoor/actions.py
a_configuration_inconsistency
def a_configuration_inconsistency(ctx): """Raise the configuration inconsistency error.""" ctx.msg = "This SDR's running configuration is inconsistent with persistent configuration. " \ "No configuration commits for this SDR will be allowed until a 'clear configuration inconsistency' " \ "command is performed." ctx.device.chain.connection.emit_message("Configuration inconsistency.", log_level=logging.ERROR) ctx.finished = True raise ConfigurationErrors("Configuration inconsistency.")
python
def a_configuration_inconsistency(ctx): """Raise the configuration inconsistency error.""" ctx.msg = "This SDR's running configuration is inconsistent with persistent configuration. " \ "No configuration commits for this SDR will be allowed until a 'clear configuration inconsistency' " \ "command is performed." ctx.device.chain.connection.emit_message("Configuration inconsistency.", log_level=logging.ERROR) ctx.finished = True raise ConfigurationErrors("Configuration inconsistency.")
[ "def", "a_configuration_inconsistency", "(", "ctx", ")", ":", "ctx", ".", "msg", "=", "\"This SDR's running configuration is inconsistent with persistent configuration. \"", "\"No configuration commits for this SDR will be allowed until a 'clear configuration inconsistency' \"", "\"command is performed.\"", "ctx", ".", "device", ".", "chain", ".", "connection", ".", "emit_message", "(", "\"Configuration inconsistency.\"", ",", "log_level", "=", "logging", ".", "ERROR", ")", "ctx", ".", "finished", "=", "True", "raise", "ConfigurationErrors", "(", "\"Configuration inconsistency.\"", ")" ]
Raise the configuration inconsistency error.
[ "Raise", "the", "configuration", "inconsistency", "error", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/actions.py#L231-L239
train
hwmrocker/smtplibaio
smtplibaio/smtp.py
SMTP.fqdn
def fqdn(self): """ Returns the string used to identify the client when initiating a SMTP session. RFC 5321 `§ 4.1.1.1`_ and `§ 4.1.3`_ tell us what to do: - Use the client FQDN ; - If it isn't available, we SHOULD fall back to an address literal. Returns: str: The value that should be used as the client FQDN. .. _`§ 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1 .. _`§ 4.1.3`: https//tools.ietf.org/html/rfc5321#section-4.1.3 """ if self._fqdn is None: # Let's try to retrieve it: self._fqdn = socket.getfqdn() if "." not in self._fqdn: try: info = socket.getaddrinfo( host="localhost", port=None, proto=socket.IPPROTO_TCP ) except socket.gaierror: addr = "127.0.0.1" else: # We only consider the first returned result and we're # only interested in getting the IP(v4 or v6) address: addr = info[0][4][0] self._fqdn = "[{}]".format(addr) return self._fqdn
python
def fqdn(self): """ Returns the string used to identify the client when initiating a SMTP session. RFC 5321 `§ 4.1.1.1`_ and `§ 4.1.3`_ tell us what to do: - Use the client FQDN ; - If it isn't available, we SHOULD fall back to an address literal. Returns: str: The value that should be used as the client FQDN. .. _`§ 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1 .. _`§ 4.1.3`: https//tools.ietf.org/html/rfc5321#section-4.1.3 """ if self._fqdn is None: # Let's try to retrieve it: self._fqdn = socket.getfqdn() if "." not in self._fqdn: try: info = socket.getaddrinfo( host="localhost", port=None, proto=socket.IPPROTO_TCP ) except socket.gaierror: addr = "127.0.0.1" else: # We only consider the first returned result and we're # only interested in getting the IP(v4 or v6) address: addr = info[0][4][0] self._fqdn = "[{}]".format(addr) return self._fqdn
[ "def", "fqdn", "(", "self", ")", ":", "if", "self", ".", "_fqdn", "is", "None", ":", "# Let's try to retrieve it:", "self", ".", "_fqdn", "=", "socket", ".", "getfqdn", "(", ")", "if", "\".\"", "not", "in", "self", ".", "_fqdn", ":", "try", ":", "info", "=", "socket", ".", "getaddrinfo", "(", "host", "=", "\"localhost\"", ",", "port", "=", "None", ",", "proto", "=", "socket", ".", "IPPROTO_TCP", ")", "except", "socket", ".", "gaierror", ":", "addr", "=", "\"127.0.0.1\"", "else", ":", "# We only consider the first returned result and we're", "# only interested in getting the IP(v4 or v6) address:", "addr", "=", "info", "[", "0", "]", "[", "4", "]", "[", "0", "]", "self", ".", "_fqdn", "=", "\"[{}]\"", ".", "format", "(", "addr", ")", "return", "self", ".", "_fqdn" ]
Returns the string used to identify the client when initiating a SMTP session. RFC 5321 `§ 4.1.1.1`_ and `§ 4.1.3`_ tell us what to do: - Use the client FQDN ; - If it isn't available, we SHOULD fall back to an address literal. Returns: str: The value that should be used as the client FQDN. .. _`§ 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1 .. _`§ 4.1.3`: https//tools.ietf.org/html/rfc5321#section-4.1.3
[ "Returns", "the", "string", "used", "to", "identify", "the", "client", "when", "initiating", "a", "SMTP", "session", "." ]
84ce8e45b7e706476739d0efcb416c18ecabbbb6
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L132-L166
train
hwmrocker/smtplibaio
smtplibaio/smtp.py
SMTP.reset_state
def reset_state(self): """ Resets some attributes to their default values. This is especially useful when initializing a newly created :class:`SMTP` instance and when closing an existing SMTP session. It allows us to use the same SMTP instance and connect several times. """ self.last_helo_response = (None, None) self.last_ehlo_response = (None, None) self.supports_esmtp = False self.esmtp_extensions = {} self.auth_mechanisms = [] self.ssl_context = False self.reader = None self.writer = None self.transport = None
python
def reset_state(self): """ Resets some attributes to their default values. This is especially useful when initializing a newly created :class:`SMTP` instance and when closing an existing SMTP session. It allows us to use the same SMTP instance and connect several times. """ self.last_helo_response = (None, None) self.last_ehlo_response = (None, None) self.supports_esmtp = False self.esmtp_extensions = {} self.auth_mechanisms = [] self.ssl_context = False self.reader = None self.writer = None self.transport = None
[ "def", "reset_state", "(", "self", ")", ":", "self", ".", "last_helo_response", "=", "(", "None", ",", "None", ")", "self", ".", "last_ehlo_response", "=", "(", "None", ",", "None", ")", "self", ".", "supports_esmtp", "=", "False", "self", ".", "esmtp_extensions", "=", "{", "}", "self", ".", "auth_mechanisms", "=", "[", "]", "self", ".", "ssl_context", "=", "False", "self", ".", "reader", "=", "None", "self", ".", "writer", "=", "None", "self", ".", "transport", "=", "None" ]
Resets some attributes to their default values. This is especially useful when initializing a newly created :class:`SMTP` instance and when closing an existing SMTP session. It allows us to use the same SMTP instance and connect several times.
[ "Resets", "some", "attributes", "to", "their", "default", "values", "." ]
84ce8e45b7e706476739d0efcb416c18ecabbbb6
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L168-L189
train
hwmrocker/smtplibaio
smtplibaio/smtp.py
SMTP.helo
async def helo(self, from_host=None): """ Sends a SMTP 'HELO' command. - Identifies the client and starts the session. If given ``from_host`` is None, defaults to the client FQDN. For further details, please check out `RFC 5321 § 4.1.1.1`_. Args: from_host (str or None): Name to use to identify the client. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our HELO greeting. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1 """ if from_host is None: from_host = self.fqdn code, message = await self.do_cmd("HELO", from_host) self.last_helo_response = (code, message) return code, message
python
async def helo(self, from_host=None): """ Sends a SMTP 'HELO' command. - Identifies the client and starts the session. If given ``from_host`` is None, defaults to the client FQDN. For further details, please check out `RFC 5321 § 4.1.1.1`_. Args: from_host (str or None): Name to use to identify the client. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our HELO greeting. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1 """ if from_host is None: from_host = self.fqdn code, message = await self.do_cmd("HELO", from_host) self.last_helo_response = (code, message) return code, message
[ "async", "def", "helo", "(", "self", ",", "from_host", "=", "None", ")", ":", "if", "from_host", "is", "None", ":", "from_host", "=", "self", ".", "fqdn", "code", ",", "message", "=", "await", "self", ".", "do_cmd", "(", "\"HELO\"", ",", "from_host", ")", "self", ".", "last_helo_response", "=", "(", "code", ",", "message", ")", "return", "code", ",", "message" ]
Sends a SMTP 'HELO' command. - Identifies the client and starts the session. If given ``from_host`` is None, defaults to the client FQDN. For further details, please check out `RFC 5321 § 4.1.1.1`_. Args: from_host (str or None): Name to use to identify the client. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our HELO greeting. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1
[ "Sends", "a", "SMTP", "HELO", "command", ".", "-", "Identifies", "the", "client", "and", "starts", "the", "session", "." ]
84ce8e45b7e706476739d0efcb416c18ecabbbb6
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L308-L338
train
hwmrocker/smtplibaio
smtplibaio/smtp.py
SMTP.ehlo
async def ehlo(self, from_host=None): """ Sends a SMTP 'EHLO' command. - Identifies the client and starts the session. If given ``from`_host`` is None, defaults to the client FQDN. For further details, please check out `RFC 5321 § 4.1.1.1`_. Args: from_host (str or None): Name to use to identify the client. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO greeting. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1 """ if from_host is None: from_host = self.fqdn code, message = await self.do_cmd("EHLO", from_host) self.last_ehlo_response = (code, message) extns, auths = SMTP.parse_esmtp_extensions(message) self.esmtp_extensions = extns self.auth_mechanisms = auths self.supports_esmtp = True return code, message
python
async def ehlo(self, from_host=None): """ Sends a SMTP 'EHLO' command. - Identifies the client and starts the session. If given ``from`_host`` is None, defaults to the client FQDN. For further details, please check out `RFC 5321 § 4.1.1.1`_. Args: from_host (str or None): Name to use to identify the client. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO greeting. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1 """ if from_host is None: from_host = self.fqdn code, message = await self.do_cmd("EHLO", from_host) self.last_ehlo_response = (code, message) extns, auths = SMTP.parse_esmtp_extensions(message) self.esmtp_extensions = extns self.auth_mechanisms = auths self.supports_esmtp = True return code, message
[ "async", "def", "ehlo", "(", "self", ",", "from_host", "=", "None", ")", ":", "if", "from_host", "is", "None", ":", "from_host", "=", "self", ".", "fqdn", "code", ",", "message", "=", "await", "self", ".", "do_cmd", "(", "\"EHLO\"", ",", "from_host", ")", "self", ".", "last_ehlo_response", "=", "(", "code", ",", "message", ")", "extns", ",", "auths", "=", "SMTP", ".", "parse_esmtp_extensions", "(", "message", ")", "self", ".", "esmtp_extensions", "=", "extns", "self", ".", "auth_mechanisms", "=", "auths", "self", ".", "supports_esmtp", "=", "True", "return", "code", ",", "message" ]
Sends a SMTP 'EHLO' command. - Identifies the client and starts the session. If given ``from`_host`` is None, defaults to the client FQDN. For further details, please check out `RFC 5321 § 4.1.1.1`_. Args: from_host (str or None): Name to use to identify the client. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO greeting. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1
[ "Sends", "a", "SMTP", "EHLO", "command", ".", "-", "Identifies", "the", "client", "and", "starts", "the", "session", "." ]
84ce8e45b7e706476739d0efcb416c18ecabbbb6
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L340-L375
train
hwmrocker/smtplibaio
smtplibaio/smtp.py
SMTP.help
async def help(self, command_name=None): """ Sends a SMTP 'HELP' command. For further details please check out `RFC 5321 § 4.1.1.8`_. Args: command_name (str or None, optional): Name of a command for which you want help. For example, if you want to get help about the '*RSET*' command, you'd call ``help('RSET')``. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the HELP command fails. Returns: Help text as given by the server. .. _`RFC 5321 § 4.1.1.8`: https://tools.ietf.org/html/rfc5321#section-4.1.1.8 """ if command_name is None: command_name = "" code, message = await self.do_cmd("HELP", command_name) return message
python
async def help(self, command_name=None): """ Sends a SMTP 'HELP' command. For further details please check out `RFC 5321 § 4.1.1.8`_. Args: command_name (str or None, optional): Name of a command for which you want help. For example, if you want to get help about the '*RSET*' command, you'd call ``help('RSET')``. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the HELP command fails. Returns: Help text as given by the server. .. _`RFC 5321 § 4.1.1.8`: https://tools.ietf.org/html/rfc5321#section-4.1.1.8 """ if command_name is None: command_name = "" code, message = await self.do_cmd("HELP", command_name) return message
[ "async", "def", "help", "(", "self", ",", "command_name", "=", "None", ")", ":", "if", "command_name", "is", "None", ":", "command_name", "=", "\"\"", "code", ",", "message", "=", "await", "self", ".", "do_cmd", "(", "\"HELP\"", ",", "command_name", ")", "return", "message" ]
Sends a SMTP 'HELP' command. For further details please check out `RFC 5321 § 4.1.1.8`_. Args: command_name (str or None, optional): Name of a command for which you want help. For example, if you want to get help about the '*RSET*' command, you'd call ``help('RSET')``. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the HELP command fails. Returns: Help text as given by the server. .. _`RFC 5321 § 4.1.1.8`: https://tools.ietf.org/html/rfc5321#section-4.1.1.8
[ "Sends", "a", "SMTP", "HELP", "command", "." ]
84ce8e45b7e706476739d0efcb416c18ecabbbb6
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L377-L403
train
hwmrocker/smtplibaio
smtplibaio/smtp.py
SMTP.mail
async def mail(self, sender, options=None): """ Sends a SMTP 'MAIL' command. - Starts the mail transfer session. For further details, please check out `RFC 5321 § 4.1.1.2`_ and `§ 3.3`_. Args: sender (str): Sender mailbox (used as reverse-path). options (list of str or None, optional): Additional options to send along with the *MAIL* command. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the MAIL command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.2`: https://tools.ietf.org/html/rfc5321#section-4.1.1.2 .. _`§ 3.3`: https://tools.ietf.org/html/rfc5321#section-3.3 """ if options is None: options = [] from_addr = "FROM:{}".format(quoteaddr(sender)) code, message = await self.do_cmd("MAIL", from_addr, *options) return code, message
python
async def mail(self, sender, options=None): """ Sends a SMTP 'MAIL' command. - Starts the mail transfer session. For further details, please check out `RFC 5321 § 4.1.1.2`_ and `§ 3.3`_. Args: sender (str): Sender mailbox (used as reverse-path). options (list of str or None, optional): Additional options to send along with the *MAIL* command. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the MAIL command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.2`: https://tools.ietf.org/html/rfc5321#section-4.1.1.2 .. _`§ 3.3`: https://tools.ietf.org/html/rfc5321#section-3.3 """ if options is None: options = [] from_addr = "FROM:{}".format(quoteaddr(sender)) code, message = await self.do_cmd("MAIL", from_addr, *options) return code, message
[ "async", "def", "mail", "(", "self", ",", "sender", ",", "options", "=", "None", ")", ":", "if", "options", "is", "None", ":", "options", "=", "[", "]", "from_addr", "=", "\"FROM:{}\"", ".", "format", "(", "quoteaddr", "(", "sender", ")", ")", "code", ",", "message", "=", "await", "self", ".", "do_cmd", "(", "\"MAIL\"", ",", "from_addr", ",", "*", "options", ")", "return", "code", ",", "message" ]
Sends a SMTP 'MAIL' command. - Starts the mail transfer session. For further details, please check out `RFC 5321 § 4.1.1.2`_ and `§ 3.3`_. Args: sender (str): Sender mailbox (used as reverse-path). options (list of str or None, optional): Additional options to send along with the *MAIL* command. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the MAIL command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.2`: https://tools.ietf.org/html/rfc5321#section-4.1.1.2 .. _`§ 3.3`: https://tools.ietf.org/html/rfc5321#section-3.3
[ "Sends", "a", "SMTP", "MAIL", "command", ".", "-", "Starts", "the", "mail", "transfer", "session", "." ]
84ce8e45b7e706476739d0efcb416c18ecabbbb6
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L487-L517
train
hwmrocker/smtplibaio
smtplibaio/smtp.py
SMTP.rcpt
async def rcpt(self, recipient, options=None): """ Sends a SMTP 'RCPT' command. - Indicates a recipient for the e-mail. For further details, please check out `RFC 5321 § 4.1.1.3`_ and `§ 3.3`_. Args: recipient (str): E-mail address of one recipient. options (list of str or None, optional): Additional options to send along with the *RCPT* command. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the RCPT command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.3`: https://tools.ietf.org/html/rfc5321#section-4.1.1.3 .. _`§ 3.3`: https://tools.ietf.org/html/rfc5321#section-3.3 """ if options is None: options = [] to_addr = "TO:{}".format(quoteaddr(recipient)) code, message = await self.do_cmd("RCPT", to_addr, *options) return code, message
python
async def rcpt(self, recipient, options=None): """ Sends a SMTP 'RCPT' command. - Indicates a recipient for the e-mail. For further details, please check out `RFC 5321 § 4.1.1.3`_ and `§ 3.3`_. Args: recipient (str): E-mail address of one recipient. options (list of str or None, optional): Additional options to send along with the *RCPT* command. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the RCPT command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.3`: https://tools.ietf.org/html/rfc5321#section-4.1.1.3 .. _`§ 3.3`: https://tools.ietf.org/html/rfc5321#section-3.3 """ if options is None: options = [] to_addr = "TO:{}".format(quoteaddr(recipient)) code, message = await self.do_cmd("RCPT", to_addr, *options) return code, message
[ "async", "def", "rcpt", "(", "self", ",", "recipient", ",", "options", "=", "None", ")", ":", "if", "options", "is", "None", ":", "options", "=", "[", "]", "to_addr", "=", "\"TO:{}\"", ".", "format", "(", "quoteaddr", "(", "recipient", ")", ")", "code", ",", "message", "=", "await", "self", ".", "do_cmd", "(", "\"RCPT\"", ",", "to_addr", ",", "*", "options", ")", "return", "code", ",", "message" ]
Sends a SMTP 'RCPT' command. - Indicates a recipient for the e-mail. For further details, please check out `RFC 5321 § 4.1.1.3`_ and `§ 3.3`_. Args: recipient (str): E-mail address of one recipient. options (list of str or None, optional): Additional options to send along with the *RCPT* command. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the RCPT command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.3`: https://tools.ietf.org/html/rfc5321#section-4.1.1.3 .. _`§ 3.3`: https://tools.ietf.org/html/rfc5321#section-3.3
[ "Sends", "a", "SMTP", "RCPT", "command", ".", "-", "Indicates", "a", "recipient", "for", "the", "e", "-", "mail", "." ]
84ce8e45b7e706476739d0efcb416c18ecabbbb6
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L519-L549
train
hwmrocker/smtplibaio
smtplibaio/smtp.py
SMTP.quit
async def quit(self): """ Sends a SMTP 'QUIT' command. - Ends the session. For further details, please check out `RFC 5321 § 4.1.1.10`_. Returns: (int, str): A (code, message) 2-tuple containing the server response. If the connection is already closed when calling this method, returns (-1, None). .. _`RFC 5321 § 4.1.1.10`: https://tools.ietf.org/html/rfc5321#section-4.1.1.10 """ code = -1 message = None try: code, message = await self.do_cmd("QUIT") except ConnectionError: # We voluntarily ignore this kind of exceptions since... the # connection seems already closed. pass except SMTPCommandFailedError: pass await self.close() return code, message
python
async def quit(self): """ Sends a SMTP 'QUIT' command. - Ends the session. For further details, please check out `RFC 5321 § 4.1.1.10`_. Returns: (int, str): A (code, message) 2-tuple containing the server response. If the connection is already closed when calling this method, returns (-1, None). .. _`RFC 5321 § 4.1.1.10`: https://tools.ietf.org/html/rfc5321#section-4.1.1.10 """ code = -1 message = None try: code, message = await self.do_cmd("QUIT") except ConnectionError: # We voluntarily ignore this kind of exceptions since... the # connection seems already closed. pass except SMTPCommandFailedError: pass await self.close() return code, message
[ "async", "def", "quit", "(", "self", ")", ":", "code", "=", "-", "1", "message", "=", "None", "try", ":", "code", ",", "message", "=", "await", "self", ".", "do_cmd", "(", "\"QUIT\"", ")", "except", "ConnectionError", ":", "# We voluntarily ignore this kind of exceptions since... the", "# connection seems already closed.", "pass", "except", "SMTPCommandFailedError", ":", "pass", "await", "self", ".", "close", "(", ")", "return", "code", ",", "message" ]
Sends a SMTP 'QUIT' command. - Ends the session. For further details, please check out `RFC 5321 § 4.1.1.10`_. Returns: (int, str): A (code, message) 2-tuple containing the server response. If the connection is already closed when calling this method, returns (-1, None). .. _`RFC 5321 § 4.1.1.10`: https://tools.ietf.org/html/rfc5321#section-4.1.1.10
[ "Sends", "a", "SMTP", "QUIT", "command", ".", "-", "Ends", "the", "session", "." ]
84ce8e45b7e706476739d0efcb416c18ecabbbb6
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L551-L578
train
hwmrocker/smtplibaio
smtplibaio/smtp.py
SMTP.data
async def data(self, email_message): """ Sends a SMTP 'DATA' command. - Transmits the message to the server. If ``email_message`` is a bytes object, sends it as it is. Else, makes all the required changes so it can be safely trasmitted to the SMTP server.` For further details, please check out `RFC 5321 § 4.1.1.4`_. Args: email_message (str or bytes): Message to be sent. Raises: ConnectionError subclass: If the connection to the server is unexpectedely lost. SMTPCommandFailedError: If the DATA command fails. Returns: (int, str): A (code, message) 2-tuple containing the server last response (the one the server sent after all data were sent by the client). .. seealso: :meth:`SMTP.prepare_message` .. _`RFC 5321 § 4.1.1.4`: https://tools.ietf.org/html/rfc5321#section-4.1.1.4 """ code, message = await self.do_cmd("DATA", success=(354,)) email_message = SMTP.prepare_message(email_message) self.writer.write(email_message) # write is non-blocking. await self.writer.drain() # don't forget to drain. code, message = await self.reader.read_reply() return code, message
python
async def data(self, email_message): """ Sends a SMTP 'DATA' command. - Transmits the message to the server. If ``email_message`` is a bytes object, sends it as it is. Else, makes all the required changes so it can be safely trasmitted to the SMTP server.` For further details, please check out `RFC 5321 § 4.1.1.4`_. Args: email_message (str or bytes): Message to be sent. Raises: ConnectionError subclass: If the connection to the server is unexpectedely lost. SMTPCommandFailedError: If the DATA command fails. Returns: (int, str): A (code, message) 2-tuple containing the server last response (the one the server sent after all data were sent by the client). .. seealso: :meth:`SMTP.prepare_message` .. _`RFC 5321 § 4.1.1.4`: https://tools.ietf.org/html/rfc5321#section-4.1.1.4 """ code, message = await self.do_cmd("DATA", success=(354,)) email_message = SMTP.prepare_message(email_message) self.writer.write(email_message) # write is non-blocking. await self.writer.drain() # don't forget to drain. code, message = await self.reader.read_reply() return code, message
[ "async", "def", "data", "(", "self", ",", "email_message", ")", ":", "code", ",", "message", "=", "await", "self", ".", "do_cmd", "(", "\"DATA\"", ",", "success", "=", "(", "354", ",", ")", ")", "email_message", "=", "SMTP", ".", "prepare_message", "(", "email_message", ")", "self", ".", "writer", ".", "write", "(", "email_message", ")", "# write is non-blocking.", "await", "self", ".", "writer", ".", "drain", "(", ")", "# don't forget to drain.", "code", ",", "message", "=", "await", "self", ".", "reader", ".", "read_reply", "(", ")", "return", "code", ",", "message" ]
Sends a SMTP 'DATA' command. - Transmits the message to the server. If ``email_message`` is a bytes object, sends it as it is. Else, makes all the required changes so it can be safely trasmitted to the SMTP server.` For further details, please check out `RFC 5321 § 4.1.1.4`_. Args: email_message (str or bytes): Message to be sent. Raises: ConnectionError subclass: If the connection to the server is unexpectedely lost. SMTPCommandFailedError: If the DATA command fails. Returns: (int, str): A (code, message) 2-tuple containing the server last response (the one the server sent after all data were sent by the client). .. seealso: :meth:`SMTP.prepare_message` .. _`RFC 5321 § 4.1.1.4`: https://tools.ietf.org/html/rfc5321#section-4.1.1.4
[ "Sends", "a", "SMTP", "DATA", "command", ".", "-", "Transmits", "the", "message", "to", "the", "server", "." ]
84ce8e45b7e706476739d0efcb416c18ecabbbb6
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L580-L616
train
hwmrocker/smtplibaio
smtplibaio/smtp.py
SMTP.auth
async def auth(self, username, password): """ Tries to authenticate user against the SMTP server. Args: username (str): Username to authenticate with. password (str): Password to use along with the given ``username``. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. SMTPLoginError: If the authentication failed (either because all attempts failed or because there was no suitable authentication mechanism). Returns: (int, str): A (code, message) 2-tuple containing the last server response. """ # EHLO/HELO is required: await self.ehlo_or_helo_if_needed() errors = [] # To store SMTPAuthenticationErrors code = message = None # Try to authenticate using all mechanisms supported by both # server and client (and only these): for auth, meth in self.__class__._supported_auth_mechanisms.items(): if auth in self.auth_mechanisms: auth_func = getattr(self, meth) try: code, message = await auth_func(username, password) except SMTPAuthenticationError as e: errors.append(e) else: break else: if not errors: err = "Could not find any suitable authentication mechanism." errors.append(SMTPAuthenticationError(-1, err)) raise SMTPLoginError(errors) return code, message
python
async def auth(self, username, password): """ Tries to authenticate user against the SMTP server. Args: username (str): Username to authenticate with. password (str): Password to use along with the given ``username``. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. SMTPLoginError: If the authentication failed (either because all attempts failed or because there was no suitable authentication mechanism). Returns: (int, str): A (code, message) 2-tuple containing the last server response. """ # EHLO/HELO is required: await self.ehlo_or_helo_if_needed() errors = [] # To store SMTPAuthenticationErrors code = message = None # Try to authenticate using all mechanisms supported by both # server and client (and only these): for auth, meth in self.__class__._supported_auth_mechanisms.items(): if auth in self.auth_mechanisms: auth_func = getattr(self, meth) try: code, message = await auth_func(username, password) except SMTPAuthenticationError as e: errors.append(e) else: break else: if not errors: err = "Could not find any suitable authentication mechanism." errors.append(SMTPAuthenticationError(-1, err)) raise SMTPLoginError(errors) return code, message
[ "async", "def", "auth", "(", "self", ",", "username", ",", "password", ")", ":", "# EHLO/HELO is required:", "await", "self", ".", "ehlo_or_helo_if_needed", "(", ")", "errors", "=", "[", "]", "# To store SMTPAuthenticationErrors", "code", "=", "message", "=", "None", "# Try to authenticate using all mechanisms supported by both", "# server and client (and only these):", "for", "auth", ",", "meth", "in", "self", ".", "__class__", ".", "_supported_auth_mechanisms", ".", "items", "(", ")", ":", "if", "auth", "in", "self", ".", "auth_mechanisms", ":", "auth_func", "=", "getattr", "(", "self", ",", "meth", ")", "try", ":", "code", ",", "message", "=", "await", "auth_func", "(", "username", ",", "password", ")", "except", "SMTPAuthenticationError", "as", "e", ":", "errors", ".", "append", "(", "e", ")", "else", ":", "break", "else", ":", "if", "not", "errors", ":", "err", "=", "\"Could not find any suitable authentication mechanism.\"", "errors", ".", "append", "(", "SMTPAuthenticationError", "(", "-", "1", ",", "err", ")", ")", "raise", "SMTPLoginError", "(", "errors", ")", "return", "code", ",", "message" ]
Tries to authenticate user against the SMTP server. Args: username (str): Username to authenticate with. password (str): Password to use along with the given ``username``. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. SMTPLoginError: If the authentication failed (either because all attempts failed or because there was no suitable authentication mechanism). Returns: (int, str): A (code, message) 2-tuple containing the last server response.
[ "Tries", "to", "authenticate", "user", "against", "the", "SMTP", "server", "." ]
84ce8e45b7e706476739d0efcb416c18ecabbbb6
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L618-L664
train
hwmrocker/smtplibaio
smtplibaio/smtp.py
SMTP.starttls
async def starttls(self, context=None): """ Upgrades the connection to the SMTP server into TLS mode. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. If the server supports SSL/TLS, this will encrypt the rest of the SMTP session. Raises: SMTPCommandNotSupportedError: If the server does not support STARTTLS. SMTPCommandFailedError: If the STARTTLS command fails BadImplementationError: If the connection does not use aioopenssl. Args: context (:obj:`OpenSSL.SSL.Context`): SSL context Returns: (int, message): A (code, message) 2-tuple containing the server response. """ if not self.use_aioopenssl: raise BadImplementationError("This connection does not use aioopenssl") import aioopenssl import OpenSSL await self.ehlo_or_helo_if_needed() if "starttls" not in self.esmtp_extensions: raise SMTPCommandNotSupportedError("STARTTLS") code, message = await self.do_cmd("STARTTLS", success=(220,)) # Don't check for code, do_cmd did it if context is None: context = OpenSSL.SSL.Context(OpenSSL.SSL.TLSv1_2_METHOD) await self.transport.starttls(ssl_context=context) # RFC 3207: # The client MUST discard any knowledge obtained from # the server, such as the list of SMTP service extensions, # which was not obtained from the TLS negotiation itself. # FIXME: wouldn't it be better to use reset_state here ? # And reset self.reader, self.writer and self.transport just after # Maybe also self.ssl_context ? self.last_ehlo_response = (None, None) self.last_helo_response = (None, None) self.supports_esmtp = False self.esmtp_extensions = {} self.auth_mechanisms = [] return (code, message)
python
async def starttls(self, context=None): """ Upgrades the connection to the SMTP server into TLS mode. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. If the server supports SSL/TLS, this will encrypt the rest of the SMTP session. Raises: SMTPCommandNotSupportedError: If the server does not support STARTTLS. SMTPCommandFailedError: If the STARTTLS command fails BadImplementationError: If the connection does not use aioopenssl. Args: context (:obj:`OpenSSL.SSL.Context`): SSL context Returns: (int, message): A (code, message) 2-tuple containing the server response. """ if not self.use_aioopenssl: raise BadImplementationError("This connection does not use aioopenssl") import aioopenssl import OpenSSL await self.ehlo_or_helo_if_needed() if "starttls" not in self.esmtp_extensions: raise SMTPCommandNotSupportedError("STARTTLS") code, message = await self.do_cmd("STARTTLS", success=(220,)) # Don't check for code, do_cmd did it if context is None: context = OpenSSL.SSL.Context(OpenSSL.SSL.TLSv1_2_METHOD) await self.transport.starttls(ssl_context=context) # RFC 3207: # The client MUST discard any knowledge obtained from # the server, such as the list of SMTP service extensions, # which was not obtained from the TLS negotiation itself. # FIXME: wouldn't it be better to use reset_state here ? # And reset self.reader, self.writer and self.transport just after # Maybe also self.ssl_context ? self.last_ehlo_response = (None, None) self.last_helo_response = (None, None) self.supports_esmtp = False self.esmtp_extensions = {} self.auth_mechanisms = [] return (code, message)
[ "async", "def", "starttls", "(", "self", ",", "context", "=", "None", ")", ":", "if", "not", "self", ".", "use_aioopenssl", ":", "raise", "BadImplementationError", "(", "\"This connection does not use aioopenssl\"", ")", "import", "aioopenssl", "import", "OpenSSL", "await", "self", ".", "ehlo_or_helo_if_needed", "(", ")", "if", "\"starttls\"", "not", "in", "self", ".", "esmtp_extensions", ":", "raise", "SMTPCommandNotSupportedError", "(", "\"STARTTLS\"", ")", "code", ",", "message", "=", "await", "self", ".", "do_cmd", "(", "\"STARTTLS\"", ",", "success", "=", "(", "220", ",", ")", ")", "# Don't check for code, do_cmd did it", "if", "context", "is", "None", ":", "context", "=", "OpenSSL", ".", "SSL", ".", "Context", "(", "OpenSSL", ".", "SSL", ".", "TLSv1_2_METHOD", ")", "await", "self", ".", "transport", ".", "starttls", "(", "ssl_context", "=", "context", ")", "# RFC 3207:", "# The client MUST discard any knowledge obtained from", "# the server, such as the list of SMTP service extensions,", "# which was not obtained from the TLS negotiation itself.", "# FIXME: wouldn't it be better to use reset_state here ?", "# And reset self.reader, self.writer and self.transport just after", "# Maybe also self.ssl_context ?", "self", ".", "last_ehlo_response", "=", "(", "None", ",", "None", ")", "self", ".", "last_helo_response", "=", "(", "None", ",", "None", ")", "self", ".", "supports_esmtp", "=", "False", "self", ".", "esmtp_extensions", "=", "{", "}", "self", ".", "auth_mechanisms", "=", "[", "]", "return", "(", "code", ",", "message", ")" ]
Upgrades the connection to the SMTP server into TLS mode. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. If the server supports SSL/TLS, this will encrypt the rest of the SMTP session. Raises: SMTPCommandNotSupportedError: If the server does not support STARTTLS. SMTPCommandFailedError: If the STARTTLS command fails BadImplementationError: If the connection does not use aioopenssl. Args: context (:obj:`OpenSSL.SSL.Context`): SSL context Returns: (int, message): A (code, message) 2-tuple containing the server response.
[ "Upgrades", "the", "connection", "to", "the", "SMTP", "server", "into", "TLS", "mode", "." ]
84ce8e45b7e706476739d0efcb416c18ecabbbb6
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L666-L721
train
hwmrocker/smtplibaio
smtplibaio/smtp.py
SMTP.sendmail
async def sendmail( self, sender, recipients, message, mail_options=None, rcpt_options=None ): """ Performs an entire e-mail transaction. Example: >>> try: >>> with SMTP() as client: >>> try: >>> r = client.sendmail(sender, recipients, message) >>> except SMTPException: >>> print("Error while sending message.") >>> else: >>> print("Result: {}.".format(r)) >>> except ConnectionError as e: >>> print(e) Result: {}. Args: sender (str): E-mail address of the sender. recipients (list of str or str): E-mail(s) address(es) of the recipient(s). message (str or bytes): Message body. mail_options (list of str): ESMTP options (such as *8BITMIME*) to send along the *MAIL* command. rcpt_options (list of str): ESMTP options (such as *DSN*) to send along all the *RCPT* commands. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. SMTPCommandFailedError: If the server refuses our MAIL command. SMTPCommandFailedError: If the server refuses our DATA command. SMTPNoRecipientError: If the server refuses all given recipients. Returns: dict: A dict containing an entry for each recipient that was refused. Each entry is associated with a (code, message) 2-tuple containing the error code and message, as returned by the server. When everythign runs smoothly, the returning dict is empty. .. note:: The connection remains open after. It's your responsibility to close it. A good practice is to use the asynchronous context manager instead. See :meth:`SMTP.__aenter__` for further details. """ # Make sure `recipients` is a list: if isinstance(recipients, str): recipients = [recipients] # Set some defaults values: if mail_options is None: mail_options = [] if rcpt_options is None: rcpt_options = [] # EHLO or HELO is required: await self.ehlo_or_helo_if_needed() if self.supports_esmtp: if "size" in self.esmtp_extensions: mail_options.append("size={}".format(len(message))) await self.mail(sender, mail_options) errors = [] for recipient in recipients: try: await self.rcpt(recipient, rcpt_options) except SMTPCommandFailedError as e: errors.append(e) if len(recipients) == len(errors): # The server refused all our recipients: raise SMTPNoRecipientError(errors) await self.data(message) # If we got here then somebody got our mail: return errors
python
async def sendmail( self, sender, recipients, message, mail_options=None, rcpt_options=None ): """ Performs an entire e-mail transaction. Example: >>> try: >>> with SMTP() as client: >>> try: >>> r = client.sendmail(sender, recipients, message) >>> except SMTPException: >>> print("Error while sending message.") >>> else: >>> print("Result: {}.".format(r)) >>> except ConnectionError as e: >>> print(e) Result: {}. Args: sender (str): E-mail address of the sender. recipients (list of str or str): E-mail(s) address(es) of the recipient(s). message (str or bytes): Message body. mail_options (list of str): ESMTP options (such as *8BITMIME*) to send along the *MAIL* command. rcpt_options (list of str): ESMTP options (such as *DSN*) to send along all the *RCPT* commands. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. SMTPCommandFailedError: If the server refuses our MAIL command. SMTPCommandFailedError: If the server refuses our DATA command. SMTPNoRecipientError: If the server refuses all given recipients. Returns: dict: A dict containing an entry for each recipient that was refused. Each entry is associated with a (code, message) 2-tuple containing the error code and message, as returned by the server. When everythign runs smoothly, the returning dict is empty. .. note:: The connection remains open after. It's your responsibility to close it. A good practice is to use the asynchronous context manager instead. See :meth:`SMTP.__aenter__` for further details. """ # Make sure `recipients` is a list: if isinstance(recipients, str): recipients = [recipients] # Set some defaults values: if mail_options is None: mail_options = [] if rcpt_options is None: rcpt_options = [] # EHLO or HELO is required: await self.ehlo_or_helo_if_needed() if self.supports_esmtp: if "size" in self.esmtp_extensions: mail_options.append("size={}".format(len(message))) await self.mail(sender, mail_options) errors = [] for recipient in recipients: try: await self.rcpt(recipient, rcpt_options) except SMTPCommandFailedError as e: errors.append(e) if len(recipients) == len(errors): # The server refused all our recipients: raise SMTPNoRecipientError(errors) await self.data(message) # If we got here then somebody got our mail: return errors
[ "async", "def", "sendmail", "(", "self", ",", "sender", ",", "recipients", ",", "message", ",", "mail_options", "=", "None", ",", "rcpt_options", "=", "None", ")", ":", "# Make sure `recipients` is a list:", "if", "isinstance", "(", "recipients", ",", "str", ")", ":", "recipients", "=", "[", "recipients", "]", "# Set some defaults values:", "if", "mail_options", "is", "None", ":", "mail_options", "=", "[", "]", "if", "rcpt_options", "is", "None", ":", "rcpt_options", "=", "[", "]", "# EHLO or HELO is required:", "await", "self", ".", "ehlo_or_helo_if_needed", "(", ")", "if", "self", ".", "supports_esmtp", ":", "if", "\"size\"", "in", "self", ".", "esmtp_extensions", ":", "mail_options", ".", "append", "(", "\"size={}\"", ".", "format", "(", "len", "(", "message", ")", ")", ")", "await", "self", ".", "mail", "(", "sender", ",", "mail_options", ")", "errors", "=", "[", "]", "for", "recipient", "in", "recipients", ":", "try", ":", "await", "self", ".", "rcpt", "(", "recipient", ",", "rcpt_options", ")", "except", "SMTPCommandFailedError", "as", "e", ":", "errors", ".", "append", "(", "e", ")", "if", "len", "(", "recipients", ")", "==", "len", "(", "errors", ")", ":", "# The server refused all our recipients:", "raise", "SMTPNoRecipientError", "(", "errors", ")", "await", "self", ".", "data", "(", "message", ")", "# If we got here then somebody got our mail:", "return", "errors" ]
Performs an entire e-mail transaction. Example: >>> try: >>> with SMTP() as client: >>> try: >>> r = client.sendmail(sender, recipients, message) >>> except SMTPException: >>> print("Error while sending message.") >>> else: >>> print("Result: {}.".format(r)) >>> except ConnectionError as e: >>> print(e) Result: {}. Args: sender (str): E-mail address of the sender. recipients (list of str or str): E-mail(s) address(es) of the recipient(s). message (str or bytes): Message body. mail_options (list of str): ESMTP options (such as *8BITMIME*) to send along the *MAIL* command. rcpt_options (list of str): ESMTP options (such as *DSN*) to send along all the *RCPT* commands. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. SMTPCommandFailedError: If the server refuses our MAIL command. SMTPCommandFailedError: If the server refuses our DATA command. SMTPNoRecipientError: If the server refuses all given recipients. Returns: dict: A dict containing an entry for each recipient that was refused. Each entry is associated with a (code, message) 2-tuple containing the error code and message, as returned by the server. When everythign runs smoothly, the returning dict is empty. .. note:: The connection remains open after. It's your responsibility to close it. A good practice is to use the asynchronous context manager instead. See :meth:`SMTP.__aenter__` for further details.
[ "Performs", "an", "entire", "e", "-", "mail", "transaction", "." ]
84ce8e45b7e706476739d0efcb416c18ecabbbb6
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L723-L810
train
hwmrocker/smtplibaio
smtplibaio/smtp.py
SMTP._auth_cram_md5
async def _auth_cram_md5(self, username, password): """ Performs an authentication attemps using the CRAM-MD5 mechanism. Protocol: 1. Send 'AUTH CRAM-MD5' to server ; 2. If the server replies with a 334 return code, we can go on: 1) The challenge (sent by the server) is base64-decoded ; 2) The decoded challenge is hashed using HMAC-MD5 and the user password as key (shared secret) ; 3) The hashed challenge is converted to a string of lowercase hexadecimal digits ; 4) The username and a space character are prepended to the hex digits ; 5) The concatenation is base64-encoded and sent to the server. 6) If the server replies with a return code of 235, user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "CRAM-MD5" code, message = await self.do_cmd("AUTH", mechanism, success=(334,)) decoded_challenge = base64.b64decode(message) challenge_hash = hmac.new( key=password.encode("utf-8"), msg=decoded_challenge, digestmod="md5" ) hex_hash = challenge_hash.hexdigest() response = "{} {}".format(username, hex_hash) encoded_response = SMTP.b64enc(response) try: code, message = await self.do_cmd(encoded_response, success=(235, 503)) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message
python
async def _auth_cram_md5(self, username, password): """ Performs an authentication attemps using the CRAM-MD5 mechanism. Protocol: 1. Send 'AUTH CRAM-MD5' to server ; 2. If the server replies with a 334 return code, we can go on: 1) The challenge (sent by the server) is base64-decoded ; 2) The decoded challenge is hashed using HMAC-MD5 and the user password as key (shared secret) ; 3) The hashed challenge is converted to a string of lowercase hexadecimal digits ; 4) The username and a space character are prepended to the hex digits ; 5) The concatenation is base64-encoded and sent to the server. 6) If the server replies with a return code of 235, user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "CRAM-MD5" code, message = await self.do_cmd("AUTH", mechanism, success=(334,)) decoded_challenge = base64.b64decode(message) challenge_hash = hmac.new( key=password.encode("utf-8"), msg=decoded_challenge, digestmod="md5" ) hex_hash = challenge_hash.hexdigest() response = "{} {}".format(username, hex_hash) encoded_response = SMTP.b64enc(response) try: code, message = await self.do_cmd(encoded_response, success=(235, 503)) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message
[ "async", "def", "_auth_cram_md5", "(", "self", ",", "username", ",", "password", ")", ":", "mechanism", "=", "\"CRAM-MD5\"", "code", ",", "message", "=", "await", "self", ".", "do_cmd", "(", "\"AUTH\"", ",", "mechanism", ",", "success", "=", "(", "334", ",", ")", ")", "decoded_challenge", "=", "base64", ".", "b64decode", "(", "message", ")", "challenge_hash", "=", "hmac", ".", "new", "(", "key", "=", "password", ".", "encode", "(", "\"utf-8\"", ")", ",", "msg", "=", "decoded_challenge", ",", "digestmod", "=", "\"md5\"", ")", "hex_hash", "=", "challenge_hash", ".", "hexdigest", "(", ")", "response", "=", "\"{} {}\"", ".", "format", "(", "username", ",", "hex_hash", ")", "encoded_response", "=", "SMTP", ".", "b64enc", "(", "response", ")", "try", ":", "code", ",", "message", "=", "await", "self", ".", "do_cmd", "(", "encoded_response", ",", "success", "=", "(", "235", ",", "503", ")", ")", "except", "SMTPCommandFailedError", "as", "e", ":", "raise", "SMTPAuthenticationError", "(", "e", ".", "code", ",", "e", ".", "message", ",", "mechanism", ")", "return", "code", ",", "message" ]
Performs an authentication attemps using the CRAM-MD5 mechanism. Protocol: 1. Send 'AUTH CRAM-MD5' to server ; 2. If the server replies with a 334 return code, we can go on: 1) The challenge (sent by the server) is base64-decoded ; 2) The decoded challenge is hashed using HMAC-MD5 and the user password as key (shared secret) ; 3) The hashed challenge is converted to a string of lowercase hexadecimal digits ; 4) The username and a space character are prepended to the hex digits ; 5) The concatenation is base64-encoded and sent to the server. 6) If the server replies with a return code of 235, user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response.
[ "Performs", "an", "authentication", "attemps", "using", "the", "CRAM", "-", "MD5", "mechanism", "." ]
84ce8e45b7e706476739d0efcb416c18ecabbbb6
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L861-L913
train
hwmrocker/smtplibaio
smtplibaio/smtp.py
SMTP._auth_login
async def _auth_login(self, username, password): """ Performs an authentication attempt using the LOGIN mechanism. Protocol: 1. The username is base64-encoded ; 2. The string 'AUTH LOGIN' and a space character are prepended to the base64-encoded username and sent to the server ; 3. If the server replies with a 334 return code, we can go on: 1) The password is base64-encoded and sent to the server ; 2) If the server replies with a 235 return code, the user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "LOGIN" code, message = await self.do_cmd( "AUTH", mechanism, SMTP.b64enc(username), success=(334,) ) try: code, message = await self.do_cmd(SMTP.b64enc(password), success=(235, 503)) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message
python
async def _auth_login(self, username, password): """ Performs an authentication attempt using the LOGIN mechanism. Protocol: 1. The username is base64-encoded ; 2. The string 'AUTH LOGIN' and a space character are prepended to the base64-encoded username and sent to the server ; 3. If the server replies with a 334 return code, we can go on: 1) The password is base64-encoded and sent to the server ; 2) If the server replies with a 235 return code, the user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "LOGIN" code, message = await self.do_cmd( "AUTH", mechanism, SMTP.b64enc(username), success=(334,) ) try: code, message = await self.do_cmd(SMTP.b64enc(password), success=(235, 503)) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message
[ "async", "def", "_auth_login", "(", "self", ",", "username", ",", "password", ")", ":", "mechanism", "=", "\"LOGIN\"", "code", ",", "message", "=", "await", "self", ".", "do_cmd", "(", "\"AUTH\"", ",", "mechanism", ",", "SMTP", ".", "b64enc", "(", "username", ")", ",", "success", "=", "(", "334", ",", ")", ")", "try", ":", "code", ",", "message", "=", "await", "self", ".", "do_cmd", "(", "SMTP", ".", "b64enc", "(", "password", ")", ",", "success", "=", "(", "235", ",", "503", ")", ")", "except", "SMTPCommandFailedError", "as", "e", ":", "raise", "SMTPAuthenticationError", "(", "e", ".", "code", ",", "e", ".", "message", ",", "mechanism", ")", "return", "code", ",", "message" ]
Performs an authentication attempt using the LOGIN mechanism. Protocol: 1. The username is base64-encoded ; 2. The string 'AUTH LOGIN' and a space character are prepended to the base64-encoded username and sent to the server ; 3. If the server replies with a 334 return code, we can go on: 1) The password is base64-encoded and sent to the server ; 2) If the server replies with a 235 return code, the user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response.
[ "Performs", "an", "authentication", "attempt", "using", "the", "LOGIN", "mechanism", "." ]
84ce8e45b7e706476739d0efcb416c18ecabbbb6
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L915-L954
train
hwmrocker/smtplibaio
smtplibaio/smtp.py
SMTP._auth_plain
async def _auth_plain(self, username, password): """ Performs an authentication attempt using the PLAIN mechanism. Protocol: 1. Format the username and password in a suitable way ; 2. The formatted string is base64-encoded ; 3. The string 'AUTH PLAIN' and a space character are prepended to the base64-encoded username and password and sent to the server ; 4. If the server replies with a 235 return code, user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "PLAIN" credentials = "\0{}\0{}".format(username, password) encoded_credentials = SMTP.b64enc(credentials) try: code, message = await self.do_cmd( "AUTH", mechanism, encoded_credentials, success=(235, 503) ) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message
python
async def _auth_plain(self, username, password): """ Performs an authentication attempt using the PLAIN mechanism. Protocol: 1. Format the username and password in a suitable way ; 2. The formatted string is base64-encoded ; 3. The string 'AUTH PLAIN' and a space character are prepended to the base64-encoded username and password and sent to the server ; 4. If the server replies with a 235 return code, user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "PLAIN" credentials = "\0{}\0{}".format(username, password) encoded_credentials = SMTP.b64enc(credentials) try: code, message = await self.do_cmd( "AUTH", mechanism, encoded_credentials, success=(235, 503) ) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message
[ "async", "def", "_auth_plain", "(", "self", ",", "username", ",", "password", ")", ":", "mechanism", "=", "\"PLAIN\"", "credentials", "=", "\"\\0{}\\0{}\"", ".", "format", "(", "username", ",", "password", ")", "encoded_credentials", "=", "SMTP", ".", "b64enc", "(", "credentials", ")", "try", ":", "code", ",", "message", "=", "await", "self", ".", "do_cmd", "(", "\"AUTH\"", ",", "mechanism", ",", "encoded_credentials", ",", "success", "=", "(", "235", ",", "503", ")", ")", "except", "SMTPCommandFailedError", "as", "e", ":", "raise", "SMTPAuthenticationError", "(", "e", ".", "code", ",", "e", ".", "message", ",", "mechanism", ")", "return", "code", ",", "message" ]
Performs an authentication attempt using the PLAIN mechanism. Protocol: 1. Format the username and password in a suitable way ; 2. The formatted string is base64-encoded ; 3. The string 'AUTH PLAIN' and a space character are prepended to the base64-encoded username and password and sent to the server ; 4. If the server replies with a 235 return code, user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response.
[ "Performs", "an", "authentication", "attempt", "using", "the", "PLAIN", "mechanism", "." ]
84ce8e45b7e706476739d0efcb416c18ecabbbb6
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L956-L995
train
OnroerendErfgoed/language-tags
language_tags/Tag.py
Tag.format
def format(self): """ Get format according to algorithm defined in RFC 5646 section 2.1.1. :return: formatted tag string. """ tag = self.data['tag'] subtags = tag.split('-') if len(subtags) == 1: return subtags[0] formatted_tag = subtags[0] private_tag = False for i, subtag in enumerate(subtags[1:]): if len(subtags[i]) == 1 or private_tag: formatted_tag += '-' + subtag private_tag = True elif len(subtag) == 2: formatted_tag += '-' + subtag.upper() elif len(subtag) == 4: formatted_tag += '-' + subtag.capitalize() else: formatted_tag += '-' + subtag return formatted_tag
python
def format(self): """ Get format according to algorithm defined in RFC 5646 section 2.1.1. :return: formatted tag string. """ tag = self.data['tag'] subtags = tag.split('-') if len(subtags) == 1: return subtags[0] formatted_tag = subtags[0] private_tag = False for i, subtag in enumerate(subtags[1:]): if len(subtags[i]) == 1 or private_tag: formatted_tag += '-' + subtag private_tag = True elif len(subtag) == 2: formatted_tag += '-' + subtag.upper() elif len(subtag) == 4: formatted_tag += '-' + subtag.capitalize() else: formatted_tag += '-' + subtag return formatted_tag
[ "def", "format", "(", "self", ")", ":", "tag", "=", "self", ".", "data", "[", "'tag'", "]", "subtags", "=", "tag", ".", "split", "(", "'-'", ")", "if", "len", "(", "subtags", ")", "==", "1", ":", "return", "subtags", "[", "0", "]", "formatted_tag", "=", "subtags", "[", "0", "]", "private_tag", "=", "False", "for", "i", ",", "subtag", "in", "enumerate", "(", "subtags", "[", "1", ":", "]", ")", ":", "if", "len", "(", "subtags", "[", "i", "]", ")", "==", "1", "or", "private_tag", ":", "formatted_tag", "+=", "'-'", "+", "subtag", "private_tag", "=", "True", "elif", "len", "(", "subtag", ")", "==", "2", ":", "formatted_tag", "+=", "'-'", "+", "subtag", ".", "upper", "(", ")", "elif", "len", "(", "subtag", ")", "==", "4", ":", "formatted_tag", "+=", "'-'", "+", "subtag", ".", "capitalize", "(", ")", "else", ":", "formatted_tag", "+=", "'-'", "+", "subtag", "return", "formatted_tag" ]
Get format according to algorithm defined in RFC 5646 section 2.1.1. :return: formatted tag string.
[ "Get", "format", "according", "to", "algorithm", "defined", "in", "RFC", "5646", "section", "2", ".", "1", ".", "1", "." ]
acb91e5458d22617f344e2eefaba9a9865373fdd
https://github.com/OnroerendErfgoed/language-tags/blob/acb91e5458d22617f344e2eefaba9a9865373fdd/language_tags/Tag.py#L118-L146
train
happyleavesaoc/aoc-mgz
mgz/enums.py
ObjectEnum
def ObjectEnum(ctx): """Object Enumeration. Should export the whole list from the game for the best accuracy. """ return Enum( ctx, villager_male=83, villager_female=293, scout_cavalry=448, eagle_warrior=751, king=434, flare=332, relic=285, turkey=833, sheep=594, deer=65, boar=48, iron_boar=810, ostrich=1026, javelina=822, crocodile=1031, rhinoceros=1139, wolf=126, jaguar=812, hawk=96, macaw=816, shore_fish=69, fish_1=455, fish_2=456, fish_4=458, fish_3=457, marlin_1=450, marlin_2=451, dolphin=452, cactus=709, berry_bush=59, stone_pile=102, gold_pile=66, forest_tree=350, forest_tree_2=411, snow_pine_tree=413, straggler_tree=349, tc_1=109, tc_2=618, tc_3=619, tc_4=620, castle=70, palisade_wall=72, stone_wall=117, stone_gate_1=64, stone_gate_2=81, stone_gate_3=88, stone_gate_4=95, palisade_gate_1=662, palisade_gate_2=666, palisade_gate_3=670, palisade_gate_4=674, fortified_wall=155, cliff_1=264, cliff_2=265, cliff_3=266, cliff_4=267, cliff_5=268, cliff_6=269, cliff_7=270, cliff_8=271, cliff_9=272, cliff_10=273, outpost=598, shipwreck=722, map_revealer=837, default=Pass )
python
def ObjectEnum(ctx): """Object Enumeration. Should export the whole list from the game for the best accuracy. """ return Enum( ctx, villager_male=83, villager_female=293, scout_cavalry=448, eagle_warrior=751, king=434, flare=332, relic=285, turkey=833, sheep=594, deer=65, boar=48, iron_boar=810, ostrich=1026, javelina=822, crocodile=1031, rhinoceros=1139, wolf=126, jaguar=812, hawk=96, macaw=816, shore_fish=69, fish_1=455, fish_2=456, fish_4=458, fish_3=457, marlin_1=450, marlin_2=451, dolphin=452, cactus=709, berry_bush=59, stone_pile=102, gold_pile=66, forest_tree=350, forest_tree_2=411, snow_pine_tree=413, straggler_tree=349, tc_1=109, tc_2=618, tc_3=619, tc_4=620, castle=70, palisade_wall=72, stone_wall=117, stone_gate_1=64, stone_gate_2=81, stone_gate_3=88, stone_gate_4=95, palisade_gate_1=662, palisade_gate_2=666, palisade_gate_3=670, palisade_gate_4=674, fortified_wall=155, cliff_1=264, cliff_2=265, cliff_3=266, cliff_4=267, cliff_5=268, cliff_6=269, cliff_7=270, cliff_8=271, cliff_9=272, cliff_10=273, outpost=598, shipwreck=722, map_revealer=837, default=Pass )
[ "def", "ObjectEnum", "(", "ctx", ")", ":", "return", "Enum", "(", "ctx", ",", "villager_male", "=", "83", ",", "villager_female", "=", "293", ",", "scout_cavalry", "=", "448", ",", "eagle_warrior", "=", "751", ",", "king", "=", "434", ",", "flare", "=", "332", ",", "relic", "=", "285", ",", "turkey", "=", "833", ",", "sheep", "=", "594", ",", "deer", "=", "65", ",", "boar", "=", "48", ",", "iron_boar", "=", "810", ",", "ostrich", "=", "1026", ",", "javelina", "=", "822", ",", "crocodile", "=", "1031", ",", "rhinoceros", "=", "1139", ",", "wolf", "=", "126", ",", "jaguar", "=", "812", ",", "hawk", "=", "96", ",", "macaw", "=", "816", ",", "shore_fish", "=", "69", ",", "fish_1", "=", "455", ",", "fish_2", "=", "456", ",", "fish_4", "=", "458", ",", "fish_3", "=", "457", ",", "marlin_1", "=", "450", ",", "marlin_2", "=", "451", ",", "dolphin", "=", "452", ",", "cactus", "=", "709", ",", "berry_bush", "=", "59", ",", "stone_pile", "=", "102", ",", "gold_pile", "=", "66", ",", "forest_tree", "=", "350", ",", "forest_tree_2", "=", "411", ",", "snow_pine_tree", "=", "413", ",", "straggler_tree", "=", "349", ",", "tc_1", "=", "109", ",", "tc_2", "=", "618", ",", "tc_3", "=", "619", ",", "tc_4", "=", "620", ",", "castle", "=", "70", ",", "palisade_wall", "=", "72", ",", "stone_wall", "=", "117", ",", "stone_gate_1", "=", "64", ",", "stone_gate_2", "=", "81", ",", "stone_gate_3", "=", "88", ",", "stone_gate_4", "=", "95", ",", "palisade_gate_1", "=", "662", ",", "palisade_gate_2", "=", "666", ",", "palisade_gate_3", "=", "670", ",", "palisade_gate_4", "=", "674", ",", "fortified_wall", "=", "155", ",", "cliff_1", "=", "264", ",", "cliff_2", "=", "265", ",", "cliff_3", "=", "266", ",", "cliff_4", "=", "267", ",", "cliff_5", "=", "268", ",", "cliff_6", "=", "269", ",", "cliff_7", "=", "270", ",", "cliff_8", "=", "271", ",", "cliff_9", "=", "272", ",", "cliff_10", "=", "273", ",", "outpost", "=", "598", ",", "shipwreck", "=", "722", ",", "map_revealer", "=", "837", ",", "default", "=", "Pass", ")" ]
Object Enumeration. Should export the whole list from the game for the best accuracy.
[ "Object", "Enumeration", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/enums.py#L8-L81
train
happyleavesaoc/aoc-mgz
mgz/enums.py
GameTypeEnum
def GameTypeEnum(ctx): """Game Type Enumeration.""" return Enum( ctx, RM=0, Regicide=1, DM=2, Scenario=3, Campaign=4, KingOfTheHill=5, WonderRace=6, DefendTheWonder=7, TurboRandom=8 )
python
def GameTypeEnum(ctx): """Game Type Enumeration.""" return Enum( ctx, RM=0, Regicide=1, DM=2, Scenario=3, Campaign=4, KingOfTheHill=5, WonderRace=6, DefendTheWonder=7, TurboRandom=8 )
[ "def", "GameTypeEnum", "(", "ctx", ")", ":", "return", "Enum", "(", "ctx", ",", "RM", "=", "0", ",", "Regicide", "=", "1", ",", "DM", "=", "2", ",", "Scenario", "=", "3", ",", "Campaign", "=", "4", ",", "KingOfTheHill", "=", "5", ",", "WonderRace", "=", "6", ",", "DefendTheWonder", "=", "7", ",", "TurboRandom", "=", "8", ")" ]
Game Type Enumeration.
[ "Game", "Type", "Enumeration", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/enums.py#L92-L105
train
happyleavesaoc/aoc-mgz
mgz/enums.py
ObjectTypeEnum
def ObjectTypeEnum(ctx): """Object Type Enumeration.""" return Enum( ctx, static=10, animated=20, doppelganger=25, moving=30, action=40, base=50, missile=60, combat=70, building=80, tree=90, default=Pass )
python
def ObjectTypeEnum(ctx): """Object Type Enumeration.""" return Enum( ctx, static=10, animated=20, doppelganger=25, moving=30, action=40, base=50, missile=60, combat=70, building=80, tree=90, default=Pass )
[ "def", "ObjectTypeEnum", "(", "ctx", ")", ":", "return", "Enum", "(", "ctx", ",", "static", "=", "10", ",", "animated", "=", "20", ",", "doppelganger", "=", "25", ",", "moving", "=", "30", ",", "action", "=", "40", ",", "base", "=", "50", ",", "missile", "=", "60", ",", "combat", "=", "70", ",", "building", "=", "80", ",", "tree", "=", "90", ",", "default", "=", "Pass", ")" ]
Object Type Enumeration.
[ "Object", "Type", "Enumeration", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/enums.py#L107-L122
train
happyleavesaoc/aoc-mgz
mgz/enums.py
PlayerTypeEnum
def PlayerTypeEnum(ctx): """Player Type Enumeration.""" return Enum( ctx, absent=0, closed=1, human=2, eliminated=3, computer=4, cyborg=5, spectator=6 )
python
def PlayerTypeEnum(ctx): """Player Type Enumeration.""" return Enum( ctx, absent=0, closed=1, human=2, eliminated=3, computer=4, cyborg=5, spectator=6 )
[ "def", "PlayerTypeEnum", "(", "ctx", ")", ":", "return", "Enum", "(", "ctx", ",", "absent", "=", "0", ",", "closed", "=", "1", ",", "human", "=", "2", ",", "eliminated", "=", "3", ",", "computer", "=", "4", ",", "cyborg", "=", "5", ",", "spectator", "=", "6", ")" ]
Player Type Enumeration.
[ "Player", "Type", "Enumeration", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/enums.py#L124-L135
train
happyleavesaoc/aoc-mgz
mgz/enums.py
ResourceEnum
def ResourceEnum(ctx): """Resource Type Enumeration.""" return Enum( ctx, food=0, wood=1, stone=2, gold=3, decay=12, fish=17, default=Pass # lots of resource types exist )
python
def ResourceEnum(ctx): """Resource Type Enumeration.""" return Enum( ctx, food=0, wood=1, stone=2, gold=3, decay=12, fish=17, default=Pass # lots of resource types exist )
[ "def", "ResourceEnum", "(", "ctx", ")", ":", "return", "Enum", "(", "ctx", ",", "food", "=", "0", ",", "wood", "=", "1", ",", "stone", "=", "2", ",", "gold", "=", "3", ",", "decay", "=", "12", ",", "fish", "=", "17", ",", "default", "=", "Pass", "# lots of resource types exist", ")" ]
Resource Type Enumeration.
[ "Resource", "Type", "Enumeration", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/enums.py#L167-L178
train
happyleavesaoc/aoc-mgz
mgz/enums.py
VictoryEnum
def VictoryEnum(ctx): """Victory Type Enumeration.""" return Enum( ctx, standard=0, conquest=1, exploration=2, ruins=3, artifacts=4, discoveries=5, gold=6, time_limit=7, score=8, standard2=9, regicide=10, last_man=11 )
python
def VictoryEnum(ctx): """Victory Type Enumeration.""" return Enum( ctx, standard=0, conquest=1, exploration=2, ruins=3, artifacts=4, discoveries=5, gold=6, time_limit=7, score=8, standard2=9, regicide=10, last_man=11 )
[ "def", "VictoryEnum", "(", "ctx", ")", ":", "return", "Enum", "(", "ctx", ",", "standard", "=", "0", ",", "conquest", "=", "1", ",", "exploration", "=", "2", ",", "ruins", "=", "3", ",", "artifacts", "=", "4", ",", "discoveries", "=", "5", ",", "gold", "=", "6", ",", "time_limit", "=", "7", ",", "score", "=", "8", ",", "standard2", "=", "9", ",", "regicide", "=", "10", ",", "last_man", "=", "11", ")" ]
Victory Type Enumeration.
[ "Victory", "Type", "Enumeration", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/enums.py#L180-L196
train
happyleavesaoc/aoc-mgz
mgz/enums.py
StartingAgeEnum
def StartingAgeEnum(ctx): """Starting Age Enumeration.""" return Enum( ctx, what=-2, unset=-1, dark=0, feudal=1, castle=2, imperial=3, postimperial=4, dmpostimperial=6 )
python
def StartingAgeEnum(ctx): """Starting Age Enumeration.""" return Enum( ctx, what=-2, unset=-1, dark=0, feudal=1, castle=2, imperial=3, postimperial=4, dmpostimperial=6 )
[ "def", "StartingAgeEnum", "(", "ctx", ")", ":", "return", "Enum", "(", "ctx", ",", "what", "=", "-", "2", ",", "unset", "=", "-", "1", ",", "dark", "=", "0", ",", "feudal", "=", "1", ",", "castle", "=", "2", ",", "imperial", "=", "3", ",", "postimperial", "=", "4", ",", "dmpostimperial", "=", "6", ")" ]
Starting Age Enumeration.
[ "Starting", "Age", "Enumeration", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/enums.py#L219-L231
train
happyleavesaoc/aoc-mgz
mgz/enums.py
GameActionModeEnum
def GameActionModeEnum(ctx): """Game Action Modes.""" return Enum( ctx, diplomacy=0, speed=1, instant_build=2, quick_build=4, allied_victory=5, cheat=6, unk0=9, spy=10, unk1=11, farm_queue=13, farm_unqueue=14, default=Pass )
python
def GameActionModeEnum(ctx): """Game Action Modes.""" return Enum( ctx, diplomacy=0, speed=1, instant_build=2, quick_build=4, allied_victory=5, cheat=6, unk0=9, spy=10, unk1=11, farm_queue=13, farm_unqueue=14, default=Pass )
[ "def", "GameActionModeEnum", "(", "ctx", ")", ":", "return", "Enum", "(", "ctx", ",", "diplomacy", "=", "0", ",", "speed", "=", "1", ",", "instant_build", "=", "2", ",", "quick_build", "=", "4", ",", "allied_victory", "=", "5", ",", "cheat", "=", "6", ",", "unk0", "=", "9", ",", "spy", "=", "10", ",", "unk1", "=", "11", ",", "farm_queue", "=", "13", ",", "farm_unqueue", "=", "14", ",", "default", "=", "Pass", ")" ]
Game Action Modes.
[ "Game", "Action", "Modes", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/enums.py#L250-L266
train
happyleavesaoc/aoc-mgz
mgz/enums.py
ReleaseTypeEnum
def ReleaseTypeEnum(ctx): """Types of Releases.""" return Enum( ctx, all=0, selected=3, sametype=4, notselected=5, inversetype=6, default=Pass )
python
def ReleaseTypeEnum(ctx): """Types of Releases.""" return Enum( ctx, all=0, selected=3, sametype=4, notselected=5, inversetype=6, default=Pass )
[ "def", "ReleaseTypeEnum", "(", "ctx", ")", ":", "return", "Enum", "(", "ctx", ",", "all", "=", "0", ",", "selected", "=", "3", ",", "sametype", "=", "4", ",", "notselected", "=", "5", ",", "inversetype", "=", "6", ",", "default", "=", "Pass", ")" ]
Types of Releases.
[ "Types", "of", "Releases", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/enums.py#L278-L288
train
happyleavesaoc/aoc-mgz
mgz/enums.py
MyDiplomacyEnum
def MyDiplomacyEnum(ctx): """Player's Diplomacy Enumeration.""" return Enum( ctx, gaia=0, self=1, ally=2, neutral=3, enemy=4, invalid_player=-1 )
python
def MyDiplomacyEnum(ctx): """Player's Diplomacy Enumeration.""" return Enum( ctx, gaia=0, self=1, ally=2, neutral=3, enemy=4, invalid_player=-1 )
[ "def", "MyDiplomacyEnum", "(", "ctx", ")", ":", "return", "Enum", "(", "ctx", ",", "gaia", "=", "0", ",", "self", "=", "1", ",", "ally", "=", "2", ",", "neutral", "=", "3", ",", "enemy", "=", "4", ",", "invalid_player", "=", "-", "1", ")" ]
Player's Diplomacy Enumeration.
[ "Player", "s", "Diplomacy", "Enumeration", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/enums.py#L310-L320
train
happyleavesaoc/aoc-mgz
mgz/enums.py
ActionEnum
def ActionEnum(ctx): """Action Enumeration.""" return Enum( ctx, interact=0, stop=1, ai_interact=2, move=3, add_attribute=5, give_attribute=6, ai_move=10, resign=11, spec=15, waypoint=16, stance=18, guard=19, follow=20, patrol=21, formation=23, save=27, ai_waypoint=31, chapter=32, ai_command=53, ai_queue=100, research=101, build=102, game=103, wall=105, delete=106, attackground=107, tribute=108, repair=110, release=111, multiqueue=112, togglegate=114, flare=115, order=117, queue=119, gatherpoint=120, sell=122, buy=123, droprelic=126, townbell=127, backtowork=128, postgame=255, default=Pass )
python
def ActionEnum(ctx): """Action Enumeration.""" return Enum( ctx, interact=0, stop=1, ai_interact=2, move=3, add_attribute=5, give_attribute=6, ai_move=10, resign=11, spec=15, waypoint=16, stance=18, guard=19, follow=20, patrol=21, formation=23, save=27, ai_waypoint=31, chapter=32, ai_command=53, ai_queue=100, research=101, build=102, game=103, wall=105, delete=106, attackground=107, tribute=108, repair=110, release=111, multiqueue=112, togglegate=114, flare=115, order=117, queue=119, gatherpoint=120, sell=122, buy=123, droprelic=126, townbell=127, backtowork=128, postgame=255, default=Pass )
[ "def", "ActionEnum", "(", "ctx", ")", ":", "return", "Enum", "(", "ctx", ",", "interact", "=", "0", ",", "stop", "=", "1", ",", "ai_interact", "=", "2", ",", "move", "=", "3", ",", "add_attribute", "=", "5", ",", "give_attribute", "=", "6", ",", "ai_move", "=", "10", ",", "resign", "=", "11", ",", "spec", "=", "15", ",", "waypoint", "=", "16", ",", "stance", "=", "18", ",", "guard", "=", "19", ",", "follow", "=", "20", ",", "patrol", "=", "21", ",", "formation", "=", "23", ",", "save", "=", "27", ",", "ai_waypoint", "=", "31", ",", "chapter", "=", "32", ",", "ai_command", "=", "53", ",", "ai_queue", "=", "100", ",", "research", "=", "101", ",", "build", "=", "102", ",", "game", "=", "103", ",", "wall", "=", "105", ",", "delete", "=", "106", ",", "attackground", "=", "107", ",", "tribute", "=", "108", ",", "repair", "=", "110", ",", "release", "=", "111", ",", "multiqueue", "=", "112", ",", "togglegate", "=", "114", ",", "flare", "=", "115", ",", "order", "=", "117", ",", "queue", "=", "119", ",", "gatherpoint", "=", "120", ",", "sell", "=", "122", ",", "buy", "=", "123", ",", "droprelic", "=", "126", ",", "townbell", "=", "127", ",", "backtowork", "=", "128", ",", "postgame", "=", "255", ",", "default", "=", "Pass", ")" ]
Action Enumeration.
[ "Action", "Enumeration", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/enums.py#L322-L368
train
bollwyvl/nosebook
nosebook.py
NosebookThree.newKernel
def newKernel(self, nb): """ generate a new kernel """ manager, kernel = utils.start_new_kernel( kernel_name=nb.metadata.kernelspec.name ) return kernel
python
def newKernel(self, nb): """ generate a new kernel """ manager, kernel = utils.start_new_kernel( kernel_name=nb.metadata.kernelspec.name ) return kernel
[ "def", "newKernel", "(", "self", ",", "nb", ")", ":", "manager", ",", "kernel", "=", "utils", ".", "start_new_kernel", "(", "kernel_name", "=", "nb", ".", "metadata", ".", "kernelspec", ".", "name", ")", "return", "kernel" ]
generate a new kernel
[ "generate", "a", "new", "kernel" ]
6a79104b9be4b5acf1ff06cbf745f220a54a4613
https://github.com/bollwyvl/nosebook/blob/6a79104b9be4b5acf1ff06cbf745f220a54a4613/nosebook.py#L65-L72
train
bollwyvl/nosebook
nosebook.py
Nosebook.configure
def configure(self, options, conf): """ apply configured options """ super(Nosebook, self).configure(options, conf) self.testMatch = re.compile(options.nosebookTestMatch).match self.testMatchCell = re.compile(options.nosebookTestMatchCell).match scrubs = [] if options.nosebookScrub: try: scrubs = json.loads(options.nosebookScrub) except Exception: scrubs = [options.nosebookScrub] if isstr(scrubs): scrubs = { scrubs: "<...>" } elif not isinstance(scrubs, dict): scrubs = dict([ (scrub, "<...%s>" % i) for i, scrub in enumerate(scrubs) ]) self.scrubMatch = { re.compile(scrub): sub for scrub, sub in scrubs.items() }
python
def configure(self, options, conf): """ apply configured options """ super(Nosebook, self).configure(options, conf) self.testMatch = re.compile(options.nosebookTestMatch).match self.testMatchCell = re.compile(options.nosebookTestMatchCell).match scrubs = [] if options.nosebookScrub: try: scrubs = json.loads(options.nosebookScrub) except Exception: scrubs = [options.nosebookScrub] if isstr(scrubs): scrubs = { scrubs: "<...>" } elif not isinstance(scrubs, dict): scrubs = dict([ (scrub, "<...%s>" % i) for i, scrub in enumerate(scrubs) ]) self.scrubMatch = { re.compile(scrub): sub for scrub, sub in scrubs.items() }
[ "def", "configure", "(", "self", ",", "options", ",", "conf", ")", ":", "super", "(", "Nosebook", ",", "self", ")", ".", "configure", "(", "options", ",", "conf", ")", "self", ".", "testMatch", "=", "re", ".", "compile", "(", "options", ".", "nosebookTestMatch", ")", ".", "match", "self", ".", "testMatchCell", "=", "re", ".", "compile", "(", "options", ".", "nosebookTestMatchCell", ")", ".", "match", "scrubs", "=", "[", "]", "if", "options", ".", "nosebookScrub", ":", "try", ":", "scrubs", "=", "json", ".", "loads", "(", "options", ".", "nosebookScrub", ")", "except", "Exception", ":", "scrubs", "=", "[", "options", ".", "nosebookScrub", "]", "if", "isstr", "(", "scrubs", ")", ":", "scrubs", "=", "{", "scrubs", ":", "\"<...>\"", "}", "elif", "not", "isinstance", "(", "scrubs", ",", "dict", ")", ":", "scrubs", "=", "dict", "(", "[", "(", "scrub", ",", "\"<...%s>\"", "%", "i", ")", "for", "i", ",", "scrub", "in", "enumerate", "(", "scrubs", ")", "]", ")", "self", ".", "scrubMatch", "=", "{", "re", ".", "compile", "(", "scrub", ")", ":", "sub", "for", "scrub", ",", "sub", "in", "scrubs", ".", "items", "(", ")", "}" ]
apply configured options
[ "apply", "configured", "options" ]
6a79104b9be4b5acf1ff06cbf745f220a54a4613
https://github.com/bollwyvl/nosebook/blob/6a79104b9be4b5acf1ff06cbf745f220a54a4613/nosebook.py#L136-L165
train
bollwyvl/nosebook
nosebook.py
Nosebook.wantFile
def wantFile(self, filename): """ filter files to those that match nosebook-match """ log.info("considering %s", filename) if self.testMatch(filename) is None: return False nb = self.readnb(filename) for cell in self.codeCells(nb): return True log.info("no `code` cells in %s", filename) return False
python
def wantFile(self, filename): """ filter files to those that match nosebook-match """ log.info("considering %s", filename) if self.testMatch(filename) is None: return False nb = self.readnb(filename) for cell in self.codeCells(nb): return True log.info("no `code` cells in %s", filename) return False
[ "def", "wantFile", "(", "self", ",", "filename", ")", ":", "log", ".", "info", "(", "\"considering %s\"", ",", "filename", ")", "if", "self", ".", "testMatch", "(", "filename", ")", "is", "None", ":", "return", "False", "nb", "=", "self", ".", "readnb", "(", "filename", ")", "for", "cell", "in", "self", ".", "codeCells", "(", "nb", ")", ":", "return", "True", "log", ".", "info", "(", "\"no `code` cells in %s\"", ",", "filename", ")", "return", "False" ]
filter files to those that match nosebook-match
[ "filter", "files", "to", "those", "that", "match", "nosebook", "-", "match" ]
6a79104b9be4b5acf1ff06cbf745f220a54a4613
https://github.com/bollwyvl/nosebook/blob/6a79104b9be4b5acf1ff06cbf745f220a54a4613/nosebook.py#L193-L210
train
rhjdjong/SlipLib
sliplib/slipsocket.py
SlipSocket.create_connection
def create_connection(cls, address, timeout=None, source_address=None): """Create a SlipSocket connection. This convenience method creates a connection to the the specified address using the :func:`socket.create_connection` function. The socket that is returned from that call is automatically wrapped in a :class:`SlipSocket` object. .. note:: The :meth:`create_connection` method does not magically turn the socket at the remote address into a SlipSocket. For the connection to work properly, the remote socket must already have been configured to use the SLIP protocol. """ sock = socket.create_connection(address, timeout, source_address) return cls(sock)
python
def create_connection(cls, address, timeout=None, source_address=None): """Create a SlipSocket connection. This convenience method creates a connection to the the specified address using the :func:`socket.create_connection` function. The socket that is returned from that call is automatically wrapped in a :class:`SlipSocket` object. .. note:: The :meth:`create_connection` method does not magically turn the socket at the remote address into a SlipSocket. For the connection to work properly, the remote socket must already have been configured to use the SLIP protocol. """ sock = socket.create_connection(address, timeout, source_address) return cls(sock)
[ "def", "create_connection", "(", "cls", ",", "address", ",", "timeout", "=", "None", ",", "source_address", "=", "None", ")", ":", "sock", "=", "socket", ".", "create_connection", "(", "address", ",", "timeout", ",", "source_address", ")", "return", "cls", "(", "sock", ")" ]
Create a SlipSocket connection. This convenience method creates a connection to the the specified address using the :func:`socket.create_connection` function. The socket that is returned from that call is automatically wrapped in a :class:`SlipSocket` object. .. note:: The :meth:`create_connection` method does not magically turn the socket at the remote address into a SlipSocket. For the connection to work properly, the remote socket must already have been configured to use the SLIP protocol.
[ "Create", "a", "SlipSocket", "connection", "." ]
8300dba3e512bca282380f234be34d75f4a73ce1
https://github.com/rhjdjong/SlipLib/blob/8300dba3e512bca282380f234be34d75f4a73ce1/sliplib/slipsocket.py#L94-L110
train
rhjdjong/SlipLib
sliplib/slipwrapper.py
SlipWrapper.send_msg
def send_msg(self, message): """Send a SLIP-encoded message over the stream. :param bytes message: The message to encode and send """ packet = self.driver.send(message) self.send_bytes(packet)
python
def send_msg(self, message): """Send a SLIP-encoded message over the stream. :param bytes message: The message to encode and send """ packet = self.driver.send(message) self.send_bytes(packet)
[ "def", "send_msg", "(", "self", ",", "message", ")", ":", "packet", "=", "self", ".", "driver", ".", "send", "(", "message", ")", "self", ".", "send_bytes", "(", "packet", ")" ]
Send a SLIP-encoded message over the stream. :param bytes message: The message to encode and send
[ "Send", "a", "SLIP", "-", "encoded", "message", "over", "the", "stream", "." ]
8300dba3e512bca282380f234be34d75f4a73ce1
https://github.com/rhjdjong/SlipLib/blob/8300dba3e512bca282380f234be34d75f4a73ce1/sliplib/slipwrapper.py#L65-L71
train
rhjdjong/SlipLib
sliplib/slipwrapper.py
SlipWrapper.recv_msg
def recv_msg(self): """Receive a single message from the stream. :return: A SLIP-decoded message :rtype: bytes :raises ProtocolError: when a SLIP protocol error has been encountered. A subsequent call to :meth:`recv_msg` (after handling the exception) will return the message from the next packet. """ # First check if there are any pending messages if self._messages: return self._messages.popleft() # No pending messages left. If a ProtocolError has occurred # it must be re-raised here: if self._protocol_error: self._handle_pending_protocol_error() while not self._messages and not self._stream_closed: # As long as no messages are available, # flush the internal packet buffer, # and try to read data try: if self._flush_needed: self._flush_needed = False self._messages.extend(self.driver.flush()) else: data = self.recv_bytes() if data == b'': self._stream_closed = True self._messages.extend(self.driver.receive(data)) except ProtocolError as pe: self._messages.extend(self.driver.messages) self._protocol_error = pe self._traceback = sys.exc_info()[2] break if self._messages: return self._messages.popleft() if self._protocol_error: self._handle_pending_protocol_error() else: return b''
python
def recv_msg(self): """Receive a single message from the stream. :return: A SLIP-decoded message :rtype: bytes :raises ProtocolError: when a SLIP protocol error has been encountered. A subsequent call to :meth:`recv_msg` (after handling the exception) will return the message from the next packet. """ # First check if there are any pending messages if self._messages: return self._messages.popleft() # No pending messages left. If a ProtocolError has occurred # it must be re-raised here: if self._protocol_error: self._handle_pending_protocol_error() while not self._messages and not self._stream_closed: # As long as no messages are available, # flush the internal packet buffer, # and try to read data try: if self._flush_needed: self._flush_needed = False self._messages.extend(self.driver.flush()) else: data = self.recv_bytes() if data == b'': self._stream_closed = True self._messages.extend(self.driver.receive(data)) except ProtocolError as pe: self._messages.extend(self.driver.messages) self._protocol_error = pe self._traceback = sys.exc_info()[2] break if self._messages: return self._messages.popleft() if self._protocol_error: self._handle_pending_protocol_error() else: return b''
[ "def", "recv_msg", "(", "self", ")", ":", "# First check if there are any pending messages", "if", "self", ".", "_messages", ":", "return", "self", ".", "_messages", ".", "popleft", "(", ")", "# No pending messages left. If a ProtocolError has occurred", "# it must be re-raised here:", "if", "self", ".", "_protocol_error", ":", "self", ".", "_handle_pending_protocol_error", "(", ")", "while", "not", "self", ".", "_messages", "and", "not", "self", ".", "_stream_closed", ":", "# As long as no messages are available,", "# flush the internal packet buffer,", "# and try to read data", "try", ":", "if", "self", ".", "_flush_needed", ":", "self", ".", "_flush_needed", "=", "False", "self", ".", "_messages", ".", "extend", "(", "self", ".", "driver", ".", "flush", "(", ")", ")", "else", ":", "data", "=", "self", ".", "recv_bytes", "(", ")", "if", "data", "==", "b''", ":", "self", ".", "_stream_closed", "=", "True", "self", ".", "_messages", ".", "extend", "(", "self", ".", "driver", ".", "receive", "(", "data", ")", ")", "except", "ProtocolError", "as", "pe", ":", "self", ".", "_messages", ".", "extend", "(", "self", ".", "driver", ".", "messages", ")", "self", ".", "_protocol_error", "=", "pe", "self", ".", "_traceback", "=", "sys", ".", "exc_info", "(", ")", "[", "2", "]", "break", "if", "self", ".", "_messages", ":", "return", "self", ".", "_messages", ".", "popleft", "(", ")", "if", "self", ".", "_protocol_error", ":", "self", ".", "_handle_pending_protocol_error", "(", ")", "else", ":", "return", "b''" ]
Receive a single message from the stream. :return: A SLIP-decoded message :rtype: bytes :raises ProtocolError: when a SLIP protocol error has been encountered. A subsequent call to :meth:`recv_msg` (after handling the exception) will return the message from the next packet.
[ "Receive", "a", "single", "message", "from", "the", "stream", "." ]
8300dba3e512bca282380f234be34d75f4a73ce1
https://github.com/rhjdjong/SlipLib/blob/8300dba3e512bca282380f234be34d75f4a73ce1/sliplib/slipwrapper.py#L73-L117
train
kstaniek/condoor
condoor/connection.py
Connection.finalize
def finalize(self): """Clean up the object. After calling this method the object can't be used anymore. This will be reworked when changing the logging model. """ self.pause_session_logging() self._disable_logging() self._msg_callback = None self._error_msg_callback = None self._warning_msg_callback = None self._info_msg_callback = None
python
def finalize(self): """Clean up the object. After calling this method the object can't be used anymore. This will be reworked when changing the logging model. """ self.pause_session_logging() self._disable_logging() self._msg_callback = None self._error_msg_callback = None self._warning_msg_callback = None self._info_msg_callback = None
[ "def", "finalize", "(", "self", ")", ":", "self", ".", "pause_session_logging", "(", ")", "self", ".", "_disable_logging", "(", ")", "self", ".", "_msg_callback", "=", "None", "self", ".", "_error_msg_callback", "=", "None", "self", ".", "_warning_msg_callback", "=", "None", "self", ".", "_info_msg_callback", "=", "None" ]
Clean up the object. After calling this method the object can't be used anymore. This will be reworked when changing the logging model.
[ "Clean", "up", "the", "object", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/connection.py#L100-L111
train
kstaniek/condoor
condoor/connection.py
Connection._chain_indices
def _chain_indices(self): """Get the deque of chain indices starting with last successful index.""" chain_indices = deque(range(len(self.connection_chains))) chain_indices.rotate(self._last_chain_index) return chain_indices
python
def _chain_indices(self): """Get the deque of chain indices starting with last successful index.""" chain_indices = deque(range(len(self.connection_chains))) chain_indices.rotate(self._last_chain_index) return chain_indices
[ "def", "_chain_indices", "(", "self", ")", ":", "chain_indices", "=", "deque", "(", "range", "(", "len", "(", "self", ".", "connection_chains", ")", ")", ")", "chain_indices", ".", "rotate", "(", "self", ".", "_last_chain_index", ")", "return", "chain_indices" ]
Get the deque of chain indices starting with last successful index.
[ "Get", "the", "deque", "of", "chain", "indices", "starting", "with", "last", "successful", "index", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/connection.py#L226-L230
train
kstaniek/condoor
condoor/connection.py
Connection.resume_session_logging
def resume_session_logging(self): """Resume session logging.""" self._chain.ctrl.set_session_log(self.session_fd) self.log("Session logging resumed")
python
def resume_session_logging(self): """Resume session logging.""" self._chain.ctrl.set_session_log(self.session_fd) self.log("Session logging resumed")
[ "def", "resume_session_logging", "(", "self", ")", ":", "self", ".", "_chain", ".", "ctrl", ".", "set_session_log", "(", "self", ".", "session_fd", ")", "self", ".", "log", "(", "\"Session logging resumed\"", ")" ]
Resume session logging.
[ "Resume", "session", "logging", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/connection.py#L371-L374
train
kstaniek/condoor
condoor/connection.py
Connection.rollback
def rollback(self, label=None, plane='sdr'): """Rollback the configuration. This method rolls back the configuration on the device. Args: label (text): The configuration label ID plane: (text): sdr or admin Returns: A string with commit label or None """ begin = time.time() rb_label = self._chain.target_device.rollback(label=label, plane=plane) elapsed = time.time() - begin if label: self.emit_message("Configuration rollback last {:.0f}s. Label: {}".format(elapsed, rb_label), log_level=logging.INFO) else: self.emit_message("Configuration failed.", log_level=logging.WARNING) return rb_label
python
def rollback(self, label=None, plane='sdr'): """Rollback the configuration. This method rolls back the configuration on the device. Args: label (text): The configuration label ID plane: (text): sdr or admin Returns: A string with commit label or None """ begin = time.time() rb_label = self._chain.target_device.rollback(label=label, plane=plane) elapsed = time.time() - begin if label: self.emit_message("Configuration rollback last {:.0f}s. Label: {}".format(elapsed, rb_label), log_level=logging.INFO) else: self.emit_message("Configuration failed.", log_level=logging.WARNING) return rb_label
[ "def", "rollback", "(", "self", ",", "label", "=", "None", ",", "plane", "=", "'sdr'", ")", ":", "begin", "=", "time", ".", "time", "(", ")", "rb_label", "=", "self", ".", "_chain", ".", "target_device", ".", "rollback", "(", "label", "=", "label", ",", "plane", "=", "plane", ")", "elapsed", "=", "time", ".", "time", "(", ")", "-", "begin", "if", "label", ":", "self", ".", "emit_message", "(", "\"Configuration rollback last {:.0f}s. Label: {}\"", ".", "format", "(", "elapsed", ",", "rb_label", ")", ",", "log_level", "=", "logging", ".", "INFO", ")", "else", ":", "self", ".", "emit_message", "(", "\"Configuration failed.\"", ",", "log_level", "=", "logging", ".", "WARNING", ")", "return", "rb_label" ]
Rollback the configuration. This method rolls back the configuration on the device. Args: label (text): The configuration label ID plane: (text): sdr or admin Returns: A string with commit label or None
[ "Rollback", "the", "configuration", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/connection.py#L424-L446
train
kstaniek/condoor
condoor/connection.py
Connection.discovery
def discovery(self, logfile=None, tracefile=None): """Discover the device details. This method discover several device attributes. Args: logfile (file): Optional file descriptor for session logging. The file must be open for write. The session is logged only if ``log_session=True`` was passed to the constructor. It the parameter is not passed then the default *session.log* file is created in `log_dir`. """ self._enable_logging(logfile=logfile, tracefile=tracefile) self.log("'discovery' method is deprecated. Please 'connect' with force_discovery=True.") self.log("Device discovery process started") self.connect(logfile=logfile, force_discovery=True, tracefile=tracefile) self.disconnect()
python
def discovery(self, logfile=None, tracefile=None): """Discover the device details. This method discover several device attributes. Args: logfile (file): Optional file descriptor for session logging. The file must be open for write. The session is logged only if ``log_session=True`` was passed to the constructor. It the parameter is not passed then the default *session.log* file is created in `log_dir`. """ self._enable_logging(logfile=logfile, tracefile=tracefile) self.log("'discovery' method is deprecated. Please 'connect' with force_discovery=True.") self.log("Device discovery process started") self.connect(logfile=logfile, force_discovery=True, tracefile=tracefile) self.disconnect()
[ "def", "discovery", "(", "self", ",", "logfile", "=", "None", ",", "tracefile", "=", "None", ")", ":", "self", ".", "_enable_logging", "(", "logfile", "=", "logfile", ",", "tracefile", "=", "tracefile", ")", "self", ".", "log", "(", "\"'discovery' method is deprecated. Please 'connect' with force_discovery=True.\"", ")", "self", ".", "log", "(", "\"Device discovery process started\"", ")", "self", ".", "connect", "(", "logfile", "=", "logfile", ",", "force_discovery", "=", "True", ",", "tracefile", "=", "tracefile", ")", "self", ".", "disconnect", "(", ")" ]
Discover the device details. This method discover several device attributes. Args: logfile (file): Optional file descriptor for session logging. The file must be open for write. The session is logged only if ``log_session=True`` was passed to the constructor. It the parameter is not passed then the default *session.log* file is created in `log_dir`.
[ "Discover", "the", "device", "details", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/connection.py#L453-L469
train
kstaniek/condoor
condoor/connection.py
Connection.reload
def reload(self, reload_timeout=300, save_config=True, no_reload_cmd=False): """Reload the device and wait for device to boot up. Returns False if reload was not successful. """ begin = time.time() self._chain.target_device.clear_info() result = False try: result = self._chain.target_device.reload(reload_timeout, save_config, no_reload_cmd) except ConnectionStandbyConsole as exc: message = exc.message self.log("Active RP became standby: {}".format(message)) self.disconnect() # self._conn_status.clear() result = self.reconnect() # connection error caused by device booting up except ConnectionError as exc: message = exc.message self.log("Connection error: {}".format(message)) self.disconnect() result = self.reconnect() if result: elapsed = time.time() - begin self.emit_message("Target device reload last {:.0f}s.".format(elapsed), log_level=logging.INFO) else: self.emit_message("Target device not reloaded.", log_level=logging.ERROR) return result
python
def reload(self, reload_timeout=300, save_config=True, no_reload_cmd=False): """Reload the device and wait for device to boot up. Returns False if reload was not successful. """ begin = time.time() self._chain.target_device.clear_info() result = False try: result = self._chain.target_device.reload(reload_timeout, save_config, no_reload_cmd) except ConnectionStandbyConsole as exc: message = exc.message self.log("Active RP became standby: {}".format(message)) self.disconnect() # self._conn_status.clear() result = self.reconnect() # connection error caused by device booting up except ConnectionError as exc: message = exc.message self.log("Connection error: {}".format(message)) self.disconnect() result = self.reconnect() if result: elapsed = time.time() - begin self.emit_message("Target device reload last {:.0f}s.".format(elapsed), log_level=logging.INFO) else: self.emit_message("Target device not reloaded.", log_level=logging.ERROR) return result
[ "def", "reload", "(", "self", ",", "reload_timeout", "=", "300", ",", "save_config", "=", "True", ",", "no_reload_cmd", "=", "False", ")", ":", "begin", "=", "time", ".", "time", "(", ")", "self", ".", "_chain", ".", "target_device", ".", "clear_info", "(", ")", "result", "=", "False", "try", ":", "result", "=", "self", ".", "_chain", ".", "target_device", ".", "reload", "(", "reload_timeout", ",", "save_config", ",", "no_reload_cmd", ")", "except", "ConnectionStandbyConsole", "as", "exc", ":", "message", "=", "exc", ".", "message", "self", ".", "log", "(", "\"Active RP became standby: {}\"", ".", "format", "(", "message", ")", ")", "self", ".", "disconnect", "(", ")", "# self._conn_status.clear()", "result", "=", "self", ".", "reconnect", "(", ")", "# connection error caused by device booting up", "except", "ConnectionError", "as", "exc", ":", "message", "=", "exc", ".", "message", "self", ".", "log", "(", "\"Connection error: {}\"", ".", "format", "(", "message", ")", ")", "self", ".", "disconnect", "(", ")", "result", "=", "self", ".", "reconnect", "(", ")", "if", "result", ":", "elapsed", "=", "time", ".", "time", "(", ")", "-", "begin", "self", ".", "emit_message", "(", "\"Target device reload last {:.0f}s.\"", ".", "format", "(", "elapsed", ")", ",", "log_level", "=", "logging", ".", "INFO", ")", "else", ":", "self", ".", "emit_message", "(", "\"Target device not reloaded.\"", ",", "log_level", "=", "logging", ".", "ERROR", ")", "return", "result" ]
Reload the device and wait for device to boot up. Returns False if reload was not successful.
[ "Reload", "the", "device", "and", "wait", "for", "device", "to", "boot", "up", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/connection.py#L482-L512
train
kstaniek/condoor
condoor/connection.py
Connection.run_fsm
def run_fsm(self, name, command, events, transitions, timeout, max_transitions=20): """Instantiate and run the Finite State Machine for the current device connection. Here is the example of usage:: test_dir = "rw_test" dir = "disk0:" + test_dir REMOVE_DIR = re.compile(re.escape("Remove directory filename [{}]?".format(test_dir))) DELETE_CONFIRM = re.compile(re.escape("Delete {}/{}[confirm]".format(filesystem, test_dir))) REMOVE_ERROR = re.compile(re.escape("%Error Removing dir {} (Directory doesnot exist)".format(test_dir))) command = "rmdir {}".format(dir) events = [device.prompt, REMOVE_DIR, DELETE_CONFIRM, REMOVE_ERROR, pexpect.TIMEOUT] transitions = [ (REMOVE_DIR, [0], 1, send_newline, 5), (DELETE_CONFIRM, [1], 2, send_newline, 5), # if dir does not exist initially it's ok (REMOVE_ERROR, [0], 2, None, 0), (device.prompt, [2], -1, None, 0), (pexpect.TIMEOUT, [0, 1, 2], -1, error, 0) ] if not conn.run_fsm("DELETE_DIR", command, events, transitions, timeout=5): return False This FSM tries to remove directory from disk0: Args: name (str): Name of the state machine used for logging purposes. Can't be *None* command (str): The command sent to the device before FSM starts events (list): List of expected strings or pexpect.TIMEOUT exception expected from the device. transitions (list): List of tuples in defining the state machine transitions. timeout (int): Default timeout between states in seconds. max_transitions (int): Default maximum number of transitions allowed for FSM. The transition tuple format is as follows:: (event, [list_of_states], next_state, action, timeout) Where: - **event** (str): string from the `events` list which is expected to be received from device. - **list_of_states** (list): List of FSM states that triggers the action in case of event occurrence. - **next_state** (int): Next state for FSM transition. - **action** (func): function to be executed if the current FSM state belongs to `list_of_states` and the `event` occurred. The action can be also *None* then FSM transits to the next state without any action. Action can be also the exception, which is raised and FSM stops. The example action:: def send_newline(ctx): ctx.ctrl.sendline() return True def error(ctx): ctx.message = "Filesystem error" return False def readonly(ctx): ctx.message = "Filesystem is readonly" return False The ctx object description refer to :class:`condoor.fsm.FSM`. If the action returns True then the FSM continues processing. If the action returns False then FSM stops and the error message passed back to the ctx object is posted to the log. The FSM state is the integer number. The FSM starts with initial ``state=0`` and finishes if the ``next_state`` is set to -1. If action returns False then FSM returns False. FSM returns True if reaches the -1 state. """ return self._chain.target_device.run_fsm(name, command, events, transitions, timeout, max_transitions)
python
def run_fsm(self, name, command, events, transitions, timeout, max_transitions=20): """Instantiate and run the Finite State Machine for the current device connection. Here is the example of usage:: test_dir = "rw_test" dir = "disk0:" + test_dir REMOVE_DIR = re.compile(re.escape("Remove directory filename [{}]?".format(test_dir))) DELETE_CONFIRM = re.compile(re.escape("Delete {}/{}[confirm]".format(filesystem, test_dir))) REMOVE_ERROR = re.compile(re.escape("%Error Removing dir {} (Directory doesnot exist)".format(test_dir))) command = "rmdir {}".format(dir) events = [device.prompt, REMOVE_DIR, DELETE_CONFIRM, REMOVE_ERROR, pexpect.TIMEOUT] transitions = [ (REMOVE_DIR, [0], 1, send_newline, 5), (DELETE_CONFIRM, [1], 2, send_newline, 5), # if dir does not exist initially it's ok (REMOVE_ERROR, [0], 2, None, 0), (device.prompt, [2], -1, None, 0), (pexpect.TIMEOUT, [0, 1, 2], -1, error, 0) ] if not conn.run_fsm("DELETE_DIR", command, events, transitions, timeout=5): return False This FSM tries to remove directory from disk0: Args: name (str): Name of the state machine used for logging purposes. Can't be *None* command (str): The command sent to the device before FSM starts events (list): List of expected strings or pexpect.TIMEOUT exception expected from the device. transitions (list): List of tuples in defining the state machine transitions. timeout (int): Default timeout between states in seconds. max_transitions (int): Default maximum number of transitions allowed for FSM. The transition tuple format is as follows:: (event, [list_of_states], next_state, action, timeout) Where: - **event** (str): string from the `events` list which is expected to be received from device. - **list_of_states** (list): List of FSM states that triggers the action in case of event occurrence. - **next_state** (int): Next state for FSM transition. - **action** (func): function to be executed if the current FSM state belongs to `list_of_states` and the `event` occurred. The action can be also *None* then FSM transits to the next state without any action. Action can be also the exception, which is raised and FSM stops. The example action:: def send_newline(ctx): ctx.ctrl.sendline() return True def error(ctx): ctx.message = "Filesystem error" return False def readonly(ctx): ctx.message = "Filesystem is readonly" return False The ctx object description refer to :class:`condoor.fsm.FSM`. If the action returns True then the FSM continues processing. If the action returns False then FSM stops and the error message passed back to the ctx object is posted to the log. The FSM state is the integer number. The FSM starts with initial ``state=0`` and finishes if the ``next_state`` is set to -1. If action returns False then FSM returns False. FSM returns True if reaches the -1 state. """ return self._chain.target_device.run_fsm(name, command, events, transitions, timeout, max_transitions)
[ "def", "run_fsm", "(", "self", ",", "name", ",", "command", ",", "events", ",", "transitions", ",", "timeout", ",", "max_transitions", "=", "20", ")", ":", "return", "self", ".", "_chain", ".", "target_device", ".", "run_fsm", "(", "name", ",", "command", ",", "events", ",", "transitions", ",", "timeout", ",", "max_transitions", ")" ]
Instantiate and run the Finite State Machine for the current device connection. Here is the example of usage:: test_dir = "rw_test" dir = "disk0:" + test_dir REMOVE_DIR = re.compile(re.escape("Remove directory filename [{}]?".format(test_dir))) DELETE_CONFIRM = re.compile(re.escape("Delete {}/{}[confirm]".format(filesystem, test_dir))) REMOVE_ERROR = re.compile(re.escape("%Error Removing dir {} (Directory doesnot exist)".format(test_dir))) command = "rmdir {}".format(dir) events = [device.prompt, REMOVE_DIR, DELETE_CONFIRM, REMOVE_ERROR, pexpect.TIMEOUT] transitions = [ (REMOVE_DIR, [0], 1, send_newline, 5), (DELETE_CONFIRM, [1], 2, send_newline, 5), # if dir does not exist initially it's ok (REMOVE_ERROR, [0], 2, None, 0), (device.prompt, [2], -1, None, 0), (pexpect.TIMEOUT, [0, 1, 2], -1, error, 0) ] if not conn.run_fsm("DELETE_DIR", command, events, transitions, timeout=5): return False This FSM tries to remove directory from disk0: Args: name (str): Name of the state machine used for logging purposes. Can't be *None* command (str): The command sent to the device before FSM starts events (list): List of expected strings or pexpect.TIMEOUT exception expected from the device. transitions (list): List of tuples in defining the state machine transitions. timeout (int): Default timeout between states in seconds. max_transitions (int): Default maximum number of transitions allowed for FSM. The transition tuple format is as follows:: (event, [list_of_states], next_state, action, timeout) Where: - **event** (str): string from the `events` list which is expected to be received from device. - **list_of_states** (list): List of FSM states that triggers the action in case of event occurrence. - **next_state** (int): Next state for FSM transition. - **action** (func): function to be executed if the current FSM state belongs to `list_of_states` and the `event` occurred. The action can be also *None* then FSM transits to the next state without any action. Action can be also the exception, which is raised and FSM stops. The example action:: def send_newline(ctx): ctx.ctrl.sendline() return True def error(ctx): ctx.message = "Filesystem error" return False def readonly(ctx): ctx.message = "Filesystem is readonly" return False The ctx object description refer to :class:`condoor.fsm.FSM`. If the action returns True then the FSM continues processing. If the action returns False then FSM stops and the error message passed back to the ctx object is posted to the log. The FSM state is the integer number. The FSM starts with initial ``state=0`` and finishes if the ``next_state`` is set to -1. If action returns False then FSM returns False. FSM returns True if reaches the -1 state.
[ "Instantiate", "and", "run", "the", "Finite", "State", "Machine", "for", "the", "current", "device", "connection", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/connection.py#L514-L588
train
kstaniek/condoor
condoor/connection.py
Connection.emit_message
def emit_message(self, message, log_level): """Call the msg callback function with the message.""" self.log(message) if log_level == logging.ERROR: if self._error_msg_callback: self._error_msg_callback(message) return if log_level == logging.WARNING: if self._warning_msg_callback: self._warning_msg_callback(message) return if log_level == logging.INFO: if self._info_msg_callback: self._info_msg_callback(message) return if self._msg_callback: self._msg_callback(message)
python
def emit_message(self, message, log_level): """Call the msg callback function with the message.""" self.log(message) if log_level == logging.ERROR: if self._error_msg_callback: self._error_msg_callback(message) return if log_level == logging.WARNING: if self._warning_msg_callback: self._warning_msg_callback(message) return if log_level == logging.INFO: if self._info_msg_callback: self._info_msg_callback(message) return if self._msg_callback: self._msg_callback(message)
[ "def", "emit_message", "(", "self", ",", "message", ",", "log_level", ")", ":", "self", ".", "log", "(", "message", ")", "if", "log_level", "==", "logging", ".", "ERROR", ":", "if", "self", ".", "_error_msg_callback", ":", "self", ".", "_error_msg_callback", "(", "message", ")", "return", "if", "log_level", "==", "logging", ".", "WARNING", ":", "if", "self", ".", "_warning_msg_callback", ":", "self", ".", "_warning_msg_callback", "(", "message", ")", "return", "if", "log_level", "==", "logging", ".", "INFO", ":", "if", "self", ".", "_info_msg_callback", ":", "self", ".", "_info_msg_callback", "(", "message", ")", "return", "if", "self", ".", "_msg_callback", ":", "self", ".", "_msg_callback", "(", "message", ")" ]
Call the msg callback function with the message.
[ "Call", "the", "msg", "callback", "function", "with", "the", "message", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/connection.py#L590-L609
train
kstaniek/condoor
condoor/connection.py
Connection.msg_callback
def msg_callback(self, callback): """Set the message callback.""" if callable(callback): self._msg_callback = callback else: self._msg_callback = None
python
def msg_callback(self, callback): """Set the message callback.""" if callable(callback): self._msg_callback = callback else: self._msg_callback = None
[ "def", "msg_callback", "(", "self", ",", "callback", ")", ":", "if", "callable", "(", "callback", ")", ":", "self", ".", "_msg_callback", "=", "callback", "else", ":", "self", ".", "_msg_callback", "=", "None" ]
Set the message callback.
[ "Set", "the", "message", "callback", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/connection.py#L617-L622
train
kstaniek/condoor
condoor/connection.py
Connection.error_msg_callback
def error_msg_callback(self, callback): """Set the error message callback.""" if callable(callback): self._error_msg_callback = callback else: self._error_msg_callback = None
python
def error_msg_callback(self, callback): """Set the error message callback.""" if callable(callback): self._error_msg_callback = callback else: self._error_msg_callback = None
[ "def", "error_msg_callback", "(", "self", ",", "callback", ")", ":", "if", "callable", "(", "callback", ")", ":", "self", ".", "_error_msg_callback", "=", "callback", "else", ":", "self", ".", "_error_msg_callback", "=", "None" ]
Set the error message callback.
[ "Set", "the", "error", "message", "callback", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/connection.py#L630-L635
train
kstaniek/condoor
condoor/connection.py
Connection.warning_msg_callback
def warning_msg_callback(self, callback): """Set the warning message callback.""" if callable(callback): self._warning_msg_callback = callback else: self._warning_msg_callback = None
python
def warning_msg_callback(self, callback): """Set the warning message callback.""" if callable(callback): self._warning_msg_callback = callback else: self._warning_msg_callback = None
[ "def", "warning_msg_callback", "(", "self", ",", "callback", ")", ":", "if", "callable", "(", "callback", ")", ":", "self", ".", "_warning_msg_callback", "=", "callback", "else", ":", "self", ".", "_warning_msg_callback", "=", "None" ]
Set the warning message callback.
[ "Set", "the", "warning", "message", "callback", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/connection.py#L643-L648
train
kstaniek/condoor
condoor/connection.py
Connection.info_msg_callback
def info_msg_callback(self, callback): """Set the info message callback.""" if callable(callback): self._info_msg_callback = callback else: self._info_msg_callback = None
python
def info_msg_callback(self, callback): """Set the info message callback.""" if callable(callback): self._info_msg_callback = callback else: self._info_msg_callback = None
[ "def", "info_msg_callback", "(", "self", ",", "callback", ")", ":", "if", "callable", "(", "callback", ")", ":", "self", ".", "_info_msg_callback", "=", "callback", "else", ":", "self", ".", "_info_msg_callback", "=", "None" ]
Set the info message callback.
[ "Set", "the", "info", "message", "callback", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/connection.py#L656-L661
train
thomasjiangcy/django-rest-mock
rest_mock_server/core/extractor.py
Extractor._get_view_details
def _get_view_details(self, urlpatterns, parent=''): """Recursive function to extract all url details""" for pattern in urlpatterns: if isinstance(pattern, (URLPattern, RegexURLPattern)): try: d = describe_pattern(pattern) docstr = pattern.callback.__doc__ method = None expected_json_response = '' expected_url = '' if docstr: # Get expected URL u = re.findall(r'URL: (.*)', docstr, flags=re.DOTALL) if u: expected_url = u[0] # Get all possible methods if 'view_class' not in dir(pattern.callback): continue possible_methods = [m for m in dir(pattern.callback.view_class) if m in METHODS] for method in possible_methods: view_method_docstr = getattr(pattern.callback.view_class, method).__doc__ if view_method_docstr: # Check if method is modifier if method in ['put', 'patch', 'delete']: self.url_details.append({ 'url': expected_url, 'method': method }) continue # Extract request method and JSON response from docstring of request method j = re.findall(r'```(.*)```', view_method_docstr, flags=re.DOTALL) if j is not None: for match in j: expected_json_response = match.strip() # Only add the details if all 3 values are filled if method is not None and expected_json_response and expected_url: self.url_details.append({ 'url': expected_url, 'method': method, 'response': expected_json_response }) continue except ViewDoesNotExist: pass elif isinstance(pattern, (URLResolver, RegexURLResolver)): try: patterns = pattern.url_patterns except ImportError: continue d = describe_pattern(pattern) current_full_url = parent + d self._get_view_details(patterns, current_full_url)
python
def _get_view_details(self, urlpatterns, parent=''): """Recursive function to extract all url details""" for pattern in urlpatterns: if isinstance(pattern, (URLPattern, RegexURLPattern)): try: d = describe_pattern(pattern) docstr = pattern.callback.__doc__ method = None expected_json_response = '' expected_url = '' if docstr: # Get expected URL u = re.findall(r'URL: (.*)', docstr, flags=re.DOTALL) if u: expected_url = u[0] # Get all possible methods if 'view_class' not in dir(pattern.callback): continue possible_methods = [m for m in dir(pattern.callback.view_class) if m in METHODS] for method in possible_methods: view_method_docstr = getattr(pattern.callback.view_class, method).__doc__ if view_method_docstr: # Check if method is modifier if method in ['put', 'patch', 'delete']: self.url_details.append({ 'url': expected_url, 'method': method }) continue # Extract request method and JSON response from docstring of request method j = re.findall(r'```(.*)```', view_method_docstr, flags=re.DOTALL) if j is not None: for match in j: expected_json_response = match.strip() # Only add the details if all 3 values are filled if method is not None and expected_json_response and expected_url: self.url_details.append({ 'url': expected_url, 'method': method, 'response': expected_json_response }) continue except ViewDoesNotExist: pass elif isinstance(pattern, (URLResolver, RegexURLResolver)): try: patterns = pattern.url_patterns except ImportError: continue d = describe_pattern(pattern) current_full_url = parent + d self._get_view_details(patterns, current_full_url)
[ "def", "_get_view_details", "(", "self", ",", "urlpatterns", ",", "parent", "=", "''", ")", ":", "for", "pattern", "in", "urlpatterns", ":", "if", "isinstance", "(", "pattern", ",", "(", "URLPattern", ",", "RegexURLPattern", ")", ")", ":", "try", ":", "d", "=", "describe_pattern", "(", "pattern", ")", "docstr", "=", "pattern", ".", "callback", ".", "__doc__", "method", "=", "None", "expected_json_response", "=", "''", "expected_url", "=", "''", "if", "docstr", ":", "# Get expected URL", "u", "=", "re", ".", "findall", "(", "r'URL: (.*)'", ",", "docstr", ",", "flags", "=", "re", ".", "DOTALL", ")", "if", "u", ":", "expected_url", "=", "u", "[", "0", "]", "# Get all possible methods", "if", "'view_class'", "not", "in", "dir", "(", "pattern", ".", "callback", ")", ":", "continue", "possible_methods", "=", "[", "m", "for", "m", "in", "dir", "(", "pattern", ".", "callback", ".", "view_class", ")", "if", "m", "in", "METHODS", "]", "for", "method", "in", "possible_methods", ":", "view_method_docstr", "=", "getattr", "(", "pattern", ".", "callback", ".", "view_class", ",", "method", ")", ".", "__doc__", "if", "view_method_docstr", ":", "# Check if method is modifier", "if", "method", "in", "[", "'put'", ",", "'patch'", ",", "'delete'", "]", ":", "self", ".", "url_details", ".", "append", "(", "{", "'url'", ":", "expected_url", ",", "'method'", ":", "method", "}", ")", "continue", "# Extract request method and JSON response from docstring of request method", "j", "=", "re", ".", "findall", "(", "r'```(.*)```'", ",", "view_method_docstr", ",", "flags", "=", "re", ".", "DOTALL", ")", "if", "j", "is", "not", "None", ":", "for", "match", "in", "j", ":", "expected_json_response", "=", "match", ".", "strip", "(", ")", "# Only add the details if all 3 values are filled", "if", "method", "is", "not", "None", "and", "expected_json_response", "and", "expected_url", ":", "self", ".", "url_details", ".", "append", "(", "{", "'url'", ":", "expected_url", ",", "'method'", ":", "method", ",", "'response'", ":", "expected_json_response", "}", ")", "continue", "except", "ViewDoesNotExist", ":", "pass", "elif", "isinstance", "(", "pattern", ",", "(", "URLResolver", ",", "RegexURLResolver", ")", ")", ":", "try", ":", "patterns", "=", "pattern", ".", "url_patterns", "except", "ImportError", ":", "continue", "d", "=", "describe_pattern", "(", "pattern", ")", "current_full_url", "=", "parent", "+", "d", "self", ".", "_get_view_details", "(", "patterns", ",", "current_full_url", ")" ]
Recursive function to extract all url details
[ "Recursive", "function", "to", "extract", "all", "url", "details" ]
09e91de20d1a5efd5c47c6e3d7fe979443012e2c
https://github.com/thomasjiangcy/django-rest-mock/blob/09e91de20d1a5efd5c47c6e3d7fe979443012e2c/rest_mock_server/core/extractor.py#L81-L139
train
zestyping/star-destroyer
star_destroyer.py
for_each_child
def for_each_child(node, callback): """Calls the callback for each AST node that's a child of the given node.""" for name in node._fields: value = getattr(node, name) if isinstance(value, list): for item in value: if isinstance(item, ast.AST): callback(item) elif isinstance(value, ast.AST): callback(value)
python
def for_each_child(node, callback): """Calls the callback for each AST node that's a child of the given node.""" for name in node._fields: value = getattr(node, name) if isinstance(value, list): for item in value: if isinstance(item, ast.AST): callback(item) elif isinstance(value, ast.AST): callback(value)
[ "def", "for_each_child", "(", "node", ",", "callback", ")", ":", "for", "name", "in", "node", ".", "_fields", ":", "value", "=", "getattr", "(", "node", ",", "name", ")", "if", "isinstance", "(", "value", ",", "list", ")", ":", "for", "item", "in", "value", ":", "if", "isinstance", "(", "item", ",", "ast", ".", "AST", ")", ":", "callback", "(", "item", ")", "elif", "isinstance", "(", "value", ",", "ast", ".", "AST", ")", ":", "callback", "(", "value", ")" ]
Calls the callback for each AST node that's a child of the given node.
[ "Calls", "the", "callback", "for", "each", "AST", "node", "that", "s", "a", "child", "of", "the", "given", "node", "." ]
e23584c85d1e8b8f098e5c75977c6a98a41f3f68
https://github.com/zestyping/star-destroyer/blob/e23584c85d1e8b8f098e5c75977c6a98a41f3f68/star_destroyer.py#L51-L60
train
zestyping/star-destroyer
star_destroyer.py
resolve_frompath
def resolve_frompath(pkgpath, relpath, level=0): """Resolves the path of the module referred to by 'from ..x import y'.""" if level == 0: return relpath parts = pkgpath.split('.') + ['_'] parts = parts[:-level] + (relpath.split('.') if relpath else []) return '.'.join(parts)
python
def resolve_frompath(pkgpath, relpath, level=0): """Resolves the path of the module referred to by 'from ..x import y'.""" if level == 0: return relpath parts = pkgpath.split('.') + ['_'] parts = parts[:-level] + (relpath.split('.') if relpath else []) return '.'.join(parts)
[ "def", "resolve_frompath", "(", "pkgpath", ",", "relpath", ",", "level", "=", "0", ")", ":", "if", "level", "==", "0", ":", "return", "relpath", "parts", "=", "pkgpath", ".", "split", "(", "'.'", ")", "+", "[", "'_'", "]", "parts", "=", "parts", "[", ":", "-", "level", "]", "+", "(", "relpath", ".", "split", "(", "'.'", ")", "if", "relpath", "else", "[", "]", ")", "return", "'.'", ".", "join", "(", "parts", ")" ]
Resolves the path of the module referred to by 'from ..x import y'.
[ "Resolves", "the", "path", "of", "the", "module", "referred", "to", "by", "from", "..", "x", "import", "y", "." ]
e23584c85d1e8b8f098e5c75977c6a98a41f3f68
https://github.com/zestyping/star-destroyer/blob/e23584c85d1e8b8f098e5c75977c6a98a41f3f68/star_destroyer.py#L62-L68
train
zestyping/star-destroyer
star_destroyer.py
find_module
def find_module(modpath): """Determines whether a module exists with the given modpath.""" module_path = modpath.replace('.', '/') + '.py' init_path = modpath.replace('.', '/') + '/__init__.py' for root_path in sys.path: path = os.path.join(root_path, module_path) if os.path.isfile(path): return path path = os.path.join(root_path, init_path) if os.path.isfile(path): return path
python
def find_module(modpath): """Determines whether a module exists with the given modpath.""" module_path = modpath.replace('.', '/') + '.py' init_path = modpath.replace('.', '/') + '/__init__.py' for root_path in sys.path: path = os.path.join(root_path, module_path) if os.path.isfile(path): return path path = os.path.join(root_path, init_path) if os.path.isfile(path): return path
[ "def", "find_module", "(", "modpath", ")", ":", "module_path", "=", "modpath", ".", "replace", "(", "'.'", ",", "'/'", ")", "+", "'.py'", "init_path", "=", "modpath", ".", "replace", "(", "'.'", ",", "'/'", ")", "+", "'/__init__.py'", "for", "root_path", "in", "sys", ".", "path", ":", "path", "=", "os", ".", "path", ".", "join", "(", "root_path", ",", "module_path", ")", "if", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "return", "path", "path", "=", "os", ".", "path", ".", "join", "(", "root_path", ",", "init_path", ")", "if", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "return", "path" ]
Determines whether a module exists with the given modpath.
[ "Determines", "whether", "a", "module", "exists", "with", "the", "given", "modpath", "." ]
e23584c85d1e8b8f098e5c75977c6a98a41f3f68
https://github.com/zestyping/star-destroyer/blob/e23584c85d1e8b8f098e5c75977c6a98a41f3f68/star_destroyer.py#L70-L80
train
zestyping/star-destroyer
star_destroyer.py
ImportMap.add
def add(self, modpath, name, origin): """Adds a possible origin for the given name in the given module.""" self.map.setdefault(modpath, {}).setdefault(name, set()).add(origin)
python
def add(self, modpath, name, origin): """Adds a possible origin for the given name in the given module.""" self.map.setdefault(modpath, {}).setdefault(name, set()).add(origin)
[ "def", "add", "(", "self", ",", "modpath", ",", "name", ",", "origin", ")", ":", "self", ".", "map", ".", "setdefault", "(", "modpath", ",", "{", "}", ")", ".", "setdefault", "(", "name", ",", "set", "(", ")", ")", ".", "add", "(", "origin", ")" ]
Adds a possible origin for the given name in the given module.
[ "Adds", "a", "possible", "origin", "for", "the", "given", "name", "in", "the", "given", "module", "." ]
e23584c85d1e8b8f098e5c75977c6a98a41f3f68
https://github.com/zestyping/star-destroyer/blob/e23584c85d1e8b8f098e5c75977c6a98a41f3f68/star_destroyer.py#L116-L118
train
zestyping/star-destroyer
star_destroyer.py
ImportMap.add_package_origins
def add_package_origins(self, modpath): """Whenever you 'import a.b.c', Python automatically binds 'b' in a to the a.b module and binds 'c' in a.b to the a.b.c module.""" parts = modpath.split('.') parent = parts[0] for part in parts[1:]: child = parent + '.' + part if self.find_module(child): self.add(parent, part, child) parent = child
python
def add_package_origins(self, modpath): """Whenever you 'import a.b.c', Python automatically binds 'b' in a to the a.b module and binds 'c' in a.b to the a.b.c module.""" parts = modpath.split('.') parent = parts[0] for part in parts[1:]: child = parent + '.' + part if self.find_module(child): self.add(parent, part, child) parent = child
[ "def", "add_package_origins", "(", "self", ",", "modpath", ")", ":", "parts", "=", "modpath", ".", "split", "(", "'.'", ")", "parent", "=", "parts", "[", "0", "]", "for", "part", "in", "parts", "[", "1", ":", "]", ":", "child", "=", "parent", "+", "'.'", "+", "part", "if", "self", ".", "find_module", "(", "child", ")", ":", "self", ".", "add", "(", "parent", ",", "part", ",", "child", ")", "parent", "=", "child" ]
Whenever you 'import a.b.c', Python automatically binds 'b' in a to the a.b module and binds 'c' in a.b to the a.b.c module.
[ "Whenever", "you", "import", "a", ".", "b", ".", "c", "Python", "automatically", "binds", "b", "in", "a", "to", "the", "a", ".", "b", "module", "and", "binds", "c", "in", "a", ".", "b", "to", "the", "a", ".", "b", ".", "c", "module", "." ]
e23584c85d1e8b8f098e5c75977c6a98a41f3f68
https://github.com/zestyping/star-destroyer/blob/e23584c85d1e8b8f098e5c75977c6a98a41f3f68/star_destroyer.py#L120-L129
train
zestyping/star-destroyer
star_destroyer.py
ImportMap.scan_module
def scan_module(self, pkgpath, modpath, node): """Scans a module, collecting possible origins for all names, assuming names can only become bound to values in other modules by import.""" def scan_imports(node): if node_type(node) == 'Import': for binding in node.names: name, asname = binding.name, binding.asname if asname: self.add(modpath, asname, name) else: top_name = name.split('.')[0] self.add(modpath, top_name, top_name) self.add_package_origins(name) elif node_type(node) == 'ImportFrom': frompath = resolve_frompath(pkgpath, node.module, node.level) for binding in node.names: name, asname = binding.name, binding.asname if name == '*': for name in self.get_star_names(frompath): self.add(modpath, name, frompath + '.' + name) self.add_package_origins(frompath) else: self.add(modpath, asname or name, frompath + '.' + name) self.add_package_origins(frompath + '.' + name) else: for_each_child(node, scan_imports) for_each_child(node, scan_imports)
python
def scan_module(self, pkgpath, modpath, node): """Scans a module, collecting possible origins for all names, assuming names can only become bound to values in other modules by import.""" def scan_imports(node): if node_type(node) == 'Import': for binding in node.names: name, asname = binding.name, binding.asname if asname: self.add(modpath, asname, name) else: top_name = name.split('.')[0] self.add(modpath, top_name, top_name) self.add_package_origins(name) elif node_type(node) == 'ImportFrom': frompath = resolve_frompath(pkgpath, node.module, node.level) for binding in node.names: name, asname = binding.name, binding.asname if name == '*': for name in self.get_star_names(frompath): self.add(modpath, name, frompath + '.' + name) self.add_package_origins(frompath) else: self.add(modpath, asname or name, frompath + '.' + name) self.add_package_origins(frompath + '.' + name) else: for_each_child(node, scan_imports) for_each_child(node, scan_imports)
[ "def", "scan_module", "(", "self", ",", "pkgpath", ",", "modpath", ",", "node", ")", ":", "def", "scan_imports", "(", "node", ")", ":", "if", "node_type", "(", "node", ")", "==", "'Import'", ":", "for", "binding", "in", "node", ".", "names", ":", "name", ",", "asname", "=", "binding", ".", "name", ",", "binding", ".", "asname", "if", "asname", ":", "self", ".", "add", "(", "modpath", ",", "asname", ",", "name", ")", "else", ":", "top_name", "=", "name", ".", "split", "(", "'.'", ")", "[", "0", "]", "self", ".", "add", "(", "modpath", ",", "top_name", ",", "top_name", ")", "self", ".", "add_package_origins", "(", "name", ")", "elif", "node_type", "(", "node", ")", "==", "'ImportFrom'", ":", "frompath", "=", "resolve_frompath", "(", "pkgpath", ",", "node", ".", "module", ",", "node", ".", "level", ")", "for", "binding", "in", "node", ".", "names", ":", "name", ",", "asname", "=", "binding", ".", "name", ",", "binding", ".", "asname", "if", "name", "==", "'*'", ":", "for", "name", "in", "self", ".", "get_star_names", "(", "frompath", ")", ":", "self", ".", "add", "(", "modpath", ",", "name", ",", "frompath", "+", "'.'", "+", "name", ")", "self", ".", "add_package_origins", "(", "frompath", ")", "else", ":", "self", ".", "add", "(", "modpath", ",", "asname", "or", "name", ",", "frompath", "+", "'.'", "+", "name", ")", "self", ".", "add_package_origins", "(", "frompath", "+", "'.'", "+", "name", ")", "else", ":", "for_each_child", "(", "node", ",", "scan_imports", ")", "for_each_child", "(", "node", ",", "scan_imports", ")" ]
Scans a module, collecting possible origins for all names, assuming names can only become bound to values in other modules by import.
[ "Scans", "a", "module", "collecting", "possible", "origins", "for", "all", "names", "assuming", "names", "can", "only", "become", "bound", "to", "values", "in", "other", "modules", "by", "import", "." ]
e23584c85d1e8b8f098e5c75977c6a98a41f3f68
https://github.com/zestyping/star-destroyer/blob/e23584c85d1e8b8f098e5c75977c6a98a41f3f68/star_destroyer.py#L131-L161
train
zestyping/star-destroyer
star_destroyer.py
ImportMap.get_origins
def get_origins(self, modpath, name): """Returns the set of possible origins for a name in a module.""" return self.map.get(modpath, {}).get(name, set())
python
def get_origins(self, modpath, name): """Returns the set of possible origins for a name in a module.""" return self.map.get(modpath, {}).get(name, set())
[ "def", "get_origins", "(", "self", ",", "modpath", ",", "name", ")", ":", "return", "self", ".", "map", ".", "get", "(", "modpath", ",", "{", "}", ")", ".", "get", "(", "name", ",", "set", "(", ")", ")" ]
Returns the set of possible origins for a name in a module.
[ "Returns", "the", "set", "of", "possible", "origins", "for", "a", "name", "in", "a", "module", "." ]
e23584c85d1e8b8f098e5c75977c6a98a41f3f68
https://github.com/zestyping/star-destroyer/blob/e23584c85d1e8b8f098e5c75977c6a98a41f3f68/star_destroyer.py#L163-L165
train
zestyping/star-destroyer
star_destroyer.py
ImportMap.dump
def dump(self): """Prints out the contents of the import map.""" for modpath in sorted(self.map): title = 'Imports in %s' % modpath print('\n' + title + '\n' + '-'*len(title)) for name, value in sorted(self.map.get(modpath, {}).items()): print(' %s -> %s' % (name, ', '.join(sorted(value))))
python
def dump(self): """Prints out the contents of the import map.""" for modpath in sorted(self.map): title = 'Imports in %s' % modpath print('\n' + title + '\n' + '-'*len(title)) for name, value in sorted(self.map.get(modpath, {}).items()): print(' %s -> %s' % (name, ', '.join(sorted(value))))
[ "def", "dump", "(", "self", ")", ":", "for", "modpath", "in", "sorted", "(", "self", ".", "map", ")", ":", "title", "=", "'Imports in %s'", "%", "modpath", "print", "(", "'\\n'", "+", "title", "+", "'\\n'", "+", "'-'", "*", "len", "(", "title", ")", ")", "for", "name", ",", "value", "in", "sorted", "(", "self", ".", "map", ".", "get", "(", "modpath", ",", "{", "}", ")", ".", "items", "(", ")", ")", ":", "print", "(", "' %s -> %s'", "%", "(", "name", ",", "', '", ".", "join", "(", "sorted", "(", "value", ")", ")", ")", ")" ]
Prints out the contents of the import map.
[ "Prints", "out", "the", "contents", "of", "the", "import", "map", "." ]
e23584c85d1e8b8f098e5c75977c6a98a41f3f68
https://github.com/zestyping/star-destroyer/blob/e23584c85d1e8b8f098e5c75977c6a98a41f3f68/star_destroyer.py#L167-L173
train
zestyping/star-destroyer
star_destroyer.py
UsageMap.scan_module
def scan_module(self, modpath, node): """Scans a module, collecting all used origins, assuming that modules are obtained only by dotted paths and no other kinds of expressions.""" used_origins = self.map.setdefault(modpath, set()) def get_origins(modpath, name): """Returns the chain of all origins for a given name in a module.""" origins = set() def walk_origins(modpath, name): for origin in self.import_map.get_origins(modpath, name): if origin not in origins: origins.add(origin) if '.' in origin: walk_origins(*origin.rsplit('.', 1)) walk_origins(modpath, name) return origins def get_origins_for_node(node): """Returns the set of all possible origins to which the given dotted-path expression might dereference.""" if node_type(node) == 'Name' and node_type(node.ctx) == 'Load': return {modpath + '.' + node.id} | get_origins(modpath, node.id) if node_type(node) == 'Attribute' and node_type(node.ctx) == 'Load': return set.union(set(), *[ {parent + '.' + node.attr} | get_origins(parent, node.attr) for parent in get_origins_for_node(node.value)]) return set() def get_origins_used_by_node(node): """Returns the set of all possible origins that could be used during dereferencing of the given dotted-path expression.""" if node_type(node) == 'Name': return get_origins_for_node(node) if node_type(node) == 'Attribute': return set.union(get_origins_used_by_node(node.value), get_origins_for_node(node)) return set() def scan_loads(node): if node_type(node) in ['Name', 'Attribute']: used_origins.update(get_origins_used_by_node(node)) for_each_child(node, scan_loads) for_each_child(node, scan_loads) intermediate_origins = set() for origin in used_origins: parts = origin.split('.') for i in range(1, len(parts)): intermediate_origins.add('.'.join(parts[:i])) used_origins.update(intermediate_origins)
python
def scan_module(self, modpath, node): """Scans a module, collecting all used origins, assuming that modules are obtained only by dotted paths and no other kinds of expressions.""" used_origins = self.map.setdefault(modpath, set()) def get_origins(modpath, name): """Returns the chain of all origins for a given name in a module.""" origins = set() def walk_origins(modpath, name): for origin in self.import_map.get_origins(modpath, name): if origin not in origins: origins.add(origin) if '.' in origin: walk_origins(*origin.rsplit('.', 1)) walk_origins(modpath, name) return origins def get_origins_for_node(node): """Returns the set of all possible origins to which the given dotted-path expression might dereference.""" if node_type(node) == 'Name' and node_type(node.ctx) == 'Load': return {modpath + '.' + node.id} | get_origins(modpath, node.id) if node_type(node) == 'Attribute' and node_type(node.ctx) == 'Load': return set.union(set(), *[ {parent + '.' + node.attr} | get_origins(parent, node.attr) for parent in get_origins_for_node(node.value)]) return set() def get_origins_used_by_node(node): """Returns the set of all possible origins that could be used during dereferencing of the given dotted-path expression.""" if node_type(node) == 'Name': return get_origins_for_node(node) if node_type(node) == 'Attribute': return set.union(get_origins_used_by_node(node.value), get_origins_for_node(node)) return set() def scan_loads(node): if node_type(node) in ['Name', 'Attribute']: used_origins.update(get_origins_used_by_node(node)) for_each_child(node, scan_loads) for_each_child(node, scan_loads) intermediate_origins = set() for origin in used_origins: parts = origin.split('.') for i in range(1, len(parts)): intermediate_origins.add('.'.join(parts[:i])) used_origins.update(intermediate_origins)
[ "def", "scan_module", "(", "self", ",", "modpath", ",", "node", ")", ":", "used_origins", "=", "self", ".", "map", ".", "setdefault", "(", "modpath", ",", "set", "(", ")", ")", "def", "get_origins", "(", "modpath", ",", "name", ")", ":", "\"\"\"Returns the chain of all origins for a given name in a module.\"\"\"", "origins", "=", "set", "(", ")", "def", "walk_origins", "(", "modpath", ",", "name", ")", ":", "for", "origin", "in", "self", ".", "import_map", ".", "get_origins", "(", "modpath", ",", "name", ")", ":", "if", "origin", "not", "in", "origins", ":", "origins", ".", "add", "(", "origin", ")", "if", "'.'", "in", "origin", ":", "walk_origins", "(", "*", "origin", ".", "rsplit", "(", "'.'", ",", "1", ")", ")", "walk_origins", "(", "modpath", ",", "name", ")", "return", "origins", "def", "get_origins_for_node", "(", "node", ")", ":", "\"\"\"Returns the set of all possible origins to which the given\n dotted-path expression might dereference.\"\"\"", "if", "node_type", "(", "node", ")", "==", "'Name'", "and", "node_type", "(", "node", ".", "ctx", ")", "==", "'Load'", ":", "return", "{", "modpath", "+", "'.'", "+", "node", ".", "id", "}", "|", "get_origins", "(", "modpath", ",", "node", ".", "id", ")", "if", "node_type", "(", "node", ")", "==", "'Attribute'", "and", "node_type", "(", "node", ".", "ctx", ")", "==", "'Load'", ":", "return", "set", ".", "union", "(", "set", "(", ")", ",", "*", "[", "{", "parent", "+", "'.'", "+", "node", ".", "attr", "}", "|", "get_origins", "(", "parent", ",", "node", ".", "attr", ")", "for", "parent", "in", "get_origins_for_node", "(", "node", ".", "value", ")", "]", ")", "return", "set", "(", ")", "def", "get_origins_used_by_node", "(", "node", ")", ":", "\"\"\"Returns the set of all possible origins that could be used\n during dereferencing of the given dotted-path expression.\"\"\"", "if", "node_type", "(", "node", ")", "==", "'Name'", ":", "return", "get_origins_for_node", "(", "node", ")", "if", "node_type", "(", "node", ")", "==", "'Attribute'", ":", "return", "set", ".", "union", "(", "get_origins_used_by_node", "(", "node", ".", "value", ")", ",", "get_origins_for_node", "(", "node", ")", ")", "return", "set", "(", ")", "def", "scan_loads", "(", "node", ")", ":", "if", "node_type", "(", "node", ")", "in", "[", "'Name'", ",", "'Attribute'", "]", ":", "used_origins", ".", "update", "(", "get_origins_used_by_node", "(", "node", ")", ")", "for_each_child", "(", "node", ",", "scan_loads", ")", "for_each_child", "(", "node", ",", "scan_loads", ")", "intermediate_origins", "=", "set", "(", ")", "for", "origin", "in", "used_origins", ":", "parts", "=", "origin", ".", "split", "(", "'.'", ")", "for", "i", "in", "range", "(", "1", ",", "len", "(", "parts", ")", ")", ":", "intermediate_origins", ".", "add", "(", "'.'", ".", "join", "(", "parts", "[", ":", "i", "]", ")", ")", "used_origins", ".", "update", "(", "intermediate_origins", ")" ]
Scans a module, collecting all used origins, assuming that modules are obtained only by dotted paths and no other kinds of expressions.
[ "Scans", "a", "module", "collecting", "all", "used", "origins", "assuming", "that", "modules", "are", "obtained", "only", "by", "dotted", "paths", "and", "no", "other", "kinds", "of", "expressions", "." ]
e23584c85d1e8b8f098e5c75977c6a98a41f3f68
https://github.com/zestyping/star-destroyer/blob/e23584c85d1e8b8f098e5c75977c6a98a41f3f68/star_destroyer.py#L186-L239
train
zestyping/star-destroyer
star_destroyer.py
UsageMap.dump
def dump(self): """Prints out the contents of the usage map.""" for modpath in sorted(self.map): title = 'Used by %s' % modpath print('\n' + title + '\n' + '-'*len(title)) for origin in sorted(self.get_used_origins(modpath)): print(' %s' % origin)
python
def dump(self): """Prints out the contents of the usage map.""" for modpath in sorted(self.map): title = 'Used by %s' % modpath print('\n' + title + '\n' + '-'*len(title)) for origin in sorted(self.get_used_origins(modpath)): print(' %s' % origin)
[ "def", "dump", "(", "self", ")", ":", "for", "modpath", "in", "sorted", "(", "self", ".", "map", ")", ":", "title", "=", "'Used by %s'", "%", "modpath", "print", "(", "'\\n'", "+", "title", "+", "'\\n'", "+", "'-'", "*", "len", "(", "title", ")", ")", "for", "origin", "in", "sorted", "(", "self", ".", "get_used_origins", "(", "modpath", ")", ")", ":", "print", "(", "' %s'", "%", "origin", ")" ]
Prints out the contents of the usage map.
[ "Prints", "out", "the", "contents", "of", "the", "usage", "map", "." ]
e23584c85d1e8b8f098e5c75977c6a98a41f3f68
https://github.com/zestyping/star-destroyer/blob/e23584c85d1e8b8f098e5c75977c6a98a41f3f68/star_destroyer.py#L247-L253
train
happyleavesaoc/aoc-mgz
mgz/util.py
convert_to_timestamp
def convert_to_timestamp(time): """Convert int to timestamp string.""" if time == -1: return None time = int(time*1000) hour = time//1000//3600 minute = (time//1000//60) % 60 second = (time//1000) % 60 return str(hour).zfill(2)+":"+str(minute).zfill(2)+":"+str(second).zfill(2)
python
def convert_to_timestamp(time): """Convert int to timestamp string.""" if time == -1: return None time = int(time*1000) hour = time//1000//3600 minute = (time//1000//60) % 60 second = (time//1000) % 60 return str(hour).zfill(2)+":"+str(minute).zfill(2)+":"+str(second).zfill(2)
[ "def", "convert_to_timestamp", "(", "time", ")", ":", "if", "time", "==", "-", "1", ":", "return", "None", "time", "=", "int", "(", "time", "*", "1000", ")", "hour", "=", "time", "//", "1000", "//", "3600", "minute", "=", "(", "time", "//", "1000", "//", "60", ")", "%", "60", "second", "=", "(", "time", "//", "1000", ")", "%", "60", "return", "str", "(", "hour", ")", ".", "zfill", "(", "2", ")", "+", "\":\"", "+", "str", "(", "minute", ")", ".", "zfill", "(", "2", ")", "+", "\":\"", "+", "str", "(", "second", ")", ".", "zfill", "(", "2", ")" ]
Convert int to timestamp string.
[ "Convert", "int", "to", "timestamp", "string", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/util.py#L43-L51
train
happyleavesaoc/aoc-mgz
mgz/util.py
MgzPrefixed._parse
def _parse(self, stream, context, path): """Parse tunnel.""" length = self.length(context) new_stream = BytesIO(construct.core._read_stream(stream, length)) return self.subcon._parse(new_stream, context, path)
python
def _parse(self, stream, context, path): """Parse tunnel.""" length = self.length(context) new_stream = BytesIO(construct.core._read_stream(stream, length)) return self.subcon._parse(new_stream, context, path)
[ "def", "_parse", "(", "self", ",", "stream", ",", "context", ",", "path", ")", ":", "length", "=", "self", ".", "length", "(", "context", ")", "new_stream", "=", "BytesIO", "(", "construct", ".", "core", ".", "_read_stream", "(", "stream", ",", "length", ")", ")", "return", "self", ".", "subcon", ".", "_parse", "(", "new_stream", ",", "context", ",", "path", ")" ]
Parse tunnel.
[ "Parse", "tunnel", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/util.py#L26-L30
train
happyleavesaoc/aoc-mgz
mgz/util.py
Find._parse
def _parse(self, stream, context, path): """Parse stream to find a given byte string.""" start = stream.tell() read_bytes = "" if self.max_length: read_bytes = stream.read(self.max_length) else: read_bytes = stream.read() skip = read_bytes.find(self.find) + len(self.find) stream.seek(start + skip) return skip
python
def _parse(self, stream, context, path): """Parse stream to find a given byte string.""" start = stream.tell() read_bytes = "" if self.max_length: read_bytes = stream.read(self.max_length) else: read_bytes = stream.read() skip = read_bytes.find(self.find) + len(self.find) stream.seek(start + skip) return skip
[ "def", "_parse", "(", "self", ",", "stream", ",", "context", ",", "path", ")", ":", "start", "=", "stream", ".", "tell", "(", ")", "read_bytes", "=", "\"\"", "if", "self", ".", "max_length", ":", "read_bytes", "=", "stream", ".", "read", "(", "self", ".", "max_length", ")", "else", ":", "read_bytes", "=", "stream", ".", "read", "(", ")", "skip", "=", "read_bytes", ".", "find", "(", "self", ".", "find", ")", "+", "len", "(", "self", ".", "find", ")", "stream", ".", "seek", "(", "start", "+", "skip", ")", "return", "skip" ]
Parse stream to find a given byte string.
[ "Parse", "stream", "to", "find", "a", "given", "byte", "string", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/util.py#L94-L104
train
happyleavesaoc/aoc-mgz
mgz/util.py
RepeatUpTo._parse
def _parse(self, stream, context, path): """Parse until a given byte string is found.""" objs = [] while True: start = stream.tell() test = stream.read(len(self.find)) stream.seek(start) if test == self.find: break else: subobj = self.subcon._parse(stream, context, path) objs.append(subobj) return objs
python
def _parse(self, stream, context, path): """Parse until a given byte string is found.""" objs = [] while True: start = stream.tell() test = stream.read(len(self.find)) stream.seek(start) if test == self.find: break else: subobj = self.subcon._parse(stream, context, path) objs.append(subobj) return objs
[ "def", "_parse", "(", "self", ",", "stream", ",", "context", ",", "path", ")", ":", "objs", "=", "[", "]", "while", "True", ":", "start", "=", "stream", ".", "tell", "(", ")", "test", "=", "stream", ".", "read", "(", "len", "(", "self", ".", "find", ")", ")", "stream", ".", "seek", "(", "start", ")", "if", "test", "==", "self", ".", "find", ":", "break", "else", ":", "subobj", "=", "self", ".", "subcon", ".", "_parse", "(", "stream", ",", "context", ",", "path", ")", "objs", ".", "append", "(", "subobj", ")", "return", "objs" ]
Parse until a given byte string is found.
[ "Parse", "until", "a", "given", "byte", "string", "is", "found", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/util.py#L117-L129
train
happyleavesaoc/aoc-mgz
mgz/util.py
GotoObjectsEnd._parse
def _parse(self, stream, context, path): """Parse until the end of objects data.""" num_players = context._._._.replay.num_players start = stream.tell() # Have to read everything to be able to use find() read_bytes = stream.read() # Try to find the first marker, a portion of the next player structure marker_up14 = read_bytes.find(b"\x16\xc6\x00\x00\x00\x21") marker_up15 = read_bytes.find(b"\x16\xf0\x00\x00\x00\x21") marker = -1 if marker_up14 > 0 and marker_up15 < 0: marker = marker_up14 elif marker_up15 > 0 and marker_up14 < 0: marker = marker_up15 # If it exists, we're not on the last player yet if marker > 0: # Backtrack through the player name count = 0 while struct.unpack("<H", read_bytes[marker-2:marker])[0] != count: marker -= 1 count += 1 # Backtrack through the rest of the next player structure backtrack = 43 + num_players # Otherwise, this is the last player else: # Search for the scenario header marker = read_bytes.find(b"\xf6\x28\x9c\x3f") # Backtrack through the achievements and initial structure footer backtrack = ((1817 * (num_players - 1)) + 4 + 19) # Seek to the position we found end = start + marker - backtrack stream.seek(end) return end
python
def _parse(self, stream, context, path): """Parse until the end of objects data.""" num_players = context._._._.replay.num_players start = stream.tell() # Have to read everything to be able to use find() read_bytes = stream.read() # Try to find the first marker, a portion of the next player structure marker_up14 = read_bytes.find(b"\x16\xc6\x00\x00\x00\x21") marker_up15 = read_bytes.find(b"\x16\xf0\x00\x00\x00\x21") marker = -1 if marker_up14 > 0 and marker_up15 < 0: marker = marker_up14 elif marker_up15 > 0 and marker_up14 < 0: marker = marker_up15 # If it exists, we're not on the last player yet if marker > 0: # Backtrack through the player name count = 0 while struct.unpack("<H", read_bytes[marker-2:marker])[0] != count: marker -= 1 count += 1 # Backtrack through the rest of the next player structure backtrack = 43 + num_players # Otherwise, this is the last player else: # Search for the scenario header marker = read_bytes.find(b"\xf6\x28\x9c\x3f") # Backtrack through the achievements and initial structure footer backtrack = ((1817 * (num_players - 1)) + 4 + 19) # Seek to the position we found end = start + marker - backtrack stream.seek(end) return end
[ "def", "_parse", "(", "self", ",", "stream", ",", "context", ",", "path", ")", ":", "num_players", "=", "context", ".", "_", ".", "_", ".", "_", ".", "replay", ".", "num_players", "start", "=", "stream", ".", "tell", "(", ")", "# Have to read everything to be able to use find()", "read_bytes", "=", "stream", ".", "read", "(", ")", "# Try to find the first marker, a portion of the next player structure", "marker_up14", "=", "read_bytes", ".", "find", "(", "b\"\\x16\\xc6\\x00\\x00\\x00\\x21\"", ")", "marker_up15", "=", "read_bytes", ".", "find", "(", "b\"\\x16\\xf0\\x00\\x00\\x00\\x21\"", ")", "marker", "=", "-", "1", "if", "marker_up14", ">", "0", "and", "marker_up15", "<", "0", ":", "marker", "=", "marker_up14", "elif", "marker_up15", ">", "0", "and", "marker_up14", "<", "0", ":", "marker", "=", "marker_up15", "# If it exists, we're not on the last player yet", "if", "marker", ">", "0", ":", "# Backtrack through the player name", "count", "=", "0", "while", "struct", ".", "unpack", "(", "\"<H\"", ",", "read_bytes", "[", "marker", "-", "2", ":", "marker", "]", ")", "[", "0", "]", "!=", "count", ":", "marker", "-=", "1", "count", "+=", "1", "# Backtrack through the rest of the next player structure", "backtrack", "=", "43", "+", "num_players", "# Otherwise, this is the last player", "else", ":", "# Search for the scenario header", "marker", "=", "read_bytes", ".", "find", "(", "b\"\\xf6\\x28\\x9c\\x3f\"", ")", "# Backtrack through the achievements and initial structure footer", "backtrack", "=", "(", "(", "1817", "*", "(", "num_players", "-", "1", ")", ")", "+", "4", "+", "19", ")", "# Seek to the position we found", "end", "=", "start", "+", "marker", "-", "backtrack", "stream", ".", "seek", "(", "end", ")", "return", "end" ]
Parse until the end of objects data.
[ "Parse", "until", "the", "end", "of", "objects", "data", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/util.py#L138-L170
train
kstaniek/condoor
condoor/drivers/XR.py
Driver.rollback
def rollback(self, label, plane): """Rollback config.""" cm_label = 'condoor-{}'.format(int(time.time())) self.device.send(self.rollback_cmd.format(label), timeout=120) return cm_label
python
def rollback(self, label, plane): """Rollback config.""" cm_label = 'condoor-{}'.format(int(time.time())) self.device.send(self.rollback_cmd.format(label), timeout=120) return cm_label
[ "def", "rollback", "(", "self", ",", "label", ",", "plane", ")", ":", "cm_label", "=", "'condoor-{}'", ".", "format", "(", "int", "(", "time", ".", "time", "(", ")", ")", ")", "self", ".", "device", ".", "send", "(", "self", ".", "rollback_cmd", ".", "format", "(", "label", ")", ",", "timeout", "=", "120", ")", "return", "cm_label" ]
Rollback config.
[ "Rollback", "config", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/drivers/XR.py#L145-L149
train
ajdavis/GreenletProfiler
GreenletProfiler.py
start
def start(builtins=False, profile_threads=True): """Starts profiling all threads and all greenlets. This function can be called from any thread at any time. Resumes profiling if stop() was called previously. * `builtins`: Profile builtin functions used by standart Python modules. * `profile_threads`: Profile all threads if ``True``, else profile only the calling thread. """ # TODO: what about builtins False or profile_threads False? _vendorized_yappi.yappi.set_context_id_callback( lambda: greenlet and id(greenlet.getcurrent()) or 0) _vendorized_yappi.yappi.set_context_name_callback( lambda: greenlet and greenlet.getcurrent().__class__.__name__ or '') _vendorized_yappi.yappi.start(builtins, profile_threads)
python
def start(builtins=False, profile_threads=True): """Starts profiling all threads and all greenlets. This function can be called from any thread at any time. Resumes profiling if stop() was called previously. * `builtins`: Profile builtin functions used by standart Python modules. * `profile_threads`: Profile all threads if ``True``, else profile only the calling thread. """ # TODO: what about builtins False or profile_threads False? _vendorized_yappi.yappi.set_context_id_callback( lambda: greenlet and id(greenlet.getcurrent()) or 0) _vendorized_yappi.yappi.set_context_name_callback( lambda: greenlet and greenlet.getcurrent().__class__.__name__ or '') _vendorized_yappi.yappi.start(builtins, profile_threads)
[ "def", "start", "(", "builtins", "=", "False", ",", "profile_threads", "=", "True", ")", ":", "# TODO: what about builtins False or profile_threads False?", "_vendorized_yappi", ".", "yappi", ".", "set_context_id_callback", "(", "lambda", ":", "greenlet", "and", "id", "(", "greenlet", ".", "getcurrent", "(", ")", ")", "or", "0", ")", "_vendorized_yappi", ".", "yappi", ".", "set_context_name_callback", "(", "lambda", ":", "greenlet", "and", "greenlet", ".", "getcurrent", "(", ")", ".", "__class__", ".", "__name__", "or", "''", ")", "_vendorized_yappi", ".", "yappi", ".", "start", "(", "builtins", ",", "profile_threads", ")" ]
Starts profiling all threads and all greenlets. This function can be called from any thread at any time. Resumes profiling if stop() was called previously. * `builtins`: Profile builtin functions used by standart Python modules. * `profile_threads`: Profile all threads if ``True``, else profile only the calling thread.
[ "Starts", "profiling", "all", "threads", "and", "all", "greenlets", "." ]
700349864a4f368a8a73a2a60f048c2e818d7cea
https://github.com/ajdavis/GreenletProfiler/blob/700349864a4f368a8a73a2a60f048c2e818d7cea/GreenletProfiler.py#L18-L35
train
kstaniek/condoor
condoor/protocols/telnet.py
Telnet.connect
def connect(self, driver): """Connect using the Telnet protocol specific FSM.""" # 0 1 2 3 events = [ESCAPE_CHAR, driver.press_return_re, driver.standby_re, driver.username_re, # 4 5 6 7 driver.password_re, driver.more_re, self.device.prompt_re, driver.rommon_re, # 8 9 10 11 12 driver.unable_to_connect_re, driver.timeout_re, pexpect.TIMEOUT, PASSWORD_OK, driver.syntax_error_re] transitions = [ (ESCAPE_CHAR, [0], 1, None, _C['esc_char_timeout']), (driver.syntax_error_re, [0], -1, CommandSyntaxError("Command syntax error"), 0), (driver.press_return_re, [0, 1], 1, a_send_newline, 10), (PASSWORD_OK, [0, 1], 1, a_send_newline, 10), (driver.standby_re, [0, 5], -1, partial(a_standby_console), 0), (driver.username_re, [0, 1, 5, 6], -1, partial(a_save_last_pattern, self), 0), (driver.password_re, [0, 1, 5], -1, partial(a_save_last_pattern, self), 0), (driver.more_re, [0, 5], 7, partial(a_send, "q"), 10), # router sends it again to delete (driver.more_re, [7], 8, None, 10), # (prompt, [0, 1, 5], 6, a_send_newline, 10), (self.device.prompt_re, [0, 1, 5], 0, None, 10), (self.device.prompt_re, [6, 8, 5], -1, partial(a_save_last_pattern, self), 0), (driver.rommon_re, [0, 1, 5], -1, partial(a_save_last_pattern, self), 0), (driver.unable_to_connect_re, [0, 1, 5], -1, a_unable_to_connect, 0), (driver.timeout_re, [0, 1, 5], -1, ConnectionTimeoutError("Connection Timeout", self.hostname), 0), (pexpect.TIMEOUT, [0, 1], 5, a_send_newline, 10), (pexpect.TIMEOUT, [5], -1, ConnectionTimeoutError("Connection timeout", self.hostname), 0) ] self.log("EXPECTED_PROMPT={}".format(pattern_to_str(self.device.prompt_re))) # setting max_transitions to large number to swallow prompt like strings from prompt fsm = FSM("TELNET-CONNECT", self.device, events, transitions, timeout=_C['connect_timeout'], init_pattern=self.last_pattern, max_transitions=500) return fsm.run()
python
def connect(self, driver): """Connect using the Telnet protocol specific FSM.""" # 0 1 2 3 events = [ESCAPE_CHAR, driver.press_return_re, driver.standby_re, driver.username_re, # 4 5 6 7 driver.password_re, driver.more_re, self.device.prompt_re, driver.rommon_re, # 8 9 10 11 12 driver.unable_to_connect_re, driver.timeout_re, pexpect.TIMEOUT, PASSWORD_OK, driver.syntax_error_re] transitions = [ (ESCAPE_CHAR, [0], 1, None, _C['esc_char_timeout']), (driver.syntax_error_re, [0], -1, CommandSyntaxError("Command syntax error"), 0), (driver.press_return_re, [0, 1], 1, a_send_newline, 10), (PASSWORD_OK, [0, 1], 1, a_send_newline, 10), (driver.standby_re, [0, 5], -1, partial(a_standby_console), 0), (driver.username_re, [0, 1, 5, 6], -1, partial(a_save_last_pattern, self), 0), (driver.password_re, [0, 1, 5], -1, partial(a_save_last_pattern, self), 0), (driver.more_re, [0, 5], 7, partial(a_send, "q"), 10), # router sends it again to delete (driver.more_re, [7], 8, None, 10), # (prompt, [0, 1, 5], 6, a_send_newline, 10), (self.device.prompt_re, [0, 1, 5], 0, None, 10), (self.device.prompt_re, [6, 8, 5], -1, partial(a_save_last_pattern, self), 0), (driver.rommon_re, [0, 1, 5], -1, partial(a_save_last_pattern, self), 0), (driver.unable_to_connect_re, [0, 1, 5], -1, a_unable_to_connect, 0), (driver.timeout_re, [0, 1, 5], -1, ConnectionTimeoutError("Connection Timeout", self.hostname), 0), (pexpect.TIMEOUT, [0, 1], 5, a_send_newline, 10), (pexpect.TIMEOUT, [5], -1, ConnectionTimeoutError("Connection timeout", self.hostname), 0) ] self.log("EXPECTED_PROMPT={}".format(pattern_to_str(self.device.prompt_re))) # setting max_transitions to large number to swallow prompt like strings from prompt fsm = FSM("TELNET-CONNECT", self.device, events, transitions, timeout=_C['connect_timeout'], init_pattern=self.last_pattern, max_transitions=500) return fsm.run()
[ "def", "connect", "(", "self", ",", "driver", ")", ":", "# 0 1 2 3", "events", "=", "[", "ESCAPE_CHAR", ",", "driver", ".", "press_return_re", ",", "driver", ".", "standby_re", ",", "driver", ".", "username_re", ",", "# 4 5 6 7", "driver", ".", "password_re", ",", "driver", ".", "more_re", ",", "self", ".", "device", ".", "prompt_re", ",", "driver", ".", "rommon_re", ",", "# 8 9 10 11 12", "driver", ".", "unable_to_connect_re", ",", "driver", ".", "timeout_re", ",", "pexpect", ".", "TIMEOUT", ",", "PASSWORD_OK", ",", "driver", ".", "syntax_error_re", "]", "transitions", "=", "[", "(", "ESCAPE_CHAR", ",", "[", "0", "]", ",", "1", ",", "None", ",", "_C", "[", "'esc_char_timeout'", "]", ")", ",", "(", "driver", ".", "syntax_error_re", ",", "[", "0", "]", ",", "-", "1", ",", "CommandSyntaxError", "(", "\"Command syntax error\"", ")", ",", "0", ")", ",", "(", "driver", ".", "press_return_re", ",", "[", "0", ",", "1", "]", ",", "1", ",", "a_send_newline", ",", "10", ")", ",", "(", "PASSWORD_OK", ",", "[", "0", ",", "1", "]", ",", "1", ",", "a_send_newline", ",", "10", ")", ",", "(", "driver", ".", "standby_re", ",", "[", "0", ",", "5", "]", ",", "-", "1", ",", "partial", "(", "a_standby_console", ")", ",", "0", ")", ",", "(", "driver", ".", "username_re", ",", "[", "0", ",", "1", ",", "5", ",", "6", "]", ",", "-", "1", ",", "partial", "(", "a_save_last_pattern", ",", "self", ")", ",", "0", ")", ",", "(", "driver", ".", "password_re", ",", "[", "0", ",", "1", ",", "5", "]", ",", "-", "1", ",", "partial", "(", "a_save_last_pattern", ",", "self", ")", ",", "0", ")", ",", "(", "driver", ".", "more_re", ",", "[", "0", ",", "5", "]", ",", "7", ",", "partial", "(", "a_send", ",", "\"q\"", ")", ",", "10", ")", ",", "# router sends it again to delete", "(", "driver", ".", "more_re", ",", "[", "7", "]", ",", "8", ",", "None", ",", "10", ")", ",", "# (prompt, [0, 1, 5], 6, a_send_newline, 10),", "(", "self", ".", "device", ".", "prompt_re", ",", "[", "0", ",", "1", ",", "5", "]", ",", "0", ",", "None", ",", "10", ")", ",", "(", "self", ".", "device", ".", "prompt_re", ",", "[", "6", ",", "8", ",", "5", "]", ",", "-", "1", ",", "partial", "(", "a_save_last_pattern", ",", "self", ")", ",", "0", ")", ",", "(", "driver", ".", "rommon_re", ",", "[", "0", ",", "1", ",", "5", "]", ",", "-", "1", ",", "partial", "(", "a_save_last_pattern", ",", "self", ")", ",", "0", ")", ",", "(", "driver", ".", "unable_to_connect_re", ",", "[", "0", ",", "1", ",", "5", "]", ",", "-", "1", ",", "a_unable_to_connect", ",", "0", ")", ",", "(", "driver", ".", "timeout_re", ",", "[", "0", ",", "1", ",", "5", "]", ",", "-", "1", ",", "ConnectionTimeoutError", "(", "\"Connection Timeout\"", ",", "self", ".", "hostname", ")", ",", "0", ")", ",", "(", "pexpect", ".", "TIMEOUT", ",", "[", "0", ",", "1", "]", ",", "5", ",", "a_send_newline", ",", "10", ")", ",", "(", "pexpect", ".", "TIMEOUT", ",", "[", "5", "]", ",", "-", "1", ",", "ConnectionTimeoutError", "(", "\"Connection timeout\"", ",", "self", ".", "hostname", ")", ",", "0", ")", "]", "self", ".", "log", "(", "\"EXPECTED_PROMPT={}\"", ".", "format", "(", "pattern_to_str", "(", "self", ".", "device", ".", "prompt_re", ")", ")", ")", "# setting max_transitions to large number to swallow prompt like strings from prompt", "fsm", "=", "FSM", "(", "\"TELNET-CONNECT\"", ",", "self", ".", "device", ",", "events", ",", "transitions", ",", "timeout", "=", "_C", "[", "'connect_timeout'", "]", ",", "init_pattern", "=", "self", ".", "last_pattern", ",", "max_transitions", "=", "500", ")", "return", "fsm", ".", "run", "(", ")" ]
Connect using the Telnet protocol specific FSM.
[ "Connect", "using", "the", "Telnet", "protocol", "specific", "FSM", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/protocols/telnet.py#L37-L71
train
kstaniek/condoor
condoor/protocols/telnet.py
TelnetConsole.disconnect
def disconnect(self, driver): """Disconnect from the console.""" self.log("TELNETCONSOLE disconnect") try: while self.device.mode != 'global': self.device.send('exit', timeout=10) except OSError: self.log("TELNETCONSOLE already disconnected") except pexpect.TIMEOUT: self.log("TELNETCONSOLE unable to get the root prompt") try: self.device.ctrl.send(chr(4)) except OSError: self.log("TELNETCONSOLE already disconnected")
python
def disconnect(self, driver): """Disconnect from the console.""" self.log("TELNETCONSOLE disconnect") try: while self.device.mode != 'global': self.device.send('exit', timeout=10) except OSError: self.log("TELNETCONSOLE already disconnected") except pexpect.TIMEOUT: self.log("TELNETCONSOLE unable to get the root prompt") try: self.device.ctrl.send(chr(4)) except OSError: self.log("TELNETCONSOLE already disconnected")
[ "def", "disconnect", "(", "self", ",", "driver", ")", ":", "self", ".", "log", "(", "\"TELNETCONSOLE disconnect\"", ")", "try", ":", "while", "self", ".", "device", ".", "mode", "!=", "'global'", ":", "self", ".", "device", ".", "send", "(", "'exit'", ",", "timeout", "=", "10", ")", "except", "OSError", ":", "self", ".", "log", "(", "\"TELNETCONSOLE already disconnected\"", ")", "except", "pexpect", ".", "TIMEOUT", ":", "self", ".", "log", "(", "\"TELNETCONSOLE unable to get the root prompt\"", ")", "try", ":", "self", ".", "device", ".", "ctrl", ".", "send", "(", "chr", "(", "4", ")", ")", "except", "OSError", ":", "self", ".", "log", "(", "\"TELNETCONSOLE already disconnected\"", ")" ]
Disconnect from the console.
[ "Disconnect", "from", "the", "console", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/protocols/telnet.py#L147-L161
train
happyleavesaoc/aoc-mgz
mgz/recorded_game/__init__.py
_calculate_apm
def _calculate_apm(index, player_actions, other_actions, duration): """Calculate player's rAPM.""" apm_per_player = {} for player_index, histogram in player_actions.items(): apm_per_player[player_index] = sum(histogram.values()) total_unattributed = sum(other_actions.values()) total_attributed = sum(apm_per_player.values()) player_proportion = apm_per_player[index] / total_attributed player_unattributed = total_unattributed * player_proportion apm = (apm_per_player[index] + player_unattributed) / (duration / 60) return int(apm)
python
def _calculate_apm(index, player_actions, other_actions, duration): """Calculate player's rAPM.""" apm_per_player = {} for player_index, histogram in player_actions.items(): apm_per_player[player_index] = sum(histogram.values()) total_unattributed = sum(other_actions.values()) total_attributed = sum(apm_per_player.values()) player_proportion = apm_per_player[index] / total_attributed player_unattributed = total_unattributed * player_proportion apm = (apm_per_player[index] + player_unattributed) / (duration / 60) return int(apm)
[ "def", "_calculate_apm", "(", "index", ",", "player_actions", ",", "other_actions", ",", "duration", ")", ":", "apm_per_player", "=", "{", "}", "for", "player_index", ",", "histogram", "in", "player_actions", ".", "items", "(", ")", ":", "apm_per_player", "[", "player_index", "]", "=", "sum", "(", "histogram", ".", "values", "(", ")", ")", "total_unattributed", "=", "sum", "(", "other_actions", ".", "values", "(", ")", ")", "total_attributed", "=", "sum", "(", "apm_per_player", ".", "values", "(", ")", ")", "player_proportion", "=", "apm_per_player", "[", "index", "]", "/", "total_attributed", "player_unattributed", "=", "total_unattributed", "*", "player_proportion", "apm", "=", "(", "apm_per_player", "[", "index", "]", "+", "player_unattributed", ")", "/", "(", "duration", "/", "60", ")", "return", "int", "(", "apm", ")" ]
Calculate player's rAPM.
[ "Calculate", "player", "s", "rAPM", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L59-L69
train
happyleavesaoc/aoc-mgz
mgz/recorded_game/__init__.py
guess_finished
def guess_finished(summary, postgame): """Sometimes a game is finished, but not recorded as such.""" if postgame and postgame.complete: return True for player in summary['players']: if 'resign' in player['action_histogram']: return True return False
python
def guess_finished(summary, postgame): """Sometimes a game is finished, but not recorded as such.""" if postgame and postgame.complete: return True for player in summary['players']: if 'resign' in player['action_histogram']: return True return False
[ "def", "guess_finished", "(", "summary", ",", "postgame", ")", ":", "if", "postgame", "and", "postgame", ".", "complete", ":", "return", "True", "for", "player", "in", "summary", "[", "'players'", "]", ":", "if", "'resign'", "in", "player", "[", "'action_histogram'", "]", ":", "return", "True", "return", "False" ]
Sometimes a game is finished, but not recorded as such.
[ "Sometimes", "a", "game", "is", "finished", "but", "not", "recorded", "as", "such", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L72-L79
train
happyleavesaoc/aoc-mgz
mgz/recorded_game/__init__.py
RecordedGame._num_players
def _num_players(self): """Compute number of players, both human and computer.""" self._player_num = 0 self._computer_num = 0 for player in self._header.scenario.game_settings.player_info: if player.type == 'human': self._player_num += 1 elif player.type == 'computer': self._computer_num += 1
python
def _num_players(self): """Compute number of players, both human and computer.""" self._player_num = 0 self._computer_num = 0 for player in self._header.scenario.game_settings.player_info: if player.type == 'human': self._player_num += 1 elif player.type == 'computer': self._computer_num += 1
[ "def", "_num_players", "(", "self", ")", ":", "self", ".", "_player_num", "=", "0", "self", ".", "_computer_num", "=", "0", "for", "player", "in", "self", ".", "_header", ".", "scenario", ".", "game_settings", ".", "player_info", ":", "if", "player", ".", "type", "==", "'human'", ":", "self", ".", "_player_num", "+=", "1", "elif", "player", ".", "type", "==", "'computer'", ":", "self", ".", "_computer_num", "+=", "1" ]
Compute number of players, both human and computer.
[ "Compute", "number", "of", "players", "both", "human", "and", "computer", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L124-L132
train
happyleavesaoc/aoc-mgz
mgz/recorded_game/__init__.py
RecordedGame._parse_lobby_chat
def _parse_lobby_chat(self, messages, source, timestamp): """Parse a lobby chat message.""" for message in messages: if message.message_length == 0: continue chat = ChatMessage(message.message, timestamp, self._players(), source=source) self._parse_chat(chat)
python
def _parse_lobby_chat(self, messages, source, timestamp): """Parse a lobby chat message.""" for message in messages: if message.message_length == 0: continue chat = ChatMessage(message.message, timestamp, self._players(), source=source) self._parse_chat(chat)
[ "def", "_parse_lobby_chat", "(", "self", ",", "messages", ",", "source", ",", "timestamp", ")", ":", "for", "message", "in", "messages", ":", "if", "message", ".", "message_length", "==", "0", ":", "continue", "chat", "=", "ChatMessage", "(", "message", ".", "message", ",", "timestamp", ",", "self", ".", "_players", "(", ")", ",", "source", "=", "source", ")", "self", ".", "_parse_chat", "(", "chat", ")" ]
Parse a lobby chat message.
[ "Parse", "a", "lobby", "chat", "message", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L134-L140
train
happyleavesaoc/aoc-mgz
mgz/recorded_game/__init__.py
RecordedGame._parse_action
def _parse_action(self, action, current_time): """Parse a player action. TODO: handle cancels """ if action.action_type == 'research': name = mgz.const.TECHNOLOGIES[action.data.technology_type] self._research[action.data.player_id].append({ 'technology': name, 'timestamp': _timestamp_to_time(action.timestamp) }) elif action.action_type == 'build': self._build[action.data.player_id].append({ 'building': mgz.const.UNITS[action.data.building_type], 'timestamp': _timestamp_to_time(current_time), 'coordinates': {'x': action.data.x, 'y': action.data.y} }) elif action.action_type == 'queue': for _ in range(0, int(action.data.number)): self._queue.append({ 'unit': mgz.const.UNITS[action.data.unit_type], 'timestamp': _timestamp_to_time(current_time) })
python
def _parse_action(self, action, current_time): """Parse a player action. TODO: handle cancels """ if action.action_type == 'research': name = mgz.const.TECHNOLOGIES[action.data.technology_type] self._research[action.data.player_id].append({ 'technology': name, 'timestamp': _timestamp_to_time(action.timestamp) }) elif action.action_type == 'build': self._build[action.data.player_id].append({ 'building': mgz.const.UNITS[action.data.building_type], 'timestamp': _timestamp_to_time(current_time), 'coordinates': {'x': action.data.x, 'y': action.data.y} }) elif action.action_type == 'queue': for _ in range(0, int(action.data.number)): self._queue.append({ 'unit': mgz.const.UNITS[action.data.unit_type], 'timestamp': _timestamp_to_time(current_time) })
[ "def", "_parse_action", "(", "self", ",", "action", ",", "current_time", ")", ":", "if", "action", ".", "action_type", "==", "'research'", ":", "name", "=", "mgz", ".", "const", ".", "TECHNOLOGIES", "[", "action", ".", "data", ".", "technology_type", "]", "self", ".", "_research", "[", "action", ".", "data", ".", "player_id", "]", ".", "append", "(", "{", "'technology'", ":", "name", ",", "'timestamp'", ":", "_timestamp_to_time", "(", "action", ".", "timestamp", ")", "}", ")", "elif", "action", ".", "action_type", "==", "'build'", ":", "self", ".", "_build", "[", "action", ".", "data", ".", "player_id", "]", ".", "append", "(", "{", "'building'", ":", "mgz", ".", "const", ".", "UNITS", "[", "action", ".", "data", ".", "building_type", "]", ",", "'timestamp'", ":", "_timestamp_to_time", "(", "current_time", ")", ",", "'coordinates'", ":", "{", "'x'", ":", "action", ".", "data", ".", "x", ",", "'y'", ":", "action", ".", "data", ".", "y", "}", "}", ")", "elif", "action", ".", "action_type", "==", "'queue'", ":", "for", "_", "in", "range", "(", "0", ",", "int", "(", "action", ".", "data", ".", "number", ")", ")", ":", "self", ".", "_queue", ".", "append", "(", "{", "'unit'", ":", "mgz", ".", "const", ".", "UNITS", "[", "action", ".", "data", ".", "unit_type", "]", ",", "'timestamp'", ":", "_timestamp_to_time", "(", "current_time", ")", "}", ")" ]
Parse a player action. TODO: handle cancels
[ "Parse", "a", "player", "action", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L142-L164
train
happyleavesaoc/aoc-mgz
mgz/recorded_game/__init__.py
RecordedGame.operations
def operations(self, op_types=None): """Process operation stream.""" if not op_types: op_types = ['message', 'action', 'sync', 'viewlock', 'savedchapter'] while self._handle.tell() < self._eof: current_time = mgz.util.convert_to_timestamp(self._time / 1000) try: operation = mgz.body.operation.parse_stream(self._handle) except (ConstructError, ValueError): raise MgzError('failed to parse body operation') if operation.type == 'action': if operation.action.type in ACTIONS_WITH_PLAYER_ID: counter = self._actions_by_player[operation.action.player_id] counter.update([operation.action.type]) else: self._actions_without_player.update([operation.action.type]) if operation.type == 'action' and isinstance(operation.action.type, int): print(operation.action) if operation.type == 'sync': self._time += operation.time_increment if operation.type == 'action' and operation.action.type == 'postgame': self._postgame = operation if operation.type == 'action': action = Action(operation, current_time) self._parse_action(action, current_time) if operation.type == 'savedchapter': # fix: Don't load messages we already saw in header or prev saved chapters self._parse_lobby_chat(operation.lobby.messages, 'save', current_time) if operation.type == 'viewlock': if operation.type in op_types: yield Viewlock(operation) elif operation.type == 'action' and operation.action.type != 'postgame': if operation.type in op_types: yield Action(operation, current_time) elif ((operation.type == 'message' or operation.type == 'embedded') and operation.subtype == 'chat'): chat = ChatMessage(operation.data.text, current_time, self._players(), self._diplomacy['type'], 'game') self._parse_chat(chat) if operation.type in op_types: yield chat
python
def operations(self, op_types=None): """Process operation stream.""" if not op_types: op_types = ['message', 'action', 'sync', 'viewlock', 'savedchapter'] while self._handle.tell() < self._eof: current_time = mgz.util.convert_to_timestamp(self._time / 1000) try: operation = mgz.body.operation.parse_stream(self._handle) except (ConstructError, ValueError): raise MgzError('failed to parse body operation') if operation.type == 'action': if operation.action.type in ACTIONS_WITH_PLAYER_ID: counter = self._actions_by_player[operation.action.player_id] counter.update([operation.action.type]) else: self._actions_without_player.update([operation.action.type]) if operation.type == 'action' and isinstance(operation.action.type, int): print(operation.action) if operation.type == 'sync': self._time += operation.time_increment if operation.type == 'action' and operation.action.type == 'postgame': self._postgame = operation if operation.type == 'action': action = Action(operation, current_time) self._parse_action(action, current_time) if operation.type == 'savedchapter': # fix: Don't load messages we already saw in header or prev saved chapters self._parse_lobby_chat(operation.lobby.messages, 'save', current_time) if operation.type == 'viewlock': if operation.type in op_types: yield Viewlock(operation) elif operation.type == 'action' and operation.action.type != 'postgame': if operation.type in op_types: yield Action(operation, current_time) elif ((operation.type == 'message' or operation.type == 'embedded') and operation.subtype == 'chat'): chat = ChatMessage(operation.data.text, current_time, self._players(), self._diplomacy['type'], 'game') self._parse_chat(chat) if operation.type in op_types: yield chat
[ "def", "operations", "(", "self", ",", "op_types", "=", "None", ")", ":", "if", "not", "op_types", ":", "op_types", "=", "[", "'message'", ",", "'action'", ",", "'sync'", ",", "'viewlock'", ",", "'savedchapter'", "]", "while", "self", ".", "_handle", ".", "tell", "(", ")", "<", "self", ".", "_eof", ":", "current_time", "=", "mgz", ".", "util", ".", "convert_to_timestamp", "(", "self", ".", "_time", "/", "1000", ")", "try", ":", "operation", "=", "mgz", ".", "body", ".", "operation", ".", "parse_stream", "(", "self", ".", "_handle", ")", "except", "(", "ConstructError", ",", "ValueError", ")", ":", "raise", "MgzError", "(", "'failed to parse body operation'", ")", "if", "operation", ".", "type", "==", "'action'", ":", "if", "operation", ".", "action", ".", "type", "in", "ACTIONS_WITH_PLAYER_ID", ":", "counter", "=", "self", ".", "_actions_by_player", "[", "operation", ".", "action", ".", "player_id", "]", "counter", ".", "update", "(", "[", "operation", ".", "action", ".", "type", "]", ")", "else", ":", "self", ".", "_actions_without_player", ".", "update", "(", "[", "operation", ".", "action", ".", "type", "]", ")", "if", "operation", ".", "type", "==", "'action'", "and", "isinstance", "(", "operation", ".", "action", ".", "type", ",", "int", ")", ":", "print", "(", "operation", ".", "action", ")", "if", "operation", ".", "type", "==", "'sync'", ":", "self", ".", "_time", "+=", "operation", ".", "time_increment", "if", "operation", ".", "type", "==", "'action'", "and", "operation", ".", "action", ".", "type", "==", "'postgame'", ":", "self", ".", "_postgame", "=", "operation", "if", "operation", ".", "type", "==", "'action'", ":", "action", "=", "Action", "(", "operation", ",", "current_time", ")", "self", ".", "_parse_action", "(", "action", ",", "current_time", ")", "if", "operation", ".", "type", "==", "'savedchapter'", ":", "# fix: Don't load messages we already saw in header or prev saved chapters", "self", ".", "_parse_lobby_chat", "(", "operation", ".", "lobby", ".", "messages", ",", "'save'", ",", "current_time", ")", "if", "operation", ".", "type", "==", "'viewlock'", ":", "if", "operation", ".", "type", "in", "op_types", ":", "yield", "Viewlock", "(", "operation", ")", "elif", "operation", ".", "type", "==", "'action'", "and", "operation", ".", "action", ".", "type", "!=", "'postgame'", ":", "if", "operation", ".", "type", "in", "op_types", ":", "yield", "Action", "(", "operation", ",", "current_time", ")", "elif", "(", "(", "operation", ".", "type", "==", "'message'", "or", "operation", ".", "type", "==", "'embedded'", ")", "and", "operation", ".", "subtype", "==", "'chat'", ")", ":", "chat", "=", "ChatMessage", "(", "operation", ".", "data", ".", "text", ",", "current_time", ",", "self", ".", "_players", "(", ")", ",", "self", ".", "_diplomacy", "[", "'type'", "]", ",", "'game'", ")", "self", ".", "_parse_chat", "(", "chat", ")", "if", "operation", ".", "type", "in", "op_types", ":", "yield", "chat" ]
Process operation stream.
[ "Process", "operation", "stream", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L167-L207
train
happyleavesaoc/aoc-mgz
mgz/recorded_game/__init__.py
RecordedGame.summarize
def summarize(self): """Summarize game.""" if not self._achievements_summarized: for _ in self.operations(): pass self._summarize() return self._summary
python
def summarize(self): """Summarize game.""" if not self._achievements_summarized: for _ in self.operations(): pass self._summarize() return self._summary
[ "def", "summarize", "(", "self", ")", ":", "if", "not", "self", ".", "_achievements_summarized", ":", "for", "_", "in", "self", ".", "operations", "(", ")", ":", "pass", "self", ".", "_summarize", "(", ")", "return", "self", ".", "_summary" ]
Summarize game.
[ "Summarize", "game", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L214-L220
train
happyleavesaoc/aoc-mgz
mgz/recorded_game/__init__.py
RecordedGame.is_nomad
def is_nomad(self): """Is this game nomad. TODO: Can we get from UP 1.4 achievements? """ nomad = self._header.initial.restore_time == 0 or None for i in range(1, self._header.replay.num_players): for obj in self._header.initial.players[i].objects: if obj.type == 'building' and obj.object_type == 'tc_1': return False return nomad
python
def is_nomad(self): """Is this game nomad. TODO: Can we get from UP 1.4 achievements? """ nomad = self._header.initial.restore_time == 0 or None for i in range(1, self._header.replay.num_players): for obj in self._header.initial.players[i].objects: if obj.type == 'building' and obj.object_type == 'tc_1': return False return nomad
[ "def", "is_nomad", "(", "self", ")", ":", "nomad", "=", "self", ".", "_header", ".", "initial", ".", "restore_time", "==", "0", "or", "None", "for", "i", "in", "range", "(", "1", ",", "self", ".", "_header", ".", "replay", ".", "num_players", ")", ":", "for", "obj", "in", "self", ".", "_header", ".", "initial", ".", "players", "[", "i", "]", ".", "objects", ":", "if", "obj", ".", "type", "==", "'building'", "and", "obj", ".", "object_type", "==", "'tc_1'", ":", "return", "False", "return", "nomad" ]
Is this game nomad. TODO: Can we get from UP 1.4 achievements?
[ "Is", "this", "game", "nomad", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L222-L232
train
happyleavesaoc/aoc-mgz
mgz/recorded_game/__init__.py
RecordedGame.is_regicide
def is_regicide(self): """Is this game regicide.""" for i in range(1, self._header.replay.num_players): for obj in self._header.initial.players[i].objects: if obj.type == 'unit' and obj.object_type == 'king': return True return False
python
def is_regicide(self): """Is this game regicide.""" for i in range(1, self._header.replay.num_players): for obj in self._header.initial.players[i].objects: if obj.type == 'unit' and obj.object_type == 'king': return True return False
[ "def", "is_regicide", "(", "self", ")", ":", "for", "i", "in", "range", "(", "1", ",", "self", ".", "_header", ".", "replay", ".", "num_players", ")", ":", "for", "obj", "in", "self", ".", "_header", ".", "initial", ".", "players", "[", "i", "]", ".", "objects", ":", "if", "obj", ".", "type", "==", "'unit'", "and", "obj", ".", "object_type", "==", "'king'", ":", "return", "True", "return", "False" ]
Is this game regicide.
[ "Is", "this", "game", "regicide", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L234-L240
train
happyleavesaoc/aoc-mgz
mgz/recorded_game/__init__.py
RecordedGame._parse_chat
def _parse_chat(self, chat): """Parse a chat message.""" if chat.data['type'] == 'chat': if chat.data['player'] in [p.player_name for i, p in self._players()]: self._chat.append(chat.data) elif chat.data['type'] == 'ladder': self._ladder = chat.data['ladder'] elif chat.data['type'] == 'rating': if chat.data['rating'] != 1600: self._ratings[chat.data['player']] = chat.data['rating']
python
def _parse_chat(self, chat): """Parse a chat message.""" if chat.data['type'] == 'chat': if chat.data['player'] in [p.player_name for i, p in self._players()]: self._chat.append(chat.data) elif chat.data['type'] == 'ladder': self._ladder = chat.data['ladder'] elif chat.data['type'] == 'rating': if chat.data['rating'] != 1600: self._ratings[chat.data['player']] = chat.data['rating']
[ "def", "_parse_chat", "(", "self", ",", "chat", ")", ":", "if", "chat", ".", "data", "[", "'type'", "]", "==", "'chat'", ":", "if", "chat", ".", "data", "[", "'player'", "]", "in", "[", "p", ".", "player_name", "for", "i", ",", "p", "in", "self", ".", "_players", "(", ")", "]", ":", "self", ".", "_chat", ".", "append", "(", "chat", ".", "data", ")", "elif", "chat", ".", "data", "[", "'type'", "]", "==", "'ladder'", ":", "self", ".", "_ladder", "=", "chat", ".", "data", "[", "'ladder'", "]", "elif", "chat", ".", "data", "[", "'type'", "]", "==", "'rating'", ":", "if", "chat", ".", "data", "[", "'rating'", "]", "!=", "1600", ":", "self", ".", "_ratings", "[", "chat", ".", "data", "[", "'player'", "]", "]", "=", "chat", ".", "data", "[", "'rating'", "]" ]
Parse a chat message.
[ "Parse", "a", "chat", "message", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L253-L262
train
happyleavesaoc/aoc-mgz
mgz/recorded_game/__init__.py
RecordedGame._compass_position
def _compass_position(self, player_x, player_y): """Get compass position of player.""" map_dim = self._map.size_x third = map_dim * (1/3.0) for direction in mgz.const.COMPASS: point = mgz.const.COMPASS[direction] xlower = point[0] * map_dim xupper = (point[0] * map_dim) + third ylower = point[1] * map_dim yupper = (point[1] * map_dim) + third if (player_x >= xlower and player_x < xupper and player_y >= ylower and player_y < yupper): return direction
python
def _compass_position(self, player_x, player_y): """Get compass position of player.""" map_dim = self._map.size_x third = map_dim * (1/3.0) for direction in mgz.const.COMPASS: point = mgz.const.COMPASS[direction] xlower = point[0] * map_dim xupper = (point[0] * map_dim) + third ylower = point[1] * map_dim yupper = (point[1] * map_dim) + third if (player_x >= xlower and player_x < xupper and player_y >= ylower and player_y < yupper): return direction
[ "def", "_compass_position", "(", "self", ",", "player_x", ",", "player_y", ")", ":", "map_dim", "=", "self", ".", "_map", ".", "size_x", "third", "=", "map_dim", "*", "(", "1", "/", "3.0", ")", "for", "direction", "in", "mgz", ".", "const", ".", "COMPASS", ":", "point", "=", "mgz", ".", "const", ".", "COMPASS", "[", "direction", "]", "xlower", "=", "point", "[", "0", "]", "*", "map_dim", "xupper", "=", "(", "point", "[", "0", "]", "*", "map_dim", ")", "+", "third", "ylower", "=", "point", "[", "1", "]", "*", "map_dim", "yupper", "=", "(", "point", "[", "1", "]", "*", "map_dim", ")", "+", "third", "if", "(", "player_x", ">=", "xlower", "and", "player_x", "<", "xupper", "and", "player_y", ">=", "ylower", "and", "player_y", "<", "yupper", ")", ":", "return", "direction" ]
Get compass position of player.
[ "Get", "compass", "position", "of", "player", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L340-L352
train
happyleavesaoc/aoc-mgz
mgz/recorded_game/__init__.py
RecordedGame._players
def _players(self): """Get player attributes with index. No Gaia.""" for i in range(1, self._header.replay.num_players): yield i, self._header.initial.players[i].attributes
python
def _players(self): """Get player attributes with index. No Gaia.""" for i in range(1, self._header.replay.num_players): yield i, self._header.initial.players[i].attributes
[ "def", "_players", "(", "self", ")", ":", "for", "i", "in", "range", "(", "1", ",", "self", ".", "_header", ".", "replay", ".", "num_players", ")", ":", "yield", "i", ",", "self", ".", "_header", ".", "initial", ".", "players", "[", "i", "]", ".", "attributes" ]
Get player attributes with index. No Gaia.
[ "Get", "player", "attributes", "with", "index", ".", "No", "Gaia", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L354-L357
train
happyleavesaoc/aoc-mgz
mgz/recorded_game/__init__.py
RecordedGame.players
def players(self, postgame, game_type): """Return parsed players.""" for i, attributes in self._players(): yield self._parse_player(i, attributes, postgame, game_type)
python
def players(self, postgame, game_type): """Return parsed players.""" for i, attributes in self._players(): yield self._parse_player(i, attributes, postgame, game_type)
[ "def", "players", "(", "self", ",", "postgame", ",", "game_type", ")", ":", "for", "i", ",", "attributes", "in", "self", ".", "_players", "(", ")", ":", "yield", "self", ".", "_parse_player", "(", "i", ",", "attributes", ",", "postgame", ",", "game_type", ")" ]
Return parsed players.
[ "Return", "parsed", "players", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L359-L362
train