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 export_json(self, filename): """ Export graph in JSON form to the given file. """
json_graph = self.to_json() with open(filename, 'wb') as f: f.write(json_graph.encode('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 import_json(cls, filename): """ Import graph from the given file. The file is expected to contain UTF-8 encoded JSON data. """
with open(filename, 'rb') as f: json_graph = f.read().decode('utf-8') return cls.from_json(json_graph)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_dot(self): """ Produce a graph in DOT format. """
edge_labels = { edge.id: edge.annotation for edge in self._edges } edges = [self._format_edge(edge_labels, edge) for edge in self._edges] vertices = [ DOT_VERTEX_TEMPLATE.format( vertex=vertex.id, label=dot_quote(vertex.annotation), ) for vertex in self.vertices ] return DOT_DIGRAPH_TEMPLATE.format( edges="".join(edges), vertices="".join(vertices), )
<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_brew(target_path): """ Install brew to the target path """
if not os.path.exists(target_path): try: os.makedirs(target_path) except OSError: logger.warn("Unable to create directory %s for brew." % target_path) logger.warn("Skipping...") return extract_targz(HOMEBREW_URL, target_path, remove_common_prefix=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 pass_service(*names): """Injects a service instance into the kwargs """
def decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): for name in names: kwargs[name] = service_proxy(name) return f(*args, **kwargs) 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 get_conn(): """Return a connection to DynamoDB."""
if os.environ.get('DEBUG', False) or os.environ.get('travis', False): # In DEBUG mode - use the local DynamoDB # This also works for travis since we'll be running dynalite conn = DynamoDBConnection( host='localhost', port=8000, aws_access_key_id='TEST', aws_secret_access_key='TEST', is_secure=False ) else: # Regular old production conn = DynamoDBConnection() return conn
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def table_schema_call(self, target, cls): """Perform a table schema call. We call the callable target with the args and keywords needed for the table defined by cls. This is how we centralize the Table.create and Table ctor calls. """
index_defs = [] for name in cls.index_names() or []: index_defs.append(GlobalIncludeIndex( gsi_name(name), parts=[HashKey(name)], includes=['value'] )) return target( cls.get_table_name(), connection=get_conn(), schema=[HashKey('id')], global_indexes=index_defs or 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 thread(self): """ Start a thread for this consumer. """
log.info('@{}.thread starting'.format(self.__class__.__name__)) thread = threading.Thread(target=thread_wrapper(self.consume), args=()) thread.daemon = True thread.start()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_multifile(self, desired_type: Type[T], obj: PersistedObject, parsing_plan_for_children: Dict[str, ParsingPlan], logger: Logger, options: Dict[str, Dict[str, Any]]) -> T: """ First parse all children from the parsing plan, then calls _build_object_from_parsed_children :param desired_type: :param obj: :param parsing_plan_for_children: :param logger: :param options: :return: """
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 execute(self, logger: Logger, options: Dict[str, Dict[str, Any]]) -> T: """ Overrides the parent method to add log messages. :param logger: the logger to use during parsing (optional: None is supported) :param options: :return: """
in_root_call = False if logger is not None: # log only for the root object, not for the children that will be created by the code below if not hasattr(_BaseParsingPlan.thrd_locals, 'flag_exec') \ or _BaseParsingPlan.thrd_locals.flag_exec == 0: # print('Executing Parsing Plan for ' + str(self)) logger.debug('Executing Parsing Plan for [{location}]' ''.format(location=self.obj_on_fs_to_parse.get_pretty_location(append_file_ext=False))) _BaseParsingPlan.thrd_locals.flag_exec = 1 in_root_call = True # Common log message logger.debug('(P) ' + get_parsing_plan_log_str(self.obj_on_fs_to_parse, self.obj_type, log_only_last=not in_root_call, parser=self.parser)) try: res = super(_BaseParsingPlan, self).execute(logger, options) if logger.isEnabledFor(DEBUG): logger.info('(P) {loc} -> {type} SUCCESS !' ''.format(loc=self.obj_on_fs_to_parse.get_pretty_location( blank_parent_part=not GLOBAL_CONFIG.full_paths_in_logs, compact_file_ext=True), type=get_pretty_type_str(self.obj_type))) else: logger.info('SUCCESS parsed [{loc}] as a [{type}] successfully. Parser used was [{parser}]' ''.format(loc=self.obj_on_fs_to_parse.get_pretty_location(compact_file_ext=True), type=get_pretty_type_str(self.obj_type), parser=str(self.parser))) if in_root_call: # print('Completed parsing successfully') logger.debug('Completed parsing successfully') return res finally: # remove threadlocal flag if needed if in_root_call: _BaseParsingPlan.thrd_locals.flag_exec = 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 _execute(self, logger: Logger, options: Dict[str, Dict[str, Any]]) -> T: """ Implementation of the parent class method. Checks that self.parser is a _BaseParser, and calls the appropriate parsing method. :param logger: :param options: :return: """
if isinstance(self.parser, _BaseParser): if (not self.is_singlefile) and self.parser.supports_multifile(): return self.parser._parse_multifile(self.obj_type, self.obj_on_fs_to_parse, self._get_children_parsing_plan(), logger, options) elif self.is_singlefile and self.parser.supports_singlefile(): return self.parser._parse_singlefile(self.obj_type, self.get_singlefile_path(), self.get_singlefile_encoding(), logger, options) else: raise _InvalidParserException.create(self.parser, self.obj_on_fs_to_parse) else: raise TypeError('Parser attached to this _BaseParsingPlan is not a ' + str(_BaseParser))
<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_parsing_plan(self, desired_type: Type[T], filesystem_object: PersistedObject, logger: Logger, _main_call: bool = True): """ Implements the abstract parent method by using the recursive parsing plan impl. Subclasses wishing to produce their own parsing plans should rather override _create_parsing_plan in order to benefit from this same log msg. :param desired_type: :param filesystem_object: :param logger: :param _main_call: internal parameter for recursive calls. Should not be changed by the user. :return: """
in_root_call = False # -- log msg only for the root call, not for the children that will be created by the code below if _main_call and (not hasattr(AnyParser.thrd_locals, 'flag_init') or AnyParser.thrd_locals.flag_init == 0): # print('Building a parsing plan to parse ' + str(filesystem_object) + ' into a ' + # get_pretty_type_str(desired_type)) logger.debug('Building a parsing plan to parse [{location}] into a {type}' ''.format(location=filesystem_object.get_pretty_location(append_file_ext=False), type=get_pretty_type_str(desired_type))) AnyParser.thrd_locals.flag_init = 1 in_root_call = True # -- create the parsing plan try: pp = self._create_parsing_plan(desired_type, filesystem_object, logger, log_only_last=(not _main_call)) finally: # remove threadlocal flag if needed if in_root_call: AnyParser.thrd_locals.flag_init = 0 # -- log success only if in root call if in_root_call: # print('Parsing Plan created successfully') logger.debug('Parsing Plan created successfully') # -- finally return return pp
<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_parsing_plan(self, desired_type: Type[T], filesystem_object: PersistedObject, logger: Logger, log_only_last: bool = False): """ Adds a log message and creates a recursive parsing plan. :param desired_type: :param filesystem_object: :param logger: :param log_only_last: a flag to only log the last part of the file path (default False) :return: """
logger.debug('(B) ' + get_parsing_plan_log_str(filesystem_object, desired_type, log_only_last=log_only_last, parser=self)) return AnyParser._RecursiveParsingPlan(desired_type, filesystem_object, self, logger)
<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_parsing_plan_for_multifile_children(self, obj_on_fs: PersistedObject, desired_type: Type[T], logger: Logger) -> Dict[str, ParsingPlan[T]]: """ This method is called by the _RecursiveParsingPlan when created. Implementing classes should return a dictionary containing a ParsingPlan for each child they plan to parse using this framework. Note that for the files that will be parsed using a parsing library it is not necessary to return a ParsingPlan. In other words, implementing classes should return here everything they need for their implementation of _parse_multifile to succeed. Indeed during parsing execution, the framework will call their _parse_multifile method with that same dictionary as an argument (argument name is 'parsing_plan_for_children', see _BaseParser). :param obj_on_fs: :param desired_type: :param logger: :return: """
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 _parse_singlefile(self, desired_type: Type[T], file_path: str, encoding: str, logger: Logger, options: Dict[str, Dict[str, Any]]) -> T: """ Relies on the inner parsing function to parse the file. If _streaming_mode is True, the file will be opened and closed by this method. Otherwise the parsing function will be responsible to open and close. :param desired_type: :param file_path: :param encoding: :param options: :return: """
opts = get_options_for_id(options, self.get_id_for_options()) if self._streaming_mode: # We open the stream, and let the function parse from it file_stream = None try: # Open the file with the appropriate encoding file_stream = open(file_path, 'r', encoding=encoding) # Apply the parsing function if self.function_args is None: return self._parser_func(desired_type, file_stream, logger, **opts) else: return self._parser_func(desired_type, file_stream, logger, **self.function_args, **opts) except TypeError as e: raise CaughtTypeError.create(self._parser_func, e) finally: if file_stream is not None: # Close the File in any case file_stream.close() else: # the parsing function will open the file itself if self.function_args is None: return self._parser_func(desired_type, file_path, encoding, logger, **opts) else: return self._parser_func(desired_type, file_path, encoding, logger, **self.function_args, **opts)
<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_error_to_io_stream(err: Exception, io: TextIOBase, print_big_traceback : bool = True): """ Utility method to print an exception's content to a stream :param err: :param io: :param print_big_traceback: :return: """
if print_big_traceback: traceback.print_tb(err.__traceback__, file=io, limit=-GLOBAL_CONFIG.multiple_errors_tb_limit) else: traceback.print_tb(err.__traceback__, file=io, limit=-1) io.writelines(' ' + str(err.__class__.__name__) + ' : ' + 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 should_hide_traceback(e): """ Returns True if we can hide the error traceback in the warnings messages """
if type(e) in {WrongTypeCreatedError, CascadeError, TypeInformationRequiredError}: return True elif type(e).__name__ in {'InvalidAttributeNameForConstructorError', 'MissingMandatoryAttributeFiles'}: return True else: 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 _create_parsing_plan(self, desired_type: Type[T], filesystem_object: PersistedObject, logger: Logger, log_only_last: bool = False) -> ParsingPlan[T]: """ Creates a parsing plan to parse the given filesystem object into the given desired_type. This overrides the method in AnyParser, in order to provide a 'cascading' parsing plan :param desired_type: :param filesystem_object: :param logger: :param log_only_last: a flag to only log the last part of the file path (default False) :return: """
# build the parsing plan logger.debug('(B) ' + get_parsing_plan_log_str(filesystem_object, desired_type, log_only_last=log_only_last, parser=self)) return CascadingParser.CascadingParsingPlan(desired_type, filesystem_object, self, self._parsers_list, logger=logger)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def are_worth_chaining(base_parser: Parser, to_type: Type[S], converter: Converter[S,T]) -> bool: """ Utility method to check if it makes sense to chain this parser configured with the given to_type, with this converter. It is an extension of ConverterChain.are_worth_chaining :param base_parser: :param to_type: :param converter: :return: """
if isinstance(converter, ConversionChain): for conv in converter._converters_list: if not Parser.are_worth_chaining(base_parser, to_type, conv): return False # all good return True else: return Parser.are_worth_chaining(base_parser, to_type, converter)
<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_mode(self, mode): """Set Lupusec alarm mode."""
_LOGGER.debug('State change called from alarm device') if not mode: _LOGGER.info('No mode supplied') elif mode not in CONST.ALL_MODES: _LOGGER.warning('Invalid mode') response_object = self._lupusec.set_mode(CONST.MODE_TRANSLATION[mode]) if response_object['result'] != 1: _LOGGER.warning('Mode setting unsuccessful') self._json_state['mode'] = mode _LOGGER.info('Mode set to: %s', mode) 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 to_utf8(value): """Returns a string encoded using UTF-8. This function comes from `Tornado`_. :param value: A unicode or string to be encoded. :returns: The encoded string. """
if isinstance(value, unicode): return value.encode('utf-8') assert isinstance(value, str) return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_unicode(value): """Returns a unicode string from a string, using UTF-8 to decode if needed. This function comes from `Tornado`_. :param value: A unicode or string to be decoded. :returns: The decoded string. """
if isinstance(value, str): return value.decode('utf-8') assert isinstance(value, unicode) return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_commands(): """ Get all valid commands return - all valid commands in dictionary form """
commands = {} #Try to load the settings file (settings can be specified on the command line) and get the INSTALLED_APPS try: from percept.conf.base import settings apps = settings.INSTALLED_APPS except KeyError: apps = [] #For each app, try to find the command module (command folder in the app) #Then, try to load all commands in the directory for app_name in apps: try: path = find_commands_module(app_name) commands.update(dict([(name, app_name) for name in find_all_commands(path)])) except ImportError as e: pass return commands
<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): """ Run the command with the command line arguments """
#Initialize the option parser parser = LaxOptionParser( usage="%prog subcommand [options] [args]", option_list=BaseCommand.option_list #This will define what is allowed input to the parser (ie --settings=) ) #Parse the options options, args = parser.parse_args(self.argv) #Handle --settings and --pythonpath properly options = handle_default_options(options) try: #Get the name of the subcommand subcommand = self.argv[1] except IndexError: #If the subcommand name cannot be found, set it to help subcommand = 'help' #If the subcommand is help, print the usage of the parser, and available command names if subcommand == 'help': if len(args) <= 2: parser.print_help() sys.stdout.write(self.help_text + '\n') else: #Otherwise, run the given command self.fetch_command(subcommand).run_from_argv(self.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 help_text(self): """ Formats and prints the help text from the command list """
help_text = '\n'.join(sorted(get_commands().keys())) help_text = "\nCommands:\n" + help_text return help_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 register(self): """ Registers a new device with the name entity_id. This device has permissions for services like subscribe, publish and access historical data. """
register_url = self.base_url + "api/0.1.0/register" register_headers = { "apikey": str(self.owner_api_key), "resourceID": str(self.entity_id), "serviceType": "publish,subscribe,historicData" } with self.no_ssl_verification(): r = requests.get(register_url, {}, headers=register_headers) response = r.content.decode("utf-8") if "APIKey" in str(r.content.decode("utf-8")): response = json.loads(response[:-331] + "}") # Temporary fix to a middleware bug, should be removed in future response["Registration"] = "success" else: response = json.loads(response) response["Registration"] = "failure" 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 no_ssl_verification(self): """ Requests module fails due to lets encrypt ssl encryption. Will be fixed in the future release."""
try: from functools import partialmethod except ImportError: # Python 2 fallback: https://gist.github.com/carymrobbins/8940382 from functools import partial class partialmethod(partial): def __get__(self, instance, owner): if instance is None: return self return partial(self.func, instance, *(self.args or ()), **(self.keywords or {})) old_request = requests.Session.request requests.Session.request = partialmethod(old_request, verify=False) warnings.filterwarnings('ignore', 'Unverified HTTPS request') yield warnings.resetwarnings() requests.Session.request = old_request
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def publish(self, data): """ This function allows an entity to publish data to the middleware. Args: data (string): contents to be published by this entity. """
if self.entity_api_key == "": return {'status': 'failure', 'response': 'No API key found in request'} publish_url = self.base_url + "api/0.1.0/publish" publish_headers = {"apikey": self.entity_api_key} publish_data = { "exchange": "amq.topic", "key": str(self.entity_id), "body": str(data) } with self.no_ssl_verification(): r = requests.post(publish_url, json.dumps(publish_data), headers=publish_headers) response = dict() if "No API key" in str(r.content.decode("utf-8")): response["status"] = "failure" r = json.loads(r.content.decode("utf-8"))['message'] elif 'publish message ok' in str(r.content.decode("utf-8")): response["status"] = "success" r = r.content.decode("utf-8") else: response["status"] = "failure" r = r.content.decode("utf-8") response["response"] = str(r) 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 db(self, entity, query_filters="size=10"): """ This function allows an entity to access the historic data. Args: entity (string): Name of the device to listen to query_filters (string): Elastic search response format string example, "pretty=true&size=10" """
if self.entity_api_key == "": return {'status': 'failure', 'response': 'No API key found in request'} historic_url = self.base_url + "api/0.1.0/historicData?" + query_filters historic_headers = { "apikey": self.entity_api_key, "Content-Type": "application/json" } historic_query_data = json.dumps({ "query": { "match": { "key": entity } } }) with self.no_ssl_verification(): r = requests.get(historic_url, data=historic_query_data, headers=historic_headers) response = dict() if "No API key" in str(r.content.decode("utf-8")): response["status"] = "failure" else: r = r.content.decode("utf-8") response = r 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 bind(self, devices_to_bind): """ This function allows an entity to list the devices to subscribe for data. This function must be called at least once, before doing a subscribe. Subscribe function will listen to devices that are bound here. Args: devices_to_bind (list): an array of devices to listen to. Example bind(["test100","testDemo"]) """
if self.entity_api_key == "": return {'status': 'failure', 'response': 'No API key found in request'} url = self.base_url + "api/0.1.0/subscribe/bind" headers = {"apikey": self.entity_api_key} data = { "exchange": "amq.topic", "keys": devices_to_bind, "queue": self.entity_id } with self.no_ssl_verification(): r = requests.post(url, json=data, headers=headers) response = dict() if "No API key" in str(r.content.decode("utf-8")): response["status"] = "failure" r = json.loads(r.content.decode("utf-8"))['message'] elif 'bind queue ok' in str(r.content.decode("utf-8")): response["status"] = "success" r = r.content.decode("utf-8") else: response["status"] = "failure" r = r.content.decode("utf-8") response["response"] = str(r) 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 unbind(self, devices_to_unbind): """ This function allows an entity to unbound devices that are already bound. Args: devices_to_unbind (list): an array of devices that are to be unbound ( stop listening) Example unbind(["test10","testDemo105"]) """
if self.entity_api_key == "": return {'status': 'failure', 'response': 'No API key found in request'} url = self.base_url + "api/0.1.0/subscribe/unbind" headers = {"apikey": self.entity_api_key} data = { "exchange": "amq.topic", "keys": devices_to_unbind, "queue": self.entity_id } with self.no_ssl_verification(): r = requests.delete(url, json=data, headers=headers) print(r) response = dict() if "No API key" in str(r.content.decode("utf-8")): response["status"] = "failure" r = json.loads(r.content.decode("utf-8"))['message'] elif 'unbind' in str(r.content.decode("utf-8")): response["status"] = "success" r = r.content.decode("utf-8") else: response["status"] = "failure" r = r.content.decode("utf-8") response["response"] = str(r) 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 subscribe(self, devices_to_bind=[]): """ This function allows an entity to subscribe for data from the devices specified in the bind operation. It creates a thread with an event loop to manager the tasks created in start_subscribe_worker. Args: devices_to_bind (list): an array of devices to listen to """
if self.entity_api_key == "": return {'status': 'failure', 'response': 'No API key found in request'} self.bind(devices_to_bind) loop = asyncio.new_event_loop() t1 = threading.Thread(target=self.start_subscribe_worker, args=(loop,)) t1.daemon = True t1.start()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start_subscribe_worker(self, loop): """ Switch to new event loop as a thread and run until complete. """
url = self.base_url + "api/0.1.0/subscribe" task = loop.create_task(self.asynchronously_get_data(url + "?name={0}".format(self.entity_id))) asyncio.set_event_loop(loop) loop.run_until_complete(task) self.event_loop = loop
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop_subscribe(self): """ This function is used to stop the event loop created when subscribe is called. But this function doesn't stop the thread and should be avoided until its completely developed. """
asyncio.gather(*asyncio.Task.all_tasks()).cancel() self.event_loop.stop() self.event_loop.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 timeuntil(d, now=None): """ Like timesince, but returns a string measuring the time until the given time. """
if not now: if getattr(d, 'tzinfo', None): now = datetime.datetime.now(LocalTimezone(d)) else: now = datetime.datetime.now() return timesince(now, 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 delete_all_eggs(self): """ delete all the eggs in the directory specified """
path_to_delete = os.path.join(self.egg_directory, "lib", "python") if os.path.exists(path_to_delete): shutil.rmtree(path_to_delete)
<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_egg(self, egg_name): """ Install an egg into the egg directory """
if not os.path.exists(self.egg_directory): os.makedirs(self.egg_directory) self.requirement_set.add_requirement( InstallRequirement.from_line(egg_name, None)) try: self.requirement_set.prepare_files(self.finder) self.requirement_set.install(['--prefix=' + self.egg_directory], []) except DistributionNotFound: self.requirement_set.requirements._keys.remove(egg_name) raise PipException()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def chunks(cls, iterable, n, fill=None): """ Collects elements in fixed-length chunks. """
return cls(itertools.zip_longest(*[iter(iterable)] * n, fillvalue=fill))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def partition(cls, iterable, pred): """ Use a predicate to partition items into false and true entries. """
t1, t2 = itertools.tee(iterable) return cls(itertools.filterfalse(pred, t1), filter(pred, t2))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def count(cls, iterable): """ Returns the number of items in an iterable. """
iterable = iter(iterable) count = 0 while True: try: next(iterable) except StopIteration: break count += 1 return count
<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_names(self, table): """An iterable of column names, for a particular table or view."""
table_info = self.execute( u'PRAGMA table_info(%s)' % quote(table)) return (column['name'] for column in table_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 execute(self, sql, *args, **kwargs): ''' Run raw SQL on the database, and receive relaxing output. This is sort of the foundational method that most of the others build on. ''' try: self.cursor.execute(sql, *args) except self.sqlite3.InterfaceError, msg: raise self.sqlite3.InterfaceError(unicode(msg) + '\nTry converting types or pickling.') rows = self.cursor.fetchall() self.__commit_if_necessary(kwargs) if None == self.cursor.description: return None else: colnames = [d[0].decode('utf-8') for d in self.cursor.description] rawdata = [OrderedDict(zip(colnames,row)) for row in rows] return rawdata
<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_table(self, data, table_name, error_if_exists = False, **kwargs): 'Create a table based on the data, but don\'t insert anything.' converted_data = convert(data) if len(converted_data) == 0 or converted_data[0] == []: raise ValueError(u'You passed no sample values, or all the values you passed were null.') else: startdata = OrderedDict(converted_data[0]) # Select a non-null item for k, v in startdata.items(): if v != None: break else: v = None if_not_exists = u'' if error_if_exists else u'IF NOT EXISTS' # Do nothing if all items are null. if v != None: try: # This is vulnerable to injection. sql = u''' CREATE TABLE %s %s ( %s %s );''' % (if_not_exists, quote(table_name), quote(k), get_column_type(startdata[k])) self.execute(sql, commit = False) except: raise else: self.commit() for row in converted_data: self.__check_and_add_columns(table_name, row)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_var(self, key): 'Retrieve one saved variable from the database.' vt = quote(self.__vars_table) data = self.execute(u'SELECT * FROM %s WHERE `key` = ?' % vt, [key], commit = False) if data == []: raise NameError(u'The DumpTruck variables table doesn\'t have a value for %s.' % key) else: tmp = quote(self.__vars_table_tmp) row = data[0] self.execute(u'DROP TABLE IF EXISTS %s' % tmp, commit = False) # This is vulnerable to injection self.execute(u'CREATE TEMPORARY TABLE %s (`value` %s)' % (tmp, row['type']), commit = False) # This is ugly self.execute(u'INSERT INTO %s (`value`) VALUES (?)' % tmp, [row['value']], commit = False) value = self.dump(tmp)[0]['value'] self.execute(u'DROP TABLE %s' % tmp, commit = False) return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def save_var(self, key, value, **kwargs): 'Save one variable to the database.' # Check whether Highwall's variables table exists self.__check_or_create_vars_table() column_type = get_column_type(value) tmp = quote(self.__vars_table_tmp) self.execute(u'DROP TABLE IF EXISTS %s' % tmp, commit = False) # This is vulnerable to injection self.execute(u'CREATE TABLE %s (`value` %s)' % (tmp, column_type), commit = False) # This is ugly self.execute(u'INSERT INTO %s (`value`) VALUES (?)' % tmp, [value], commit = False) table = (quote(self.__vars_table), tmp) params = [key, column_type] self.execute(u''' INSERT OR REPLACE INTO %s (`key`, `type`, `value`) SELECT ? AS key, ? AS type, value FROM %s ''' % table, params) self.execute(u'DROP TABLE %s' % tmp, commit = False) self.__commit_if_necessary(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 drop(self, table_name = 'dumptruck', if_exists = False, **kwargs): 'Drop a table.' return self.execute(u'DROP TABLE %s %s;' % ('IF EXISTS' if if_exists else '', quote(table_name)), **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 __install_perforce(self, config): """ install perforce binary """
if not system.is_64_bit(): self.logger.warn("Perforce formula is only designed for 64 bit systems! Not install executables...") return False version = config.get('version', 'r13.2') key = 'osx' if system.is_osx() else 'linux' perforce_packages = package_dict[version][key] d = self.directory.install_directory(self.feature_name) if not os.path.exists(d): os.makedirs(d) self.logger.info("Downloading p4 executable...") with open(os.path.join(d, "p4"), 'wb+') as fh: fh.write(lib.cleaned_request('get', url_prefix + perforce_packages['p4']).content) self.directory.symlink_to_bin("p4", os.path.join(d, "p4")) self.p4_command = os.path.join(d, "p4") self.logger.info("Installing p4v...") if system.is_osx(): return self._install_p4v_osx(url_prefix + perforce_packages['p4v']) else: return self._install_p4v_linux(url_prefix + perforce_packages['p4v'])
<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_p4v_osx(self, url, overwrite=False): """ Install perforce applications and binaries for mac """
package_exists = False root_dir = os.path.expanduser(os.path.join("~", "Applications")) package_exists = len([x for x in P4V_APPLICATIONS if os.path.exists(os.path.join(root_dir, x))]) if not package_exists or overwrite: lib.extract_dmg(url, root_dir) else: self.logger.warn("P4V exists already in %s! Not overwriting..." % root_dir) 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 _install_p4v_linux(self, url): """ Install perforce applications and binaries for linux """
lib.extract_targz(url, self.directory.install_directory(self.feature_name), remove_common_prefix=True) bin_path = os.path.join(self.directory.install_directory(self.feature_name), 'bin') if os.path.exists(bin_path): for f in os.listdir(bin_path): self.directory.symlink_to_bin(f, os.path.join(bin_path, f)) 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 __write_p4settings(self, config): """ write perforce settings """
self.logger.info("Writing p4settings...") root_dir = os.path.expanduser(config.get('root_path')) p4settings_path = os.path.join(root_dir, ".p4settings") if os.path.exists(p4settings_path): if self.target.get('overwrite_p4settings', False): self.logger.info("Overwriting existing p4settings...") os.remove(p4settings_path) else: return with open(p4settings_path, "w+") as p4settings_file: p4settings_file.write(p4settings_template % config.to_dict()) if config.get('write_password_p4settings', 'no'): p4settings_file.write("\nP4PASSWD=%s" % config['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 __configure_client(self, config): """ write the perforce client """
self.logger.info("Configuring p4 client...") client_dict = config.to_dict() client_dict['root_path'] = os.path.expanduser(config.get('root_path')) os.chdir(client_dict['root_path']) client_dict['hostname'] = system.NODE client_dict['p4view'] = config['p4view'] % self.environment.target.get_context_dict() client = re.sub('//depot', ' //depot', p4client_template % client_dict) self.logger.info(lib.call("%s client -i" % self.p4_command, stdin=client, env=self.p4environ, cwd=client_dict['root_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 __install_eggs(self, config): """ Install eggs for a particular configuration """
egg_carton = (self.directory.install_directory(self.feature_name), 'requirements.txt') eggs = self.__gather_eggs(config) self.logger.debug("Installing eggs %s..." % eggs) self.__load_carton(egg_carton, eggs) self.__prepare_eggs(egg_carton, config)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __add_paths(self, config): """ add the proper resources into the environment """
bin_path = os.path.join(self.directory.install_directory(self.feature_name), 'bin') whitelist_executables = self._get_whitelisted_executables(config) for f in os.listdir(bin_path): for pattern in BLACKLISTED_EXECUTABLES: if re.match(pattern, f): continue if whitelist_executables and f not in whitelist_executables: continue self.directory.symlink_to_bin(f, os.path.join(bin_path, 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 amended_commits(commits): """Return those git commit sha1s that have been amended later."""
# which SHA1 are declared as amended later? amended_sha1s = [] for message in commits.values(): amended_sha1s.extend(re.findall(r'AMENDS\s([0-f]+)', message)) return amended_sha1s
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enrich_git_log_dict(messages, labels): """Enrich git log with related information on tickets."""
for commit_sha1, message in messages.items(): # detect module and ticket numbers for each commit: component = None title = message.split('\n')[0] try: component, title = title.split(":", 1) component = component.strip() except ValueError: pass # noqa paragraphs = [analyse_body_paragraph(p, labels) for p in message.split('\n\n')] yield { 'sha1': commit_sha1, 'component': component, 'title': title.strip(), 'tickets': re.findall(r'\s(#\d+)', message), 'paragraphs': [ (label, remove_ticket_directives(message)) for label, message in paragraphs ], }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def release(obj, commit='HEAD', components=False): """Generate release notes."""
options = obj.options repository = obj.repository try: sha = 'oid' commits = _pygit2_commits(commit, repository) except ImportError: try: sha = 'hexsha' commits = _git_commits(commit, repository) except ImportError: click.echo('To use this feature, please install pygit2. ' 'GitPython will also work but is not recommended ' '(python <= 2.7 only).', file=sys.stderr) return 2 messages = OrderedDict([(getattr(c, sha), c.message) for c in commits]) for commit_sha1 in amended_commits(messages): if commit_sha1 in messages: del messages[commit_sha1] full_messages = list( enrich_git_log_dict(messages, options.get('commit_msg_labels')) ) indent = ' ' if components else '' wrapper = textwrap.TextWrapper( width=70, initial_indent=indent + '- ', subsequent_indent=indent + ' ', ) for label, section in options.get('commit_msg_labels'): if section is None: continue bullets = [] for commit in full_messages: bullets += [ {'text': bullet, 'component': commit['component']} for lbl, bullet in commit['paragraphs'] if lbl == label and bullet is not None ] if len(bullets) > 0: click.echo(section) click.echo('~' * len(section)) click.echo() if components: def key(cmt): return cmt['component'] for component, bullets in itertools.groupby( sorted(bullets, key=key), key): bullets = list(bullets) if len(bullets) > 0: click.echo('+ {}'.format(component)) click.echo() for bullet in bullets: click.echo(wrapper.fill(bullet['text'])) click.echo() else: for bullet in bullets: click.echo(wrapper.fill(bullet['text'])) click.echo() return 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 redirect(view=None, url=None, **kwargs): """Redirects to the specified view or url """
if view: if url: kwargs["url"] = url url = flask.url_for(view, **kwargs) current_context.exit(flask.redirect(url))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def statsd_metric(name, count, elapsed): """Metric that records to statsd & graphite"""
with statsd.pipeline() as pipe: pipe.incr(name, count) pipe.timing(name, int(round(1000 * elapsed)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compile_file(env, src_path, dst_path, encoding='utf-8', base_dir=''): """Compiles a Jinja2 template to python code. :param env: a Jinja2 Environment instance. :param src_path: path to the source file. :param dst_path: path to the destination file. :param encoding: template encoding. :param base_dir: the base path to be removed from the compiled template filename. """
src_file = file(src_path, 'r') source = src_file.read().decode(encoding) name = src_path.replace(base_dir, '') raw = env.compile(source, name=name, filename=name, raw=True) src_file.close() dst_file = open(dst_path, 'w') dst_file.write(raw) dst_file.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 _pre_dump(cls): """Output all recorded stats"""
shutil.rmtree(cls.outdir, ignore_errors=True) os.makedirs(cls.outdir) super(PlotMetric, cls)._pre_dump()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _histogram(self, which, mu, sigma, data): """plot a histogram. For internal use only"""
weights = np.ones_like(data)/len(data) # make bar heights sum to 100% n, bins, patches = plt.hist(data, bins=25, weights=weights, facecolor='blue', alpha=0.5) plt.title(r'%s %s: $\mu=%.2f$, $\sigma=%.2f$' % (self.name, which.capitalize(), mu, sigma)) plt.xlabel('Items' if which == 'count' else 'Seconds') plt.ylabel('Frequency') plt.gca().yaxis.set_major_formatter(FuncFormatter(lambda y, position: "{:.1f}%".format(y*100)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _scatter(self): """plot a scatter plot of count vs. elapsed. For internal use only"""
plt.scatter(self.count_arr, self.elapsed_arr) plt.title('{}: Count vs. Elapsed'.format(self.name)) plt.xlabel('Items') plt.ylabel('Seconds')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bind(self, __fun, *args, **kwargs): """ Bind a worker function to the future. This worker function will be executed when the future is executed. """
with self._lock: if self._running or self._completed or self._cancelled: raise RuntimeError('Future object can not be reused') if self._worker: raise RuntimeError('Future object is already bound') self._worker = functools.partial(__fun, *args, **kwargs) return 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 set_result(self, result): """ Allows you to set the result of the future without requiring the future to actually be executed. This can be used if the result is available before the future is run, allowing you to keep the future as the interface for retrieving the result data. :param result: The result of the future. :raise RuntimeError: If the future is already enqueued. """
with self._lock: if self._enqueued: raise RuntimeError('can not set result of enqueued Future') self._result = result self._completed = True callbacks = self._prepare_done_callbacks() callbacks()
<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_exception(self, exc_info): """ This method allows you to set an exception in the future without requring that exception to be raised from the futures worker. This method can be called on an unbound future. :param exc_info: Either an exception info tuple or an exception value. In the latter case, the traceback will be automatically generated from the parent frame. :raise RuntimeError: If the future is already enqueued. """
if not isinstance(exc_info, tuple): if not isinstance(exc_info, BaseException): raise TypeError('expected BaseException instance') try: # TODO: Filld the traceback so it appears as if the exception # was actually raised by the caller? (Not sure if possible) raise exc_info except: exc_info = sys.exc_info() exc_info = (exc_info[0], exc_info[1], exc_info[2]) with self._lock: if self._enqueued: raise RuntimeError('can not set exception of enqueued Future') self._exc_info = exc_info self._completed = True callbacks = self._prepare_done_callbacks() callbacks()
<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(self, future): """ Enqueue a future to be processed by one of the threads in the pool. The future must be bound to a worker and not have been started yet. """
future.enqueue() with self._lock: if self._shutdown: raise RuntimeError('ThreadPool has been shut down and can no ' 'longer accept futures.') self._queue.append(future) if len(self._running) == len(self._workers): self._new_worker() self._lock.notify_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 submit(self, __fun, *args, **kwargs): """ Creates a new future and enqueues it. Returns the future. """
future = Future().bind(__fun, *args, **kwargs) self.enqueue(future) return future
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def timeit(func): """ Returns the number of seconds that a function took along with the result """
@wraps(func) def timer_wrapper(*args, **kwargs): """ Inner function that uses the Timer context object """ with Timer() as timer: result = func(*args, **kwargs) return result, timer return timer_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 timeout(seconds): """ Raises a TimeoutError if a function does not terminate within specified seconds. """
def _timeout_error(signal, frame): raise TimeoutError("Operation did not finish within \ {} seconds".format(seconds)) def timeout_decorator(func): @wraps(func) def timeout_wrapper(*args, **kwargs): signal.signal(signal.SIGALRM, _timeout_error) signal.alarm(seconds) try: return func(*args, **kwargs) finally: signal.alarm(0) return timeout_wrapper return timeout_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 create_persisted_object(self, location: str, logger: Logger) -> PersistedObject: """ Creates a PersistedObject representing the object at location 'location', and recursively creates all of its children :param location: :param logger: :return: """
#print('Checking all files under ' + location) logger.debug('Checking all files under [{loc}]'.format(loc=location)) obj = FileMappingConfiguration.RecursivePersistedObject(location=location, file_mapping_conf=self, logger=logger) #print('File checks done') logger.debug('File checks done') 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_multifile_object_without_children(self, location: str) -> bool: """ Returns True if an item with this location is present as a multifile object without children. For this implementation, this means that there is a folder without any files in it :param location: :return: """
return isdir(location) and len(self.find_multifile_object_children(location)) == 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 get_multifile_object_child_location(self, parent_item_prefix: str, child_name: str) -> str: """ Implementation of the parent abstract method. In this mode the attribute is a file inside the parent object folder :param parent_item_prefix: the absolute file prefix of the parent item. :return: the file prefix for this attribute """
check_var(parent_item_prefix, var_types=str, var_name='parent_item_prefix') check_var(child_name, var_types=str, var_name='item_name') # assert that folder_path is a folder if not isdir(parent_item_prefix): raise ValueError( 'Cannot get attribute item in non-flat mode, parent item path is not a folder : ' + parent_item_prefix) return join(parent_item_prefix, child_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 is_multifile_object_without_children(self, location: str) -> bool: """ Returns True if an item with this location is present as a multifile object without children. For this implementation, this means that there is a file with the appropriate name but without extension :param location: :return: """
# (1) Find the base directory and base name if isdir(location): # special case: parent location is the root folder where all the files are. return len(self.find_multifile_object_children(location)) == 0 else: # TODO same comment than in find_multifile_object_children if exists(location): # location is a file without extension. We can accept that as being a multifile object without children return True else: 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 special_links_replace(text, urls): ''' Replace simplified Regulations and Guidelines links into actual links. 'urls' dictionary is expected to provide actual links to the targeted Regulations and Guidelines, as well as to the PDF file. ''' match_number = r'([A-Za-z0-9]+)' + r'(\+*)' reference_list = [(r'regulations:article:' + match_number, urls['regulations']), (r'regulations:regulation:' + match_number, urls['regulations']), (r'guidelines:article:' + match_number, urls['guidelines']), (r'guidelines:guideline:' + match_number, urls['guidelines']), ] anchor_list = [(r'regulations:contents', urls['regulations'] + r'#contents'), (r'guidelines:contents', urls['guidelines'] + r'#contents'), (r'regulations:top', urls['regulations'] + r'#'), (r'guidelines:top', urls['guidelines'] + r'#'), (r'link:pdf', urls['pdf'] + '.pdf'), ] retval = text for match, repl in reference_list: retval = re.sub(match, repl + r'#\1\2', retval) for match, repl in anchor_list: retval = re.sub(match, repl, retval) return retval
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def link2html(text): ''' Turns md links to html ''' match = r'\[([^\]]+)\]\(([^)]+)\)' replace = r'<a href="\2">\1</a>' return re.sub(match, replace, 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 simple_md2html(text, urls): ''' Convert a text from md to html ''' retval = special_links_replace(text, urls) # Create a par break for double newlines retval = re.sub(r'\n\n', r'</p><p>', retval) # Create a visual br for every new line retval = re.sub(r'\n', r'<br />\n', retval) # Do we really need this ? Help reduce the diff to only '\n' diff. retval = re.sub(r'"', r'&quot;', retval) retval = list2html(retval) return link2html(retval)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def generate_ul(self, a_list): ''' Determines if we should generate th 'ul' around the list 'a_list' ''' return len(a_list) > 0 and (isinstance(a_list[0], Rule) or isinstance(a_list[0], LabelDecl))
<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_version_info(): """Extract version information as a dictionary from version.py."""
version_info = {} with open(os.path.join("refcycle", "version.py"), 'r') as f: version_code = compile(f.read(), "version.py", 'exec') exec(version_code, version_info) return version_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 div_filter(key: str, value: list, format: str, meta: Any) -> Optional[list]: """Filter the JSON ``value`` for alert divs. Arguments --------- key Key of the structure value Values in the structure format Output format of the processing meta Meta information """
if key != "Div" or format != "latex": return None [[_, classes, _], contents] = value try: alert_type = [name.split("-")[1] for name in classes if "-" in name][0] except IndexError: return None if alert_type not in ALLOWED_ALERT_TYPES.__members__: return None filtered = [RawBlock("latex", rf"\begin{{{alert_type}box}}")] filtered.extend(contents) filtered.append(RawBlock("latex", rf"\end{{{alert_type}box}}")) return filtered
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_div(text: str, format: Optional[str] = None) -> "applyJSONFilters": """Apply the `dev_filter` action to the text."""
return applyJSONFilters([div_filter], text, format=format)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def raw_html_filter(key: str, value: list, format: str, meta: Any) -> Optional[list]: """Filter the JSON ``value`` for raw html to convert to LaTeX. Arguments --------- key Key of the structure value Values in the structure format Output format of the processing meta Meta information """
if key == "RawInline" and format == "latex" and value[0] == "html": if value[1] == "<sup>": filtered = [RawInline("latex", r"\textsuperscript{")] elif value[1] == "</sup>": filtered = [RawInline("latex", "}")] elif value[1] == "<sub>": filtered = [RawInline("latex", r"\textsubscript{")] elif value[1] == "</sub>": filtered = [RawInline("latex", "}")] else: return None return filtered 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 convert_raw_html(text: str, format: Optional[str] = None) -> "applyJSONFilters": """Apply the `raw_html_filter` action to the text."""
return applyJSONFilters([raw_html_filter], text, format=format)
<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, element): """Add an element to this set."""
key = self._transform(element) if key not in self._elements: self._elements[key] = element
<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_items_to_message(msg, log_dict): """Utility function to add dictionary items to a log message."""
out = msg for key, value in log_dict.items(): out += " {}={}".format(key, value) 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 metric(cls, name, count, elapsed): """A metric function that writes multiple CSV files :arg str name: name of the metric :arg int count: number of items :arg float elapsed: time in seconds """
if name is None: warnings.warn("Ignoring unnamed metric", stacklevel=3) return with cls.lock: if not cls.instances: # first call shutil.rmtree(cls.outdir, ignore_errors=True) os.makedirs(cls.outdir) if cls.dump_atexit: atexit.register(cls.dump) try: self = cls.instances[name] except KeyError: self = cls.instances[name] = cls(name) self.writer.writerow((count, "%f"%elapsed))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def metric(self, name, count, elapsed): """A metric function that writes a single CSV file :arg str name: name of the metric :arg int count: number of items :arg float elapsed: time in seconds """
if name is None: warnings.warn("Ignoring unnamed metric", stacklevel=3) return with self.lock: self.writer.writerow((name, count, "%f"%elapsed))
<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(parts): """ Build an absolute path from parts array and and return the contents of the resulting file. Assume UTF-8 encoding. """
cur_dir = os.path.abspath(os.path.dirname(__file__)) with codecs.open(os.path.join(cur_dir, *parts), "rb", "utf-8") as f: return f.read()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ensure_clean_git(operation='operation'): """ Verify that git has no uncommitted changes """
if os.system('git diff-index --quiet HEAD --'): print("Unstaged or uncommitted changes detected. {} aborted.".format( operation.capitalize())) sys.exit()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hasmethod(obj, meth): """ Checks if an object, obj, has a callable method, meth return True or False """
if hasattr(obj, meth): return callable(getattr(obj,meth)) 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 hasvar(obj, var): """ Checks if object, obj has a variable var return True or False """
if hasattr(obj, var): return not callable(getattr(obj, var)) 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 getmethattr(obj, meth): """ Returns either the variable value or method invocation """
if hasmethod(obj, meth): return getattr(obj, meth)() elif hasvar(obj, meth): return getattr(obj, meth) 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 assure_obj_child_dict(obj, var): """Assure the object has the specified child dict """
if not var in obj or type(obj[var]) != type({}): obj[var] = {} 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 warmup(f): """ Decorator to run warmup before running a command """
@wraps(f) def wrapped(self, *args, **kwargs): if not self.warmed_up: self.warmup() return f(self, *args, **kwargs) return wrapped
<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_required(f): """ Return an exception if the namespace is not already installed """
@wraps(f) def wrapped(self, *args, **kwargs): if self.directory.new: raise SprinterException("Namespace %s is not yet installed!" % self.namespace) return f(self, *args, **kwargs) return wrapped
<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(self): """ Install the environment """
self.phase = PHASE.INSTALL if not self.directory.new: self.logger.info("Namespace %s directory already exists!" % self.namespace) self.source = load_manifest(self.directory.manifest_path) return self.update() try: self.logger.info("Installing environment %s..." % self.namespace) self.directory.initialize() self.install_sandboxes() self.instantiate_features() self.grab_inputs() self._specialize() for feature in self.features.run_order: self.run_action(feature, 'sync') self.inject_environment_config() self._finalize() except Exception: self.logger.debug("", exc_info=sys.exc_info()) self.logger.info("An error occured during installation!") if not self.ignore_errors: self.clear_all() self.logger.info("Removing installation %s..." % self.namespace) self.directory.remove() et, ei, tb = sys.exc_info() reraise(et, ei, tb)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, reconfigure=False): """ update the environment """
try: self.phase = PHASE.UPDATE self.logger.info("Updating environment %s..." % self.namespace) self.install_sandboxes() self.instantiate_features() # We don't grab inputs, only on install # updates inputs are grabbed on demand # self.grab_inputs(reconfigure=reconfigure) if reconfigure: self.grab_inputs(reconfigure=True) else: self._copy_source_to_target() self._specialize(reconfigure=reconfigure) for feature in self.features.run_order: self.run_action(feature, 'sync') self.inject_environment_config() self._finalize() except Exception: self.logger.debug("", exc_info=sys.exc_info()) et, ei, tb = sys.exc_info() reraise(et, ei, tb)
<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(self): """ remove the environment """
try: self.phase = PHASE.REMOVE self.logger.info("Removing environment %s..." % self.namespace) self.instantiate_features() self._specialize() for feature in self.features.run_order: try: self.run_action(feature, 'sync') except FormulaException: # continue trying to remove any remaining features. pass self.clear_all() self.directory.remove() self.injections.commit() if self.error_occured: self.logger.error(warning_template) self.logger.error(REMOVE_WARNING) except Exception: self.logger.debug("", exc_info=sys.exc_info()) et, ei, tb = sys.exc_info() reraise(et, ei, tb)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deactivate(self): """ deactivate the environment """
try: self.phase = PHASE.DEACTIVATE self.logger.info("Deactivating environment %s..." % self.namespace) self.directory.rewrite_config = False self.instantiate_features() self._specialize() for feature in self.features.run_order: self.logger.info("Deactivating %s..." % feature[0]) self.run_action(feature, 'deactivate') self.clear_all() self._finalize() except Exception: self.logger.debug("", exc_info=sys.exc_info()) et, ei, tb = sys.exc_info() reraise(et, ei, tb)
<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): """ Validate the target environment """
self.phase = PHASE.VALIDATE self.logger.info("Validating %s..." % self.namespace) self.instantiate_features() context_dict = {} if self.target: for s in self.target.formula_sections(): context_dict["%s:root_dir" % s] = self.directory.install_directory(s) context_dict['config:root_dir'] = self.directory.root_dir context_dict['config:node'] = system.NODE self.target.add_additional_context(context_dict) for feature in self.features.run_order: self.run_action(feature, 'validate', run_if_error=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 clear_all(self): """ clear all files that were to be injected """
self.injections.clear_all() for config_file in CONFIG_FILES: self.injections.clear(os.path.join("~", config_file))