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 certify_set( value, certifier=None, min_len=None, max_len=None, include_collections=False, required=True, ): """ Certifier for a set. :param set value: The set to be certified. :param func certifier: A function to be called on each value in the list to check that it is valid. :param int min_len: The minimum acceptable length for the list. If None, the minimum length is not checked. :param int max_len: The maximum acceptable length for the list. If None, the maximum length is not checked. :param bool include_collections: Include types from collections. :param bool required: Whether the value can be `None`. Defaults to True. :return: The certified set. :rtype: set :raises CertifierTypeError: The type is invalid :raises CertifierValueError: The valid is invalid """
certify_bool(include_collections, required=True) certify_iterable( value=value, types=tuple([set, MutableSet, Set]) if include_collections else tuple([set]), certifier=certifier, min_len=min_len, max_len=max_len, schema=None, required=required, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def certify_tuple(value, certifier=None, min_len=None, max_len=None, required=True, schema=None): """ Validates a tuple, checking it against an optional schema. The schema should be a list of expected values replaced by functions which will be called to with the corresponding value in the input. A simple example: :param tuple value: The value to be certified. :param func certifier: A function to be called on each value in the iterable to check that it is valid. :param int min_len: The minimum acceptable length for the iterable. If None, the minimum length is not checked. :param int max_len: The maximum acceptable length for the iterable. If None, the maximum length is not checked. :param bool required: Whether the value can't be `None`. Defaults to True. :param tuple schema: The schema against which the value should be checked. For single-item tuple make sure to add comma at the end of schema tuple, that is, for example: schema=(certify_int(),) :return: The certified tuple. :rtype: tuple :raises CertifierTypeError: The type is invalid :raises CertifierValueError: The valid is invalid """
certify_iterable( value=value, types=tuple([tuple]), certifier=certifier, min_len=min_len, max_len=max_len, schema=schema, required=required, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def certify_list( value, certifier=None, min_len=None, max_len=None, required=True, schema=None, include_collections=False, ): """ Certifier for a list. :param list value: The array to be certified. :param func certifier: A function to be called on each value in the iterable to check that it is valid. :param int min_len: The minimum acceptable length for the iterable. If None, the minimum length is not checked. :param int max_len: The maximum acceptable length for the iterable. If None, the maximum length is not checked. :param bool required: Whether the value can't be `None`. Defaults to True. :param tuple schema: The schema against which the value should be checked. For single-item tuple make sure to add comma at the end of schema tuple, that is, for example: schema=(certify_int(),) :param bool include_collections: Include types from collections. :return: The certified list. :rtype: list :raises CertifierTypeError: The type is invalid :raises CertifierValueError: The valid is invalid """
certify_bool(include_collections, required=True) certify_iterable( value=value, types=tuple([list, MutableSequence, Sequence]) if include_collections else tuple([list]), certifier=certifier, min_len=min_len, max_len=max_len, schema=schema, required=required, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def certify_email(value, required=True): """ Certifier which verifies that email addresses are well-formed. Does not check that the address exists. :param six.string_types value: The email address to certify. **Should be normalized!** :param bool required: Whether the value can be `None`. Defaults to True. :return: The certified email address. :rtype: six.string_types :raises CertifierTypeError: The type is invalid :raises CertifierValueError: The valid is invalid """
certify_required( value=value, required=required, ) certify_string(value, min_length=3, max_length=320) try: certification_result = email_validator.validate_email( value, check_deliverability=False, ) except email_validator.EmailNotValidError as ex: six.raise_from( CertifierValueError( message="{value!r} is not a valid email address: {ex}".format( value=value, # email_validator returns unicode characters in exception string ex=six.u(repr(ex)) ), value=value, required=required, ), ex ) else: if certification_result['email'] != value: raise CertifierValueError( message="{value!r} is not normalized, should be {normalized!r}".format( value=value, normalized=certification_result['email']), value=value, required=required, )
<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_valid(self, model, validator=None): """Returns true if the model passes the validation, and false if not. Validator must be present_optional if validation is not 'simple'. """
if self.property_name and self.is_property_specific: arg0 = getattr(model, self.property_name) else: arg0 = model if self.is_simple: is_valid = self.callback(arg0) else: is_valid = self.callback(arg0, validator) return (is_valid, None if is_valid else (self.message or "is invalid"))
<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, model, validator=None): """Checks the model against all filters, and if it shoud be validated, runs the validation. if the model is invalid, an error is added to the model. Then the validity value is returned. """
for filter_ in self.filters: if not filter_(model): return True is_valid, message = self.is_valid(model, validator) if not is_valid: model.add_error(self.pretty_property_name or self.property_name, message) return is_valid
<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_present(val): """Returns True if the value is not None, and if it is either not a string, or a string with length > 0. """
if val is None: return False if isinstance(val, str): return len(val) > 0 return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_length(property_name, *, min_length=1, max_length=None, present_optional=False): """Returns a Validation that checks the length of a string."""
def check(val): """Checks that a value matches a scope-enclosed set of length parameters.""" if not val: return present_optional else: if len(val) >= min_length: if max_length is None: return True else: return len(val) <= max_length else: return False if max_length: message = "must be at least {0} characters long".format(min_length) else: message = "must be between {0} and {1} characters long".format(min_length, max_length) return Validation(check, property_name, message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def matches(property_name, regex, *, present_optional=False, message=None): """Returns a Validation that checks a property against a regex."""
def check(val): """Checks that a value matches a scope-enclosed regex.""" if not val: return present_optional else: return True if regex.search(val) else False return Validation(check, property_name, message)
<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_numeric(property_name, *, numtype="float", min=None, max=None, present_optional=False, message=None): """Returns a Validation that checks a property as a number, with optional range constraints."""
if numtype == "int": cast = util.try_parse_int elif numtype == "decimal": cast = util.try_parse_decimal elif numtype == "float": cast = util.try_parse_float else: raise ValueError("numtype argument must be one of: int, decimal, float") def check(val): """Checks that a value can be parsed as a number.""" if val is None: return present_optional else: is_num, new_val = cast(val) if not is_num: return False else: if min is not None and new_val < min: return False if max is not None and new_val > max: return False return True if not message: msg = ["must be a"] if numtype == "int": msg.append("whole number") else: msg.append("number") if min is not None and max is not None: msg.append("between {0} and {1}".format(min, max)) elif min is not None: msg.append("greater than or equal to {0}".format(min)) elif max is not None: msg.append("less than or equal to {0}".format(max)) message = " ".join(msg) return Validation(check, property_name, message)
<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_date(property_name, *, format=None, present_optional=False, message=None): """Returns a Validation that checks a value as a date."""
# NOTE: Not currently using format param def check(val): """Checks that a value can be parsed as a date.""" if val is None: return present_optional else: is_date, _ = util.try_parse_date(val) return is_date return Validation(check, property_name, message)
<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_datetime(property_name, *, format=None, present_optional=False, message=None): """Returns a Validation that checks a value as a datetime."""
# NOTE: Not currently using format param def check(val): """Checks that a value can be parsed as a datetime.""" if val is None: return present_optional else: is_date, _ = util.try_parse_datetime(val) return is_date return Validation(check, property_name, message)
<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_in(property_name, set_values, *, present_optional=False, message=None): """Returns a Validation that checks that a value is contained within a given set."""
def check(val): """Checks that a value is contained within a scope-enclosed set.""" if val is None: return present_optional else: return val in set_values return Validation(check, property_name, message)
<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_unique(keys, *, scope=None, comparison_operators=None, present_optional=False, message=None): """Returns a Validation that makes sure the given value is unique for a table and optionally a scope. """
def check(pname, validator): """Checks that a value is unique in its column, with an optional scope.""" # pylint: disable=too-many-branches model = validator.model data_access = validator.data_access pkname = model.primary_key_name pkey = model.primary_key if isinstance(keys, str): key = getattr(model, keys) if present_optional and key is None: return True if comparison_operators: if isinstance(comparison_operators, str): op = comparison_operators else: op = comparison_operators[0] else: op = " = " constraints = [(keys, key, op)] else: if comparison_operators: ops = comparison_operators else: ops = [" = "] * len(keys) constraints = list(zip(keys, [getattr(model, key) for key in keys], ops)) if scope: if comparison_operators: ops = comparison_operators[len(constraints):] else: ops = [" = "] * len(scope) constraints.extend(zip(scope, [getattr(model, col) for col in scope], ops)) dupe = data_access.find(model.table_name, constraints, columns=pkname) if dupe is None: return True if isinstance(pkname, str): return dupe[0] == pkey else: return tuple(dupe) == tuple(pkey) return Validation(check, keys, message or "is already taken", is_simple=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 validate(self, model, data_access=None, *, fail_fast=None): """Validates a model against the collection of Validations. Returns True if all Validations pass, or False if one or more do not. """
if fail_fast is None: fail_fast = self.fail_fast self.model = model self.data_access = data_access is_valid = True for validation in self.validations: if not validation.validate(model, self): is_valid = False if fail_fast: break return is_valid
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def configured_options(self): """What are the configured options in the git repo."""
stdout_lines = self._check_output(['config', '--list']).splitlines() return {key: value for key, value in [line.split('=') for line in stdout_lines]}
<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_es_action_item(data_item, action_settings, es_type, id_field=None): ''' This method will return an item formated and ready to append to the action list ''' action_item = dict.copy(action_settings) if id_field is not None: id_val = first(list(get_dict_key(data_item, id_field))) if id_val is not None: action_item['_id'] = id_val elif data_item.get('id'): if data_item['id'].startswith("%s/" % action_settings['_index']): action_item['_id'] = "/".join(data_item['id'].split("/")[2:]) else: action_item['_id'] = data_item['id'] if data_item.get('data'): action_item['_source'] = data_item['data'] else: action_item['_source'] = data_item action_item['_type'] = es_type return action_item
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def es_field_sort(fld_name): """ Used with lambda to sort fields """
parts = fld_name.split(".") if "_" not in parts[-1]: parts[-1] = "_" + parts[-1] return ".".join(parts)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def app_routes(app): """ list of route of an app """
_routes = [] for rule in app.url_map.iter_rules(): _routes.append({ 'path': rule.rule, 'name': rule.endpoint, 'methods': list(rule.methods) }) return jsonify({'routes': _routes})
<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_input_type(self, type_or_parse): """ Set an unique input type. If you use this then you have only one input for the play. """
self._inputs = OrderedDict() default_inputs = self.engine.in_name if len(default_inputs) > 1: raise ValueError("Need more than one input, you sould use `add_input` for each of them") self.add_input(default_inputs[0], type_or_parse)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_input(self, in_name, type_or_parse=None): """ Declare a possible input """
if type_or_parse is None: type_or_parse = GenericType() elif not isinstance(type_or_parse, GenericType) and callable(type_or_parse): type_or_parse = GenericType(parse=type_or_parse) elif not isinstance(type_or_parse, GenericType): raise ValueError("the given 'type_or_parse' is invalid") self._inputs[in_name] = type_or_parse
<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_outputs(self, *outputs): """ Set the outputs of the view """
self._outputs = OrderedDict() for output in outputs: out_name = None type_or_serialize = None if isinstance((list, tuple), output): if len(output) == 1: out_name = output[0] elif len(output) == 2: out_name = output[0] type_or_serialize = output[1] else: raise ValueError("invalid output format") else: out_name = output self.add_output(out_name, type_or_serialize)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_output(self, out_name, type_or_serialize=None, **kwargs): """ Declare an output """
if out_name not in self.engine.all_outputs(): raise ValueError("'%s' is not generated by the engine %s" % (out_name, self.engine.all_outputs())) if type_or_serialize is None: type_or_serialize = GenericType() if not isinstance(type_or_serialize, GenericType) and callable(type_or_serialize): type_or_serialize = GenericType(serialize=type_or_serialize) elif not isinstance(type_or_serialize, GenericType): raise ValueError("the given 'type_or_serialize' is invalid") # register outpurs self._outputs[out_name] = { 'serializer': type_or_serialize, 'parameters': kwargs if kwargs 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 options(self): """ Engine options discover HTTP entry point """
#configure engine with an empty dict to ensure default selection/options self.engine.configure({}) conf = self.engine.as_dict() conf["returns"] = [oname for oname in six.iterkeys(self._outputs)] # Note: we overide args to only list the ones that are declared in this view conf["args"] = [iname for iname in six.iterkeys(self._inputs)] return jsonify(conf)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def init_stream_from_settings(cfg: dict) -> Stream: """ Shortcut to create Stream from configured settings. Will definitely fail if there is no meaningful configuration provided. Example of such is:: { "streams": { "rabbitmq": { "transport": "sunhead.events.transports.amqp.AMQPClient", "connection_parameters": { "login": "guest", "password": "", "host": "localhost", "port": 5672, "virtualhost": "video", }, "exchange_name": "video_bus", "exchange_type": "topic", "global_qos": None, }, "kafka": {}, }, "active_stream": "rabbitmq", } :return: Instantiated Stream object. """
cfg_name = cfg["active_stream"] stream_init_kwargs = cfg["streams"][cfg_name] stream = Stream(**stream_init_kwargs) await stream.connect() _stream_storage.push(cfg_name, stream) return stream
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def interpret(self, infile): """ Process a file of rest and return list of dicts """
data = [] for record in self.generate_records(infile): data.append(record) 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 read_profile(name): """Get a named profile from the CONFIG_FILE. Args: name The name of the profile to load. Returns: A dictionary with the profile's ``repo`` and ``token`` values. """
config = configparser.ConfigParser() config.read(CONFIG_FILE) profile = config[name] repo = profile["repo"] token = profile["token"] return {"repo": repo, "token": token}
<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_profile(name, repo, token): """Save a profile to the CONFIG_FILE. After you use this method to save a profile, you can load it anytime later with the ``read_profile()`` function defined above. Args: name The name of the profile to save. repo The Github repo you want to connect to. For instance, this repo is ``jtpaasch/simplygithub``. token A personal access token to connect to the repo. It is Returns: A dictionary with the profile's ``repo`` and ``token`` values. """
make_sure_folder_exists(CONFIG_FOLDER) config = configparser.ConfigParser() config.read(CONFIG_FILE) profile = {"repo": repo, "token": token} config[name] = profile with open(CONFIG_FILE, "w") as configfile: config.write(configfile) return profile
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def requirements(fname): """ Utility function to create a list of requirements from the output of the pip freeze command saved in a text file. """
packages = Setup.read(fname, fail_silently=True).split('\n') packages = (p.strip() for p in packages) packages = (p for p in packages if p and not p.startswith('#')) return list(packages)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_parser(): """ Returns an argparse.ArgumentParser instance to parse the command line arguments for lk """
import argparse description = "A programmer's search tool, parallel and fast" parser = argparse.ArgumentParser(description=description) parser.add_argument('pattern', metavar='PATTERN', action='store', help='a python re regular expression') parser.add_argument('--ignore-case', '-i', dest='ignorecase', action='store_true', default=False, help='ignore case when searching') parser.add_argument('--no-unicode', '-u', dest='unicode', action='store_false', default=True, help='unicode-unfriendly searching') parser.add_argument('--no-multiline', '-l', dest='multiline', action='store_false', default=True, help='don\'t search over multiple lines') parser.add_argument('--dot-all', '-a', dest='dot_all', action='store_true', default=False, help='dot in PATTERN matches newline') parser.add_argument('--escape', '-e', dest='escape', action='store_true', default=False, help='treat PATTERN as a string instead of a regex') if sys.version_info >= (2, 6): parser.add_argument('--follow-links', '-s', dest='follow_links', action='store_true', default=False, help='follow symlinks (Python >= 2.6 only)') parser.add_argument('--hidden', '-n', dest='search_hidden', action='store_true', default=False, help='search hidden files and directories') parser.add_argument('--binary', '-b', dest='search_binary', action='store_true', default=False, help='search binary files') parser.add_argument('--no-colors', '-c', dest='use_ansi_colors', action='store_false', default=True, help="don't print ANSI colors") parser.add_argument('--stats', '-t', dest='print_stats', action='store_true', default=False, help='print statistics') parser.add_argument('--num-processes', '-p', dest='number_processes', action='store', default=10, type=int, help='number of child processes to concurrently search with') parser.add_argument('--exclude', '-x', metavar='PATH_PATTERN', dest='exclude_path_patterns', action='append', default=[], type=str, help='exclude paths matching PATH_PATTERN') parser.add_argument('--open-with', '-o', metavar='COMMAND', dest='command_strings', action='append', default=[], type=str, help='run each COMMAND where COMMAND is a string with a placeholder, %%s, for the absolute path of the matched file') parser.add_argument('directory', metavar='DIRECTORY', nargs='?', default=getcwd(), help='a directory to search in (default cwd)') 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 get_file_contents(path, binary=False): """ Return the contents of the text file at path. If it is a binary file,raise an IOError """
# if this isn't a text file, we should raise an IOError f = open(path, 'r') file_contents = f.read() f.close() if not binary and file_contents.find('\000') >= 0: raise IOError('Expected text file, got binary file') return file_contents
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(): """ if lk.py is run as a script, this function will run """
parser = build_parser() args = parser.parse_args() flags = re.LOCALE if args.dot_all: flags |= re.DOTALL if args.ignorecase: flags |= re.IGNORECASE if args.unicode: flags |= re.UNICODE if args.multiline: flags |= re.MULTILINE exclude_path_flags = re.UNICODE | re.LOCALE exclude_path_regexes = [ re.compile(pattern, exclude_path_flags) for pattern in args.exclude_path_patterns ] pattern = re.escape(args.pattern) if args.escape else args.pattern try: search_manager = SearchManager(regex=re.compile(pattern, flags), number_processes=args.number_processes, search_hidden=args.search_hidden, follow_links=args.follow_links, search_binary=args.search_binary, use_ansi_colors=args.use_ansi_colors, print_stats=args.print_stats, exclude_path_regexes=exclude_path_regexes, command_strings=args.command_strings) search_manager.enqueue_directory(args.directory) search_manager.process_queue() except (KeyboardInterruptError, KeyboardInterrupt): sys.stdout.write('\n') 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 enqueue_directory(self, directory): """ add a search of the directory to the queue """
exclude_path_regexes = self.exclude_path_regexes[:] if not self.search_hidden: exclude_path_regexes.append(self.hidden_file_regex) else: exclude_path_regexes.remove(self.hidden_file_regex) self.mark = datetime.datetime.now() def is_path_excluded(path): """ return True if name matches on of the regexes in exclude_path_regexes, False otherwise """ for exclude_path_regex in exclude_path_regexes: for found in exclude_path_regex.finditer(path): return False return True def search_walk(): try: walk_generator = walk(directory, followlinks=self.follow_links) except TypeError: # for python less than 2.6 walk_generator = walk(directory) for packed in walk_generator: directory_path, directory_names, file_names = packed directory_names[:] = filter(is_path_excluded, directory_names) file_names[:] = filter(is_path_excluded, file_names) yield directory_path, directory_names, file_names writer = ColorWriter(sys.stdout, self.use_ansi_colors) def print_directory_result(directory_result): writer.print_result(directory_result) for command_string in self.command_strings: if command_string.find('%s') < 0: command_string += ' %s' for file_name, line_result in directory_result.iter_line_results_items(): file_path = path.join(directory_result.directory_path, file_name) Popen(command_string % file_path, shell=True) break for directory_path, directory_names, file_names in search_walk(): process = Process(target=self.search_worker, args=(self.regex, directory_path, file_names, self.search_binary, print_directory_result)) self.queue.append(process)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_worker(self, regex, directory_path, names, binary=False, callback=None): """ build a DirectoryResult for the given regex, directory path, and file names """
try: result = DirectoryResult(directory_path) def find_matches(name): full_path = path.join(directory_path, name) file_contents = get_file_contents(full_path, binary) start = 0 match = regex.search(file_contents, start) while match: result.put(name, file_contents, match) start = match.end() match = regex.search(file_contents, start) for name in names: try: find_matches(name) except IOError: pass if callback: callback(result) except KeyboardInterrupt, e: 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 print_result(self, directory_result): """ Print out the contents of the directory result, using ANSI color codes if supported """
for file_name, line_results_dict in directory_result.iter_line_results_items(): full_path = path.join(directory_result.directory_path, file_name) self.write(full_path, 'green') self.write('\n') for line_number, line_results in sorted(line_results_dict.items()): self.write('%s: ' % (line_results[0].line_number)) out = list(line_results[0].left_of_group + line_results[0].group + line_results[0].right_of_group) offset = 0 for line_result in line_results: group_length = len(line_result.group) out.insert(offset+line_result.left_offset-1, self.colors['blue']) out.insert(offset+line_result.left_offset+group_length, self.colors['end']) offset += group_length + 1 self.write(''.join(out)+'\n') self.write('\n')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_or_get_from_request(request): """Returns `RequestInfo` instance. If object was already created during ``request`` it is returned. Otherwise new instance is created with details populated from ``request``. New instance is then cached for reuse on subsequential calls. """
saved = getattr(request, REQUEST_CACHE_FIELD, None) if isinstance(saved, RequestInfo): return saved req = RequestInfo() req.user_ip = request.META.get('REMOTE_ADDR') req.user_host = request.META.get('REMOTE_HOST') req.user_agent = request.META.get('HTTP_USER_AGENT') req.full_path = request.build_absolute_uri( request.get_full_path()) req.method = request.META.get('REQUEST_METHOD') req.referer = request.META.get('HTTP_REFERER') req.save() setattr(request, REQUEST_CACHE_FIELD, req) return req
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def materialize(self): """Returns instance of ``TrackedModel`` created from current ``History`` snapshot. To rollback to current snapshot, simply call ``save`` on materialized object. """
if self.action_type == ActionType.DELETE: # On deletion current state is dumped to change_log # so it's enough to just restore it to object data = serializer.from_json(self.change_log) obj = serializer.restore_model(self._tracked_model, data) return obj changes = History.objects.filter( model_name=self.model_name, app_label=self.app_label, table_id=self.table_id) changes = changes.filter(revision_ts__lte=self.revision_ts) changes = list(changes.order_by('revision_ts')) creation = changes.pop(0) data = serializer.from_json(creation.change_log) obj = serializer.restore_model(self._tracked_model, data) for change in changes: change_log = serializer.from_json(change.change_log) for field in change_log: next_val = change_log[field][Field.NEW] setattr(obj, field, next_val) return obj
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _is_plugin_disabled(plugin): """ Determines if provided plugin is disabled from running for the active task. """
item = _registered.get(plugin.name) if not item: return False _, props = item return bool(props.get('disabled'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _setup_events(plugin): """ Handles setup or teardown of event hook registration for the provided plugin. `plugin` ``Plugin`` class. """
events = plugin.events if events and isinstance(events, (list, tuple)): for event in [e for e in events if e in _EVENT_VALS]: register('event', event, plugin)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _setup_options(plugin): """ Handles setup or teardown of option hook registration for the provided plugin. `plugin` ``Plugin`` class. """
options = plugin.options if options and isinstance(options, (list, tuple)): for props in options: if isinstance(props, dict): if 'block' in props and 'options' in props: # block block = props['block'] option_list = props['options'] # options for this block for props in option_list: if isinstance(props, dict): name = props.pop('name', None) if name: key = "{0}_{1}".format(block, name) register('option', key, plugin, props) else: # non-block option name = props.pop('name', None) if name: register('option', name, plugin, props)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register(hook_type, key, plugin_cls, properties=None): """ Handles registration of a plugin hook in the global registries. `hook_type` Type of hook to register ('event', 'command', or 'option') `key` Unique key associated with `hook_type` and `plugin`. Value depends on type:: 'command' - Name of the command 'event' - Name of the event to associate with plugin: ('task_start', 'task_run', 'task_end') 'option' - Option name for task config file. Name should be prefixed with block name if it has one: (e.g. apps_startpath) `plugin_cls` ``Plugin`` class. `properties` Dictionary with properties related to provided plugin and key. Note, upon registration of any hooks, the plugin will also be registered in the master plugin registry. """
def fetch_plugin(): """ This function is used as a lazy evaluation of fetching the specified plugin. This is required, because at the time of registration of hooks (metaclass creation), the plugin class won't exist yet in the class namespace, which is required for the `Registry.get()` method. One benefit of this implementation is that we can reference the same object instance in each of the hook registries instead of making a new instance of the plugin for every registry that links to the same plugin. """ return _registered.get(plugin_cls.name)[0] # extended, strip type info # type information for plugin in main registry type_info = {} # register a command for plugin if hook_type == 'command': _command_hooks.register(key, fetch_plugin) type_info['command'] = True # register event chain for plugin elif hook_type == 'event': if not key in _event_hooks: _event_hooks[key] = [] _event_hooks[key].append((plugin_cls.name, fetch_plugin)) type_info['event'] = True # register an option for plugin elif hook_type == 'option': _option_hooks.register(key, fetch_plugin, properties or {}) type_info['option'] = True else: return # register this class in main registry _registered.register(plugin_cls.name, plugin_cls, type_info)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup_sudo_access(plugin): """ Injects a `run_root` method into the provided plugin instance that forks a shell command using sudo. Used for command plugin needs. `plugin` ``Plugin`` instance. """
def run_root(self, command): """ Executes a shell command as root. `command` Shell command string. Returns boolean. """ try: return not (common.shell_process('sudo ' + command) is None) except KeyboardInterrupt: # user cancelled return False plugin.run_root = types.MethodType(run_root, plugin)
<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_registered(option_hooks=None, event_hooks=None, command_hooks=None, root_access=None, task_active=True): """ Returns a generator of registered plugins matching filters. `option_hooks` Boolean to include or exclude plugins using option hooks. `event_hooks` Boolean to include or exclude task event plugins. `command_hooks` Boolean to include or exclude command plugins. `root_access` Boolean to include or exclude root plugins. `task_active` Set to ``False`` to not filter by task-based plugins. Returns list of ``Plugin`` instances. """
plugins = [] for _, item in _registered: plugin, type_info = item # filter out any task-specific plugins if task_active: if type_info.get('disabled'): continue else: if plugin.options or plugin.task_only: continue if not option_hooks is None: if option_hooks != bool(type_info.get('option')): continue if not event_hooks is None: if event_hooks != bool(type_info.get('event')): continue if not command_hooks is None: if command_hooks != bool(type_info.get('command')): continue if not root_access is None: if root_access != plugin.needs_root: continue plugins.append(plugin) return plugins
<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_hook(command, task_active=True): """ Gets registered command ``Plugin`` instance for the provided command. `command` Command string registered to a plugin. `task_active` Set to ``False`` to indicate no active tasks. Returns ``Plugin`` instance or ``None``. """
plugin_obj = _command_hooks.get(command) if plugin_obj: if task_active or (not plugin_obj.options and not plugin_obj.task_only): if not _is_plugin_disabled(plugin_obj): return plugin_obj 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 run_event_hooks(event, task): """ Executes registered task event plugins for the provided event and task. `event` Name of the event to trigger for the plugin: ('task_start', 'task_run', 'task_end') `task` ``Task`` instance. """
# get chain of classes registered for this event call_chain = _event_hooks.get(event) if call_chain: # lookup the associated class method for this event event_methods = { 'task_start': 'on_taskstart', 'task_run': 'on_taskrun', 'task_end': 'on_taskend' } method = event_methods.get(event) if method: for _, get_plugin in call_chain: plugin_obj = get_plugin() if not _is_plugin_disabled(plugin_obj): try: getattr(plugin_obj, method)(task) # execute except Exception: # TODO: log these issues for plugin author or user 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 run_option_hooks(parser, disable_missing=True): """ Executes registered plugins using option hooks for the provided ``SettingParser`` instance. `parser` ``SettingParser`` instance. `disable_missing` Set to ``True`` to disable any plugins using option hooks whose defined option hooks are not available in the data returned from the parser. * Raises ``InvalidTaskConfig`` if task config parsing failed. """
plugins = [] state = {} # state information def _raise_error(msg, block): """ Raises ``InvalidTaskConfig`` exception with given message. """ if block: msg += u' (block: "{0}")'.format(block) raise errors.InvalidTaskConfig(parser.filename, reason=msg) def _run_hooks(options, block): """ Runs option hooks for the block and options provided. """ for option, value_list in options: key = '{0}_{1}'.format(block, option) if block else option item = _option_hooks.get(key) if item: plugin_obj, props = item # enforce some properties if not key in state: state[key] = 0 state[key] += 1 # currently only supports 'allow_duplicates' if not props.get('allow_duplicates', True) and state[key] > 1: msg = u'Duplicate option "{0}"'.format(option) _raise_error(msg, block) try: plugin_obj.parse_option(option, block, *value_list) plugins.append(plugin_obj) except TypeError: # invalid value length msg = u'Value mismatch for option "{0}"'.format(option) _raise_error(msg, block) except ValueError as exc: msg = unicode(exc) if not msg: msg = (u'Invalid value provided for option "{0}"' .format(option)) _raise_error(msg, block) else: # invalid key found msg = u'Invalid option "{0}" found'.format(option) _raise_error(msg, block) # run hooks for non-block options _run_hooks(parser.options, None) # run hooks for blocks for block, option_list in parser.blocks: _run_hooks(option_list, block) # disable any plugins using option hooks that didn't match parser data if disable_missing: reg_plgs = get_registered(option_hooks=True) for plugin in [p for p in reg_plgs if p not in plugins]: disable_plugin_instance(plugin)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _recursive_merge(dct, merge_dct, raise_on_missing): # type: (Dict[str, Any], Dict[str, Any], bool) -> Dict[str, Any] """Recursive dict merge This modifies `dct` in place. Use `copy.deepcopy` if this behavior is not desired. """
for k, v in merge_dct.items(): if k in dct: if isinstance(dct[k], dict) and isinstance(merge_dct[k], BaseMapping): dct[k] = _recursive_merge(dct[k], merge_dct[k], raise_on_missing) else: dct[k] = merge_dct[k] elif isinstance(dct, Extensible): dct[k] = merge_dct[k] else: message = "Unknown configuration key: '{k}'".format(k=k) if raise_on_missing: raise KeyError(message) else: logging.getLogger(__name__).warning(message) return dct
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply(self, config, raise_on_unknown_key=True): # type: (Dict[str, Any], bool) -> None """Apply additional configuration from a dictionary This will look for dictionary items that exist in the base_config any apply their values on the current configuration object """
_recursive_merge(self._data, config, raise_on_unknown_key)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply_object(self, config_obj, apply_on=None): """Apply additional configuration from any Python object This will look for object attributes that exist in the base_config and apply their values on the current configuration object """
self._init_flat_pointers() try: config_obj_keys = vars(config_obj).keys() # type: Iterable[str] except TypeError: config_obj_keys = filter(lambda k: k[0] != '_', dir(config_obj)) for config_key in config_obj_keys: if apply_on: flat_key = apply_on + (config_key, ) else: flat_key = (config_key, ) if flat_key in self._flat_pointers: container, orig_key = self._flat_pointers[flat_key] container[orig_key] = getattr(config_obj, config_key)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply_flat(self, config, namespace_separator='_', prefix=''): # type: (Dict[str, Any], str, str) -> None """Apply additional configuration from a flattened dictionary This will look for dictionary items that match flattened keys from base_config and apply their values on the current configuration object. This can be useful for applying configuration from environment variables and flat configuration file formats such as INI files. """
self._init_flat_pointers() for key_stack, (container, orig_key) in self._flat_pointers.items(): flat_key = '{prefix}{joined_key}'.format(prefix=prefix, joined_key=namespace_separator.join(key_stack)) if flat_key in config: container[orig_key] = config[flat_key]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cross(environment, book, row, sheet_source, column_source, column_key): """ Returns a single value from a column from a different dataset, matching by the key. """
a = book.sheets[sheet_source] return environment.copy(a.get(**{column_key: row[column_key]})[column_source])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def column(environment, book, sheet_name, sheet_source, column_source, column_key): """ Returns an array of values from column from a different dataset, ordered as the key. """
a = book.sheets[sheet_source] b = book.sheets[sheet_name] return environment.copy([a.get(**{column_key: row[column_key]})[column_source] for row in b.all()])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(input_file, output, format): """Converts an image file to a Leaflet map."""
try: process_image(input_file, subfolder=output, ext=format) except Exception as e: sys.exit(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 with_lock(lock, func, *args, **kwargs): """A 'context manager' for performing operations requiring a lock. :param lock: A BasicLock instance :type lock: silverberg.lock.BasicLock :param func: A callable to execute while the lock is held. :type func: function """
d = lock.acquire() def release_lock(result): deferred = lock.release() return deferred.addCallback(lambda x: result) def lock_acquired(lock): return defer.maybeDeferred(func, *args, **kwargs).addBoth(release_lock) d.addCallback(lock_acquired) return 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 koji_instance(config, message, instance=None, *args, **kw): """ Particular koji instances You may not have even known it, but we have multiple instances of the koji build system. There is the **primary** buildsystem at `koji.fedoraproject.org <http://koji.fedoraproject.org>`_ and also secondary instances for `ppc <http://ppc.koji.fedoraproject.org>`_, `arm <http://arm.koji.fedoraproject.org>`_, and `s390 <http://s390.koji.fedoraproject.org>`_. With this rule, you can limit messages to only those from particular koji instances (like the **primary** one if you want to ignore the secondary ones). You should use this rule **in combination** with other koji rules so you get only a *certain subset* of messages from one instance. You almost certainly do not want **all** messages from a given instance. You can specify several instances by separating them with a comma ',', i.e.: ``primary,ppc``. """
instance = kw.get('instance', instance) if not instance: return False instances = [item.strip() for item in instance.split(',')] return message['msg'].get('instance') in instances
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add(self, value_id, name, value_class): """ Factory function that creates a value. :param value_id: id of the value, used to reference the value within this list.BaseException :param value_class: The class of the value that should be created with this function. """
item = value_class( name, value_id=self.controller.component_id + "." + value_id, is_input=self.is_input, index=self.count, spine = self.controller.spine ) #if self._inject and self.controller: # setattr(self.controller, value_id, item) #setattr(self, value_id, item) self.count += 1 self._items[value_id] = item if self.is_input and self.controller: item.add_observer(self.controller) return item
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register(self, name): """Decorator for registering a named function in the sesion logic. Args: name: str. Function name. func: obj. Parameterless function to register. The following named functions must be registered: 'LaunchRequest' - logic for launch request. 'SessionEndedRequest': logic for session ended request. In addition, all intents must be registered by their names specified in the intent schema. The aliased decorators: @launch, @intent(name), and @session_ended exist as a convenience for registering specific functions. """
def decorator(func): """Inner decorator, not used directly. Args: func: obj. Parameterless function to register. Returns: func: decorated function. """ self.logic[name] = func @wraps(func) def wrapper(): """Wrapper, not used directly.""" raise RuntimeError('working outside of request context') return wrapper 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 pass_session_attributes(self): """Copies request attributes to response"""
for key, value in six.iteritems(self.request.session.attributes): self.response.sessionAttributes[key] = 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 dispatch(self): """Calls the matching logic function by request type or intent name."""
if self.request.request.type == 'IntentRequest': name = self.request.request.intent.name else: name = self.request.request.type if name in self.logic: self.logic[name]() else: error = 'Unable to find a registered logic function named: {}' raise KeyError(error.format(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 process(self, body, url=None, sig=None): """Process request body given skill logic. To validate a request, both, url and sig are required. Attributes received through body will be automatically added to the response. Args: body: str. HTTP request body. url: str. SignatureCertChainUrl header value sent by request. PEM-encoded X.509 certificate chain that Alexa used to sign the message. sig: str. Signature header value sent by request. Base64-encoded signature of the request body. Return: str or bool: HTTP response body or False if the request is invalid. """
self.request = RequestBody() self.response = ResponseBody() self.request.parse(body) app_id = self.request.session.application.application_id stamp = self.request.request.timestamp if not self.valid.request(app_id, body, stamp, url, sig): return False self.pass_session_attributes() self.dispatch() if self.request.request.type == 'SessionEndedRequest': self.terminate() return self.response.to_json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def walk(self, filters: str=None, filter_type: type=None, pprint=False, depth=-1): """ Iterate tree in pre-order wide-first search order :param filters: filter by python expression :param filter_type: Filter by class :return: """
children = self.children() if children is None: children = [] res = [] if depth == 0: return res elif depth != -1: depth -= 1 for child in children: if isinstance(child, Formula): tmp = child.walk(filters=filters, filter_type=filter_type, pprint=pprint, depth=depth) if tmp: res.extend(tmp) if filter_type is None: if filters is not None: if eval(filters) is True: res.append(self) else: res.append(self) elif isinstance(self, filter_type): if filters is not None: if eval(filters) is True: res.append(self) else: res.append(self) if pprint: res = [str(x) + " " for x in res] res = "\n".join(res) return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def red_workshift(request, message=None): ''' Redirects to the base workshift page for users who are logged in ''' if message: messages.add_message(request, messages.ERROR, message) return HttpResponseRedirect(reverse('workshift:view_semester'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _user_settings(self): """ Resolve settings dict from django settings module. Validate that all the required keys are present and also that none of the removed keys do. Result is cached. """
user_settings = getattr(settings, self._name, {}) if not user_settings and self._required: raise ImproperlyConfigured("Settings file is missing dict options with name {}".format(self._name)) keys = frozenset(user_settings.keys()) required = self._required - keys if required: raise ImproperlyConfigured("Following options for {} are missing from settings file: {}".format(self._name, ', '.join(sorted(required)))) removed = keys & self._removed if removed: raise ImproperlyConfigured("Following options for {} have been removed: {}".format(self._name, ', '.join(sorted(removed)))) return user_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 copy(self, empty=False): """returns an independent copy of the current object."""
# Create an empty object newobject = self.__new__(self.__class__) if empty: return # And fill it ! for prop in ["_properties","_side_properties", "_derived_properties","_build_properties" ]: if prop not in dir(self): continue try: # Try to deep copy because but some time it does not work (e.g. wcs) newobject.__dict__[prop] = copy.deepcopy(self.__dict__[prop]) except: newobject.__dict__[prop] = copy.copy(self.__dict__[prop]) # This be sure things are correct newobject._update_() # and return it return newobject
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def msg(self, message, *args, **kwargs): """Shortcut to send a message through the connection. This function sends the input message through the connection. A target can be defined, else it will send it to the channel or user from the input Line, effectively responding on whatever triggered the command which calls this function to be called. If raw has not been set to True, formatting will be applied using the standard Python Formatting Mini-Language, using the additional given args and kwargs, along with some additional kwargs, such as the match object to easily access Regex matches, color codes and other things. http://docs.python.org/3.3/library/string.html#format-string-syntax """
target = kwargs.pop('target', None) raw = kwargs.pop('raw', False) if not target: target = self.line.sender.nick if self.line.pm else \ self.line.target if not raw: kw = { 'm': self, 'b': chr(2), 'c': chr(3), 'u': chr(31), } kw.update(kwargs) try: message = message.format(*args, **kw) except IndexError: if len(args) == 1 and isinstance(args[0], list): # Message might be: msg, [arg1, arg2], kwargs message = message.format(*args[0], **kw) else: raise self.connection.msg(target, message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def shell_run(cmd, cin=None, cwd=None, timeout=10, critical=True, verbose=True): ''' Runs a shell command within a controlled environment. .. note:: |use_photon_m| :param cmd: The command to run * A string one would type into a console like \ :command:`git push -u origin master`. * Will be split using :py:func:`shlex.split`. * It is possible to use a list here, but then no splitting is done. :param cin: Add something to stdin of `cmd` :param cwd: Run `cmd` insde specified current working directory :param timeout: Catch infinite loops (e.g. ``ping``). Exit after `timeout` seconds :param critical: If set to ``True``: |appteardown| on failure of `cmd` :param verbose: Show messages and warnings :returns: A dictionary containing the results from running `cmd` with the following: * 'command': `cmd` * 'stdin': `cin` (If data was set in `cin`) * 'cwd': `cwd` (If `cwd` was set) * 'exception': exception message (If an exception was thrown) * 'timeout': `timeout` (If a timeout exception was thrown) * 'stdout': List from stdout (If any) * 'stderr': List from stderr (If any) * 'returncode': The returncode (If not any exception) * 'out': The most urgent message as joined string. \ ('exception' > 'stderr' > 'stdout') ''' res = dict(command=cmd) if cin: cin = str(cin) res.update(dict(stdin=cin)) if cwd: res.update(dict(cwd=cwd)) if isinstance(cmd, str): cmd = _split(cmd) try: p = _Popen( cmd, stdin=_PIPE, stdout=_PIPE, stderr=_PIPE, bufsize=1, cwd=cwd, universal_newlines=True ) except Exception as ex: res.update(dict(exception=str(ex))) else: try: out, err = p.communicate(input=cin, timeout=timeout) if out: res.update(dict( stdout=[o for o in out.split('\n') if o] )) if err: res.update(dict( stderr=[e for e in err.split('\n') if e] )) res.update(dict(returncode=p.returncode)) except _TimeoutExpired as ex: res.update(dict(exception=str(ex), timeout=timeout)) p.kill() except Exception as ex: res.update(dict(exception=str(ex))) res.update( out=( res.get('exception') or '\n'.join(res.get('stderr') or res.get('stdout', '')) ) ) if res.get('returncode', -1) != 0: res.update(dict(critical=critical)) shell_notify( 'error in shell command \'%s\'' % (res.get('command')), state=True if critical else None, more=res, verbose=verbose ) return res
<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_timestamp(time=True, precice=False): ''' What time is it? :param time: Append ``-%H.%M.%S`` to the final string. :param precice: Append ``-%f`` to the final string. Is only recognized when `time` is set to ``True`` :returns: A timestamp string of now in the format ``%Y.%m.%d-%H.%M.%S-%f`` .. seealso:: `strftime.org <http://strftime.org/>`_ is awesome! ''' f = '%Y.%m.%d' if time: f += '-%H.%M.%S' if precice: f += '-%f' return _datetime.now().strftime(f)
<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_hostname(): ''' Determines the current hostname by probing ``uname -n``. Falls back to ``hostname`` in case of problems. |appteardown| if both failed (usually they don't but consider this if you are debugging weird problems..) :returns: The hostname as string. Domain parts will be split off ''' h = shell_run('uname -n', critical=False, verbose=False) if not h: h = shell_run('hostname', critical=False, verbose=False) if not h: shell_notify('could not retrieve hostname', state=True) return str(h.get('out')).split('.')[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 open_connection(self, verbose=False): """ Initializes a new IMAP4_SSL connection to an email server."""
# Connect to server hostname = self.configs.get('IMAP', 'hostname') if verbose: print('Connecting to ' + hostname) connection = imaplib.IMAP4_SSL(hostname) # Authenticate username = self.configs.get('IMAP', 'username') password = self.configs.get('IMAP', 'password') if verbose: print('Logging in as', username) connection.login(username, password) return 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 get_body(self, msg): """ Extracts and returns the decoded body from an EmailMessage object"""
body = "" charset = "" if msg.is_multipart(): for part in msg.walk(): ctype = part.get_content_type() cdispo = str(part.get('Content-Disposition')) # skip any text/plain (txt) attachments if ctype == 'text/plain' and 'attachment' not in cdispo: body = part.get_payload(decode=True) # decode charset = part.get_content_charset() break # not multipart - i.e. plain text, no attachments, keeping fingers crossed else: body = msg.get_payload(decode=True) charset = msg.get_content_charset() return body.decode(charset)
<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_subject(self, msg): """Extracts the subject line from an EmailMessage object."""
text, encoding = decode_header(msg['subject'])[-1] try: text = text.decode(encoding) # If it's already decoded, ignore error except AttributeError: pass return text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def run(self, conn, tmp, module_name, module_args, inject): ''' transfer the given module name, plus the async module, then run it ''' # shell and command module are the same if module_name == 'shell': module_name = 'command' module_args += " #USE_SHELL" (module_path, is_new_style, shebang) = self.runner._copy_module(conn, tmp, module_name, module_args, inject) self.runner._low_level_exec_command(conn, "chmod a+rx %s" % module_path, tmp) return self.runner._execute_module(conn, tmp, 'async_wrapper', module_args, async_module=module_path, async_jid=self.runner.generated_jid, async_limit=self.runner.background, inject=inject )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getparams(self, param): """Get parameters which match with input param. :param Parameter param: parameter to compare with this parameters. :rtype: list """
return list(cparam for cparam in self.values() if cparam == param)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(): """ Parse the arguments and use them to create a ExistCli object """
version = 'Python Exist %s' % __version__ arguments = docopt(__doc__, version=version) ExistCli(arguments)
<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_config(self): """ Read credentials from the config file """
with open(self.config_file) as cfg: try: self.config.read_file(cfg) except AttributeError: self.config.readfp(cfg) self.client_id = self.config.get('exist', 'client_id') self.client_secret = self.config.get('exist', 'client_secret') self.access_token = self.config.get('exist', 'access_token')
<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_config(self, access_token): """ Write credentials to the config file """
self.config.add_section('exist') # TODO: config is reading 'None' as string during authorization, so clearing this out # if no id or secret is set - need to fix this later if self.client_id: self.config.set('exist', 'client_id', self.client_id) else: self.config.set('exist', 'client_id', '') if self.client_secret: self.config.set('exist', 'client_secret', self.client_secret) else: self.config.set('exist', 'client_secret', '') self.config.set('exist', 'access_token', access_token) with open(self.config_file, 'w') as cfg: self.config.write(cfg) print('Credentials written to %s' % self.config_file)
<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_resource(self, arguments): """ Gets the resource requested in the arguments """
attribute_name = arguments['<attribute_name>'] limit = arguments['--limit'] page = arguments['--page'] date_min = arguments['--date_min'] date_max = arguments['--date_max'] # feed in the config we have, and let the Exist class figure out the best # way to authenticate exist = Exist(self.client_id, self.client_secret, self.access_token) # TODO: Tidy this up since we are repeating ourselves a lot below if arguments['user']: result = exist.user() elif arguments['attributes']: result = exist.attributes(attribute_name, limit, page, date_min, date_max) elif arguments['insights']: result = exist.insights(attribute_name, limit, page, date_min, date_max) elif arguments['averages']: result = exist.averages(attribute_name, limit, page, date_min, date_max) elif arguments['correlations']: result = exist.correlations(attribute_name, limit, page, date_min, date_max) elif arguments['acquire_attributes']: attributes_dict = [{'name': x.split(':')[0], 'active': x.split(':')[1]} for x in arguments['<attribute:value>']] result = exist.arquire_attributes(attributes_dict) elif arguments['release_attributes']: attributes_dict = [{'name': x} for x in arguments['<attribute_name>']] result = exist.release_attributes(attributes_dict) elif arguments['owned_attributes']: result = exist.owned_attributes() elif arguments['update_attributes']: attributes_dict = [{'name': x.split(':')[0], 'date': x.split(':')[1], 'value': x.split(':')[2]} for x in arguments['<attribute:date:value>']] result = exist.update_attributes(attributes_dict) pp = PrettyPrinter(indent=4) if isinstance(result, list): pp.pprint([res.data for res in result]) else: pp.pprint(result.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 authorize(self, api_token=None, username=None, password=None): """ Authorize a user using the browser and a CherryPy server, and write the resulting credentials to a config file. """
access_token = None if username and password: # if we have a username and password, go and collect a token auth = ExistAuthBasic(username, password) auth.authorize() if auth.token: access_token = auth.token['access_token'] elif api_token: # if we already have a token, just use that access_token = api_token else: # if we have a client_id and client_secret, we need to # authorize through the browser auth = ExistAuth(self.client_id, self.client_secret, 'code', self.redirect_uri) auth.browser_authorize() if auth.token: access_token = auth.token['access_token'] # store the access token in the config file if access_token: self.write_config(access_token) else: print('ERROR: We were unable to authorize to use the Exist API.')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def refresh_token(self, arguments): """ Refresh a user's access token, using existing the refresh token previously received in the auth flow. """
new_access_token = None auth = ExistAuth(self.client_id, self.client_secret) resp = auth.refresh_token(self.access_token) if auth.token: new_access_token = auth.token['access_token'] print('OAuth token refreshed: %s' % new_access_token) self.write_config(new_access_token) else: print('ERROR: We were unable to refresh the OAuth token | %s' % json.dumps(resp))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _version_find_existing(): """Returns set of existing versions in this repository. This information is backed by previously used version tags in git. Available tags are pulled from origin repository before. :return: available versions :rtype: set """
_tool_run('git fetch origin -t') git_tags = [x for x in (y.strip() for y in (_tool_run('git tag -l') .stdout.split('\n'))) if x] return {tuple(int(n) if n else 0 for n in m.groups()) for m in (_version_re.match(t) for t in git_tags) if m}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _git_enable_branch(desired_branch): """Enable desired branch name."""
preserved_branch = _git_get_current_branch() try: if preserved_branch != desired_branch: _tool_run('git checkout ' + desired_branch) yield finally: if preserved_branch and preserved_branch != desired_branch: _tool_run('git checkout ' + preserved_branch)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mk_travis_config(): """Generate configuration for travis."""
t = dedent("""\ language: python python: 3.4 env: {jobs} install: - pip install -r requirements/ci.txt script: - invoke ci_run_job $TOX_JOB after_success: coveralls """) jobs = [env for env in parseconfig(None, 'tox').envlist if not env.startswith('cov-')] jobs += 'coverage', print(t.format(jobs=('\n'.join((' - TOX_JOB=' + job) for job in jobs))))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mkrelease(finish='yes', version=''): """Allocates the next version number and marks current develop branch state as a new release with the allocated version number. Syncs new state with origin repository. """
if not version: version = _version_format(_version_guess_next()) if _git_get_current_branch() != 'release/' + version: _tool_run('git checkout develop', 'git flow release start ' + version) _project_patch_version(version) _project_patch_changelog() patched_files = ' '.join([VERSION_FILE, CHANGES_FILE]) run('git diff ' + patched_files, pty=True) _tool_run(('git commit -m "Bump Version to {0!s}" {1!s}' .format(version, patched_files))) if finish not in ('no', 'n', ): _tool_run("git flow release finish -m '{0}' {0}".format(version), env={b'GIT_MERGE_AUTOEDIT': b'no', }) _tool_run('git push origin --tags develop master')
<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_allow_future(self): """ Only superusers and users with the permission can edit the post. """
qs = self.get_queryset() post_edit_permission = '{}.edit_{}'.format( qs.model._meta.app_label, qs.model._meta.model_name ) if self.request.user.has_perm(post_edit_permission): 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 update_changed_requirements(): """ Checks for changes in the requirements file across an update, and gets new requirements if changes have occurred. """
reqs_path = join(env.proj_path, env.reqs_path) get_reqs = lambda: run("cat %s" % reqs_path, show=False) old_reqs = get_reqs() if env.reqs_path else "" yield if old_reqs: new_reqs = get_reqs() if old_reqs == new_reqs: # Unpinned requirements should always be checked. for req in new_reqs.split("\n"): if req.startswith("-e"): if "@" not in req: # Editable requirement without pinned commit. break elif req.strip() and not req.startswith("#"): if not set(">=<") & set(req): # PyPI requirement without version. break else: # All requirements are pinned. return pip("-r %s/%s" % (env.proj_path, env.reqs_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 run(command, show=True, *args, **kwargs): """ Runs a shell comand on the remote server. """
if show: print_command(command) with hide("running"): return _run(command, *args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sudo(command, show=True, *args, **kwargs): """ Runs a command as sudo on the remote server. """
if show: print_command(command) with hide("running"): return _sudo(command, *args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_templates(): """ Returns each of the templates with env vars injected. """
injected = {} for name, data in templates.items(): injected[name] = dict([(k, v % env) for k, v in data.items()]) return injected
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upload_template_and_reload(name): """ Uploads a template only if it has changed, and if so, reload the related service. """
template = get_templates()[name] local_path = template["local_path"] if not os.path.exists(local_path): project_root = os.path.dirname(os.path.abspath(__file__)) local_path = os.path.join(project_root, local_path) remote_path = template["remote_path"] reload_command = template.get("reload_command") owner = template.get("owner") mode = template.get("mode") remote_data = "" if exists(remote_path): with hide("stdout"): remote_data = sudo("cat %s" % remote_path, show=False) with open(local_path, "r") as f: local_data = f.read() # Escape all non-string-formatting-placeholder occurrences of '%': local_data = re.sub(r"%(?!\(\w+\)s)", "%%", local_data) if "%(db_pass)s" in local_data: env.db_pass = db_pass() local_data %= env clean = lambda s: s.replace("\n", "").replace("\r", "").strip() if clean(remote_data) == clean(local_data): return upload_template(local_path, remote_path, env, use_sudo=True, backup=False) if owner: sudo("chown %s %s" % (owner, remote_path)) if mode: sudo("chmod %s %s" % (mode, remote_path)) if reload_command: sudo(reload_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 rsync_upload(): """ Uploads the project with rsync excluding some files and folders. """
excludes = ["*.pyc", "*.pyo", "*.db", ".DS_Store", ".coverage", "local_settings.py", "/static", "/.git", "/.hg"] local_dir = os.getcwd() + os.sep return rsync_project(remote_dir=env.proj_path, local_dir=local_dir, exclude=excludes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def vcs_upload(): """ Uploads the project with the selected VCS tool. """
if env.deploy_tool == "git": remote_path = "ssh://%s@%s%s" % (env.user, env.host_string, env.repo_path) if not exists(env.repo_path): run("mkdir -p %s" % env.repo_path) with cd(env.repo_path): run("git init --bare") local("git push -f %s master" % remote_path) with cd(env.repo_path): run("GIT_WORK_TREE=%s git checkout -f master" % env.proj_path) run("GIT_WORK_TREE=%s git reset --hard" % env.proj_path) elif env.deploy_tool == "hg": remote_path = "ssh://%s@%s/%s" % (env.user, env.host_string, env.repo_path) with cd(env.repo_path): if not exists("%s/.hg" % env.repo_path): run("hg init") print(env.repo_path) with fab_settings(warn_only=True): push = local("hg push -f %s" % remote_path) if push.return_code == 255: abort() run("hg update")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def postgres(command): """ Runs the given command as the postgres user. """
show = not command.startswith("psql") return sudo(command, show=show, user="postgres")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def psql(sql, show=True): """ Runs SQL against the project's database. """
out = postgres('psql -c "%s"' % sql) if show: print_command(sql) 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 backup(filename): """ Backs up the project database. """
tmp_file = "/tmp/%s" % filename # We dump to /tmp because user "postgres" can't write to other user folders # We cd to / because user "postgres" might not have read permissions # elsewhere. with cd("/"): postgres("pg_dump -Fc %s > %s" % (env.proj_name, tmp_file)) run("cp %s ." % tmp_file) sudo("rm -f %s" % tmp_file)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def python(code, show=True): """ Runs Python code in the project's virtual environment, with Django loaded. """
setup = "import os;" \ "os.environ[\'DJANGO_SETTINGS_MODULE\']=\'%s.settings\';" \ "import django;" \ "django.setup();" % env.proj_app full_code = 'python -c "%s%s"' % (setup, code.replace("`", "\\\`")) with project(): if show: print_command(code) result = run(full_code, show=False) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def install(): """ Installs the base system and Python requirements for the entire server. """
# Install system requirements sudo("apt-get update -y -q") apt("nginx libjpeg-dev python-dev python-setuptools git-core " "postgresql libpq-dev memcached supervisor python-pip") run("mkdir -p /home/%s/logs" % env.user) # Install Python requirements sudo("pip install -U pip virtualenv virtualenvwrapper mercurial") # Set up virtualenv run("mkdir -p %s" % env.venv_home) run("echo 'export WORKON_HOME=%s' >> /home/%s/.bashrc" % (env.venv_home, env.user)) run("echo 'source /usr/local/bin/virtualenvwrapper.sh' >> " "/home/%s/.bashrc" % env.user) print(green("Successfully set up git, mercurial, pip, virtualenv, " "supervisor, memcached.", bold=True))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove(): """ Blow away the current project. """
if exists(env.venv_path): run("rm -rf %s" % env.venv_path) if exists(env.proj_path): run("rm -rf %s" % env.proj_path) for template in get_templates().values(): remote_path = template["remote_path"] if exists(remote_path): sudo("rm %s" % remote_path) if exists(env.repo_path): run("rm -rf %s" % env.repo_path) sudo("supervisorctl update") psql("DROP DATABASE IF EXISTS %s;" % env.proj_name) psql("DROP USER IF EXISTS %s;" % env.proj_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 deploy(): """ Deploy latest version of the project. Backup current version of the project, push latest version of the project via version control or rsync, install new requirements, sync and migrate the database, collect any new static assets, and restart gunicorn's worker processes for the project. """
if not exists(env.proj_path): if confirm("Project does not exist in host server: %s" "\nWould you like to create it?" % env.proj_name): create() else: abort() # Backup current version of the project with cd(env.proj_path): backup("last.db") if env.deploy_tool in env.vcs_tools: with cd(env.repo_path): if env.deploy_tool == "git": run("git rev-parse HEAD > %s/last.commit" % env.proj_path) elif env.deploy_tool == "hg": run("hg id -i > last.commit") with project(): static_dir = static() if exists(static_dir): run("tar -cf static.tar --exclude='*.thumbnails' %s" % static_dir) else: with cd(join(env.proj_path, "..")): excludes = ["*.pyc", "*.pio", "*.thumbnails"] exclude_arg = " ".join("--exclude='%s'" % e for e in excludes) run("tar -cf {0}.tar {1} {0}".format(env.proj_name, exclude_arg)) # Deploy latest version of the project with update_changed_requirements(): if env.deploy_tool in env.vcs_tools: vcs_upload() else: rsync_upload() with project(): manage("collectstatic -v 0 --noinput") manage("migrate --noinput") for name in get_templates(): upload_template_and_reload(name) restart() return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rollback(): """ Reverts project state to the last deploy. When a deploy is performed, the current state of the project is backed up. This includes the project files, the database, and all static files. Calling rollback will revert all of these to their state prior to the last deploy. """
with update_changed_requirements(): if env.deploy_tool in env.vcs_tools: with cd(env.repo_path): if env.deploy_tool == "git": run("GIT_WORK_TREE={0} git checkout -f " "`cat {0}/last.commit`".format(env.proj_path)) elif env.deploy_tool == "hg": run("hg update -C `cat last.commit`") with project(): with cd(join(static(), "..")): run("tar -xf %s/static.tar" % env.proj_path) else: with cd(env.proj_path.rsplit("/", 1)[0]): run("rm -rf %s" % env.proj_name) run("tar -xf %s.tar" % env.proj_name) with cd(env.proj_path): restore("last.db") restart()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_single(site, domain, delete_code=False, no_prompt=False): """ Delete a single site @type site: Site @type domain: Domain @type delete_code: bool @type no_prompt: bool """
click.secho('Deleting installation "{sn}" hosted on the domain {dn}'.format(sn=site.name, dn=domain.name), fg='yellow', bold=True) if not no_prompt: if delete_code: warn_text = click.style('WARNING! THIS WILL PERMANENTLY DELETE THIS SITE AND ALL OF THE ASSOCIATED ' 'PROJECT CODE FILES!\nTHIS MEANS ALL DATA FILES, INCLUDING ANY CREATED CUSTOM ' 'APPLICATIONS AND PLUGINS WILL BE PERMANENTLY AND IRREVOCABLY ERASED!', fg='red', bold=True) click.echo(warn_text) prompt_text = click.style('In order to continue, please re-input the site name', fg='white', bold=True) prompt = click.prompt(prompt_text) # If our prompt doesn't match, abort if prompt != site.name: click.secho('Site name did not match, site will not be deleted. Aborting.', fg='red', bold=True) raise click.Abort('Site name prompt did not match') else: prompt_text = click.style('Are you sure you want to delete this site entry? Your project files will ' 'still be preserved.', fg='white', bold=True) click.confirm(prompt_text, abort=True) site.delete() if delete_code: _remove_code(site) # If this is the only site left in the domain, remove the domain now as well domain_sites = [ds for ds in domain.sites if ds.id != site.id] if not len(domain_sites): Session.delete(domain) Session.commit() click.secho('{sn} removed'.format(sn=site.name), fg='yellow', bold=True) # Restart Nginx FNULL = open(os.devnull, 'w') subprocess.check_call(['service', 'nginx', 'restart'], stdout=FNULL, stderr=subprocess.STDOUT)