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 choice(opts, default=1, text='Please make a choice.'): """ Prompt the user to select an option @param opts: List of tuples containing options in (key, value)...
opts_len = len(opts) opts_enum = enumerate(opts, 1) opts = list(opts) for key, opt in opts_enum: click.echo('[{k}] {o}'.format(k=key, o=opt[1] if isinstance(opt, tuple) else opt)) click.echo('-' * 12) opt = click.prompt(text, default, type=click.IntRange(1, opts_len)) opt = opts[o...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def styled_status(enabled, bold=True): """ Generate a styled status string @param enabled: Enabled / Disabled boolean @type enabled: bool @param bold: Display st...
return click.style('Enabled' if enabled else 'Disabled', 'green' if enabled else 'red', bold=bold)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def domain_parse(url): """ urlparse wrapper for user input @type url: str @rtype: urlparse.ParseResult """
url = url.lower() if not url.startswith('http://') and not url.startswith('https://'): url = '{schema}{host}'.format(schema='http://', host=url) url = urlparse(url) if not url.hostname: raise ValueError('Invalid domain provided') # Strip www prefix any additional URL data 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 http_session(cookies=None): """ Generate a Requests session @param cookies: Cookies to load. None loads the app default CookieJar. False disables cookie load...
session = requests.Session() if cookies is not False: session.cookies.update(cookies or cookiejar()) session.headers.update({'User-Agent': 'ipsv/{v}'.format(v=ips_vagrant.__version__)}) return session
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cookiejar(name='session'): """ Ready the CookieJar, loading a saved session if available @rtype: cookielib.LWPCookieJar """
log = logging.getLogger('ipsv.common.cookiejar') spath = os.path.join(config().get('Paths', 'Data'), '{n}.txt'.format(n=name)) cj = cookielib.LWPCookieJar(spath) log.debug('Attempting to load session file: %s', spath) if os.path.exists(spath): try: cj.load() log.info...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sendUserInvitationRevoked(self, context={}): """ Sent when user is invitation is revoked """
organization, invited, invitator = context['invite'].organization, context['invite'].invited, context['invite'].invitator # invited user email self.__init__(organization, async_mail=self.async_mail, override_receiver=invited.email, locale=invited.locale) self.sendEmail('userInvitedRevoked-toUser', 'You...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sendUserLeft(self, context={}): """ Sent when user leaves organization """
self.__init__(context['organization'], async_mail=self.async_mail, override_receiver=context['user'].email, locale=context['user'].locale) self.sendEmail('userLeft-toUser', 'You have left an organization', context) self.__init__(context['organization'], async_mail=self.async_mail, override_receiver=contex...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dynamic_zoom_plot(x, y, N, RegionStartSize=1000): """ plots 2 time traces, the top is the downsampled time trace the bottom is the full time trace. """
x_lowres = x[::N] y_lowres = y[::N] ax1 = _plt.subplot2grid((2, 1), (0, 0), colspan=1) ax2 = _plt.subplot2grid((2, 1), (1, 0)) fig = ax1.get_figure() _plt.subplots_adjust(bottom=0.25) # makes space at bottom for sliders CenterTime0 = len(x)/2 TimeWidth0 = len(x)/RegionSta...
<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_config(fname='.rdo.conf', start=None): """Go up until you find an rdo config. """
start = start or os.getcwd() config_file = os.path.join(start, fname) if os.path.isfile(config_file): return config_file parent, _ = os.path.split(start) if parent == start: raise Exception('Config file not found') return find_config(fname, parent)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def departure(stop, destination): """Get departure information."""
from pyruter.api import Departures async def get_departures(): """Get departure information.""" async with aiohttp.ClientSession() as session: data = Departures(LOOP, stop, destination, session) await data.get_departures() print(json.dumps(data.departures, 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 destinations(stop): """Get destination information."""
from pyruter.api import Departures async def get_destinations(): """Get departure information.""" async with aiohttp.ClientSession() as session: data = Departures(LOOP, stop, session=session) result = await data.get_final_destination() print(json.dumps(resul...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authenticated_redirect(view_func=None, path=None): """ Decorator for an already authenticated user that we don't want to serve a view to. Instead we send the...
default_path = getattr(settings, 'DEFAULT_AUTHENTICATED_PATH', 'dashboard') if view_func is None: return functools.partial(authenticated_redirect, path=path) @functools.wraps(view_func) def _wrapped_view(request, *args, **kwargs): if path == request.path.replace('/', ''): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process(self, job_id): """ Process a job by the queue """
self._logger.info( '{:.2f}: Process job {}'.format(self._env.now, job_id) ) # log time of commencement of service self._observer.notify_service(time=self._env.now, job_id=job_id) # draw a new service time try: service_time = next(self._service_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate(self): """ Source generates jobs according to the interarrival time distribution """
inter_arrival_time = 0.0 while True: # wait for next job to arrive try: yield self._env.timeout(inter_arrival_time) except TypeError: # error: arrival time of wrong type error_msg = ( "arrival time ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse(cls, rule_string): """ returns a list of rules a single line may yield multiple rules """
result = parser.parseString(rule_string) rules = [] # breakout port ranges into multple rules kwargs = {} kwargs['address'] = result.ip_and_mask or None kwargs['group'] = result.security_group or None kwargs['group_name'] = result.group_name or None fo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bind_to(self, argspec, dispatcher): """ Add our function to dispatcher """
self.bound_to[argspec.key].add((argspec, dispatcher)) dispatcher.bind(self.f, argspec)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unbind(self): """ Unbind from dispatchers and target function. :return: set of tuples containing [argspec, dispatcher] """
args_dispatchers = set() f = self._wf() if f is not None: for ad_list in self.bound_to.values(): args_dispatchers.update(ad_list) for argspec, dispatcher in ad_list: dispatcher.unbind(self.f, argspec) del f.__dict__['__...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def insert_taxon_in_new_fasta_file(self, aln): """primer4clades infers the codon usage table from the taxon names in the sequences. These names need to be enclos...
new_seq_records = [] for seq_record in SeqIO.parse(aln, 'fasta'): new_seq_record_id = "[{0}] {1}".format(self.taxon_for_codon_usage, seq_record.id) new_seq_record = SeqRecord(seq_record.seq, id=new_seq_record_id) new_seq_records.append(new_seq_record) base_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 group_primers(self, my_list): """Group elements in list by certain number 'n'"""
new_list = [] n = 2 for i in range(0, len(my_list), n): grouped_primers = my_list[i:i + n] forward_primer = grouped_primers[0].split(" ") reverse_primer = grouped_primers[1].split(" ") formatted_primers = ">F_{0}\n{1}".format(forward_primer[1], fo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def choose_best_amplicon(self, amplicon_tuples): """Iterates over amplicon tuples and returns the one with highest quality and amplicon length. """
quality = 0 amplicon_length = 0 best_amplicon = None for amplicon in amplicon_tuples: if int(amplicon[4]) >= quality and int(amplicon[5]) >= amplicon_length: quality = int(amplicon[4]) amplicon_length = int(amplicon[5]) best_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 run(): """ Run a command in the context of the system dependencies. """
parser = argparse.ArgumentParser() parser.add_argument( '--deps-def', default=data_lines_from_file("system deps.txt") + data_lines_from_file("build deps.txt"), help="A file specifying the dependencies (one per line)", type=data_lines_from_file, dest="spec_deps") parser.add_argument( '--dep', action="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 dependency_context(package_names, aggressively_remove=False): """ Install the supplied packages and yield. Finally, remove all packages that were installe...
installed_packages = [] log = logging.getLogger(__name__) try: if not package_names: logging.debug('No packages requested') if package_names: lock = yg.lockfile.FileLock( '/tmp/.pkg-context-lock', timeout=30 * 60) log.info('Acquiring lock to perform install') lock.acquire() log.info('Inst...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tarball_context(url, target_dir=None, runner=None, pushd=pushd): """ Get a tarball, extract it, change to that directory, yield, then clean up. `runner` ...
if target_dir is None: target_dir = os.path.basename(url).replace('.tar.gz', '').replace( '.tgz', '') if runner is None: runner = functools.partial(subprocess.check_call, shell=True) # In the tar command, use --strip-components=1 to strip the first path and # then # use -C to cause the files to be extrac...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def infer_compression(url): """ Given a URL or filename, infer the compression code for tar. """
# cheat and just assume it's the last two characters compression_indicator = url[-2:] mapping = dict( gz='z', bz='j', xz='J', ) # Assume 'z' (gzip) if no match return mapping.get(compression_indicator, 'z')
<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_dir(remover=shutil.rmtree): """ Create a temporary directory context. Pass a custom remover to override the removal behavior. """
temp_dir = tempfile.mkdtemp() try: yield temp_dir finally: remover(temp_dir)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def repo_context(url, branch=None, quiet=True, dest_ctx=temp_dir): """ Check out the repo indicated by url. If dest_ctx is supplied, it should be a context ma...
exe = 'git' if 'git' in url else 'hg' with dest_ctx() as repo_dir: cmd = [exe, 'clone', url, repo_dir] if branch: cmd.extend(['--branch', branch]) devnull = open(os.path.devnull, 'w') stdout = devnull if quiet else None subprocess.check_call(cmd, stdout=stdout) yield repo_dir
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def device_from_request(request): """ Determine's the device name from the request by first looking for an overridding cookie, and if not found then matching the...
from yacms.conf import settings try: # If a device was set via cookie, match available devices. for (device, _) in settings.DEVICE_USER_AGENTS: if device == request.COOKIES["yacms-device"]: return device except KeyError: # If a device wasn't set via cooki...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def body(self): """ String from `wsgi.input`. """
if self._body is None: if self._fieldstorage is not None: raise ReadBodyTwiceError() clength = int(self.environ('CONTENT_LENGTH') or 0) self._body = self._environ['wsgi.input'].read(clength) if isinstance(self._body, bytes): 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 fieldstorage(self): """ `cgi.FieldStorage` from `wsgi.input`. """
if self._fieldstorage is None: if self._body is not None: raise ReadBodyTwiceError() self._fieldstorage = cgi.FieldStorage( environ=self._environ, fp=self._environ['wsgi.input'] ) return self._fieldstorage
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def params(self): """ Parsed query string. """
if self._params is None: self._params = self.arg_container() data = compat.parse_qs(self.environ('QUERY_STRING') or '') for k, v in data.items(): self._params[k] = v[0] return self._params
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cookie(self): """ Cookie values. """
if self._cookie is None: self._cookie = self.arg_container() data = compat.parse_qs(self.http_header('cookie') or '') for k, v in data.items(): self._cookie[k.strip()] = v[0] return self._cookie
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def data(self): """ Values in request body. """
if self._data is None: self._data = self.arg_container() if isinstance(self.fieldstorage.value, list): for k in self.fieldstorage.keys(): fname = self.fieldstorage[k].filename if fname: self._data[k] = (fna...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def drain(self, p): '''Reads the named pipe.''' self.logging.info('Started.') fd = os.open(p, os.O_RDWR | os.O_NONBLOCK) gevent_os.make_nonblocking(fd) while self.loop(): try: lines = gevent_os.nb_read(fd, 4096).splitlines() if len(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 add(self, handler, name=None, exception_handlers=()): """Add a handler to the route. :param handler: The "handler" callable to add. :param name: Optional. Wh...
self.route.append((name, handler, exception_handlers))
<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(self, match, handler): """Register a handler with the Router. :param match: The first argument passed to the :meth:`match` method when checking against t...
self.routes.append((match, ( Route(handler) if not isinstance(handler, Route) else handler )))
<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_annotated_data_x_y(timestamps, data, lbls): """ DOESN'T work with OVERLAPPING labels :param timestamps: :param data: :param lbls: :return: """
timestamps = np.array(timestamps) timestamp_step = timestamps[3]-timestamps[2] current_new_timestamp = 0.0 new_timestamps = [] X = None Y = [] classes = [] for i in range(0, len(timestamps)): for lbl in lbls: if lbl.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 scope_logger(cls): """ Class decorator for adding a class local logger Example: """
cls.log = logging.getLogger('{0}.{1}'.format(cls.__module__, cls.__name__)) return cls
<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): """Run the thread, logging everything. """
self._finished.clear() for line in iter(self.pipeReader.readline, ''): logging.log(self.level, line.strip('\n')) self.pipeReader.close() self._finished.set()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(self, source, filepath=None): """ Load source as manifest attributes Arguments: source (string or file-object): CSS source to parse and serialize to fi...
# Set _path if source is a file-like object try: self._path = source.name except AttributeError: self._path = filepath # Get source content either it's a string or a file-like object try: source_content = source.read() except Attribut...
<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_rule(self, name, properties): """ Set a rules as object attribute. Arguments: name (string): Rule name to set as attribute name. properties (dict): Dic...
self._rule_attrs.append(name) setattr(self, name, properties)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_rule(self, name): """ Remove a rule from attributes. Arguments: name (string): Rule name to remove. """
self._rule_attrs.remove(name) delattr(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 to_json(self, indent=4): """ Serialize metas and reference attributes to a JSON string. Keyword Arguments: indent (int): Space indentation, default to ``4``...
agregate = { 'metas': self.metas, } agregate.update({k: getattr(self, k) for k in self._rule_attrs}) return json.dumps(agregate, indent=indent)
<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(self, to, cc, subject, body, atts=None, delete=False): """Send an email action. :param to: receivers list :param cc: copy user list :param subject: emai...
email_cnt = MIMEMultipart() email_cnt['From'] = Header(self.smtp_user, CHARSET_ENCODING) email_cnt['To'] = Header(';'.join(to), CHARSET_ENCODING) email_cnt['Cc'] = Header(';'.join(cc), CHARSET_ENCODING) email_cnt['Subject'] = Header(subject, CHARSET_ENCODING) email_cnt['...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restrict(self, addr): """ Drop an address from the set of addresses this proxy is permitted to introduce. :param addr: The address to remove. """
# Remove the address from the set ip_addr = _parse_ip(addr) if ip_addr is None: LOG.warn("Cannot restrict address %r from proxy %s: " "invalid address" % (addr, self.address)) else: self.excluded.add(addr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def accept(self, addr): """ Add an address to the set of addresses this proxy is permitted to introduce. :param addr: The address to add. """
# Add the address to the set ip_addr = _parse_ip(addr) if ip_addr is None: LOG.warn("Cannot add address %r to proxy %s: " "invalid address" % (addr, self.address)) else: self.accepted.add(addr)
<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, proxy_ip, client_ip): """ Looks up the proxy identified by its IP, then verifies that the given client IP may be introduced by that proxy. :pa...
# First, look up the proxy if self.pseudo_proxy: proxy = self.pseudo_proxy elif proxy_ip not in self.proxies: return False else: proxy = self.proxies[proxy_ip] # Now, verify that the client is valid return client_ip in proxy
<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_auth(func): """Handle authentication checks. .. py:decorator:: requires_auth Checks if the token has expired and performs authentication if needed. ...
@six.wraps(func) def wrapper(self, *args, **kwargs): if self.token_expired: self.authenticate() return func(self, *args, **kwargs) return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def headers(self): """Provide access to updated headers."""
self._headers.update(**{'Accept-Language': self.language}) if self.__token: self._headers.update( **{'Authorization': 'Bearer %s' % self.__token}) return self._headers
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def token_expired(self): """Provide access to flag indicating if token has expired."""
if self._token_timer is None: return True return timeutil.is_newer_than(self._token_timer, timeutil.ONE_HOUR)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def session(self): """Provide access to request session with local cache enabled."""
if self._session is None: self._session = cachecontrol.CacheControl( requests.Session(), cache=caches.FileCache('.tvdb_cache')) return self._session
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _exec_request(self, service, method=None, path_args=None, data=None, params=None): """Execute request."""
if path_args is None: path_args = [] req = { 'method': method or 'get', 'url': '/'.join(str(a).strip('/') for a in [ cfg.CONF.tvdb.service_url, service] + path_args), 'data': json.dumps(data) if data else None, 'headers': 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 authenticate(self): """Aquire authorization token for using thetvdb apis."""
if self.__token: try: resp = self._refresh_token() except exceptions.TVDBRequestException as err: # if a 401 is the cause try to login if getattr(err.response, 'status_code', 0) == 401: resp = self._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 search_series(self, **kwargs): """Provide the ability to search for a series. .. warning:: authorization token required The following search arguments curren...
params = {} for arg, val in six.iteritems(kwargs): if arg in SERIES_BY: params[arg] = val resp = self._exec_request( 'search', path_args=['series'], params=params) if cfg.CONF.tvdb.select_first: return resp['data'][0] return re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_episodes(self, series_id, **kwargs): """All episodes for a given series. Paginated with 100 results per page. .. warning:: authorization token required T...
params = {'page': 1} for arg, val in six.iteritems(kwargs): if arg in EPISODES_BY: params[arg] = val return self._exec_request( 'series', path_args=[series_id, 'episodes', 'query'], params=params)['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 intersectingPoint(self, p): """ given a point, get intervals in the tree that are intersected. :param p: intersection point :return: the list of intersected ...
# perfect match if p == self.data.mid: return self.data.ends if p > self.data.mid: # we know all intervals in self.data begin before p (if they began after # p, they would have not included mid) we just need to find those that # end after p endAfterP = [r for r in self.data.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 intersectingInterval(self, start, end): """ given an interval, get intervals in the tree that are intersected. :param start: start of the intersecting interv...
# find all intervals in this node that intersect start and end l = [] for x in self.data.starts: xStartsAfterInterval = (x.start > end and not self.openEnded) or \ (x.start >= end and self.openEnded) xEndsBeforeInterval = (x.end < start and not self.openEnded) 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 intersectingIntervalIterator(self, start, end): """ Get an iterator which will iterate over those objects in the tree which intersect the given interval - so...
items = self.intersectingInterval(start, end) items.sort(key=lambda x: x.start) for item in items: yield item
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def initiate_tasks(self): """ Loads all tasks using `TaskLoader` from respective configuration option """
self.tasks_classes = TaskLoader().load_tasks( paths=self.configuration[Configuration.ALGORITHM][Configuration.TASKS][Configuration.PATHS])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def instantiate_tasks(self): """ All loaded tasks are initialized. Depending on configuration fails in such instantiations may be silent """
self.tasks_instances = {} for task_name, task_class in self.tasks_classes.items(): try: self.tasks_instances[task_name] = task_class() except Exception as ex: if not self.configuration[Configuration.ALGORITHM][Configuration.IOSF]: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _have(self, name=None): """Check if a configure flag is set. If called without argument, it returns all HAVE_* items. Example: """
if name is None: return ( (k, v) for k, v in self.env.items() if k.startswith('HAVE_') ) return self.env.get('HAVE_' + self.env_key(name)) == True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _lib(self, name, only_if_have=False): """Specify a linker library. Example: LDFLAGS={{ lib("rt") }} {{ lib("pthread", True) }} Will unconditionally add `-lrt...
emit = True if only_if_have: emit = self.env.get('HAVE_LIB' + self.env_key(name)) if emit: return '-l' + name 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 _with(self, option=None): """Check if a build option is enabled. If called without argument, it returns all WITH_* items. Example: """
if option is None: return ( (k, v) for k, v in self.env.items() if k.startswith('WITH_') ) return self.env.get('WITH_' + option.upper()) == True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_codes(self, codes, reject=False): """ Set the accepted or rejected codes codes list. :param codes: A list of the response codes. :param reject: If True, ...
self.codes = set(codes) self.reject = reject
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def accept(self, code): """ Determine whether to accept the given code. :param code: The response code. :returns: True if the code should be accepted, False othe...
if code in self.codes: return not self.reject return self.reject
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _needescape(c): """ Return True if character needs escaping, else False. """
return not ascii.isprint(c) or c == '"' or c == '\\' or ascii.isctrl(c)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def escape(cls, string): """ Utility method to produce an escaped version of a given string. :param string: The string to escape. :returns: The escaped version o...
return ''.join([cls._escapes[c] if cls._needescape(c) else c for c in string.encode('utf8')])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def submit(self): """ Posts the form's data and returns the resulting Page Returns Page - The resulting page """
u = urlparse(self.url) if not self.action: self.action = self.url elif self.action == u.path: self.action = self.url else: if not u.netloc in self.action: path = "/".join(u.path.split("/")[1:-1]) if self.action...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compute_hash(attributes, ignored_attributes=None): """ Computes a hash code for the given dictionary that is safe for persistence round trips """
ignored_attributes = list(ignored_attributes) if ignored_attributes else [] tuple_attributes = _convert(attributes.copy(), ignored_attributes) hasher = hashlib.sha256(str(tuple_attributes).encode('utf-8', errors='ignore')) return hasher.hexdigest()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def SimpleRowColumn(field, *args, **kwargs): """ Shortcut for simple row with only a full column """
if isinstance(field, basestring): field = Field(field, *args, **kwargs) return Row( Column(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 save(self, commit=True): """Save and send"""
contact = super(ContactFormBase, self).save() context = {'contact': contact} context.update(get_site_metas()) subject = ''.join(render_to_string(self.mail_subject_template, context).splitlines()) content = render_to_string(self.mail_content_template, context) send_mail...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bark_filter(global_conf, **local_conf): """ Factory function for Bark. Returns a function which, when passed the application, returns an instance of BarkMidd...
# First, parse the configuration conf_file = None sections = {} for key, value in local_conf.items(): # 'config' key causes a load of a configuration file; settings # in the local_conf will override settings in the # configuration file, however if key == '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 blog_post_feed(request, format, **kwargs): """ Blog posts feeds - maps format to the correct feed view. """
try: return {"rss": PostsRSS, "atom": PostsAtom}[format](**kwargs)(request) except KeyError: raise Http404()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect(self): """ Connects to RabbitMQ """
self.connection = Connection(self.broker_url) e = Exchange('mease', type='fanout', durable=False, delivery_mode=1) self.exchange = e(self.connection.default_channel) self.exchange.declare()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def publish(self, message_type, client_id, client_storage, *args, **kwargs): """ Publishes a message Uses `self.pack` instead of 'msgpack' serializer on kombu fo...
if self.connection.connected: message = self.exchange.Message( self.pack(message_type, client_id, client_storage, args, kwargs)) self.exchange.publish(message, routing_key='')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect(self): """ Connects to RabbitMQ and starts listening """
logger.info("Connecting to RabbitMQ on {broker_url}...".format( broker_url=self.broker_url)) super(RabbitMQSubscriber, self).connect() q = Queue(exchange=self.exchange, exclusive=True, durable=False) self.queue = q(self.connection.default_channel) self.queue.decla...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def listen(self): """ Listens to messages """
with Consumer(self.connection, queues=self.queue, on_message=self.on_message, auto_declare=False): for _ in eventloop(self.connection, timeout=1, ignore_timeouts=True): 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 main_loop(self): """Runs the main game loop."""
while True: for e in pygame.event.get(): self.handle_event(e) self.step() pygame.time.wait(5)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def quit(self, event): """Quit the game."""
self.logger.info("Quitting.") self.on_exit() sys.exit()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setCredentials(self, user, password): """! Set authentication credentials. @param user Username. @param password Password. """
self._checkUserAndPass(user, password) self.user = user self.password = password
<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_setting_with_envfallback(setting, default=None, typecast=None): """ Get the given setting and fall back to the default of not found in ``django.conf.sett...
try: from django.conf import settings except ImportError: return default else: fallback = getattr(settings, setting, default) value = os.environ.get(setting, fallback) if typecast: value = typecast(value) return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_file_locations(self, file_locations=[]): """ Adds a list of file locations to the current list Args: file_locations: list of file location tuples """
if not hasattr(self, '__file_locations__'): self.__file_locations__ = copy.copy(file_locations) else: self.__file_locations__ += copy.copy(file_locations)
<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, **kwargs): """ Reset the triplestore with all of the data """
self.drop_all(**kwargs) file_locations = self.__file_locations__ self.__file_locations__ = [] self.load(file_locations, **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 drop_all(self, **kwargs): """ Drops all definitions"""
conn = self.__get_conn__(**kwargs) conn.update_query("DROP ALL") self.loaded = [] self.loaded_times = {}
<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_file(self, filepath, **kwargs): """ loads a file into the defintion triplestore args: filepath: the path to the file """
log.setLevel(kwargs.get("log_level", self.log_level)) filename = os.path.split(filepath)[-1] if filename in self.loaded: if self.loaded_times.get(filename, datetime.datetime(2001,1,1)).timestamp() \ < os.path.getmtime(filepath): ...
<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_directory(self, directory, **kwargs): """ loads all rdf files in a directory args: directory: full path to the directory """
log.setLevel(kwargs.get("log_level", self.log_level)) conn = self.__get_conn__(**kwargs) file_extensions = kwargs.get('file_extensions', conn.rdf_formats) file_list = list_files(directory, file_extensions, kwargs.get('include...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(fileobj, version=None): """Read tz data from a binary file. @param fileobj: @param version: @return: TZFileData """
magic = fileobj.read(5) if magic[:4] != b"TZif": raise ValueError("not a zoneinfo file") if version is None: version = int(magic[4:]) if magic[4] else 0 fileobj.seek(20) # Read the counts: # [0] - The number of UT/local indicators stored in the file. # [1] - The number of 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 convert(data): """ convert a standalone unicode string or unicode strings in a mapping or iterable into byte strings. """
if isinstance(data, unicode): return data.encode('utf-8') elif isinstance(data, str): return data elif isinstance(data, collections.Mapping): return dict(map(convert, data.iteritems())) elif isinstance(data, collections.Iterable): return type(data)(map(convert, 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 make_fetch_func(base_url, async, **kwargs): """ make a fetch function based on conditions of 1) async 2) ssl """
if async: client = AsyncHTTPClient(force_instance=True, defaults=kwargs) return partial(async_fetch, httpclient=client) else: client = HTTPClient(force_instance=True, defaults=kwargs) return partial(sync_fetch, httpclient=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 _getAuthHeaders(self): """ Get authentication headers. If we have valid header data already, they immediately return it. If not, then get new authentication ...
def _handleAuthBody(body): self.msg("_handleAuthBody: %(body)s", body=body) try: body_parsed = json.loads(body) access_token = body_parsed['access']['token'] tenant_id = access_token['tenant']['id'].encode('ascii') auth_t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(): """ Project's main method which will parse the command line arguments, run a scan using the TagCubeClient and exit. """
cmd_args = TagCubeCLI.parse_args() try: tagcube_cli = TagCubeCLI.from_cmd_args(cmd_args) except ValueError, ve: # We get here when there are no credentials configured print '%s' % ve sys.exit(1) try: sys.exit(tagcube_cli.run()) except ValueError, ve: ...
<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(filetypes): """ Decorator to register a class as a checker for extensions. """
def decorator(clazz): for ext in filetypes: checkers.setdefault(ext, []).append(clazz) return clazz return decorator
<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(self, paths): """ Return list of error dicts for all found errors in paths. The default implementation expects `tool`, and `tool_err_re` to be defined....
if not paths: return () cmd_pieces = [self.tool] cmd_pieces.extend(self.tool_args) return self._check_std(paths, cmd_pieces)
<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_version(cls): """ Return the version number of the tool. """
cmd_pieces = [cls.tool, '--version'] process = Popen(cmd_pieces, stdout=PIPE, stderr=PIPE) out, err = process.communicate() if err: return '' else: return out.splitlines()[0].strip()
<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_std(self, paths, cmd_pieces): """ Run `cmd` as a check on `paths`. """
cmd_pieces.extend(paths) process = Popen(cmd_pieces, stdout=PIPE, stderr=PIPE) out, err = process.communicate() lines = out.strip().splitlines() + err.strip().splitlines() result = [] for line in lines: match = self.tool_err_re.match(line) if not ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replace(dict,line): """ Find and replace the special words according to the dictionary. Parameters ========== dict : Dictionary A dictionary derived from a y...
words = line.split() new_line = "" for word in words: fst = word[0] last = word[-1] # Check if the word ends with a punctuation if last == "," or last == ";" or last == ".": clean_word = word[0:-1] last = last + " " elif last == "]": ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def translate(src_filename, dest_filename, dest_lang, src_lang='auto', specialwords_filename=''): """ Converts a source file to a destination file in the selecte...
translator = Translator() # Initialize translator object with open(src_filename) as srcfile, open(dest_filename, 'w') as destfile: lines = srcfile.readlines() specialwords_dict = {} # If special words file exists, place special word mappings into specialwords_dict if specialw...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deprecated(f): """Decorate a function object as deprecated. Work nicely with the @command and @subshell decorators. Add a __deprecated__ field to the input o...
def inner_func(*args, **kwargs): print(textwrap.dedent("""\ This command is deprecated and is subject to complete removal at any later version without notice. """)) f(*args, **kwargs) inner_func.__deprecated__ = True inner_func.__doc__ = f.__d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def helper(*commands): """Decorate a function to be the helper function of commands. Arguments: commands: Names of command that should trigger this function obje...
def decorated_func(f): f.__help_targets__ = list(commands) return f return decorated_func
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def completer(*commands): """Decorate a function to be the completer function of commands. Arguments: commands: Names of command that should trigger this functio...
def decorated_func(f): f.__complete_targets__ = list(commands) return f return decorated_func
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def subshell(shell_cls, *commands, **kwargs): """Decorate a function to conditionally launch a _ShellBase subshell. Arguments: shell_cls: A subclass of _ShellBas...
def decorated_func(f): def inner_func(self, cmd, args): retval = f(self, cmd, args) # Do not launch the subshell if the return value is None. if not retval: return # Pass the context (see the doc string) to the subshell if the # re...