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 __public_objs(self): """ Returns a dictionary mapping a public identifier name to a Python object. """
members = dict(inspect.getmembers(self.module)) return dict([(name, obj) for name, obj in members.items() if self.__is_exported(name, inspect.getmodule(obj))])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __new_submodule(self, name, obj): """ Create a new submodule documentation object for this `obj`, which must by a Python module object and pass along any set...
# Forcefully set the module name so that it is always the absolute # import path. We can't rely on `obj.__name__`, since it doesn't # necessarily correspond to the public exported name of the module. obj.__dict__['__budoc_module_name'] = '%s.%s' % (self.refname, name) return Mod...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def class_variables(self): """ Returns all documented class variables in the class, sorted alphabetically as a list of `pydoc.Variable`. """
p = lambda o: isinstance(o, Variable) and self.module._docfilter(o) return filter(p, self.doc.values())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fill_inheritance(self): """ Traverses this class's ancestor list and attempts to fill in missing documentation from its ancestor's documentation. The first ...
mro = filter(lambda c: c != self and isinstance(c, Class), self.module.mro(self)) def search(d, fdoc): for c in mro: doc = fdoc(c) if d.name in doc and isinstance(d, type(doc[d.name])): return doc[d.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 params(self): """ Returns a list where each element is a nicely formatted parameter of this function. This includes argument lists, keyword arguments and def...
def fmt_param(el): if isinstance(el, str) or isinstance(el, unicode): return el else: return '(%s)' % (', '.join(map(fmt_param, el))) try: getspec = getattr(inspect, 'getfullargspec', inspect.getargspec) s = getspec(self.fu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _defaults(): """Returns a dict of default args from the environment, which can be overridden by command line args. """
d = {} d['url'] = os.environ.get('BUGZSCOUT_URL') d['user'] = os.environ.get('BUGZSCOUT_USER') d['project'] = os.environ.get('BUGZSCOUT_PROJECT') d['area'] = os.environ.get('BUGZSCOUT_AREA') return 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 _from_args(args): """Factory method to create a new instance from command line args. :param args: instance of :class:`argparse.Namespace` """
return bugzscout.BugzScout(args.url, args.user, args.project, args.area)
<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_logging(verbose): """Enable logging o stream."""
hdlr = logging.StreamHandler() hdlr.setFormatter(logging.Formatter( '%(asctime)s [%(levelname)s] [%(module)s] %(message)s')) LOG.addHandler(hdlr) if verbose: LOG.setLevel(logging.DEBUG) LOG.debug('Verbose output enabled.') else: LOG.setLevel(logging.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 _parse_args(): """Parse and return command line arguments."""
parser = argparse.ArgumentParser( description=__doc__, formatter_class=_CliFormatter) parser.add_argument('-v', '--verbose', action='store_true', help='Enable verbose output.') fb_group = parser.add_argument_group('FogBugz arguments') fb_group.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 main(): """Create a new instance and publish an error from command line args. There is a console script for invoking this function from the command line dire...
args = _parse_args() _init_logging(args.verbose) client = _from_args(args) client.submit_error(args.description, args.extra, default_message=args.default_message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def plot_lf_hf(x, xlf, xhf, title=''): '''Plot original signal, low-pass filtered, and high-pass filtered signals Args ---- x: ndarray Signal data array xlf: ndarray Low-pass filtered signal xhf: ndarray High-pass filtered signal title: str Main title of plot...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def plot_acc_pry_depth(A_g_lf, A_g_hf, pry_deg, depths, glide_mask=None): '''Plot the acceleration with the pitch, roll, and heading Args ---- A_g_lf: ndarray Low-pass filtered calibration accelerometer signal A_g_hf: ndarray High-pass filtered calibration accelerometer signal p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def plot_welch_perdiogram(x, fs, nperseg): '''Plot Welch perdiogram Args ---- x: ndarray Signal array fs: float Sampling frequency nperseg: float Length of each data segment in PSD ''' import scipy.signal import numpy # Generate a test signal, a 2 Vrms 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 plot_data_filter(data, data_f, b, a, cutoff, fs): '''Plot frequency response and filter overlay for butter filtered data Args ---- data: ndarray Signal array data_f: float Signal sampling rate b: array_like Numerator of a linear filter a: array_like Denom...
<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_url(self, host, sport, method, id, format, parameters): """ build url from args """
path = "/".join(filter(None, (sport, method, id))) url = "https://" + host + "/" + path + "." + format if parameters: paramstring = urllib.parse.urlencode(parameters) url = url + "?" + paramstring return url
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_teams(self): """ Return json current roster of team """
return self.make_request(host="erikberg.com", sport='nba', method="teams", id=None, format="json", parameters={})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def prh(ax, ay, az): '''Calculate the pitch, roll and heading for triaxial movement signalsi Args ---- ax: ndarray x-axis acceleration values ay: ndarray y-axis acceleration values az: ndarray z-axis acceleration values Returns ------- pitch: ndarray ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def absdeg(deg): '''Change from signed degrees to 0-180 or 0-360 ranges deg: ndarray Movement data in pitch, roll, yaw (degrees) Returns ------- deg_abs: ndarray Movement translated from -180:180/-90:90 degrees to 0:360/0:180 degrees Example ------- deg = numpy.array([...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def acceleration_magnitude(ax, ay, az): '''Cacluate the magnitude of 3D acceleration Args ---- ax: ndarray x-axis acceleration values ay: ndarray y-axis acceleration values az: ndarray z-axis acceleration values Returns ------- acc_mag: ndarray Magni...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pstd(self, *args, **kwargs): """ Console to STDOUT """
kwargs['file'] = self.out self.print(*args, **kwargs) sys.stdout.flush()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def perr(self, *args, **kwargs): """ Console to STERR """
kwargs['file'] = self.err self.print(*args, **kwargs) sys.stderr.flush()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pverb(self, *args, **kwargs): """ Console verbose message to STDOUT """
if not self.verbose: return self.pstd(*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 read(self, prompt='', clean=lambda x: x): """ Display a prompt and ask user for input A function to clean the user input can be passed as ``clean`` argument....
ans = read(prompt + ' ') return clean(ans)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rvpl(self, prompt, error='Entered value is invalid', intro=None, validator=lambda x: x != '', clean=lambda x: x.strip(), strict=True, default=None): """ Star...
if intro: self.pstd(utils.rewrap_long(intro)) val = self.read(prompt, clean) while not validator(val): if not strict: return default if hasattr(error, '__call__'): self.perr(error(val)) else: self.pe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def yesno(self, prompt, error='Please type either y or n', intro=None, default=None): """ Ask user for yes or no answer The prompt will include a typical '(y/n):...
if default is None: prompt += ' (y/n):' else: if default is True: prompt += ' (Y/n):' default = 'y' if default is False: prompt += ' (y/N):' default = 'n' validator = lambda x: x in ['y', 'yes', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def menu(self, choices, prompt='Please choose from the provided options:', error='Invalid choice', intro=None, strict=True, default=None, numerator=lambda x: [i +...
numbers = list(numerator(len(choices))) labels = (label for _, label in choices) values = [value for value, _ in choices] # Print intro and menu itself if intro: self.pstd('\n' + utils.rewrap_long(intro)) for n, label in zip(numbers, labels): 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 readpipe(self, chunk=None): """ Return iterator that iterates over STDIN line by line If ``chunk`` is set to a positive non-zero integer value, then the read...
read = [] while True: l = sys.stdin.readline() if not l: if read: yield read return return if not chunk: yield l else: read.append(l) 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 error(self, msg='Program error: {err}', exit=None): """ Error handler factory This function takes a message with optional ``{err}`` placeholder and returns a...
def handler(exc): if msg: self.perr(msg.format(err=exc)) if exit is not None: self.quit(exit) return handler
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: prog='.', excs=(Exception,), reraise=True): """ Context manager for handling interactive prog indication This context manager streamlines presenting banners and ...
if not onerror: onerror = self.error() if type(onerror) is str: onerror = self.error(msg=onerror) self.pverb(msg, end=sep) prog = progress.Progress(self.pverb, end=end, abrt=abrt, prog=prog) try: yield prog prog.end() excep...
<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(self, name_or_index, word): """ Write a word in the Register with the name ``name_or_index`` or with the index ``name_or_index``. ``name_or_index...
if(isinstance(name_or_index, str)): if(name_or_index in self.registers_by_name): self.registers_by_name[name_or_index].write(word) else: raise NameError("No Register with name '{}'".format(name_or_index)) elif( isinstance(name_or_index, int)): if(name_or_index < len(self.registers_by_index)): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_interrupt(self, interrupt): """ Adds the interrupt to the internal interrupt storage ``self.interrupts`` and registers the interrupt address in the...
self.interrupts.append(interrupt) self.constants[interrupt.name] = interrupt.address
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def interrupt(self, address): """ Interrupts the Processor and forces him to jump to ``address``. If ``push_pc`` is enabled this will push the PC to the st...
if(self.push_pc): self.memory_bus.write_word(self.sp, self.pc) self._set_sp(self.sp - 1) self._set_pc(address)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _raw_recv(self): """ Return the next available IRC message in the buffer. """
with self.lock: if self._index >= len(self._buffer): self._mcon() if self._index >= 199: self._resetbuffer() self._mcon() msg = self._buffer[self._index] while self.find(msg, 'PING :'): self._index +...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def post(json_data, url, dry_run=False): """ POST json data to the url provided and verify the requests was successful """
if dry_run: info('POST: %s' % json.dumps(json_data, indent=4)) else: response = SESSION.post(url, data=json.dumps(json_data), headers={'content-type': 'application/json'}) if response.status_code != 200: raise...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def push_json_file(json_file, url, dry_run=False, batch_size=100, anonymize_fields=[], remove_fields=[], rename_fields=[]): """ read the json file provided and P...
batch = [] json_data = json.loads(json_file.read()) if isinstance(json_data, list): for item in json_data: # anonymize fields for field_name in anonymize_fields: if field_name in item: item[field_name] = md5sum(item[field_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 load(self): """ Loads the shop name and inventory """
pg = self.usr.getPage("http://www.neopets.com/objects.phtml?type=shop&obj_type=" + self.id) self.name = pg.find("td", "contentModuleHeader").text.strip() self.inventory = MainShopInventory(self.usr, self.id)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def random_token(length=10): """ Builds a random string. :param length: Token length. **Default:** 10 :type length: int :return: str """
return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(length))
<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_plugins_directory(config_path=None, microdrop_user_root=None): ''' Resolve plugins directory. Plugins directory is resolved as follows, highest-priority first: 1. ``plugins`` directory specified in provided :data:`config_path`. 2. ``plugins`` sub-directory of specified MicroDrop profile ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def plugin_request(plugin_str): ''' Extract plugin name and version specifiers from plugin descriptor string. .. versionchanged:: 0.25.2 Import from `pip_helpers` locally to avoid error `sci-bots/mpm#5`_. .. _sci-bots/mpm#5: https://github.com/sci-bots/mpm/issues/5 ''' from pip_hel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tweetqueue(ctx, dry_run, config): """A command line tool for time-delaying your tweets."""
ctx.obj = {} ctx.obj['DRYRUN'] = dry_run # If the subcommand is "config", bypass all setup code if ctx.invoked_subcommand == 'config': return # If the config file wasn't provided, attempt to load the default one. if config is None: user_home = os.path.expanduser("~") 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 tweet(ctx, message): """Sends a tweet directly to your timeline"""
if not valid_tweet(message): click.echo("Message is too long for twitter.") click.echo("Message:" + message) ctx.exit(2) if not ctx.obj['DRYRUN']: ctx.obj['TWEEPY_API'].update_status(message) else: click.echo("Tweet not sent due to dry-run mode.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def queue(ctx, message): """Adds a message to your twitter queue"""
if not valid_tweet(message): click.echo("Message is too long for twitter.") click.echo("Message: " + message) ctx.exit(2) if ctx.obj['DRYRUN']: click.echo("Message not queue due to dry-run mode.") ctx.exit(0) ctx.obj['TWEETLIST'].append(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 dequeue(ctx): """Sends a tweet from the queue"""
tweet =ctx.obj['TWEETLIST'].peek() if tweet is None: click.echo("Nothing to dequeue.") ctx.exit(1) if ctx.obj['DRYRUN']: click.echo(tweet) else: tweet = ctx.obj['TWEETLIST'].pop() ctx.obj['TWEEPY_API'].update_status(tweet)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def config(ctx): """Creates a tweetqueue configuration file"""
home_directory = os.path.expanduser('~') default_config_file = os.path.join(home_directory, '.tweetqueue') default_database_file = os.path.join(home_directory, '.tweetqueue.db') config = {} config['API_KEY'] = click.prompt('API Key') config['API_SECRET'] = click.prompt('API Secret') confi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(ctx,tweet): """Deletes a tweet from the queue with a given ID"""
if not ctx.obj['DRYRUN']: try: ctx.obj['TWEETLIST'].delete(tweet) except ValueError as e: click.echo("Now tweet was found with that id.") ctx.exit(1) else: click.echo("Not ran due to dry-run.")
<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_request(self, model, action, url_params={}, post_data=None): ''' Send request to API then validate, parse, and return the response ''' url = self._create_url(model, **url_params) headers = self._headers(action) try: response = requests.request(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 insert_jobs(jobs, verify_jobs=True, conn=None): """ insert_jobs function inserts data into Brain.Jobs table jobs must be in Job format :param jobs: <list> of...
assert isinstance(jobs, list) if verify_jobs \ and not verify({Jobs.DESCRIPTOR.name: jobs}, Jobs()): raise ValueError("Invalid Jobs") inserted = RBJ.insert(jobs).run(conn) return inserted
<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_job_status(job_id, status, conn=None): """Updates a job to a new status :param job_id: <str> the id of the job :param status: <str> new status :param ...
if status not in VALID_STATES: raise ValueError("Invalid status") job_update = RBJ.get(job_id).update({STATUS_FIELD: status}).run(conn) if job_update["replaced"] == 0 and job_update["unchanged"] == 0: raise ValueError("Unknown job_id: {}".format(job_id)) output_job_status = {OUTPUTJOB_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 write_output(job_id, content, conn=None): """writes output to the output table :param job_id: <str> id of the job :param content: <str> output to write :para...
output_job = get_job_by_id(job_id, conn) results = {} if output_job is not None: entry = { OUTPUTJOB_FIELD: output_job, CONTENT_FIELD: content } results = RBO.insert(entry, conflict=RDB_REPLACE).run(conn) return 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 generate_words(numberofwords, wordlist, secure=None): """Generate a list of random words from wordlist."""
if not secure: chooser = random.choice else: chooser = random.SystemRandom().choice return [chooser(wordlist) for _ in range(numberofwords)]
<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_stream(filename): """Load a file stream from the package resources."""
rawfile = pkg_resources.resource_stream(__name__, filename) if six.PY2: return rawfile return io.TextIOWrapper(rawfile, 'utf-8')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cli(): """Run the command line interface."""
args = docopt.docopt(__doc__, version=__VERSION__) secure = args['--secure'] numberofwords = int(args['<numberofwords>']) dictpath = args['--dict'] if dictpath is not None: dictfile = open(dictpath) else: dictfile = load_stream('words.txt') with dictfile: wordlist =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def processor_for(content_model_or_slug, exact_page=False): """ Decorator that registers the decorated function as a page processor for the given content model o...
content_model = None slug = "" if isinstance(content_model_or_slug, (str, _str)): try: parts = content_model_or_slug.split(".", 1) content_model = apps.get_model(*parts) except (TypeError, ValueError, LookupError): slug = content_model_or_slug elif is...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def autodiscover(): """ Taken from ``django.contrib.admin.autodiscover`` and used to run any calls to the ``processor_for`` decorator. """
global LOADED if LOADED: return LOADED = True for app in get_app_name_list(): try: module = import_module(app) except ImportError: pass else: try: import_module("%s.page_processors" % app) 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 can_vote_on_poll(self, request): """Based on jmbo.models.can_vote."""
# can't vote if liking is closed if self.votes_closed: return False, 'closed' # can't vote if liking is disabled if not self.votes_enabled: return False, 'disabled' # anonymous users can't vote if anonymous votes are disabled if not request.use...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def vote_count(self): """ Returns the total number of votes cast across all the poll's options. """
return Vote.objects.filter( content_type=ContentType.objects.get(app_label='poll', model='polloption'), object_id__in=[o.id for o in self.polloption_set.all()] ).aggregate(Sum('vote'))['vote__sum'] or 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 vote_count(self): """ Returns the total number of votes cast for this poll options. """
return Vote.objects.filter( content_type=ContentType.objects.get_for_model(self), object_id=self.id ).aggregate(Sum('vote'))['vote__sum'] or 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 percentage(self): """ Returns the percentage of votes cast for this poll option in relation to all of its poll's other options. """
total_vote_count = self.poll.vote_count if total_vote_count: return self.vote_count * 100.0 / total_vote_count return 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 does_not_mutate(func): """Prevents methods from mutating the receiver"""
def wrapper(self, *args, **kwargs): new = self.copy() return func(new, *args, **kwargs) wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ 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 find_by(self, **kwargs): """ Find first record subject to restrictions in +kwargs+, raising RecordNotFound if no such record exists. """
result = self.where(**kwargs).first() if result: return result else: raise RecordNotFound(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 where(self, *custom_restrictions, **restrictions): """ Restricts the records to the query subject to the passed +restrictions+. Analog to "WHERE" in SQL. Can...
for attr, value in restrictions.items(): self.where_query[attr] = value if custom_restrictions: self.custom_where.append(tuple(custom_restrictions)) 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 joins(self, table): """ Analog to "INNER JOIN" in SQL on the passed +table+. Use only once per query. """
def do_join(table, model): while model is not associations.model_from_name(table): # ex) Category -> Forum -> Thread -> Post # Category: {"posts": "forums"} # Forum: {"posts": "threads"} # Thread: {"posts": None} # >>>...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self, **attributes): """ Creates a new record suject to the restructions in the query and with the passed +attributes+. Operates using `build`. """
record = self.build(**attributes) record.save() return record
<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(technical_terms_filename, spellchecker_cache_path): """Create a Dictionary at spellchecker_cache_path with technical words."""
user_dictionary = os.path.join(os.getcwd(), "DICTIONARY") user_words = read_dictionary_file(user_dictionary) technical_terms_set = set(user_words) if technical_terms_filename: with open(technical_terms_filename) as tech_tf: technical_terms_set |= set(tech_tf.read().splitlines()) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect(self, agent='Python'): """ Context manager for HTTP Connection state and ensures proper handling of network sockets, sends a GET request. Exception i...
headers = {'User-Agent': agent} request = urlopen(Request(self.url, headers=headers)) try: yield request finally: request.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reader(self): """ Reads raw text from the connection stream. Ensures proper exception handling. :return bytes: request """
request_stream = '' with self.connect() as request: if request.msg != 'OK': raise HTTPError request_stream = request.read().decode('utf-8') return request_stream
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def json(self): """ Serializes json text stream into python dictionary. :return dict: json """
_json = json.loads(self.reader) if _json.get('error', None): raise HTTPError(_json['error']['errors']) return _json
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_class(classpath, package=None): """ Load and return a class """
if '.' in classpath: module, classname = classpath.rsplit('.', 1) if package and not module.startswith('.'): module = '.{0}'.format(module) mod = import_module(module, package) else: classname = classpath mod = import_module(package) return getattr(mod, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_module(self, module, idx=-1): """ Register a module. You could indicate position inside inner list. :param module: must be a string or a module obje...
if module in self._modules: raise AlreadyRegisteredError("Module '{0}' is already registered on loader.".format(module)) if idx < 0: self._modules.append(module) else: self._modules.insert(idx, module)
<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_class(self, classname): """ Loads a class looking for it in each module registered. :param classname: Class name you want to load. :type classname: str ...
module_list = self._get_module_list() for module in module_list: try: return import_class(classname, module.__name__) except (AttributeError, ImportError): pass raise ImportError("Class '{0}' could not be loaded.".format(classname))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def factory(self, classname, *args, **kwargs): """ Creates an instance of class looking for it in each module registered. You can add needed params to instance t...
klass = self.load_class(classname) return self.get_factory_by_class(klass)(*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 get_factory_by_class(self, klass): """ Returns a custom factory for class. By default it will return the class itself. :param klass: Class type :type klass: ...
for check, factory in self._factories.items(): if klass is check: return factory(self, klass) for check, factory in self._factories.items(): if issubclass(klass, check): return factory(self, klass) return klass
<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_module(self, module, namespace=None): """ Register a module. :param module: must be a string or a module object to register. :type module: str :para...
namespace = namespace if namespace is not None else module \ if isinstance(module, str) else module.__name__ self.register_namespace(namespace, module)
<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(self, namespace, module): """ Register a namespace. :param namespace: Namespace tag. :type namespace: str :param module: must be a string ...
if namespace in self._namespaces: raise AlreadyRegisteredError("Namespace '{0}' is already registered on loader.".format(namespace)) self._namespaces[namespace] = module
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unregister_namespace(self, namespace): """ Unregister a namespace. :param namespace: Namespace tag. :type namespace: str """
if namespace not in self._namespaces: raise NoRegisteredError("Namespace '{0}' is not registered on loader.".format(namespace)) del self._namespaces[namespace]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self): """ Close service client and its plugins. """
self._execute_plugin_hooks_sync(hook='close') if not self.session.closed: ensure_future(self.session.close(), loop=self.loop)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def api(f): """Decorator for functions and methods that are part of the external module API and that can throw XPathError exceptions. The call stack for these ex...
def api_function(*args, **kwargs): try: return f(*args, **kwargs) except XPathError, e: raise e api_function.__name__ = f.__name__ api_function.__doc__ = f.__doc__ return api_function
<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, path, strict): """ Gets the item for `path`. If `strict` is true, this method returns `None` when matching path is not found. Otherwise, this retur...
item, pathinfo = self._get(path, strict) if item is None: if strict: return None, pathinfo else: return self._item, pathinfo else: return item, pathinfo
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set(self, path, item, replace): """ Sets item for `path` and returns the item. Replaces existing item with `item` when `replace` is true :param path: Path fo...
if len(path) == 0: if self._item is None or replace: self._item = item return self._item else: head, tail = path[0], path[1:] if head.startswith(':'): default = (head[1:], self.__class__()) _, rtree = sel...
<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_ajax_rsvps(event, user_profile): """Return link and list strings for a given event."""
if user_profile in event.rsvps.all(): link_string = True else: link_string = False if not event.rsvps.all().count(): list_string = 'No RSVPs.' else: list_string = 'RSVPs:' for counter, profile in enumerate(event.rsvps.all()): if counter > 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 setResponse(self, response): """ A response has been received by the gateway """
self.response = response self.result = self.response.body if isinstance(self.result, remoting.ErrorFault): self.result.raiseException()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addHeader(self, name, value, must_understand=False): """ Sets a persistent header to send with each request. @param name: Header name. """
self.headers[name] = value self.headers.set_required(name, must_understand)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getRequest(self, id_): """ Gets a request based on the id. :raise LookupError: Request not found. """
for request in self.requests: if request.id == id_: return request raise LookupError("Request %r not found" % (id_,))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addRequest(self, service, *args): """ Adds a request to be sent to the remoting gateway. """
wrapper = RequestWrapper(self, '/%d' % self.request_number, service, *args) self.request_number += 1 self.requests.append(wrapper) if self.logger: self.logger.debug('Adding request %s%r', wrapper.service, args) 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 removeRequest(self, service, *args): """ Removes a request from the pending request list. """
if isinstance(service, RequestWrapper): if self.logger: self.logger.debug('Removing request: %s', self.requests[self.requests.index(service)]) del self.requests[self.requests.index(service)] return for request in self.requests: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute_single(self, request): """ Builds, sends and handles the response to a single request, returning the response. """
if self.logger: self.logger.debug('Executing single request: %s', request) self.removeRequest(request) body = remoting.encode(self.getAMFRequest([request]), strict=self.strict) http_request = urllib2.Request(self._root_url, body.getvalue(), self._get_execute_h...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getResponse(self, http_request): """ Gets and handles the HTTP response from the remote gateway. """
if self.logger: self.logger.debug('Sending POST request to %s', self._root_url) try: fbh = self.opener(http_request) except urllib2.URLError, e: if self.logger: self.logger.exception('Failed request for %s', self._root_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 setCredentials(self, username, password): """ Sets authentication credentials for accessing the remote gateway. """
self.addHeader('Credentials', dict(userid=username.decode('utf-8'), password=password.decode('utf-8')), 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 patch_gevent_hub(): """ This patches the error handler in the gevent Hub object. """
from gevent.hub import Hub def patched_handle_error(self, context, etype, value, tb): """ Patched to not print KeyboardInterrupt exceptions. """ if isinstance(value, str): value = etype(value) not_error = issubclass(etype, self.NOT_ERROR) system_error = issubclass(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 col2name(col_item): "helper for SyntheticTable.columns. takes something from SelectX.cols, returns a string column name" if isinstance(col_item, sqparse2.NameX): return col_item.name elif isinstance(col_item, sqparse2.AliasX): return col_item.alias else: raise TypeError(type(col_item), col_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 add(self, name, target): "target should be a Table or SyntheticTable" if not isinstance(target, (table.Table, SyntheticTable)): raise TypeError(type(target), target) if name in self: # note: this is critical for avoiding cycles raise ScopeCollisionError('scope already has', name) 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 clone_from_upstream(pkg_name, repo_url): """Clone a non-existent package using the upstream registry."""
msg = "Spawning a cloning task for %s from upstream due to API req." LOG.info(msg % pkg_name) upstream_url = settings.UPSTREAM_BOWER_REGISTRY upstream_pkg = bowerlib.get_package(upstream_url, pkg_name) if upstream_pkg is None: raise Http404 task = tasks.cl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def allocate_port(): """Allocate an unused port. There is a small race condition here (between the time we allocate the port, and the time it actually gets used)...
sock = socket.socket() try: sock.bind(("localhost", 0)) return get_port(sock) finally: sock.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spawn(self): """Spawn the fake executable using subprocess.Popen."""
self._process = subprocess.Popen( [self.path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) self.addCleanup(self._process_kill)
<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, port=None): """Make the fake executable listen to the specified port. Possible values for 'port' are: - None: Allocate immediately a free port a...
if port is None: port = allocate_port() self.port = port self.line("import socket") self.line("sock = socket.socket()") self.line("sock.bind(('localhost', {}))".format(self.port)) self.log("listening: %d" % self.port) self.line("sock.listen(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 _process_kill(self): """Kill the fake executable process if it's still running."""
if self._process.poll() is None: # pragma: no cover self._process.kill() self._process.wait(timeout=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 _process_info(self): """Return details about the fake process."""
if not self._process: return [] output, error = self._process.communicate(timeout=5) if error is None: error = b"" output = output.decode("utf-8").strip() error = error.decode("utf-8").strip() info = (u"returncode: %r\n" u"output:...
<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_tasks_from_file(self, file_path): """ Imports specified python module and returns subclasses of BaseTask from it :param file_path: a fully qualified fil...
file_name, module_path, objects = Loader.import_custom_python_file(file_path) result = {} for entry in objects: try: if issubclass(entry, BaseTask): if entry.__name__ != BaseTask.__name__ and entry.name == BaseTask.name: ra...
<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_tasks_from_dir(self, dir_path, propagate_exceptions=False): """ Imports all python modules in specified directories and returns subclasses of BaseTask f...
if not os.path.exists(dir_path): raise GOSTaskException() if os.path.isfile(dir_path): raise GOSTaskException() result = {} for file_basename in os.listdir(dir_path): full_file_path = os.path.join(dir_path, file_basename) try: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_tasks(self, paths, propagate_exception=False): """ Loads all subclasses of BaseTask from modules that are contained in supplied directory paths or direc...
try: result = {} for path in paths: try: if os.path.isdir(path): result.update(self.load_tasks_from_dir(dir_path=path, propagate_exceptions=propagate_exception)) elif os.path.isfile(path): ...