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(argume...
<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 ...
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: ...
<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)...
<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 th...
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_[ne...
<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.asdic...
<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><Operat...
# ~~~ 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.passw...
<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_resp...
<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 configurat...
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(config...
<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:...
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: ...
<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...
_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 o...
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) ...
<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...
<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) respo...
<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 sp...
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' fall...
<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', ...
<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') != 'NULLAB...
<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]).ti...
<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 n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _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)) ...
<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,...
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 implement...
<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) dualo...
<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 argu...
# 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) ...
<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,...
<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 informatio...
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) annihilat...
<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 c...
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()) ...
<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__, d...
<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 ...
# 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 o...
<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....
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...
<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...
<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&...
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 ar...
<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 = 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.su...
<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 filep...
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_na...
<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_...
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 establishe...
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_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_mat...
<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 ...
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, r...
# 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(): thr...
<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 documenta...
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 ...
<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()...
<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.low...
<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.du...
<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:...
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...
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...
<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 accoun...
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 # automatical...
<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...
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" ...
<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 t...
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, ...
<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: ...
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 ...
<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.lo...
<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...
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 workite...
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, plea...
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): ...
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 = p...
<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-b...
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: ...
<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 stri...
rp = returned_properties return self.query.queryWorkitems(query_str=query_str, projectarea_id=projectarea_id, projectarea_name=projectarea_name, 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 addComment(self, msg=None): """Add a comment to this workitem :param msg: comment message :return: the :class:`rtcclient.models.Comment` object :rtype: rtccl...
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/te...
<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: t...
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>", ...
<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 ...
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() ...
<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 emai...
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>", ...
<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. :pa...
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() ...
<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 r...
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, ...
<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_proper...
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, ...
<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:...
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, ...
<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 :...
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"...
<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 ...