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 subcommand: command name """
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() sys.stderr.write(colorize('ERROR: ', fg='red')) self.stderr.write('%s\n' % e) sys.exit(1) except Exception, e: if isinstance(e, IOError) and getattr(e, 'errno') == errno.EPIPE: sys.exit(0) if options['debug']: try: import ipdb ipdb.set_trace() except ImportError: import pdb pdb.set_trace() if options.get('traceback'): import traceback self.stderr.write(u'\n'.join(( '=========', 'TRACEBACK', '=========', '', '', ))) traceback.print_exc(file=self.stderr) sys.stderr.write(colorize('ERROR: ', fg='red')) self.stderr.write('%s\n' % e) sys.exit(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 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 as ``self.repo``. **Available options** * ``start_date``: only changesets not older than this parameter would be generated * ``end_date``: only changesets not younger than this parameter would be generated * ``start``: changeset's ID from which changesets would be generated * ``end``: changeset's ID to which changesets would be generated * ``branch``: branch for which changesets would be generated. If ``all`` flag is specified, this option would be ignored. By default, branch would by tried to retrieved from working directory. * ``all``: return changesets from all branches * ``reversed``: by default changesets are returned in date order. If this flag is set to ``True``, reverse order would be applied. * ``limit``: if specified, show no more changesets than this value. Default is ``None``. """
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_date'] = parse_datetime(options['end_date']) changesets = repo.get_changesets( start=options.get('start'), end=options.get('end', options.get('main')), start_date=options.get('start_date'), end_date=options.get('end_date'), branch_name=branch_name, reverse=not options.get('reversed', False), ) try: limit = int(options.get('limit')) except (ValueError, TypeError): limit = None count = 0 for changeset in changesets: if self.show_changeset(changeset, **options): yield changeset count += 1 if count == limit: break
<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 : `str`, optional String to print after the data (default: '\\\\n'). """
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=',\n' if i < len(keys) - 1 else '\n') print(' ' * indent, '}', sep='', end=end) elif isinstance(data, list): if any(isinstance(x, (dict, list)) for x in data): print('[') new_indent = indent + 4 space = ' ' * new_indent for i, x in enumerate(data): print(space, end='') pprint(x, new_indent, end=',\n' if i < len(data) - 1 else '\n') print(' ' * indent, ']', sep='', end=end) else: print(json.dumps(data), end=end) else: print(json.dumps(data), end=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 arguments. Returns ------- `cls` """
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 = SqliteStorage.load(fname) if args.settings is not None: extend(storage.settings, args.settings) return cls.from_storage(storage)
<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.Namespace` Command arguments. """
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...') with open_(fname, 'wt') as fp: markov.save(fp) else: markov.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 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. Raises ------ ValueError If output file is stdout and progress bars are enabled. """
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: try: fname = args.output except AttributeError: fname = '.json' if fname is None or fname.endswith('.json') or fname.endswith('.json.bz2'): args.type = JSON else: args.type = SQLITE settings = {} try: if args.settings is not None: settings = json.load(args.settings) args.settings.close() except AttributeError: pass args.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 check_output_format(fmt, nfiles): """Validate file format string. Parameters fmt : `str` File format string. nfiles : `int` Number of files. Raises ------ ValueError If nfiles < 0 or format string is invalid. """
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 : `bool`, optional Leave progress bar (default: True). Returns ------- `generator` of `str` Input file paths. """
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 (default: `False`). dataset : `str`, optional Dataset key prefix (default: ''). """
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.DEFAULT_STORAGE) Returns ------- `markovchain.Markov` """
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`, optional Storage class (default: cls.DEFAULT_STORAGE) Returns ------- `markovchain.Markov` """
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 ------- `PIL.Image` Resized image or input image. """
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 = img.size if img_width < self.min_size or img_height < self.min_size: raise ValueError('input image is too small: {0} x {1} < {2} x {2}' .format(img_width, img_height, self.min_size)) 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 level(self, img, level): """Get image level. Parameters img : `PIL.Image` Input image. level : `int` Level number. Returns ------- `PIL.Image` Converted image. """
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 == 0. img : `PIL.Image` Current level image. Returns ------- `generator` of (`str` or `markovchain.scanner.Scanner.END` or (`markovchain.scanner.Scanner.START`, `str`)) Token generator. """
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: yield pixel_to_state(img.getpixel(xy)) yield self.END else: scale = self.level_scale[level - 1] for xy in tr: x0 = xy[0] * scale y0 = xy[1] * scale start = ( self.START, pixel_to_state(prev.getpixel(xy)) ) yield start for dxy in self.traversal[level](scale, scale, True): if dxy is None: yield start yield pixel_to_state( img.getpixel((x0 + dxy[0], y0 + dxy[1])) ) yield self.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 smse(y_true, y_pred): """ Standardised mean squared error. Parameters y_true: ndarray vector of true targets y_pred: ndarray vector of predicted targets Returns ------- float: SMSE of predictions vs truth (scalar) Example ------- 0.0 True """
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 predicted targets y_var: float or ndarray predicted variances Returns ------- float: The mean negative log loss (negative log likelihood) Example ------- True True """
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: ndarray vector of predicted targets y_var: float or ndarray predicted variances y_train: ndarray vector of *training* targets by which to standardise Returns ------- float: The negative mean standardised log loss (negative log likelihood) Example ------- True True """
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_true: ndarray vector of true targets y_pred: ndarray vector of predicted targets Returns ------- float: 1.0 for a perfect match between :code:`y_true` and :code:`y_pred`, less otherwise Example ------- True True """
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 # get_data_response() so that get_concrete_response() can handle it self.middleware_interrupt_exc = exc self.request = last_good_request else: self.request = middleware_result # middleware ended cleanly if GiottoControl in type(middleware_result).mro(): # middleware returned a control object self.middleware_control = middleware_result self.request = last_good_request response = self.get_concrete_response() if self.persist_data: response = self.persist(self.persist_data, response) return self.program.execute_output_middleware_stream(self.request, response, self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_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 middleware but return it as if it ## came from a view. return {'body': self.middleware_control} if self.model_mock and self.program.has_mock_defined(): model_data = self.program.get_model_mock() else: args, kwargs = self.program.get_model_args_kwargs() data = self.get_data_for_model(args, kwargs) self.display_data = data # just for displaying in __repr__ if self.program.cache and not self.errors: key = self.get_cache_key(data) hit = self.cache.get(key) if hit: return hit model_data = self.program.execute_model(data) response = self.program.execute_view(model_data, self.mimetype, self.errors) if self.program.cache and not self.errors and not self.model_mock: self.cache.set(key, response, self.program.cache) if 'persist' in response: self.persist_data = response['persist'] return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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 model. In other words, this function does the "data negotiation" between the controller and the model. """
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 model needs ## `field` here is the name of each needed var. # the 'default' value that may be defined in the model. # this variable might be a string or int or might even be a primitive object. # NotImplemented here is used as to preserve if a default value is None. # it is used here as a sort of MetaNone. default_defined_in_model = defaults.get(field, NotImplemented) # the value in kwarg arguments such as --values and GET params from_data_kwargs = kwargs_from_invocation.get(field, None) # The value that will end up being used. value_to_use = None if default_defined_in_model == RAW_INVOCATION_ARGS: # flag that the RAW_INVOCATION_ARGS primitive has been invoked # used later to suppress errors for unused program args # when this primitive is invoked, all positional args are invalid. raw = True if type(default_defined_in_model) == GiottoPrimitive: value_to_use = self.get_primitive(default_defined_in_model.name) elif from_data_kwargs: value_to_use = from_data_kwargs elif not raw and args_from_invocation: value_to_use = args_from_invocation.popleft() elif default_defined_in_model is not NotImplemented: value_to_use = default_defined_in_model else: raise InvalidInvocation("Data Missing For Program. Missing: %s" % field) output[field] = value_to_use if args_from_invocation and not raw: msg = "Too many arguments. Program `%s` takes %s arguments, %s given" % ( self.program.name, len(args) + len(kwargs), len(args_from_invocation) ) raise InvalidInvocation(msg) return 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 _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. @type node: L{logilab.astng.bases.NodeNG} @return: a boolean indicating if the given node is defined as an inner class or inner function. """
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{logilab.astng.bases.NodeNG} to inspect. @return: a boolean indicating if the given node is a setter. """
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 themselves. Then check for epytext markups for function or method. @param node_type: type of node @param node: current node of pylint """
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 docstring as they are documented in # the getter. return self.add_message('W9208', node=node) return elif not docstring.strip(): # Empty docstring. self.add_message('W9209', node=node) return # Get line number of docstring. linenoDocstring = self._getDocstringLineno(node_type, node) self._checkDocstringFormat(node_type, node, linenoDocstring) self._checkEpytext(node_type, node, linenoDocstring) self._checkBlankLineBeforeEpytext(node_type, node, linenoDocstring)
<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 @param linenoDocstring: linenumber of docstring """
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' else node.argnames()) if _isSetter(node_type, node): # For setter methods we remove the `value` argument as it # does not need to be documented. try: argnames.remove('value') except ValueError: # No `value` in arguments. pass for argname in argnames: if node.name.startswith('opt_'): # The docstring for option methods is presented as user-facing # documentation. Avoid requiring epytext in them. return if not re.search(r"@param\s+%s\s*:" % argname, node.doc): self.add_message('W9202', line=linenoDocstring, node=node, args=argname) if not re.search(r"@type\s+%s\s*:" % argname, node.doc): self.add_message('W9203', line=linenoDocstring, node=node, args=argname) self._checkReturnValueEpytext(node, linenoDocstring)
<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: linenumber of docstring """
# 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 return value. if self._hasReturnValue(node): if node.name.startswith('test_'): # Ignore return documentation for test methods. return if not re.search(r"@return[s]{0,1}\s*:", node.doc): self.add_message('W9204', line=linenoDocstring, node=node) if not re.search(r"@rtype\s*:", node.doc): self.add_message('W9205', line=linenoDocstring, 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 _checkBlankLineBeforeEpytext(self, node_type, node, linenoDocstring): """ Check whether there is a blank line before epytext. @param node_type: type of node @param node: current node of pylint @param linenoDocstring: linenumber of docstring """
# 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 matchedEpytext: # This docstring have epytext markups, # then check the blank line before them. posEpytext = matchedEpytext.start() + 1 if not re.search(r"\n\s*\n\s*$", node.doc[:posEpytext]): self.add_message('W9207', line=linenoDocstring, 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 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) except Exception as e: logger.error('Serializer %s not found: %s' % (serializer, e)) return None return serializer
<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.filter( user_field_permissions__user=self.user, content_type__model=model_name, content_type__app_label=app_label ) self.cached_allowed_fields[full_model_name] = permissions return permissions
<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_superuser: return fields # fields that can be accessed by auhtenticated user allowed_fields = self._get_user_allowed_fields() for allowed_field in allowed_fields: field = fields[allowed_field.name] # subfields are NestedModelSerializer if isinstance(field, ModelPermissionsSerializer): # no rights on subfield's fields # calculate how the relation should be retrieved if not field.get_fields(): field_cls = field._related_class kwargs = get_relation_kwargs(allowed_field.name, field.info) if not issubclass(field_cls, serializers.HyperlinkedRelatedField): kwargs.pop('view_name', None) field = field_cls(**kwargs) ret[allowed_field.name] = field return ret
<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 = '__all__' return NestedModelPermissionSerializer
<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> :return {<str> column: <variant> value, ..} """
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_string(15) auth_session_engine.set(session_key, user.username, get_config('auth_session_expire')) return {'session_key': session_key, 'user': user}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dbRestore(self, db_value, context=None): """ Extracts the db_value provided back from the database. :param db_value: <variant> :param context: <orb.Context> :return: <variant> """
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.') if isinstance(db_value, dict): cls = self.referenceModel() if not cls: raise orb.errors.ModelNotFound(schema=self.reference()) else: load_event = orb.events.LoadEvent(data=db_value) # update the expansion information to not propagate to references if context: context = context.copy() expand = context.expandtree(cls) sub_expand = expand.pop(self.name(), {}) context.expand = context.raw_values['expand'] = sub_expand db_value = cls(loadEvent=load_event, context=context) return super(ReferenceColumn, self).dbRestore(db_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 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 inflated: <bool> :return: <variant> """
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 locale, val in value.items()} else: return self._restore(value, 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 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 type of value being provided. :param value: <variant> :return: <bool> """
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(), expects=expected_schema, received=received_schema) return super(ReferenceColumn, 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 valueFromString(self, value, context=None): """ Re-implements the orb.Column.valueFromString method to lookup a reference object based on the given value. :param value: <str> :param context: <orb.Context> || None :return: <orb.Model> || None """
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) self.__connection = connection
<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 for pattern checking and save results """
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 @return: patterns of special functions and classes """
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 extname == ".py": pathFile = os.path.join(path, file) with open(pathFile) as f: findPatternsInFile(f.read(), finder) return finder.patternsFunc, finder.patternsClass
<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 name is 'getattr'. if not hasattr(nodeCall.func, "id"): return if nodeCall.func.id != "getattr": return # Capture 'f = getattr(foo, "bar_%s" % baz )' or # 'f = getattr(foo, "bar_" + baz )'. nodeArgument = nodeCall.args[1] if not isinstance(nodeArgument, ast.BinOp): return operation = nodeArgument.op if type(operation) not in [ast.Mod, ast.Add]: return nodePattern = nodeArgument.left if not isinstance(nodePattern, ast.Str): return pattern = nodePattern.s if not ((type(operation) == ast.Add and pattern.endswith("_")) or (pattern.count("%s") == 1 and pattern.endswith("_%s"))): return pattern = pattern.replace("%s", "") if pattern[:1].isalpha() and not pattern[:1].islower(): self.patternsClass.add(pattern) else: self.patternsFunc.add(pattern)
<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(self.__model, self.__column, **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 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 = orb.schema.model(jdata.get('model')) if not model: raise orb.errors.ModelNotFound(schema=jdata.get('model')) else: column = (model, jdata['column']) else: column = (jdata['column'],) query = orb.Query(*column) query.setOp(orb.Query.Op(jdata.get('op', 'Is'))) query.setInverted(jdata.get('inverted', False)) query.setCaseSensitive(jdata.get('caseSensitive', False)) query.setValue(jdata.get('value')) # restore the function information for func in jdata.get('functions', []): query.addFunction(orb.Query.Function(func)) # restore the math information for entry in jdata.get('math', []): query.addMath(orb.Query.Math(entry.get('op')), entry.get('value')) return 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 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 using the '.' accessor to access individual columns for referenced tables. :param model | <orb.Model> :return <orb.Query> || <orb.QueryCompound> """
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)) and sub_q.value().model(model) != sub_q.model(model)): sub_model = sub_q.value().model(model) sub_col = sub_q.value().column() new_records = sub_model.select(columns=[sub_col]) sub_q = sub_q.copy() sub_q.setOp(sub_q.Op.IsIn) sub_q.setValue(new_records) if current_records is not None and current_records.model() == sub_q.model(model): new_records = new_records.refine(createNew=False, where=sub_q) else: queries.append(sub_q) current_records = new_records # update the existing recordset in the chain elif (current_records is not None and ( (isinstance(sub_q, orb.Query) and current_records.model() == query.model(model)) or (isinstance(sub_q, orb.QueryCompound) and current_records.model() in sub_q.models(model)) )): current_records.refine(createNew=False, where=sub_q) # clear out the chain and move on to the next query set else: current_records = None queries.append(query) return QueryCompound(*queries, op=self.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 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_ |(test isNot 1 or name is Eric) """
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(self.__queries) + [other] return QueryCompound(*queries, op=QueryCompound.Op.Or) else: return QueryCompound(self, other, op=QueryCompound.Op.Or)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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 be added to the app. """
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" "static maps configuration.") return handlers for map_item in self.conf['maps']: logger.debug("Mapping %s handlers." % map_item['name']) self.static_maps[map_item['name']] = {} self.static_maps[ map_item['name']]['root'] = self.static_root if 'root' in map_item: if os.path.isabs(map_item['root']): self.static_maps[ map_item['name']]['root'] = map_item['root'] else: self.static_maps[ map_item['name']]['root'] = os.path.abspath( os.path.join(self.static_root, map_item['root'])) if 'handlers' in map_item: if map_item['handlers'] is None: logger.warning("There is no handles mapped in the" " static maps config file.") else: handlers = handlers + self.get_static_handlers( map_item) else: logger.warning("No static maps configurations were provided.") return handlers
<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 # If the pattern has things like %(foo)s, then the values can't be a # tuple, so don't check for it. if "%(" in pattern: return valueString = node.right.as_string() tupleUsed = valueString.startswith('(') if tupleUsed: return self.add_message('W9501', 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 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) return else: # Test names start with 'test_NAME' and can be like # test_SOME_NAME or test_render_SomeCondition. return if name[0].isupper(): self.add_message('C9302', node=node) return if name.startswith('___'): self.add_message('C9302', node=node) return if name.endswith('___'): self.add_message('C9302', node=node) return if name.startswith('__'): if name.endswith('___'): # To many trailing underscores. self.add_message('C9302', node=node) return if name.endswith('_') and not name.endswith('__'): # To few trailing underscored self.add_message('C9302', node=node) return if name.endswith('__'): # This is a reserved name and we don't do any checks on it. return name = name[2:-2] if name.startswith('_'): name = name[1:] if name.endswith('_'): self.add_message('C9302', node=node) return if '_' in name: # This has a underscore in the main name. prefix = self._getMethodNamePrefix(node) if prefix: # There are other names with same prefix so this should be # a dispatched method. return self.add_message('C9302', node=node) return if isTestModule(node.name) and self.moduleContainsTestCase(node): self._checkTestMethodName(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('_'): # We ignore prefixes which are just underscores. continue return prefix 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 _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 found. """
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(invocation) return AuthenticatedOrRedirect
<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 will take a query as an input and return a modified query to use. :usage class MyModel(orb.Model): objects = orb.ReverseLookup('Object') @classmethod @objects.queryFilter() def objectsFilter(cls, query, **context): return orb.Query() :param function: <callable> :return: <wrapper> """
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]')=CFUNCTYPE, use_errno: bool=False, use_last_error: bool=False, ) -> 'Callable': """ Decorator factory for creating callables for native functions. Decorator factory for constructing relatively-nicely-looking callables that call into existing native functions exposed from a dynamically-linkable library. :param library: The library to look at :param name_or_ordinal: Typically the name of the symbol to load from the library. In rare cases it may also be the index of the function inside the library. :param proto_factory: The prototype factory. :param use_last_error: Passed directly to the prototype factory. :param use_last_error: Passed directly to the prototype factory. :returns: A decorator for a function with particular, special annotations. .. note:: Since nested functions have hard-to-reach documentation, the documentation of the function returned from ``native()`` is documented below. """
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 prototype(func_spec, metadata.paramflags) 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 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 the PCI vendor. .. note:: Lookup respects various flag properties that impact the behavior in case the name cannot be found in the local database. Refer to the documentation of each of the ``flag_`` properties. """
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.decode("utf-8")
<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 device_id: PCI device identifier :ptype device_id: int :returns: Name of the PCI device. .. note:: Lookup respects various flag properties that impact the behavior in case the name cannot be found in the local database. Refer to the documentation of each of the ``flag_`` properties. """
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, vendor_id, device_id) return buf.value.decode("utf-8")
<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 vendor identifier :ptype vendor_id: int :param device_id: PCI device identifier :ptype device_id: int :param subvendor_id: PCI subvendor identifier :ptype subvendor_id: int :param device_id: PCI subdevice identifier :ptype subdevice_id: int :returns: Name of the PCI subsystem device. .. note:: Lookup respects various flag properties that impact the behavior in case the name cannot be found in the local database. Refer to the documentation of each of the ``flag_`` properties. """
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 flags = self._flags | pci_lookup_mode.PCI_LOOKUP_DEVICE pci_lookup_name4(self._access, buf, ctypes.sizeof(buf), flags, vendor_id, device_id, subvendor_id, subdevice_id) return buf.value.decode("utf-8")
<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 so it can be retried after a POST failure. """
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=render_error_page(500, exc, traceback=sio.read()), content_type="text/html" ) return response(environ, start_response) return application
<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 from the user agent is mobile. """
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.Model> || None :return: <dict> """
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 defaults if not expand: return {} def build_tree(parts, tree): tree.setdefault(parts[0], {}) if len(parts) > 1: build_tree(parts[1:], tree[parts[0]]) tree = {} for branch in expand: build_tree(branch.split('.'), tree) return 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 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')): touch(os.path.join(target, cur_path, '__init__.py')) return cur_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 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.__requireNumber: rules.append('have at least one number') if self.__requireWildcard: rules.append('have at least one non alpha-number character') if len(rules) == 1: return rules[0] else: return ', '.join(rules[:-1]) + ' and ' + rules[-1]