text_prompt
stringlengths 100
17.7k
⌀ | code_prompt
stringlengths 7
9.86k
⌀ |
---|---|
<SYSTEM_TASK:>
Write a list of items to stream in CSV format.
<END_TASK>
<USER_TASK:>
Description:
def csv_from_items(items, stream=None):
"""Write a list of items to stream in CSV format.
The items need to be attrs-decorated.
""" |
items = iter(items)
first = next(items)
cls = first.__class__
if stream is None:
stream = sys.stdout
fields = [f.name for f in attr.fields(cls)]
writer = csv.DictWriter(stream, fieldnames=fields)
writer.writeheader()
writer.writerow(attr.asdict(first))
writer.writerows((attr.asdict(x) for x in items)) |
<SYSTEM_TASK:>
Allow a user to query a device directly using XML-requests.
<END_TASK>
<USER_TASK:>
Description:
def make_rpc_call(self, rpc_command):
"""
Allow a user to query a device directly using XML-requests.
:param rpc_command: (str) rpc command such as:
<Get><Operational><LLDP><NodeTable></NodeTable></LLDP></Operational></Get>
""" |
# ~~~ hack: ~~~
if not self.is_alive():
self.close() # force close for safety
self.open() # reopen
# ~~~ end hack ~~~
result = self._execute_rpc(rpc_command)
return ET.tostring(result) |
<SYSTEM_TASK:>
Open a connection to an IOS-XR device.
<END_TASK>
<USER_TASK:>
Description:
def open(self):
"""
Open a connection to an IOS-XR device.
Connects to the device using SSH and drops into XML mode.
""" |
try:
self.device = ConnectHandler(device_type='cisco_xr',
ip=self.hostname,
port=self.port,
username=self.username,
password=self.password,
**self.netmiko_kwargs)
self.device.timeout = self.timeout
self._xml_agent_alive = True # successfully open thus alive
except NetMikoTimeoutException as t_err:
raise ConnectError(t_err.args[0])
except NetMikoAuthenticationException as au_err:
raise ConnectError(au_err.args[0])
self._cli_prompt = self.device.find_prompt() # get the prompt
self._enter_xml_mode() |
<SYSTEM_TASK:>
Executes an operational show-type command.
<END_TASK>
<USER_TASK:>
Description:
def _execute_show(self, show_command):
"""
Executes an operational show-type command.
""" |
rpc_command = '<CLI><Exec>{show_command}</Exec></CLI>'.format(
show_command=escape_xml(show_command)
)
response = self._execute_rpc(rpc_command)
raw_response = response.xpath('.//CLI/Exec')[0].text
return raw_response.strip() if raw_response else '' |
<SYSTEM_TASK:>
Executes a configuration show-type command.
<END_TASK>
<USER_TASK:>
Description:
def _execute_config_show(self, show_command, delay_factor=.1):
"""
Executes a configuration show-type command.
""" |
rpc_command = '<CLI><Configuration>{show_command}</Configuration></CLI>'.format(
show_command=escape_xml(show_command)
)
response = self._execute_rpc(rpc_command, delay_factor=delay_factor)
raw_response = response.xpath('.//CLI/Configuration')[0].text
return raw_response.strip() if raw_response else '' |
<SYSTEM_TASK:>
Close the connection to the IOS-XR device.
<END_TASK>
<USER_TASK:>
Description:
def close(self):
"""
Close the connection to the IOS-XR device.
Clean up after you are done and explicitly close the router connection.
""" |
if self.lock_on_connect or self.locked:
self.unlock() # this refers to the config DB
self._unlock_xml_agent() # this refers to the XML agent
if hasattr(self.device, 'remote_conn'):
self.device.remote_conn.close() |
<SYSTEM_TASK:>
Lock the config database.
<END_TASK>
<USER_TASK:>
Description:
def lock(self):
"""
Lock the config database.
Use if Locking/Unlocking is not performaed automatically by lock=False
""" |
if not self.locked:
rpc_command = '<Lock/>'
try:
self._execute_rpc(rpc_command)
except XMLCLIError:
raise LockError('Unable to enter in configure exclusive mode!', self)
self.locked = True |
<SYSTEM_TASK:>
Unlock the IOS-XR device config.
<END_TASK>
<USER_TASK:>
Description:
def unlock(self):
"""
Unlock the IOS-XR device config.
Use if Locking/Unlocking is not performaed automatically by lock=False
""" |
if self.locked:
rpc_command = '<Unlock/>'
try:
self._execute_rpc(rpc_command)
except XMLCLIError:
raise UnlockError('Unable to unlock the config!', self)
self.locked = False |
<SYSTEM_TASK:>
Load candidate confguration.
<END_TASK>
<USER_TASK:>
Description:
def load_candidate_config(self, filename=None, config=None):
"""
Load candidate confguration.
Populate the attribute candidate_config with the desired
configuration and loads it into the router. You can populate it from
a file or from a string. If you send both a filename and a string
containing the configuration, the file takes precedence.
:param filename: Path to the file containing the desired
configuration. By default is None.
:param config: String containing the desired configuration.
""" |
configuration = ''
if filename is None:
configuration = config
else:
with open(filename) as f:
configuration = f.read()
rpc_command = '<CLI><Configuration>{configuration}</Configuration></CLI>'.format(
configuration=escape_xml(configuration) # need to escape, otherwise will try to load invalid XML
)
try:
self._execute_rpc(rpc_command)
except InvalidInputError as e:
self.discard_config()
raise InvalidInputError(e.args[0], self) |
<SYSTEM_TASK:>
Retrieve the configuration loaded as candidate config in your configuration session.
<END_TASK>
<USER_TASK:>
Description:
def get_candidate_config(self, merge=False, formal=False):
"""
Retrieve the configuration loaded as candidate config in your configuration session.
:param merge: Merge candidate config with running config to return
the complete configuration including all changed
:param formal: Return configuration in IOS-XR formal config format
""" |
command = "show configuration"
if merge:
command += " merge"
if formal:
command += " formal"
response = self._execute_config_show(command)
match = re.search(".*(!! IOS XR Configuration.*)$", response, re.DOTALL)
if match is not None:
response = match.group(1)
return response |
<SYSTEM_TASK:>
Compare configuration to be merged with the one on the device.
<END_TASK>
<USER_TASK:>
Description:
def compare_config(self):
"""
Compare configuration to be merged with the one on the device.
Compare executed candidate config with the running config and
return a diff, assuming the loaded config will be merged with the
existing one.
:return: Config diff.
""" |
_show_merge = self._execute_config_show('show configuration merge')
_show_run = self._execute_config_show('show running-config')
diff = difflib.unified_diff(_show_run.splitlines(1)[2:-2], _show_merge.splitlines(1)[2:-2])
return ''.join([x.replace('\r', '') for x in diff]) |
<SYSTEM_TASK:>
Commit the candidate config.
<END_TASK>
<USER_TASK:>
Description:
def commit_config(self, label=None, comment=None, confirmed=None):
"""
Commit the candidate config.
:param label: Commit comment, displayed in the commit entry on the device.
:param comment: Commit label, displayed instead of the commit ID on the device. (Max 60 characters)
:param confirmed: Commit with auto-rollback if new commit is not made in 30 to 300 sec
""" |
rpc_command = '<Commit'
if label:
rpc_command += ' Label="%s"' % label
if comment:
rpc_command += ' Comment="%s"' % comment[:60]
if confirmed:
if 30 <= int(confirmed) <= 300:
rpc_command += ' Confirmed="%d"' % int(confirmed)
else:
raise InvalidInputError('confirmed needs to be between 30 and 300 seconds', self)
rpc_command += '/>'
self._execute_rpc(rpc_command) |
<SYSTEM_TASK:>
Rollback the last committed configuration.
<END_TASK>
<USER_TASK:>
Description:
def rollback(self, rb_id=1):
"""
Rollback the last committed configuration.
:param rb_id: Rollback a specific number of steps. Default: 1
""" |
rpc_command = '<Unlock/><Rollback><Previous>{rb_id}</Previous></Rollback><Lock/>'.format(rb_id=rb_id)
self._execute_rpc(rpc_command) |
<SYSTEM_TASK:>
A simple demo to be used from command line.
<END_TASK>
<USER_TASK:>
Description:
def _main():
""" A simple demo to be used from command line. """ |
import sys
def log(message):
print(message)
def print_usage():
log('usage: %s <application key> <application secret> send <number> <message> <from_number>' % sys.argv[0])
log(' %s <application key> <application secret> status <message_id>' % sys.argv[0])
if len(sys.argv) > 4 and sys.argv[3] == 'send':
key, secret, number, message = sys.argv[1], sys.argv[2], sys.argv[4], sys.argv[5]
client = SinchSMS(key, secret)
if len(sys.argv) > 6:
log(client.send_message(number, message, sys.argv[6]))
else:
log(client.send_message(number, message))
elif len(sys.argv) > 3 and sys.argv[3] == 'status':
key, secret, message_id = sys.argv[1], sys.argv[2], sys.argv[4]
client = SinchSMS(key, secret)
log(client.check_status(message_id))
else:
print_usage()
sys.exit(1)
sys.exit(0) |
<SYSTEM_TASK:>
Send a request and read response.
<END_TASK>
<USER_TASK:>
Description:
def _request(self, url, values=None):
""" Send a request and read response.
Sends a get request if values are None, post request otherwise.
""" |
if values:
json_data = json.dumps(values)
request = urllib2.Request(url, json_data.encode())
request.add_header('content-type', 'application/json')
request.add_header('authorization', self._auth)
connection = urllib2.urlopen(request)
response = connection.read()
connection.close()
else:
request = urllib2.Request(url)
request.add_header('authorization', self._auth)
connection = urllib2.urlopen(request)
response = connection.read()
connection.close()
try:
result = json.loads(response.decode())
except ValueError as exception:
return {'errorCode': 1, 'message': str(exception)}
return result |
<SYSTEM_TASK:>
Send a message to the specified number and return a response dictionary.
<END_TASK>
<USER_TASK:>
Description:
def send_message(self, to_number, message, from_number=None):
""" Send a message to the specified number and return a response dictionary.
The numbers must be specified in international format starting with a '+'.
Returns a dictionary that contains a 'MessageId' key with the sent message id value or
contains 'errorCode' and 'message' on error.
Possible error codes:
40001 - Parameter validation
40002 - Missing parameter
40003 - Invalid request
40100 - Illegal authorization header
40200 - There is not enough funds to send the message
40300 - Forbidden request
40301 - Invalid authorization scheme for calling the method
50000 - Internal error
""" |
values = {'Message': message}
if from_number is not None:
values['From'] = from_number
return self._request(self.SEND_SMS_URL + to_number, values) |
<SYSTEM_TASK:>
Restore row from BigQuery
<END_TASK>
<USER_TASK:>
Description:
def restore_row(self, row, schema):
"""Restore row from BigQuery
""" |
for index, field in enumerate(schema.fields):
if field.type == 'datetime':
row[index] = parse(row[index])
if field.type == 'date':
row[index] = parse(row[index]).date()
if field.type == 'time':
row[index] = parse(row[index]).time()
return schema.cast_row(row) |
<SYSTEM_TASK:>
Restore type from BigQuery
<END_TASK>
<USER_TASK:>
Description:
def restore_type(self, type):
"""Restore type from BigQuery
""" |
# Mapping
mapping = {
'BOOLEAN': 'boolean',
'DATE': 'date',
'DATETIME': 'datetime',
'INTEGER': 'integer',
'FLOAT': 'number',
'STRING': 'string',
'TIME': 'time',
}
# Not supported type
if type not in mapping:
message = 'Type %s is not supported' % type
raise tableschema.exceptions.StorageError(message)
return mapping[type] |
<SYSTEM_TASK:>
Returns an AST where all operations of lower precedence are finalized.
<END_TASK>
<USER_TASK:>
Description:
def _start_operation(self, ast, operation, precedence):
"""
Returns an AST where all operations of lower precedence are finalized.
""" |
if TRACE_PARSE:
print(' start_operation:', repr(operation), 'AST:', ast)
op_prec = precedence[operation]
while True:
if ast[1] is None:
# [None, None, x]
if TRACE_PARSE: print(' start_op: ast[1] is None:', repr(ast))
ast[1] = operation
if TRACE_PARSE: print(' --> start_op: ast[1] is None:', repr(ast))
return ast
prec = precedence[ast[1]]
if prec > op_prec: # op=&, [ast, |, x, y] -> [[ast, |, x], &, y]
if TRACE_PARSE: print(' start_op: prec > op_prec:', repr(ast))
ast = [ast, operation, ast.pop(-1)]
if TRACE_PARSE: print(' --> start_op: prec > op_prec:', repr(ast))
return ast
if prec == op_prec: # op=&, [ast, &, x] -> [ast, &, x]
if TRACE_PARSE: print(' start_op: prec == op_prec:', repr(ast))
return ast
if not (inspect.isclass(ast[1]) and issubclass(ast[1], Function)):
# the top ast node should be a function subclass at this stage
raise ParseError(error_code=PARSE_INVALID_NESTING)
if ast[0] is None: # op=|, [None, &, x, y] -> [None, |, x&y]
if TRACE_PARSE: print(' start_op: ast[0] is None:', repr(ast))
subexp = ast[1](*ast[2:])
new_ast = [ast[0], operation, subexp]
if TRACE_PARSE: print(' --> start_op: ast[0] is None:', repr(new_ast))
return new_ast
else: # op=|, [[ast, &, x], ~, y] -> [ast, &, x, ~y]
if TRACE_PARSE: print(' start_op: else:', repr(ast))
ast[0].append(ast[1](*ast[2:]))
ast = ast[0]
if TRACE_PARSE: print(' --> start_op: else:', repr(ast)) |
<SYSTEM_TASK:>
Return an iterable of 3-tuple describing each token given an expression
<END_TASK>
<USER_TASK:>
Description:
def tokenize(self, expr):
"""
Return an iterable of 3-tuple describing each token given an expression
unicode string.
This 3-tuple contains (token, token string, position):
- token: either a Symbol instance or one of TOKEN_* token types.
- token string: the original token unicode string.
- position: some simple object describing the starting position of the
original token string in the `expr` string. It can be an int for a
character offset, or a tuple of starting (row/line, column).
The token position is used only for error reporting and can be None or
empty.
Raise ParseError on errors. The ParseError.args is a tuple of:
(token_string, position, error message)
You can use this tokenizer as a base to create specialized tokenizers
for your custom algebra by subclassing BooleanAlgebra. See also the
tests for other examples of alternative tokenizers.
This tokenizer has these characteristics:
- The `expr` string can span multiple lines,
- Whitespace is not significant.
- The returned position is the starting character offset of a token.
- A TOKEN_SYMBOL is returned for valid identifiers which is a string
without spaces. These are valid identifiers:
- Python identifiers.
- a string even if starting with digits
- digits (except for 0 and 1).
- dotted names : foo.bar consist of one token.
- names with colons: foo:bar consist of one token.
These are not identifiers:
- quoted strings.
- any punctuation which is not an operation
- Recognized operators are (in any upper/lower case combinations):
- for and: '*', '&', 'and'
- for or: '+', '|', 'or'
- for not: '~', '!', 'not'
- Recognized special symbols are (in any upper/lower case combinations):
- True symbols: 1 and True
- False symbols: 0, False and None
""" |
if not isinstance(expr, basestring):
raise TypeError('expr must be string but it is %s.' % type(expr))
# mapping of lowercase token strings to a token type id for the standard
# operators, parens and common true or false symbols, as used in the
# default tokenizer implementation.
TOKENS = {
'*': TOKEN_AND, '&': TOKEN_AND, 'and': TOKEN_AND,
'+': TOKEN_OR, '|': TOKEN_OR, 'or': TOKEN_OR,
'~': TOKEN_NOT, '!': TOKEN_NOT, 'not': TOKEN_NOT,
'(': TOKEN_LPAR, ')': TOKEN_RPAR,
'[': TOKEN_LPAR, ']': TOKEN_RPAR,
'true': TOKEN_TRUE, '1': TOKEN_TRUE,
'false': TOKEN_FALSE, '0': TOKEN_FALSE, 'none': TOKEN_FALSE
}
position = 0
length = len(expr)
while position < length:
tok = expr[position]
sym = tok.isalpha() or tok == '_'
if sym:
position += 1
while position < length:
char = expr[position]
if char.isalnum() or char in ('.', ':', '_'):
position += 1
tok += char
else:
break
position -= 1
try:
yield TOKENS[tok.lower()], tok, position
except KeyError:
if sym:
yield TOKEN_SYMBOL, tok, position
elif tok not in (' ', '\t', '\r', '\n'):
raise ParseError(token_string=tok, position=position,
error_code=PARSE_UNKNOWN_TOKEN)
position += 1 |
<SYSTEM_TASK:>
Recursively flatten the `expr` expression for the `op_example`
<END_TASK>
<USER_TASK:>
Description:
def _rdistributive(self, expr, op_example):
"""
Recursively flatten the `expr` expression for the `op_example`
AND or OR operation instance exmaple.
""" |
if expr.isliteral:
return expr
expr_class = expr.__class__
args = (self._rdistributive(arg, op_example) for arg in expr.args)
args = tuple(arg.simplify() for arg in args)
if len(args) == 1:
return args[0]
expr = expr_class(*args)
dualoperation = op_example.dual
if isinstance(expr, dualoperation):
expr = expr.distributive()
return expr |
<SYSTEM_TASK:>
Return a normalized expression transformed to its normal form in the
<END_TASK>
<USER_TASK:>
Description:
def normalize(self, expr, operation):
"""
Return a normalized expression transformed to its normal form in the
given AND or OR operation.
The new expression arguments will satisfy these conditions:
- operation(*args) == expr (here mathematical equality is meant)
- the operation does not occur in any of its arg.
- NOT is only appearing in literals (aka. Negation normal form).
The operation must be an AND or OR operation or a subclass.
""" |
# ensure that the operation is not NOT
assert operation in (self.AND, self.OR,)
# Move NOT inwards.
expr = expr.literalize()
# Simplify first otherwise _rdistributive() may take forever.
expr = expr.simplify()
operation_example = operation(self.TRUE, self.FALSE)
expr = self._rdistributive(expr, operation_example)
# Canonicalize
expr = expr.simplify()
return expr |
<SYSTEM_TASK:>
Return a list of all the literals contained in this expression.
<END_TASK>
<USER_TASK:>
Description:
def get_literals(self):
"""
Return a list of all the literals contained in this expression.
Include recursively subexpressions symbols.
This includes duplicates.
""" |
if self.isliteral:
return [self]
if not self.args:
return []
return list(itertools.chain.from_iterable(arg.get_literals() for arg in self.args)) |
<SYSTEM_TASK:>
Return an expression where NOTs are only occurring as literals.
<END_TASK>
<USER_TASK:>
Description:
def literalize(self):
"""
Return an expression where NOTs are only occurring as literals.
Applied recursively to subexpressions.
""" |
if self.isliteral:
return self
args = tuple(arg.literalize() for arg in self.args)
if all(arg is self.args[i] for i, arg in enumerate(args)):
return self
return self.__class__(*args) |
<SYSTEM_TASK:>
Return a list of all the symbols contained in this expression.
<END_TASK>
<USER_TASK:>
Description:
def get_symbols(self):
"""
Return a list of all the symbols contained in this expression.
Include recursively subexpressions symbols.
This includes duplicates.
""" |
return [s if isinstance(s, Symbol) else s.args[0] for s in self.get_literals()] |
<SYSTEM_TASK:>
Return a pretty formatted representation of self.
<END_TASK>
<USER_TASK:>
Description:
def pretty(self, indent=0, debug=False):
"""
Return a pretty formatted representation of self.
""" |
debug_details = ''
if debug:
debug_details += '<isliteral=%r, iscanonical=%r>' % (self.isliteral, self.iscanonical)
obj = "'%s'" % self.obj if isinstance(self.obj, basestring) else repr(self.obj)
return (' ' * indent) + ('%s(%s%s)' % (self.__class__.__name__, debug_details, obj)) |
<SYSTEM_TASK:>
Return a pretty formatted representation of self as an indented tree.
<END_TASK>
<USER_TASK:>
Description:
def pretty(self, indent=0, debug=False):
"""
Return a pretty formatted representation of self as an indented tree.
If debug is True, also prints debug information for each expression arg.
For example:
>>> print Expression().parse(u'not a and not b and not (a and ba and c) and c or c').pretty()
OR(
AND(
NOT(Symbol('a')),
NOT(Symbol('b')),
NOT(
AND(
Symbol('a'),
Symbol('ba'),
Symbol('c')
)
),
Symbol('c')
),
Symbol('c')
)
""" |
debug_details = ''
if debug:
debug_details += '<isliteral=%r, iscanonical=%r' % (self.isliteral, self.iscanonical)
identity = getattr(self, 'identity', None)
if identity is not None:
debug_details += ', identity=%r' % (identity)
annihilator = getattr(self, 'annihilator', None)
if annihilator is not None:
debug_details += ', annihilator=%r' % (annihilator)
dual = getattr(self, 'dual', None)
if dual is not None:
debug_details += ', dual=%r' % (dual)
debug_details += '>'
cls = self.__class__.__name__
args = [a.pretty(indent=indent + 2, debug=debug) for a in self.args]
pfargs = ',\n'.join(args)
cur_indent = ' ' * indent
new_line = '' if self.isliteral else '\n'
return '{cur_indent}{cls}({debug_details}{new_line}{pfargs}\n{cur_indent})'.format(**locals()) |
<SYSTEM_TASK:>
Return an expression where NOTs are only occurring as literals.
<END_TASK>
<USER_TASK:>
Description:
def literalize(self):
"""
Return an expression where NOTs are only occurring as literals.
""" |
expr = self.demorgan()
if isinstance(expr, self.__class__):
return expr
return expr.literalize() |
<SYSTEM_TASK:>
Return a simplified expr in canonical form.
<END_TASK>
<USER_TASK:>
Description:
def simplify(self):
"""
Return a simplified expr in canonical form.
This means double negations are canceled out and all contained boolean
objects are in their canonical form.
""" |
if self.iscanonical:
return self
expr = self.cancel()
if not isinstance(expr, self.__class__):
return expr.simplify()
if expr.args[0] in (self.TRUE, self.FALSE,):
return expr.args[0].dual
expr = self.__class__(expr.args[0].simplify())
expr.iscanonical = True
return expr |
<SYSTEM_TASK:>
Cancel itself and following NOTs as far as possible.
<END_TASK>
<USER_TASK:>
Description:
def cancel(self):
"""
Cancel itself and following NOTs as far as possible.
Returns the simplified expression.
""" |
expr = self
while True:
arg = expr.args[0]
if not isinstance(arg, self.__class__):
return expr
expr = arg.args[0]
if not isinstance(expr, self.__class__):
return expr |
<SYSTEM_TASK:>
Return a expr where the NOT function is moved inward.
<END_TASK>
<USER_TASK:>
Description:
def demorgan(self):
"""
Return a expr where the NOT function is moved inward.
This is achieved by canceling double NOTs and using De Morgan laws.
""" |
expr = self.cancel()
if expr.isliteral or not isinstance(expr, self.NOT):
return expr
op = expr.args[0]
return op.dual(*(self.__class__(arg).cancel() for arg in op.args)) |
<SYSTEM_TASK:>
Return a pretty formatted representation of self.
<END_TASK>
<USER_TASK:>
Description:
def pretty(self, indent=1, debug=False):
"""
Return a pretty formatted representation of self.
Include additional debug details if `debug` is True.
""" |
debug_details = ''
if debug:
debug_details += '<isliteral=%r, iscanonical=%r>' % (self.isliteral, self.iscanonical)
if self.isliteral:
pretty_literal = self.args[0].pretty(indent=0, debug=debug)
return (' ' * indent) + '%s(%s%s)' % (self.__class__.__name__, debug_details, pretty_literal)
else:
return super(NOT, self).pretty(indent=indent, debug=debug) |
<SYSTEM_TASK:>
Return a new simplified expression in canonical form from this
<END_TASK>
<USER_TASK:>
Description:
def simplify(self):
"""
Return a new simplified expression in canonical form from this
expression.
For simplification of AND and OR fthe ollowing rules are used
recursively bottom up:
- Associativity (output does not contain same operations nested)
- Annihilation
- Idempotence
- Identity
- Complementation
- Elimination
- Absorption
- Commutativity (output is always sorted)
Other boolean objects are also in their canonical form.
""" |
# TODO: Refactor DualBase.simplify into different "sub-evals".
# If self is already canonical do nothing.
if self.iscanonical:
return self
# Otherwise bring arguments into canonical form.
args = [arg.simplify() for arg in self.args]
# Create new instance of own class with canonical args.
# TODO: Only create new class if some args changed.
expr = self.__class__(*args)
# Literalize before doing anything, this also applies De Morgan's Law
expr = expr.literalize()
# Associativity:
# (A & B) & C = A & (B & C) = A & B & C
# (A | B) | C = A | (B | C) = A | B | C
expr = expr.flatten()
# Annihilation: A & 0 = 0, A | 1 = 1
if self.annihilator in expr.args:
return self.annihilator
# Idempotence: A & A = A, A | A = A
# this boils down to removing duplicates
args = []
for arg in expr.args:
if arg not in args:
args.append(arg)
if len(args) == 1:
return args[0]
# Identity: A & 1 = A, A | 0 = A
if self.identity in args:
args.remove(self.identity)
if len(args) == 1:
return args[0]
# Complementation: A & ~A = 0, A | ~A = 1
for arg in args:
if self.NOT(arg) in args:
return self.annihilator
# Elimination: (A & B) | (A & ~B) = A, (A | B) & (A | ~B) = A
i = 0
while i < len(args) - 1:
j = i + 1
ai = args[i]
if not isinstance(ai, self.dual):
i += 1
continue
while j < len(args):
aj = args[j]
if not isinstance(aj, self.dual) or len(ai.args) != len(aj.args):
j += 1
continue
# Find terms where only one arg is different.
negated = None
for arg in ai.args:
# FIXME: what does this pass Do?
if arg in aj.args:
pass
elif self.NOT(arg).cancel() in aj.args:
if negated is None:
negated = arg
else:
negated = None
break
else:
negated = None
break
# If the different arg is a negation simplify the expr.
if negated is not None:
# Cancel out one of the two terms.
del args[j]
aiargs = list(ai.args)
aiargs.remove(negated)
if len(aiargs) == 1:
args[i] = aiargs[0]
else:
args[i] = self.dual(*aiargs)
if len(args) == 1:
return args[0]
else:
# Now the other simplifications have to be redone.
return self.__class__(*args).simplify()
j += 1
i += 1
# Absorption: A & (A | B) = A, A | (A & B) = A
# Negative absorption: A & (~A | B) = A & B, A | (~A & B) = A | B
args = self.absorb(args)
if len(args) == 1:
return args[0]
# Commutativity: A & B = B & A, A | B = B | A
args.sort()
# Create new (now canonical) expression.
expr = self.__class__(*args)
expr.iscanonical = True
return expr |
<SYSTEM_TASK:>
Return a new expression where nested terms of this expression are
<END_TASK>
<USER_TASK:>
Description:
def flatten(self):
"""
Return a new expression where nested terms of this expression are
flattened as far as possible.
E.g. A & (B & C) becomes A & B & C.
""" |
args = list(self.args)
i = 0
for arg in self.args:
if isinstance(arg, self.__class__):
args[i:i + 1] = arg.args
i += len(arg.args)
else:
i += 1
return self.__class__(*args) |
<SYSTEM_TASK:>
Given an `args` sequence of expressions, return a new list of expression
<END_TASK>
<USER_TASK:>
Description:
def absorb(self, args):
"""
Given an `args` sequence of expressions, return a new list of expression
applying absorption and negative absorption.
See https://en.wikipedia.org/wiki/Absorption_law
Absorption: A & (A | B) = A, A | (A & B) = A
Negative absorption: A & (~A | B) = A & B, A | (~A & B) = A | B
""" |
args = list(args)
if not args:
args = list(self.args)
i = 0
while i < len(args):
absorber = args[i]
j = 0
while j < len(args):
if j == i:
j += 1
continue
target = args[j]
if not isinstance(target, self.dual):
j += 1
continue
# Absorption
if absorber in target:
del args[j]
if j < i:
i -= 1
continue
# Negative absorption
neg_absorber = self.NOT(absorber).cancel()
if neg_absorber in target:
b = target.subtract(neg_absorber, simplify=False)
if b is None:
del args[j]
if j < i:
i -= 1
continue
else:
args[j] = b
j += 1
continue
if isinstance(absorber, self.dual):
remove = None
for arg in absorber.args:
narg = self.NOT(arg).cancel()
if arg in target.args:
pass
elif narg in target.args:
if remove is None:
remove = narg
else:
remove = None
break
else:
remove = None
break
if remove is not None:
args[j] = target.subtract(remove, simplify=True)
j += 1
i += 1
return args |
<SYSTEM_TASK:>
Return a new expression where the `expr` expression has been removed
<END_TASK>
<USER_TASK:>
Description:
def subtract(self, expr, simplify):
"""
Return a new expression where the `expr` expression has been removed
from this expression if it exists.
""" |
args = self.args
if expr in self.args:
args = list(self.args)
args.remove(expr)
elif isinstance(expr, self.__class__):
if all(arg in self.args for arg in expr.args):
args = tuple(arg for arg in self.args if arg not in expr)
if len(args) == 0:
return None
if len(args) == 1:
return args[0]
newexpr = self.__class__(*args)
if simplify:
newexpr = newexpr.simplify()
return newexpr |
<SYSTEM_TASK:>
Return a term where the leading AND or OR terms are switched.
<END_TASK>
<USER_TASK:>
Description:
def distributive(self):
"""
Return a term where the leading AND or OR terms are switched.
This is done by applying the distributive laws:
A & (B|C) = (A&B) | (A&C)
A | (B&C) = (A|B) & (A|C)
""" |
dual = self.dual
args = list(self.args)
for i, arg in enumerate(args):
if isinstance(arg, dual):
args[i] = arg.args
else:
args[i] = (arg,)
prod = itertools.product(*args)
args = tuple(self.__class__(*arg).simplify() for arg in prod)
if len(args) == 1:
return args[0]
else:
return dual(*args) |
<SYSTEM_TASK:>
The age range that the user is interested in.
<END_TASK>
<USER_TASK:>
Description:
def ages(self):
"""The age range that the user is interested in.""" |
match = self._ages_re.match(self.raw_fields.get('ages'))
if not match:
match = self._ages_re2.match(self.raw_fields.get('ages'))
return self.Ages(int(match.group(1)),int(match.group(1)))
return self.Ages(int(match.group(1)), int(match.group(2))) |
<SYSTEM_TASK:>
Whether or not the user is only interested in people that are single.
<END_TASK>
<USER_TASK:>
Description:
def single(self):
"""Whether or not the user is only interested in people that are single.
""" |
return 'display: none;' not in self._looking_for_xpb.li(id='ajax_single').\
one_(self._profile.profile_tree).attrib['style'] |
<SYSTEM_TASK:>
Update the looking for attributes of the logged in user.
<END_TASK>
<USER_TASK:>
Description:
def update(self, ages=None, single=None, near_me=None, kinds=None,
gentation=None):
"""Update the looking for attributes of the logged in user.
:param ages: The ages that the logged in user is interested in.
:type ages: tuple
:param single: Whether or not the user is only interested in people that
are single.
:type single: bool
:param near_me: Whether or not the user is only interested in
people that are near them.
:type near_me: bool
:param kinds: What kinds of relationships the user should be updated to
be interested in.
:type kinds: list
:param gentation: The sex/orientation of people the user is interested
in.
:type gentation: str
""" |
ages = ages or self.ages
single = single if single is not None else self.single
near_me = near_me if near_me is not None else self.near_me
kinds = kinds or self.kinds
gentation = gentation or self.gentation
data = {
'okc_api': '1',
'searchprefs.submit': '1',
'update_prefs': '1',
'lquery': '',
'locid': '0',
'filter5': '1, 1' # TODO(@IvanMalison) Do this better...
}
if kinds:
kinds_numbers = self._build_kinds_numbers(kinds)
if kinds_numbers:
data['lookingfor'] = kinds_numbers
age_min, age_max = ages
data.update(looking_for_filters.legacy_build(
status=single, gentation=gentation, radius=25 if near_me else 0,
age_min=age_min, age_max=age_max
))
log.info(simplejson.dumps({'looking_for_update': data}))
util.cached_property.bust_caches(self)
response = self._profile.authcode_post('profileedit2', data=data)
self._profile.refresh(reload=False)
return response.content |
<SYSTEM_TASK:>
Upload the file to okcupid and confirm, among other things, its
<END_TASK>
<USER_TASK:>
Description:
def upload_and_confirm(self, incoming, **kwargs):
"""Upload the file to okcupid and confirm, among other things, its
thumbnail position.
:param incoming: A filepath string, :class:`.Info` object or
a file like object to upload to okcupid.com.
If an info object is provided, its thumbnail
positioning will be used by default.
:param caption: The caption to add to the photo.
:param thumb_nail_left: For thumb nail positioning.
:param thumb_nail_top: For thumb nail positioning.
:param thumb_nail_right: For thumb nail positioning.
:param thumb_nail_bottom: For thumb nail positioning.
""" |
response_dict = self.upload(incoming)
if 'error' in response_dict:
log.warning('Failed to upload photo')
return response_dict
if isinstance(incoming, Info):
kwargs.setdefault('thumb_nail_left', incoming.thumb_nail_left)
kwargs.setdefault('thumb_nail_top', incoming.thumb_nail_top)
kwargs.setdefault('thumb_nail_right', incoming.thumb_nail_right)
kwargs.setdefault('thumb_nail_bottom', incoming.thumb_nail_bottom)
kwargs['height'] = response_dict.get('height')
kwargs['width'] = response_dict.get('width')
self.confirm(response_dict['id'], **kwargs)
return response_dict |
<SYSTEM_TASK:>
Delete a photo from the logged in users account.
<END_TASK>
<USER_TASK:>
Description:
def delete(self, photo_id, album_id=0):
"""Delete a photo from the logged in users account.
:param photo_id: The okcupid id of the photo to delete.
:param album_id: The album from which to delete the photo.
""" |
if isinstance(photo_id, Info):
photo_id = photo_id.id
return self._session.okc_post('photoupload', data={
'albumid': album_id,
'picid': photo_id,
'authcode': self._authcode,
'picture.delete_ajax': 1
}) |
<SYSTEM_TASK:>
Returns the 'DBMS Version' string, or ''. If a connection to the
<END_TASK>
<USER_TASK:>
Description:
def __get_dbms_version(self, make_connection=True):
"""
Returns the 'DBMS Version' string, or ''. If a connection to the
database has not already been established, a connection will be made
when `make_connection` is True.
""" |
if not self.connection and make_connection:
self.connect()
with self.connection.cursor() as cursor:
cursor.execute("SELECT SERVERPROPERTY('productversion')")
return cursor.fetchone()[0] |
<SYSTEM_TASK:>
Respond to a question in exactly the way that is described by
<END_TASK>
<USER_TASK:>
Description:
def respond_from_user_question(self, user_question, importance):
"""Respond to a question in exactly the way that is described by
the given user_question.
:param user_question: The user question to respond with.
:type user_question: :class:`.UserQuestion`
:param importance: The importance that should be used in responding to
the question.
:type importance: int see :attr:`.importance_name_to_number`
""" |
user_response_ids = [option.id
for option in user_question.answer_options
if option.is_users]
match_response_ids = [option.id
for option in user_question.answer_options
if option.is_match]
if len(match_response_ids) == len(user_question.answer_options):
match_response_ids = 'irrelevant'
return self.respond(user_question.id, user_response_ids,
match_response_ids, importance,
note=user_question.explanation or '') |
<SYSTEM_TASK:>
Copy the answer given in `question` to the logged in user's
<END_TASK>
<USER_TASK:>
Description:
def respond_from_question(self, question, user_question, importance):
"""Copy the answer given in `question` to the logged in user's
profile.
:param question: A :class:`~.Question` instance to copy.
:param user_question: An instance of :class:`~.UserQuestion` that
corresponds to the same question as `question`.
This is needed to retrieve the answer id from
the question text answer on question.
:param importance: The importance to assign to the response to the
answered question.
""" |
option_index = user_question.answer_text_to_option[
question.their_answer
].id
self.respond(question.id, [option_index], [option_index], importance) |
<SYSTEM_TASK:>
Message an okcupid user. If an existing conversation between the
<END_TASK>
<USER_TASK:>
Description:
def message(self, username, message_text):
"""Message an okcupid user. If an existing conversation between the
logged in user and the target user can be found, reply to that thread
instead of starting a new one.
:param username: The username of the user to which the message should
be sent.
:type username: str
:param message_text: The body of the message.
:type message_text: str
""" |
# Try to reply to an existing thread.
if not isinstance(username, six.string_types):
username = username.username
for mailbox in (self.inbox, self.outbox):
for thread in mailbox:
if thread.correspondent.lower() == username.lower():
thread.reply(message_text)
return
return self._message_sender.send(username, message_text) |
<SYSTEM_TASK:>
Get the index of the answer that was given to `question`
<END_TASK>
<USER_TASK:>
Description:
def get_question_answer_id(self, question, fast=False,
bust_questions_cache=False):
"""Get the index of the answer that was given to `question`
See the documentation for :meth:`~.get_user_question` for important
caveats about the use of this function.
:param question: The question whose `answer_id` should be retrieved.
:type question: :class:`~okcupyd.question.BaseQuestion`
:param fast: Don't try to look through the users existing questions to
see if arbitrarily answering the question can be avoided.
:type fast: bool
:param bust_questions_cache: :param bust_questions_cache: clear the
:attr:`~okcupyd.profile.Profile.questions`
attribute of this users
:class:`~okcupyd.profile.Profile`
before looking for an existing answer.
Be aware that even this does not eliminate
all race conditions.
:type bust_questions_cache: bool
""" |
if hasattr(question, 'answer_id'):
# Guard to handle incoming user_question.
return question.answer_id
user_question = self.get_user_question(
question, fast=fast, bust_questions_cache=bust_questions_cache
)
# Look at recently answered questions
return user_question.get_answer_id_for_question(question) |
<SYSTEM_TASK:>
Return the default gentation for the given gender and orientation.
<END_TASK>
<USER_TASK:>
Description:
def get_default_gentation(gender, orientation):
"""Return the default gentation for the given gender and orientation.""" |
gender = gender.lower()[0]
orientation = orientation.lower()
return gender_to_orientation_to_gentation[gender][orientation] |
<SYSTEM_TASK:>
Update the mailbox associated with the given mailbox name.
<END_TASK>
<USER_TASK:>
Description:
def update_mailbox(self, mailbox_name='inbox'):
"""Update the mailbox associated with the given mailbox name.
""" |
with txn() as session:
last_updated_name = '{0}_last_updated'.format(mailbox_name)
okcupyd_user = session.query(model.OKCupydUser).join(model.User).filter(
model.User.okc_id == self._user.profile.id
).with_for_update().one()
log.info(simplejson.dumps({
'{0}_last_updated'.format(mailbox_name): helpers.datetime_to_string(
getattr(okcupyd_user, last_updated_name)
)
}))
res = self._sync_mailbox_until(
getattr(self._user, mailbox_name)(),
getattr(okcupyd_user, last_updated_name)
)
if not res:
return None, None
last_updated, threads, new_messages = res
if last_updated:
setattr(okcupyd_user, last_updated_name, last_updated)
return threads, new_messages |
<SYSTEM_TASK:>
Copy photos to the destination user.
<END_TASK>
<USER_TASK:>
Description:
def photos(self):
"""Copy photos to the destination user.""" |
# Reverse because pictures appear in inverse chronological order.
for photo_info in self.dest_user.profile.photo_infos:
self.dest_user.photo.delete(photo_info)
return [self.dest_user.photo.upload_and_confirm(info)
for info in reversed(self.source_profile.photo_infos)] |
<SYSTEM_TASK:>
Copy looking for attributes from the source profile to the
<END_TASK>
<USER_TASK:>
Description:
def looking_for(self):
"""Copy looking for attributes from the source profile to the
destination profile.
""" |
looking_for = self.source_profile.looking_for
return self.dest_user.profile.looking_for.update(
gentation=looking_for.gentation,
single=looking_for.single,
near_me=looking_for.near_me,
kinds=looking_for.kinds,
ages=looking_for.ages
) |
<SYSTEM_TASK:>
Message the user associated with this profile.
<END_TASK>
<USER_TASK:>
Description:
def message(self, message, thread_id=None):
"""Message the user associated with this profile.
:param message: The message to send to this user.
:param thread_id: The id of the thread to respond to, if any.
""" |
return_value = helpers.Messager(self._session).send(
self.username, message, self.authcode, thread_id
)
self.refresh(reload=False)
return return_value |
<SYSTEM_TASK:>
Rate this profile as the user that was logged in with the session
<END_TASK>
<USER_TASK:>
Description:
def rate(self, rating):
"""Rate this profile as the user that was logged in with the session
that this object was instantiated with.
:param rating: The rating to give this user.
""" |
parameters = {
'voterid': self._current_user_id,
'target_userid': self.id,
'type': 'vote',
'cf': 'profile2',
'target_objectid': 0,
'vote_type': 'personality',
'score': rating,
}
response = self._session.okc_post('vote_handler',
data=parameters)
response_json = response.json()
log_function = log.info if response_json.get('status', False) \
else log.error
log_function(simplejson.dumps({'rate_response': response_json,
'sent_parameters': parameters,
'headers': dict(self._session.headers)}))
self.refresh(reload=False) |
<SYSTEM_TASK:>
Build an evaluation checker that will return True when it is
<END_TASK>
<USER_TASK:>
Description:
def arity_evaluation_checker(function):
"""Build an evaluation checker that will return True when it is
guaranteed that all positional arguments have been accounted for.
""" |
is_class = inspect.isclass(function)
if is_class:
function = function.__init__
function_info = inspect.getargspec(function)
function_args = function_info.args
if is_class:
# This is to handle the fact that self will get passed in
# automatically.
function_args = function_args[1:]
def evaluation_checker(*args, **kwargs):
kwarg_keys = set(kwargs.keys())
if function_info.keywords is None:
acceptable_kwargs = function_args[len(args):]
# Make sure that we didn't get an argument we can't handle.
if not kwarg_keys.issubset(acceptable_kwargs):
TypeError("Unrecognized Arguments: {0}".format(
[key for key in kwarg_keys
if key not in acceptable_kwargs]
))
needed_args = function_args[len(args):]
if function_info.defaults:
needed_args = needed_args[:-len(function_info.defaults)]
return not needed_args or kwarg_keys.issuperset(needed_args)
return evaluation_checker |
<SYSTEM_TASK:>
Query workitems using the saved query url
<END_TASK>
<USER_TASK:>
Description:
def runSavedQueryByUrl(self, saved_query_url, returned_properties=None):
"""Query workitems using the saved query url
:param saved_query_url: the saved query url
:param returned_properties: the returned properties that you want.
Refer to :class:`rtcclient.client.RTCClient` for more explanations
:return: a :class:`list` that contains the queried
:class:`rtcclient.workitem.Workitem` objects
:rtype: list
""" |
try:
if "=" not in saved_query_url:
raise exception.BadValue()
saved_query_id = saved_query_url.split("=")[-1]
if not saved_query_id:
raise exception.BadValue()
except:
error_msg = "No saved query id is found in the url"
self.log.error(error_msg)
raise exception.BadValue(error_msg)
return self._runSavedQuery(saved_query_id,
returned_properties=returned_properties) |
<SYSTEM_TASK:>
Query workitems using the saved query id
<END_TASK>
<USER_TASK:>
Description:
def runSavedQueryByID(self, saved_query_id, returned_properties=None):
"""Query workitems using the saved query id
This saved query id can be obtained by below two methods:
1. :class:`rtcclient.models.SavedQuery` object (e.g.
mysavedquery.id)
2. your saved query url (e.g.
https://myrtc:9443/jazz/web/xxx#action=xxxx%id=_mGYe0CWgEeGofp83pg),
where the last "_mGYe0CWgEeGofp83pg" is the saved query id.
:param saved_query_id: the saved query id
:param returned_properties: the returned properties that you want.
Refer to :class:`rtcclient.client.RTCClient` for more explanations
:return: a :class:`list` that contains the queried
:class:`rtcclient.workitem.Workitem` objects
:rtype: list
""" |
if not isinstance(saved_query_id,
six.string_types) or not saved_query_id:
excp_msg = "Please specify a valid saved query id"
self.log.error(excp_msg)
raise exception.BadValue(excp_msg)
return self._runSavedQuery(saved_query_id,
returned_properties=returned_properties) |
<SYSTEM_TASK:>
Sends a PUT request. Refactor from requests module
<END_TASK>
<USER_TASK:>
Description:
def put(self, url, data=None, verify=False,
headers=None, proxies=None, timeout=60, **kwargs):
"""Sends a PUT request. Refactor from requests module
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, bytes, or file-like object to
send in the body of the :class:`Request`.
:param verify: (optional) if ``True``, the SSL cert will be verified.
A CA_BUNDLE path can also be provided.
:param headers: (optional) Dictionary of HTTP Headers to send with
the :class:`Request`.
:param proxies: (optional) Dictionary mapping protocol to the URL of
the proxy.
:param timeout: (optional) How long to wait for the server to send data
before giving up, as a float, or a :ref:`(connect timeout, read
timeout) <timeouts>` tuple.
:type timeout: float or tuple
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
""" |
self.log.debug("Put a request to %s with data: %s",
url, data)
response = requests.put(url, data=data,
verify=verify, headers=headers,
proxies=proxies, timeout=timeout, **kwargs)
if response.status_code not in [200, 201]:
self.log.error('Failed PUT request at <%s> with response: %s',
url,
response.content)
response.raise_for_status()
return response |
<SYSTEM_TASK:>
Strip and trailing slash to validate a url
<END_TASK>
<USER_TASK:>
Description:
def validate_url(cls, url):
"""Strip and trailing slash to validate a url
:param url: the url address
:return: the valid url address
:rtype: string
""" |
if url is None:
return None
url = url.strip()
while url.endswith('/'):
url = url[:-1]
return url |
<SYSTEM_TASK:>
Initialize the object from the request
<END_TASK>
<USER_TASK:>
Description:
def _initialize(self):
"""Initialize the object from the request""" |
self.log.debug("Start initializing data from %s",
self.url)
resp = self.get(self.url,
verify=False,
proxies=self.rtc_obj.proxies,
headers=self.rtc_obj.headers)
self.__initialize(resp)
self.log.info("Finish the initialization for <%s %s>",
self.__class__.__name__, self) |
<SYSTEM_TASK:>
Initialize from the response
<END_TASK>
<USER_TASK:>
Description:
def __initialize(self, resp):
"""Initialize from the response""" |
raw_data = xmltodict.parse(resp.content)
root_key = list(raw_data.keys())[0]
self.raw_data = raw_data.get(root_key)
self.__initializeFromRaw() |
<SYSTEM_TASK:>
Get template from some to-be-copied workitems
<END_TASK>
<USER_TASK:>
Description:
def getTemplate(self, copied_from, template_name=None,
template_folder=None, keep=False, encoding="UTF-8"):
"""Get template from some to-be-copied workitems
More details, please refer to
:class:`rtcclient.template.Templater.getTemplate`
""" |
return self.templater.getTemplate(copied_from,
template_name=template_name,
template_folder=template_folder,
keep=keep,
encoding=encoding) |
<SYSTEM_TASK:>
Get templates from a group of to-be-copied workitems
<END_TASK>
<USER_TASK:>
Description:
def getTemplates(self, workitems, template_folder=None,
template_names=None, keep=False, encoding="UTF-8"):
"""Get templates from a group of to-be-copied workitems
and write them to files named after the names in `template_names`
respectively.
More details, please refer to
:class:`rtcclient.template.Templater.getTemplates`
""" |
self.templater.getTemplates(workitems,
template_folder=template_folder,
template_names=template_names,
keep=keep,
encoding=encoding) |
<SYSTEM_TASK:>
List all the attributes to be rendered directly from some
<END_TASK>
<USER_TASK:>
Description:
def listFieldsFromWorkitem(self, copied_from, keep=False):
"""List all the attributes to be rendered directly from some
to-be-copied workitems
More details, please refer to
:class:`rtcclient.template.Templater.listFieldsFromWorkitem`
""" |
return self.templater.listFieldsFromWorkitem(copied_from,
keep=keep) |
<SYSTEM_TASK:>
Create a workitem
<END_TASK>
<USER_TASK:>
Description:
def createWorkitem(self, item_type, title, description=None,
projectarea_id=None, projectarea_name=None,
template=None, copied_from=None, keep=False,
**kwargs):
"""Create a workitem
:param item_type: the type of the workitem
(e.g. task/defect/issue)
:param title: the title of the new created workitem
:param description: the description of the new created workitem
:param projectarea_id: the :class:`rtcclient.project_area.ProjectArea`
id
:param projectarea_name: the project area name
:param template: The template to render.
The template is actually a file, which is usually generated
by :class:`rtcclient.template.Templater.getTemplate` and can also
be modified by user accordingly.
:param copied_from: the to-be-copied workitem id
:param keep: refer to `keep` in
:class:`rtcclient.template.Templater.getTemplate`. Only works when
`template` is not specified
:param \*\*kwargs: Optional/mandatory arguments when creating a new
workitem. More details, please refer to `kwargs` in
:class:`rtcclient.template.Templater.render`
:return: the :class:`rtcclient.workitem.Workitem` object
:rtype: rtcclient.workitem.Workitem
""" |
if not isinstance(projectarea_id,
six.string_types) or not projectarea_id:
projectarea = self.getProjectArea(projectarea_name)
projectarea_id = projectarea.id
else:
projectarea = self.getProjectAreaByID(projectarea_id)
itemtype = projectarea.getItemType(item_type)
if not template:
if not copied_from:
self.log.error("Please choose either-or between "
"template and copied_from")
raise exception.EmptyAttrib("At least choose either-or "
"between template and copied_from")
self._checkMissingParamsFromWorkitem(copied_from, keep=keep,
**kwargs)
kwargs = self._retrieveValidInfo(projectarea_id,
**kwargs)
wi_raw = self.templater.renderFromWorkitem(copied_from,
keep=keep,
encoding="UTF-8",
title=title,
description=description,
**kwargs)
else:
self._checkMissingParams(template, **kwargs)
kwargs = self._retrieveValidInfo(projectarea_id,
**kwargs)
wi_raw = self.templater.render(template,
title=title,
description=description,
**kwargs)
self.log.info("Start to create a new <%s> with raw data: %s",
item_type, wi_raw)
wi_url_post = "/".join([self.url,
"oslc/contexts",
projectarea_id,
"workitems/%s" % itemtype.identifier])
return self._createWorkitem(wi_url_post, wi_raw) |
<SYSTEM_TASK:>
Create a workitem by copying from an existing one
<END_TASK>
<USER_TASK:>
Description:
def copyWorkitem(self, copied_from, title=None, description=None,
prefix=None):
"""Create a workitem by copying from an existing one
:param copied_from: the to-be-copied workitem id
:param title: the new workitem title/summary.
If `None`, will copy that from a to-be-copied workitem
:param description: the new workitem description.
If `None`, will copy that from a to-be-copied workitem
:param prefix: used to add a prefix to the copied title and
description
:return: the :class:`rtcclient.workitem.Workitem` object
:rtype: rtcclient.workitem.Workitem
""" |
copied_wi = self.getWorkitem(copied_from)
if title is None:
title = copied_wi.title
if prefix is not None:
title = prefix + title
if description is None:
description = copied_wi.description
if prefix is not None:
description = prefix + description
self.log.info("Start to create a new <Workitem>, copied from ",
"<Workitem %s>", copied_from)
wi_url_post = "/".join([self.url,
"oslc/contexts/%s" % copied_wi.contextId,
"workitems",
"%s" % copied_wi.type.split("/")[-1]])
wi_raw = self.templater.renderFromWorkitem(copied_from,
keep=True,
encoding="UTF-8",
title=title,
description=description)
return self._createWorkitem(wi_url_post, wi_raw) |
<SYSTEM_TASK:>
Check the missing parameters for rendering from the template file
<END_TASK>
<USER_TASK:>
Description:
def _checkMissingParams(self, template, **kwargs):
"""Check the missing parameters for rendering from the template file
""" |
parameters = self.listFields(template)
self._findMissingParams(parameters, **kwargs) |
<SYSTEM_TASK:>
Check the missing parameters for rendering directly from the
<END_TASK>
<USER_TASK:>
Description:
def _checkMissingParamsFromWorkitem(self, copied_from, keep=False,
**kwargs):
"""Check the missing parameters for rendering directly from the
copied workitem
""" |
parameters = self.listFieldsFromWorkitem(copied_from,
keep=keep)
self._findMissingParams(parameters, **kwargs) |
<SYSTEM_TASK:>
Query workitems with the query string in a certain project area
<END_TASK>
<USER_TASK:>
Description:
def queryWorkitems(self, query_str, projectarea_id=None,
projectarea_name=None, returned_properties=None,
archived=False):
"""Query workitems with the query string in a certain project area
At least either of `projectarea_id` and `projectarea_name` is given
:param query_str: a valid query string
:param projectarea_id: the :class:`rtcclient.project_area.ProjectArea`
id
:param projectarea_name: the project area name
:param returned_properties: the returned properties that you want.
Refer to :class:`rtcclient.client.RTCClient` for more explanations
:param archived: (default is False) whether the workitems are archived
:return: a :class:`list` that contains the queried
:class:`rtcclient.workitem.Workitem` objects
:rtype: list
""" |
rp = returned_properties
return self.query.queryWorkitems(query_str=query_str,
projectarea_id=projectarea_id,
projectarea_name=projectarea_name,
returned_properties=rp,
archived=archived) |
<SYSTEM_TASK:>
Add a comment to this workitem
<END_TASK>
<USER_TASK:>
Description:
def addComment(self, msg=None):
"""Add a comment to this workitem
:param msg: comment message
:return: the :class:`rtcclient.models.Comment` object
:rtype: rtcclient.models.Comment
""" |
origin_comment = '''
<rdf:RDF
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:rtc_ext="http://jazz.net/xmlns/prod/jazz/rtc/ext/1.0/"
xmlns:rtc_cm="http://jazz.net/xmlns/prod/jazz/rtc/cm/1.0/"
xmlns:oslc_cm="http://open-services.net/ns/cm#"
xmlns:dcterms="http://purl.org/dc/terms/"
xmlns:oslc_cmx="http://open-services.net/ns/cm-x#"
xmlns:oslc="http://open-services.net/ns/core#">
<rdf:Description rdf:about="{0}">
<rdf:type rdf:resource="http://open-services.net/ns/core#Comment"/>
<dcterms:description rdf:parseType="Literal">{1}</dcterms:description>
</rdf:Description>
</rdf:RDF>
'''
comments_url = "/".join([self.url,
"rtc_cm:comments"])
headers = copy.deepcopy(self.rtc_obj.headers)
resp = self.get(comments_url,
verify=False,
proxies=self.rtc_obj.proxies,
headers=headers)
raw_data = xmltodict.parse(resp.content)
total_cnt = raw_data["oslc_cm:Collection"]["@oslc_cm:totalCount"]
comment_url = "/".join([comments_url,
total_cnt])
comment_msg = origin_comment.format(comment_url, msg)
headers["Content-Type"] = self.OSLC_CR_RDF
headers["Accept"] = self.OSLC_CR_RDF
headers["OSLC-Core-Version"] = "2.0"
headers["If-Match"] = resp.headers.get("etag")
req_url = "/".join([comments_url,
"oslc:comment"])
resp = self.post(req_url,
verify=False,
headers=headers,
proxies=self.rtc_obj.proxies,
data=comment_msg)
self.log.info("Successfully add comment: [%s] for <Workitem %s>",
msg, self)
raw_data = xmltodict.parse(resp.content)
return Comment(comment_url,
self.rtc_obj,
raw_data=raw_data["rdf:RDF"]["rdf:Description"]) |
<SYSTEM_TASK:>
Add a subscriber to this workitem
<END_TASK>
<USER_TASK:>
Description:
def addSubscriber(self, email):
"""Add a subscriber to this workitem
If the subscriber has already been added, no more actions will be
performed.
:param email: the subscriber's email
""" |
headers, raw_data = self._perform_subscribe()
existed_flag, raw_data = self._add_subscriber(email, raw_data)
if existed_flag:
return
self._update_subscribe(headers, raw_data)
self.log.info("Successfully add a subscriber: %s for <Workitem %s>",
email, self) |
<SYSTEM_TASK:>
Add subscribers to this workitem
<END_TASK>
<USER_TASK:>
Description:
def addSubscribers(self, emails_list):
"""Add subscribers to this workitem
If the subscribers have already been added, no more actions will be
performed.
:param emails_list: a :class:`list`/:class:`tuple`/:class:`set`
contains the the subscribers' emails
""" |
if not hasattr(emails_list, "__iter__"):
error_msg = "Input parameter 'emails_list' is not iterable"
self.log.error(error_msg)
raise exception.BadValue(error_msg)
# overall flag
existed_flags = False
headers, raw_data = self._perform_subscribe()
for email in emails_list:
existed_flag, raw_data = self._add_subscriber(email, raw_data)
existed_flags = existed_flags and existed_flag
if existed_flags:
return
self._update_subscribe(headers, raw_data)
self.log.info("Successfully add subscribers: %s for <Workitem %s>",
emails_list, self) |
<SYSTEM_TASK:>
Remove a subscriber from this workitem
<END_TASK>
<USER_TASK:>
Description:
def removeSubscriber(self, email):
"""Remove a subscriber from this workitem
If the subscriber has not been added, no more actions will be
performed.
:param email: the subscriber's email
""" |
headers, raw_data = self._perform_subscribe()
missing_flag, raw_data = self._remove_subscriber(email, raw_data)
if missing_flag:
return
self._update_subscribe(headers, raw_data)
self.log.info("Successfully remove a subscriber: %s for <Workitem %s>",
email, self) |
<SYSTEM_TASK:>
Remove subscribers from this workitem
<END_TASK>
<USER_TASK:>
Description:
def removeSubscribers(self, emails_list):
"""Remove subscribers from this workitem
If the subscribers have not been added, no more actions will be
performed.
:param emails_list: a :class:`list`/:class:`tuple`/:class:`set`
contains the the subscribers' emails
""" |
if not hasattr(emails_list, "__iter__"):
error_msg = "Input parameter 'emails_list' is not iterable"
self.log.error(error_msg)
raise exception.BadValue(error_msg)
# overall flag
missing_flags = True
headers, raw_data = self._perform_subscribe()
for email in emails_list:
missing_flag, raw_data = self._remove_subscriber(email, raw_data)
missing_flags = missing_flags and missing_flag
if missing_flags:
return
self._update_subscribe(headers, raw_data)
self.log.info("Successfully remove subscribers: %s for <Workitem %s>",
emails_list, self) |
<SYSTEM_TASK:>
Get the parent workitem of this workitem
<END_TASK>
<USER_TASK:>
Description:
def getParent(self, returned_properties=None):
"""Get the parent workitem of this workitem
If no parent, None will be returned.
:param returned_properties: the returned properties that you want.
Refer to :class:`rtcclient.client.RTCClient` for more explanations
:return: a :class:`rtcclient.workitem.Workitem` object
:rtype: rtcclient.workitem.Workitem
""" |
parent_tag = ("rtc_cm:com.ibm.team.workitem.linktype."
"parentworkitem.parent")
rp = returned_properties
parent = (self.rtc_obj
._get_paged_resources("Parent",
workitem_id=self.identifier,
customized_attr=parent_tag,
page_size="5",
returned_properties=rp))
# No more than one parent
if parent:
# only one element
return parent[0]
return None |
<SYSTEM_TASK:>
Get all the children workitems of this workitem
<END_TASK>
<USER_TASK:>
Description:
def getChildren(self, returned_properties=None):
"""Get all the children workitems of this workitem
If no children, None will be returned.
:param returned_properties: the returned properties that you want.
Refer to :class:`rtcclient.client.RTCClient` for more explanations
:return: a :class:`rtcclient.workitem.Workitem` object
:rtype: rtcclient.workitem.Workitem
""" |
children_tag = ("rtc_cm:com.ibm.team.workitem.linktype."
"parentworkitem.children")
rp = returned_properties
return (self.rtc_obj
._get_paged_resources("Children",
workitem_id=self.identifier,
customized_attr=children_tag,
page_size="10",
returned_properties=rp)) |
<SYSTEM_TASK:>
Get all the ChangeSets of this workitem
<END_TASK>
<USER_TASK:>
Description:
def getChangeSets(self):
"""Get all the ChangeSets of this workitem
:return: a :class:`list` contains all the
:class:`rtcclient.models.ChangeSet` objects
:rtype: list
""" |
changeset_tag = ("rtc_cm:com.ibm.team.filesystem.workitems."
"change_set.com.ibm.team.scm.ChangeSet")
return (self.rtc_obj
._get_paged_resources("ChangeSet",
workitem_id=self.identifier,
customized_attr=changeset_tag,
page_size="10")) |
<SYSTEM_TASK:>
Add a parent to current workitem
<END_TASK>
<USER_TASK:>
Description:
def addParent(self, parent_id):
"""Add a parent to current workitem
Notice: for a certain workitem, no more than one parent workitem
can be added and specified
:param parent_id: the parent workitem id/number
(integer or equivalent string)
""" |
if isinstance(parent_id, bool):
raise exception.BadValue("Please input a valid workitem id")
if isinstance(parent_id, six.string_types):
parent_id = int(parent_id)
if not isinstance(parent_id, int):
raise exception.BadValue("Please input a valid workitem id")
self.log.debug("Try to add a parent <Workitem %s> to current "
"<Workitem %s>",
parent_id,
self)
headers = copy.deepcopy(self.rtc_obj.headers)
headers["Content-Type"] = self.OSLC_CR_JSON
req_url = "".join([self.url,
"?oslc_cm.properties=com.ibm.team.workitem.",
"linktype.parentworkitem.parent"])
parent_tag = ("rtc_cm:com.ibm.team.workitem.linktype."
"parentworkitem.parent")
parent_url = ("{0}/resource/itemName/com.ibm.team."
"workitem.WorkItem/{1}".format(self.rtc_obj.url,
parent_id))
parent_original = {parent_tag: [{"rdf:resource": parent_url}]}
self.put(req_url,
verify=False,
proxies=self.rtc_obj.proxies,
headers=headers,
data=json.dumps(parent_original))
self.log.info("Successfully add a parent <Workitem %s> to current "
"<Workitem %s>",
parent_id,
self) |
<SYSTEM_TASK:>
Add a child to current workitem
<END_TASK>
<USER_TASK:>
Description:
def addChild(self, child_id):
"""Add a child to current workitem
:param child_id: the child workitem id/number
(integer or equivalent string)
""" |
self.log.debug("Try to add a child <Workitem %s> to current "
"<Workitem %s>",
child_id,
self)
self._addChildren([child_id])
self.log.info("Successfully add a child <Workitem %s> to current "
"<Workitem %s>",
child_id,
self) |
<SYSTEM_TASK:>
Add children to current workitem
<END_TASK>
<USER_TASK:>
Description:
def addChildren(self, child_ids):
"""Add children to current workitem
:param child_ids: a :class:`list` contains the children
workitem id/number (integer or equivalent string)
""" |
if not hasattr(child_ids, "__iter__"):
error_msg = "Input parameter 'child_ids' is not iterable"
self.log.error(error_msg)
raise exception.BadValue(error_msg)
self.log.debug("Try to add children <Workitem %s> to current "
"<Workitem %s>",
child_ids,
self)
self._addChildren(child_ids)
self.log.info("Successfully add children <Workitem %s> to current "
"<Workitem %s>",
child_ids,
self) |
<SYSTEM_TASK:>
Remove the parent workitem from current workitem
<END_TASK>
<USER_TASK:>
Description:
def removeParent(self):
"""Remove the parent workitem from current workitem
Notice: for a certain workitem, no more than one parent workitem
can be added and specified
""" |
self.log.debug("Try to remove the parent workitem from current "
"<Workitem %s>",
self)
headers = copy.deepcopy(self.rtc_obj.headers)
headers["Content-Type"] = self.OSLC_CR_JSON
req_url = "".join([self.url,
"?oslc_cm.properties=com.ibm.team.workitem.",
"linktype.parentworkitem.parent"])
parent_tag = ("rtc_cm:com.ibm.team.workitem.linktype."
"parentworkitem.parent")
parent_original = {parent_tag: []}
self.put(req_url,
verify=False,
proxies=self.rtc_obj.proxies,
headers=headers,
data=json.dumps(parent_original))
self.log.info("Successfully remove the parent workitem of current "
"<Workitem %s>",
self) |
<SYSTEM_TASK:>
Remove a child from current workitem
<END_TASK>
<USER_TASK:>
Description:
def removeChild(self, child_id):
"""Remove a child from current workitem
:param child_id: the child workitem id/number
(integer or equivalent string)
""" |
self.log.debug("Try to remove a child <Workitem %s> from current "
"<Workitem %s>",
child_id,
self)
self._removeChildren([child_id])
self.log.info("Successfully remove a child <Workitem %s> from "
"current <Workitem %s>",
child_id,
self) |
<SYSTEM_TASK:>
Remove children from current workitem
<END_TASK>
<USER_TASK:>
Description:
def removeChildren(self, child_ids):
"""Remove children from current workitem
:param child_ids: a :class:`list` contains the children
workitem id/number (integer or equivalent string)
""" |
if not hasattr(child_ids, "__iter__"):
error_msg = "Input parameter 'child_ids' is not iterable"
self.log.error(error_msg)
raise exception.BadValue(error_msg)
self.log.debug("Try to remove children <Workitem %s> from current "
"<Workitem %s>",
child_ids,
self)
self._removeChildren(child_ids)
self.log.info("Successfully remove children <Workitem %s> from "
"current <Workitem %s>",
child_ids,
self) |
<SYSTEM_TASK:>
Upload attachment to a workitem
<END_TASK>
<USER_TASK:>
Description:
def addAttachment(self, filepath):
"""Upload attachment to a workitem
:param filepath: the attachment file path
:return: the :class:`rtcclient.models.Attachment` object
:rtype: rtcclient.models.Attachment
""" |
proj_id = self.contextId
fa = self.rtc_obj.getFiledAgainst(self.filedAgainst,
projectarea_id=proj_id)
fa_id = fa.url.split("/")[-1]
headers = copy.deepcopy(self.rtc_obj.headers)
if headers.__contains__("Content-Type"):
headers.__delitem__("Content-Type")
filename = os.path.basename(filepath)
fileh = open(filepath, "rb")
files = {"attach": (filename, fileh, "application/octet-stream")}
params = {"projectId": proj_id,
"multiple": "true",
"category": fa_id}
req_url = "".join([self.rtc_obj.url,
"/service/com.ibm.team.workitem.service.",
"internal.rest.IAttachmentRestService/"])
resp = self.post(req_url,
verify=False,
headers=headers,
proxies=self.rtc_obj.proxies,
params=params,
files=files)
raw_data = xmltodict.parse(resp.content)
json_body = json.loads(raw_data["html"]["body"]["textarea"])
attachment_info = json_body["files"][0]
return self._add_attachment_link(attachment_info) |
<SYSTEM_TASK:>
List the containers on the system.
<END_TASK>
<USER_TASK:>
Description:
def list_containers(active=True, defined=True,
as_object=False, config_path=None):
"""
List the containers on the system.
""" |
if config_path:
if not os.path.exists(config_path):
return tuple()
try:
entries = _lxc.list_containers(active=active, defined=defined,
config_path=config_path)
except ValueError:
return tuple()
else:
try:
entries = _lxc.list_containers(active=active, defined=defined)
except ValueError:
return tuple()
if as_object:
return tuple([Container(name, config_path) for name in entries])
else:
return entries |
<SYSTEM_TASK:>
Run a command when attaching
<END_TASK>
<USER_TASK:>
Description:
def attach_run_command(cmd):
"""
Run a command when attaching
Please do not call directly, this will execvp the command.
This is to be used in conjunction with the attach method
of a container.
""" |
if isinstance(cmd, tuple):
return _lxc.attach_run_command(cmd)
elif isinstance(cmd, list):
return _lxc.attach_run_command((cmd[0], cmd))
else:
return _lxc.attach_run_command((cmd, [cmd])) |
<SYSTEM_TASK:>
Determine the process personality corresponding to the architecture
<END_TASK>
<USER_TASK:>
Description:
def arch_to_personality(arch):
"""
Determine the process personality corresponding to the architecture
""" |
if isinstance(arch, bytes):
arch = unicode(arch)
return _lxc.arch_to_personality(arch) |
<SYSTEM_TASK:>
Add network device to running container.
<END_TASK>
<USER_TASK:>
Description:
def add_device_net(self, name, destname=None):
"""
Add network device to running container.
""" |
if not self.running:
return False
if os.path.exists("/sys/class/net/%s/phy80211/name" % name):
with open("/sys/class/net/%s/phy80211/name" % name) as fd:
phy = fd.read().strip()
if subprocess.call(['iw', 'phy', phy, 'set', 'netns',
str(self.init_pid)]) != 0:
return False
if destname:
def rename_interface(args):
old, new = args
return subprocess.call(['ip', 'link', 'set',
'dev', old, 'name', new])
return self.attach_wait(rename_interface, (name, destname),
namespaces=(CLONE_NEWNET)) == 0
return True
if not destname:
destname = name
if not os.path.exists("/sys/class/net/%s/" % name):
return False
return subprocess.call(['ip', 'link', 'set',
'dev', name,
'netns', str(self.init_pid),
'name', destname]) == 0 |
<SYSTEM_TASK:>
Append 'value' to 'key', assuming 'key' is a list.
<END_TASK>
<USER_TASK:>
Description:
def append_config_item(self, key, value):
"""
Append 'value' to 'key', assuming 'key' is a list.
If 'key' isn't a list, 'value' will be set as the value of 'key'.
""" |
return _lxc.Container.set_config_item(self, key, value) |
<SYSTEM_TASK:>
Create a new rootfs for the container.
<END_TASK>
<USER_TASK:>
Description:
def create(self, template=None, flags=0, args=()):
"""
Create a new rootfs for the container.
"template" if passed must be a valid template name.
"flags" (optional) is an integer representing the optional
create flags to be passed.
"args" (optional) is a tuple of arguments to pass to the
template. It can also be provided as a dict.
""" |
if isinstance(args, dict):
template_args = []
for item in args.items():
template_args.append("--%s" % item[0])
template_args.append("%s" % item[1])
else:
template_args = args
if template:
return _lxc.Container.create(self, template=template,
flags=flags,
args=tuple(template_args))
else:
return _lxc.Container.create(self, flags=flags,
args=tuple(template_args)) |
<SYSTEM_TASK:>
Clone the current container.
<END_TASK>
<USER_TASK:>
Description:
def clone(self, newname, config_path=None, flags=0, bdevtype=None,
bdevdata=None, newsize=0, hookargs=()):
"""
Clone the current container.
""" |
args = {}
args['newname'] = newname
args['flags'] = flags
args['newsize'] = newsize
args['hookargs'] = hookargs
if config_path:
args['config_path'] = config_path
if bdevtype:
args['bdevtype'] = bdevtype
if bdevdata:
args['bdevdata'] = bdevdata
if _lxc.Container.clone(self, **args):
return Container(newname, config_path=config_path)
else:
return False |
<SYSTEM_TASK:>
Returns the value for a given cgroup entry.
<END_TASK>
<USER_TASK:>
Description:
def get_cgroup_item(self, key):
"""
Returns the value for a given cgroup entry.
A list is returned when multiple values are set.
""" |
value = _lxc.Container.get_cgroup_item(self, key)
if value is False:
return False
else:
return value.rstrip("\n") |
<SYSTEM_TASK:>
Returns the value for a given config key.
<END_TASK>
<USER_TASK:>
Description:
def get_config_item(self, key):
"""
Returns the value for a given config key.
A list is returned when multiple values are set.
""" |
value = _lxc.Container.get_config_item(self, key)
if value is False:
return False
elif value.endswith("\n"):
return value.rstrip("\n").split("\n")
else:
return value |
<SYSTEM_TASK:>
Returns a list of valid sub-keys.
<END_TASK>
<USER_TASK:>
Description:
def get_keys(self, key=None):
"""
Returns a list of valid sub-keys.
""" |
if key:
value = _lxc.Container.get_keys(self, key)
else:
value = _lxc.Container.get_keys(self)
if value is False:
return False
elif value.endswith("\n"):
return value.rstrip("\n").split("\n")
else:
return value |
<SYSTEM_TASK:>
Get a tuple of IPs for the container.
<END_TASK>
<USER_TASK:>
Description:
def get_ips(self, interface=None, family=None, scope=None, timeout=0):
"""
Get a tuple of IPs for the container.
""" |
kwargs = {}
if interface:
kwargs['interface'] = interface
if family:
kwargs['family'] = family
if scope:
kwargs['scope'] = scope
ips = None
timeout = int(os.environ.get('LXC_GETIP_TIMEOUT', timeout))
while not ips:
ips = _lxc.Container.get_ips(self, **kwargs)
if timeout == 0:
break
timeout -= 1
time.sleep(1)
return ips |
<SYSTEM_TASK:>
Rename the container.
<END_TASK>
<USER_TASK:>
Description:
def rename(self, new_name):
"""
Rename the container.
On success, returns the new Container object.
On failure, returns False.
""" |
if _lxc.Container.rename(self, new_name):
return Container(new_name)
return False |
<SYSTEM_TASK:>
Set a config key to a provided value.
<END_TASK>
<USER_TASK:>
Description:
def set_config_item(self, key, value):
"""
Set a config key to a provided value.
The value can be a list for the keys supporting multiple values.
""" |
try:
old_value = self.get_config_item(key)
except KeyError:
old_value = None
# Get everything to unicode with python2
if isinstance(value, str):
value = value.decode()
elif isinstance(value, list):
for i in range(len(value)):
if isinstance(value[i], str):
value[i] = value[i].decode()
# Check if it's a list
def set_key(key, value):
self.clear_config_item(key)
if isinstance(value, list):
for entry in value:
if not _lxc.Container.set_config_item(self, key, entry):
return False
else:
_lxc.Container.set_config_item(self, key, value)
set_key(key, value)
new_value = self.get_config_item(key)
# loglevel is special and won't match the string we set
if key == "lxc.loglevel":
new_value = value
if (isinstance(value, unicode) and isinstance(new_value, unicode) and
value == new_value):
return True
elif (isinstance(value, list) and isinstance(new_value, list) and
set(value) == set(new_value)):
return True
elif (isinstance(value, unicode) and isinstance(new_value, list) and
set([value]) == set(new_value)):
return True
elif old_value:
set_key(key, old_value)
return False
else:
self.clear_config_item(key)
return False |
<SYSTEM_TASK:>
Wait for the container to reach a given state or timeout.
<END_TASK>
<USER_TASK:>
Description:
def wait(self, state, timeout=-1):
"""
Wait for the container to reach a given state or timeout.
""" |
if isinstance(state, str):
state = state.upper()
return _lxc.Container.wait(self, state, timeout) |
<SYSTEM_TASK:>
Renders the template
<END_TASK>
<USER_TASK:>
Description:
def render(self, template, **kwargs):
"""Renders the template
:param template: The template to render.
The template is actually a file, which is usually generated
by :class:`rtcclient.template.Templater.getTemplate`
and can also be modified by user accordingly.
:param kwargs: The `kwargs` dict is used to fill the template.
These two parameter are mandatory:
* description
* title
Some of below parameters (which may not be included in some
customized workitem type ) are mandatory if `keep` (parameter in
:class:`rtcclient.template.Templater.getTemplate`) is set to
`False`; Optional for otherwise.
* teamArea (Team Area)
* ownedBy (Owned By)
* plannedFor(Planned For)
* severity(Severity)
* priority(Priority)
* filedAgainst(Filed Against)
Actually all these needed keywords/attributes/fields can be
retrieved by :class:`rtcclient.template.Templater.listFields`
:return: the :class:`string` object
:rtype: string
""" |
try:
temp = self.environment.get_template(template)
return temp.render(**kwargs)
except AttributeError:
err_msg = "Invalid value for 'template'"
self.log.error(err_msg)
raise exception.BadValue(err_msg) |
<SYSTEM_TASK:>
List all the attributes to be rendered from the template file
<END_TASK>
<USER_TASK:>
Description:
def listFields(self, template):
"""List all the attributes to be rendered from the template file
:param template: The template to render.
The template is actually a file, which is usually generated
by :class:`rtcclient.template.Templater.getTemplate` and can also
be modified by user accordingly.
:return: a :class:`set` contains all the needed attributes
:rtype: set
""" |
try:
temp_source = self.environment.loader.get_source(self.environment,
template)
return self.listFieldsFromSource(temp_source)
except AttributeError:
err_msg = "Invalid value for 'template'"
self.log.error(err_msg)
raise exception.BadValue(err_msg) |
<SYSTEM_TASK:>
List all the attributes to be rendered directly from template
<END_TASK>
<USER_TASK:>
Description:
def listFieldsFromSource(self, template_source):
"""List all the attributes to be rendered directly from template
source
:param template_source: the template source (usually represents the
template content in string format)
:return: a :class:`set` contains all the needed attributes
:rtype: set
""" |
ast = self.environment.parse(template_source)
return jinja2.meta.find_undeclared_variables(ast) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.