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 generate(self): """ Generates a new token for this column based on its bit length. This method will not ensure uniqueness in the model itself, that should be checked against the model records in the database first. :return: <str> """
try: model = self.schema().model() except AttributeError: return os.urandom(self.__bits).encode('hex') else: while True: token = os.urandom(self.__bits).encode('hex') if model.select(where=orb.Query(self) == token).count() == 0: return token
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start_monitoring(seconds_frozen=SECONDS_FROZEN, test_interval=TEST_INTERVAL): """Start monitoring for hanging threads. seconds_frozen - How much time should thread hang to activate printing stack trace - default(10) tests_interval - Sleep time of monitoring thread (in milliseconds) - default(100) """
thread = StoppableThread(target=monitor, args=(seconds_frozen, test_interval)) thread.daemon = True thread.start() return thread
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def monitor(seconds_frozen, test_interval): """Monitoring thread function. Checks if thread is hanging for time defined by ``seconds_frozen`` parameter every ``test_interval`` milliseconds. """
current_thread = threading.current_thread() hanging_threads = set() old_threads = {} # Threads found on previous iteration. while not current_thread.is_stopped(): new_threads = get_current_frames() # Report died threads. for thread_id in old_threads.keys(): if thread_id not in new_threads and thread_id in hanging_threads: log_died_thread(thread_id) # Process live threads. time.sleep(test_interval/1000.) now = time.time() then = now - seconds_frozen for thread_id, thread_data in new_threads.items(): # Don't report the monitor thread. if thread_id == current_thread.ident: continue frame = thread_data['frame'] # If thread is new or it's stack is changed then update time. if (thread_id not in old_threads or frame != old_threads[thread_id]['frame']): thread_data['time'] = now # If the thread was hanging then report awaked thread. if thread_id in hanging_threads: hanging_threads.remove(thread_id) log_awaked_thread(thread_id) else: # If stack is not changed then keep old time. last_change_time = old_threads[thread_id]['time'] thread_data['time'] = last_change_time # Check if this is a new hanging thread. if (thread_id not in hanging_threads and last_change_time < then): # Gotcha! hanging_threads.add(thread_id) # Report the hanged thread. log_hanged_thread(thread_id, frame) old_threads = new_threads
<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_current_frames(): """Return current threads prepared for further processing. """
return dict( (thread_id, {'frame': thread2list(frame), 'time': None}) for thread_id, frame in sys._current_frames().items() )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def frame2string(frame): """Return info about frame. Keyword arg: frame Return string in format: File {file name}, line {line number}, in {name of parent of code object} {newline} Line from file at line number """
lineno = frame.f_lineno # or f_lasti co = frame.f_code filename = co.co_filename name = co.co_name s = '\tFile "{0}", line {1}, in {2}'.format(filename, lineno, name) line = linecache.getline(filename, lineno, frame.f_globals).lstrip() return s + '\n\t\t' + line
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def thread2list(frame): """Return list with string frame representation of each frame of thread. """
l = [] while frame: l.insert(0, frame2string(frame)) frame = frame.f_back return l
<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_log(title, message=''): """Write formatted log message to stderr."""
sys.stderr.write(''.join([ title.center(40).center(60, '-'), '\n', message ]))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute_input_middleware_stream(self, request, controller): """ Request comes from the controller. Returned is a request. controller arg is the name of the controller. """
start_request = request # either 'http' or 'cmd' or 'irc' controller_name = "".join(controller.get_controller_name().split('-')[:1]) middlewares = list(self.pre_input_middleware) + list(self.input_middleware) for m in middlewares: to_execute = getattr(m(controller), controller_name) if to_execute: result = to_execute(request) if GiottoControl in type(result).mro(): # a middleware class returned a control object (redirection, et al.) # ignore all other middleware classes return request, result request = result return start_request, 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 _get_suggestions(self, filter_word=None): """ This only gets caled internally from the get_suggestion method. """
keys = self.manifest.keys() words = [] for key in keys: if isinstance(self.manifest[key], Manifest): # if this key is another manifest, append a slash to the # suggestion so the user knows theres more items under this key words.append(key + '/') else: words.append(key) if filter_word: words = [x for x in words if x.startswith(filter_word)] return words
<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_suggestion(self, front_path): """ Returns suggestions for a path. Used in tab completion from the command line. """
if '/' in front_path: # transverse the manifest, return the new manifest, then # get those suggestions with the remaining word splitted = front_path.split('/') new_manifest = self.manifest pre_path = '' for item in splitted: try: new_manifest = new_manifest[item] except KeyError: partial_word = item break else: pre_path += item + '/' if isinstance(new_manifest, Program): return [] matches = new_manifest._get_suggestions(partial_word) return [pre_path + match for match in matches] else: return self._get_suggestions(front_path 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 parse_invocation(self, invocation, controller_tag): """ Given an invocation string, determine which part is the path, the program, and the args. """
if invocation.endswith('/'): invocation = invocation[:-1] if not invocation.startswith('/'): invocation = '/' + invocation if invocation == '': invocation = '/' all_programs = self.get_urls(controllers=[controller_tag]) matching_paths = set() for program_path in sorted(all_programs): if invocation.startswith(program_path): matching_paths.add(program_path) longest = "" for path in matching_paths: longest = path if len(path) > len(longest) else longest matching_path = longest program = self.get_program(matching_path, controller=controller_tag) if not matching_path: raise ProgramNotFound("Can't find %s" % invocation) program_name = matching_path.split('/')[-1] path = "/".join(matching_path.split('/')[:-1]) + '/' args_fragment = invocation[len(matching_path):] superformat = None if args_fragment.startswith('.'): # args_fragment will be something like ".html/arg1/arg2" or just ".html" superformat = args_fragment.split('/')[0][1:] args = args_fragment.split('/')[1:] args_fragment = '/'.join(args) else: args = args_fragment.split("/")[1:] if args_fragment else [] args_fragment = args_fragment[1:] if (args_fragment and args_fragment[0] =='/') else args_fragment return { 'program': program, 'program_name': program_name, 'superformat': superformat, 'superformat_mime': super_accept_to_mimetype(superformat), 'args': args, 'raw_args': args_fragment, 'path': path, 'invocation': invocation, }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy(self): """ Returns a new instance copy of this column. :return: <orb.Column> """
out = type(self)( name=self.__name, field=self.__field, display=self.__display, flags=self.__flags, default=self.__default, defaultOrder=self.__defaultOrder, getter=self.__gettermethod, setter=self.__settermethod, queryFilter=self.__query_filter, shortcut=self.__shortcut, readPermit=self.__readPermit, writePermit=self.__writePermit, order=self.__order ) 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 dbMath(self, typ, field, op, value): """ Performs some database math on the given field. This will be database specific implementations and should return the resulting database operation. :param field: <str> :param op: <orb.Query.Math> :param target: <variant> :param context: <orb.Context> || None :return: <str> """
ops = orb.Query.Math(op) format = self.MathMap.get(typ, {}).get(ops) or self.MathMap.get('Default').get(ops) or '{field}' return format.format(field=field, value=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 dbType(self, typ): """ Returns the database object type based on the given connection type. :param typ: <str> :return: <str> """
return self.TypeMap.get(typ, self.TypeMap.get('Default'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def default(self): """ Returns the default value for this column to return when generating new instances. :return <variant> """
if isinstance(self.__default, (str, unicode)): return self.valueFromString(self.__default) else: return self.__default
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def field(self): """ Returns the field name that this column will have inside the database. :return <str> """
if not self.__field: default_field = inflection.underscore(self.__name) if isinstance(self, orb.ReferenceColumn): default_field += '_id' self.__field = default_field return self.__field or default_field
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def firstMemberSchema(self, schemas): """ Returns the first schema within the list that this column is a member of. :param schemas | [<orb.TableSchema>, ..] :return <orb.TableSchema> || None """
for schema in schemas: if schema.hasColumn(self): return schema return self.schema()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isMemberOf(self, schemas): """ Returns whether or not this column is a member of any of the given schemas. :param schemas | [<orb.TableSchema>, ..] || <orb.TableSchema> :return <bool> """
if type(schemas) not in (tuple, list, set): schemas = (schemas,) for schema in schemas: if schema.hasColumn(self): 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 loadJSON(self, jdata): """ Initializes the information for this class from the given JSON data blob. :param jdata: <dict> """
# required params self.__name = jdata['name'] self.__field = jdata['field'] # optional fields self.__display = jdata.get('display') or self.__display self.__flags = jdata.get('flags') or self.__flags self.__defaultOrder = jdata.get('defaultOrder') or self.__defaultOrder self.__default = jdata.get('default') or self.__default
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setFlag(self, flag, state=True): """ Sets whether or not this flag should be on. :param flag | <Column.Flags> state | <bool> """
if state: self.__flags |= flag else: self.__flags &= ~flag
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(self, value): """ Validates the inputted value against this columns rules. If the inputted value does not pass, then a validation error will be raised. Override this method in column sub-classes for more specialized validation. :param value | <variant> :return <bool> success """
# check for the required flag if self.testFlag(self.Flags.Required) and not self.testFlag(self.Flags.AutoAssign): if self.isNull(value): msg = '{0} is a required column.'.format(self.name()) raise orb.errors.ColumnValidationError(self, msg) # otherwise, we're good 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 fromJSON(cls, jdata): """ Generates a new column from the given json data. This should be already loaded into a Python dictionary, not a JSON string. :param jdata | <dict> :return <orb.Column> || None """
cls_type = jdata.get('type') col_cls = cls.byName(cls_type) if not col_cls: raise orb.errors.ColumnTypeNotFound(cls_type) else: col = col_cls() col.loadJSON(jdata) return col
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ancestry(self): """ Returns the different inherited schemas for this instance. :return [<TableSchema>, ..] """
if not self.inherits(): return [] schema = orb.system.schema(self.inherits()) if not schema: return [] return schema.ancestry() + [schema]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addColumn(self, column): """ Adds the inputted column to this table schema. :param column | <orb.Column> """
column.setSchema(self) self.__columns[column.name()] = column
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addIndex(self, index): """ Adds the inputted index to this table schema. :param index | <orb.Index> """
index.setSchema(self) self.__indexes[index.name()] = index
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addCollector(self, collector): """ Adds the inputted collector reference to this table schema. :param collector | <orb.Collector> """
collector.setSchema(self) self.__collectors[collector.name()] = collector
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def collector(self, name, recurse=True): """ Returns the collector that matches the inputted name. :return <orb.Collector> || None """
return self.collectors(recurse=recurse).get(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 collectors(self, recurse=True, flags=0): """ Returns a list of the collectors for this instance. :return {<str> name: <orb.Collector>, ..} """
output = {} if recurse and self.inherits(): schema = orb.system.schema(self.inherits()) if not schema: raise orb.errors.ModelNotFound(schema=self.inherits()) else: iflags = (flags & ~orb.Collector.Flags.Virtual) if flags else ~orb.Collector.Flags.Virtual output.update(schema.collectors(recurse=recurse, flags=iflags)) output.update({c.name(): c for c in self.__collectors.values() if not flags or c.testFlag(flags)}) return output
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inheritanceTree(self): """ Returns the inheritance tree for this schema, traversing up the hierarchy for the inherited schema instances. :return: <generator> """
inherits = self.inherits() while inherits: ischema = orb.system.schema(inherits) if not ischema: raise orb.errors.ModelNotFound(schema=inherits) yield ischema inherits = ischema.inherits()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def namespace(self, **context): """ Returns the namespace that should be used for this schema, when specified. :return: <str> """
context = orb.Context(**context) if context.forceNamespace: return context.namespace or self.__namespace else: return self.__namespace or context.namespace
<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_kwargs(kwargs): """ Convert a list of kwargs into a dictionary. Duplicates of the same keyword get added to an list within the dictionary. {'var1': [1, 3], 'var2': 2} """
d = defaultdict(list) for k, v in ((k.lstrip('-'), v) for k,v in (a.split('=') for a in kwargs)): d[k].append(v) ret = {} for k, v in d.items(): # replace single item lists with just the item. if len(v) == 1 and type(v) is list: ret[k] = v[0] else: ret[k] = v return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def htmlize_list(items): """ Turn a python list into an html list. """
out = ["<ul>"] for item in items: out.append("<li>" + htmlize(item) + "</li>") out.append("</ul>") 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 pre_process_json(obj): """ Preprocess items in a dictionary or list and prepare them to be json serialized. """
if type(obj) is dict: new_dict = {} for key, value in obj.items(): new_dict[key] = pre_process_json(value) return new_dict elif type(obj) is list: new_list = [] for item in obj: new_list.append(pre_process_json(item)) return new_list elif hasattr(obj, 'todict'): return dict(obj.todict()) else: try: json.dumps(obj) except TypeError: try: json.dumps(obj.__dict__) except TypeError: return str(obj) else: return obj.__dict__ else: 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 render_error_page(code, exc, mimetype='text/html', traceback=''): """ Render the error page """
from giotto.views import get_jinja_template if 'json' in mimetype: return json.dumps({ 'code': code, 'exception': exc.__class__.__name__, 'message': str(exc), }) et = get_config('error_template') if not et: return "%s %s\n%s" % (code, str(exc), traceback) template = get_jinja_template(et) return template.render( code=code, exception=exc.__class__.__name__, message=str(exc), traceback=traceback )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def initialize(module_name=None): """ Build the giotto settings object. This function gets called at the very begining of every request cycle. """
import giotto from giotto.utils import random_string, switchout_keyvalue from django.conf import settings setattr(giotto, '_config', GiottoSettings()) if not module_name: # For testing. No settings will be set. return project_module = importlib.import_module(module_name) project_path = os.path.dirname(project_module.__file__) setattr(giotto._config, 'project_path', project_path) try: secrets = importlib.import_module("%s.controllers.secrets" % module_name) except ImportError: secrets = None try: machine = importlib.import_module("%s.controllers.machine" % module_name) except ImportError: machine = None config = importlib.import_module("%s.controllers.config" % module_name) if config: for item in dir(config): setting_value = getattr(config, item) setattr(giotto._config, item, setting_value) if secrets: for item in dir(secrets): setting_value = getattr(secrets, item) setattr(giotto._config, item, setting_value) else: logging.warning("No secrets.py found") if machine: for item in dir(machine): setting_value = getattr(machine, item) setattr(giotto._config, item, setting_value) else: logging.warning("No machine.py found") settings.configure( SECRET_KEY=random_string(32), DATABASES=get_config('DATABASES'), INSTALLED_APPS=(module_name, 'giotto') ) ss = get_config('session_store', None) if ss: class_ = switchout_keyvalue(ss) setattr(giotto._config, "session_store", class_()) cache_engine = get_config("cache", None) if hasattr(cache_engine, 'lower'): # session engine was passed in as string, exchange for engine object. class_ = switchout_keyvalue(cache_engine) e = class_(host=get_config("cache_host", "localhost")) setattr(giotto._config, "cache_engine", e)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_config(item, default=None): """ Use this function to get values from the config object. """
import giotto return getattr(giotto._config, item, default) or default
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has_object_permission(self, request, view, obj): """ check filter permissions """
user = request.user if not user.is_superuser and not user.is_anonymous(): valid = False try: ct = ContentType.objects.get_for_model(obj) fpm = FilterPermissionModel.objects.get(user=user, content_type=ct) myq = QSerializer(base64=True).loads(fpm.filter) try: myobj = obj.__class__.objects.filter(myq).distinct().get(pk=obj.pk) if myobj: valid = True except ObjectDoesNotExist: valid = False except ObjectDoesNotExist: valid = True finally: return valid 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 displayHelp(self): """ Output help message of twistedchecker. """
self.outputStream.write(self.linter.help()) sys.exit(32)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unregisterChecker(self, checker): """ Remove a checker from the list of registered checkers. @param checker: the checker to remove """
self.linter._checkers[checker.name].remove(checker) if checker in self.linter._reports: del self.linter._reports[checker] if checker in self.linter.options_providers: self.linter.options_providers.remove(checker)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def findUselessCheckers(self, allowedMessages): """ Find checkers which generate no allowed messages. @param allowedMessages: allowed messages @return: useless checkers, remove them from pylint """
uselessCheckers = [] for checkerName in self.linter._checkers: for checker in list(self.linter._checkers[checkerName]): messagesOfChecker = set(checker.msgs) if not messagesOfChecker.intersection(allowedMessages): uselessCheckers.append(checker) return uselessCheckers
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restrictCheckers(self, allowedMessages): """ Unregister useless checkers to speed up twistedchecker. @param allowedMessages: output messages allowed in twistedchecker """
uselessCheckers = self.findUselessCheckers(allowedMessages) # Unregister these checkers for checker in uselessCheckers: self.unregisterChecker(checker)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getCheckerByName(self, checkerType): """ Get checker by given name. @checkerType: type of the checker """
for checker in sum(list(self.linter._checkers.values()), []): if isinstance(checker, checkerType): return checker 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 allowPatternsForNameChecking(self, patternsFunc, patternsClass): """ Allow name exceptions by given patterns. @param patternsFunc: patterns of special function names @param patternsClass: patterns of special class names """
cfgParser = self.linter.cfgfile_parser nameChecker = self.getCheckerByName(NameChecker) if not nameChecker: return if patternsFunc: regexFuncAdd = "|((%s).+)$" % "|".join(patternsFunc) else: regexFuncAdd = "" if patternsClass: regexClassAdd = "|((%s).+)$" % "|".join(patternsClass) else: regexClassAdd = "" # Modify regex for function, method and class name. regexMethod = cfgParser.get("BASIC", "method-rgx") + regexFuncAdd regexFunction = cfgParser.get("BASIC", "function-rgx") + regexFuncAdd regexClass = cfgParser.get("BASIC", "class-rgx") + regexClassAdd # Save to config parser. cfgParser.set("BASIC", "method-rgx", regexMethod) cfgParser.set("BASIC", "function-rgx", regexFunction) cfgParser.set("BASIC", "class-rgx", regexClass) # Save to name checker. nameChecker.config.method_rgx = re.compile(regexMethod) nameChecker.config.function_rgx = re.compile(regexFunction) nameChecker.config.class_rgx = re.compile(regexClass)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getPathList(self, filesOrModules): """ Transform a list of modules to path. @param filesOrModules: a list of modules (may be foo/bar.py or foo.bar) """
pathList = [] for fileOrMod in filesOrModules: if not os.path.exists(fileOrMod): # May be given module is not not a path, # then transform it to a path. try: filepath = file_from_modpath(fileOrMod.split('.')) except (ImportError, SyntaxError): # Could not load this module. continue if not os.path.exists(filepath): # Could not find this module in file system. continue if os.path.basename(filepath) == "__init__.py": filepath = os.path.dirname(filepath) else: filepath = fileOrMod pathList.append(filepath) return pathList
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setNameExceptions(self, filesOrModules): """ Find name exceptions in codes and allow them to be ignored in checking. @param filesOrModules: a list of modules (may be foo/bar.py or foo.bar) """
pathList = self.getPathList(filesOrModules) for path in pathList: patternsFunc, patternsClass = findAllExceptions(path) self.allowPatternsForNameChecking(patternsFunc, patternsClass)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self, args): """ Setup the environment, and run pylint. @param args: arguments will be passed to pylint @type args: list of string """
# set output stream. if self.outputStream: self.linter.reporter.set_output(self.outputStream) try: args = self.linter.load_command_line_configuration(args) except SystemExit as exc: if exc.code == 2: # bad options exc.code = 32 raise if not args: self.displayHelp() # Check for 'strict-epydoc' option. if self.allowOptions and not self.linter.option_value("strict-epydoc"): for msg in ["W9203", "W9205"]: self.linter.disable(msg) # insert current working directory to the python path to have a correct # behaviour. sys.path.insert(0, os.getcwd()) # set exceptions for name checking. self.setNameExceptions(args) # check for diff option. self.diffOption = self.linter.option_value("diff") if self.diffOption: self.prepareDiff() # check codes. self.linter.check(args) # show diff of warnings if diff option on. if self.diffOption: diffCount = self.showDiffResults() exitCode = 1 if diffCount else 0 sys.exit(exitCode) sys.exit(self.linter.msg_status)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepareDiff(self): """ Prepare to run the checker and get diff results. """
self.streamForDiff = NativeStringIO() self.linter.reporter.set_output(self.streamForDiff)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def showDiffResults(self): """ Show results when diff option on. """
try: oldWarnings = self.parseWarnings(self._readDiffFile()) except: sys.stderr.write(self.errorResultRead % self.diffOption) return 1 newWarnings = self.parseWarnings(self.streamForDiff.getvalue()) diffWarnings = self.generateDiff(oldWarnings, newWarnings) if diffWarnings: diffResult = self.formatWarnings(diffWarnings) self.outputStream.write(diffResult + "\n") return len(diffWarnings) else: 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 _readDiffFile(self): """ Read content of diff file. This is here to help with testing. @return: File content. @rtype: c{str} """
with open(self.diffOption) as f: content = f.read() return content
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generateDiff(self, oldWarnings, newWarnings): """ Generate diff between given two lists of warnings. @param oldWarnings: parsed old warnings @param newWarnings: parsed new warnings @return: a dict object of diff """
diffWarnings = {} for modulename in newWarnings: diffInModule = ( newWarnings[modulename] - oldWarnings.get(modulename, set())) if diffInModule: diffWarnings[modulename] = diffInModule return diffWarnings
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parseWarnings(self, result): """ Transform result in string to a dict object. @param result: a list of warnings in string @return: a dict of warnings """
warnings = {} currentModule = None warningsCurrentModule = [] for line in result.splitlines(): if line.startswith(self.prefixModuleName): # Save results for previous module if currentModule: warnings[currentModule] = set(warningsCurrentModule) # Initial results for current module moduleName = line.replace(self.prefixModuleName, "") currentModule = moduleName warningsCurrentModule = [] elif re.search(self.regexLineStart, line): warningsCurrentModule.append(line) else: if warningsCurrentModule: warningsCurrentModule[-1] += "\n" + line # Save warnings for last module if currentModule: warnings[currentModule] = set(warningsCurrentModule) return warnings
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def formatWarnings(self, warnings): """ Format warnings to a list of results. @param warnings: a dict of warnings produced by parseWarnings @return: a list of warnings in string """
lines = [] for modulename in sorted(warnings): lines.append(self.prefixModuleName + modulename) lines.extend(sorted(warnings[modulename], key=lambda x: x.split(":")[1])) return "\n".join(lines)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_N50(readlengths): """Calculate read length N50. Based on https://github.com/PapenfussLab/Mungo/blob/master/bin/fasta_stats.py """
return readlengths[np.where(np.cumsum(readlengths) >= 0.5 * np.sum(readlengths))[0][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 remove_length_outliers(df, columnname): """Remove records with length-outliers above 3 standard deviations from the median."""
return df[df[columnname] < (np.median(df[columnname]) + 3 * np.std(df[columnname]))]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ave_qual(quals, qround=False, tab=errs_tab(128)): """Calculate average basecall quality of a read. Receive the integer quality scores of a read and return the average quality for that read First convert Phred scores to probabilities, calculate average error probability convert average back to Phred scale """
if quals: mq = -10 * log(sum([tab[q] for q in quals]) / len(quals), 10) if qround: return round(mq) else: return mq else: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_stats(datadfs, outputfile, names=[]): """Call calculation functions and write stats file. This function takes a list of DataFrames, and will create a column for each in the tab separated output. """
if outputfile == 'stdout': output = sys.stdout else: output = open(outputfile, 'wt') stats = [Stats(df) for df in datadfs] features = { "Number of reads": "number_of_reads", "Total bases": "number_of_bases", "Total bases aligned": "number_of_bases_aligned", "Median read length": "median_read_length", "Mean read length": "mean_read_length", "Read length N50": "n50", "Average percent identity": "average_identity", "Median percent identity": "median_identity", "Active channels": "active_channels", "Mean read quality": "mean_qual", "Median read quality": "median_qual", } max_len = max([len(k) for k in features.keys()]) try: max_num = max(max([len(str(s.number_of_bases)) for s in stats]), max([len(str(n)) for n in names])) + 6 except ValueError: max_num = max([len(str(s.number_of_bases)) for s in stats]) + 6 output.write("{:<{}}{}\n".format('General summary:', max_len, " ".join(['{:>{}}'.format(n, max_num) for n in names]))) for f in sorted(features.keys()): try: output.write("{f:{pad}}{v}\n".format( f=f + ':', pad=max_len, v=feature_list(stats, features[f], padding=max_num))) except KeyError: pass if all(["quals" in df for df in datadfs]): long_features = { "Top 5 longest reads and their mean basecall quality score": ["top5_lengths", range(1, 6)], "Top 5 highest mean basecall quality scores and their read lengths": ["top5_quals", range(1, 6)], "Number, percentage and megabases of reads above quality cutoffs": ["reads_above_qual", [">Q" + str(q) for q in stats[0].qualgroups]], } for lf in sorted(long_features.keys()): output.write(lf + "\n") for i in range(5): output.write("{}:\t{}\n".format( long_features[lf][1][i], feature_list(stats, long_features[lf][0], index=i)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def errorRecorder(self, lineNumber, offset, text, check): """ A function to override report_error in pycodestyle. And record output warnings. @param lineNumber: line number @param offset: column offset @param text: warning message @param check: check object in pycodestyle """
code = text.split(" ")[0] lineOffset = self.report.line_offset self.warnings.append((lineOffset + lineNumber, offset + 1, code, text))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """ Run pycodestyle checker and record warnings. """
# Set a stream to replace stdout, and get results in it stdoutBak = sys.stdout streamResult = StringIO() sys.stdout = streamResult try: pycodestyle.Checker.check_all(self) finally: sys.stdout = stdoutBak
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _outputMessages(self, warnings, node): """ Map pycodestyle results to messages in pylint, then output them. @param warnings: it should be a list of tuple including line number and message id """
if not warnings: # No warnings were found return for warning in warnings: linenum, offset, msgidInPyCodeStyle, text = warning if text.startswith(msgidInPyCodeStyle): # If the PyCodeStyle code is at the start of the text, trim it out text = text[len(msgidInPyCodeStyle) + 1:] if msgidInPyCodeStyle in self.mapPyCodeStyleMessages: msgid, patternArguments = self.mapPyCodeStyleMessages[msgidInPyCodeStyle] if (not self.pycodestyleEnabled and msgid in self.standardPyCodeStyleMessages): continue arguments = [] if patternArguments: matchResult = re.search(patternArguments, text) if matchResult: arguments = matchResult.groups() self.add_message(msgid, line=linenum, args=arguments, node=node)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_level_from_string(str_level): """ Returns the proper log level core based on a given string :param str_level: Log level string :return: The log level code """
levels = { 'CRITICAL': logging.CRITICAL, 'ERROR': logging.ERROR, 'WARNING': logging.WARNING, 'INFO': logging.INFO, 'DEBUG': logging.DEBUG, } try: return levels[str_level.upper()] except KeyError: pass except AttributeError: if str_level in [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL]: return str_level return logging.NOTSET
<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_config_from_package(package): """ Breaks a package string in module and class. :param package: A package string. :return: A config dict with class and module. """
package_x = package.split('.') package_conf = {} package_conf['class'] = package_x[-1] package_conf['module'] = '.'.join(package_x[:-1][:]) return package_conf
<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_class_from_module(module, class_name): """ Returns a class from a module and a class name parameters. This function is used by get_class_from_config and get_class_from_name. Example: :param basestring module: The module name. :param basestring class_name: The class name. :return: The class resolved by the module and class name provided. """
import importlib module = importlib.import_module(module) return getattr(module, class_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 load_yaml_config_file(path): """ Returns the parsed structure from a yaml config file. :param path: Path where the yaml file is located. :return: The yaml configuration represented by the yaml file. """
result = None with open(path, 'r') as steam: result = yaml.safe_load(steam) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_config(config, config_data): """ Populates config with data from the configuration data dict. It handles components, data, log, management and session sections from the configuration data. :param config: The config reference of the object that will hold the configuration data from the config_data. :param config_data: The configuration data loaded from a configuration file. """
if 'components' in config_data: process_components_config_section(config, config_data['components']) if 'data' in config_data: process_data_config_section(config, config_data['data']) if 'log' in config_data: process_log_config_section(config, config_data['log']) if 'management' in config_data: process_management_config_section(config, config_data['management']) if 'session' in config_data: process_session_config_section(config, config_data['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 process_app_config(config, config_data): """ Populates config with data from the configuration data dict. It handles everything that process_config does plus application section. :param config: The config reference of the object that will hold the configuration data from the config_data. :param config_data: The configuration data loaded from a configuration file. """
process_config(config, config_data) # If apps is on config data, this is running o multi app mode if 'apps' in config_data: config.app['multi'] = True process_apps_config_session(config, config_data['apps']) else: # If not the app definition is on the firenado config file if 'app' in config_data: process_app_config_section(config, config_data['app'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_app_config_section(config, app_config): """ Processes the app section from a configuration data dict. :param config: The config reference of the object that will hold the configuration data from the config_data. :param app_config: App section from a config data dict. """
if 'addresses' in app_config: config.app['addresses'] = app_config['addresses'] if 'component' in app_config: config.app['component'] = app_config['component'] if 'data' in app_config: if 'sources' in app_config['data']: config.app['data']['sources'] = app_config['data']['sources'] if 'id' in app_config: config.app['id'] = app_config['id'] if 'login' in app_config: if 'urls' in app_config['login']: for url in app_config['login']['urls']: config.app['login']['urls'][url['name']] = url['value'] if 'pythonpath' in app_config: config.app['pythonpath'] = app_config['pythonpath'] if 'port' in app_config: config.app['port'] = app_config['port'] if 'process' in app_config: if 'num_processes' in app_config['process']: config.app['process']['num_processes'] = app_config[ 'process']['num_processes'] if 'url_root_path' in app_config: root_url = app_config['url_root_path'].strip() if root_url[0] == "/": root_url = root_url[1:] if root_url == "": root_url = None config.app['url_root_path'] = root_url if 'settings' in app_config: config.app['settings'] = app_config['settings'] if 'socket' in app_config: config.app['socket'] = app_config['socket'] if 'static_path' in app_config: config.app['static_path'] = app_config['static_path'] if 'static_url_prefix' in app_config: config.app['static_url_prefix'] = app_config['static_url_prefix'] if 'type' in app_config: config.app['type'] = app_config['type'] if 'types' in app_config: for app_type in app_config['types']: app_type['launcher'] = get_config_from_package( app_type['launcher']) config.app['types'][app_type['name']] = app_type if 'wait_before_shutdown' in app_config: config.app['wait_before_shutdown'] = app_config['wait_before_shutdown']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_components_config_section(config, components_config): """ Processes the components section from a configuration data dict. :param config: The config reference of the object that will hold the configuration data from the config_data. :param components_config: Data section from a config data dict. """
for component_config in components_config: if 'id' not in component_config: raise Exception('The component %s was defined without an id.' % component_config) component_id = component_config['id'] if component_id not in config.components: config.components[component_id] = {} config.components[component_id]['enabled'] = False config.components[component_id]['config'] = {} if 'class' in component_config: class_config_x = component_config['class'].split('.') config.components[component_id]['class'] = class_config_x[-1] config.components[component_id]['module'] = '.'.join( class_config_x[:-1]) if 'enabled' in component_config: config.components[component_id]['enabled'] = bool( component_config['enabled'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_data_config_section(config, data_config): """ Processes the data configuration section from the configuration data dict. :param config: The config reference of the object that will hold the configuration data from the config_data. :param data_config: Data configuration section from a config data dict. """
if 'connectors' in data_config: for connector in data_config['connectors']: config.data['connectors'][ connector['name']] = get_config_from_package( connector['class']) if 'sources' in data_config: if data_config['sources']: for source in data_config['sources']: config.data['sources'][source['name']] = source del config.data['sources'][source['name']]['name']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_log_config_section(config, log_config): """ Processes the log section from a configuration data dict. :param config: The config reference of the object that will hold the configuration data from the config_data. :param log_config: Log section from a config data dict. """
if 'format' in log_config: config.log['format'] = log_config['format'] if 'level' in log_config: config.log['level'] = log_level_from_string(log_config['level'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_management_config_section(config, management_config): """ Processes the management section from a configuration data dict. :param config: The config reference of the object that will hold the configuration data from the config_data. :param management_config: Management section from a config data dict. """
if 'commands' in management_config: for command in management_config['commands']: config.management['commands'].append(command)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_session_config_section(config, session_config): """ Processes the session section from the configuration data dict. :param config: The config reference of the object that will hold the configuration data from the config_data. :param session_config: Session configuration section from a config data dict. """
# Setting session type as file by default config.session['type'] = 'file' if 'enabled' in session_config: config.session['enabled'] = session_config['enabled'] if 'type' in session_config: config.session['type'] = session_config['type'] if config.session['type'] == 'file': if 'path' in session_config: config.session['file']['path'] = session_config['path'] if config.session['type'] == 'redis': if 'data' in session_config: if 'source' in session_config['data']: config.session['redis']['data']['source'] = session_config[ 'data']['source'] if 'handlers' in session_config: for handler in session_config['handlers']: handler_class_x = handler['class'].split('.') handler['class'] = handler_class_x[-1] handler['module'] = '.'.join(handler_class_x[:-1][:]) config.session['handlers'][handler['name']] = handler del config.session['handlers'][handler['name']]['name'] if 'encoders' in session_config: for encoder in session_config['encoders']: encoder_class_x = encoder['class'].split('.') encoder['encoder'] = encoder_class_x[-1] encoder['class'] = encoder_class_x[-1] encoder['module'] = '.'.join(encoder_class_x[:-1][:]) config.session['encoders'][encoder['name']] = encoder del config.session['encoders'][encoder['name']]['name'] if 'id_generators' in session_config: for generator in session_config['id_generators']: generator_ref_x = generator['function'].split('.') generator['function'] = generator_ref_x[-1] generator['module'] = '.'.join(generator_ref_x[:-1][:]) config.session['id_generators'][generator['name']] = generator del config.session['id_generators'][generator['name']]['name'] if 'name' in session_config: config.session['name'] = session_config['name'] if 'life_time' in session_config: config.session['life_time'] = session_config['life_time'] if 'callback_hiccup' in session_config: config.session['callback_hiccup'] = session_config['callback_hiccup'] if 'callback_time' in session_config: config.session['callback_time'] = session_config['callback_time'] if 'purge_limit' in session_config: config.session['purge_limit'] = session_config['purge_limit']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _open(self, db, writeAccess=False): """ Handles simple, SQL specific connection creation. This will not have to manage thread information as it is already managed within the main open method for the SQLBase class. :param db | <orb.Database> :return <variant> | backend specific database connection """
if not pymysql: raise orb.errors.BackendNotFound('psycopg2 is not installed.') # create the python connection try: return pymysql.connect(db=db.name(), user=db.username(), passwd=db.password(), host=(db.writeHost() if writeAccess else db.host()) or 'localhost', port=db.port() or 3306, cursorclass=pymysql.cursors.DictCursor) except pymysql.OperationalError as err: log.exception('Failed to connect to postgres') raise orb.errors.ConnectionFailed()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_script(script_path, session, handle_command=None, handle_line=None): """ Run a script file using a valid sqlalchemy session. Based on https://bit.ly/2CToAhY. See also sqlalchemy transaction control: https://bit.ly/2yKso0A :param script_path: The path where the script is located :param session: A sqlalchemy session to execute the sql commands from the script :param handle_command: Function to handle a valid command :param handle_line: Function to handle a valid line :return: """
logger.debug("Opening script %s." % script_path) with open(script_path, "r") as stream: sql_command = "" for line in stream: # Ignore commented lines if not line.startswith("--") and line.strip("\n"): # Append line to the command string if handle_line is not None: logger.debug("Calling the handle line function for: " "%s." % line) line = handle_line(line) sql_command = "%s%s" % (sql_command, line.strip("\n")) # If the command string ends with ";", it is a full statement if sql_command.endswith(";"): # Try to execute statement and commit it try: if handle_command is not None: logger.debug("Calling the handle command function " "for: %s." % sql_command) sql_command = handle_command(sql_command) session.execute(text(sql_command)) # Assert in case of error except Exception as e: session.rollback() raise e # Finally, clear command string finally: sql_command = "" 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 run_from_command_line(): """ Run Firenado's management commands from a command line """
for commands_conf in firenado.conf.management['commands']: logger.debug("Loading %s commands from %s." % ( commands_conf['name'], commands_conf['module'] )) exec('import %s' % commands_conf['module']) command_index = 1 for arg in sys.argv[1:]: command_index += 1 if arg[0] != "-": break parser = FirenadoArgumentParser(prog=os.path.split(sys.argv[0])[1], add_help=False) parser.add_argument("-h", "--help", default=argparse.SUPPRESS) parser.add_argument("command", default="help", help="Command to executed") try: namespace = parser.parse_args(sys.argv[1:command_index]) if not command_exists(namespace.command): show_command_line_usage(parser) else: run_command(namespace.command, sys.argv[command_index-1:]) except FirenadoArgumentError: show_command_line_usage(parser, 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 get_command_header(parser, usage_message="", usage=False): """ Return the command line header :param parser: :param usage_message: :param usage: :return: The command header """
loader = template.Loader(os.path.join( firenado.conf.ROOT, 'management', 'templates', 'help')) return loader.load("header.txt").generate( parser=parser, usage_message=usage_message, usage=usage, firenado_version=".".join(map(str, firenado.__version__))).decode( sys.stdout.encoding)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def show_command_line_usage(parser, usage=False): """ Show the command line help """
help_header_message = get_command_header(parser, "command", usage) loader = template.Loader(os.path.join( firenado.conf.ROOT, 'management', 'templates', 'help')) command_template = " {0.name:15}{0.description:40}" help_message = loader.load("main_command_help.txt").generate( command_categories=command_categories, command_template=command_template ).decode(sys.stdout.encoding) # TODO: This print has to go. Use proper stream instead(stdout or stderr) print(''.join([help_header_message, help_message]))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def command_exists(command): """ Check if the given command was registered. In another words if it exists. """
for category, commands in iteritems(command_categories): for existing_command in commands: if existing_command.match(command): 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 run_command(command, args): """ Run all tasks registered in a command. """
for category, commands in iteritems(command_categories): for existing_command in commands: if existing_command.match(command): existing_command.run(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 check(self, value, namespace): """ See whether the TypeVar is bound for the first time or is met with _exactly_ the same type as previously. That type must also obey the TypeVar's bound, if any. Everything else is a type error. """
return namespace.is_compatible(self.typevar, type(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 check_lines(self, lines, i): """ check lines have less than a maximum number of characters. It ignored lines with long URLs. """
maxChars = self.config.max_line_length for line in lines.splitlines(): if len(line) > maxChars: if 'http://' in line or 'https://' in line: continue self.add_message('C0301', line=i, args=(len(line), maxChars)) i += 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 to_representation(self, obj): """ Represent data for the field. """
many = isinstance(obj, collections.Iterable) \ or isinstance(obj, models.Manager) \ and not isinstance(obj, dict) assert self.serializer is not None \ and issubclass(self.serializer, serializers.ModelSerializer), ( "Bad serializer defined %s" % self.serializer ) extra_params = {} if issubclass(self.serializer, ModelPermissionsSerializer): extra_params['cached_allowed_fields'] =\ self.parent.cached_allowed_fields ser = self.serializer(obj, context=self.context, many=many, **extra_params) return ser.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 setRemoveAction(self, action): """ Sets the remove action that should be taken when a model is removed from the collection generated by this reverse lookup. Valid actions are "unset" or "delete", any other values will raise an exception. :param action: <str> """
if action not in ('unset', 'delete'): raise orb.errors.ValidationError('The remove action must be either "unset" or "delete"') else: self.__removeAction = action
<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, typevar, its_type): """ Binds typevar to the type its_type. Binding occurs on the instance if the typevar is a TypeVar of the generic type of the instance, on call level otherwise. """
assert type(typevar) == tg.TypeVar if self.is_generic_in(typevar): self.bind_to_instance(typevar, its_type) else: self._ns[typevar] = its_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 binding_of(self, typevar): """Returns the type the typevar is bound to, or None."""
if typevar in self._ns: return self._ns[typevar] if self._instance_ns and typevar in self._instance_ns: return self._instance_ns[typevar] 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 _checkCopyright(self, text, node): """ Check whether the module has copyright header. @param text: codes of the module @param node: node of the module """
if not re.search(br"%s\s*\n\s*%s" % self.commentsCopyright, text): self.add_message('W9001', node=node)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_message(self, msg): """ Manage message of different type and in the context of path. """
if msg.msg_id in self.messagesAllowed: super(LimitedReporter, self).handle_message(msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unregister(self, obj=None): """ Unregisters the object from the system. If None is supplied, then all objects will be unregistered :param obj: <str> or <orb.Database> or <orb.Schema> or None """
if obj is None: self.__databases.clear() self.__schemas.clear() elif isinstance(obj, orb.Schema): self.__schemas.pop(obj.name(), None) elif isinstance(obj, orb.Database): if obj == self.__current_db: self.__current_db = None self.__databases.pop(obj.name(), None) else: self.__current_db = None self.__schemas.pop(obj, None) self.__databases.pop(obj, 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 page(self, number, **context): """ Returns the records for the current page, or the specified page number. If a page size is not specified, then this record sets page size will be used. :param pageno | <int> pageSize | <int> :return <orb.RecordSet> """
size = max(0, self.context(**context).pageSize) if not size: return self.copy() else: return self.copy(page=number, pageSize=size)
<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(self, event): """ Processes a load event by setting the properties of this record to the data restored from the database. :param event: <orb.events.LoadEvent> """
if not event.data: return context = self.context() schema = self.schema() dbname = schema.dbname() clean = {} for col, value in event.data.items(): try: model_dbname, col_name = col.split('.') except ValueError: col_name = col model_dbname = dbname # make sure the value we're setting is specific to this model try: column = schema.column(col_name) except orb.errors.ColumnNotFound: column = None if model_dbname != dbname or (column in clean and isinstance(clean[column], Model)): continue # look for preloaded reverse lookups and pipes elif not column: self.__preload[col_name] = value # extract the value from the database else: value = column.dbRestore(value, context=context) clean[column] = value # update the local values with WriteLocker(self.__dataLock): for col, val in clean.items(): default = val if not isinstance(val, dict) else val.copy() self.__values[col.name()] = (default, val) self.__loaded.add(col) if self.processEvent(event): self.onLoad(event)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def changes(self, columns=None, recurse=True, flags=0, inflated=False): """ Returns a dictionary of changes that have been made to the data from this record. :return { <orb.Column>: ( <variant> old, <variant> new), .. } """
output = {} is_record = self.isRecord() schema = self.schema() columns = [schema.column(c) for c in columns] if columns else \ schema.columns(recurse=recurse, flags=flags).values() context = self.context(inflated=inflated) with ReadLocker(self.__dataLock): for col in columns: old, curr = self.__values.get(col.name(), (None, None)) if col.testFlag(col.Flags.ReadOnly): continue elif not is_record: old = None check_old = col.restore(old, context) check_curr = col.restore(curr, context) try: different = check_old != check_curr except StandardError: different = True if different: output[col] = (check_old, check_curr) return output
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def context(self, **context): """ Returns the lookup options for this record. This will track the options that were used when looking this record up from the database. :return <orb.LookupOptions> """
output = orb.Context(context=self.__context) if self.__context is not None else orb.Context() output.update(context) return output
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, **context): """ Removes this record from the database. If the dryRun \ flag is specified then the command will be logged and \ not executed. :note From version 0.6.0 on, this method now accepts a mutable keyword dictionary of values. You can supply any member value for either the <orb.LookupOptions> or <orb.Context>, as well as the keyword 'lookup' to an instance of <orb.LookupOptions> and 'options' for an instance of the <orb.Context> :return <int> """
if not self.isRecord(): return 0 event = orb.events.DeleteEvent(record=self, context=self.context(**context)) if self.processEvent(event): self.onDelete(event) if event.preventDefault: return 0 if self.__delayed: self.__delayed = False self.read() with WriteLocker(self.__dataLock): self.__loaded.clear() context = self.context(**context) conn = context.db.connection() _, count = conn.delete([self], context) # clear out the old values if count == 1: col = self.schema().column(self.schema().idColumn()) with WriteLocker(self.__dataLock): self.__values[col.name()] = (None, None) 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 markLoaded(self, *columns): """ Tells the model to treat the given columns as though they had been loaded from the database. :param columns: (<str>, ..) """
schema = self.schema() columns = {schema.column(col) for col in columns} column_names = {col.name() for col in columns} with WriteLocker(self.__dataLock): for key, (old_value, new_value) in self.__values.items(): if key in column_names: self.__values[key] = (new_value, new_value) self.__loaded.update(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 isRecord(self, db=None): """ Returns whether or not this database table record exists in the database. :return <bool> """
if db is not None: same_db = db == self.context().db if db is None or same_db: col = self.schema().idColumn() with ReadLocker(self.__dataLock): return (col in self.__loaded) and (self.__values[col.name()][0] is not None) else: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, values=None, after=None, before=None, **context): """ Commits the current change set information to the database, or inserts this object as a new record into the database. This method will only update the database if the record has any local changes to it, otherwise, no commit will take place. If the dryRun flag is set, then the SQL will be logged but not executed. :param values: None or dictionary of values to update before save :param after: <orb.Model> || None (optional) if provided, this save call will be delayed until after the given record has been saved, triggering a PostSaveEvent callback :param before: <orb.Model> || None (optional) if provided, this save call will be delayed until before the given record is about to be saved, triggering a PreSaveEvent callback :note From version 0.6.0 on, this method now accepts a mutable keyword dictionary of values. You can supply any member value for either the <orb.LookupOptions> or <orb.Context>, 'options' for an instance of the <orb.Context> :return <bool> success """
# specify that this save call should be performed after the save of # another record, useful for chaining events if after is not None: callback = orb.events.Callback(self.save, values=values, **context) after.addCallback(orb.events.PostSaveEvent, callback, record=after, once=True) return callback # specify that this save call should be performed before the save # of another record, useful for chaining events elif before is not None: callback = orb.events.Callback(self.save, values=values, **context) after.addCallback(orb.events.PreSaveEvent, callback, record=after, once=True) return callback if values is not None: self.update(values, **context) # create the commit options context = self.context(**context) new_record = not self.isRecord() # create the pre-commit event changes = self.changes(columns=context.columns) event = orb.events.PreSaveEvent(record=self, context=context, newRecord=new_record, changes=changes) if self.processEvent(event): self.onPreSave(event) if event.preventDefault: return event.result # check to see if we have any modifications to store if not (self.isModified() and self.validate()): return False conn = context.db.connection() if not self.isRecord(): records, _ = conn.insert([self], context) if records: event = orb.events.LoadEvent(record=self, data=records[0]) self._load(event) else: conn.update([self], context) # mark all the data as committed cols = [self.schema().column(c).name() for c in context.columns or []] with WriteLocker(self.__dataLock): for col_name, (_, value) in self.__values.items(): if not cols or col_name in cols: self.__values[col_name] = (value, value) # create post-commit event event = orb.events.PostSaveEvent(record=self, context=context, newRecord=new_record, changes=changes) if self.processEvent(event): self.onPostSave(event) 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 update(self, values, **context): """ Updates the model with the given dictionary of values. :param values: <dict> :param context: <orb.Context> :return: <int> """
schema = self.schema() column_updates = {} other_updates = {} for key, value in values.items(): try: column_updates[schema.column(key)] = value except orb.errors.ColumnNotFound: other_updates[key] = value # update the columns in order for col in sorted(column_updates.keys(), key=lambda x: x.order()): self.set(col, column_updates[col], **context) # update the other values for key, value in other_updates.items(): try: self.set(key, value, **context) except orb.errors.ColumnValidationError: pass return len(values)
<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, columns=None): """ Validates the current record object to make sure it is ok to commit to the database. If the optional override dictionary is passed in, then it will use the given values vs. the one stored with this record object which can be useful to check to see if the record will be valid before it is committed. :param overrides | <dict> :return <bool> """
schema = self.schema() if not columns: ignore_flags = orb.Column.Flags.Virtual | orb.Column.Flags.ReadOnly columns = schema.columns(flags=~ignore_flags).values() use_indexes = True else: use_indexes = False # validate the column values values = self.values(key='column', columns=columns) for col, value in values.items(): if not col.validate(value): return False # valide the index values if use_indexes: for index in self.schema().indexes().values(): if not index.validate(self, values): return False 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 addCallback(cls, eventType, func, record=None, once=False): """ Adds a callback method to the class. When an event of the given type is triggered, any registered callback will be executed. :param eventType: <str> :param func: <callable> """
callbacks = cls.callbacks() callbacks.setdefault(eventType, []) callbacks[eventType].append((func, record, once))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def callbacks(cls, eventType=None): """ Returns a list of callback methods that can be invoked whenever an event is processed. :return: {subclass of <Event>: <list>, ..} """
key = '_{0}__callbacks'.format(cls.__name__) try: callbacks = getattr(cls, key) except AttributeError: callbacks = {} setattr(cls, key, callbacks) return callbacks.get(eventType, []) if eventType is not None else 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 create(cls, values, **context): """ Shortcut for creating a new record for this table. :param values | <dict> :return <orb.Table> """
schema = cls.schema() model = cls # check for creating inherited classes from a sub class polymorphic_columns = schema.columns(flags=orb.Column.Flags.Polymorphic) if polymorphic_columns: polymorphic_column = polymorphic_columns.values()[0] schema_name = values.get(polymorphic_column.name(), schema.name()) if schema_name and schema_name != schema.name(): schema = orb.system.schema(schema_name) if not schema: raise orb.errors.ModelNotFound(schema=schema_name) else: model = schema.model() column_values = {} collector_values = {} for key, value in values.items(): obj = schema.collector(key) or schema.column(key) if isinstance(obj, orb.Collector): collector_values[key] = value else: column_values[key] = value # create the new record with column values (values stored on this record) record = model(context=orb.Context(**context)) record.update(column_values) record.save() # save any collector values after the model is generated (values stored on other records) record.update(collector_values) return record