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 post(self, document): """Send to API a document or a list of document. :param document: a document or a list of document. :type document: dict or list :retur...
if type(document) is dict: document = [document] return self.make_request(method='POST', uri='updates/', data=document)
<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): """Return the status from a job. :param key: id of job :type document: dict or list :return: message with location of job :rtype: dict :raise...
uri = 'updates/job/{}'.format(key) return self.make_request(method='GET', uri=uri)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def detect_range(line = None): ''' A helper function that checks a given host line to see if it contains a range pattern descibed in the docstring above. Returnes True if the given line contains a pattern, else False. ''' if (not line.startswith("[") and line.find("[") != -1 and ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def expand_hostname_range(line = None): ''' A helper function that expands a given line that contains a pattern specified in top docstring, and returns a list that consists of the expanded version. The '[' and ']' characters are used to maintain the pseudo-code appearance. They are replaced 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 create(self, image=None): """Create content and return url. In case of images add the image."""
container = self.context new = api.content.create( container=container, type=self.portal_type, title=self.title, safe_id=True, ) if image: namedblobimage = NamedBlobImage( data=image.read(), 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 redirect(self, url): """Has its own method to allow overriding"""
url = '{}/view'.format(url) return self.request.response.redirect(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 update_users(self, entries): """Update user properties on the roster """
ws = IWorkspace(self.context) members = ws.members # check user permissions against join policy join_policy = self.context.join_policy if (join_policy == "admin" and not checkPermission( "collective.workspace: Manage roster", self.con...
<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_remote(self, cached=True): ''' Helper function to determine remote :param cached: Use cached values or query remotes ''' return self.m( 'getting current remote', cmdd=dict( cmd='git remote show %s' % ('-n' if cached 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 _log(self, num=None, format=None): ''' Helper function to receive git log :param num: Number of entries :param format: Use formatted output with specified format string ''' num = '-n %s' % (num) if num else '' format = '--format="%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 _get_branch(self, remotes=False): ''' Helper function to determine current branch :param remotes: List the remote-tracking branches ''' return self.m( 'getting git branch information', cmdd=dict( cmd='git branch %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 _checkout(self, treeish): ''' Helper function to checkout something :param treeish: String for '`tag`', '`branch`', or remote tracking '-B `banch`' ''' return self.m( 'checking out "%s"' % (treeish), cmdd=dict(cmd='git checkout %s' % (tre...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _pull(self): ''' Helper function to pull from remote ''' pull = self.m( 'pulling remote changes', cmdd=dict(cmd='git pull --tags', cwd=self.local), critical=False ) if 'CONFLICT' in pull.get('out'): self.m( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _temp_filename(contents): """ Make a temporary file with `contents`. The file will be cleaned up on exit. """
fp = tempfile.NamedTemporaryFile( prefix='codequalitytmp', delete=False) name = fp.name fp.write(contents) fp.close() _files_to_cleanup.append(name) return name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def set_options(pool_or_cursor,row_instance): "for connection-level options that need to be set on Row instances" # todo: move around an Options object instead for option in ('JSON_READ',): setattr(row_instance,option,getattr(pool_or_cursor,option,None)) return row_instance
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def transform_specialfield(jsonify,f,v): "helper for serialize_row" raw = f.ser(v) if is_serdes(f) else v return ujson.dumps(raw) if not isinstance(f,basestring) and jsonify else raw
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dirty(field,ttl=None): "decorator to cache the result of a function until a field changes" if ttl is not None: raise NotImplementedError('pg.dirty ttl feature') def decorator(f): @functools.wraps(f) def wrapper(self,*args,**kwargs): # warning: not reentrant d=self.dirty_cache[field]...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def create_table(clas,pool_or_cursor): "uses FIELDS, PKEY, INDEXES and TABLE members to create a sql table for the model" def mkfield((name,tp)): return name,(tp if isinstance(tp,basestring) else 'jsonb') fields = ','.join(map(' '.join,map(mkfield,clas.FIELDS))) base = 'create table if not exists %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 pkey_get(clas,pool_or_cursor,*vals): "lookup by primary keys in order" pkey = clas.PKEY.split(',') if len(vals)!=len(pkey): raise ValueError("%i args != %i-len primary key for %s"%(len(vals),len(pkey),clas.TABLE)) rows = list(clas.select(pool_or_cursor,**dict(zip(pkey,vals)))) if not 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 select_models(clas,pool_or_cursor,**kwargs): "returns generator yielding instances of the class" if 'columns' in kwargs: raise ValueError("don't pass 'columns' to select_models") return (set_options(pool_or_cursor,clas(*row)) for row in clas.select(pool_or_cursor,**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 kwinsert(clas,pool_or_cursor,**kwargs): "kwargs version of insert" returning = kwargs.pop('returning',None) fields,vals = zip(*kwargs.items()) # note: don't do SpecialField resolution here; clas.insert takes care of it return clas.insert(pool_or_cursor,fields,vals,returning=returning)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def kwinsert_mk(clas,pool_or_cursor,**kwargs): "wrapper for kwinsert that returns a constructed class. use this over kwinsert in most cases" if 'returning' in kwargs: raise ValueError("don't call kwinsert_mk with 'returning'") return set_options( pool_or_cursor, clas(*clas.kwinsert(pool_or_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def updatewhere(clas,pool_or_cursor,where_keys,**update_keys): "this doesn't allow raw_keys for now" # if clas.JSONFIELDS: raise NotImplementedError # todo(awinter): do I need to make the same change for SpecialField? if not where_keys or not update_keys: raise ValueError setclause=','.join(k+'=%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 clean_to_decimal(x, prec=28): """Convert an string, int or float to Decimal object Parameters x : str, list, tuple, numpy.ndarray, pandas.DataFrame A string,...
import numpy as np import pandas as pd import decimal def proc_elem(e): try: return decimal.Decimal(e) + decimal.Decimal('0.0') except Exception as e: print(e) return None def proc_list(x): return [proc_elem(e) for e in x] def proc_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rating_for(context, obj): """ Provides a generic context variable name for the object that ratings are being rendered for, and the rating form. """
context["rating_object"] = context["rating_obj"] = obj context["rating_form"] = RatingForm(context["request"], obj) ratings = context["request"].COOKIES.get("yacms-rating", "") rating_string = "%s.%s" % (obj._meta, obj.pk) context["rated"] = (rating_string in ratings) rating_name = obj.get_rati...
<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_attr_info(binary_view): '''Gets basic information from a binary stream to allow correct processing of the attribute header. This function allows the interpretation of the Attribute type, attribute length and if the attribute is non resident. Args: binary_view (memoryview of bytearr...
<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_attrcontent_class(name, fields, inheritance=(object,), data_structure=None, extra_functions=None, docstring=""): '''Helper function that creates a class for attribute contents. This function creates is a boilerplate to create all the expected methods of an attributes. The basic methods work 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 _astimezone_ts(self, timezone): """Changes the time zones of all timestamps. Receives a new timezone and applies to all timestamps, if necessary. Args: timez...
if self.created.tzinfo is timezone: return self else: nw_obj = Timestamps((None,)*4) nw_obj.created = self.created.astimezone(timezone) nw_obj.changed = self.changed.astimezone(timezone) nw_obj.mft_changed = self.mft_changed.astimezone(timezone) nw_obj.accessed =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _len_objid(self): '''Get the actual size of the content, as some attributes have variable sizes''' try: return self._size except AttributeError: temp = (self.object_id, self.birth_vol_id, self.birth_object_id, self.birth_domain_id) self._size = sum([ObjectID._UUID_SIZE for data 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 _allocated_entries_bitmap(self): '''Creates a generator that returns all allocated entries in the bitmap. Yields: int: The bit index of the allocated entries. ''' for entry_number in range(len(self._bitmap) * 8): if self.entry_allocated(entry_number): yield entry_nu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _entry_allocated_bitmap(self, entry_number): """Checks if a particular index is allocated. Args: entry_number (int): Index to verify Returns: bool: True if ...
index, offset = divmod(entry_number, 8) return bool(self._bitmap[index] & (1 << 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 _get_next_empty_bitmap(self): """Returns the next empty entry. Returns: int: The value of the empty entry """
#TODO probably not the best way, redo for i, byte in enumerate(self._bitmap): if byte != 255: for offset in range(8): if not byte & (1 << offset): return (i * 8) + 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 _len_ea_entry(self): '''Returns the size of the entry''' return EaEntry._REPR.size + len(self.name.encode("ascii")) + self.value_len
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _str_sid(self): 'Return a nicely formatted representation string' sub_auths = "-".join([str(sub) for sub in self.sub_authorities]) return f'S-{self.revision_number}-{self.authority}-{sub_auths}'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _len_sec_desc(self): '''Returns the logical size of the file''' return len(self.header) + len(self.owner_sid) + len(self.group_sid) + len(self.sacl) + len(self.dacl)
<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_from_binary(cls, binary_view): '''Creates a new object DataRuns from a binary stream. The binary stream can be represented by a byte string, bytearray or a memoryview of the bytearray. Args: binary_view (memoryview of bytearray) - A binary stream 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 create_from_binary(cls, binary_view): '''Creates a new object AttributeHeader from a binary stream. The binary stream can be represented by a byte string, bytearray or a memoryview of the bytearray. Args: binary_view (memoryview of bytearray) - A binary stream 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 create_from_binary(cls, load_dataruns, binary_view): '''Creates a new object NonResidentAttrHeader from a binary stream. The binary stream can be represented by a byte string, bytearray or a memoryview of the bytearray. Args: load_dataruns (bool) - Indicates if the datar...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_slide_list(self, logname, slides): """ Write list of slides to logfile """
# Write slides.txt with list of slides with open('%s/%s' % (self.cache, logname), 'w') as logfile: for slide in slides: heading = slide['heading']['text'] filename = self.get_image_name(heading) print('%s,%d' % (filename, slid...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rotate(self, img): """ Rotate image if exif says it needs it """
try: exif = image2exif.get_exif(img) except AttributeError: # image format doesn't support exif return img orientation = exif.get('Orientation', 1) landscape = img.height < img.width if orientation == 6 and landscape: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draw_image(self, image, item, source): """ Add an image to the image """
top, left = item['top'], item['left'] width, height = item['width'], item['height'] image_file = item['image'] img = Image.open(source) img = self.rotate(img) iwidth, iheight = img.size wratio = width / iwidth hratio = height / iheight ratio ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def slugify(self, name): """ Turn name into a slug suitable for an image file name """
slug = '' last = '' for char in name.replace('#', '').lower().strip(): if not char.isalnum(): char = '_' if last == '_' and char == '_': continue slug += char last = char return slug
<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_keys(self): """ Returns list of the available keys :return: List of the keys available in the storage :rtype list """
return [k for k, el in self._keystore.items() if not el.is_expired]
<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, key, value, expire_in=None): """ Function to set or change particular property in the storage :param key: key name :param value: value to set :para...
if key not in self._keystore: self._keystore[key] = InMemoryItemValue(expire_in=expire_in) k = self._keystore[key] """:type k InMemoryItemValue""" k.update_expire_time(expire_in) k.value = value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, key): """ Retrieves previously stored key from the storage :return value, stored in the storage """
if key not in self._keystore: return None rec = self._keystore[key] """:type rec InMemoryItemValue""" if rec.is_expired: self.delete(key) return None return rec.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 exists(self, key): """ Check if the particular key exists in the storage :param key: name of the key which existence need to be checked :return: :type key st...
if key in self._keystore and not self._keystore[key].is_expired: return True elif key in self._keystore and self._keystore[key].is_expired: self.delete(key) return False 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 plot_2d_single(x, y, pdffilename, **kwargs): """ Do make_2d_single_plot and pass all arguments args: x: array_like xdata y: array_like ydata filepath: string...
pdffilepath = DataSets.get_pdffilepath(pdffilename) plotsingle2d = PlotSingle2D(x, y, pdffilepath, **kwargs) return plotsingle2d.plot()
<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_pdffilepath(pdffilename): """ Returns the path for the pdf file args: pdffilename: string returns path for the plots folder / pdffilename.pdf """
return FILEPATHSTR.format( root_dir=ROOT_DIR, os_sep=os.sep, os_extsep=os.extsep, name=pdffilename, folder=PURPOSE.get("plots").get("folder", "plots"), ext=PURPOSE.get("plots").get("extension", "pdf") )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_tex_table(inputlist, outputfilename, fmt=None, **kwargs): """ Do make_tex_table and pass all arguments args: inputlist: list outputfilename: string fmt:...
outputfilepath = FILEPATHSTR.format( root_dir=ROOT_DIR, os_sep=os.sep, os_extsep=os.extsep, name=outputfilename, folder=PURPOSE.get("tables").get("folder", "tables"), ext=PURPOSE.get("tables").get("extension", "tex") ) table.make_tex_table(inputli...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_compute_file(self): """ Make the compute file from the self.vardict and self.vardictformat """
string = "" try: vardict_items = self.vardict.iteritems() except AttributeError: vardict_items = self.vardict.items() for key, val in vardict_items: # get default default_format = get_default_format(val) string_format = "\\newc...
<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_es_mappings(self): """ Returns the mapping defitions presetn in elasticsearh """
es_mappings = json.loads(requests.get(self.mapping_url).text) es_mappings = {"_".join(key.split("_")[:-1]): value['mappings'] \ for key, value in es_mappings.items()} return es_mappings
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def readable_time_delta(seconds): """ Convert a number of seconds into readable days, hours, and minutes """
days = seconds // 86400 seconds -= days * 86400 hours = seconds // 3600 seconds -= hours * 3600 minutes = seconds // 60 m_suffix = 's' if minutes != 1 else '' h_suffix = 's' if hours != 1 else '' d_suffix = 's' if days != 1 else '' retval = u'{0} minute{1}'.format(minutes, m_suffi...
<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_occurrence(reminder): """ Calculate the next occurrence of a repeatable reminder """
now = datetime.datetime.utcnow().replace(tzinfo=pytz.UTC) now_dow = now.weekday() # Start/end dow starting from tomorrow start_dow = now_dow + 1 end_dow = start_dow + 7 # Modded range from tomorrow until 1 week from now. Normalizes # wraparound values that span into next week dow_iter...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def at_reminder(client, channel, nick, args): """ Schedule a reminder to occur at a specific time. The given time can optionally be specified to occur at a speci...
global _scheduled now = datetime.datetime.utcnow().replace(tzinfo=pytz.UTC) # Parse the time it should go off, and the minute offset of the day hh, mm = map(int, args[0].split(':')) # Strip time from args args = args[1:] # Default timezone timezone = pytz.timezone(getattr(settings, ...
<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_template(self, template, subdir): """ Use yacms's project template by default. The method of picking the default directory is copied from Django's Tem...
if template is None: return six.text_type(os.path.join(yacms.__path__[0], subdir)) return super(Command, self).handle_template(template, subdir)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, *args, **kwargs): """Automatically set image"""
if not self.image: # Fetch image url = "http://img.youtube.com/vi/%s/0.jpg" % self.youtube_id response = None try: response = requests.get(url) except requests.exceptions.RequestException: # Nothing we can really do 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 name(self): """ Compute a name according to sub meta results names 'operation:[plus, moins]' """
return "%s:[%s]" % (self._name, ", ".join(meta.name for meta in self._metas))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def errors(self): """ get all the errors [ValueError('invalid data',), RuntimeError('server not anwsering',)] """
errors = [] for meta in self: errors.extend(meta.errors) return errors
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def defaults(self): """ component default component .. Note:: default components is just an indication for user and the views, except if the Block is required. I...
default = self._defaults # if require and no default, the first component as default if not len(default) and self.required and len(self._components): default = [six.next(six.itervalues(self._components)).name] 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 selected(self): """ returns the list of selected component names. if no component selected return the one marked as default. If the block is required and no ...
selected = self._selected if len(self._selected) == 0 and self.required: # nothing has been selected yet BUT the component is required selected = self.defaults return selected
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_dict(self): """ returns a dictionary representation of the block and of all component options """
#TODO/FIXME: add selected information if self.hidden: rdict = {} else: def_selected = self.selected() comps = [ { 'name': comp.name, 'default': comp.name in self.defaults, 'options': ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset(self): """ Removes all the components of the block """
self._components = OrderedDict() self.clear_selections() self._logger.info("<block: %s> reset component list" % (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 setup(self, in_name=None, out_name=None, required=None, hidden=None, multiple=None, defaults=None): """ Set the options of the block. Only the not None given...
if in_name is not None: self.in_name = in_name if isinstance(in_name, list) else [in_name] if out_name is not None: self.out_name = out_name if required is not None: self.required = required if hidden is not None: self.hidden = hidden ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(self): """ check that the block can be run """
if self.required and len(self.selected()) == 0: raise ReliureError("No component selected for block '%s'" % 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 requires(self, *names): """ Declare what block will be used in this engine. It should be call before adding or setting any component. Blocks order will be pr...
if len(names) == 0: raise ValueError("You should give at least one block name") if self._blocks is not None and len(self._blocks) > 0: raise ReliureError("Method 'requires' should be called only once before adding any composant") for name in names: if na...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def needed_inputs(self): """ List all the needed inputs of a configured engine ['in'] But now if we unactivate the first component: ['middle'] More complex examp...
needed = set() available = set() # set of available data for bnum, block in enumerate(self): if not block.selected(): # if the block will not be used continue if block.in_name is not None: for in_name in block.in_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 as_dict(self): """ dict repr of the components """
drepr = { 'blocks': [ block.as_dict() for block in self if block.hidden == False ], 'args': list(self.needed_inputs()) } return drepr
<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(self): """ Returns a list of cached instances. """
class_list = list(self.get_class_list()) if not class_list: self.cache = [] return [] if self.cache is not None: return self.cache results = [] for cls_path in class_list: module_name, class_name = cls_path.rsplit('.', 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 _download_initial_config(self): """Loads the initial config."""
_initial_config = self._download_running_config() # this is a bit slow! self._last_working_config = _initial_config self._config_history.append(_initial_config) self._config_history.append(_initial_config)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _upload_config_content(self, configuration, rollbacked=False): """Will try to upload a specific configuration on the device."""
try: for configuration_line in configuration.splitlines(): self._device.cli(configuration_line) self._config_changed = True # configuration was changed self._committed = False # and not committed yet except (pyPluribus.exceptions.CommandExecutionErr...
<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_candidate(self, filename=None, config=None): """ Loads a candidate configuration on the device. In case the load fails at any point, will automatically ...
configuration = '' if filename is None: configuration = config else: with open(filename) as config_file: configuration = config_file.read() return self._upload_config_content(configuration)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def discard(self): # pylint: disable=no-self-use """ Clears uncommited changes. :raise pyPluribus.exceptions.ConfigurationDiscardError: If the configuration appl...
try: self.rollback(0) except pyPluribus.exceptions.RollbackError as rbackerr: raise pyPluribus.exceptions.ConfigurationDiscardError("Cannot discard configuration: {err}.\ ".format(err=rbackerr))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def commit(self): # pylint: disable=no-self-use """Will commit the changes on the device"""
if self._config_changed: self._last_working_config = self._download_running_config() self._config_history.append(self._last_working_config) self._committed = True # comfiguration was committed self._config_changed = False # no changes since last 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 compare(self): # pylint: disable=no-self-use """ Computes the difference between the candidate config and the running config. """
# becuase we emulate the configuration history # the difference is between the last committed config and the running-config running_config = self._download_running_config() running_config_lines = running_config.splitlines() last_committed_config = self._last_working_config ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rollback(self, number=0): """ Will rollback the configuration to a previous state. Can be called also when :param number: How many steps back in the configur...
if number < 0: raise pyPluribus.exceptions.RollbackError("Please provide a positive number to rollback to!") available_configs = len(self._config_history) max_rollbacks = available_configs - 2 if max_rollbacks < 0: raise pyPluribus.exceptions.RollbackError("Canno...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draw(self, label, expire): """ Return a Serial number for this resource queue, after bootstrapping. """
# get next number with self.client.pipeline() as pipe: pipe.msetnx({self.keys.dispenser: 0, self.keys.indicator: 1}) pipe.incr(self.keys.dispenser) number = pipe.execute()[-1] # publish for humans self.message('{} assigned to "{}"'.format(number, lab...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait(self, number, patience): """ Waits and resets if necessary. """
# inspect indicator for our number waiting = int(self.client.get(self.keys.indicator)) != number # wait until someone announces our number while waiting: message = self.subscription.listen(patience) if message is None: # timeout beyond patience, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def message(self, text): """ Public message. """
self.client.publish(self.keys.external, '{}: {}'.format(self.resource, 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 announce(self, number): """ Announce an indicator change on both channels. """
self.client.publish(self.keys.internal, self.keys.key(number)) self.message('{} granted'.format(number))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bump(self): """ Fix indicator in case of unnanounced departments. """
# read client values = self.client.mget(self.keys.indicator, self.keys.dispenser) indicator, dispenser = map(int, values) # determine active users numbers = range(indicator, dispenser + 1) keys = [self.keys.key(n) for n in numbers] pairs = zip(keys, self.client....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lock(self, resource, label='', expire=60, patience=60): """ Lock a resource. :param resource: String corresponding to resource type :param label: String labe...
queue = Queue(client=self.client, resource=resource) with queue.draw(label=label, expire=expire) as number: queue.wait(number=number, patience=patience) yield queue.close()
<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_refs(profile, ref_type=None): """List all refs. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this ...
resource = "/refs" if ref_type: resource += "/" + ref_type data = api.get_request(profile, resource) result = [prepare(x) for x in data] return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_ref(profile, ref): """Fetch a ref. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the...
resource = "/refs/" + ref data = api.get_request(profile, resource) return prepare(data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_ref(profile, ref, sha): """Create a ref. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this modul...
resource = "/refs" payload = {"ref": "refs/" + ref, "sha": sha} data = api.post_request(profile, resource, payload) return prepare(data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_ref(profile, ref, sha): """Point a ref to a new SHA. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tel...
resource = "/refs/" + ref payload = {"sha": sha} data = api.patch_request(profile, resource, payload) return prepare(data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def latency(self): """ Checks the connection latency. """
with self.lock: self.send('PING %s' % self.server) ctime = self._m_time.time() msg = self._recv(expected_replies=('PONG',)) if msg[0] == 'PONG': latency = self._m_time.time() - ctime return latency
<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_section_relations(Section): """Find every relationship between section and the item model."""
all_rels = (Section._meta.get_all_related_objects() + Section._meta.get_all_related_many_to_many_objects()) return filter_item_rels(all_rels)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authorize_url(self): """ Build the authorization url and save the state. Return the authorization url """
url, self.state = self.oauth.authorization_url( '%sauthorize' % OAUTH_URL) return url
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch_token(self, code, state): """ Fetch the token, using the verification code. Also, make sure the state received in the response matches the one in the r...
if self.state != state: raise MismatchingStateError() self.token = self.oauth.fetch_token( '%saccess_token/' % OAUTH_URL, code=code, client_secret=self.client_secret) return self.token['access_token']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def refresh_token(self, refresh_token): """ Get a new token, using the provided refresh token. Returns the new access_token. """
response = requests.post('%saccess_token' % OAUTH_URL, { 'refresh_token': refresh_token, 'grant_type': 'refresh_token', 'client_id': self.client_id, 'client_secret': self.client_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def browser_authorize(self): """ Open a browser to the authorization url and spool up a CherryPy server to accept the response """
url = self.authorize_url() # Open the web browser in a new thread for command-line browser support threading.Timer(1, webbrowser.open, args=(url,)).start() server_config = { 'server.socket_host': '0.0.0.0', 'server.socket_port': 443, 'server.ssl_mod...
<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, state, code=None, error=None): """ Receive a Exist response containing a verification code. Use the code to fetch the access_token. """
error = None if code: try: auth_token = self.fetch_token(code, state) except MissingTokenError: error = self._fmt_failure( 'Missing access token parameter.</br>Please check that ' 'you are using the correct ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _shutdown_cherrypy(self): """ Shutdown cherrypy in one second, if it's running """
if cherrypy.engine.state == cherrypy.engine.states.STARTED: threading.Timer(1, cherrypy.engine.exit).start()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def roundup(x, order): '''Round a number to the passed order Args ---- x: float Number to be rounded order: int Order to which `x` should be rounded Returns ------- x_round: float The passed value rounded to the passed order ''' return x if x % 10**order...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def hourminsec(n_seconds): '''Generate a string of hours and minutes from total number of seconds Args ---- n_seconds: int Total number of seconds to calculate hours, minutes, and seconds from Returns ------- hours: int Number of hours in `n_seconds` minutes: int ...
<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_alpha_labels(axes, xpos=0.03, ypos=0.95, suffix='', color=None, fontsize=14, fontweight='normal', boxstyle='square', facecolor='white', edgecolor='white', alpha=1.0): '''Add sequential alphbet labels to subplot axes Args ---- axes: list of pyplot.ax A list of matplotlib ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def merge_limits(axes, xlim=True, ylim=True): '''Set maximum and minimum limits from list of axis objects to each axis Args ---- axes: iterable list of `matplotlib.pyplot` axis objects whose limits should be modified xlim: bool Flag to set modification of x axis limits ylim: boo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def plot_noncontiguous(ax, data, ind, color='black', label='', offset=0, linewidth=0.5, linestyle='-'): '''Plot non-contiguous slice of data Args ---- data: ndarray The data with non continguous regions to plot ind: ndarray indices of data to be plotted color: matplotlib...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def plot_shade_mask(ax, ind, mask, facecolor='gray', alpha=0.5): '''Shade across x values where boolean mask is `True` Args ---- ax: pyplot.ax Axes object to plot with a shaded region ind: ndarray The indices to use for the x-axis values of the data mask: ndarray Boolean...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fields(self, new_fieldnames): """ Overwrite all field names with new field names. Mass renaming. """
if len(new_fieldnames) != len(self.fields): raise Exception("Cannot replace fieldnames (len: %s) with list of " "incorrect length (len: %s)" % (len(new_fieldnames), len(self.fields))) for old_name, new_n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fromcsvstring(cls, csvstring, delimiter=",", quotechar="\""): """ Takes one string that represents the entire contents of the CSV file, or similar delimited ...
if not isinstance(csvstring, basestring): raise Exception("If trying to construct a DataTable with " "a list of lists, just use the main " "constructor. Make sure to include a header row") stringio = StringIO(csvstring.encode('utf-8')...