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 clean_up(group, identifier, date): """Delete all of a groups local mbox, index, and state files. :type group: str :param group: group name :type identifier: ...
#log.error('exception raised, cleaning up files.') glob_pat = '{g}.{d}.mbox*'.format(g=group, d=date) for f in glob(glob_pat): #log.error('removing {f}'.format(f=f)) try: os.remove(f) except OSError: continue glob_pat = '{id}_state.json'.format(id=identif...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def utf8_encode_str(string, encoding='UTF-8'): """Attempt to detect the native encoding of `string`, and re-encode to utf-8 :type string: str :param string: The ...
if not string: return '' src_enc = chardet.detect(string)['encoding'] try: return string.decode(src_enc).encode(encoding) except: return string.decode('ascii', errors='replace').encode(encoding)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inline_compress_chunk(chunk, level=1): """Compress a string using gzip. :type chunk: str :param chunk: The string to be compressed. :rtype: str :returns: `ch...
b = cStringIO.StringIO() g = gzip.GzipFile(fileobj=b, mode='wb', compresslevel=level) g.write(chunk) g.close() cc = b.getvalue() b.close() return cc
<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_list_of_git_directories(): """Returns a list of paths of git repos under the current directory."""
dirs = [path[0] for path in list(os.walk('.')) if path[0].endswith('.git')] dirs = ['/'.join(path.split('/')[:-1]) for path in dirs] return sorted(dirs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_git_concurrently(base_dir): """Runs the 'git status' and 'git pull' commands in threads and reports the results in a pretty table."""
os.chdir(base_dir) git_dirs = get_list_of_git_directories() print("Processing %d git repos: %s" % (len(git_dirs), ', '.join(git_dirs))) widgets = [Percentage(), ' ', Bar(), ' ', Counter(), ' ', AdaptiveETA()] pbar = ProgressBar(widgets=widgets, maxval=...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def v1_search(request, response, visid_to_dbid, config, search_engines, filters, cid, engine_name): '''Search feature collections. The route for this endpoint is: ``/dossier/v1/<content_id>/search/<search_engine_name>``. ``content_id`` can be any *profile* content identifier. (This 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 v1_fc_get(visid_to_dbid, store, cid): '''Retrieve a single feature collection. The route for this endpoint is: ``/dossier/v1/feature-collections/<content_id>``. This endpoint returns a JSON serialization of the feature collection identified by ``content_id``. ''' fc = store.get(visid_t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def v1_random_fc_get(response, dbid_to_visid, store): '''Retrieves a random feature collection from the database. The route for this endpoint is: ``GET /dossier/v1/random/feature-collection``. Assuming the database has at least one feature collection, this end point returns an array of two element...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def v1_label_put(request, response, visid_to_dbid, config, label_hooks, label_store, cid1, cid2, annotator_id): '''Store a single label. The route for this endpoint is: ``PUT /dossier/v1/labels/<content_id1>/<content_id2>/<annotator_id>``. ``content_id`` are the ids of the feature col...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def v1_label_direct(request, response, visid_to_dbid, dbid_to_visid, label_store, cid, subid=None): '''Return directly connected labels. The routes for this endpoint are ``/dossier/v1/label/<cid>/direct`` and ``/dossier/v1/label/<cid>/subtopic/<subid>/direct``. This returns all...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def v1_label_negative_inference(request, response, visid_to_dbid, dbid_to_visid, label_store, cid): '''Return inferred negative labels. The route for this endpoint is: ``/dossier/v1/label/<cid>/negative-inference``. Negative labels are 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 v1_folder_list(request, kvlclient): '''Retrieves a list of folders for the current user. The route for this endpoint is: ``GET /dossier/v1/folder``. (Temporarily, the "current user" can be set via the ``annotator_id`` query parameter.) The payload returned is a list of folder identifiers. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def v1_folder_add(request, response, kvlclient, fid): '''Adds a folder belonging to the current user. The route for this endpoint is: ``PUT /dossier/v1/folder/<fid>``. If the folder was added successfully, ``201`` status is returned. (Temporarily, the "current user" can be set via the ``annotator...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def v1_subfolder_list(request, response, kvlclient, fid): '''Retrieves a list of subfolders in a folder for the current user. The route for this endpoint is: ``GET /dossier/v1/folder/<fid>/subfolder``. (Temporarily, the "current user" can be set via the ``annotator_id`` query parameter.) 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 v1_subfolder_add(request, response, kvlclient, fid, sfid, cid, subid=None): '''Adds a subtopic to a subfolder for the current user. The route for this endpoint is: ``PUT /dossier/v1/folder/<fid>/subfolder/<sfid>/<cid>/<subid>``. ``fid`` is the folder identifier, e.g., ``My_Fol...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def v1_subtopic_list(request, response, kvlclient, fid, sfid): '''Retrieves a list of items in a subfolder. The route for this endpoint is: ``GET /dossier/v1/folder/<fid>/subfolder/<sfid>``. (Temporarily, the "current user" can be set via the ``annotator_id`` query parameter.) The payload ret...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def v1_folder_delete(request, response, kvlclient, fid, sfid=None, cid=None, subid=None): '''Deletes a folder, subfolder or item. The routes for this endpoint are: * ``DELETE /dossier/v1/folder/<fid>`` * ``DELETE /dossier/v1/folder/<fid>/subfolder/<sfid>`` * ``DELETE /dossier/...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def v1_folder_rename(request, response, kvlclient, fid_src, fid_dest, sfid_src=None, sfid_dest=None): '''Rename a folder or a subfolder. The routes for this endpoint are: * ``POST /dossier/v1/<fid_src>/rename/<fid_dest>`` * ``POST /dossier/v1/<fid_src>/subfolder/<sfid_src>/rename/...
<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_query_param(url, param, value): '''Returns a new URL with the given query parameter set to ``value``. ``value`` may be a list.''' scheme, netloc, path, qs, frag = urlparse.urlsplit(url) params = urlparse.parse_qs(qs) params[param] = value qs = urllib.urlencode(params, doseq=True) re...
<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_status(self): """utility method to get the status of a slicing job resource, but also used to initialize slice objects by location"""
if self._state in ["processed", "error"]: return self._state get_resp = requests.get(self.location, cookies={"session": self.session}) self._state = get_resp.json()["status"] self.slice_time = get_resp.json()["slice_time"] return self._state
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _to_json(self): """ Gets a dict of this object's properties so that it can be used to send a dump to the client """
return dict(( (k, v) for k, v in self.__dict__.iteritems() if k != 'server'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def change_name(self, username): """ changes the username to given username, throws exception if username used """
self.release_name() try: self.server.register_name(username) except UsernameInUseException: logging.log(', '.join(self.server.registered_names)) self.server.register_name(self.name) raise self.name = username
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_name(self, username): """ register a name """
if self.is_username_used(username): raise UsernameInUseException('Username {username} already in use!'.format(username=username)) self.registered_names.append(username)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def release_name(self, username): """ release a name and add it to the temp list """
self.temp_names.append(username) if self.is_username_used(username): self.registered_names.remove(username)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _do_exit(self, cmd, args): """\ Exit shell. exit | C-D Exit to the parent shell. exit root | end Exit to the root shell. exit all Exit to the command line. "...
if cmd == 'end': if not args: return 'root' else: self.stderr.write(textwrap.dedent('''\ end: unrecognized arguments: {} ''')).format(args) # Hereafter, cmd == 'exit'. if not 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 _complete_exit(self, cmd, args, text): """Find candidates for the 'exit' command."""
if args: return return [ x for x in { 'root', 'all', } \ if x.startswith(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 _do_history(self, cmd, args): """\ Display history. history Display history. history clear Clear history. history clearall Clear history for all shells. """
if args and args[0] == 'clear': readline.clear_history() readline.write_history_file(self.history_fname) elif args and args[0] == 'clearall': readline.clear_history() shutil.rmtree(self._temp_dir, ignore_errors = True) os.makedirs(os.path.join...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _complete_history(self, cmd, args, text): """Find candidates for the 'history' command."""
if args: return return [ x for x in { 'clear', 'clearall' } \ if x.startswith(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 __dump_stack(self): """Dump the shell stack in a human friendly way. An example output is: 0 PlayBoy 1 └── foo-prompt: foo@[] 2 └── karPROMPT: kar@[] 3 └── D...
maxdepth = len(self._mode_stack) maxdepth_strlen = len(str(maxdepth)) index_width = 4 - (-maxdepth_strlen) % 4 + 4 index_str = lambda i: '{:<{}d}'.format(i, index_width) self.stdout.write(index_str(0) + self.root_prompt) self.stdout.write('\n') tree_prefix = 'β””...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _do_help(self, cmd, args): """Display doc strings of the shell and its commands. """
print(self.doc_string()) print() # Create data of the commands table. data_unsorted = [] cls = self.__class__ for name in dir(cls): obj = getattr(cls, name) if iscommand(obj): cmds = [] for cmd in getcommands(obj):...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hazeDriver(): """ Process the command line arguments and run the appropriate haze subcommand. We want to be able to do git-style handoffs to subcommands wher...
try: (command, args) = findSubCommand(sys.argv) # If we can't construct a subcommand from sys.argv, it'll still be able # to find this haze driver script, and re-running ourself isn't useful. if os.path.basename(command) == "haze": print "Could not find a subcommand for %s" % " ".join(sys.argv...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def quoted_split(string, sep, quotes='"'): """ Split a string on the given separation character, but respecting double-quoted sections of the string. Returns an ...
# Initialize the algorithm start = None escape = False quote = False # Walk through the string for i, c in enumerate(string): # Save the start index if start is None: start = i # Handle escape sequences if escape: escape = 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 parse_ctype(ctype): """ Parse a content type. :param ctype: The content type, with corresponding parameters. :returns: A tuple of the content type and a dict...
result_ctype = None result = {} for part in quoted_split(ctype, ';'): # Extract the content type first if result_ctype is None: result_ctype = part result['_'] = part continue # OK, we have a 'key' or 'key=value' to handle; figure it # o...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _match_mask(mask, ctype): """ Determine if a content type mask matches a given content type. :param mask: The content type mask, taken from the Accept header...
# Handle the simple cases first if '*' not in mask: return ctype == mask elif mask == '*/*': return True elif not mask.endswith('/*'): return False mask_major = mask[:-2] ctype_major = ctype.split('/', 1)[0] return ctype_major == mask_major
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def best_match(requested, allowed): """ Determine the best content type to use for the request. :param ctypes: A list of the available content types. :returns: A...
requested = [parse_ctype(ctype) for ctype in quoted_split(requested, ',')] best_q = -1 best_ctype = '' best_params = {} best_match = '*/*' # Walk the list of content types for ctype in allowed: # Compare to the accept list for ctype_mask, params in requested: ...
<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_key(log_prefix, result_dict, key, value, desc="parameter"): """ Helper to set a key value in a dictionary. This function issues a warning if the key has...
if key in result_dict: LOG.warn("%s: Duplicate value for %s %r" % (log_prefix, desc, key)) # Allow the overwrite # Demand the value be quoted if len(value) <= 2 or value[0] not in ('"', "'") or value[0] != value[-1]: LOG.warn("%s: Invalid value %r for %s %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 _parse_version_rule(loader, version, verspec): """ Parse a version rule. The first token is the name of the application implementing that API version. The re...
result = dict(name=version, params={}) for token in quoted_split(verspec, ' ', quotes='"\''): if not token: continue # Convert the application if 'app' not in result: result['app'] = loader.get_app(token) continue # What remains is key="quo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_alias_rule(alias, alias_spec): """ Parse an alias rule. The first token is the canonical name of the version. The remaining tokens are key="quoted val...
result = dict(alias=alias, params={}) for token in quoted_split(alias_spec, ' ', quotes='"\''): if not token: continue # Suck out the canonical version name if 'version' not in result: result['version'] = token continue # What remains is 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 set_ctype(self, ctype, orig_ctype=None): """ Set the selected content type. Will not override the value of the content type if that has already been determin...
if self.ctype is None: self.ctype = ctype self.orig_ctype = orig_ctype
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _process(self, request, result=None): """ Process the rules for the request. :param request: The Request object provided by WebOb. :param result: The Result ...
# Allocate a result and process all the rules result = result if result is not None else Result() self._proc_uri(request, result) self._proc_ctype_header(request, result) self._proc_accept_header(request, result) 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 _proc_uri(self, request, result): """ Process the URI rules for the request. Both the desired API version and desired content type can be determined from tho...
if result: # Result has already been fully determined return # First, determine the version based on the URI prefix for prefix, version in self.uris: if (request.path_info == prefix or request.path_info.startswith(prefix + '/')): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _proc_ctype_header(self, request, result): """ Process the Content-Type header rules for the request. Only the desired API version can be determined from tho...
if result: # Result has already been fully determined return try: ctype = request.headers['content-type'] except KeyError: # No content-type header to examine return # Parse the content type ctype, params = parse_cty...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _proc_accept_header(self, request, result): """ Process the Accept header rules for the request. Both the desired API version and content type can be determi...
if result: # Result has already been fully determined return try: accept = request.headers['accept'] except KeyError: # No Accept header to examine return # Obtain the best-match content type and its parameters ctype...
<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_available_hashes(): """ Returns a tuple of the available hashes """
if sys.version_info >= (3,2): return hashlib.algorithms_available elif sys.version_info >= (2,7) and sys.version_info < (3,0): return hashlib.algorithms else: return 'md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512'
<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_defaults_for(session, user, only_for=None, detail_values=None): """ Create a sizable amount of defaults for a new user. """
detail_values = detail_values or {} if not user.openid.endswith('.fedoraproject.org'): log.warn("New user not from fedoraproject.org. No defaults set.") return # the openid is of the form USERNAME.id.fedoraproject.org nick = user.openid.split('.')[0] # TODO -- make the root her...
<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_queryset(self): # DROP_WITH_DJANGO15 """Use the same ordering as TreeManager"""
args = (self.model._mptt_meta.tree_id_attr, self.model._mptt_meta.left_attr) method = 'get_query_set' if django.VERSION < (1, 6) else 'get_queryset' return getattr(super(SectionManager, self), method)().order_by(*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 item_related_name(self): """ The ManyToMany field on the item class pointing to this class. If there is more than one field, this value will be None. """
if not hasattr(self, '_item_related_name'): many_to_many_rels = \ get_section_many_to_many_relations(self.__class__) if len(many_to_many_rels) != 1: self._item_related_name = None else: self._item_related_name = many_to_many_re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_item(self, item, field_name=None): """ Add the item to the specified section. Intended for use with items of settings.ARMSTRONG_SECTION_ITEM_MODEL. Behav...
field_name = self._choose_field_name(field_name) related_manager = getattr(item, field_name) related_manager.add(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_item(self, item, field_name=None): """ Remove the item from the specified section. Intended for use with items of settings.ARMSTRONG_SECTION_ITEM_MODE...
field_name = self._choose_field_name(field_name) related_manager = getattr(item, field_name) related_manager.remove(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 toggle_item(self, item, test_func, field_name=None): """ Toggles the section based on test_func. test_func takes an item and returns a boolean. If it returns...
if test_func(item): self.add_item(item, field_name) return True else: self.remove_item(item, field_name) return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def determine_ticks(low, high): """The function used to auto-generate ticks for an axis, based on its range of values. :param Number low: The lower bound of the ...
range_ = high - low tick_difference = 10 ** math.floor(math.log10(range_ / 1.25)) low_tick = math.floor(low / tick_difference) * tick_difference ticks = [low_tick + tick_difference] if low_tick < low else [low_tick] while ticks[-1] + tick_difference <= high: ticks.append(ticks[-1] + ti...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def x_ticks(self, *ticks): """The points on the x-axis for which there are markers and grid lines. There are default ticks, but you can pass values to this metho...
if ticks: for tick in ticks: if not is_numeric(tick): raise TypeError("'%s' is not a numeric tick" % str(tick)) self._x_ticks = tuple(sorted(ticks)) else: if self._x_ticks: return self._x_ticks 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 y_ticks(self, *ticks): """The points on the y-axis for which there are markers and grid lines. There are default ticks, but you can pass values to this metho...
if ticks: for tick in ticks: if not is_numeric(tick): raise TypeError("'%s' is not a numeric tick" % str(tick)) self._y_ticks = tuple(sorted(ticks)) else: if self._y_ticks: return self._y_ticks 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 x_grid(self, grid=None): """The horizontal lines that run accross the chart from the x-ticks. If a boolean value is given, these gridlines will be turned on ...
if grid is None: return self._x_grid else: if not isinstance(grid, bool): raise TypeError("grid must be boolean, not '%s'" % grid) self._x_grid = grid
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def y_grid(self, grid=None): """The vertical lines that run accross the chart from the y-ticks. If a boolean value is given, these gridlines will be turned on or...
if grid is None: return self._y_grid else: if not isinstance(grid, bool): raise TypeError("grid must be boolean, not '%s'" % grid) self._y_grid = grid
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def grid(self, grid): """Turns all gridlines on or off :param bool grid: turns the gridlines on if ``True``, off if ``False``"""
if not isinstance(grid, bool): raise TypeError("grid must be boolean, not '%s'" % grid) self._x_grid = self._y_grid = grid
<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_event_loop(self): """Get the event loop. This may be None or an instance of EventLoop. """
if (self._event_loop is None and threading.current_thread().name == 'MainThread'): self._event_loop = self.new_event_loop() return self._event_loop
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_event_loop(self, event_loop): """Set the event loop."""
assert event_loop is None or isinstance(event_loop, AbstractEventLoop) self._event_loop = event_loop
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def patch_datasette(): """ Monkey patching for original Datasette """
def inspect(self): " Inspect the database and return a dictionary of table metadata " if self._inspect: return self._inspect _inspect = {} files = self.files for filename in files: self.files = (filename,) path = Path(filename) ...
<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_fas(config): """ Return a fedora.client.fas2.AccountSystem object if the provided configuration contains a FAS username and password. """
global _FAS if _FAS is not None: return _FAS # In some development environments, having fas_credentials around is a # pain.. so, let things proceed here, but emit a warning. try: creds = config['fas_credentials'] except KeyError: log.warn("No fas_credentials available. ...
<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_packagers_of_package(config, package): """ Retrieve the list of users who have commit on a package. :arg config: a dict containing the fedmsg config :arg...
if not _cache.is_configured: _cache.configure(**config['fmn.rules.cache']) key = cache_key_generator(get_packagers_of_package, package) creator = lambda: _get_pkgdb2_packagers_for(config, package) return _cache.get_or_create(key, creator)
<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_packages_of_user(config, username, flags): """ Retrieve the list of packages where the specified user some acl. :arg config: a dict containing the fedmsg...
if not _cache.is_configured: _cache.configure(**config['fmn.rules.cache']) packages = [] groups = get_groups_of_user(config, get_fas(config), username) owners = [username] + ['group::' + group for group in groups] for owner in owners: key = cache_key_generator(get_packages_of_us...
<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_user_of_group(config, fas, groupname): ''' Return the list of users in the specified group. :arg config: a dict containing the fedmsg config :arg fas: a fedora.client.fas2.AccountSystem object instanciated and loged into FAS. :arg groupname: the name of the group for which we want to re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def delist(target): ''' for any "list" found, replace with a single entry if the list has exactly one entry ''' result = target if type(target) is dict: for key in target: target[key] = delist(target[key]) if type(target) is list: if len(target)==0: result = None ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def check_schema_coverage(doc, schema): ''' FORWARD CHECK OF DOCUMENT This routine looks at each element in the doc, and makes sure there is a matching 'name' in the schema at that level. ''' error_list = [] to_delete = [] for entry in doc.list_tuples(): (name, 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 sub_schema_raises(doc, schema): ''' Look for "raise_error", "raise_warning", and "raise_log" ''' error_list = [] temp_schema = schema_match_up(doc, schema) for msg in temp_schema.list_values("raise_error"): error_list.append( ("[error]", "doc", doc.seq, "'{}'".format(msg)) ) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_valid_row(cls, row): """Indicates whether or not the given row contains valid data."""
for k in row.keys(): if row[k] is None: 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 get_cursor(cls): """Return a message list cursor that returns sqlite3.Row objects"""
db = SqliteConnection.get() db.row_factory = sqlite3.Row return db.cursor()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_header(self, header_string): """ Parses the header and determines the column type and its column index. """
header_content = header_string.strip().split('\t') if len(header_content) != self._snv_enum.HEADER_LEN.value: raise MTBParserException( "Only {} header columns found, {} expected!" .format(len(header_content), self._snv_enum.HEADER_LEN.value)) counter...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_content(self, snv_entries): """ Parses SNV entries to SNVItems, objects representing the content for every entry, that can be used for further process...
if len(snv_entries) == 1: return for line in snv_entries[1:]: info_dict = self._map_info_to_col(line) self._snv_list.append(SNVItem(**info_dict))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def actions(obj, **kwargs): """ Return actions available for an object """
if 'exclude' in kwargs: kwargs['exclude'] = kwargs['exclude'].split(',') actions = obj.get_actions(**kwargs) if isinstance(actions, dict): actions = actions.values() buttons = "".join("%s" % action.render() for action in actions) return '<div class="actions">%s</div>' % buttons
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_models(self, limit=-1, offset=-1): """Get a list of models in the registry. Parameters limit : int Limit number of items in the result set offset : int...
return self.registry.list_models(limit=limit, offset=offset)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_model(self, model_id, properties, parameters, outputs, connector): """Register a new model with the engine. Expects connection information for Rabbi...
# Validate the given connector information self.validate_connector(connector) # Connector information is valid. Ok to register the model. Will raise # ValueError if model with given identifier exists. Catch duplicate # key error to transform it into a ValueError try: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_model(self, model_run, run_url): """Execute the given model run. Throws a ValueError if the given run specifies an unknown model or if the model connecto...
# Get model to verify that it exists and to get connector information model = self.get_model(model_run.model_id) if model is None: raise ValueError('unknown model: ' + model_run.model_id) # By now there is only one connector. Use the buffered connector to # avoid clo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_connector(self, connector): """Validate a given connector. Raises ValueError if the connector is not valid. Parameters connector : dict Connection i...
if not 'connector' in connector: raise ValueError('missing connector name') elif connector['connector'] != CONNECTOR_RABBITMQ: raise ValueError('unknown connector: ' + str(connector['connector'])) # Call the connector specific validator. Will raise a ValueError if ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_model(self, model_run, run_url): """Run model by sending message to RabbitMQ queue containing the run end experiment identifier. Messages are persistent ...
# Open connection to RabbitMQ server. Will raise an exception if the # server is not running. In this case we raise an EngineException to # allow caller to delete model run. try: credentials = pika.PlainCredentials(self.user, self.password) con = pika.BlockingCon...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_model(self, model_run, run_url): """Create entry in run request buffer. Parameters model_run : ModelRunHandle Handle to model run run_url : string URL fo...
# Create model run request request = RequestFactory().get_request(model_run, run_url) # Write request and connector information into buffer self.collection.insert_one({ 'connector' : self.connector, 'request' : request.to_dict() })
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_request(self, model_run, run_url): """Create request object to run model. Requests are handled by SCO worker implementations. Parameters model_run : Mode...
return ModelRunRequest( model_run.identifier, model_run.experiment_id, run_url )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def submit_error(url, user, project, area, description, extra=None, default_message=None): """Celery task for submitting errors asynchronously. :param url: strin...
LOG.debug('Creating new BugzScout instance.') client = bugzscout.BugzScout( url, user, project, area) LOG.debug('Submitting BugzScout error.') client.submit_error( description, extra=extra, default_message=default_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 apply_depth_first(nodes, func, depth=0, as_dict=False, parents=None): ''' Given a structure such as the application menu layout described above, we may want to apply an operation to each entry to create a transformed version of the structure. For example, let's convert all entries in the applic...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def apply_dict_depth_first(nodes, func, depth=0, as_dict=True, parents=None, pre=None, post=None): ''' This function is similar to the `apply_depth_first` except that it operates on the `OrderedDict`-based structure returned from `apply_depth_first` when `as_dict=True`. Note that if `as_dict` is `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 collect(nested_nodes, transform=None): ''' Return list containing the result of the `transform` function applied to each item in the supplied list of nested nodes. A custom transform function may be applied to each entry during the flattening by specifying a function through the `transform` 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 wrap_split_big_content(func_, *args, **kwargs): """ chunk the content into smaller binary blobs before inserting this function should chunk in such a way tha...
obj_dict = args[0] if len(obj_dict[CONTENT_FIELD]) < MAX_PUT: obj_dict[PART_FIELD] = False return func_(*args, **kwargs) else: return _perform_chunking(func_, *args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _only_if_file_not_exist(func_, *args, **kwargs): """ horribly non-atomic :param func_: :param args: :param kwargs: :return: """
obj_dict = args[1] conn = args[-1] try: RBF.get(obj_dict[PRIMARY_FIELD]).pluck(PRIMARY_FIELD).run(conn) err_str = "Duplicate primary key `Name`: {}".format(obj_dict[PRIMARY_FIELD]) err_dict = {'errors': 1, 'first_error': err_str} return err_dict exce...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _perform_chunking(func_, *args, **kwargs): """ internal function alled only by wrap_split_big_content performs the actual chunking. :param func_: :param args...
obj_dict = args[0] start_point = 0 file_count = 0 new_dict = {} resp_dict = Counter({}) file_list = [] while start_point < len(obj_dict[CONTENT_FIELD]): file_count += 1 chunk_fn = CHUNK_POSTFIX.format(obj_dict[PRIMARY_FIELD], str(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 import_class(import_path): """ Imports a class dynamically from a full import path. """
if not '.' in import_path: raise IncorrectImportPath( "Invalid Python-style import path provided: {0}.".format( import_path ) ) path_bits = import_path.split('.') mod_path = '.'.join(path_bits[:-1]) klass_name = path_bits[-1] try: mo...
<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_hfs_accounts(netid): """ Return a restclients.models.hfs.HfsAccounts object on the given uwnetid """
url = ACCOUNTS_URL.format(uwnetid=netid) response = get_resource(url) return _object_from_json(response)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _timedelta_from_elements(elements): """ Return a timedelta from a dict of date elements. Accepts a dict containing any of the following: - years - months - d...
days = sum(( elements['days'], _months_to_days(elements.get('months', 0)), _years_to_days(elements.get('years', 0)) )) return datetime.timedelta(days=days, hours=elements.get('hours', 0), minutes=elements.get('minutes', 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 next(self): """Return one of record in this batch in out-of-order. :raises: `StopIteration` when no more record is in this batch """
if self._records_iter >= len(self._records): raise StopIteration self._records_iter += 1 return self._records[self._records_iter - 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 formatted_str(self, format): """Return formatted str. :param format: one of 'json', 'csv' are supported """
assert(format in ('json', 'csv')) ret_str_list = [] for rec in self._records: if format == 'json': ret_str_list.append('{') for i in xrange(len(rec)): colname, colval = self._rdef[i].name, rec[i] ret_str_list.ap...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def envify(app=None, add_repo_to_path=True): """ This will simply activate virtualenv on openshift ans returs the app in a wsgi.py or app.py in your openshift py...
if getvar('HOMEDIR'): if add_repo_to_path: sys.path.append(os.path.join(getvar('REPO_DIR'))) sys.path.insert(0, os.path.dirname(__file__) or '.') virtenv = getvar('PYTHON_DIR') + '/virtenv/' virtualenv = os.path.join(virtenv, 'bin/activate_this.py') exec_namesp...
<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(self, filename): """Return the lines from the given file, ignoring lines that start with comments"""
result = [] with open(filename, 'r') as f: lines = f.read().split('\n') for line in lines: nocomment = line.strip().split('#')[0].strip() if nocomment: result.append(nocomment) 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 order_by(self, field, orientation='ASC'): """ Indica los campos y el criterio de ordenamiento """
if isinstance(field, list): self.raw_order_by.append(field) else: self.raw_order_by.append([field, orientation]) 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 create_or_update_issue(self, title, body, culprit, labels, **kwargs): '''Creates or comments on existing issue in the store. :params title: title for the issue :params body: body, the content of the issue :params culprit: string used to identify the cause of the issue, a...
<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(self, q, labels, state='open,closed', **kwargs): """Search for issues in Github. :param q: query string to search :param state: state of the issue :re...
search_result = self.github_request.search(q=q, state=state, **kwargs) if search_result['total_count'] > 0: return list( map(lambda issue_dict: GithubIssue( github_request=self.github_request, **issue_dict), search_result['items']) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_issue_comment(self, issue, title, body, **kwargs): """Decides whether to comment or create a new issue when trying to comment. :param issue: issue on ...
if self._is_time_delta_valid(issue.updated_time_delta): if issue.comments_count < self.max_comments: issue.comment(body=body) return issue else: return self.create_issue(title=title, body=body, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_issue(self, title, body, labels=None): """Creates a new issue in Github. :params title: title of the issue to be created :params body: body of the iss...
kwargs = self.github_request.create( title=title, body=body, labels=labels) return GithubIssue(github_request=self.github_request, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def updated_time_delta(self): """Returns the number of seconds ago the issue was updated from current time. """
local_timezone = tzlocal() update_at = datetime.datetime.strptime(self.updated_at, '%Y-%m-%dT%XZ') update_at_utc = pytz.utc.localize(update_at) update_at_local = update_at_utc.astimezone(local_timezone) delta = datetime.datetime.now(local_timezone) - update_at_local retu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open_issue(self): """Changes the state of issue to 'open'. """
self.github_request.update(issue=self, state='open') self.state = 'open'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def comment(self, body): """Adds a comment to the issue. :params body: body, content of the comment :returns: issue object :rtype: :class:`exreporter.stores.gith...
self.github_request.comment(issue=self, body=body) if self.state == 'closed': self.open_issue() return self