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 isBirthday(self): """ Is it the user's birthday today? """
if not self.birthday: return False birthday = self.birthdate() today = date.today() return (birthday.month == today.month and birthday.day == today.day)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reload(self): """ If there is an LDAP connection, query it for another instance of this member and set its internal dictionary to that result. """
if not self.ldap: return self.memberDict = self.ldap.member(self.uid)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def consume(self, stream, source=None, chunksize=1): """ Consuming given strem object and returns processing stats. :param stream: streaming object to consume :t...
stats = { PROCESSING_TOTAL: 0, PROCESSING_SKIPPED: 0, PROCESSING_SUCCESS: 0, PROCESSING_ERROR: 0 } if source: stats['source'] = source def skip_unless(r): if r: return r stats[PROCESSING...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reader(self, fp, encoding): """ Simple `open` wrapper for several file types. This supports ``.gz`` and ``.json``. :param fp: opened file :type fp: file poin...
_, suffix = os.path.splitext(fp.name) if suffix == '.gz': fp.close() return gzip.open(fp.name) elif suffix == '.json': return json.load(fp) elif suffix == '.csv' or self.delimiter: return csvreader(fp, encoding, delimiter=self.delimiter 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 handle(self, files, encoding, chunksize=1): """ Handle given files with given encoding. :param files: opened files. :type files: list :param encoding: encodi...
stats = [] if files: logging.info("Input file count: %d", len(files)) for fp in files: stream = self.reader(fp, encoding) parsed = self.streamer.consume(stream, source=fp.name, chunksize=chunksize) stats.append(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init(parser = None): """ module needs to be initialized by 'init'. Can be called with parser to use a pre-built parser, otherwise a simple default parser is ...
global p,subparsers if parser is None: p = argparse.ArgumentParser() else: p = parser arg = p.add_argument subparsers = p.add_subparsers()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authenticate(self): """ Authenticates with the PA Oauth system """
if self._auth_token is None or self._token_expiry < time.time(): self._perform_auth() yield self._auth_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 _query_api(self, method, url, fields=None, extra_headers=None, req_body=None): """ Abstracts http queries to the API """
with self.auth.authenticate() as token: logging.debug('PA Authentication returned token %s', token) headers = { 'Authorization': 'Bearer %s' % (token,), 'Realm': self.auth_realm } if extra_headers is not None: heade...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all_jobtemplates(self): """ Retrieves the list of jobTemplates for the current realm. """
endpoint = self._build_url('jobTemplates', { 'paginationPageSize': self.PAGE_SIZE }) data = self._query_api('GET', endpoint) return data['results']
<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_job_template(self, template): """ Creates a job template """
endpoint = self._build_url('jobTemplates') data = self._query_api('POST', endpoint, None, {'Content-Type': 'application/json'}, json.dumps(template)) return data['results'...
<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_job(self, job_template_uri): """ Creates a job """
endpoint = self._build_url('jobs') data = self._query_api('POST', endpoint, None, {'Content-Type': 'application/json'}, json.dumps({'jobTemplateUri': job_template_uri})) 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 normalize_to_range( values, minimum = 0.0, maximum = 1.0 ): """ This function normalizes values of a list to a specified range and returns the original objec...
normalized_values = [] minimum_value = min(values) maximum_value = max(values) for value in values: numerator = value - minimum_value denominator = maximum_value - minimum_value value_normalized = (maximum - minimum) * numerator/denominator + minimum normalized_values.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 list_element_combinations_variadic( elements_specification ): """ This function accepts a specification of lists of elements for each place in lists in the f...
lists = [list(list_generated) for index, element_specification in enumerate(elements_specification) for list_generated in itertools.product(*elements_specification[:index + 1])] return lists
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def correlation_linear( values_1, values_2, printout = None ): """ This function calculates the Pearson product-moment correlation coefficient. This is a measure...
r, p_value = scipy.stats.pearsonr(values_1, values_2) if printout is not True: return r, p_value else: text = ( "Pearson linear correlation coefficient: {r}\n" "2-tailed p-value: {p_value}" ).format( r = r, p_value = p_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 propose_number_of_bins( values, binning_logic_system = None, ): """ This function returns a proposal for binning for a histogram of a specified list using an...
# Set the default binning logic system. if binning_logic_system is None: binning_logic_system = "Scott" # Engage the requested logic system. if binning_logic_system == "Freedman-Diaconis": #log.debug("engage Freedman-Diaconis binning logic") bin_size =\ 2 * interqua...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extent(self): """ return range of 2D data """
return [min(self.x), max(self.x), min(self.y), max(self.y)]
<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_symbol_by_slope( self, slope, default_symbol ): """ return line oriented approximatively along the slope value """
if slope > math.tan(3 * math.pi / 8): draw_symbol = "|" elif math.tan(math.pi / 8) < slope < math.tan(3 * math.pi / 8): draw_symbol = u"\u27cb" # "/" elif abs(slope) < math.tan(math.pi / 8): draw_symbol = "-" elif slope < math.tan(-math.pi / 8) 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 limit_x( self, limit_lower = None, # float limit_upper = None # float ): """ get or set x limits of the current axes x_min, x_max = limit_x() # return the cu...
if limit_lower is None and limit_upper is None: return self._limit_x elif hasattr(limit_lower, "__iter__"): self._limit_x = limit_lower[:2] else: self._limit_x = [limit_lower, limit_upper] if self._limit_x[0] == self._limit_x[1]: self._li...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def limit_y( self, limit_lower = None, limit_upper = None ): """ get or set y limits of the current axes y_min, y_max = limit_x() # return the current limit_y li...
if limit_lower is None and limit_upper is None: return self._limit_y elif hasattr(limit_lower, "__iter__"): self._limit_y = limit_lower[:2] else: self._limit_y = [limit_lower, limit_upper] if self._limit_y[0] == self._limit_y[1]: self._li...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _clip_line( self, line_pt_1, line_pt_2 ): """ clip line to canvas """
x_min = min(line_pt_1[0], line_pt_2[0]) x_max = max(line_pt_1[0], line_pt_2[0]) y_min = min(line_pt_1[1], line_pt_2[1]) y_max = max(line_pt_1[1], line_pt_2[1]) extent = self.extent() if line_pt_1[0] == line_pt_2[0]: return ( (line_pt_1[0], ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_dyndns_records(login, password): """Gets the set of dynamic DNS records associated with this account"""
params = dict(action='getdyndns', sha=get_auth_key(login, password)) response = requests.get('http://freedns.afraid.org/api/', params=params, timeout=timeout) raw_records = (line.split('|') for line in response.content.split()) try: records = frozenset(DnsRecord(*record) for record in raw_reco...
<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_continuously(records, update_interval=600): """Update `records` every `update_interval` seconds"""
while True: for record in records: try: record.update() except (ApiError, RequestException): pass time.sleep(update_interval)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self): """Updates remote DNS record by requesting its special endpoint URL"""
response = requests.get(self.update_url, timeout=timeout) match = ip_pattern.search(response.content) # response must contain an ip address, or else we can't parse it if not match: raise ApiError("Couldn't parse the server's response", response.content) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup_app(app, api): """setup the resources urls."""
api.add_resource( KnwKBAllResource, '/api/knowledge' ) api.add_resource( KnwKBResource, '/api/knowledge/<string:slug>' ) api.add_resource( KnwKBMappingsResource, '/api/knowledge/<string:slug>/mappings' ) api.add_resource( KnwKBMappings...
<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, slug): """Get KnwKB. Url parameters: - from: filter "mappings from" - to: filter "mappings to" - page - per_page - match_type: s=substring, e=exact...
kb = api.get_kb_by_slug(slug) # check if is accessible from api check_knowledge_access(kb) parser = reqparse.RequestParser() parser.add_argument( 'from', type=str, help="Return only entries where key matches this.") parser.add_argument( ...
<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_mappings(kb, key=None, value=None, match_type=None, sortby=None, page=None, per_page=None): """Search tags for knowledge."""
if kb.kbtype == models.KnwKB.KNWKB_TYPES['written_as']: return pagination.RestfulSQLAlchemyPagination( api.query_kb_mappings( kbid=kb.id, key=key or '', value=value or '', match_type=match_type or '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(self, slug): """Get list of mappings. Url parameters: - from: filter "mappings from" - to: filter "mappings to" - page - per_page - match_type: s=substri...
kb = api.get_kb_by_slug(slug) # check if is accessible from api check_knowledge_access(kb) parser = reqparse.RequestParser() parser.add_argument( 'from', type=str, help="Return only entries where 'from' matches this.") parser.add_argument( ...
<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_list(kb, value=None, match_type=None, page=None, per_page=None, unique=False): """Search "mappings to" for knowledge."""
# init page = page or 1 per_page = per_page or 10 if kb.kbtype == models.KnwKB.KNWKB_TYPES['written_as']: # get the base query query = api.query_kb_mappings( kbid=kb.id, value=value or '', match_type=match_type 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 search_list(kb, from_=None, match_type=None, page=None, per_page=None, unique=False): """Search "mapping from" for knowledge."""
# init page = page or 1 per_page = per_page or 10 if kb.kbtype == models.KnwKB.KNWKB_TYPES['written_as']: # get the base query query = api.query_kb_mappings( kbid=kb.id, key=from_ or '', match_type=match_type or '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(self, slug): """Get list of "mappings from". Url parameters - unique: if set, return a unique list - filter: filter "mappings from" - page - per_page - m...
kb = api.get_kb_by_slug(slug) # check if is accessible from api check_knowledge_access(kb) parser = reqparse.RequestParser() parser.add_argument( 'unique', type=bool, help="The list contains unique names of 'mapping to'") parser.add_argument( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def manage_mep(self, mep_json): ''' Import a mep as a representative from the json dict fetched from parltrack ''' # Some versions of memopol will connect to this and skip inactive meps. responses = representative_pre_import.send(sender=self, representati...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _calc_dir_size(path): """ Calculate size of all files in `path`. Args: path (str): Path to the directory. Returns: int: Size of the directory in bytes. """
dir_size = 0 for (root, dirs, files) in os.walk(path): for fn in files: full_fn = os.path.join(root, fn) dir_size += os.path.getsize(full_fn) return dir_size
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_localized_fn(path, root_dir): """ Return absolute `path` relative to `root_dir`. When `path` == ``/home/xex/somefile.txt`` and `root_dir` == ``/home``, ...
local_fn = path if path.startswith(root_dir): local_fn = path.replace(root_dir, "", 1) if not local_fn.startswith("/"): return "/" + local_fn return local_fn
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compose_info(root_dir, files, hash_fn, aleph_record, urn_nbn=None): """ Compose `info` XML file. Info example:: <?xml version="1.0" encoding="UTF-8" standalo...
# compute hash for hashfile with open(hash_fn) as f: hash_file_md5 = hashlib.md5(f.read()).hexdigest() schema_location = "http://www.ndk.cz/standardy-digitalizace/info11.xsd" document = odict[ "info": odict[ "@xmlns:xsi": "http://www.w3.org/2001/XMLSchema-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 run(argv=None): """Main CLI entry point."""
cli = InfrascopeCLI() return cli.run(sys.argv[1:] if argv is None else 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 create_app(configobj=ProdConfig): """ Create and configure Flask Application """
app = Flask(__name__) app.config.from_object(configobj) configure_blueprints(app) configure_extensions(app) configure_callbacks(app) configure_filters(app) configure_error_handlers(app) return app
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def configure_extensions(app): """ Configure application extensions """
db.init_app(app) app.wsgi_app = ProxyFix(app.wsgi_app) assets.init_app(app) for asset in bundles: for (name, bundle) in asset.iteritems(): assets.register(name, bundle) login_manager.login_view = 'frontend.login' login_manager.login_message_category = 'info' @login_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def configure_callbacks(app): """ Configure application callbacks """
@app.before_request def before_request(): """ Retrieve menu configuration before every request (this will return cached version if possible, else reload from database. """ from flask import session #g.menusystem = helper.generate_menusystem() session['menusystem']...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def configure_error_handlers(app): """ Configure application error handlers """
def render_error(error): return (render_template('errors/%s.html' % error.code, title=error_messages[error.code], code=error.code), error.code) for (errcode, title) in error_messages.iteritems(): app.errorhandler(errcode)(render_error)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _strip_colors(self, message: str) -> str: """ Remove all of the color tags from this message. """
for c in self.COLORS: message = message.replace(c, "") return message
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_str(window, line_num, str): """ attempt to draw str on screen and ignore errors if they occur """
try: window.addstr(line_num, 0, str) except curses.error: pass
<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_file_to_descriptor(input_queue, descriptor): """ get item from input_queue and write it to descriptor returns True if and only if it was successfully w...
try: file_name = input_queue.get(timeout=2) descriptor.write("{}\n".format(file_name)) descriptor.flush() input_queue.task_done() return True except Empty: # no more files in queue descriptor.close() return False except IOError: return...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def smooth(l): """Yields a generator which smooths all elements as if the given list was of depth 1. **Examples**: :: list(auxly.listy.smooth([1,[2,[3,[4]]]])) #...
if type(l) in [list, tuple]: for i in l: for j in smooth(i): yield j else: yield l
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def s3path(self, rel_path): """Return the path as an S3 schema"""
import urlparse path = self.path(rel_path, public_url=True) parts = list(urlparse.urlparse(path)) parts[0] = 's3' parts[1] = self.bucket_name return urlparse.urlunparse(parts)
<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_stream(self, rel_path, cb=None, return_meta=False): """Return the object as a stream"""
from boto.s3.key import Key from boto.exception import S3ResponseError import StringIO from . import MetadataFlo b = StringIO.StringIO() try: k = self._get_boto_key(rel_path) if not k: return None k.get_contents_to_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 list(self, path=None, with_metadata=False, include_partitions=False): '''Get a list of all of bundle files in the cache. Does not return partition files''' import json sub_path = self.prefix + '/' + path.strip('/') if path else self.prefix l = {} for e in self.bucket.list(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _send_streamify(self, frame): """ Helper method to streamify a frame. """
# Get the state and framer state = self._send_framer_state framer = self._send_framer # Reset the state as needed state._reset(framer) # Now pass the frame through streamify() and return the result return framer.streamify(state, frame)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _recv_frameify(self, data): """ Helper method to frameify a stream. """
# Get the state and framer state = self._recv_framer_state framer = None # Grab off as many frames as we can frameify = None while True: # Check if we need to change framers if framer != self._recv_framer: # Notify the currently-...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def closed(self, error=None): """ Notify the application that the connection has been closed. :param error: The exception which has caused the connection to be c...
if self._application: try: self._application.closed(error) except Exception: # Ignore exceptions from the notification pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_framer(self, value): """ Set the framer in use for the sending side of the connection. The framer state will be reset next time the framer is used. """
if not isinstance(value, framers.Framer): raise ValueError("framer must be an instance of tendril.Framer") self._send_framer = 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 recv_framer(self, value): """ Set the framer in use for the receiving side of the connection. The framer state will be reset next time the framer is used. ""...
if not isinstance(value, framers.Framer): raise ValueError("framer must be an instance of tendril.Framer") self._recv_framer = 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 framers(self, value): """ Set the framers in use for the connection. The framer states will be reset next time their respective framer is used. """
# Handle sequence values if isinstance(value, collections.Sequence): if len(value) != 2: raise ValueError('need exactly 2 values to unpack') elif (not isinstance(value[0], framers.Framer) or not isinstance(value[1], framers.Framer)): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def framers(self): """ Reset the framers in use for the connection to be a tendril.IdentityFramer. The framer states will be reset next time their respective fra...
f = self.default_framer() self._send_framer = f self._recv_framer = 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 application(self, value): """Update the application."""
# Always allow None if value is None: self._application = None return # Check that the state is valid if not isinstance(value, application.Application): raise ValueError("application must be an instance of " "tendril.App...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build(): """ Builds pages given template.jinja, style.css, and content.rst produces index.html. """
test_files() with open('content.rst') as f: content = publish_parts(f.read(), writer_name='html') title = content['title'] body = content['html_body'].replace('\n',' ') with open('template.jinja', 'r') as f: loader = FileSystemLoader(getcwd()) env= Environment(load...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init(directory=None): """ Initializes a new site in the `directory` Current working dir if directory is None. """
if directory is not None and not path.exists(directory): makedirs(directory) else: print('%s already exists, populating with template files' % (directory)) directory = '' if not path.isfile(path.join(directory,'style.css')): grab('style.css', directory) print('Added...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def callback(self, callback, *args, **kwds): """ Registers an arbitrary callback and arguments. Cannot suppress exceptions. """
return self << _CloseDummy(callback, args, kwds)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pop_all(self): """ Preserve the context stack by transferring it to a new instance """
ret = ExitStack() ret._context_stack.append(self._context_stack.pop()) self._context_stack.append([])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, **kwargs): """Update fields on the model. :param kwargs: The model attribute values to update the model with. """
self.validate(**kwargs) for attr, value in kwargs.items(): setattr(self, attr, value) 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 validate(cls, partial=True, **kwargs): """ Validate kwargs before setting attributes on the model """
data = kwargs if not partial: data = dict(**kwargs, **{col.name: None for col in cls.__table__.c if col.name not in kwargs}) errors = defaultdict(list) for name, value in data.items(): for validator in cls._get_validators(nam...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def of(fixture_classes: Iterable[type], context: Union[None, 'torment.TestContext'] = None) -> Iterable['torment.fixtures.Fixture']: '''Obtain all Fixture objects of the provided classes. **Parameters** :``fixture_classes``: classes inheriting from ``torment.fixtures.Fixture`` :``context``: 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 register(namespace, base_classes: Tuple[type], properties: Dict[str, Any]) -> None: '''Register a Fixture class in namespace with the given properties. Creates a Fixture class (not object) and inserts it into the provided namespace. The properties is a dict but allows functions to reference other ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _prepare_mock(context: 'torment.contexts.TestContext', symbol: str, return_value = None, side_effect = None) -> None: '''Sets return value or side effect of symbol's mock in context. .. seealso:: :py:func:`_find_mocker` **Parameters** :``context``: the search context :``symbol``: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _find_mocker(symbol: str, context: 'torment.contexts.TestContext') -> Callable[[], bool]: '''Find method within the context that mocks symbol. Given a symbol (i.e. ``tornado.httpclient.AsyncHTTPClient.fetch``), find the shortest ``mock_`` method that resembles the symbol. Resembles means the lowerc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _resolve_functions(functions: Dict[str, Callable[[Any], Any]], fixture: Fixture) -> None: '''Apply functions and collect values as properties on fixture. Call functions and apply their values as properteis on fixture. Functions will continue to get applied until no more functions resolve. All unres...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _unique_class_name(namespace: Dict[str, Any], uuid: uuid.UUID) -> str: '''Generate unique to namespace name for a class using uuid. **Parameters** :``namespace``: the namespace to verify uniqueness against :``uuid``: the "unique" portion of the name **Return Value(s)** A unique stri...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def run(self) -> None: '''Calls sibling with exception expectation.''' with self.context.assertRaises(self.error.__class__) as error: super().run() self.exception = error.exception
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cache_keys(keys): """Allow debugging via PyCharm"""
d = known_keys() known_names = dict(zip(d.values(), d.keys())) for k in keys: i = (ord(k),) if len(k) == 1 else known_names[k] _key_cache.insert(0, 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 _get_keycodes(): """Read keypress giving a tuple of key codes A 'key code' is the ordinal value of characters read For example, pressing 'A' will give (65,) ...
try: return _key_cache.pop() except IndexError: pass result = [] terminators = 'ABCDFHPQRS~' with TerminalContext(): code = get_ord() result.append(code) if code == 27: with TimerContext(0.1) as timer: code = get_ord() ...
<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_key(): """Get a key from the keyboard as a string A 'key' will be a single char, or the name of an extended key """
character_name = chr codes = _get_keycodes() if len(codes) == 1: code = codes[0] if code >= 32: return character_name(code) return control_key_name(code) return get_extended_key_name(codes)
<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_ports_on_br(self, bridge='br-ex', ports=['eth3']): """Check ports exist on bridge. ovs-vsctl list-ports bridge """
LOG.info("RPC: check_ports_on_br bridge: %s, ports: %s" % (bridge, ports)) cmd = ['ovs-vsctl', 'list-ports', bridge] stdcode, stdout = agent_utils.execute(cmd, root=True) data = dict() if stdcode == 0: for port in ports: if port in st...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ping(self, ips, boardcast=False, count=2, timeout=2, interface=None): """Ping host or broadcast. ping host -c 2 -W 2 """
cmd = ['ping', '-c', str(count), '-W', str(timeout)] True if not interface else cmd.extend(['-I', interface]) True if not boardcast else cmd.append('-b') # Batch create subprocess data = dict() try: for ip in ips: stdcode, stdout = agent_utils...
<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_vlan_to_interface(self, interface, vlan_id): """Add vlan interface. ip link add link eth0 name eth0.10 type vlan id 10 """
subif = '%s.%s' % (interface, vlan_id) vlan_id = '%s' % vlan_id cmd = ['ip', 'link', 'add', 'link', interface, 'name', subif, 'type', 'vlan', 'id', vlan_id] stdcode, stdout = agent_utils.execute(cmd, root=True) if stdcode == 0: return agent_utils.make_...
<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_interface(self, interface='eth0'): """Interface info. ifconfig interface """
LOG.info("RPC: get_interface interfae: %s" % interface) code, message, data = agent_utils.get_interface(interface) return agent_utils.make_response(code, message, 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 setup_link(self, interface, cidr): """Setup a link. ip addr add dev interface ip link set dev interface up """
# clear old ipaddr in interface cmd = ['ip', 'addr', 'flush', 'dev', interface] agent_utils.execute(cmd, root=True) ip = IPNetwork(cidr) cmd = ['ip', 'addr', 'add', cidr, 'broadcast', str(ip.broadcast), 'dev', interface] stdcode, stdout = agent_utils.execu...
<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_iperf_server(self, protocol='TCP', port=5001, window=None): """iperf -s """
iperf = iperf_driver.IPerfDriver() try: data = iperf.start_server(protocol='TCP', port=5001, window=None) return agent_utils.make_response(code=0, data=data) except: message = 'Start iperf server failed!' return agent_utils.make_response(code=1, 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 isreference(a): """ Tell whether a variable is an object reference. Due to garbage collection, some objects happen to get the id of a distinct variable. As a...
return False return id(a) != id(copy.copy(a)) check = ('__dict__', '__slots__') for attr in check: try: getattr(a, attr) except (SystemExit, KeyboardInterrupt): raise except: pass else: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lookup_type(storable_type): """ Look for the Python type that corresponds to a storable type name. """
if storable_type.startswith('Python'): _, module_name = storable_type.split('.', 1) else: module_name = storable_type #type_name, module_name = \ names = [ _name[::-1] for _name in module_name[::-1].split('.', 1) ] if names[1:]: type_name, module_name = names 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 poke(exposes): """ Default serializer factory. Arguments: exposes (iterable): attributes to serialized. Returns: callable: serializer (`poke` routine). """
def _poke(store, objname, obj, container, visited=None, _stack=None): try: sub_container = store.newContainer(objname, obj, container) except (SystemExit, KeyboardInterrupt): raise except: raise ValueError('generic poke not supported by store') #_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def poke_assoc(store, objname, assoc, container, visited=None, _stack=None): """ Serialize association lists. """
try: sub_container = store.newContainer(objname, assoc, container) except (SystemExit, KeyboardInterrupt): raise except: raise ValueError('generic poke not supported by store') escape_keys = assoc and not all(isinstance(iobjname, strtypes) for iobjname,_ in assoc) reported_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 default_peek(python_type, exposes): """ Autoserializer factory. Works best in Python 3. Arguments: python_type (type): type constructor. exposes (iterable):...
with_args = False make = python_type try: make() except (SystemExit, KeyboardInterrupt): raise except: make = lambda: python_type.__new__(python_type) try: make() except (SystemExit, KeyboardInterrupt): raise except: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unsafe_peek(init): """ Deserialize all the attributes available in the container and pass them in the same order as they come in the container. This is a fac...
def peek(store, container, _stack=None): return init(*[ store.peek(attr, container, _stack=_stack) for attr in container ]) return peek
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def peek_with_kwargs(init, args=[]): """ Make datatypes passing keyworded arguments to the constructor. This is a factory function; returns the actual `peek` rou...
def peek(store, container, _stack=None): return init(\ *[ store.peek(attr, container, _stack=_stack) for attr in args ], \ **dict([ (attr, store.peek(attr, container, _stack=_stack)) \ for attr in container if attr not in args ])) return peek
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def peek(init, exposes, debug=False): """ Default deserializer factory. Arguments: init (callable): type constructor. exposes (iterable): attributes to be peek...
def _peek(store, container, _stack=None): args = [ store.peek(objname, container, _stack=_stack) \ for objname in exposes ] if debug: print(args) return init(*args) return _peek
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def peek_assoc(store, container, _stack=None): """ Deserialize association lists. """
assoc = [] try: if store.getRecordAttr('key', container) == 'escaped': for i in container: assoc.append(store.peek(i, container, _stack=_stack)) else: for i in container: assoc.append((store.strRecord(i, container), store.peek(i, container...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def most_exposes(python_type): """ Core engine for the automatic generation of storable instances. Finds the attributes exposed by the objects of a given type. M...
_exposes = set() try: # list all standard class attributes and methods: do_not_expose = set(python_type.__dir__(object) + \ ['__slots__', '__module__', '__weakref__']) # may raise `AttributeError` empty = python_type.__new__(python_type) # may raise `TypeError` except At...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def default_storable(python_type, exposes=None, version=None, storable_type=None, peek=default_peek): """ Default mechanics for building the storable instance fo...
if not exposes: for extension in expose_extensions: try: exposes = extension(python_type) except (SystemExit, KeyboardInterrupt): raise except: pass else: if exposes: break ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def not_storable(_type): """ Helper for tagging unserializable types. Arguments: _type (type): type to be ignored. Returns: Storable: storable instance that doe...
return Storable(_type, handlers=StorableHandler(poke=fake_poke, peek=fail_peek(_type)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def force_auto(service, _type): """ Helper for forcing autoserialization of a datatype with already registered explicit storable instance. Arguments: service (St...
storable = service.byPythonType(_type, istype=True) version = max(handler.version[0] for handler in storable.handlers) + 1 _storable = default_storable(_type, version=(version, )) storable.handlers.append(_storable.handlers[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 poke_native(getstate): """ Serializer factory for types which state can be natively serialized. Arguments: getstate (callable): takes an object and returns ...
def poke(service, objname, obj, container, visited=None, _stack=None): service.pokeNative(objname, getstate(obj), container) return poke
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def peek_native(make): """ Deserializer factory for types which state can be natively serialized. Arguments: make (callable): type constructor. Returns: callabl...
def peek(service, container, _stack=None): return make(service.peekNative(container)) return peek
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handler(init, exposes, version=None): """ Simple handler with default `peek` and `poke` procedures. Arguments: init (callable): type constructor. exposes (i...
return StorableHandler(poke=poke(exposes), peek=peek(init, exposes), version=version)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def namedtuple_storable(namedtuple, *args, **kwargs): """ Storable factory for named tuples. """
return default_storable(namedtuple, namedtuple._fields, *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 pokeVisited(self, objname, obj, record, existing, visited=None, _stack=None, **kwargs): """ Serialize an already serialized object. If the underlying store s...
if self.hasPythonType(obj): storable = self.byPythonType(obj).asVersion() self.pokeStorable(storable, objname, obj, record, visited=visited, \ _stack=_stack, **kwargs) else: try: self.pokeNative(objname, obj, record) except...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def defaultStorable(self, python_type=None, storable_type=None, version=None, **kwargs): """ Generate a default storable instance. Arguments: python_type (type):...
if python_type is None: python_type = lookup_type(storable_type) if self.verbose: print('generating storable instance for type: {}'.format(python_type)) self.storables.registerStorable(default_storable(python_type, \ version=version, storable_type=storabl...
<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, name: str, default: Any = None) -> Any: """Return the first value, either the default or actual"""
return super().get(name, [default])[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 getlist(self, name: str, default: Any = None) -> List[Any]: """Return the entire list"""
return super().get(name, 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 validate(self, path): """Run path against filter sets and return True if all pass"""
# Exclude hidden files and folders with '.' prefix if os.path.basename(path).startswith('.'): return False # Check that current path level is more than min path and less than max path if not self.check_level(path): return False if self.filters: ...
<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_thread(cls, backend, *args, **kwargs): """Create a comment thread for the desired backend. :arg backend: String name of backend (e.g., 'file', 'githu...
ct_cls = cls._known_backends.get(backend) if not ct_cls: return None return ct_cls(*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 find_dossier(data): ''' Find dossier with reference matching either 'ref_an' or 'ref_sen', create it if not found. Ensure its reference is 'ref_an' if both fields are present. ''' changed = False dossier = None reffield = None for field in [k for k in ('ref_an', 'ref_sen') if ...