text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_argv_for_command(self): """ Returns stripped arguments that would be passed into the command. """
argv = [a for a in self.argv] argv.insert(0, self.prog_name) return 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 execute(self): """ Executes whole process of parsing and running command. """
self.autocomplete() if len(self.argv): cmd = self.argv[0] cmd_argv = self.get_argv_for_command() self.run_command(cmd, cmd_argv) else: self.show_help()
<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_command_class(self, cmd): """ Returns command class from the registry for a given ``cmd``. :param cmd: command to run (key at the registry) """
try: cmdpath = self.registry[cmd] except KeyError: raise CommandError("No such command %r" % cmd) if isinstance(cmdpath, basestring): Command = import_class(cmdpath) else: Command = cmdpath return 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 run_command(self, cmd, argv): """ Runs command. :param cmd: command to run (key at the registry) :param argv: arguments passed to the command """
try: Command = self.get_command_class(cmd) except CommandError, e: self.stderr.write(str(e) + '\n') self.show_help() sys.exit(-1) command = Command(stdout=self.stdout, stderr=self.stderr) command.run_from_argv(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 show_help(self): """ Prints help text about available commands. """
output = [ 'Usage %s subcommand [options] [args]' % self.prog_name, '', 'Available commands:', '', ] for cmd in self.get_commands(): output.append(' %s' % cmd) output += ['', ''] self.stdout.write(u'\n'.join(output))
<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_parser(self, prog_name, subcommand): """ Returns parser for given ``prog_name`` and ``subcommand``. :param prog_name: vcs main script name :param subcomm...
parser = OptionParser( prog=prog_name, usage=self.usage(subcommand), version=self.get_version(), option_list=sorted(self.get_option_list())) return parser
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_help(self, prog_name, subcommand): """ Prints parser's help. :param prog_name: vcs main script name :param subcommand: command name """
parser = self.get_parser(prog_name, subcommand) parser.print_help()
<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_from_argv(self, argv): """ Runs command for given arguments. :param argv: arguments """
parser = self.get_parser(argv[0], argv[1]) options, args = parser.parse_args(argv[2:]) self.execute(*args, **options.__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 execute(self, *args, **options): """ Executes whole process of parsing arguments, running command and trying to catch errors. """
try: self.handle(*args, **options) except CommandError, e: if options['debug']: try: import ipdb ipdb.set_trace() except ImportError: import pdb pdb.set_trace() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle(self, *args, **options): """ Runs ``pre_process``, ``handle_repo`` and ``post_process`` methods, in that order. """
self.pre_process(self.repo) self.handle_repo(self.repo, *args, **options) self.post_process(self.repo, **options)
<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_changesets(self, repo, **options): """ Returns generator of changesets from given ``repo`` for given ``options``. :param repo: repository instance. Same ...
branch_name = None if not options.get('all', None): branch_name = options.get('branch') or repo.workdir.get_branch() if options.get('start_date'): options['start_date'] = parse_datetime(options['start_date']) if options.get('end_date'): options['end_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 get_progressbar(self, total, **options): """ Returns progress bar instance for a given ``total`` number of clicks it should do. """
progressbar = ColoredProgressBar(total) progressbar.steps_label = 'Commit' progressbar.elements += ['eta', 'time'] return progressbar
<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_changeset(self, **options): """ Returns changeset for given ``options``. """
cid = options.get('changeset_id', None) return self.repo.get_changeset(cid)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pprint(data, indent=0, end='\n'): """Pretty print JSON data. Parameters data JSON data. indent : `int`, optional Indent level in characters (default: 0). end...
if isinstance(data, dict): print('{') new_indent = indent + 4 space = ' ' * new_indent keys = list(sorted(data.keys())) for i, k in enumerate(keys): print(space, json.dumps(k), ': ', sep='', end='') pprint(data[k], new_indent, end='...
<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(cls, fname, args): """Load a generator. Parameters cls : `type` Generator class. fname : `str` Input file path. args : `argparse.Namespace` Command argu...
if args.type == JSON: if fname.endswith('.bz2'): open_ = bz2.open else: open_ = open if args.progress: print('Loading JSON data...') with open_(fname, 'rt') as fp: storage = JsonStorage.load(fp) else: storage = SqliteSto...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(markov, fname, args): """Save a generator. Parameters markov : `markovchain.Markov` Generator to save. fname : `str` Output file path. args : `argparse....
if isinstance(markov.storage, JsonStorage): if fname is None: markov.save(sys.stdout) else: if fname.endswith('.bz2'): open_ = bz2.open else: open_ = open if args.progress: print('Saving JSON 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 save_image(img, fname): """Save an image. Parameters img : `PIL.Image` Image to save. fname : `str` File path. """
_, ext = os.path.splitext(fname) ext = ext[1:] or 'png' with open(fname, 'wb') as fp: img.save(fp, ext)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_args(args): """Set computed command arguments. Parameters args : `argparse.Namespace` Command arguments. base : `iterable` of `type` Generator mixins. Ra...
try: if args.output is sys.stdout and args.progress: raise ValueError('args.output is stdout and args.progress') except AttributeError: pass try: fname = '.' + args.type except AttributeError: try: fname = args.state except AttributeError...
<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_output_format(fmt, nfiles): """Validate file format string. Parameters fmt : `str` File format string. nfiles : `int` Number of files. Raises ------ Va...
if nfiles < 0: raise ValueError('Invalid file count: ' + str(nfiles)) if nfiles == 1: return try: fmt % nfiles except TypeError as err: raise ValueError(''.join( ('Invalid file format string: ', fmt, ': ', str(err)) ))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def infiles(fnames, progress, leave=True): """Get input file paths. Parameters fnames : `list` of `str` File paths. progress : `bool` Show progress bar. leave : ...
if progress: if fnames: fnames = tqdm(fnames, desc='Loading', unit='file', bar_format=BAR_FORMAT, leave=leave, dynamic_ncols=True) else: progress = False yield fnames if progress: fnames.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 cmd_settings(args): """Print generator settings. Parameters args : `argparse.Namespace` Command arguments. """
if args.type == SQLITE: storage = SqliteStorage else: storage = JsonStorage storage = storage.load(args.state) data = storage.settings try: del data['markov']['nodes'] except KeyError: pass pprint(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 print_warning(cls): """Print a missing progress bar warning if it was not printed. """
if not cls.warning: cls.warning = True print('Can\'t create progress bar:', str(TQDM_IMPORT_ERROR), file=sys.stderr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def data(self, data, part=False, dataset=''): """Parse data and update links. Parameters data Data to parse. part : `bool`, optional True if data is partial (def...
links = self.parser(self.scanner(data, part), part, dataset) self.storage.add_links(links)
<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_settings_json(self): """Convert generator settings to JSON. Returns ------- `dict` JSON data. """
return { 'scanner': None if self.scanner is None else self.scanner.save(), 'parser': None if self.parser is None else self.parser.save() }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_storage(cls, storage): """Load from storage. Parameters storage : `markovchain.storage.Storage` Returns ------- `markovchain.Markov` """
args = dict(storage.settings.get('markov', {})) args['storage'] = storage return cls(**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 from_file(cls, fp, storage=None): """Load from file. Parameters fp : `str` or `file` File or path. storage : `type`, optional Storage class (default: cls.DEF...
if storage is None: storage = cls.DEFAULT_STORAGE return cls.from_storage(storage.load(fp))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_settings(cls, settings=None, storage=None): """Create from settings. Parameters settings : `dict`, optional Settings (default: None). storage : `type`, ...
if storage is None: storage = cls.DEFAULT_STORAGE return cls.from_storage(storage(settings=settings))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def input(self, img): """Resize input image if necessary. Parameters img : `PIL.Image` Input image. Raises ------ ValueError If input image is too small. Returns...
img_width, img_height = img.size if self.resize: width, height = self.resize scale = min(width / img_width, height / img_height) img = img.resize((floor(img_width * scale), floor(img_height * scale))) img_width, img_height =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def level(self, img, level): """Get image level. Parameters img : `PIL.Image` Input image. level : `int` Level number. Returns ------- `PIL.Image` Converted imag...
if level < self.levels - 1: width, height = img.size scale = reduce(lambda x, y: x * y, islice(self.level_scale, level, self.levels)) img = img.resize((width // scale, height // scale), self.scale) return img
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _scan_level(self, level, prev, img): """Scan a level. Parameters level : `int` Level number. prev : `PIL.Image` or None Previous level image or None if level...
if level == 0: width, height = img.size else: width, height = prev.size tr = self.traversal[0](width, height, ends=(level == 0)) if level == 0: for xy in tr: if xy is None: yield self.END 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 smse(y_true, y_pred): """ Standardised mean squared error. Parameters y_true: ndarray vector of true targets y_pred: ndarray vector of predicted targets Retu...
N = y_true.shape[0] return ((y_true - y_pred)**2).sum() / (N * y_true.var())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mll(y_true, y_pred, y_var): """ Mean log loss under a Gaussian distribution. Parameters y_true: ndarray vector of true targets y_pred: ndarray vector of pred...
return - norm.logpdf(y_true, loc=y_pred, scale=np.sqrt(y_var)).mean()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def msll(y_true, y_pred, y_var, y_train): """ Mean standardised log loss under a Gaussian distribution. Parameters y_true: ndarray vector of true targets y_pred:...
var = y_train.var() mu = y_train.mean() ll_naive = norm.logpdf(y_true, loc=mu, scale=np.sqrt(var)) ll_mod = norm.logpdf(y_true, loc=y_pred, scale=np.sqrt(y_var)) return - (ll_mod - ll_naive).mean()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lins_ccc(y_true, y_pred): """ Lin's Concordance Correlation Coefficient. See https://en.wikipedia.org/wiki/Concordance_correlation_coefficient Parameters y_t...
t = y_true.mean() p = y_pred.mean() St = y_true.var() Sp = y_pred.var() Spt = np.mean((y_true - t) * (y_pred - p)) return 2 * Spt / (St + Sp + (t - p)**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 get_response(self): """ High level function for getting a response. This is what the concrete controller should call. Returns a controller specific response....
last_good_request = self.request middleware_result = None try: last_good_request, middleware_result = self.program.execute_input_middleware_stream(self.request, self) except GiottoException as exc: # save this exception so it can be re-raised from within ...
<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_data_response(self): """ Execute the model and view, and handle the cache. Returns controller-agnostic response data. """
if self.middleware_interrupt_exc: ## the middleware raised an exception, re-raise it here so ## get_concrete_response (defined in subclasses) can catch it. raise self.middleware_interrupt_exc if self.middleware_control: ## this redirect object came from ...
<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_data_for_model(self, args, kwargs): """ In comes args and kwargs expected for the model. Out comes the data from this invocation that will go to the mode...
kwargs_from_invocation = self.get_raw_data() args_from_invocation = deque(self.path_args) defaults = kwargs values = args + list(kwargs.keys()) output = {} raw = False for i, field in enumerate(values): ## going through each bit of data that the mo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _isInner(node): """ Determine whether the given node is, at any point in its syntactic parentage, defined within a function. @param node: The node to inspect...
while node: node = node.parent if isinstance(node, scoped_nodes.FunctionDef): return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getDecoratorsName(node): """ Return a list with names of decorators attached to this node. @param node: current node of pylint """
# For setter properties pylint fails so we use a custom code. decorators = [] if not node.decorators: return decorators for decorator in node.decorators.nodes: decorators.append(decorator.as_string()) return decorators
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _isSetter(node_type, node): """ Determine whether the given node is a setter property. @param node_type: The type of the node to inspect. @param node: The L{...
if node_type not in ['function', 'method']: return False for name in _getDecoratorsName(node): if '.setter' in name: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_docstring(self, node_type, node, report_missing=True, confidence=None): """ Check whether the opening and the closing of docstring on a line by themse...
docstring = node.doc if docstring is None: # The node does not have a docstring. if _isInner(node): # Do not check things inside a function or method. return if _isSetter(node_type, node): # Setters don't need a docstr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _hasReturnValue(self, node): """ Determine whether the given method or function has a return statement. @param node: the node currently checks """
returnFound = False for subnode in node.body: if type(subnode) == node_classes.Return and subnode.value: returnFound = True break return returnFound
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _checkEpytext(self, node_type, node, linenoDocstring): """ Check epytext of docstring. @param node_type: type of node @param node: current node of pylint @pa...
if node_type not in ['function', 'method']: return # Check for arguments. # If current node is method, # then first argument could not have a epytext markup. # The first argument usually named 'self'. argnames = (node.argnames()[1:] if node_type == 'method' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _checkReturnValueEpytext(self, node, linenoDocstring): """ Check if return value is documented. @param node: current node of pylint @param linenoDocstring: l...
# Getter properties don't need to document their return value, # but then need to have a return value. if 'property' in _getDecoratorsName(node): if self._hasReturnValue(node): # Getter properties don't need a docstring. return # Check for re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _checkBlankLineBeforeEpytext(self, node_type, node, linenoDocstring): """ Check whether there is a blank line before epytext. @param node_type: type of node ...
# Check whether there is a blank line before epytext markups. patternEpytext = (r"\n *@(param|type|return|returns|rtype|ivar|cvar" r"|raises|raise)" r"\s*[a-zA-Z0-9_]*\s*\:") matchedEpytext = re.search(patternEpytext, node.doc) if matc...
<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_serializer(serializer): """ Load a serializer. """
if isinstance(serializer, string_types): try: app_label, serializer_name = serializer.split('.') app_package = get_application(app_label) serializer_module = import_module('%s.serializers' % app_package) serializer = getattr(serializer_module, serializer_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 _get_user_allowed_fields(self): """ Retrieve all allowed field names ofr authenticated user. """
model_name = self.Meta.model.__name__.lower() app_label = self.Meta.model._meta.app_label full_model_name = '%s.%s' % (app_label, model_name) permissions = self.cached_allowed_fields.get(full_model_name) if not permissions: permissions = FieldPermission.objects.filt...
<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_fields(self): """ Calculate fields that can be accessed by authenticated user. """
ret = OrderedDict() # no rights to see anything if not self.user: return ret # all fields that can be accessed through serializer fields = super(ModelPermissionsSerializer, self).get_fields() # superuser can see all the fields if self.user.is_super...
<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_field_names(self, declared_fields, model_info): """ Return default field names for serializer. """
return ( [model_info.pk.name] + list(declared_fields.keys()) + list(model_info.fields.keys()) + list(model_info.relations.keys()) )
<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_nested_class(self, nested_depth, relation_info): """ Define the serializer class for a relational field. """
class NestedModelPermissionSerializer(ModelPermissionsSerializer): """ Default nested class for relation. """ class Meta: model = relation_info.related_model depth = nested_depth - 1 nested_context = self.context fields =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dict_factory(cursor, row): """ Converts the cursor information from a SQLite query to a dictionary. :param cursor | <sqlite3.Cursor> row | <sqlite3.Row> :ret...
out = {} for i, col in enumerate(cursor.description): out[col[0]] = row[i] return 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 basic_register(username, password, password2): """ Register a user and session, and then return the session_key and user. """
if password != password2: raise InvalidInput(password={'message': "Passwords do not match"}, username={'value': username}) user = User.objects.create_user(username, password) return create_session(user.username, password)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_session(username, password): """ Create a session for the user, and then return the key. """
user = User.objects.get_user_by_password(username, password) auth_session_engine = get_config('auth_session_engine') if not user: raise InvalidInput('Username or password incorrect') session_key = random_string(15) while auth_session_engine.get(session_key): session_key = random_str...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dbRestore(self, db_value, context=None): """ Extracts the db_value provided back from the database. :param db_value: <variant> :param context: <orb.Context> ...
if isinstance(db_value, (str, unicode)) and db_value.startswith('{'): try: db_value = projex.text.safe_eval(db_value) except StandardError: log.exception('Invalid reference found') raise orb.errors.OrbError('Invalid reference found.') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def loadJSON(self, jdata): """ Loads the given JSON information for this column. :param jdata: <dict> """
super(ReferenceColumn, self).loadJSON(jdata) # load additional information self.__reference = jdata.get('reference') or self.__reference self.__removeAction = jdata.get('removeAction') or self.__removeAction
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def referenceModel(self): """ Returns the model that this column references. :return <Table> || None """
model = orb.system.model(self.__reference) if not model: raise orb.errors.ModelNotFound(schema=self.__reference) return model
<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, value, context=None): """ Returns the inflated value state. This method will match the desired inflated state. :param value: <variant> :param i...
context = context or orb.Context() value = super(ReferenceColumn, self).restore(value, context=context) # check to make sure that we're processing the right values if self.testFlag(self.Flags.I18n) and context.locale == 'all': return {locale: self._restore(val, context) for...
<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(self, value): """ Re-implements the orb.Column.validate method to verify that the reference model type that is used with this column instance is the...
ref_model = self.referenceModel() if isinstance(value, orb.Model): expected_schema = ref_model.schema().name() received_schema = value.schema().name() if expected_schema != received_schema: raise orb.errors.InvalidReference(self.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 valueFromString(self, value, context=None): """ Re-implements the orb.Column.valueFromString method to lookup a reference object based on the given value. :p...
model = self.referenceModel() return model(value, context=context)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addNamespace(self, namespace, **context): """ Creates a new namespace within this database. :param namespace: <str> """
self.connection().addNamespace(namespace, orb.Context(**context))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setConnection(self, connection): """ Assigns the backend connection for this database instance. :param connection: <str> || <orb.Connection> """
# define custom properties if not isinstance(connection, orb.Connection): conn = orb.Connection.byName(connection) if not conn: raise orb.errors.BackendNotFound(connection) connection = conn(self) else: connection.setDatabase(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 findPatternsInFile(codes, patternFinder): """ Find patterns of exceptions in a file. @param codes: code of the file to check @param patternFinder: a visitor ...
tree = ast.parse(codes) patternFinder.visit(tree)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def findAllExceptions(pathToCheck): """ Find patterns of exceptions in a file or folder. @param patternFinder: a visitor for pattern checking and save results @r...
finder = PatternFinder() if os.path.isfile(pathToCheck): with open(pathToCheck) as f: findPatternsInFile(f.read(), finder) else: for path, dirs, files in os.walk(pathToCheck): for file in files: _, extname = os.path.splitext(file) if e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit_Call(self, nodeCall): """ Be invoked when visiting a node of function call. @param node: currently visiting node """
super(PatternFinder, self).generic_visit(nodeCall) # Capture assignment like 'f = getattr(...)'. if hasattr(nodeCall.func, "func"): # In this case, the statement should be # 'f = getattr(...)()'. nodeCall = nodeCall.func # Make sure the function's nam...
<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): """ Returns a duplicate of this instance. :return <Query> """
options = { 'op': self.__op, 'caseSensitive': self.__caseSensitive, 'value': copy.copy(self.__value), 'inverted': self.__inverted, 'functions': copy.copy(self.__functions), 'math': copy.copy(self.__math) } return orb.Query(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inverted(self): """ Returns an inverted copy of this query. :return <orb.Query> """
out = self.copy() out.setInverted(not self.isInverted()) return 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 fromJSON(jdata): """ Creates a new Query object from the given JSON data. :param jdata | <dict> :return <orb.Query> || <orb.QueryCompound> """
if jdata['type'] == 'compound': queries = [orb.Query.fromJSON(jquery) for jquery in jdata['queries']] out = orb.QueryCompound(*queries) out.setOp(orb.QueryCompound.Op(jdata['op'])) return out else: if jdata.get('model'): model ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def columns(self, model=None): """ Returns any columns used within this query. :return [<orb.Column>, ..] """
for query in self.__queries: for column in query.columns(model=model): yield column
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expand(self, model=None, ignoreFilter=False): """ Expands any shortcuts that were created for this query. Shortcuts provide the user access to joined methods...
queries = [] current_records = None for query in self.__queries: sub_q = query.expand(model) if not sub_q: continue # chain together joins into sub-queries if ((isinstance(sub_q, orb.Query) and isinstance(sub_q.value(), orb.Query...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def negated(self): """ Negates this instance and returns it. :return self """
op = QueryCompound.Op.And if self.__op == QueryCompound.Op.Or else QueryCompound.Op.Or return QueryCompound(*self.__queries, op=op)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def or_(self, other): """ Creates a new compound query using the QueryCompound.Op.Or type. :param other <Query> || <QueryCompound> :return <QueryCompound> :sa or...
if not isinstance(other, (Query, QueryCompound)) or other.isNull(): return self.copy() elif self.isNull(): return other.copy() else: # grow this if the operators are the same if self.__op == QueryCompound.Op.And: queries = list(sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def models(self, model=None): """ Returns the tables that this query is referencing. :return [ <subclass of Table>, .. ] """
for query in self.__queries: if isinstance(query, orb.Query): yield query.model(model) else: for model in query.models(model): yield model
<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_handlers(self): """ Returns the handlers defined on the static_maps.yml file located at the app config directory. Returns: An array of static handlers to...
handlers = [] self.static_root = self.application.get_app_component( ).get_component_path() if self.conf: if 'maps' in self.conf: if self.conf['maps'] is None: logger.warning("Maps configuration is empty. Finish the" ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit_binop(self, node): """ Called when if a binary operation is found. Only check for string formatting operations. @param node: currently checking node ""...
if node.op != "%": return pattern = node.left.as_string() # If the pattern's not a constant string, we don't know whether a # dictionary or a tuple makes sense, so don't try to guess. if not pattern.startswith("'") or pattern.startswith('"'): return ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit_functiondef(self, node): """ A interface will be called when visiting a function or a method. @param node: the current node """
if not node.is_method(): # We only check methods. return name = node.name if isTestModule(node.root().name): if name.startswith('test'): if not name.startswith('test_'): self.add_message('C9303', node=node) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getMethodNamePrefix(self, node): """ Return the prefix of this method based on sibling methods. @param node: the current node """
targetName = node.name for sibling in node.parent.nodes_of_class(type(node)): if sibling is node: # We are on the same node in parent so we skip it. continue prefix = self._getCommonStart(targetName, sibling.name) if not prefix.rstrip(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getCommonStart(self, left, right): """ Return the common prefix of the 2 strings. @param left: one string @param right: another string """
prefix = [] for a, b in zip(left, right): if a == b: prefix.append(a) else: break return ''.join(prefix)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def listen(manifest, config, model_mock=False): """ IRC listening process. """
config['manifest'] = manifest config['model_mock'] = model_mock IRC = IrcBot(config) try: IRC.start() except KeyboardInterrupt: 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 get_user_by_password(self, username, password): """ Given a username and a raw, unhashed password, get the corresponding user, retuns None if no match is fou...
try: user = self.get(username=username) except User.DoesNotExist: return None if bcrypt.hashpw(password, user.pass_hash) == user.pass_hash: return user else: 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 AuthenticatedOrRedirect(invocation): """ Middleware class factory that redirects if the user is not logged in. Otherwise, nothing is effected. """
class AuthenticatedOrRedirect(GiottoInputMiddleware): def http(self, request): if request.user: return request return Redirection(invocation) def cmd(self, request): if request.user: return request return Redirection(i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def queryFilter(self, function=None): """ Defines a decorator that can be used to filter queries. It will assume the function being associated with the decorator...
if function is not None: self.__query_filter = function return function def wrapper(func): self.__query_filter = func return func return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Function( library: CDLL, name_or_ordinal: 'Union[str, int, None]'=None, proto_factory: ('Union[ctypes.CFUNCTYPE, ctypes.WINFUNCTYPE,' ' ctypes.PYFUNCTYPE]')=C...
def decorator(fn: 'Callable') -> 'Callable': metadata = _ctypes_metadata(fn) prototype = proto_factory( metadata.restype, *metadata.argtypes, use_errno=use_errno, use_last_error=use_last_error) func_spec = (name_or_ordinal or fn.__name__, library) return prot...
<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): """Release libpci resources."""
if self._access is not None: _logger.debug("Cleaning up") pci_cleanup(self._access) self._access = 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 lookup_vendor_name(self, vendor_id): """ Lookup the name of a given vendor. :param vendor_id: PCI vendor identifier :ptype vendor_id: int :returns: Name of t...
buf = ctypes.create_string_buffer(1024) _logger.debug("Performing the lookup on vendor %#06x", vendor_id) flags = self._flags | pci_lookup_mode.PCI_LOOKUP_VENDOR pci_lookup_name1(self._access, buf, ctypes.sizeof(buf), flags, vendor_id) return buf.value.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 lookup_device_name(self, vendor_id, device_id): """ Lookup the name of a given device. :param vendor_id: PCI vendor identifier :ptype vendor_id: int :param d...
buf = ctypes.create_string_buffer(1024) _logger.debug("Performing the lookup on vendor:device %#06x:%#06x", vendor_id, device_id) flags = self._flags | pci_lookup_mode.PCI_LOOKUP_DEVICE pci_lookup_name2(self._access, buf, ctypes.sizeof(buf), flags, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lookup_subsystem_device_name( self, vendor_id, device_id, subvendor_id, subdevice_id): """ Lookup the name of a given subsystem device. :param vendor_id: PCI...
buf = ctypes.create_string_buffer(1024) _logger.debug("Performing the lookup on vendor:device " "subvendor:subdevice %#06x:%#06x %#06x:%#06x", vendor_id, device_id, subvendor_id, subdevice_id) flags = self._flags | pci_lookup_mode.PCI_LOOKUP_SUBSYSTEM...
<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_duplicate_request(request): """ Since werkzeug request objects are immutable, this is needed to create an identical reuet object with immutable values s...
class FakeRequest(object): method = 'GET' path = request.path headers = request.headers GET = request.GET POST = request.POST user = getattr(request, 'user', None) cookies = request.cookies is_xhr = request.is_xhr return FakeRequest()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fancy_error_template_middleware(app): """ WGSI middleware for catching errors and rendering the error page. """
def application(environ, start_response): try: return app(environ, start_response) except Exception as exc: sio = StringIO() traceback.print_exc(file=sio) sio.seek(0) response = Response( status=500, body=r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_mobile(user_agent): """ Checks if the user browser from the given user agent is mobile. Args: user_agent: A given user agent. Returns: True if the browser...
if user_agent: b = reg_b.search(user_agent) v = reg_v.search(user_agent[0:4]) return b or v return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy(self): """ Returns a copy of this database option set. :return <orb.Context> """
properties = {} for key, value in self.raw_values.items(): if key in self.UnhashableOptions: properties[key] = value else: properties[key] = copy.copy(value) return Context(**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 expandtree(self, model=None): """ Goes through the expand options associated with this context and returns a trie of data. :param model: subclass of <orb.Mod...
if model and not self.columns: schema = model.schema() defaults = schema.columns(flags=orb.Column.Flags.AutoExpand).keys() defaults += schema.collectors(flags=orb.Collector.Flags.AutoExpand).keys() else: defaults = [] expand = self.expand or defa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isNull(self): """ Returns whether or not this option set has been modified. :return <bool> """
check = self.raw_values.copy() scope = check.pop('scope', {}) return len(check) == 0 and len(scope) == 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 create_module(module, target): """ Create a module directory structure into the target directory. """
module_x = module.split('.') cur_path = '' for path in module_x: cur_path = os.path.join(cur_path, path) if not os.path.isdir(os.path.join(target, cur_path)): os.mkdir(os.path.join(target, cur_path)) if not os.path.exists(os.path.join(target, cur_path, '__init__.py')): ...
<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_file_extension(filename): """ Return the extension if the filename has it. None if not. :param filename: The filename. :return: Extension or None. """
filename_x = filename.split('.') if len(filename_x) > 1: if filename_x[-1].strip() is not '': return filename_x[-1] 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 write(path, data, binary=False): """ Writes a given data to a file located at the given path. """
mode = "w" if binary: mode = "wb" with open(path, mode) as f: f.write(data) f.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 read(path): """ Reads a file located at the given path. """
data = None with open(path, 'r') as f: data = f.read() f.close() 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 touch(path): """ Creates a file located at the given path. """
with open(path, 'a') as f: os.utime(path, None) f.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 loadJSON(self, jdata): """ Loads JSON data for this column type. :param jdata: <dict> """
super(StringColumn, self).loadJSON(jdata) # load additional info self.__maxLength = jdata.get('maxLength') or self.__maxLength
<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(self, value): """ Validates the value provided is a valid email address, at least, on paper. :param value: <str> :return: <bool> """
if isinstance(value, (str, unicode)) and not re.match(self.__pattern, value): raise orb.errors.ColumnValidationError(self, 'The email provided is not valid.') else: return super(EmailColumn, self).validate(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 rules(self): """ Returns the rules for this password based on the configured options. :return: <str> """
rules = ['Passwords need to be at least {0} characters long'.format(self.__minlength)] if self.__requireUppercase: rules.append('have at least one uppercase letter') if self.__requireLowercase: rules.append('have at least one lowercase letter') if self.__require...