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 find_docstring(self): """Sets the docstring of this interface using the docstrings of its embedded module procedures that it is an interface for. """
#The docstrings for the interface are compiled from the separate docstrings #of the module procedures it is an interface for. We choose the first of these #procedures by convention and copy its docstrings over. #Just use the very first embedded method that isn't None and has a docstring. if self.first and len(self.docstring) == 0: self.docstring = self.first.docstring
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def describe(self): """Returns a home-grown description that includes a summary of the calling interface for all the module procedures embedded in this interface. """
#Interfaces are tricky because we can have an arbitrary number of embedded procedures #that each have different calling interfaces and return types. We are trying to #summarize that information in a single interface. Interfaces can't mix executable #types; they are either all subroutines or all functions. self.find_docstring() if not self.subroutine: #We have a return type to worry about, compile it from all the targets ret_type = [] for target in self.targets: if target.returns not in ret_type: ret_type.append(target.returns) ret_text = ', '.join(ret_type) else: ret_text = "" #The list of types it accepts is constructed the same way for functions and subroutines. act_type = [] for target in self.targets: param = target.ordered_parameters[0] if param.strtype not in act_type: act_type.append(param.strtype) act_text = ', '.join(act_type) if self.subroutine: return "SUMMARY: {} | ACCEPTS: {}".format(self.summary, act_text) else: return "SUMMARY: {} | RETURNS: {} | ACCEPTS: {}".format(self.summary, ret_text, act_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 first(self): """Returns the first module procedure embedded in the interface that has a valid instance of a CodeElement. """
if self._first is None: for target in self.targets: if target is not None: self._first = target break else: self._first = False return self._first
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def targets(self): """Provides an ordered list of CodeElement instances for each of the embedded module procedures in the generic interface. """
if self._targets is None: self._targets = {} for key in self.procedures: element = self.module.parent.get_executable(key) if element is not None: self._targets[key] = element else: self._targets[key] = None msg.warn("unable to locate module procedure {}".format(key) + " in interface {}".format(self.name)) return [self._targets[key] for key in self.procedures]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_dependencies(self): """Returns a list of other modules that this module and its members and executables depend on in order to run correctly. This differs from the self.dependencies attribute that just hase explicit module names from the 'use' clauses. """
result = [self.module.name] #First we look at the explicit use references from this module and all #its dependencies until the chain terminates. stack = self.needs while len(stack) > 0: module = stack.pop() if module in result: continue self.parent.load_dependency(module, True, True, False) if module in self.parent.modules: for dep in self.parent.modules[module].needs: modname = dep.split(".")[0] if modname not in result: result.append(modname) if modname not in stack: stack.append(modname) #Add any incidentals from the automatic construction of code. These can be from #executables that use special precision types without importing them or from #derived types. Same applies to the local members of this module. for ekey, anexec in list(self.executables.items()): for dep in anexec.search_dependencies(): if dep is not None and dep not in result: result.append(dep) for member in list(self.members.values()): dep = member.dependency() if dep is not None and dep not in result: result.append(dep) 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 compile_path(self): """Returns the file path to this module taking the pre-processing into account. If the module requires pre-processing, the extension is reported as F90; otherwise, the regular self.filepath is returned. """
if not self.precompile: return self.filepath else: if self._compile_path is None: segs = self.filepath.split('.') segs.pop() segs.append("F90") self._compile_path = '.'.join(segs) return self._compile_path
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def all_to_public(self): """Sets all members, types and executables in this module as public as long as it doesn't already have the 'private' modifier. """
if "private" not in self.modifiers: def public_collection(attribute): for key in self.collection(attribute): if key not in self.publics: self.publics[key.lower()] = 1 public_collection("members") public_collection("types") public_collection("executables")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rt_update(self, statement, linenum, mode, modulep, lineparser): """Uses the specified line parser to parse the given statement. :arg statement: a string of lines that are part of a single statement. :arg linenum: the line number of the first line in the statement relative to the entire module contents. :arg mode: either 'insert', 'replace' or 'delete' :arg modulep: an instance of ModuleParser for handling the changes to the instance of the module. :arg lineparser: a line parser instance for dealing with new instances of types or executables that are add using only a signature. """
#Most of the module is body, since that includes everything inside #of the module ... end module keywords. Since docstrings are handled #at a higher level by line parser, we only need to deal with the body #Changes of module name are so rare that we aren't going to bother with them. section = self.find_section(self.module.charindex(linenum, 1)) if section == "body": modulep.rt_update(statement, self, mode, linenum, lineparser)
<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_dependency_element(self, symbol): """Checks if the specified symbol is the name of one of the methods that this module depends on. If it is, search for the actual code element and return it."""
for depend in self.dependencies: if "." in depend: #We know the module name and the executable name, easy if depend.split(".")[1] == symbol.lower(): found = self.parent.get_executable(depend) break else: #We only have the name of an executable or interface, we have to search #the whole module for the element. fullname = "{}.{}".format(depend, symbol) if self.parent.get_executable(fullname) is not None: found = self.parent.get_executable(fullname) break if self.parent.get_interface(fullname) is not None: found = self.parent.get_interface(fullname) break else: return None return found
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def completions(self, symbol, attribute, recursive = False): """Finds all possible symbol completions of the given symbol that belong to this module and its dependencies. :arg symbol: the code symbol that needs to be completed. :arg attribute: one of ['dependencies', 'publics', 'members', 'types', 'executables'] for specifying which collections to search. :arg result: the possible completions collected so far in the search. """
possible = [] for ekey in self.collection(attribute): if symbol in ekey: possible.append(ekey) #Try this out on all the dependencies as well to find all the possible #completions. if recursive: for depkey in self.dependencies: #Completions need to be fast. If the module for the parent isn't already #loaded, we just ignore the completions it might have. if depkey in self.parent.modules: possible.extend(self.parent.modules[depkey].completions(symbol, attribute)) return possible
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def needs(self): """Returns a unique list of module names that this module depends on."""
result = [] for dep in self.dependencies: module = dep.split(".")[0].lower() if module not in result: result.append(module) 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 _filter_execs(self, isSubroutine): """Filters the executables in the dictionary by their type."""
result = {} for key in self.executables: if (isinstance(self.executables[key], Subroutine) and isSubroutine) or \ (isinstance(self.executables[key], Function) and not isSubroutine): result[key] = self.executables[key] 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 warn(self, collection): """Checks the module for documentation and best-practice warnings."""
super(CodeElement, self).warn(collection) if not "implicit none" in self.modifiers: collection.append("WARNING: implicit none not set in {}".format(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 collection(self, attribute): """Returns the collection corresponding the attribute name."""
return { "dependencies": self.dependencies, "publics": self.publics, "members": self.members, "types": self.types, "executables": self.executables, "interfaces": self.interfaces }[attribute]
<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_refstring(self, string): """Updates the refstring that represents the original string that the module was parsed from. Also updates any properties or attributes that are derived from the refstring."""
self.refstring = string self._lines = [] self._contains_index = None self.changed = True #The only other references that become out of date are the contains #and preamble attributes which are determined by the parsers. #Assuming we did everything right with the rt update, we should be #able to just use the new contains index to update those. icontains = self.contains_index ichar = self.charindex(icontains, 0) self.preamble = string[:ichar] self.contains = string[ichar + 9:]
<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_elements(self, line, column, charcount, docdelta=0): """Updates all the element instances that are children of this module to have new start and end charindex values based on an operation that was performed on the module source code. :arg line: the line number of the *start* of the operation. :arg column: the column number of the start of the operation. :arg charcount: the total character length change from the operation. :arg docdelta: the character length of changes made to types/execs that are children of the module whose docstrings external to their definitions were changed. """
target = self.charindex(line, column) + charcount #We are looking for all the instances whose *start* attribute lies #after this target. Then we update them all by that amount. #However, we need to be careful because of docdelta. If an elements #docstring contains the target, we don't want to update it. if line < self.contains_index: for t in self.types: if self._update_char_check(self.types[t], target, docdelta): self._element_charfix(self.types[t], charcount) for m in self.members: if self.members[m].start > target: self.members[m].start += charcount self.members[m].end += charcount self._contains_index = None else: for iexec in self.executables: if self._update_char_check(self.executables[iexec], target, docdelta): self._element_charfix(self.executables[iexec], charcount)
<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_char_check(self, element, target, docdelta): """Checks whether the specified element should have its character indices updated as part of real-time updating."""
if docdelta != 0: if (element.docstart <= target and element.docend >= target - docdelta): return True else: return element.absstart > target else: return element.absstart > target
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _element_charfix(self, element, charcount): """Updates the start and end attributes by charcount for the element."""
element.start += charcount element.docstart += charcount element.end += charcount element.docend += charcount
<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_element(self, line, column): """Gets the instance of the element who owns the specified line and column."""
ichar = self.charindex(line, column) icontains = self.contains_index result = None if line < icontains: #We only need to search through the types and members. maxstart = 0 tempresult = None for t in self.types: if ichar >= self.types[t].absstart: if self.types[t].absstart > maxstart: maxstart = self.types[t].absstart tempresult = self.types[t] #This takes the possibility of an incomplete type into account if (tempresult is not None and (ichar <= tempresult.end or tempresult.incomplete)): result = tempresult if not result: #Members only span a single line usually and don't get added #without an end token. for m in self.members: if (ichar >= self.members[m].start and ichar <= self.members[m].end): result = self.members[m] break else: #We only need to search through the executables tempresult = None maxstart = 0 for iexec in self.executables: if (ichar >= self.executables[iexec].absstart): if self.executables[iexec].absstart > maxstart: maxstart = self.executables[iexec].absstart tempresult = self.executables[iexec] if tempresult is not None and (ichar <= tempresult.end or tempresult.incomplete): result = tempresult if result is None: #We must be in the text of the module, return the module return self else: 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 update_embedded(self, attribute): """Updates the elements in the module 'result' that have character indices that are a subset of another element. These correspond to cases where the type or subroutine is declared within another subroutine. :attr attribute: the name of the collection to update over. """
#The parser doesn't handle embeddings deeper than two levels. coll = self.collection(attribute) keys = list(coll.keys()) for key in keys: element = coll[key] new_parent = self.find_embedded_parent(element) if new_parent is not None: #Update the parent of the embedded element, add it to the collection #of the parent element and then delete it from the module's collection. element.parent = new_parent if attribute == "types": new_parent.types[key] = element else: new_parent.executables[key] = element del coll[key]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def charindex(self, line, column): """Gets the absolute character index of the line and column in the continuous string."""
#Make sure that we have chars and lines to work from if this #gets called before linenum() does. if len(self._lines) == 0: self.linenum(1) if line < len(self._chars): return self._chars[line - 1] + column else: return len(self.refstring)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def linenum(self, index): """Gets the line number of the character at the specified index. If the result is unknown, -1 is returned."""
if len(self._lines) == 0 and self.refstring != "": self._lines = self.refstring.split("\n") #Add one for the \n that we split on for each line self._chars = [ len(x) + 1 for x in self._lines ] #Remove the last line break since it doesn't exist self._chars[-1] -= 1 #Now we want to add up the number of characters in each line #as the lines progress so that it is easy to search for the #line of a single character index total = 0 for i in range(len(self._chars)): total += self._chars[i] self._chars[i] = total if len(self._lines) > 0: #Now, find the first index where the character value is >= index result = -1 i = 0 while result == -1 and i < len(self._chars): if index <= self._chars[i]: result = [ i, self._chars[i] - index] i += 1 return result else: return [ -1, -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_valid(self): """ check if input is valid """
for k,input in self.inputs.items(): if k in self.valid_opts: for param in self.valid_opts[k]: if param is None or input is None: return True elif type(param) is str and '+' in param: if re.search(r'^'+param,str(input)): return True elif type(param) is bool and type(input) is bool: return True elif type(param) is list and type(input) is list: return True else: if str(input).lower() == str(param): return True raise ValueError("Invalid input for '%s' parameter. Options are: %s" % (k,' '.join(["'%s'," % str(o) for o in self.valid_opts[k]]) )) else: raise ValueError("Invalid parameter for '%s'. Params are: %s" % (self.__class__.__name__,', '.join(["'%s'" % p for p in self.valid_opts.keys()]) ))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_policy(self,defaultHeaders): """ if policy in default but not input still return """
if self.inputs is not None: for k,v in defaultHeaders.items(): if k not in self.inputs: self.inputs[k] = v return self.inputs else: return self.inputs
<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_header(self): """ return header dict """
try: self.check_valid() _header_list = [] for k,v in self.inputs.items(): if v is None: return {self.__class__.__name__.replace('_','-'):None} elif k == 'value': _header_list.insert(0,str(v)) elif isinstance(v,bool): if v is True: _header_list.append(k) else: _header_list.append('%s=%s' % (k,str(v))) return {self.__class__.__name__.replace('_','-'):'; '.join(_header_list)} except Exception, e: raise
<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_policy(self,defaultHeaders): """ rewrite update policy so that additional pins are added and not overwritten """
if self.inputs is not None: for k,v in defaultHeaders.items(): if k not in self.inputs: self.inputs[k] = v if k == 'pins': self.inputs[k] = self.inputs[k] + defaultHeaders[k] return self.inputs else: return self.inputs
<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_header(self): """ rewrite return header dict for HPKP """
try: self.check_valid() _header_list = [] for k,v in self.inputs.items(): if v is None: return {self.__class__.__name__.replace('_','-'):None} elif k == 'value': _header_list.insert(0,str(v)) elif isinstance(v,bool): if v is True: _header_list.append(k) elif type(v) is list: lambda v: len(v)>0, [_header_list.append(''.join(['pin-%s=%s' % (pink,pinv) for pink, pinv in pin.items()])) for pin in v] else: _header_list.append('%s=%s' % (k,str(v))) return {self.__class__.__name__.replace('_','-'):'; '.join(_header_list)} except Exception, e: raise
<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_policy(self,cspDefaultHeaders): """ add items to existing csp policies """
try: self.check_valid(cspDefaultHeaders) if self.inputs is not None: for p,l in self.inputs.items(): cspDefaultHeaders[p] = cspDefaultHeaders[p]+ list(set(self.inputs[p]) - set(cspDefaultHeaders[p])) return cspDefaultHeaders else: return self.inputs except Exception, e: raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rewrite_policy(self,cspDefaultHeaders): """ fresh csp policy """
try: self.check_valid(cspDefaultHeaders) if self.inputs is not None: for p,l in cspDefaultHeaders.items(): if p in self.inputs: cspDefaultHeaders[p] = self.inputs[p] else: cspDefaultHeaders[p] = [] return cspDefaultHeaders else: return self.inputs except Exception, e: raise
<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_header(self): """ return CSP header dict """
encapsulate = re.compile("|".join(['^self','^none','^unsafe-inline','^unsafe-eval','^sha[\d]+-[\w=-]+','^nonce-[\w=-]+'])) csp = {} for p,array in self.inputs.items(): csp[p] = ' '.join(["'%s'" % l if encapsulate.match(l) else l for l in array]) return {self.header:'; '.join(['%s %s' % (k, v) for k, v in csp.items() if v != ''])}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def invoke(self, dirname, filenames=set(), linter_configs=set()): """ Main entrypoint for all plugins. Returns results in the format of: {'filename': { 'line_number': [ 'error1', 'error2' ] } } """
retval = defaultdict(lambda: defaultdict(list)) if len(filenames): extensions = [e.lstrip('.') for e in self.get_file_extensions()] filenames = [f for f in filenames if f.split('.')[-1] in extensions] if not filenames: # There were a specified set of files, but none were the right # extension. Different from the else-case below. return {} to_find = ' -o '.join(['-samefile "%s"' % f for f in filenames]) else: to_find = ' -o '.join(['-name "*%s"' % ext for ext in self.get_file_extensions()]) cmd = 'find %s -path "*/%s" | xargs %s' % ( dirname, to_find, self.get_command( dirname, linter_configs=linter_configs)) result = self.executor(cmd) for line in result.split('\n'): output = self.process_line(dirname, line) if output is not None: filename, lineno, messages = output if filename.startswith(dirname): filename = filename[len(dirname) + 1:] retval[filename][lineno].append(messages) return retval
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean_already_reported(self, comments, file_name, position, message): """ message is potentially a list of messages to post. This is later converted into a string. """
for comment in comments: if ((comment['path'] == file_name and comment['position'] == position and comment['user']['login'] == self.requester.username)): return [m for m in message if m not in comment['body']] return 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 convert_message_to_string(self, message): """Convert message from list to string for GitHub API."""
final_message = '' for submessage in message: final_message += '* {submessage}\n'.format(submessage=submessage) return final_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 post_comment(self, message): """ Comments on an issue, not on a particular line. """
report_url = ( 'https://api.github.com/repos/%s/issues/%s/comments' % (self.repo_name, self.pr_number) ) result = self.requester.post(report_url, {'body': message}) if result.status_code >= 400: log.error("Error posting comment to github. %s", result.json()) 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 get(self, request, *args, **kwargs): """ Handles GET requests and instantiates a blank version of the form. """
form_class = self.get_form_class() form = self.get_form(form_class) if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def queryset(self, request, queryset): form = self.get_form(request) """ That's the trick - we create self.form when django tries to get our queryset. This allows to create unbount and bound form in the single place. """
self.form = form start_date = form.start_date() end_date = form.end_date() if form.is_valid() and (start_date or end_date): args = self.__get_filterargs( start=start_date, end=end_date, ) return queryset.filter(**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 clone_repo(self, repo_name, remote_repo, ref): """Clones the given repo and returns the Repository object."""
self.shallow_clone = False dirname, repo = self.set_up_clone(repo_name, remote_repo) if os.path.isdir("%s/.git" % dirname): log.debug("Updating %s to %s", repo.download_location, dirname) self.executor( "cd %s && git checkout master" % dirname) self.pull(dirname) else: log.debug("Cloning %s to %s", repo.download_location, dirname) self.executor( "git clone %s %s" % (repo.download_location, dirname)) if remote_repo is not None: log.debug("Pulling remote branch from %s", remote_repo.url) self.add_remote(dirname, remote_repo.name, remote_repo.url) self.pull(dirname) return repo
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare_object(obj, using="default"): """ Returns a Python dictionary representation of the given object, expected to be a Model object with an associated SearchIndex. The optional argument `using` specifies the backend to use from the Haystack connections list. """
model = obj.__class__ unified_index = connections[using].get_unified_index() index = unified_index.get_index(model) prepped_data = index.full_prepare(obj) final_data = {} for key, value in prepped_data.items(): final_data[key] = connections[using].get_backend()._from_python(value) return final_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 get_model(app_label, model_name): """ Fetches a Django model using the app registry. This doesn't require that an app with the given app label exists, which makes it safe to call when the registry is being populated. All other methods to access models might raise an exception about the registry not being ready yet. Raises LookupError if model isn't found. """
try: from django.apps import apps from django.core.exceptions import AppRegistryNotReady except ImportError: # Django < 1.7 from django.db import models return models.get_model(app_label, model_name) try: return apps.get_model(app_label, model_name) except AppRegistryNotReady: if apps.apps_ready and not apps.models_ready: # If this function is called while `apps.populate()` is # loading models, ensure that the module that defines the # target model has been imported and try looking the model up # in the app registry. This effectively emulates # `from path.to.app.models import Model` where we use # `Model = get_model('app', 'Model')` instead. app_config = apps.get_app_config(app_label) # `app_config.import_models()` cannot be used here because it # would interfere with `apps.populate()`. import_module("%s.%s" % (app_config.name, "models")) # In order to account for case-insensitivity of model_name, # look up the model through a private API of the app registry. return apps.get_registered_model(app_label, model_name) else: # This must be a different case (e.g. the model really doesn't # exist). We just re-raise the exception. raise
<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(): """ Main entrypoint for the command-line app. """
args = app.parse_args(sys.argv[1:]) params = args.__dict__ params.update(**load_config(args.config_file)) if params['debug']: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig() try: imhotep = app.gen_imhotep(**params) except NoGithubCredentials: log.error("You must specify a GitHub username or password.") return False except NoCommitInfo: log.error("You must specify a commit or PR number") return False except UnknownTools as e: log.error("Didn't find any of the specified linters.") log.error("Known linters: %s", ', '.join(e.known)) return False imhotep.invoke()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_relative_file(filename): """Returns contents of the given file, which path is supposed relative to this module."""
with open(join(dirname(abspath(__file__)), filename)) as f: return f.read()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def diff_commit(self, commit, compare_point=None): """ Returns a diff as a string from the current HEAD to the given commit. """
# @@@ This is a security hazard as compare-point is user-passed in # data. Doesn't matter until we wrap this in a service. if compare_point is not None: self.apply_commit(compare_point) return self.executor("cd %s && git diff %s" % (self.dirname, 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(self, key=NOT_SET, index=NOT_SET, d=None): """Return value with given key or index. If no value is found, return d (None by default). """
if index is NOT_SET and key is not NOT_SET: try: index, value = self._dict[key] except KeyError: return d else: return value elif index is not NOT_SET and key is NOT_SET: try: key, value = self._list[index] except IndexError: return d else: return value else: raise KEY_EQ_INDEX_ERROR
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pop_key(self, key, has_default): """Remove an element by key."""
try: index, value = self._dict.pop(key) except KeyError: if has_default: return None, None else: raise key2, value2 = self._list.pop(index) assert key is key2 assert value is value2 return index, 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 _pop_index(self, index, has_default): """Remove an element by index, or last element."""
try: if index is NOT_SET: index = len(self._list) - 1 key, value = self._list.pop() else: key, value = self._list.pop(index) if index < 0: index += len(self._list) + 1 except IndexError: if has_default: return None, None, None else: raise index2, value2 = self._dict.pop(key) assert index == index2 assert value is value2 return key, index, 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 fast_pop(self, key=NOT_SET, index=NOT_SET): """Pop a specific item quickly by swapping it to the end. Remove value with given key or index (last item by default) fast by swapping it to the last place first. Changes order of the remaining items (item that used to be last goes to the popped location). Returns tuple of (poped_value, new_moved_index, moved_key, moved_value). If key is not found raises KeyError or IndexError. Runs in O(1). """
if index is NOT_SET and key is not NOT_SET: index, popped_value = self._dict.pop(key) elif key is NOT_SET: if index is NOT_SET: index = len(self._list) - 1 key, popped_value2 = self._list[-1] else: key, popped_value2 = self._list[index] if index < 0: index += len(self._list) index2, popped_value = self._dict.pop(key) assert index == index2 else: raise KEY_AND_INDEX_ERROR if key == self._list[-1][0]: # The item we're removing happens to be the last in the list, # no swapping needed _, popped_value2 = self._list.pop() assert popped_value is popped_value2 return popped_value, len(self._list), key, popped_value else: # Swap the last item onto the deleted spot and # pop the last item from the list self._list[index] = self._list[-1] moved_key, moved_value = self._list.pop() self._dict[moved_key] = (index, moved_value) return popped_value, index, moved_key, moved_value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_pr_info(requester, reponame, number): "Returns the PullRequest as a PRInfo object" resp = requester.get( 'https://api.github.com/repos/%s/pulls/%s' % (reponame, number)) return PRInfo(resp.json())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all_tags_no_auth(image_name, branch=None): """ Try to get the tags without any authentication, this does work only for public images. GET /v1/repositories/<namespace>/<repository_name>/tags :param image_name: The docker image name :param branch: The branch to filter by :return: A list of Version instances, latest first """
output = [] logging.debug('Getting %s without authentication' % image_name) spec = '/%s/tags' % image_name headers = {'Accept': 'application/json', 'Content-Type': 'application/json'} try: # This works well for any public images: response = requests.get(API_URL + spec, headers=headers) except RequestException, re: raise DockerTagNamingException('HTTP request exception "%s"' % re) if response.status_code == 401: msg = ('Received unexpected status code %s from the registry' ' REST API, the image is private.') raise AuthException(msg % response.status_code) if response.status_code != 200: msg = ('Received unexpected status code %s from the registry' ' REST API, the image might not exist') raise DockerTagNamingException(msg % response.status_code) try: json_data = response.json() except ValueError: msg = 'JSON decode failed! Raw data is: "%s". Please report a bug.' raise DockerTagNamingException(msg % (response.content[:25]).strip()) try: tag_names = [tag_info['name'] for tag_info in json_data] except Exception: msg = ('The JSON data does not contain the expected format!' ' Raw data is: "%s". Please report a bug.') raise DockerTagNamingException(msg % (response.content[:25]).strip()) for tag_name in tag_names: try: version = version_parser(tag_name) except Exception, e: msg = 'Ignoring version tag "%s" with incorrect format: "%s"' logging.debug(msg % (tag_name, e)) continue if branch is not None: if version.branch != branch: continue output.append(version) def sort_func(version_a, version_b): return cmp(version_b.version_number, version_a.version_number) output.sort(sort_func) 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 start_publishing(mysql_settings, **kwargs): """Start publishing MySQL row-based binlog events to blinker signals Args: mysql_settings (dict): information to connect to mysql via pymysql **kwargs: The additional kwargs will be passed to :py:class:`pymysqlreplication.BinLogStreamReader`. """
_logger.info('Start publishing from %s with:\n%s' % (mysql_settings, kwargs)) kwargs.setdefault('server_id', random.randint(1000000000, 4294967295)) kwargs.setdefault('freeze_schema', True) # connect to binlog stream stream = pymysqlreplication.BinLogStreamReader( mysql_settings, only_events=[row_event.DeleteRowsEvent, row_event.UpdateRowsEvent, row_event.WriteRowsEvent], **kwargs ) """:type list[RowsEvent]""" for event in stream: # ignore non row events if not isinstance(event, row_event.RowsEvent): continue _logger.debug('Send binlog signal "%s@%s.%s"' % ( event.__class__.__name__, event.schema, event.table )) signals.binlog_signal.send(event, stream=stream) signals.binlog_position_signal.send((stream.log_file, stream.log_pos))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extractFromHTML(html, blur=5): """ Extracts text from HTML content. """
#html = html.encode('utf-8', errors='ignore') try: html = unicode(html, errors='ignore') except TypeError: pass assert isinstance(html, unicode) # Create memory file. _file = StringIO() # Convert html to text. f = formatter.AbstractFormatter(formatter.DumbWriter(_file)) p = TextExtractor() p.pathBlur = blur p.feed(html) p.close() text = p.get_plaintext() # Remove stand-alone punctuation. text = re.sub("\s[\(\),;\.\?\!](?=\s)", " ", text).strip() # Compress whitespace. text = re.sub("[\n\s]+", " ", text).strip() # Remove consequetive dashes. text = re.sub("\-{2,}", "", text).strip() # Remove consequetive periods. text = re.sub("\.{2,}", "", 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 tidyHTML(dirtyHTML): """ Runs an arbitrary HTML string through Tidy. """
try: from tidylib import tidy_document except ImportError as e: raise ImportError(("%s\nYou need to install pytidylib.\n" + "e.g. sudo pip install pytidylib") % e) options = { 'output-xhtml':1, #add_xml_decl=1,#option in tidy but not pytidylib 'indent':1, 'tidy-mark':1, #'char-encoding':'utf8', 'char-encoding':'raw', } html, errors = tidy_document(dirtyHTML, options=options) return html
<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_key(s, pattern="%s.txt"): """ Generates the cache key for the given string using the content in pattern to format the output string """
h = hashlib.sha1() #h.update(s) h.update(s.encode('utf-8')) return pattern % h.hexdigest()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cache_get(cache_dir, cache_key, default=None): """ Returns the content of a cache item or the given default """
filename = os.path.join(cache_dir, cache_key) if os.path.isfile(filename): with open(filename, 'r') as f: return f.read() return 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 cache_set(cache_dir, cache_key, content): """ Creates a new cache file in the cache directory """
filename = os.path.join(cache_dir, cache_key) with open(filename, 'w') as f: f.write(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 cache_info(cache_dir, cache_key): """ Returns the cache files mtime or 0 if it does not exists """
filename = os.path.join(cache_dir, cache_key) return os.path.getmtime(filename) if os.path.exists(filename) else 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 fetch(url, timeout=5, userAgent=None, only_mime_types=None): """ Retrieves the raw content of the URL. """
headers = {} if userAgent: headers['User-agent'] = str(userAgent) else: headers['User-agent'] = ua.random #request = Request(url=url, headers=headers) #response = urlopen(request, timeout=timeout) response = requests.get(url, headers=headers, timeout=timeout) # Return nothing of the content isn't one of the target mime-types. if only_mime_types: assert isinstance(only_mime_types, (tuple, list)) # Check for mimetype by looking at pattern in the URL. # Not super accurate, but very fast. ct, mt_encoding = mimetypes.guess_type(url) # Then check for mimetype by actually requesting the resource and # looking at the response. # More accurate, but slower since we actually have to send a request. if not ct: response_info = response.info() ct = (response_info.getheader('Content-Type') or '').split(';')[0] #TODO:if still undefined, use magic.Magic(mime=True).from_file(url)? if ct not in only_mime_types: return try: #return response.read() return response.text except httplib.IncompleteRead as e: # This should rarely happen, and is often the fault of the server # sending a malformed response. #TODO:just abandon all content and return '' instead? return e.partial
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extractFromURL(url, cache=False, cacheDir='_cache', verbose=False, encoding=None, filters=None, userAgent=None, timeout=5, blur=5, ignore_robotstxt=False, only_mime_types=None, raw=False): """ Extracts text from a URL. Parameters: url := string Remote URL or local filename where HTML will be read. cache := bool True=store and retrieve url from cache False=always retrieve url from the web cacheDir := str Directory where cached url contents will be stored. verbose := bool True=print logging messages False=print no output encoding := string The encoding of the page contents. If none given, it will attempt to guess the encoding. See http://docs.python.org/howto/unicode.html for further info on Python Unicode and encoding support. filters := string Comma-delimited list of filters to apply before parsing. only_mime_types := list of strings A list of mime-types to limit parsing to. If the mime-type of the raw-content retrieved does not match one of these, a value of None will be returned. """
blur = int(blur) try: import chardet except ImportError as e: raise ImportError(("%s\nYou need to install chardet.\n" + \ "e.g. sudo pip install chardet") % e) if only_mime_types and isinstance(only_mime_types, six.text_type): only_mime_types = only_mime_types.split(',') # Load url from cache if enabled. if cache: if not os.path.isdir(cacheDir): cache_perms = 488 # 750 in octal, '-rwxr-x---' os.makedirs(cacheDir, cache_perms) cache_key = generate_key(url) cached_content = cache_get(cacheDir, cache_key) if cached_content: return cached_content if not ignore_robotstxt: if not check_robotstxt(url, cache, cacheDir, userAgent=userAgent): if verbose: print("Request denied by robots.txt") return '' # Otherwise download the url. if verbose: print('Reading %s...' % url) html = fetch( url, timeout=timeout, userAgent=userAgent, only_mime_types=only_mime_types) if not html: return '' # If no encoding guess given, then attempt to determine # encoding automatically. if not encoding: if isinstance(html, unicode): html = html.encode('utf8', 'replace') encoding_opinion = chardet.detect(html) encoding = encoding_opinion['encoding'] if verbose: print('Using encoding %s.' % encoding) # Save raw contents to cache if enabled. if verbose: print('Read %i characters.' % len(html)) if cache: raw_key = generate_key(url, "%s.raw") cache_set(cacheDir, raw_key, html) # Apply filters. if filters: filter_names = map(str.strip, filters.split(',')) for filter_name in filter_names: fltr = get_filter(filter_name) html = fltr(html) # Clean up HTML. html = tidyHTML(html) if verbose: print('Extracted %i characters.' % len(html)) # Convert to Unicode. if not html: return '' html = unicode(html, encoding=encoding, errors='replace') if raw: return html # Extract text from HTML. res = extractFromHTML(html, blur=blur) assert isinstance(res, unicode) # Save extracted text to cache if enabled. res = res.encode(encoding, 'ignore') if cache: cache_set(cacheDir, cache_key, res) return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy(self): """Create a shallow copy of self. This runs in O(len(self.num_unique_elements())) """
out = self._from_iterable(None) out._dict = self._dict.copy() out._size = self._size 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 nlargest(self, n=None): """List the n most common elements and their counts. List is from the most common to the least. If n is None, the list all element counts. Run time should be O(m log m) where m is len(self) Args: n (int): The number of elements to return """
if n is None: return sorted(self.counts(), key=itemgetter(1), reverse=True) else: return heapq.nlargest(n, self.counts(), key=itemgetter(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 from_mapping(cls, mapping): """Create a bag from a dict of elem->count. Each key in the dict is added if the value is > 0. Raises: ValueError: If any count is < 0. """
out = cls() for elem, count in mapping.items(): out._set_count(elem, count) 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 is_subset(self, other): """Check that every element in self has a count <= in other. Args: other (Set) """
if isinstance(other, _basebag): for elem, count in self.counts(): if not count <= other.count(elem): return False else: for elem in self: if self.count(elem) > 1 or elem not in other: 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 _iadd(self, other): """Add all of the elements of other to self. if isinstance(it, _basebag): This runs in O(it.num_unique_elements()) else: This runs in O(len(it)) """
if isinstance(other, _basebag): for elem, count in other.counts(): self._increment_count(elem, count) else: for elem in other: self._increment_count(elem, 1) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _iand(self, other): """Set multiplicity of each element to the minimum of the two collections. if isinstance(other, _basebag): This runs in O(other.num_unique_elements()) else: This runs in O(len(other)) """
# TODO do we have to create a bag from the other first? if not isinstance(other, _basebag): other = self._from_iterable(other) for elem, old_count in set(self.counts()): other_count = other.count(elem) new_count = min(other_count, old_count) self._set_count(elem, new_count) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ior(self, other): """Set multiplicity of each element to the maximum of the two collections. if isinstance(other, _basebag): This runs in O(other.num_unique_elements()) else: This runs in O(len(other)) """
# TODO do we have to create a bag from the other first? if not isinstance(other, _basebag): other = self._from_iterable(other) for elem, other_count in other.counts(): old_count = self.count(elem) new_count = max(other_count, old_count) self._set_count(elem, new_count) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ixor(self, other): """Set self to the symmetric difference between the sets. if isinstance(other, _basebag): This runs in O(other.num_unique_elements()) else: This runs in O(len(other)) """
if isinstance(other, _basebag): for elem, other_count in other.counts(): count = abs(self.count(elem) - other_count) self._set_count(elem, count) else: # Let a = self.count(elem) and b = other.count(elem) # if a >= b then elem is removed from self b times leaving a - b # if a < b then elem is removed from self a times then added (b - a) # times leaving a - a + (b - a) = b - a for elem in other: try: self._increment_count(elem, -1) except ValueError: self._increment_count(elem, 1) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _isub(self, other): """Discard the elements of other from self. if isinstance(it, _basebag): This runs in O(it.num_unique_elements()) else: This runs in O(len(it)) """
if isinstance(other, _basebag): for elem, other_count in other.counts(): try: self._increment_count(elem, -other_count) except ValueError: self._set_count(elem, 0) else: for elem in other: try: self._increment_count(elem, -1) except ValueError: pass return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_all(self, other): """Remove all of the elems from other. Raises a ValueError if the multiplicity of any elem in other is greater than in self. """
if not self.is_superset(other): raise ValueError('Passed collection is not a subset of this bag') self.discard_all(other)
<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,path): """Given a path to a library, load it."""
try: # Darwin requires dlopen to be called with mode RTLD_GLOBAL instead # of the default RTLD_LOCAL. Without this, you end up with # libraries not being loadable, resulting in "Symbol not found" # errors if sys.platform == 'darwin': return ctypes.CDLL(path, ctypes.RTLD_GLOBAL) else: return ctypes.cdll.LoadLibrary(path) except OSError,e: raise ImportError(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 git_ls_files(*cmd_args): """Run ``git ls-files`` in the top-level project directory. Arguments go directly to execution call. :return: set of file names :rtype: :class:`set` """
cmd = ['git', 'ls-files'] cmd.extend(cmd_args) return set(subprocess.check_output(cmd).splitlines())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _lint(): """Run lint and return an exit code."""
# Flake8 doesn't have an easy way to run checks using a Python function, so # just fork off another process to do it. # Python 3 compat: # - The result of subprocess call outputs are byte strings, meaning we need # to pass a byte string to endswith. project_python_files = [filename for filename in get_project_files() if filename.endswith(b'.py')] retcode = subprocess.call( ['flake8', '--max-complexity=10'] + project_python_files) if retcode == 0: print_success_message('No style errors') return retcode
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def login(self): """Login v2ex, otherwise we can't complete the mission."""
response = self.session.get(self.signin_url, verify=False) user_param, password_param = self._get_hashed_params(response.text) login_data = { user_param: self.config['username'], password_param: self.config['password'], 'once': self._get_once(response.text), 'next': '/' } headers = {'Referer': 'https://www.v2ex.com/signin'} self.session.post(self.signin_url, headers=headers, data=login_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 _get_once(self, page_text): """Get once which will be used when you login."""
soup = BeautifulSoup(page_text, 'html.parser') once = soup.find('input', attrs={'name': 'once'})['value'] return 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 get_money(self): """Complete daily mission then get the money."""
response = self.session.get(self.mission_url, verify=False) soup = BeautifulSoup(response.text, 'html.parser') onclick = soup.find('input', class_='super normal button')['onclick'] url = onclick.split('=', 1)[1][2:-2] if url == '/balance': return "You have completed the mission today." else: headers = {'Referer': 'https://www.v2ex.com/mission/daily'} data = {'once': url.split('=')[-1]} self.session.get('https://www.v2ex.com'+url, verify=False, headers=headers, data=data) balance = self._get_balance() return balance
<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_balance(self): """Get to know how much you totally have and how much you get today."""
response = self.session.get(self.balance_url, verify=False) soup = BeautifulSoup(response.text, 'html.parser') first_line = soup.select( "table.data tr:nth-of-type(2)")[0].text.strip().split('\n') total, today = first_line[-2:] logging.info('%-26sTotal:%-8s', today, total) return '\n'.join([u"Today: {0}".format(today), "Total: {0}".format(total)])
<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_last(self): """Get to know how long you have kept signing in."""
response = self.session.get(self.mission_url, verify=False) soup = BeautifulSoup(response.text, 'html.parser') last = soup.select('#Main div')[-1].text return last
<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_and_pos(self): """ Save current position into file """
if not self._pos_changed: return with open(self.pos_storage_filename, 'w+') as f: _pos = '%s:%s' % (self._log_file, self._log_pos) _logger.debug('Saving position %s to file %s' % (_pos, self.pos_storage_filename)) f.write(_pos) self._pos_changed = 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 _read_file_and_pos(self): """ Read last position from file, store as current position """
try: with open(self.pos_storage_filename, 'r+') as f: _pos = f.read() _logger.debug('Got position "%s" from file %s' % (_pos, self.pos_storage_filename)) if not _pos: return log_file, log_pos = _pos.split(':') try: log_file = str(log_file) log_pos = int(log_pos) except (ValueError, TypeError) as e: _logger.critical('Can not read position: %s' % e) sys.exit(13) self._log_file = log_file self._log_pos = log_pos except IOError as e: _logger.error(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 index(self, value, start=0, end=None): """Return the index of value between start and end. By default, the entire setlist is searched. This runs in O(1) Args: value: The value to find the index of start (int): The index to start searching at (defaults to 0) end (int): The index to stop searching at (defaults to the end of the list) Returns: int: The index of the value Raises: ValueError: If the value is not in the list or outside of start - end IndexError: If start or end are out of range """
try: index = self._dict[value] except KeyError: raise ValueError else: start = self._fix_neg_index(start) end = self._fix_end_index(end) if start <= index and index < end: return index else: raise ValueError
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sub_index(self, sub, start=0, end=None): """Return the index of a subsequence. This runs in O(len(sub)) Args: sub (Sequence): An Iterable to search for Returns: int: The index of the first element of sub Raises: ValueError: If sub isn't a subsequence TypeError: If sub isn't iterable IndexError: If start or end are out of range """
start_index = self.index(sub[0], start, end) end = self._fix_end_index(end) if start_index + len(sub) > end: raise ValueError for i in range(1, len(sub)): if sub[i] != self[start_index + i]: raise ValueError return start_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 pop(self, index=-1): """Remove and return the item at index."""
value = self._list.pop(index) del self._dict[value] return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def insert(self, index, value): """Insert value at index. Args: index (int): Index to insert value at value: Value to insert Raises: ValueError: If value already in self IndexError: If start or end are out of range """
if value in self: raise ValueError index = self._fix_neg_index(index) self._dict[value] = index for elem in self._list[index:]: self._dict[elem] += 1 self._list.insert(index, 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 remove(self, value): """Remove value from self. Args: value: Element to remove from self Raises: ValueError: if element is already present """
try: index = self._dict[value] except KeyError: raise ValueError('Value "%s" is not present.') else: del self[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 difference_update(self, other): """Update self to include only the difference with other."""
other = set(other) indices_to_delete = set() for i, elem in enumerate(self): if elem in other: indices_to_delete.add(i) if indices_to_delete: self._delete_values_by_index(indices_to_delete)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def symmetric_difference_update(self, other): """Update self to include only the symmetric difference with other."""
other = setlist(other) indices_to_delete = set() for i, item in enumerate(self): if item in other: indices_to_delete.add(i) for item in other: self.add(item) self._delete_values_by_index(indices_to_delete)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shuffle(self, random=None): """Shuffle all of the elements in self randomly."""
random_.shuffle(self._list, random=random) for i, elem in enumerate(self._list): self._dict[elem] = 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 sort(self, *args, **kwargs): """Sort this setlist in place."""
self._list.sort(*args, **kwargs) for index, value in enumerate(self._list): self._dict[value] = 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 swap(self, i, j): """Swap the values at indices i & j. .. versionadded:: 1.1 """
i = self._fix_neg_index(i) j = self._fix_neg_index(j) self._list[i], self._list[j] = self._list[j], self._list[i] self._dict[self._list[i]] = i self._dict[self._list[j]] = j
<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_updated_values(before_values, after_values): """ Get updated values from 2 dicts of values Args: before_values (dict): values before update after_values (dict): values after update Returns: dict: a diff dict with key is field key, value is tuple of (before_value, after_value) """
assert before_values.keys() == after_values.keys() return dict([(k, [before_values[k], after_values[k]]) for k in before_values.keys() if before_values[k] != after_values[k]])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _convert_update_row(row): """ Convert a row for update event Args: row (dict): event row data """
after_values = row['after_values'] # type: dict before_values = row['before_values'] # type: dict values = after_values return { 'values': values, 'updated_values': _get_updated_values(before_values, after_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 _rows_event_to_dict(e, stream): """ Convert RowsEvent to a dict Args: e (pymysqlreplication.row_event.RowsEvent): the event stream (pymysqlreplication.BinLogStreamReader): the stream that yields event Returns: dict: event's data as a dict """
pk_cols = e.primary_key if isinstance(e.primary_key, (list, tuple)) \ else (e.primary_key, ) if isinstance(e, row_event.UpdateRowsEvent): sig = signals.rows_updated action = 'update' row_converter = _convert_update_row elif isinstance(e, row_event.WriteRowsEvent): sig = signals.rows_inserted action = 'insert' row_converter = _convert_write_row elif isinstance(e, row_event.DeleteRowsEvent): sig = signals.rows_deleted action = 'delete' row_converter = _convert_write_row else: assert False, 'Invalid binlog event' meta = { 'time': e.timestamp, 'log_pos': stream.log_pos, 'log_file': stream.log_file, 'schema': e.schema, 'table': e.table, 'action': action, } rows = list(map(row_converter, e.rows)) for row in rows: row['keys'] = {k: row['values'][k] for k in pk_cols} return rows, meta
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on_binlog(event, stream): """ Process on a binlog event 1. Convert event instance into a dict 2. Send corresponding schema/table/signals Args: event (pymysqlreplication.row_event.RowsEvent): the event """
rows, meta = _rows_event_to_dict(event, stream) table_name = '%s.%s' % (meta['schema'], meta['table']) if meta['action'] == 'insert': sig = signals.rows_inserted elif meta['action'] == 'update': sig = signals.rows_updated elif meta['action'] == 'delete': sig = signals.rows_deleted else: raise RuntimeError('Invalid action "%s"' % meta['action']) sig.send(table_name, rows=rows, meta=meta)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deprecated(msg, dep_version): """Decorate a function, method or class to mark as deprecated. Raise DeprecationWarning and add a deprecation notice to the docstring. """
def wrapper(func): docstring = func.__doc__ or '' docstring_msg = '.. deprecated:: {version} {msg}'.format( version=dep_version, msg=msg, ) if docstring: # We don't know how far to indent this message # so instead we just dedent everything. string_list = docstring.splitlines() first_line = string_list[0] remaining = textwrap.dedent(''.join(string_list[1:])) docstring = '\n'.join([ first_line, remaining, '', docstring_msg, ]) else: docstring = docstring_msg func.__doc__ = docstring @wraps(func) def inner(*args, **kwargs): warnings.warn(msg, category=DeprecationWarning, stacklevel=2) return func(*args, **kwargs) return inner return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ranges(self, start=None, stop=None): """Generate MappedRanges for all mapped ranges. Yields: MappedRange """
_check_start_stop(start, stop) start_loc = self._bisect_right(start) if stop is None: stop_loc = len(self._keys) else: stop_loc = self._bisect_left(stop) start_val = self._values[start_loc - 1] candidate_keys = [start] + self._keys[start_loc:stop_loc] + [stop] candidate_values = [start_val] + self._values[start_loc:stop_loc] for i, value in enumerate(candidate_values): if value is not NOT_SET: start_key = candidate_keys[i] stop_key = candidate_keys[i + 1] yield MappedRange(start_key, stop_key, value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_range(self, start=None, stop=None): """Return a RangeMap for the range start to stop. Returns: A RangeMap """
return self.from_iterable(self.ranges(start, stop))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set(self, value, start=None, stop=None): """Set the range from start to stop to value."""
_check_start_stop(start, stop) # start_index, stop_index will denote the sections we are replacing start_index = self._bisect_left(start) if start is not None: # start_index == 0 prev_value = self._values[start_index - 1] if prev_value == value: # We're setting a range where the left range has the same # value, so create one big range start_index -= 1 start = self._keys[start_index] if stop is None: new_keys = [start] new_values = [value] stop_index = len(self._keys) else: stop_index = self._bisect_right(stop) stop_value = self._values[stop_index - 1] stop_key = self._keys[stop_index - 1] if stop_key == stop and stop_value == value: new_keys = [start] new_values = [value] else: new_keys = [start, stop] new_values = [value, stop_value] self._keys[start_index:stop_index] = new_keys self._values[start_index:stop_index] = new_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 delete(self, start=None, stop=None): """Delete the range from start to stop from self. Raises: KeyError: If part of the passed range isn't mapped. """
_check_start_stop(start, stop) start_loc = self._bisect_right(start) - 1 if stop is None: stop_loc = len(self._keys) else: stop_loc = self._bisect_left(stop) for value in self._values[start_loc:stop_loc]: if value is NOT_SET: raise KeyError((start, stop)) # this is inefficient, we've already found the sub ranges self.set(NOT_SET, start=start, stop=stop)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def empty(self, start=None, stop=None): """Empty the range from start to stop. Like delete, but no Error is raised if the entire range isn't mapped. """
self.set(NOT_SET, start=start, stop=stop)
<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(self): """Get the start key of the first range. None if RangeMap is empty or unbounded to the left. """
if self._values[0] is NOT_SET: try: return self._keys[1] except IndexError: # This is empty or everything is mapped to a single value return None else: # This is unbounded to the left return self._keys[0]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_tools(whitelist, known_plugins): """ Filter all known plugins by a whitelist specified. If the whitelist is empty, default to all plugins. """
def getpath(c): return "%s:%s" % (c.__module__, c.__class__.__name__) tools = [x for x in known_plugins if getpath(x) in whitelist] if not tools: if whitelist: raise UnknownTools(map(getpath, known_plugins)) tools = known_plugins return tools
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init(directory): """Init the config fle."""
username = click.prompt("Input your username") password = click.prompt("Input your password", hide_input=True, confirmation_prompt=True) log_directory = click.prompt("Input your log directory") if not path.exists(log_directory): sys.exit("Invalid log directory, please have a check.") config_file_path = path.join(directory, 'v2ex_config.json') config = { "username": username, "password": password, "log_directory": path.abspath(log_directory) } with open(config_file_path, 'w') as f: json.dump(config, f) click.echo("Init the config file at: {0}".format(config_file_path))