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 run(self):
""" Runs the CWD's scent file. """
|
if not self.scent or len(self.scent.runners) == 0:
print("Did not find 'scent.py', running nose:")
return super(ScentSniffer, self).run()
else:
print("Using scent:")
arguments = [sys.argv[0]] + list(self.test_args)
return self.scent.run(arguments)
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 copy(self):
""" Return a copy of this object. """
|
self_copy = self.dup()
self_copy._scopes = copy.copy(self._scopes)
return self_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 bind(self, *args, **kw):
""" Bind environment variables into this object's scope. """
|
new_self = self.copy()
new_scopes = Object.translate_to_scopes(*args, **kw)
new_self._scopes = tuple(reversed(new_scopes)) + new_self._scopes
return new_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 check(self):
""" Type check this object. """
|
try:
si, uninterp = self.interpolate()
# TODO(wickman) This should probably be pushed out to the interpolate leaves.
except (Object.CoercionError, MustacheParser.Uninterpolatable) as e:
return TypeCheck(False, "Unable to interpolate: %s" % e)
return self.checker(si)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def restore(self):
""" Unloads all modules that weren't loaded when save_modules was called. """
|
sys = set(self._sys_modules.keys())
for mod_name in sys.difference(self._saved_modules):
del self._sys_modules[mod_name]
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def join(cls, splits, *namables):
""" Interpolate strings. :params splits: The output of Parser.split(string) :params namables: A sequence of Namable objects in which the interpolation should take place. Returns 2-tuple containing: joined string, list of unbound object ids (potentially empty) """
|
isplits = []
unbound = []
for ref in splits:
if isinstance(ref, Ref):
resolved = False
for namable in namables:
try:
value = namable.find(ref)
resolved = True
break
except Namable.Error:
continue
if resolved:
isplits.append(value)
else:
isplits.append(ref)
unbound.append(ref)
else:
isplits.append(ref)
return (''.join(map(str if Compatibility.PY3 else unicode, isplits)), unbound)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def outitem(title, elems, indent=4):
"""Output formatted as list item."""
|
out(title)
max_key_len = max(len(key) for key, _ in elems) + 1
for key, val in elems:
key_spaced = ('%s:' % key).ljust(max_key_len)
out('%s%s %s' % (indent * ' ', key_spaced, val))
out()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def profile_dir(name):
"""Return path to FF profile for a given profile name or path."""
|
if name:
possible_path = Path(name)
if possible_path.exists():
return possible_path
profiles = list(read_profiles())
try:
if name:
profile = next(p for p in profiles if p.name == name)
else:
profile = next(p for p in profiles if p.default)
except StopIteration:
raise ProfileNotFoundError(name)
return profile.path
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def formatter(name, default=False):
"""Decorate a Feature method to register it as an output formatter. All formatters are picked up by the argument parser so that they can be listed and selected on the CLI via the -f, --format argument. """
|
def decorator(func):
func._output_format = dict(name=name, default=default)
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 load_sqlite(self, db, query=None, table=None, cls=None, column_map=None):
"""Load data from sqlite db and return as list of specified objects."""
|
if column_map is None:
column_map = {}
db_path = self.profile_path(db, must_exist=True)
def obj_factory(cursor, row):
dict_ = {}
for idx, col in enumerate(cursor.description):
new_name = column_map.get(col[0], col[0])
dict_[new_name] = row[idx]
return cls(**dict_)
con = sqlite3.connect(str(db_path))
con.row_factory = obj_factory
cursor = con.cursor()
if not query:
columns = [f.name for f in attr.fields(cls)]
for k, v in column_map.items():
columns[columns.index(v)] = k
query = 'SELECT %s FROM %s' % (','.join(columns), table)
cursor.execute(query)
while True:
item = cursor.fetchone()
if item is None:
break
yield item
con.close()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_json(self, path):
"""Load a JSON file from the user profile."""
|
with open(self.profile_path(path, must_exist=True),
encoding='utf-8') as f:
data = json.load(f)
return data
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_mozlz4(self, path):
"""Load a Mozilla LZ4 file from the user profile. Mozilla LZ4 is regular LZ4 with a custom string prefix. """
|
with open(self.profile_path(path, must_exist=True), 'rb') as f:
if f.read(8) != b'mozLz40\0':
raise NotMozLz4Error('Not Mozilla LZ4 format.')
data = lz4.block.decompress(f.read())
return data
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def profile_path(self, path, must_exist=False):
"""Return path from current profile."""
|
full_path = self.session.profile / path
if must_exist and not full_path.exists():
raise FileNotFoundError(
errno.ENOENT,
os.strerror(errno.ENOENT),
PurePath(full_path).name,
)
return full_path
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_descriptor(self, descriptor):
"""Convert descriptor to BigQuery """
|
# Fields
fields = []
fallbacks = []
schema = tableschema.Schema(descriptor)
for index, field in enumerate(schema.fields):
converted_type = self.convert_type(field.type)
if not converted_type:
converted_type = 'STRING'
fallbacks.append(index)
mode = 'NULLABLE'
if field.required:
mode = 'REQUIRED'
fields.append({
'name': _slugify_field_name(field.name),
'type': converted_type,
'mode': mode,
})
# Descriptor
converted_descriptor = {
'fields': fields,
}
return (converted_descriptor, fallbacks)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_row(self, row, schema, fallbacks):
"""Convert row to BigQuery """
|
for index, field in enumerate(schema.fields):
value = row[index]
if index in fallbacks:
value = _uncast_value(value, field=field)
else:
value = field.cast_value(value)
row[index] = value
return row
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_type(self, type):
"""Convert type to BigQuery """
|
# Mapping
mapping = {
'any': 'STRING',
'array': None,
'boolean': 'BOOLEAN',
'date': 'DATE',
'datetime': 'DATETIME',
'duration': None,
'geojson': None,
'geopoint': None,
'integer': 'INTEGER',
'number': 'FLOAT',
'object': None,
'string': 'STRING',
'time': 'TIME',
'year': 'INTEGER',
'yearmonth': None,
}
# 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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def restore_descriptor(self, converted_descriptor):
"""Restore descriptor rom BigQuery """
|
# Convert
fields = []
for field in converted_descriptor['fields']:
field_type = self.restore_type(field['type'])
resfield = {
'name': field['name'],
'type': field_type,
}
if field.get('mode', 'NULLABLE') != 'NULLABLE':
resfield['constraints'] = {'required': True}
fields.append(resfield)
descriptor = {'fields': fields}
return descriptor
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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: 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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_looking_for(profile_tree, looking_for):
""" Update looking_for attribute of a Profile. """
|
div = profile_tree.xpath("//div[@id = 'what_i_want']")[0]
looking_for['gentation'] = div.xpath(".//li[@id = 'ajax_gentation']/text()")[0].strip()
looking_for['ages'] = replace_chars(div.xpath(".//li[@id = 'ajax_ages']/text()")[0].strip())
looking_for['near'] = div.xpath(".//li[@id = 'ajax_near']/text()")[0].strip()
looking_for['single'] = div.xpath(".//li[@id = 'ajax_single']/text()")[0].strip()
try:
looking_for['seeking'] = div.xpath(".//li[@id = 'ajax_lookingfor']/text()")[0].strip()
except:
pass
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_details(profile_tree, details):
""" Update details attribute of a Profile. """
|
div = profile_tree.xpath("//div[@id = 'profile_details']")[0]
for dl in div.iter('dl'):
title = dl.find('dt').text
item = dl.find('dd')
if title == 'Last Online' and item.find('span') is not None:
details[title.lower()] = item.find('span').text.strip()
elif title.lower() in details and len(item.text):
details[title.lower()] = item.text.strip()
else:
continue
details[title.lower()] = replace_chars(details[title.lower()])
|
<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_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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def essays(self):
"""Copy essays from the source profile to the destination profile."""
|
for essay_name in self.dest_user.profile.essays.essay_names:
setattr(self.dest_user.profile.essays, essay_name,
getattr(self.source_profile.essays, essay_name))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def details(self):
"""Copy details from the source profile to the destination profile."""
|
return self.dest_user.profile.details.convert_and_update(
self.source_profile.details.as_dict
)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rerecord(ctx, rest):
"""Rerecord tests."""
|
run('tox -e py27 -- --cassette-mode all --record --credentials {0} -s'
.format(rest), pty=True)
run('tox -e py27 -- --resave --scrub --credentials test_credentials {0} -s'
.format(rest), pty=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 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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.