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 schedule(demand: dict, alterations: set, looped: set=None, altered: set=None): """Prioritizes Triggers called from outside."""
if looped is not None and len(demand) != len(looped): for func in looped: del demand[func] if keep_temp in demand: demand.pop(increase_temp, None) demand.pop(lower_temp, None) elif lower_temp in demand: demand.pop(increase_temp, None) return demand, alterations
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def d(msg, *args, **kwargs): ''' log a message at debug level; ''' return logging.log(DEBUG, msg, *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 v(msg, *args, **kwargs): ''' log a message at verbose level; ''' return logging.log(VERBOSE, msg, *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 i(msg, *args, **kwargs): ''' log a message at info level; ''' return logging.log(INFO, msg, *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 w(msg, *args, **kwargs): ''' log a message at warn level; ''' return logging.log(WARN, msg, *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 e(msg, *args, **kwargs): ''' log a message at error level; ''' return logging.log(ERROR, msg, *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 getLogger(name=None): ''' return a logger instrumented with additional 1-letter logging methods; ''' logger = logging.getLogger(name=name) if not hasattr(logger, 'd'): def d(self, msg, *args, **kwargs): return self.log(DEBUG, msg, *args, **kwargs) logger.d = types.MethodType(d, logger) if not hasattr(logger, 'v'): def v(self, msg, *args, **kwargs): return self.log(VERBOSE, msg, *args, **kwargs) logger.v = types.MethodType(v, logger) if not hasattr(logger, 'i'): def i(self, msg, *args, **kwargs): return self.log(INFO, msg, *args, **kwargs) logger.i = types.MethodType(i, logger) if not hasattr(logger, 'w'): def w(self, msg, *args, **kwargs): return self.log(WARN, msg, *args, **kwargs) logger.w = types.MethodType(w, logger) if not hasattr(logger, 'e'): def e(self, msg, *args, **kwargs): return self.log(ERROR, msg, *args, **kwargs) logger.e = types.MethodType(e, logger) return 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 create_instances(configuration): """Create necessary class instances from a configuration with no argument to the constructor :param dict configuration: configuration dict like in :attr:`~pyextdirect.configuration.Base.configuration` :return: a class-instance mapping :rtype: dict """
instances = {} for methods in configuration.itervalues(): for element in methods.itervalues(): if not isinstance(element, tuple): continue cls, _ = element if cls not in instances: instances[cls] = cls() return 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 call(self, request): """Call the appropriate function :param dict request: request that describes the function to call :return: response linked to the request that holds the value returned by the called function :rtype: dict """
result = None try: if 'extAction' in request: # DirectSubmit method tid = request['extTID'] action = request['extAction'] method = request['extMethod'] else: tid = request['tid'] action = request['action'] method = request['method'] element = self.configuration[action][method] if isinstance(element, tuple): # class level function func = getattr(self.instances[element[0]], element[1]) else: # module level function func = element if func.exposed_kind == BASIC: # basic method args = request['data'] or [] result = func(*args) elif func.exposed_kind == LOAD: # DirectLoad method args = request['data'] or [] result = {'success': True, 'data': func(*args)} elif func.exposed_kind == SUBMIT: # DirectSubmit method kwargs = request for k in ['extAction', 'extMethod', 'extType', 'extTID', 'extUpload']: if k in kwargs: del kwargs[k] try: func(**kwargs) result = {'success': True} except FormError as e: result = e.extra result['success'] = False if e.errors: result['errors'] = e.errors elif func.exposed_kind == STORE_READ: # DirectStore read method kwargs = request['data'] or {} data = func(**kwargs) result = {'total': len(data), 'data': data} elif func.exposed_kind == STORE_CUD: # DirectStore create-update-destroy methods kwargs = request['data'][0] or {} try: result = {'success': True, 'data': func(**kwargs)} except Error: result = {'success': False} except Exception as e: if self.debug: return {'type': 'exception', 'message': str(e), 'where': '%s.%s' % (action, method)} return {'type': 'rpc', 'tid': tid, 'action': action, 'method': method, 'result': 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 url_to_filename(url): """ Safely translate url to relative filename Args: url (str): A target url string Returns: str """
# remove leading/trailing slash if url.startswith('/'): url = url[1:] if url.endswith('/'): url = url[:-1] # remove pardir symbols to prevent unwilling filesystem access url = remove_pardir_symbols(url) # replace dots to underscore in filename part url = replace_dots_to_underscores_at_last(url) return url
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_pardir_symbols(path, sep=os.sep, pardir=os.pardir): """ Remove relative path symobls such as '..' Args: path (str): A target path string sep (str): A strint to refer path delimiter (Default: `os.sep`) pardir (str): A string to refer parent directory (Default: `os.pardir`) Returns: str """
bits = path.split(sep) bits = (x for x in bits if x != pardir) return sep.join(bits)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _load(root): """Load from an xml.etree.ElementTree"""
types = _load_types(root) enums = _load_enums(root) commands = _load_commands(root) features = _load_features(root) extensions = _load_extensions(root) return Registry(None, types, enums, commands, features, extensions)
<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_type(dest, src, name, api=None, filter_symbol=None): """Import Type `name` and its dependencies from Registry `src` to Registry `dest`. :param Registry dest: Destination Registry :param Registry src: Source Registry :param str name: Name of type to import :param str api: Prefer to import Types with api Name `api`, or None to import Types with no api name. :param filter_symbol: Optional filter callable :type filter_symbol: Callable with signature ``(symbol_type:str, symbol_name:str) -> bool`` """
if not filter_symbol: filter_symbol = _default_filter_symbol type = src.get_type(name, api) for x in type.required_types: if not filter_symbol('type', x): continue import_type(dest, src, x, api, filter_symbol) dest.types[(type.name, type.api)] = type
<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_command(dest, src, name, api=None, filter_symbol=None): """Import Command `name` and its dependencies from Registry `src` to Registry `dest` :param Registry dest: Destination Registry :param Registry src: Source Registry :param str name: Name of Command to import :param str api: Prefer to import Types with api name `api`, or None to import Types with no api name :param filter_symbol: Optional filter callable :type filter_symbol: Callable with signature ``(symbol_type:str, symbol_name:str) -> bool`` """
if not filter_symbol: filter_symbol = _default_filter_symbol cmd = src.commands[name] for x in cmd.required_types: if not filter_symbol('type', x): continue import_type(dest, src, x, api, filter_symbol) dest.commands[name] = cmd
<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_enum(dest, src, name): """Import Enum `name` from Registry `src` to Registry `dest`. :param Registry dest: Destination Registry :param Registry src: Source Registry :param str name: Name of Enum to import """
dest.enums[name] = src.enums[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 import_feature(dest, src, name, api=None, profile=None, filter_symbol=None): """Imports Feature `name`, and all its dependencies, from Registry `src` to Registry `dest`. :param Registry dest: Destination Registry :param Registry src: Source Registry :param str name: Name of Feature to import :param str api: Prefer to import dependencies with api name `api`, or None to import dependencies with no API name. :param str profile: Import dependencies with profile name `profile`, or None to import all dependencies. :param filter_symbol: Optional symbol filter callable :type filter_symbol: Callable with signature ``(symbol_type:str, symbol_name:str) -> bool`` """
if filter_symbol is None: filter_symbol = _default_filter_symbol ft = src.features[name] if isinstance(name, str) else name # Gather symbols to remove from Feature remove_symbols = set() for x in src.get_removes(api, profile): remove_symbols.update(x.as_symbols()) def my_filter_symbol(t, name): return False if (t, name) in remove_symbols else filter_symbol(t, name) for req in ft.get_requires(profile): for x in req.types: if not my_filter_symbol('type', x): continue import_type(dest, src, x, api, filter_symbol) for x in req.enums: if not my_filter_symbol('enum', x): continue import_enum(dest, src, x) for x in req.commands: if not my_filter_symbol('command', x): continue import_command(dest, src, x, api, filter_symbol) dest.features[name] = ft
<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_extension(dest, src, name, api=None, profile=None, filter_symbol=None): """Imports Extension `name`, and all its dependencies. :param Registry dest: Destination Registry :param Registry src: Source Registry :param str name: Name of Extension to import :param str api: Prefer to import types with API name `api`, or None to prefer Types with no API name. :type api: str :param filter_symbol: Optional symbol filter callable :type filter_symbol: Callable with signature ``(symbol_type:str, symbol_name:str) -> bool`` """
if filter_symbol is None: filter_symbol = _default_filter_symbol ext = src.extensions[name] if isinstance(name, str) else name for req in ext.get_requires(api, profile): for x in req.types: if not filter_symbol('type', x): continue import_type(dest, src, x, api, filter_symbol) for x in req.enums: if not filter_symbol('enum', x): continue import_enum(dest, src, x) for x in req.commands: if not filter_symbol('command', x): continue import_command(dest, src, x, api, filter_symbol) dest.extensions[name] = ext
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_registry(dest, src, api=None, profile=None, support=None, filter_symbol=None): """Imports all features and extensions and all their dependencies. :param Registry dest: Destination API :param Registry src: Source Registry :param str api: Only import Features with API name `api`, or None to import all features. :param str profile: Only import Features with profile name `profile`, or None to import all features. :param str support: Only import Extensions with this extension support string, or None to import all extensions. :param filter_symbol: Optional symbol filter callable :type filter_symbol: Callable with signature ``(symbol_type:str, symbol_name:str) -> bool`` """
if filter_symbol is None: filter_symbol = _default_filter_symbol for x in src.get_features(api): import_feature(dest, src, x.name, api, profile, filter_symbol) for x in src.get_extensions(support): import_extension(dest, src, x.name, api, profile, filter_symbol)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extension_sort_key(extension): """Returns the sorting key for an extension. The sorting key can be used to sort a list of extensions into the order that is used in the Khronos C OpenGL headers. :param Extension extension: Extension to produce sort key for :returns: A sorting key """
name = extension.name category = name.split('_', 2)[1] return (0, name) if category in ('ARB', 'KHR', 'OES') else (1, 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 group_apis(reg, features=None, extensions=None, api=None, profile=None, support=None): """Groups Types, Enums, Commands with their respective Features, Extensions Similar to :py:func:`import_registry`, but generates a new Registry object for every feature or extension. :param Registry reg: Input registry :param features: Feature names to import, or None to import all. :type features: Iterable of strs :param extensions: Extension names to import, or None to import all. :type extensions: Iterable of strs :param str profile: Import features which belong in `profile`, or None to import all. :param str api: Import features which belong in `api`, or None to import all. :param str support: Import extensions which belong in this extension support string, or None to import all. :returns: list of :py:class:`Registry` objects """
features = (reg.get_features(api) if features is None else [reg.features[x] for x in features]) if extensions is None: extensions = sorted(reg.get_extensions(support), key=extension_sort_key) else: extensions = [reg.extensions[x] for x in extensions] output_symbols = set() def filter_symbol(type, name): k = (type, name) if k in output_symbols: return False else: output_symbols.add(k) return True out_apis = [] for x in features: out = Registry(x.name) import_feature(out, reg, x.name, api, profile, filter_symbol) out_apis.append(out) for x in extensions: out = Registry(x.name) import_extension(out, reg, x.name, api, profile, filter_symbol) out_apis.append(out) return out_apis
<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(args=None, prog=None): """Generates a C header file"""
args = args if args is not None else sys.argv[1:] prog = prog if prog is not None else sys.argv[0] # Prevent broken pipe exception from being raised. signal.signal(signal.SIGPIPE, signal.SIG_DFL) stdin = sys.stdin.buffer if hasattr(sys.stdin, 'buffer') else sys.stdin p = argparse.ArgumentParser(prog=prog) p.add_argument('-o', '--output', metavar='PATH', type=argparse.FileType('w'), default=sys.stdout, help='Write output to PATH') p.add_argument('--api', help='Match API', default=None) p.add_argument('--profile', help='Match profile', default=None) p.add_argument('--support', default=None, help='Match extension support string') g = p.add_mutually_exclusive_group() g.add_argument('--list-apis', action='store_true', dest='list_apis', help='List apis in registry', default=False) g.add_argument('--list-profiles', action='store_true', default=False, dest='list_profiles', help='List profiles in registry') g.add_argument('--list-supports', action='store_true', dest='list_supports', default=False, help='List extension support strings') p.add_argument('registry', type=argparse.FileType('rb'), nargs='?', default=stdin, help='Registry path') args = p.parse_args(args) o = args.output try: registry = load(args.registry) if args.list_apis: for x in sorted(registry.get_apis()): print(x, file=o) return 0 elif args.list_profiles: for x in sorted(registry.get_profiles()): print(x, file=o) return 0 elif args.list_supports: for x in sorted(registry.get_supports()): print(x, file=o) return 0 apis = group_apis(registry, None, None, args.api, args.profile, args.support) for api in apis: print('#ifndef', api.name, file=o) print('#define', api.name, file=o) print(api.text, file=o) print('#endif', file=o) print('', file=o) except: e = sys.exc_info()[1] print(prog, ': error: ', e, sep='', file=sys.stderr) return 1 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 required_types(self): """Set of names of types which the Command depends on. """
required_types = set(x.type for x in self.params) required_types.add(self.type) required_types.discard(None) return required_types
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def proto_text(self): """Formatted Command identifier. Equivalent to ``self.proto_template.format(type=self.type, name=self.name)``. """
return self.proto_template.format(type=self.type, name=self.name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def text(self): """Formatted Command declaration. This is the C declaration for the command. """
params = ', '.join(x.text for x in self.params) return '{0} ({1})'.format(self.proto_text, params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def text(self): """Formatted param definition Equivalent to ``self.template.format(name=self.name, type=self.type)``. """
return self.template.format(name=self.name, type=self.type)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_symbols(self): """Set of symbols required by this Require :return: set of ``(symbol type, symbol name)`` tuples """
out = set() for name in self.types: out.add(('type', name)) for name in self.enums: out.add(('enum', name)) for name in self.commands: out.add(('command', name)) 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 get_profiles(self): """Returns set of profile names referenced in this Feature :returns: set of profile names """
out = set(x.profile for x in self.requires if x.profile) out.update(x.profile for x in self.removes if x.profile) 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 get_requires(self, profile=None): """Get filtered list of Require objects in this Feature :param str profile: Return Require objects with this profile or None to return all Require objects. :return: list of Require objects """
out = [] for req in self.requires: # Filter Require by profile if ((req.profile and not profile) or (req.profile and profile and req.profile != profile)): continue out.append(req) 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 get_removes(self, profile=None): """Get filtered list of Remove objects in this Feature :param str profile: Return Remove objects with this profile or None to return all Remove objects. :return: list of Remove objects """
out = [] for rem in self.removes: # Filter Remove by profile if ((rem.profile and not profile) or (rem.profile and profile and rem.profile != profile)): continue out.append(rem) 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 get_apis(self): """Returns set of api names referenced in this Extension :return: set of api name strings """
out = set() out.update(x.api for x in self.requires if x.api) 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 get_profiles(self): """Returns set of profile names referenced in this Extension :return: set of profile name strings """
return set(x.profile for x in self.requires if x.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 get_requires(self, api=None, profile=None): """Return filtered list of Require objects in this Extension :param str api: Return Require objects with this api name or None to return all Require objects. :param str profile: Return Require objects with this profile or None to return all Require objects. :return: list of Require objects """
out = [] for req in self.requires: # Filter Remove by API if (req.api and not api) or (req.api and api and req.api != api): continue # Filter Remove by profile if ((req.profile and not profile) or (req.profile and profile and req.profile != profile)): continue out.append(req) 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 text(self): """Formatted API declarations. Equivalent to the concatenation of `text` attributes of types, enums and commands in this Registry. """
out = [] out.extend(x.text for x in self.types.values()) out.extend(x.text for x in self.enums.values()) out.extend('extern {0};'.format(x.text) for x in self.commands.values()) return '\n'.join(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 get_type(self, name, api=None): """Returns Type `name`, with preference for the Type of `api`. :param str name: Type name :param str api: api name to prefer, of None to prefer types with no api name :return: Type object """
k = (name, api) if k in self.types: return self.types[k] else: return self.types[(name, 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 get_features(self, api=None): """Returns filtered list of features in this registry :param str api: Return only features with this api name, or None to return all features. :return: list of Feature objects """
return [x for x in self.features.values() if api and x.api == api or not 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 get_extensions(self, support=None): """Returns filtered list of extensions in this registry :param support: Return only extensions with this extension support string, or None to return all extensions. :return: list of Extension objects """
return [x for x in self.extensions.values() if support and support in x.supported or not support]
<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_requires(self, api=None, profile=None, support=None): """Returns filtered list of Require objects in this registry :param str api: Return Require objects with this api name or None to return all Require objects. :param str profile: Return Require objects with this profile or None to return all Require objects. :param str support: Return Require objects with this extension support string or None to return all Require objects. :return: list of Require objects """
out = [] for ft in self.get_features(api): out.extend(ft.get_requires(profile)) for ext in self.extensions.values(): # Filter extension support if support and support not in ext.supported: continue out.extend(ext.get_requires(api, profile)) 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 get_removes(self, api=None, profile=None): """Returns filtered list of Remove objects in this registry :param str api: Return Remove objects with this api name or None to return all Remove objects. :param str profile: Return Remove objects with this profile or None to return all Remove objects. :return: list of Remove objects """
out = [] for ft in self.get_features(api): out.extend(ft.get_removes(profile)) 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 get_apis(self): """Returns set of api names referenced in this Registry :return: set of api name strings """
out = set(x.api for x in self.types.values() if x.api) for ft in self.features.values(): out.update(ft.get_apis()) for ext in self.extensions.values(): out.update(ext.get_apis()) 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 get_profiles(self): """Returns set of profile names referenced in this Registry :return: set of profile name strings """
out = set() for ft in self.features.values(): out.update(ft.get_profiles()) for ext in self.extensions.values(): out.update(ext.get_profiles()) 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 get_supports(self): """Returns set of extension support strings referenced in this Registry :return: set of extension support strings """
out = set() for ext in self.extensions.values(): out.update(ext.get_supports()) 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 get_open_window_names(): ''' Return a dict with open program names and their corresponding decimal ids ''' raw_names = subprocess.check_output(['wmctrl', '-l']).decode('utf8').split('\n') split_names = [name.split() for name in raw_names if name] name_dict = {} for name in split_names: if not int(name[1]): name_dict[' '.join(name[3:]).lower()] = name[0] return name_dict
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resource_row_set(package, resource): """ Generate an iterator over all the rows in this resource's source data. """
# This is a work-around because messytables hangs on boto file # handles, so we're doing it via plain old HTTP. table_set = any_tableset(resource.fh(), extension=resource.meta.get('extension'), mimetype=resource.meta.get('mime_type')) tables = list(table_set.tables) if not len(tables): log.error("No tables were found in the source file.") return row_set = tables[0] offset, headers = headers_guess(row_set.sample) row_set.register_processor(headers_processor(headers)) row_set.register_processor(offset_processor(offset + 1)) types = type_guess(row_set.sample, strict=True) row_set.register_processor(types_processor(types)) return row_set
<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_alias(cell, names): """ Generate a normalized version of the column name. """
column = slugify(cell.column or '', sep='_') column = column.strip('_') column = 'column' if not len(column) else column name, i = column, 2 # de-dupe: column, column_2, column_3, ... while name in names: name = '%s_%s' % (name, i) i += 1 return 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 random_sample(value, field, row, num=10): """ Collect a random sample of the values in a particular field based on the reservoir sampling technique. """
# TODO: Could become a more general DQ piece. if value is None: field['has_nulls'] = True return if value in field['samples']: return if isinstance(value, basestring) and not len(value.strip()): field['has_empty'] = True return if len(field['samples']) < num: field['samples'].append(value) return j = random.randint(0, row) if j < (num - 1): field['samples'][j] = 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 make_unique_ngrams(s, n): """Make a set of unique n-grams from a string."""
return set(s[i:i + n] for i in range(len(s) - n + 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 check(self, s, instant_exact=True): """Check if a string is in the DB. :param s: str, string to check against the DB. :param instant_exact: bool, look up exact matches with a hash lookup. :return: True or False :rtype: bool """
all_sets = self._get_comparison_strings(s) if instant_exact and s in all_sets: # exact match return True for comparison_string in all_sets: if self.comparison_func(s, comparison_string) >= self.cutoff: 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 insert(self, seq): """ Populates the DB from a sequence of strings, ERASING PREVIOUS STATE. :param seq: an iterable """
# erase previous elements and make defaultdict for easier insertion. self._els_idxed = defaultdict(lambda: defaultdict(set)) if type(seq) is str: raise ValueError('Provided argument should be a sequence of strings' ', but not a string itself.') for el in seq: if type(el) is not str: raise ValueError('Element %s is not a string' % (el,)) for gram in make_unique_ngrams(el, self.idx_size): self._els_idxed[gram][len(el)].add(el) # convert defaultdict to dict so as to not increase size when checking # for presence of an element self._finalize_db()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _finalize_db(self): """Convert defaultdicts to regular dicts."""
for k, v in self._els_idxed.items(): self._els_idxed[k] = dict(v) self._els_idxed = dict(self._els_idxed)
<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_comparison_strings(self, s): """Find all similar strings"""
str_len = len(s) comparison_idxs = make_unique_ngrams(s, self.idx_size) min_len = len(s) - self.plus_minus if min_len < 0: min_len = 0 if self._els_idxed is None: raise UnintitializedError('Database not created') all_sets = set() for idx in comparison_idxs: found_idx = self._els_idxed.get(idx, None) if found_idx is None: continue for i in range(min_len, str_len + self.plus_minus): found_len = found_idx.get(i, None) if found_len is not None: all_sets = all_sets.union(found_len) return all_sets
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _load_methods(package): """Loads the mappings from method call result to analysis. Args: package (str): name of the package to load for. """
global _methods _methods[package] = None from acorn.config import settings from acorn.logging.descriptors import _obj_getattr spack = settings(package) if spack is not None: if spack.has_section("analysis.methods"): _methods[package] = {} from importlib import import_module mappings = dict(spack.items("analysis.methods")) for fqdn, target in mappings.items(): rootname = target.split('.')[0] root = import_module(rootname) caller = _obj_getattr(root, target) _methods[package][fqdn] = caller
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def analyze(fqdn, result, argl, argd): """Analyzes the result from calling the method with the specified FQDN. Args: fqdn (str): full-qualified name of the method that was called. result: result of calling the method with `fqdn`. argl (tuple): positional arguments passed to the method call. argd (dict): keyword arguments passed to the method call. """
package = fqdn.split('.')[0] if package not in _methods: _load_methods(package) if _methods[package] is not None and fqdn in _methods[package]: return _methods[package][fqdn](fqdn, result, *argl, **argd)
<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(station: str, txt: str) -> TafData: """ Returns TafData and Units dataclasses with parsed data and their associated units """
core.valid_station(station) while len(txt) > 3 and txt[:4] in ('TAF ', 'AMD ', 'COR '): txt = txt[4:] _, station, time = core.get_station_and_time(txt[:20].split(' ')) retwx = { 'end_time': None, 'raw': txt, 'remarks': None, 'start_time': None, 'station': station, 'time': core.make_timestamp(time) } txt = txt.replace(station, '') txt = txt.replace(time, '').strip() if core.uses_na_format(station): use_na = True units = Units(**NA_UNITS) # type: ignore else: use_na = False units = Units(**IN_UNITS) # type: ignore # Find and remove remarks txt, retwx['remarks'] = core.get_taf_remarks(txt) # Split and parse each line lines = core.split_taf(txt) parsed_lines = parse_lines(lines, units, use_na) # Perform additional info extract and corrections if parsed_lines: parsed_lines[-1]['other'], retwx['max_temp'], retwx['min_temp'] \ = core.get_temp_min_and_max(parsed_lines[-1]['other']) if not (retwx['max_temp'] or retwx['min_temp']): parsed_lines[0]['other'], retwx['max_temp'], retwx['min_temp'] \ = core.get_temp_min_and_max(parsed_lines[0]['other']) # Set start and end times based on the first line start, end = parsed_lines[0]['start_time'], parsed_lines[0]['end_time'] parsed_lines[0]['end_time'] = None retwx['start_time'], retwx['end_time'] = start, end parsed_lines = core.find_missing_taf_times(parsed_lines, start, end) parsed_lines = core.get_taf_flight_rules(parsed_lines) # Extract Oceania-specific data if retwx['station'][0] == 'A': # type: ignore parsed_lines[-1]['other'], retwx['alts'], retwx['temps'] \ = core.get_oceania_temp_and_alt(parsed_lines[-1]['other']) # Convert to dataclass retwx['forecast'] = [TafLineData(**line) for line in parsed_lines] # type: ignore return TafData(**retwx), units
<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_lines(lines: [str], units: Units, use_na: bool = True) -> [dict]: # type: ignore """ Returns a list of parsed line dictionaries """
parsed_lines = [] prob = '' while lines: raw_line = lines[0].strip() line = core.sanitize_line(raw_line) # Remove prob from the beginning of a line if line.startswith('PROB'): # Add standalone prob to next line if len(line) == 6: prob = line line = '' # Add to current line elif len(line) > 6: prob = line[:6] line = line[6:].strip() if line: parsed_line = (parse_na_line if use_na else parse_in_line)(line, units) for key in ('start_time', 'end_time'): parsed_line[key] = core.make_timestamp(parsed_line[key]) # type: ignore parsed_line['probability'] = core.make_number(prob[4:]) # type: ignore parsed_line['raw'] = raw_line parsed_line['sanitized'] = prob + ' ' + line if prob else line prob = '' parsed_lines.append(parsed_line) lines.pop(0) return parsed_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 parse_na_line(txt: str, units: Units) -> typing.Dict[str, str]: """ Parser for the North American TAF forcast varient """
retwx = {} wxdata = txt.split(' ') wxdata, _, retwx['wind_shear'] = core.sanitize_report_list(wxdata) wxdata, retwx['type'], retwx['start_time'], retwx['end_time'] = core.get_type_and_times(wxdata) wxdata, retwx['wind_direction'], retwx['wind_speed'], \ retwx['wind_gust'], _ = core.get_wind(wxdata, units) wxdata, retwx['visibility'] = core.get_visibility(wxdata, units) wxdata, retwx['clouds'] = core.get_clouds(wxdata) retwx['other'], retwx['altimeter'], retwx['icing'], retwx['turbulance'] \ = core.get_taf_alt_ice_turb(wxdata) return retwx
<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_in_line(txt: str, units: Units) -> typing.Dict[str, str]: """ Parser for the International TAF forcast varient """
retwx = {} wxdata = txt.split(' ') wxdata, _, retwx['wind_shear'] = core.sanitize_report_list(wxdata) wxdata, retwx['type'], retwx['start_time'], retwx['end_time'] = core.get_type_and_times(wxdata) wxdata, retwx['wind_direction'], retwx['wind_speed'], \ retwx['wind_gust'], _ = core.get_wind(wxdata, units) if 'CAVOK' in wxdata: retwx['visibility'] = core.make_number('CAVOK') retwx['clouds'] = [] wxdata.pop(wxdata.index('CAVOK')) else: wxdata, retwx['visibility'] = core.get_visibility(wxdata, units) wxdata, retwx['clouds'] = core.get_clouds(wxdata) retwx['other'], retwx['altimeter'], retwx['icing'], retwx['turbulance'] \ = core.get_taf_alt_ice_turb(wxdata) return retwx
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset(self): """ Fill the screen with black pixels """
surface = Surface(self.width, self.height) surface.fill(BLACK) self.matrix = surface.matrix
<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): """ Sends the current screen contents to Mate Light """
display_data = [] for y in range(self.height): for x in range(self.width): for color in self.matrix[x][y]: display_data.append(int(color)) checksum = bytearray([0, 0, 0, 0]) data_as_bytes = bytearray(display_data) data = data_as_bytes + checksum sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.sendto(data, (self.host, self.port))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def blit(self, surface, pos=(0, 0)): """ Blits a surface on the screen at pos :param surface: Surface to blit :param pos: Top left corner to start blitting :type surface: Surface :type pos: tuple """
for x in range(surface.width): for y in range(surface.height): point = (x + pos[0], y + pos[1]) if self.point_on_screen(point): self.matrix[point[0]][point[1]] = surface.matrix[x][y]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def point_on_screen(self, pos): """ Is the point still on the screen? :param pos: Point :type pos: tuple :return: Is it? :rtype: bool """
if 0 <= pos[0] < self.width and 0 <= pos[1] < self.height: 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 get(self, word): """ Obtains the definition of a word from Urban Dictionary. :param word: word to be searched for :type word: str :return: a result set with all definitions for the word """
url = "https://mashape-community-urban-dictionary.p.mashape.com/define?term=%s" % word try: res = requests.get(url, headers = {"X-Mashape-Key": self.api_key, "Accept": "text/plain"}) except requests.ConnectionError: raise errors.ConnectionError if res.status_code == 200: if res.json()["result_type"] == 'no_results': raise errors.NoResultsError else: return Result(res.json()) else: if res.status_code == 403: raise errors.APIUnauthorizedError
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def estimate(self, upgrades): """Estimate the time needed to apply upgrades. If an upgrades does not specify and estimate it is assumed to be in the order of 1 second. :param upgrades: List of upgrades sorted in topological order. """
val = 0 for u in upgrades: val += u.estimate() return val
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def human_estimate(self, upgrades): """Make a human readable estimated time to completion string. :param upgrades: List of upgrades sorted in topological order. """
val = self.estimate(upgrades) if val < 60: return "less than 1 minute" elif val < 300: return "less than 5 minutes" elif val < 600: return "less than 10 minutes" elif val < 1800: return "less than 30 minutes" elif val < 3600: return "less than 1 hour" elif val < 3 * 3600: return "less than 3 hours" elif val < 6 * 3600: return "less than 6 hours" elif val < 12 * 3600: return "less than 12 hours" elif val < 86400: return "less than 1 day" else: return "more than 1 day"
<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_log_prefix(self, plugin_id=''): """Setup custom warning notification."""
self._logger_console_fmtter.prefix = '%s: ' % plugin_id self._logger_console_fmtter.plugin_id = plugin_id self._logger_file_fmtter.prefix = '*' self._logger_file_fmtter.plugin_id = '%s: ' % plugin_id
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _teardown_log_prefix(self): """Tear down custom warning notification."""
self._logger_console_fmtter.prefix = '' self._logger_console_fmtter.plugin_id = '' self._logger_file_fmtter.prefix = ' ' self._logger_file_fmtter.plugin_id = ''
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pre_upgrade_checks(self, upgrades): """Run upgrade pre-checks prior to applying upgrades. Pre-checks should in general be fast to execute. Pre-checks may the use the wait_for_user function, to query the user for confirmation, but should respect the --yes-i-know option to run unattended. All pre-checks will be executed even if one fails, however if one pre- check fails, the upgrade process will be stopped and the user warned. :param upgrades: List of upgrades sorted in topological order. """
errors = [] for check in self.global_pre_upgrade: self._setup_log_prefix(plugin_id=check.__name__) try: check() except RuntimeError as e: errors.append((check.__name__, e.args)) for u in upgrades: self._setup_log_prefix(plugin_id=u.name) try: u.pre_upgrade() except RuntimeError as e: errors.append((u.name, e.args)) self._teardown_log_prefix() self._check_errors(errors, "Pre-upgrade check for %s failed with the" " following errors:")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_errors(self, errors, prefix): """Check for errors and possible raise and format an error message. :param errors: List of error messages. :param prefix: str, Prefix message for error messages """
args = [] for uid, messages in errors: error_msg = [] error_msg.append(prefix % uid) for msg in messages: error_msg.append(" (-) %s" % msg) args.append("\n".join(error_msg)) if args: raise RuntimeError(*args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def post_upgrade_checks(self, upgrades): """Run post-upgrade checks after applying all pending upgrades. Post checks may be used to emit warnings encountered when applying an upgrade, but post-checks can also be used to advice the user to run re-indexing or similar long running processes. Post-checks may query for user-input, but should respect the --yes-i-know option to run in an unattended mode. All applied upgrades post-checks are executed. :param upgrades: List of upgrades sorted in topological order. """
errors = [] for u in upgrades: self._setup_log_prefix(plugin_id=u.name) try: u.post_upgrade() except RuntimeError as e: errors.append((u.name, e.args)) for check in self.global_post_upgrade: self._setup_log_prefix(plugin_id=check.__name__) try: check() except RuntimeError as e: errors.append((check.__name__, e.args)) self._teardown_log_prefix() self._check_errors(errors, "Post-upgrade check for %s failed with the " "following errors:")
<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_upgrade(self, upgrade): """Apply a upgrade and register that it was successful. A upgrade may throw a RuntimeError, if an unrecoverable error happens. :param upgrade: A single upgrade """
self._setup_log_prefix(plugin_id=upgrade.name) try: # Nested due to Python 2.4 try: upgrade.do_upgrade() self.register_success(upgrade) except RuntimeError as e: msg = ["Upgrade error(s):"] for m in e.args: msg.append(" (-) %s" % m) logger = self.get_logger() logger.error("\n".join(msg)) raise RuntimeError( "Upgrade '%s' failed. Your installation is in an" " inconsistent state. Please manually review the upgrade " "and resolve inconsistencies." % upgrade['id'] ) finally: self._teardown_log_prefix()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_history(self): """Load upgrade history from database table. If upgrade table does not exists, the history is assumed to be empty. """
if not self.history: query = Upgrade.query.order_by(desc(Upgrade.applied)) for u in query.all(): self.history[u.upgrade] = u.applied self.ordered_history.append(u.upgrade)
<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_success(self, upgrade): """Register a successful upgrade."""
u = Upgrade(upgrade=upgrade.name, applied=datetime.now()) db.session.add(u) db.session.commit()
<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_history(self): """Get history of applied upgrades."""
self.load_history() return map(lambda x: (x, self.history[x]), self.ordered_history)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _load_upgrades(self, remove_applied=True): """Load upgrade modules. :param remove_applied: if True, already applied upgrades will not be included, if False the entire upgrade graph will be returned. """
if remove_applied: self.load_history() for entry_point in iter_entry_points('invenio_upgrader.upgrades'): upgrade = entry_point.load()() self.__class__._upgrades[upgrade.name] = upgrade return self.__class__._upgrades
<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_graph(self, upgrades, history=None): """Create dependency graph from upgrades. :param upgrades: Dict of upgrades :param history: Dict of applied upgrades """
history = history or {} graph_incoming = {} # nodes their incoming edges graph_outgoing = {} # nodes their outgoing edges # Create graph data structure for mod in six.itervalues(upgrades): # Remove all incoming edges from already applied upgrades graph_incoming[mod.name] = [x for x in mod.depends_on if x not in history] # Build graph_outgoing if mod.name not in graph_outgoing: graph_outgoing[mod.name] = [] for edge in graph_incoming[mod.name]: if edge not in graph_outgoing: graph_outgoing[edge] = [] graph_outgoing[edge].append(mod.name) return (graph_incoming, graph_outgoing)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def order_upgrades(self, upgrades, history=None): """Order upgrades according to their dependencies. (topological sort using Kahn's algorithm - http://en.wikipedia.org/wiki/Topological_sorting). :param upgrades: Dict of upgrades :param history: Dict of applied upgrades """
history = history or {} graph_incoming, graph_outgoing = self._create_graph(upgrades, history) # Removed already applied upgrades (assumes all dependencies prior to # this upgrade has been applied). for node_id in six.iterkeys(history): start_nodes = [node_id, ] while start_nodes: node = start_nodes.pop() # Remove from direct dependents try: for d in graph_outgoing[node]: graph_incoming[d] = [x for x in graph_incoming[d] if x != node] except KeyError: warnings.warn("Ghost upgrade %s detected" % node) # Remove all prior dependencies if node in graph_incoming: # Get dependencies, remove node, and recursively # remove all dependencies. depends_on = graph_incoming[node] # Add dependencies to check for d in depends_on: graph_outgoing[d] = [x for x in graph_outgoing[d] if x != node] start_nodes.append(d) del graph_incoming[node] # Check for missing dependencies for node_id, depends_on in six.iteritems(graph_incoming): for d in depends_on: if d not in graph_incoming: raise RuntimeError("Upgrade %s depends on an unknown" " upgrade %s" % (node_id, d)) # Nodes with no incoming edges start_nodes = [x for x in six.iterkeys(graph_incoming) if len(graph_incoming[x]) == 0] topo_order = [] while start_nodes: # Append node_n to list (it has no incoming edges) node_n = start_nodes.pop() topo_order.append(node_n) # For each node m with and edge from n to m for node_m in graph_outgoing[node_n]: # Remove the edge n to m graph_incoming[node_m] = [x for x in graph_incoming[node_m] if x != node_n] # If m has no incoming edges, add it to start_nodes. if not graph_incoming[node_m]: start_nodes.append(node_m) for node, edges in six.iteritems(graph_incoming): if edges: raise RuntimeError("The upgrades have at least one cyclic " "dependency involving %s." % node) return map(lambda x: upgrades[x], topo_order)
<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_plugin_id(self, plugin_id): """Determine repository from plugin id."""
m = re.match("(.+)(_\d{4}_\d{2}_\d{2}_)(.+)", plugin_id) if m: return m.group(1) m = re.match("(.+)(_release_)(.+)", plugin_id) if m: return m.group(1) raise RuntimeError("Repository could not be determined from " "the upgrade identifier: %s." % plugin_id)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_metar_from_mission( mission_file: str, icao: str = 'XXXX', time: str = None, ) -> str: """ Builds a dummy METAR string from a mission file Args: mission_file: input mission file icao: dummy ICAO (defaults to XXXX) time: dummy time (defaults to now()) Returns: METAR str """
return _MetarFromMission( mission_file=mission_file, icao=icao, time=time, ).metar
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def metar(self) -> str: """ Builds a METAR string from a MIZ file A lots of information is inferred from what information we have available in DCS. There constraints in the way MIZ files are built, with precipitations for example. Returns: METAR string """
metar = f'{self._icao} ' \ f'{self._time} ' \ f'{self._wind} ' \ f'{self._visibility} ' \ f'{self._precipitations} ' \ f'{self._clouds} ' \ f'{self._temperature} ' \ f'{self._pressure} ' \ f'{self._qualifier}' return re.sub(' +', ' ', metar)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def subtopics(store, folders, folder_id, subfolder_id, ann_id=None): '''Yields an unordered generator of subtopics in a subfolder. Each item of the generator is a 4-tuple of ``content_id``, ``subtopic_id``, ``subtopic_type`` and ``data``. Subtopic type is one of the following Unicode strings: ``text``, ``image`` or ``manual``. The type of ``data`` is dependent on the subtopic type. For ``image``, ``data`` is a ``(unicode, str)``, where the first element is the URL and the second element is the binary image data. For all other types, ``data`` is a ``unicode`` string. :param str folder_id: Folder id :param str subfolder_id: Subfolder id :param str ann_id: Username :rtype: generator of ``(content_id, subtopic_id, url, subtopic_type, data)`` ''' # This code will be changed soon. In essence, it implements the # convention established in SortingDesk for storing subtopic data. # Currently, subtopic data is stored in the FC that the data (i.e., # image or snippet) came from. This is bad because it causes pretty # severe race conditions. # # Our current plan is to put each subtopic datum in its own FC. It will # require this code to make more FC fetches, but we should be able to # do it with one `store.get_many` call. items = folders.grouped_items(folder_id, subfolder_id, ann_id=ann_id) fcs = dict([(cid, fc) for cid, fc in store.get_many(items.keys())]) for cid, subids in items.iteritems(): fc = fcs[cid] for subid in subids: try: data = typed_subtopic_data(fc, subid) except KeyError: # We have a dangling label folks! continue yield cid, subid, fc['meta_url'], subtopic_type(subid), 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 typed_subtopic_data(fc, subid): '''Returns typed subtopic data from an FC.''' # I don't think this code will change after we fix the data race bug. ---AG ty = subtopic_type(subid) data = get_unicode_feature(fc, subid) assert isinstance(data, unicode), \ 'data should be `unicode` but is %r' % type(data) if ty == 'image': img_data = get_unicode_feature(fc, subid + '|data') img = re.sub('^data:image/[a-zA-Z]+;base64,', '', img_data) img = base64.b64decode(img.encode('utf-8')) return data, img elif ty in ('text', 'manual'): return data raise ValueError('unrecognized subtopic type "%s"' % ty)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def text(el, strip=True): """ Return the text of a ``BeautifulSoup`` element """
if not el: return "" text = el.text if strip: text = text.strip() 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 parse(el, typ): """ Parse a ``BeautifulSoup`` element as the given type. """
if not el: return typ() txt = text(el) if not txt: return typ() return typ(txt)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parsebool(el): """ Parse a ``BeautifulSoup`` element as a bool """
txt = text(el) up = txt.upper() if up == "OUI": return True if up == "NON": return False return bool(parseint(el))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authenticate_device(self, api_token, device_token, email=None, user_url=None, override=False, fetch=True): """Set credentials for Device authentication. Args: api_token (str): Token issued to your Application through the Gem Developer Console. device_token (str): Physical device identifier. You will receive this from a user.devices.create call or from users.create. email (str, optional): User's email address, required if user_url is not provided. user_url (str, optional): User's Gem url. override (boolean, optional): Replace existing Application credentials. fetch (boolean, optional): Return the authenticated User. Returns: An User object if `fetch` is True. """
if (self.context.has_auth_params('Gem-Device') and not override): raise OverrideError('Gem-Device') if (not api_token or not device_token or (not email and not user_url) or not self.context.authorize('Gem-Device', api_token=api_token, user_email=email, user_url=user_url, device_token=device_token)): raise AuthUsageError(self.context, 'Gem-Device') if fetch: user = self.user(email) if email else self.user() return user.refresh() else: 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 authenticate_identify(self, api_token, override=True): """Set credentials for Identify authentication. Args: api_token (str): Token issued to your Application through the Gem Developer Console. override (boolean): Replace existing Application credentials. """
if (self.context.has_auth_params('Gem-Identify') and not override): raise OverrideError('Gem-Identify') if (not api_token or not self.context.authorize('Gem-Identify', api_token=api_token)): raise AuthUsageError(self.context, 'Gem-Identify') 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 parse_options(arguments=None): """ Reads command-line arguments """
if arguments is None: arguments = sys.argv[1:] if isinstance(arguments, str): arguments = arguments.split() if isinstance(arguments, argparse.Namespace): return arguments parser = create_args_parser() args = parser.parse_args(arguments) # pprint(args.__dict__) args.dialect = args.dialect.lower() if args.dialect not in ['lisp', 'newlisp', 'clojure', 'scheme', 'all', '']: parser.error("`{0}' is not a recognized dialect".format(args.dialect)) args.backup_dir = os.path.expanduser(args.backup_dir) if not os.path.exists(args.backup_dir): parser.error("Directory `{0}' does not exist".format(args.backup_dir)) if len(args.files) > 1 and args.output_file: parser.error('Cannot use the -o flag when more than one file is specified') if not args.files: # Indentation from standard input if args.modify and not args.output_file: args.modify = False args.backup = False args.warning = False if args.output_diff: # If someone requests a diff we assume he/she doesn't want the file to be # modified args.modify = False return args
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assign_indent_numbers(lst, inum, dic=collections.defaultdict(int)): """ Associate keywords with their respective indentation numbers """
for i in lst: dic[i] = inum return dic
<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_url( width, height=None, background_color="cccccc", text_color="969696", text=None, random_background_color=False ): """ Craft the URL for a placeholder image. You can customize the background color, text color and text using the optional keyword arguments If you want to use a random color pass in random_background_color as True. """
if random_background_color: background_color = _get_random_color() # If height is not provided, presume it is will be a square if not height: height = width d = dict( width=width, height=height, bcolor=background_color, tcolor=text_color ) url = URL % d if text: text = text.replace(" ", "+") url = url + "?text=" + text return url
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def preserve_builtin_query_params(url, request=None): """ Given an incoming request, and an outgoing URL representation, append the value of any built-in query parameters. """
if request is None: return url overrides = [ api_settings.URL_FORMAT_OVERRIDE, ] for param in overrides: if param and (param in request.GET): value = request.GET[param] url = replace_query_param(url, param, value) return url
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reverse(viewname, args=None, kwargs=None, request=None, format=None, **extra): """ If versioning is being used then we pass any `reverse` calls through to the versioning scheme instance, so that the resulting URL can be modified if needed. """
scheme = getattr(request, 'versioning_scheme', None) if scheme is not None: try: url = scheme.reverse(viewname, args, kwargs, request, format, **extra) except NoReverseMatch: # In case the versioning scheme reversal fails, fallback to the # default implementation url = _reverse(viewname, args, kwargs, request, format, **extra) else: url = _reverse(viewname, args, kwargs, request, format, **extra) return preserve_builtin_query_params(url, 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 _reverse(viewname, args=None, kwargs=None, request=None, format=None, **extra): """ Same as `django.core.urlresolvers.reverse`, but optionally takes a request and returns a fully qualified URL, using the request to get the base URL. """
if format is not None: kwargs = kwargs or {} kwargs['format'] = format url = django_reverse(viewname, args=args, kwargs=kwargs, **extra) if request: return request.build_absolute_uri(url) return url
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decompose(miz_file: Path, output_folder: Path): """ Decompose this Miz into json Args: output_folder: folder to output the json structure as a Path miz_file: MIZ file path as a Path """
mission_folder, assets_folder = NewMiz._get_subfolders(output_folder) NewMiz._wipe_folders(mission_folder, assets_folder) LOGGER.info('unzipping mission file') with Miz(miz_file) as miz: version = miz.mission.d['version'] LOGGER.debug(f'mission version: "%s"', version) LOGGER.info('copying assets to: "%s"', assets_folder) ignore = shutil.ignore_patterns('mission') shutil.copytree(str(miz.temp_dir), str(assets_folder), ignore=ignore) NewMiz._reorder_warehouses(assets_folder) LOGGER.info('decomposing mission table into: "%s" (this will take a while)', mission_folder) NewMiz._decompose_dict(miz.mission.d, 'base_info', mission_folder, version, miz)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def recompose(src: Path, target_file: Path): """ Recompose a Miz from json object Args: src: folder containing the json structure target_file: target Miz file """
mission_folder, assets_folder = NewMiz._get_subfolders(src) # pylint: disable=c-extension-no-member base_info = ujson.loads(Path(mission_folder, 'base_info.json').read_text(encoding=ENCODING)) version = base_info['__version__'] with Miz(target_file) as miz: LOGGER.info('re-composing mission table from folder: "%s"', mission_folder) miz.mission.d = NewMiz._recreate_dict_from_folder(mission_folder, version) for item in assets_folder.iterdir(): target = Path(miz.temp_dir, item.name).absolute() if item.is_dir(): if target.exists(): shutil.rmtree(target) shutil.copytree(item.absolute(), target) elif item.is_file(): shutil.copy(item.absolute(), target) miz.zip(target_file, encode=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 handle(self, *args, **options): """ Sets options common to all commands. Any command subclassing this object should implement its own handle method, as is standard in Django, and run this method via a super call to inherit its functionality. """
# Create a data directory self.data_dir = os.path.join( settings.BASE_DIR, 'data') if not os.path.exists(self.data_dir): os.makedirs(self.data_dir) # Start the clock self.start_datetime = datetime.now()
<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_file(self, filename, contents): """write the html file contents to disk"""
with open(filename, 'w') as f: f.write(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 get_session(url): """Get db session. :param url: URL for connect with DB :type url: :class:`str` :returns: A sqlalchemy db session :rtype: :class:`sqlalchemy.orm.Session` """
engine = create_engine(url) db_session = scoped_session(sessionmaker(engine)) Base.metadata.create_all(engine) return db_session
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _AsynchronouslyGetProcessOutput(formattedCmd, printStdOut, printStdErr, **kwargs): ''' Asynchronously read the process ''' opts = filterKWArgsForFunc(kwargs, subprocess.Popen) opts['stdout'] = subprocess.PIPE opts['stderr'] = subprocess.PIPE process = subprocess.Popen(formattedCmd, **opts) # Launch the asynchronous readers of the process' stdout and stderr. stdout_queue = Queue.Queue() stdout_reader = _AsynchronousFileReader(process.stdout, stdout_queue) stdout_reader.start() stderr_queue = Queue.Queue() stderr_reader = _AsynchronousFileReader(process.stderr, stderr_queue) stderr_reader.start() stdOutLines = [] stdErrLines = [] # Check the queues if we received some output (until there is nothing more to get). while not stdout_reader.eof() or not stderr_reader.eof(): # Show what we received from standard output. while not stdout_queue.empty(): line = stdout_queue.get() stdOutLines.append(line) if printStdOut: print line.rstrip() # Show what we received from standard error. while not stderr_queue.empty(): line = stderr_queue.get() stdErrLines.append(line) if printStdErr: print colored(line.rstrip(),'red') # Sleep a bit before asking the readers again. time.sleep(.05) # Let's be tidy and join the threads we've started. stdout_reader.join() stderr_reader.join() # Close subprocess' file descriptors. process.stdout.close() process.stderr.close() process.wait() stdOut = ''.join(stdOutLines) stdErr = ''.join(stdErrLines) return (process.returncode, stdOut, stdErr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def execute(cmd, verbosityThreshold = 1, **kwargs): '''execute the passed in command in the shell''' global exectue_defaults opts = merge(exectue_defaults, kwargs) # the options computed from the default options together with the passed in options. subopts = filterKWArgsForFunc(opts, subprocess.Popen) formattedCmd = cmd.format(**getFormatBindings(cmd,1)) shouldPrint = opts['verbosity'] >= verbosityThreshold isDryrun = opts['dryrun'] if shouldPrint: msg = "would execute:" if isDryrun else "executing:" pre = "("+subopts['cwd']+")" if (subopts['cwd'] != exectue_defaults['cwd']) else "" print "{pre}{msg} {formattedCmd}".format(pre=pre, formattedCmd=formattedCmd, msg=msg) if isDryrun: return (0, None, None) printStdOut = shouldPrint and opts['permitShowingStdOut'] printStdErr = shouldPrint and opts['permitShowingStdErr'] returnCode = 0 if opts['captureStdOutStdErr']: (returnCode, stdOut, stdErr) = _AsynchronouslyGetProcessOutput(formattedCmd, printStdOut, printStdErr, **subopts) else: subopts['stdout'] = None if printStdOut else subprocess.PIPE subopts['stderr'] = None if printStdErr else subprocess.PIPE process = subprocess.Popen(formattedCmd, **subopts) res = process.communicate() returnCode = process.returncode stdOut = res[0] stdErr = res[1] if returnCode and not opts['ignoreErrors']: print colored('Command {} failed with return code {}!'.format(cmd, returnCode),'red') sys.exit(returnCode) # always print any errors return (returnCode, stdOut, stdErr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _extract_columns(self, table_name): ''' a method to extract the column properties of an existing table ''' import re from sqlalchemy import MetaData, VARCHAR, INTEGER, BLOB, BOOLEAN, FLOAT from sqlalchemy.dialects.postgresql import DOUBLE_PRECISION, BIT, BYTEA # retrieve list of tables metadata_object = MetaData() table_list = self.engine.table_names() # determine columns prior_columns = {} if table_name in table_list: metadata_object.reflect(self.engine) existing_table = metadata_object.tables[table_name] for column in existing_table.columns: column_type = None column_length = None if column.type.__class__ == FLOAT().__class__: column_type = 'float' elif column.type.__class__ == DOUBLE_PRECISION().__class__: # Postgres column_type = 'float' elif column.type.__class__ == INTEGER().__class__: column_type = 'integer' elif column.type.__class__ == VARCHAR().__class__: column_length = getattr(column.type, 'length', None) if column_length == 1: if column.primary_key: column_length = None column_type = 'string' elif column.type.__class__ == BLOB().__class__: column_type = 'list' elif column.type.__class__ in (BIT().__class__, BYTEA().__class__): column_type = 'list' elif column.type.__class__ == BOOLEAN().__class__: column_type = 'boolean' prior_columns[column.key] = (column.key, column_type, '', column_length) return prior_columns
<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_columns(self): ''' a helper method for parsing the column properties from the record schema ''' # construct column list column_map = {} for key, value in self.model.keyMap.items(): record_key = key[1:] if record_key: if self.item_key.findall(record_key): pass else: if value['value_datatype'] == 'map': continue datatype = value['value_datatype'] if value['value_datatype'] == 'number': datatype = 'float' if 'integer_data' in value.keys(): if value['integer_data']: datatype = 'integer' replace_key = '' if 'field_metadata' in value.keys(): if 'replace_key' in value['field_metadata'].keys(): if isinstance(value['field_metadata']['replace_key'], str): replace_key = value['field_metadata']['replace_key'] max_length = None if 'max_length' in value.keys(): max_length = value['max_length'] column_map[record_key] = (record_key, datatype, replace_key, max_length) return column_map