text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_jump_target_maps(code, opc):
"""Returns a dictionary where the key is an offset and the values are a list of instruction offsets which can get run before that instruction. This includes jump instructions as well as non-jump instructions. Therefore, the keys of the dictionary are reachable instructions. The values of the dictionary may be useful in control-flow analysis. """ |
offset2prev = {}
prev_offset = -1
for offset, op, arg in unpack_opargs_bytecode(code, opc):
if prev_offset >= 0:
prev_list = offset2prev.get(offset, [])
prev_list.append(prev_offset)
offset2prev[offset] = prev_list
if op in opc.NOFOLLOW:
prev_offset = -1
else:
prev_offset = offset
if arg is not None:
jump_offset = -1
if op in opc.JREL_OPS:
op_len = op_size(op, opc)
jump_offset = offset + op_len + arg
elif op in opc.JABS_OPS:
jump_offset = arg
if jump_offset >= 0:
prev_list = offset2prev.get(jump_offset, [])
prev_list.append(offset)
offset2prev[jump_offset] = prev_list
return offset2prev |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_const_info(const_index, const_list):
"""Helper to get optional details about const references Returns the dereferenced constant and its repr if the constant list is defined. Otherwise returns the constant index and its repr(). """ |
argval = const_index
if const_list is not None:
argval = const_list[const_index]
# float values nan and inf are not directly representable in Python at least
# before 3.5 and even there it is via a library constant.
# So we will canonicalize their representation as float('nan') and float('inf')
if isinstance(argval, float) and str(argval) in frozenset(['nan', '-nan', 'inf', '-inf']):
return argval, "float('%s')" % argval
return argval, repr(argval) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_name_info(name_index, name_list):
"""Helper to get optional details about named references Returns the dereferenced name as both value and repr if the name list is defined. Otherwise returns the name index and its repr(). """ |
argval = name_index
if (name_list is not None
# PyPY seems to "optimize" out constant names,
# so we need for that:
and name_index < len(name_list)):
argval = name_list[name_index]
argrepr = argval
else:
argrepr = repr(argval)
return argval, argrepr |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instruction_size(op, opc):
"""For a given opcode, `op`, in opcode module `opc`, return the size, in bytes, of an `op` instruction. This is the size of the opcode (1 byte) and any operand it has. In Python before version 3.6 this will be either 1 or 3 bytes. In Python 3.6 or later, it is 2 bytes or a "word".""" |
if op < opc.HAVE_ARGUMENT:
return 2 if opc.version >= 3.6 else 1
else:
return 2 if opc.version >= 3.6 else 3 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disassemble(self, lineno_width=3, mark_as_current=False, asm_format=False, show_bytes=False):
"""Format instruction details for inclusion in disassembly output *lineno_width* sets the width of the line number field (0 omits it) *mark_as_current* inserts a '-->' marker arrow as part of the line """ |
fields = []
if asm_format:
indexed_operand = set(['name', 'local', 'compare', 'free'])
# Column: Source code line number
if lineno_width:
if self.starts_line is not None:
if asm_format:
lineno_fmt = "%%%dd:\n" % lineno_width
fields.append(lineno_fmt % self.starts_line)
fields.append(' ' * (lineno_width))
if self.is_jump_target:
fields.append(' ' * (lineno_width-1))
else:
lineno_fmt = "%%%dd:" % lineno_width
fields.append(lineno_fmt % self.starts_line)
else:
fields.append(' ' * (lineno_width+1))
# Column: Current instruction indicator
if mark_as_current and not asm_format:
fields.append('-->')
else:
fields.append(' ')
# Column: Jump target marker
if self.is_jump_target:
if not asm_format:
fields.append('>>')
else:
fields = ["L%d:\n" % self.offset] + fields
if not self.starts_line:
fields.append(' ')
else:
fields.append(' ')
# Column: Instruction offset from start of code sequence
if not asm_format:
fields.append(repr(self.offset).rjust(4))
if show_bytes:
hex_bytecode = "|%02x" % self.opcode
if self.inst_size == 1:
# Not 3.6 or later
hex_bytecode += ' ' * (2*3)
if self.inst_size == 2:
# Must by Python 3.6 or later
if self.has_arg:
hex_bytecode += " %02x" % (self.arg % 256)
else :
hex_bytecode += ' 00'
elif self.inst_size == 3:
# Not 3.6 or later
hex_bytecode += " %02x %02x" % (
(self.arg >> 8, self.arg % 256))
fields.append(hex_bytecode + '|')
# Column: Opcode name
fields.append(self.opname.ljust(20))
# Column: Opcode argument
if self.arg is not None:
argrepr = self.argrepr
if asm_format:
if self.optype == 'jabs':
fields.append('L' + str(self.arg))
elif self.optype == 'jrel':
argval = self.offset + self.arg + self.inst_size
fields.append('L' + str(argval))
elif self.optype in indexed_operand:
fields.append('(%s)' % argrepr)
argrepr = None
elif (self.optype == 'const'
and not re.search('\s', argrepr)):
fields.append('(%s)' % argrepr)
argrepr = None
else:
fields.append(repr(self.arg))
elif not (show_bytes and argrepr):
fields.append(repr(self.arg).rjust(6))
# Column: Opcode argument details
if argrepr:
fields.append('(%s)' % argrepr)
pass
pass
return ' '.join(fields).rstrip() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_traceback(cls, tb):
""" Construct a Bytecode from the given traceback """ |
while tb.tb_next:
tb = tb.tb_next
return cls(tb.tb_frame.f_code, current_offset=tb.tb_lasti) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dis(self, asm_format=False, show_bytes=False):
"""Return a formatted view of the bytecode operations.""" |
co = self.codeobj
if self.current_offset is not None:
offset = self.current_offset
else:
offset = -1
output = StringIO()
self.disassemble_bytes(co.co_code, varnames=co.co_varnames,
names=co.co_names, constants=co.co_consts,
cells=self._cell_names,
linestarts=self._linestarts,
line_offset=self._line_offset,
file=output,
lasti=offset,
asm_format=asm_format,
show_bytes=show_bytes)
return output.getvalue() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_jump_target_maps(code, opc):
"""Returns a dictionary where the key is an offset and the values are a list of instruction offsets which can get run before that instruction. This includes jump instructions as well as non-jump instructions. Therefore, the keys of the dictionary are reachible instructions. The values of the dictionary may be useful in control-flow analysis. """ |
offset2prev = {}
prev_offset = -1
for offset, op, arg in unpack_opargs_wordcode(code, opc):
if prev_offset >= 0:
prev_list = offset2prev.get(offset, [])
prev_list.append(prev_offset)
offset2prev[offset] = prev_list
prev_offset = offset
if op in opc.NOFOLLOW:
prev_offset = -1
if arg is not None:
jump_offset = -1
if op in opc.JREL_OPS:
jump_offset = offset + 2 + arg
elif op in opc.JABS_OPS:
jump_offset = arg
if jump_offset >= 0:
prev_list = offset2prev.get(jump_offset, [])
prev_list.append(offset)
offset2prev[jump_offset] = prev_list
return offset2prev |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dis(self, x=None, file=None):
"""Disassemble classes, methods, functions, generators, or code. With no argument, disassemble the last traceback. """ |
self._print(self.Bytecode(x).dis(), file) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_protocol_from_name(name):
""" Returns the protocol class for the protocol with the given name. :type name: str :param name: The name of the protocol. :rtype: Protocol :return: The protocol class. """ |
cls = protocol_map.get(name)
if not cls:
raise ValueError('Unsupported protocol "%s".' % name)
return cls |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_protocol(name, **kwargs):
""" Returns an instance of the protocol with the given name. :type name: str :param name: The name of the protocol. :rtype: Protocol :return: An instance of the protocol. """ |
cls = protocol_map.get(name)
if not cls:
raise ValueError('Unsupported protocol "%s".' % name)
return cls(**kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _long_from_raw(thehash):
"""Fold to a long, a digest supplied as a string.""" |
hashnum = 0
for h in thehash:
hashnum <<= 8
hashnum |= ord(bytes([h]))
return hashnum |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def aborted(self, exc_info):
""" Called by a logger to log an exception. """ |
self.exc_info = exc_info
self.did_end = True
self.write(format_exception(*self.exc_info)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_file(filename, password='', keytype=None):
""" Returns a new PrivateKey instance with the given attributes. If keytype is None, we attempt to automatically detect the type. :type filename: string :param filename: The key file name. :type password: string :param password: The key password. :type keytype: string :param keytype: The key type. :rtype: PrivateKey :return: The new key. """ |
if keytype is None:
try:
key = RSAKey.from_private_key_file(filename)
keytype = 'rsa'
except SSHException as e:
try:
key = DSSKey.from_private_key_file(filename)
keytype = 'dss'
except SSHException as e:
msg = 'not a recognized private key: ' + repr(filename)
raise ValueError(msg)
key = PrivateKey(keytype)
key.filename = filename
key.password = password
return key |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_uri(self):
""" Returns a URI formatted representation of the host, including all of it's attributes except for the name. Uses the address, not the name of the host to build the URI. :rtype: str :return: A URI. """ |
url = Url()
url.protocol = self.get_protocol()
url.hostname = self.get_address()
url.port = self.get_tcp_port()
url.vars = dict((k, to_list(v))
for (k, v) in list(self.get_all().items())
if isinstance(v, str) or isinstance(v, list))
if self.account:
url.username = self.account.get_name()
url.password1 = self.account.get_password()
url.password2 = self.account.authorization_password
return str(url) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_address(self, address):
""" Set the address of the remote host the is contacted, without changing hostname, username, password, protocol, and TCP port number. This is the actual address that is used to open the connection. :type address: string :param address: A hostname or IP name. """ |
if is_ip(address):
self.address = clean_ip(address)
else:
self.address = address |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_option(self, name, default=None):
""" Returns the value of the given option if it is defined, returns the given default value otherwise. :type name: str :param name: The option name. :type default: object :param default: A default value. """ |
if self.options is None:
return default
return self.options.get(name, default) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_tcp_port(self, tcp_port):
""" Defines the TCP port number. :type tcp_port: int :param tcp_port: The TCP port number. """ |
if tcp_port is None:
self.tcp_port = None
return
self.tcp_port = int(tcp_port) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def append(self, name, value):
""" Appends the given value to the list variable with the given name. :type name: string :param name: The name of the variable. :type value: object :param value: The appended value. """ |
if self.vars is None:
self.vars = {}
if name in self.vars:
self.vars[name].append(value)
else:
self.vars[name] = [value] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, name, default=None):
""" Returns the value of the given variable, or the given default value if the variable is not defined. :type name: string :param name: The name of the variable. :type default: object :param default: The default value. :rtype: object :return: The value of the variable. """ |
if self.vars is None:
return default
return self.vars.get(name, default) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy_labels(src, dst):
""" Copies all labels of one object to another object. :type src: object :param src: The object to check read the labels from. :type dst: object :param dst: The object into which the labels are copied. """ |
labels = src.__dict__.get('_labels')
if labels is None:
return
dst.__dict__['_labels'] = labels.copy() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def serializeable_exc_info(thetype, ex, tb):
""" Since traceback objects can not be pickled, this function manipulates exception info tuples before they are passed accross process boundaries. """ |
return thetype, ex, ''.join(traceback.format_exception(thetype, ex, tb)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deprecated(func):
""" A decorator for marking functions as deprecated. Results in a printed warning message when the function is used. """ |
def decorated(*args, **kwargs):
warnings.warn('Call to deprecated function %s.' % func.__name__,
category=DeprecationWarning,
stacklevel=2)
return func(*args, **kwargs)
decorated.__name__ = func.__name__
decorated.__doc__ = func.__doc__
decorated.__dict__.update(func.__dict__)
return decorated |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def synchronized(func):
""" Decorator for synchronizing method access. """ |
@wraps(func)
def wrapped(self, *args, **kwargs):
try:
rlock = self._sync_lock
except AttributeError:
from multiprocessing import RLock
rlock = self.__dict__.setdefault('_sync_lock', RLock())
with rlock:
return func(self, *args, **kwargs)
return wrapped |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def debug(func):
""" Decorator that prints a message whenever a function is entered or left. """ |
@wraps(func)
def wrapped(*args, **kwargs):
arg = repr(args) + ' ' + repr(kwargs)
sys.stdout.write('Entering ' + func.__name__ + arg + '\n')
try:
result = func(*args, **kwargs)
except:
sys.stdout.write('Traceback caught:\n')
sys.stdout.write(format_exception(*sys.exc_info()))
raise
arg = repr(result)
sys.stdout.write('Leaving ' + func.__name__ + '(): ' + arg + '\n')
return result
return wrapped |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def eval(conn, string, strip_command=True, **kwargs):
""" Compiles the given template and executes it on the given connection. Raises an exception if the compilation fails. if strip_command is True, the first line of each response that is received after any command sent by the template is stripped. For example, consider the following template:: ls -1{extract /(\S+)/ as filenames} {loop filenames as filename} touch $filename {end} If strip_command is False, the response, (and hence, the `filenames' variable) contains the following:: ls -1 myfile myfile2 By setting strip_command to True, the first line is ommitted. :type conn: Exscript.protocols.Protocol :param conn: The connection on which to run the template. :type string: string :param string: The template to compile. :type strip_command: bool :param strip_command: Whether to strip the command echo from the response. :type kwargs: dict :param kwargs: Variables to define in the template. :rtype: dict :return: The variables that are defined after execution of the script. """ |
parser_args = {'strip_command': strip_command}
return _run(conn, None, string, parser_args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _urlparse_qs(url):
""" Parse a URL query string and return the components as a dictionary. Based on the cgi.parse_qs method.This is a utility function provided with urlparse so that users need not use cgi module for parsing the url query string. Arguments: :type url: str :param url: URL with query string to be parsed """ |
# Extract the query part from the URL.
querystring = urlparse(url)[4]
# Split the query into name/value pairs.
pairs = [s2 for s1 in querystring.split('&') for s2 in s1.split(';')]
# Split the name/value pairs.
result = OrderedDefaultDict(list)
for name_value in pairs:
pair = name_value.split('=', 1)
if len(pair) != 2:
continue
if len(pair[1]) > 0:
name = _unquote(pair[0].replace('+', ' '))
value = _unquote(pair[1].replace('+', ' '))
result[name].append(value)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_debug(self, debug=1):
""" Set the debug level. :type debug: int :param debug: The debug level. """ |
self._check_if_ready()
self.debug = debug
self.main_loop.debug = debug |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_max_threads(self, max_threads):
""" Set the maximum number of concurrent threads. :type max_threads: int :param max_threads: The number of threads. """ |
if max_threads is None:
raise TypeError('max_threads must not be None.')
self._check_if_ready()
self.collection.set_max_working(max_threads) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def authorize(scope, password=[None]):
""" Looks for a password prompt on the current connection and enters the given password. If a password is not given, the function uses the same password that was used at the last login attempt; it is an error if no such attempt was made before. :type password: string :param password: A password. """ |
conn = scope.get('__connection__')
password = password[0]
if password is None:
conn.app_authorize()
else:
account = Account('', password)
conn.app_authorize(account)
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def close(scope):
""" Closes the existing connection with the remote host. This function is rarely used, as normally Exscript closes the connection automatically when the script has completed. """ |
conn = scope.get('__connection__')
conn.close(1)
scope.define(__response__=conn.response)
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exec_(scope, data):
""" Sends the given data to the remote host and waits until the host has responded with a prompt. If the given data is a list of strings, each item is sent, and after each item a prompt is expected. This function also causes the response of the command to be stored in the built-in __response__ variable. :type data: string :param data: The data that is sent. """ |
conn = scope.get('__connection__')
response = []
for line in data:
conn.send(line)
conn.expect_prompt()
response += conn.response.split('\n')[1:]
scope.define(__response__=response)
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wait_for(scope, prompt):
""" Waits until the response of the remote host contains the given pattern. :type prompt: regex :param prompt: The prompt pattern. """ |
conn = scope.get('__connection__')
conn.expect(prompt)
scope.define(__response__=conn.response)
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_prompt(scope, prompt=None):
""" Defines the pattern that is recognized at any future time when Exscript needs to wait for a prompt. In other words, whenever Exscript waits for a prompt, it searches the response of the host for the given pattern and continues as soon as the pattern is found. Exscript waits for a prompt whenever it sends a command (unless the send() method was used). set_prompt() redefines as to what is recognized as a prompt. :type prompt: regex :param prompt: The prompt pattern. """ |
conn = scope.get('__connection__')
conn.set_prompt(prompt)
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_error(scope, error_re=None):
""" Defines a pattern that, whenever detected in the response of the remote host, causes an error to be raised. In other words, whenever Exscript waits for a prompt, it searches the response of the host for the given pattern and raises an error if the pattern is found. :type error_re: regex :param error_re: The error pattern. """ |
conn = scope.get('__connection__')
conn.set_error_prompt(error_re)
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_timeout(scope, timeout):
""" Defines the time after which Exscript fails if it does not receive a prompt from the remote host. :type timeout: int :param timeout: The timeout in seconds. """ |
conn = scope.get('__connection__')
conn.set_timeout(int(timeout[0]))
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_command(self, command, handler, prompt=True):
""" Registers a command. The command may be either a string (which is then automatically compiled into a regular expression), or a pre-compiled regular expression object. If the given response handler is a string, it is sent as the response to any command that matches the given regular expression. If the given response handler is a function, it is called with the command passed as an argument. :type command: str|regex :param command: A string or a compiled regular expression. :type handler: function|str :param handler: A string, or a response handler. :type prompt: bool :param prompt: Whether to show a prompt after completing the command. """ |
if prompt:
thehandler = self._create_autoprompt_handler(handler)
else:
thehandler = handler
self.commands.add(command, thehandler) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_commands_from_file(self, filename, autoprompt=True):
""" Wrapper around add_command_handler that reads the handlers from the file with the given name. The file is a Python script containing a list named 'commands' of tuples that map command names to handlers. :type filename: str :param filename: The name of the file containing the tuples. :type autoprompt: bool :param autoprompt: Whether to append a prompt to each response. """ |
if autoprompt:
deco = self._create_autoprompt_handler
else:
deco = None
self.commands.add_from_file(filename, deco) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init(self):
""" Init or reset the virtual device. :rtype: str :return: The initial response of the virtual device. """ |
self.logged_in = False
if self.login_type == self.LOGIN_TYPE_PASSWORDONLY:
self.prompt_stage = self.PROMPT_STAGE_PASSWORD
elif self.login_type == self.LOGIN_TYPE_NONE:
self.prompt_stage = self.PROMPT_STAGE_CUSTOM
else:
self.prompt_stage = self.PROMPT_STAGE_USERNAME
return self.banner + self._get_prompt() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do(self, command):
""" "Executes" the given command on the virtual device, and returns the response. :type command: str :param command: The command to be executed. :rtype: str :return: The response of the virtual device. """ |
echo = self.echo and command or ''
if not self.logged_in:
return echo + '\n' + self._get_prompt()
response = self.commands.eval(command)
if response is None:
return echo + '\n' + self._get_prompt()
return echo + response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_user(prompt=None):
""" Prompts the user for his login name, defaulting to the USER environment variable. Returns a string containing the username. May throw an exception if EOF is given by the user. :type prompt: str|None :param prompt: The user prompt or the default one if None. :rtype: string :return: A username. """ |
# Read username and password.
try:
env_user = getpass.getuser()
except KeyError:
env_user = ''
if prompt is None:
prompt = "Please enter your user name"
if env_user is None or env_user == '':
user = input('%s: ' % prompt)
else:
user = input('%s [%s]: ' % (prompt, env_user))
if user == '':
user = env_user
return user |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, key, default=None):
""" Returns the input with the given key from the section that was passed to the constructor. If either the section or the key are not found, the default value is returned. :type key: str :param key: The key for which to return a value. :type default: str|object :param default: The default value that is returned. :rtype: str|object :return: The value from the config file, or the default. """ |
if not self.parser:
return default
try:
return self.parser.get(self.section, key)
except (configparser.NoSectionError, configparser.NoOptionError):
return default |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set(self, key, value):
""" Saves the input with the given key in the section that was passed to the constructor. If either the section or the key are not found, they are created. Does nothing if the given value is None. :type key: str :param key: The key for which to define a value. :type value: str|None :param value: The value that is defined, or None. :rtype: str|None :return: The given value. """ |
if value is None:
return None
self.parser.set(self.section, key, value)
# Unfortunately ConfigParser attempts to write a string to the file
# object, and NamedTemporaryFile uses binary mode. So we nee to create
# the tempfile, and then re-open it.
with NamedTemporaryFile(delete=False) as tmpfile:
pass
with codecs.open(tmpfile.name, 'w', encoding='utf8') as fp:
self.parser.write(fp)
self.file.close()
shutil.move(tmpfile.name, self.file.name)
self.file = open(self.file.name)
return value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def acquire(self, signal=True):
""" Locks the account. Method has no effect if the constructor argument `needs_lock` wsa set to False. :type signal: bool :param signal: Whether to emit the acquired_event signal. """ |
if not self.needs_lock:
return
with self.synclock:
while not self.lock.acquire(False):
self.synclock.wait()
if signal:
self.acquired_event(self)
self.synclock.notify_all() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def release(self, signal=True):
""" Unlocks the account. Method has no effect if the constructor argument `needs_lock` wsa set to False. :type signal: bool :param signal: Whether to emit the released_event signal. """ |
if not self.needs_lock:
return
with self.synclock:
self.lock.release()
if signal:
self.released_event(self)
self.synclock.notify_all() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_name(self, name):
""" Changes the name of the account. :type name: string :param name: The account name. """ |
self.name = name
self.changed_event.emit(self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_password(self, password):
""" Changes the password of the account. :type password: string :param password: The account password. """ |
self.password = password
self.changed_event.emit(self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_authorization_password(self, password):
""" Changes the authorization password of the account. :type password: string :param password: The new authorization password. """ |
self.authorization_password = password
self.changed_event.emit(self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def for_host(parent, host):
""" Returns a new AccountProxy that has an account acquired. The account is chosen based on what the connected AccountManager selects for the given host. """ |
account = AccountProxy(parent)
account.host = host
if account.acquire():
return account
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def for_account_hash(parent, account_hash):
""" Returns a new AccountProxy that acquires the account with the given hash, if such an account is known to the account manager. It is an error if the account manager does not have such an account. """ |
account = AccountProxy(parent)
account.account_hash = account_hash
if account.acquire():
return account
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def acquire(self):
""" Locks the account. Returns True on success, False if the account is thread-local and must not be locked. """ |
if self.host:
self.parent.send(('acquire-account-for-host', self.host))
elif self.account_hash:
self.parent.send(('acquire-account-from-hash', self.account_hash))
else:
self.parent.send(('acquire-account'))
response = self.parent.recv()
if isinstance(response, Exception):
raise response
if response is None:
return False
self.account_hash, \
self.user, \
self.password, \
self.authorization_password, \
self.key = response
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def release(self):
""" Unlocks the account. """ |
self.parent.send(('release-account', self.account_hash))
response = self.parent.recv()
if isinstance(response, Exception):
raise response
if response != 'ok':
raise ValueError('unexpected response: ' + repr(response)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_account_from_hash(self, account_hash):
""" Returns the account with the given hash, or None if no such account is included in the account pool. """ |
for account in self.accounts:
if account.__hash__() == account_hash:
return account
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_account(self, accounts):
""" Adds one or more account instances to the pool. :type accounts: Account|list[Account] :param accounts: The account to be added. """ |
with self.unlock_cond:
for account in to_list(accounts):
account.acquired_event.listen(self._on_account_acquired)
account.released_event.listen(self._on_account_released)
self.accounts.add(account)
self.unlocked_accounts.append(account)
self.unlock_cond.notify_all() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reset(self):
""" Removes all accounts. """ |
with self.unlock_cond:
for owner in self.owner2account:
self.release_accounts(owner)
self._remove_account(self.accounts.copy())
self.unlock_cond.notify_all() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_account_from_name(self, name):
""" Returns the account with the given name. :type name: string :param name: The name of the account. """ |
for account in self.accounts:
if account.get_name() == name:
return account
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def acquire_account(self, account=None, owner=None):
""" Waits until an account becomes available, then locks and returns it. If an account is not passed, the next available account is returned. :type account: Account :param account: The account to be acquired, or None. :type owner: object :param owner: An optional descriptor for the owner. :rtype: :class:`Account` :return: The account that was acquired. """ |
with self.unlock_cond:
if len(self.accounts) == 0:
raise ValueError('account pool is empty')
if account:
# Specific account requested.
while account not in self.unlocked_accounts:
self.unlock_cond.wait()
self.unlocked_accounts.remove(account)
else:
# Else take the next available one.
while len(self.unlocked_accounts) == 0:
self.unlock_cond.wait()
account = self.unlocked_accounts.popleft()
if owner is not None:
self.owner2account[owner].append(account)
self.account2owner[account] = owner
account.acquire(False)
self.unlock_cond.notify_all()
return account |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_pool(self, pool, match=None):
""" Adds a new account pool. If the given match argument is None, the pool the default pool. Otherwise, the match argument is a callback function that is invoked to decide whether or not the given pool should be used for a host. When Exscript logs into a host, the account is chosen in the following order: # Exscript checks whether an account was attached to the :class:`Host` object using :class:`Host.set_account()`), and uses that. # If the :class:`Host` has no account attached, Exscript walks through all pools that were passed to :class:`Queue.add_account_pool()`. For each pool, it passes the :class:`Host` to the function in the given match argument. If the return value is True, the account pool is used to acquire an account. (Accounts within each pool are taken in a round-robin fashion.) # If no matching account pool is found, an account is taken from the default account pool. # Finally, if all that fails and the default account pool contains no accounts, an error is raised. Example usage:: def do_nothing(conn):
conn.autoinit() def use_this_pool(host):
return host.get_name().startswith('foo') default_pool = AccountPool() default_pool.add_account(Account('default-user', 'password')) other_pool = AccountPool() other_pool.add_account(Account('user', 'password')) queue = Queue() queue.account_manager.add_pool(default_pool) queue.account_manager.add_pool(other_pool, use_this_pool) host = Host('localhost') queue.run(host, do_nothing) In the example code, the host has no account attached. As a result, the queue checks whether use_this_pool() returns True. Because the hostname does not start with 'foo', the function returns False, and Exscript takes the 'default-user' account from the default pool. :type pool: AccountPool :param pool: The account pool that is added. :type match: callable :param match: A callback to check if the pool should be used. """ |
if match is None:
self.default_pool = pool
else:
self.pools.append((match, pool)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_account_from_hash(self, account_hash):
""" Returns the account with the given hash, if it is contained in any of the pools. Returns None otherwise. :type account_hash: str :param account_hash: The hash of an account object. """ |
for _, pool in self.pools:
account = pool.get_account_from_hash(account_hash)
if account is not None:
return account
return self.default_pool.get_account_from_hash(account_hash) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def acquire_account(self, account=None, owner=None):
""" Acquires the given account. If no account is given, one is chosen from the default pool. :type account: Account :param account: The account that is added. :type owner: object :param owner: An optional descriptor for the owner. :rtype: :class:`Account` :return: The account that was acquired. """ |
if account is not None:
for _, pool in self.pools:
if pool.has_account(account):
return pool.acquire_account(account, owner)
if not self.default_pool.has_account(account):
# The account is not in any pool.
account.acquire()
return account
return self.default_pool.acquire_account(account, owner) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def acquire_account_for(self, host, owner=None):
""" Acquires an account for the given host and returns it. The host is passed to each of the match functions that were passed in when adding the pool. The first pool for which the match function returns True is chosen to assign an account. :type host: :class:`Host` :param host: The host for which an account is acquired. :type owner: object :param owner: An optional descriptor for the owner. :rtype: :class:`Account` :return: The account that was acquired. """ |
# Check whether a matching account pool exists.
for match, pool in self.pools:
if match(host) is True:
return pool.acquire_account(owner=owner)
# Else, choose an account from the default account pool.
return self.default_pool.acquire_account(owner=owner) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def eval(self, command):
""" Evaluate the given string against all registered commands and return the defined response. :type command: str :param command: The command that is evaluated. :rtype: str or None :return: The response, if one was defined. """ |
for cmd, response in self.response_list:
if not cmd.match(command):
continue
if response is None:
return None
elif hasattr(response, '__call__'):
return response(command)
else:
return response
if self.strict:
raise Exception('Undefined command: ' + repr(command))
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_host(host, default_protocol='telnet', default_domain=''):
""" Given a string or a Host object, this function returns a Host object. :type host: string|Host :param host: A hostname (may be URL formatted) or a Host object. :type default_protocol: str :param default_protocol: Passed to the Host constructor. :type default_domain: str :param default_domain: Appended to each hostname that has no domain. :rtype: Host :return: The Host object. """ |
if host is None:
raise TypeError('None can not be cast to Host')
if hasattr(host, 'get_address'):
return host
if default_domain and not '.' in host:
host += '.' + default_domain
return Exscript.Host(host, default_protocol=default_protocol) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_hosts(hosts, default_protocol='telnet', default_domain=''):
""" Given a string or a Host object, or a list of strings or Host objects, this function returns a list of Host objects. :type hosts: string|Host|list(string)|list(Host) :param hosts: One or more hosts or hostnames. :type default_protocol: str :param default_protocol: Passed to the Host constructor. :type default_domain: str :param default_domain: Appended to each hostname that has no domain. :rtype: list[Host] :return: A list of Host objects. """ |
return [to_host(h, default_protocol, default_domain)
for h in to_list(hosts)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_regex(regex, flags=0):
""" Given a string, this function returns a new re.RegexObject. Given a re.RegexObject, this function just returns the same object. :type regex: string|re.RegexObject :param regex: A regex or a re.RegexObject :type flags: int :param flags: See Python's re.compile(). :rtype: re.RegexObject :return: The Python regex object. """ |
if regex is None:
raise TypeError('None can not be cast to re.RegexObject')
if hasattr(regex, 'match'):
return regex
return re.compile(regex, flags) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_ip(string):
""" Returns True if the given string is an IPv4 address, False otherwise. :type string: string :param string: Any string. :rtype: bool :return: True if the string is an IP address, False otherwise. """ |
mo = re.match(r'(\d+)\.(\d+)\.(\d+)\.(\d+)', string)
if mo is None:
return False
for group in mo.groups():
if int(group) not in list(range(0, 256)):
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def network(prefix, default_length=24):
""" Given a prefix, this function returns the corresponding network address. :type prefix: string :param prefix: An IP prefix. :type default_length: long :param default_length: The default ip prefix length. :rtype: string :return: The IP network address. """ |
address, pfxlen = parse_prefix(prefix, default_length)
ip = ip2int(address)
return int2ip(ip & pfxlen2mask_int(pfxlen)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def matches_prefix(ip, prefix):
""" Returns True if the given IP address is part of the given network, returns False otherwise. :type ip: string :param ip: An IP address. :type prefix: string :param prefix: An IP prefix. :rtype: bool :return: True if the IP is in the prefix, False otherwise. """ |
ip_int = ip2int(ip)
network, pfxlen = parse_prefix(prefix)
network_int = ip2int(network)
mask_int = pfxlen2mask_int(pfxlen)
return ip_int&mask_int == network_int&mask_int |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_private(ip):
""" Returns True if the given IP address is private, returns False otherwise. :type ip: string :param ip: An IP address. :rtype: bool :return: True if the IP is private, False otherwise. """ |
if matches_prefix(ip, '10.0.0.0/8'):
return True
if matches_prefix(ip, '172.16.0.0/12'):
return True
if matches_prefix(ip, '192.168.0.0/16'):
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sort(iterable):
""" Given an IP address list, this function sorts the list. :type iterable: Iterator :param iterable: An IP address list. :rtype: list :return: The sorted IP address list. """ |
ips = sorted(normalize_ip(ip) for ip in iterable)
return [clean_ip(ip) for ip in ips] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parse_url(path):
"""Given a urlencoded path, returns the path and the dictionary of query arguments, all in Unicode.""" |
# path changes from bytes to Unicode in going from Python 2 to
# Python 3.
if sys.version_info[0] < 3:
o = urlparse(urllib.parse.unquote_plus(path).decode('utf8'))
else:
o = urlparse(urllib.parse.unquote_plus(path))
path = o.path
args = {}
# Convert parse_qs' str --> [str] dictionary to a str --> str
# dictionary since we never use multi-value GET arguments
# anyway.
multiargs = parse_qs(o.query, keep_blank_values=True)
for arg, value in list(multiargs.items()):
args[arg] = value[0]
return path, args |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _require_authenticate(func):
'''A decorator to add digest authorization checks to HTTP Request Handlers'''
def wrapped(self):
if not hasattr(self, 'authenticated'):
self.authenticated = None
if self.authenticated:
return func(self)
auth = self.headers.get(u'Authorization')
if auth is None:
msg = u"You are not allowed to access this page. Please login first!"
return _error_401(self, msg)
token, fields = auth.split(' ', 1)
if token != 'Digest':
return _error_401(self, 'Unsupported authentication type')
# Check the header fields of the request.
cred = parse_http_list(fields)
cred = parse_keqv_list(cred)
keys = u'realm', u'username', u'nonce', u'uri', u'response'
if not all(cred.get(key) for key in keys):
return _error_401(self, 'Incomplete authentication header')
if cred['realm'] != self.server.realm:
return _error_401(self, 'Incorrect realm')
if 'qop' in cred and ('nc' not in cred or 'cnonce' not in cred):
return _error_401(self, 'qop with missing nc or cnonce')
# Check the username.
username = cred['username']
password = self.server.get_password(username)
if not username or password is None:
return _error_401(self, 'Invalid username or password')
# Check the digest string.
location = u'%s:%s' % (self.command, self.path)
location = md5hex(location.encode('utf8'))
pwhash = md5hex('%s:%s:%s' % (username, self.server.realm, password))
if 'qop' in cred:
info = (cred['nonce'],
cred['nc'],
cred['cnonce'],
cred['qop'],
location)
else:
info = cred['nonce'], location
expect = u'%s:%s' % (pwhash, ':'.join(info))
expect = md5hex(expect.encode('utf8'))
if expect != cred['response']:
return _error_401(self, 'Invalid username or password')
# Success!
self.authenticated = True
return func(self)
return wrapped |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _do_POSTGET(self, handler):
"""handle an HTTP request""" |
# at first, assume that the given path is the actual path and there are
# no arguments
self.server._dbg(self.path)
self.path, self.args = _parse_url(self.path)
# Extract POST data, if any. Clumsy syntax due to Python 2 and
# 2to3's lack of a byte literal.
self.data = u"".encode()
length = self.headers.get('Content-Length')
if length and length.isdigit():
self.data = self.rfile.read(int(length))
# POST data gets automatically decoded into Unicode. The bytestring
# will still be available in the bdata attribute.
self.bdata = self.data
try:
self.data = self.data.decode('utf8')
except UnicodeDecodeError:
self.data = None
# Run the handler.
try:
handler()
except:
self.send_response(500)
self.end_headers()
self.wfile.write(format_exc().encode('utf8')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def head(self, bytes):
""" Returns the number of given bytes from the head of the buffer. The buffer remains unchanged. :type bytes: int :param bytes: The number of bytes to return. """ |
oldpos = self.io.tell()
self.io.seek(0)
head = self.io.read(bytes)
self.io.seek(oldpos)
return head |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tail(self, bytes):
""" Returns the number of given bytes from the tail of the buffer. The buffer remains unchanged. :type bytes: int :param bytes: The number of bytes to return. """ |
self.io.seek(max(0, self.size() - bytes))
return self.io.read() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def append(self, data):
""" Appends the given data to the buffer, and triggers all connected monitors, if any of them match the buffer content. :type data: str :param data: The data that is appended. """ |
self.io.write(data)
if not self.monitors:
return
# Check whether any of the monitoring regular expressions matches.
# If it does, we need to disable that monitor until the matching
# data is no longer in the buffer. We accomplish this by keeping
# track of the position of the last matching byte.
buf = str(self)
for item in self.monitors:
regex_list, callback, bytepos, limit = item
bytepos = max(bytepos, len(buf) - limit)
for i, regex in enumerate(regex_list):
match = regex.search(buf, bytepos)
if match is not None:
item[2] = match.end()
callback(i, match) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clear(self):
""" Removes all data from the buffer. """ |
self.io.seek(0)
self.io.truncate()
for item in self.monitors:
item[2] = 0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_monitor(self, pattern, callback, limit=80):
""" Calls the given function whenever the given pattern matches the buffer. Arguments passed to the callback are the index of the match, and the match object of the regular expression. :type pattern: str|re.RegexObject|list(str|re.RegexObject) :param pattern: One or more regular expressions. :type callback: callable :param callback: The function that is called. :type limit: int :param limit: The maximum size of the tail of the buffer that is searched, in number of bytes. """ |
self.monitors.append([to_regexs(pattern), callback, 0, limit]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_template_string(string, **kwargs):
""" Reads the given SMTP formatted template, and creates a new Mail object using the information. :type string: str :param string: The SMTP formatted template. :type kwargs: str :param kwargs: Variables to replace in the template. :rtype: Mail :return: The resulting mail. """ |
tmpl = _render_template(string, **kwargs)
mail = Mail()
mail.set_from_template_string(tmpl)
return mail |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send(mail, server='localhost'):
""" Sends the given mail. :type mail: Mail :param mail: The mail object. :type server: string :param server: The address of the mailserver. """ |
sender = mail.get_sender()
rcpt = mail.get_receipients()
session = smtplib.SMTP(server)
message = MIMEMultipart()
message['Subject'] = mail.get_subject()
message['From'] = mail.get_sender()
message['To'] = ', '.join(mail.get_to())
message['Cc'] = ', '.join(mail.get_cc())
message.preamble = 'Your mail client is not MIME aware.'
body = MIMEText(mail.get_body().encode("utf-8"), "plain", "utf-8")
body.add_header('Content-Disposition', 'inline')
message.attach(body)
for filename in mail.get_attachments():
message.attach(_get_mime_object(filename))
session.sendmail(sender, rcpt, message.as_string()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_smtp_header(self):
""" Returns the SMTP formatted header of the line. :rtype: string :return: The SMTP header. """ |
header = "From: %s\r\n" % self.get_sender()
header += "To: %s\r\n" % ',\r\n '.join(self.get_to())
header += "Cc: %s\r\n" % ',\r\n '.join(self.get_cc())
header += "Bcc: %s\r\n" % ',\r\n '.join(self.get_bcc())
header += "Subject: %s\r\n" % self.get_subject()
return header |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_smtp_mail(self):
""" Returns the SMTP formatted email, as it may be passed to sendmail. :rtype: string :return: The SMTP formatted mail. """ |
header = self.get_smtp_header()
body = self.get_body().replace('\n', '\r\n')
return header + '\r\n' + body + '\r\n' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def status(logger):
""" Creates a one-line summary on the actions that were logged by the given Logger. :type logger: Logger :param logger: The logger that recorded what happened in the queue. :rtype: string :return: A string summarizing the status. """ |
aborted = logger.get_aborted_actions()
succeeded = logger.get_succeeded_actions()
total = aborted + succeeded
if total == 0:
return 'No actions done'
elif total == 1 and succeeded == 1:
return 'One action done (succeeded)'
elif total == 1 and succeeded == 0:
return 'One action done (failed)'
elif total == succeeded:
return '%d actions total (all succeeded)' % total
elif succeeded == 0:
return '%d actions total (all failed)' % total
else:
msg = '%d actions total (%d failed, %d succeeded)'
return msg % (total, aborted, succeeded) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def summarize(logger):
""" Creates a short summary on the actions that were logged by the given Logger. :type logger: Logger :param logger: The logger that recorded what happened in the queue. :rtype: string :return: A string summarizing the status of every performed task. """ |
summary = []
for log in logger.get_logs():
thestatus = log.has_error() and log.get_error(False) or 'ok'
name = log.get_name()
summary.append(name + ': ' + thestatus)
return '\n'.join(summary) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format(logger, show_successful=True, show_errors=True, show_traceback=True):
""" Prints a report of the actions that were logged by the given Logger. The report contains a list of successful actions, as well as the full error message on failed actions. :type logger: Logger :param logger: The logger that recorded what happened in the queue. :rtype: string :return: A string summarizing the status of every performed task. """ |
output = []
# Print failed actions.
errors = logger.get_aborted_actions()
if show_errors and errors:
output += _underline('Failed actions:')
for log in logger.get_aborted_logs():
if show_traceback:
output.append(log.get_name() + ':')
output.append(log.get_error())
else:
output.append(log.get_name() + ': ' + log.get_error(False))
output.append('')
# Print successful actions.
if show_successful:
output += _underline('Successful actions:')
for log in logger.get_succeeded_logs():
output.append(log.get_name())
output.append('')
return '\n'.join(output).strip() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_vars(self):
""" Returns a complete dict of all variables that are defined in this scope, including the variables of the parent. """ |
if self.parent is None:
vars = {}
vars.update(self.variables)
return vars
vars = self.parent.get_vars()
vars.update(self.variables)
return vars |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_from_name(self, name):
""" Returns the item with the given name, or None if no such item is known. """ |
with self.condition:
try:
item_id = self.name2id[name]
except KeyError:
return None
return self.id2item[item_id]
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def append(self, item, name=None):
""" Adds the given item to the end of the pipeline. """ |
with self.condition:
self.queue.append(item)
uuid = self._register_item(name, item)
self.condition.notify_all()
return uuid |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prioritize(self, item, force=False):
""" Moves the item to the very left of the queue. """ |
with self.condition:
# If the job is already running (or about to be forced),
# there is nothing to be done.
if item in self.working or item in self.force:
return
self.queue.remove(item)
if force:
self.force.append(item)
else:
self.queue.appendleft(item)
self.condition.notify_all() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_hosts_from_file(filename, default_protocol='telnet', default_domain='', remove_duplicates=False, encoding='utf-8'):
""" Reads a list of hostnames from the file with the given name. :type filename: string :param filename: A full filename. :type default_protocol: str :param default_protocol: Passed to the Host constructor. :type default_domain: str :param default_domain: Appended to each hostname that has no domain. :type remove_duplicates: bool :param remove_duplicates: Whether duplicates are removed. :type encoding: str :param encoding: The encoding of the file. :rtype: list[Host] :return: The newly created host instances. """ |
# Open the file.
if not os.path.exists(filename):
raise IOError('No such file: %s' % filename)
# Read the hostnames.
have = set()
hosts = []
with codecs.open(filename, 'r', encoding) as file_handle:
for line in file_handle:
hostname = line.split('#')[0].strip()
if hostname == '':
continue
if remove_duplicates and hostname in have:
continue
have.add(hostname)
hosts.append(to_host(hostname, default_protocol, default_domain))
return hosts |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def log_to(logger):
""" Wraps a function that has a connection passed such that everything that happens on the connection is logged using the given logger. :type logger: Logger :param logger: The logger that handles the logging. """ |
logger_id = id(logger)
def decorator(function):
func = add_label(function, 'log_to', logger_id=logger_id)
return func
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def msg(self, msg, *args):
"""Print a debug message, when the debug level is > 0. If extra arguments are present, they are substituted in the message using the standard string formatting operator. """ |
if self.debuglevel > 0:
self.stderr.write('Telnet(%s,%d): ' % (self.host, self.port))
if args:
self.stderr.write(msg % args)
else:
self.stderr.write(msg)
self.stderr.write('\n') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write(self, buffer):
"""Write a string to the socket, doubling any IAC characters. Can block if the connection is blocked. May raise socket.error if the connection is closed. """ |
if type(buffer) == type(0):
buffer = chr(buffer)
elif not isinstance(buffer, bytes):
buffer = buffer.encode(self.encoding)
if IAC in buffer:
buffer = buffer.replace(IAC, IAC+IAC)
self.msg("send %s", repr(buffer))
self.sock.send(buffer) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_all(self):
"""Read all data until EOF; block until connection closed.""" |
self.process_rawq()
while not self.eof:
self.fill_rawq()
self.process_rawq()
buf = self.cookedq.getvalue()
self.cookedq.seek(0)
self.cookedq.truncate()
return buf |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_eager(self):
"""Read readily available data. Raise EOFError if connection closed and no cooked data available. Return '' if no cooked data available otherwise. Don't block unless in the midst of an IAC sequence. """ |
self.process_rawq()
while self.cookedq.tell() == 0 and not self.eof and self.sock_avail():
self.fill_rawq()
self.process_rawq()
return self.read_very_lazy() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_receive_callback(self, callback, *args, **kwargs):
"""The callback function called after each receipt of any data.""" |
self.data_callback = callback
self.data_callback_kwargs = kwargs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_window_size(self, rows, cols):
""" Change the size of the terminal window, if the remote end supports NAWS. If it doesn't, the method returns silently. """ |
if not self.can_naws:
return
self.window_size = rows, cols
size = struct.pack('!HH', cols, rows)
self.sock.send(IAC + SB + NAWS + size + IAC + SE) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def interact(self):
"""Interaction function, emulates a very dumb telnet client.""" |
if sys.platform == "win32":
self.mt_interact()
return
while True:
rfd, wfd, xfd = select.select([self, sys.stdin], [], [])
if self in rfd:
try:
text = self.read_eager()
except EOFError:
print('*** Connection closed by remote host ***')
break
if text:
self.stdout.write(text)
self.stdout.flush()
if sys.stdin in rfd:
line = sys.stdin.readline()
if not line:
break
self.write(line) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def waitfor(self, relist, timeout=None, cleanup=None):
"""Read until one from a list of a regular expressions matches. The first argument is a list of regular expressions, either compiled (re.RegexObject instances) or uncompiled (strings). The optional second argument is a timeout, in seconds; default is no timeout. Return a tuple of three items: the index in the list of the first regular expression that matches; the match object returned; and the text read up till and including the match. If EOF is read and no text was read, raise EOFError. Otherwise, when nothing matches, return (-1, None, text) where text is the text received so far (may be the empty string if a timeout happened). If a regular expression ends with a greedy match (e.g. '.*') or if more than one expression can match the same input, the results are undeterministic, and may depend on the I/O timing. """ |
return self._waitfor(relist, timeout, False, cleanup) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read(path):
""" Returns the process id from the given file if it exists, or None otherwise. Raises an exception for all other types of OSError while trying to access the file. :type path: str :param path: The name of the pidfile. :rtype: int or None :return: The PID, or none if the file was not found. """ |
# Try to read the pid from the pidfile.
logging.info("Checking pidfile '%s'", path)
try:
return int(open(path).read())
except IOError as xxx_todo_changeme:
(code, text) = xxx_todo_changeme.args
if code == errno.ENOENT: # no such file or directory
return None
raise |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.