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...
<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 subroutin...
<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]...
<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 diff...
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 ...
<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 r...
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_p...
<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("...
<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 l...
#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. ...
<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 t...
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: ...
<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 depe...
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: ...
<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 ...
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 ...
<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 c...
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, w...
<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 u...
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 >=...
<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 corr...
#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: #U...
<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._c...
<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 ...
<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: _head...
<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: ...
<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: ...
<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 ...
<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_num...
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...
<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 s...
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....
<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 allow...
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) ...
<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 Se...
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) r...
<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 ...
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) exc...
<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: ...
<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 KE...
<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(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 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 ...
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...
<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/repositorie...
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 + sp...
<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...
_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_s...
<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...
<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...
<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 noth...
<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, onl...
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.sp...
<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 elem...
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 an...
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: T...
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.n...
# 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.nu...
# 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_element...
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 r...
<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...
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': ...
<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 :rty...
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 filen...
<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), ...
<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...
<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, ...
<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) ...
<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, 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 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...
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...
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 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_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.BinLo...
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): s...
<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 (pymysql...
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...
<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 d...
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 = ...
<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....
<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 s...
<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 f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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, plea...