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 remote_upload(apikey, picture_url, resize=None, rotation='00', noexif=False): """ prepares post for remote upload :param str apikey: Apikey needed for Autent...
check_rotation(rotation) check_resize(resize) url = check_if_redirect(picture_url) if url: picture_url = resolve_redirect(url) post_data = compose_post(apikey, resize, rotation, noexif) post_data['url[]'] = ('', picture_url) return do_upload(post_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 compose_post(apikey, resize, rotation, noexif): """ composes basic post requests """
check_rotation(rotation) check_resize(resize) post_data = { 'formatliste': ('', 'og'), 'userdrehung': ('', rotation), 'apikey': ('', apikey) } if resize and 'x' in resize: width, height = [ x.strip() for x in resize.split('x')] post_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 do_upload(post_data, callback=None): """ does the actual upload also sets and generates the user agent string """
encoder = MultipartEncoder(post_data) monitor = MultipartEncoderMonitor(encoder, callback) headers = {'User-Agent': USER_AGENT, 'Content-Type': monitor.content_type} response = post(API_URL, data=monitor, headers=headers) check_response(response) return response.json()[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 upload(self, picture, resize=None, rotation=None, noexif=None, callback=None): """ wraps upload function :param str/tuple/list picture: Path to picture as st...
if not resize: resize = self._resize if not rotation: rotation = self._rotation if not noexif: noexif = self._noexif if not callback: callback = self._callback return upload(self._apikey, picture, resize, rot...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remote_upload(self, picture_url, resize=None, rotation=None, noexif=None): """ wraps remote_upload funktion :param str picture_url: URL to picture allowd Pro...
if not resize: resize = self._resize if not rotation: rotation = self._rotation if not noexif: noexif = self._noexif return remote_upload(self._apikey, picture_url, resize, rotation, noexif)
<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_identity(config = Config()): """Load the default identity from the configuration. If there is no default identity, a KeyError is raised. """
return Identity(name = config.get('user', 'name'), email_ = config.get('user', 'email'), **config.get_section('smtp'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _smtp_server(self): """Return a smtplib SMTP object correctly initialised and connected to a SMTP server suitable for sending email on behalf of the user."""
if self._use_ssl: server = smtplib.SMTP_SSL(**self._smtp_vars) else: server = smtplib.SMTP(**self._smtp_vars) if self._use_tls: server.starttls() if self._credentials is not None: passwd = self._credentials[1] if passwd is N...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_clients(session, verbose): """Add clients to the ATVS Keystroke database."""
for ctype in ['Genuine', 'Impostor']: for cdid in userid_clients: cid = ctype + '_%d' % cdid if verbose>1: print(" Adding user '%s' of type '%s'..." % (cid, ctype)) session.add(Client(cid, ctype, cdid))
<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_files(session, imagedir, verbose): """Add files to the ATVS Keystroke database."""
def add_file(session, basename, userid, shotid, sessionid): """Parse a single filename and add it to the list.""" session.add(File(userid, basename, sessionid, shotid)) filenames = os.listdir(imagedir) for filename in filenames: basename, extension = os.path.splitext(filename) if extension == 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 create(args): """Creates or re-creates this database"""
from bob.db.utils import session_try_nolock dbfile = args.files[0] if args.recreate: if args.verbose and os.path.exists(dbfile): print('unlinking %s...' % dbfile) if os.path.exists(dbfile): os.unlink(dbfile) if not os.path.exists(os.path.dirname(dbfile)): os.makedirs(os.path.dirname(dbfil...
<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_command(subparsers): """Add specific subcommands that the action "create" can use"""
parser = subparsers.add_parser('create', help=create.__doc__) parser.add_argument('-R', '--recreate', action='store_true', help="If set, I'll first erase the current database") parser.add_argument('-v', '--verbose', action='count', help="Do SQL operations in a verbose way?") parser.add_argument('-D', '--imag...
<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(self, accept_unrecognized_args=False): """ Invoke the argument parser. """
# If the user provided a description, use it. Otherwise grab the doc string. if self.description: self.argparser.description = self.description elif getattr(sys.modules['__main__'], '__doc__', None): self.argparser.description = getattr(sys.modules['__main__'], '__doc__...
<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_config(self): """ Invoke the config file parser. """
if self.should_parse_config and (self.args.config or self.config_file): self.config = ConfigParser.SafeConfigParser() self.config.read(self.args.config or self.config_file)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __process_username_password(self): """ If indicated, process the username and password """
if self.use_username_password_store is not None: if self.args.clear_store: with load_config(sections=AUTH_SECTIONS) as config: config.remove_option(AUTH_SECTION, 'username') if not self.args.username: self.args.username = get_username...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __finish_initializing(self): """ Handle any initialization after arguments & config has been parsed. """
if self.args.debug or self.args.trace: # Set the console (StreamHandler) to allow debug statements. if self.args.debug: self.console.setLevel(logging.DEBUG) self.console.setFormatter(logging.Formatter('[%(levelname)s] %(asctime)s %(name)s - %(message)s')) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_item(self, item_number, raw=False): """ Get a dictionary or object with info about the given item number from the Hacker News API. Item can be a poll, st...
if not isinstance(item_number, int): item_number = int(item_number) suburl = "v0/item/{}.json".format(item_number) try: item_data = self._make_request(suburl) except requests.HTTPError as e: hn_logger.exception('Faulted on item request for item {}, wi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_user(self, user_name, raw=False): """ Get a dictionary or object with info about the given user from the Hacker News API. Will raise an requests.HTTPErro...
suburl = "v0/user/{}.json".format(user_name) try: user_data = self._make_request(suburl) except requests.HTTPError as e: hn_logger.exception('Faulted on item request for user {}, with status {}'.format(user_name, e.errno)) raise e if not user_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 get_recent_updates(self, raw=True): """ Get the most recent updates on Hacker News Response dictionary parameters: "items" -> A list of the most recently upd...
suburl = "v0/updates.json" try: updates_data = self._make_request(suburl) except requests.HTTPError as e: hn_logger.exception('Faulted on get max item, with status {}'.format(e.errno)) raise e return updates_data if raw else HackerNewsUpdates(**update...
<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_server(): """Creates an EC2 Server"""
try: import boto except ImportError: sys.exit("boto library required for creating servers with Amazon.") print(green("Creating EC2 server")) conn = boto.connect_ec2( get_or_prompt('ec2_key', 'API Key'), get_or_prompt('ec2_secret', 'API Secret')) reservation =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def return_time_elements(time_stamp): """Returns formatted strings of time stamps for HTML requests. :parameters time_range: pandas.tslib.Timestamp """
yyyy = str(time_stamp.year) mm = "%02d" % (time_stamp.month,) dd = "%02d" % (time_stamp.day,) hr = "%02d" % (time_stamp.hour,) mins = "%02d" % (time_stamp.minute,) return yyyy, mm, dd, hr, mins
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fromConfigFile(filename = DEFAULT_CONFIG_FILE): """ Read settings from configuration file"""
parser = SafeConfigParser() section = 'fenixedu' parser.read(filename) client_id = parser.get(section, 'client_id') redirect_uri = parser.get(section, 'redirect_uri') client_secret = parser.get(section, 'client_secret') base_url = parser.get(section, 'base_url') api_endpoint = parser....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def map_subcommands(self, func): """ Run `func` against all the subcommands attached to our root command. """
def crawl(cmd): for sc in cmd.subcommands.values(): yield from crawl(sc) yield cmd return map(func, crawl(self.root_command))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_command_error(self, command, args, exc): """ Depending on how the session is configured this will print information about an unhandled command excepti...
verbosity = self.command_error_verbosity if verbosity == 'traceback': self.pretty_print_exc(command, exc, show_traceback=True) elif verbosity == 'debug': pdb.set_trace() elif verbosity == 'raise': raise exc elif verbosity == 'pretty': ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def complete_wrap(self, func, *args, **kwargs): """ Readline eats exceptions raised by completer functions. """
# Workaround readline's one-time-read of terminal width. termcols = shutil.get_terminal_size()[0] readline.parse_and_bind('set completion-display-width %d' % termcols) try: return func(*args, **kwargs) except: traceback.print_exc() 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 setup_readline(self): """ Configure our tab completion settings for a context and then restore them to previous settings on exit. """
readline.parse_and_bind('tab: complete') completer_save = readline.get_completer() delims_save = readline.get_completer_delims() delims = set(delims_save) delims |= self.completer_delim_includes delims -= self.completer_delim_excludes readline.set_completer(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 run_loop(self): """ Main entry point for running in interactive mode. """
self.root_command.prog = '' history_file = self.load_history() rendering.vtmlprint(self.intro) try: self.loop() finally: readline.write_history_file(history_file)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def loop(self): """ Inner loop for interactive mode. Do not call directly. """
while True: with self.setup_readline(): try: line = input(self.prompt) except EOFError: _vprinterr('^D') break except KeyboardInterrupt: _vprinterr('^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 sqldelete(table, where): ('delete from t where id=%s', [5]) """
validate_name(table) (whereclause, wherevalues) = sqlwhere(where) sql = "delete from {}".format(table) if whereclause: sql += " where " + whereclause return (sql, wherevalues)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select(self, table, fields=['*'], where=None, orderby=None, limit=None, offset=None): """ Query and return list of records. 1 {'id': 1, 'name': 'Toto'} """
(sql, values) = sqlselect(table, fields, where, orderby, limit, offset) self.execute(sql, values) return self.fetchall()
<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(self, table, row): """ Add new row. Row must be a dict or implement the mapping interface. 1 {'id': 1, 'name': 'Toto'} """
(sql, values) = sqlinsert(table, row) self.execute(sql, 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 one(iterable, cmp=None): """ Return the object in the given iterable that evaluates to True. If the given iterable has more than one object that evaluates to...
the_one = False for i in iterable: if cmp(i) if cmp else i: if the_one: return False the_one = i return the_one
<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_command(self, name, command): """ Registers the `command` with the given `name`. If the `name` has already been used to register a command a :exc:`R...
if name in self.commands: raise RuntimeError('%s is already defined' % name) self.commands[name] = command
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wordify(text): """Generate a list of words given text, removing punctuation. Parameters text : unicode A piece of english text. Returns ------- words : list ...
stopset = set(nltk.corpus.stopwords.words('english')) tokens = nltk.WordPunctTokenizer().tokenize(text) return [w for w in tokens if w not in stopset]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def initialize_env(env_file=None, fail_silently=True, load_globally=True): """ Returns an instance of _Environment after reading the system environment an option...
data = {} data.update(os.environ) if env_file: data.update(read_file_values(env_file, fail_silently)) if load_globally: os.environ.update(data) return Environment(env_dict=data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup(sphinx): """Setup Sphinx object."""
from flask import has_app_context from invenio_base.factory import create_app PACKAGES = ['invenio_base', 'invenio.modules.accounts', 'invenio.modules.records', 'invenio_knowledge'] if not has_app_context(): app = create_app(PACKAGES=PACKAGES) ctx = app.test_request_con...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pretty_spaces(level): """ Return spaces and new line. :type level: int or None :param level: deep level :rtype: unicode :return: string with new line and spa...
if level is None: return u'' return (os.linesep if level >= 0 else u'') + (u' ' * (INDENT * level))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unimapping(arg, level): """ Mapping object to unicode string. :type arg: collections.Mapping :param arg: mapping object :type level: int :param level: deep l...
if not isinstance(arg, collections.Mapping): raise TypeError( 'expected collections.Mapping, {} received'.format(type(arg).__name__) ) result = [] for i in arg.items(): result.append( pretty_spaces(level) + u': '.join(map(functools.partial(convert, level=le...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def uniiterable(arg, level): """ Iterable object to unicode string. :type arg: collections.Iterable :param arg: iterable object :type level: int :param level: de...
if not isinstance(arg, collections.Iterable): raise TypeError( 'expected collections.Iterable, {} received'.format(type(arg).__name__) ) templates = { list: u'[{}]', tuple: u'({})' } result = [] for i in arg: result.append(pretty_spaces(level) ...
<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(obj, encoding=LOCALE, level=None): """ Covert any object to unicode string. :param obj: any object :type encoding: str :param encoding: codec for enc...
callable_ = CONVERTERS.get(type(obj)) if callable_ is not None: obj = callable_(obj) func = lambda x, level: compat.template.format(x) if isinstance(obj, compat.UnicodeType): # skip if condition, because unicode is a iterable type pass elif isinstance(obj, str): 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 show(ctx, city, date): """Show a particular meetup. city: The meetup series. \b date: The date. May be: - YYYY-MM-DD or YY-MM-DD (e.g. 2015-08-27) - YYYY-MM ...
db = ctx.obj['db'] today = ctx.obj['now'].date() term = ctx.obj['term'] event = cliutil.get_event(db, city, date, today) data = event.as_dict() cliutil.handle_raw_output(ctx, data) render_event(term, event, today, verbose=ctx.obj['verbose'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_list_fields(self): """Get all list fields"""
from trionyx.renderer import renderer model_fields = {f.name: f for f in self.model.get_fields(True, True)} def create_list_fields(config_fields, list_fields=None): list_fields = list_fields if list_fields else {} for field in config_fields: config = fi...
<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_form(self, config_name, only_required=False): """Get form for given config else create form"""
if getattr(self, config_name, None): return import_object_by_string(getattr(self, config_name)) def use_field(field): if not only_required: return True return field.default == NOT_PROVIDED return modelform_factory(self.model, fields=[f.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 auto_load_configs(self): """Auto load all configs from app configs"""
for app in apps.get_app_configs(): for model in app.get_models(): config = ModelConfig(model, getattr(app, model.__name__, None)) self.configs[self.get_model_name(model)] = 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 get_config(self, model): """Get config for given model"""
if not inspect.isclass(model): model = model.__class__ return self.configs.get(self.get_model_name(model))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all_configs(self, trionyx_models_only=True): """Get all model configs"""
from trionyx.models import BaseModel for index, config in self.configs.items(): if not isinstance(config.model(), BaseModel): continue yield 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 put(self, source, rel_path, metadata=None): """Puts to only the first upstream. This is to be symmetric with put_stream."""
return self.upstreams[0].put(source, rel_path, metadata)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list(self, path=None, with_metadata=False, include_partitions=False): """Combine a listing of all of the upstreams, and add a metadata item for the repo_id""...
l = {} for upstream in [self.alternate, self.upstream]: for k, v in upstream.list(path, with_metadata, include_partitions).items(): upstreams = (l[k]['caches'] if k in l else []) + \ v.get('caches', upstream.repo_id) l[k] = v ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _copy_across(self, rel_path, cb=None): """If the upstream doesn't have the file, get it from the alternate and store it in the upstream"""
from . import copy_file_or_flo if not self.upstream.has(rel_path): if not self.alternate.has(rel_path): return None source = self.alternate.get_stream(rel_path) sink = self.upstream.put_stream(rel_path, metadata=source.meta) 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 _parse_sigmak(line, lines): """Parse Energy, Re sigma xx, Im sigma xx, Re sigma zz, Im sigma zz"""
split_line = line.split() energy = float(split_line[0]) re_sigma_xx = float(split_line[1]) im_sigma_xx = float(split_line[2]) re_sigma_zz = float(split_line[3]) im_sigma_zz = float(split_line[4]) return {"energy": energy, "re_sigma_xx": re_sigma_xx, "im_sigma_xx": im_sigma_xx, "re_sigma_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def require_self(func, *args, **kwargs): """Decorator to require that this component be installed"""
try: __import__(package['name']) except ImportError: sys.stderr.write( "This component needs to be installed first. Run " + "`invoke install`\n") sys.exit(1) return func(*args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def require_pip_module(module): """Decorator to check for a module and helpfully exit if it's not found"""
def wrapper(func, *args, **kwargs): try: __import__(module) except ImportError: sys.stderr.write( "`pip install %s` to enable this feature\n" % module) sys.exit(1) else: return func(*args, **kwargs) return decorator(wrappe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replaced_by_django_migrations(func, *args, **kwargs): """Decorator to preempt South requirement"""
DjangoSettings() # trigger helpful messages if Django is missing import django if django.VERSION >= (1, 7): print("Django 1.7+ has its own migrations system.") print("Use this instead: `invoke managepy makemigrations`") sys.exit(1) return func(*args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_migration(initial=False): """Create a South migration for this project"""
settings = DjangoSettings() if 'south' not in (name.lower() for name in settings.INSTALLED_APPS): print("Temporarily adding 'south' into INSTALLED_APPS.") settings.INSTALLED_APPS.append('south') kwargs = dict(initial=True) if initial else dict(auto=True) run_django_cmd('schemamigratio...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def coverage(reportdir=None, extra=None): """Test this project with coverage reports"""
import coverage as coverage_api cov = coverage_api.coverage() opts = {'directory': reportdir} if reportdir else {} cov.start() test(extra) cov.stop() cov.html_report(**opts)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def managepy(cmd, extra=None): """Run manage.py using this component's specific Django settings"""
extra = extra.split() if extra else [] run_django_cli(['invoke', cmd] + extra)
<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_total_magnetization(line, lines): """Parse the total magnetization, which is somewhat hidden"""
toks = line.split() res = {"number of electrons": float(toks[3])} if len(toks) > 5: res["total magnetization"] = float(toks[5]) return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deferred_emails(): """Checks for deferred email, that otherwise fill up the queue."""
status = SERVER_STATUS['OK'] count = Message.objects.deferred().count() if DEFERRED_WARNING_THRESHOLD <= count < DEFERRED_DANGER_THRESHOLD: status = SERVER_STATUS['WARNING'] if count >= DEFERRED_DANGER_THRESHOLD: status = SERVER_STATUS['DANGER'] return { 'label': 'Deferred...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def email_queue(): """Checks for emails, that fill up the queue without getting sent."""
status = SERVER_STATUS['OK'] count = Message.objects.exclude(priority=PRIORITY_DEFERRED).filter( when_added__lte=now() - timedelta(minutes=QUEUE_TIMEOUT)).count() if QUEUE_WARNING_THRESHOLD <= count < QUEUE_DANGER_THRESHOLD: status = SERVER_STATUS['WARNING'] if count >= QUEUE_DANGER_TH...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def yaml_force_unicode(): """ Force pyyaml to return unicode values. """
#/ ## modified from |http://stackoverflow.com/a/2967461| if sys.version_info[0] == 2: def construct_func(self, node): return self.construct_scalar(node) yaml.Loader.add_constructor(U('tag:yaml.org,2002:str'), construct_func) yaml.SafeLoader.ad...
<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_locale_hints(): """ Get a list of locale hints, guessed according to Python's default locale info. """
#/ lang, encoding = locale.getdefaultlocale() ## can both be None #/ if lang and '_' in lang: lang3, _, lang2 = lang.partition('_') else: lang3 = None lang2 = None #/ ll_s = [encoding, lang, lang2, lan...
<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_locale_choices(locale_dir): """ Get a list of locale file names in the given locale dir. """
#/ file_name_s = os.listdir(locale_dir) #/ choice_s = [] for file_name in file_name_s: if file_name.endswith(I18n.TT_FILE_EXT_STXT): file_name_noext, _ = os.path.splitext(file_name) if file_name_noext: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def working_set(self, extra=()): """Separate method to just get the working set This is intended for reuse by similar recipes. """
options = self.options b_options = self.buildout['buildout'] # Backward compat. :( options['executable'] = sys.executable distributions = [ r.strip() for r in options.get('eggs', self.name).split('\n') if r.strip()] orig_distribution...
<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_required(dist): """Return a set with all distributions that are required of dist This also includes subdependencies and the given distribution. :param di...
d = pkg_resources.get_distribution(dist) reqs = set(d.requires()) allds = set([d]) while reqs: newreqs = set([]) for r in reqs: dr = pkg_resources.get_distribution(r) allds.add(dr) newreqs = newreqs & set(dr.requires()) reqs = newreqs - reqs ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_outdated(dist, dep=False): """Return a dict with outdated distributions If the given distribution has dependencies, they are checked as well. :param dist:...
if dep: required = get_required(dist) else: required = set([dist]) ListCommand = pip.commands['list'] lc = ListCommand() options, args = lc.parse_args(['--outdated']) outdated = {} for d, raw_ver, parsed_ver in lc.find_packages_latests_versions(options): for r in req...
<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(dist, args=None): """Update the given distribution and all of its dependencies :param dist: the distribution to check :type dist: :class:`pkg_resource...
dist = pkg_resources.get_distribution(dist) InstallCommand = pip.commands['install'] ic = InstallCommand() iargs = ['-U', dist.project_name] if args: iargs.extend(args) ic.main(iargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restart(): """Restart the application the same way it was started :returns: None :rtype: None :raises: SystemExit """
python = sys.executable os.execl(python, python, * sys.argv)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authenticated(f): """Decorator that authenticates to Keystone automatically."""
@wraps(f) def new_f(self, *args, **kwargs): if not self.nova_client.client.auth_token: self.authenticate() return f(self, *args, **kwargs) return new_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 _translate_struct(inner_dict): """Translate a teleport Struct into a val subschema."""
try: optional = inner_dict['optional'].items() required = inner_dict['required'].items() except KeyError as ex: raise DeserializationError("Missing key: {}".format(ex)) except AttributeError as ex: raise DeserializationError( "Invalid Structure: {}".format(inner_...
<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_composite(teleport_value): """Translate a composite teleport value into a val subschema."""
for key in ("Array", "Map", "Struct"): value = teleport_value.get(key) if value is None: continue return COMPOSITES[key](value) raise DeserializationError( "Could not interpret %r as a teleport schema." % teleport_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 _translate(teleport_value): """Translate a teleport value in to a val subschema."""
if isinstance(teleport_value, dict): return _translate_composite(teleport_value) if teleport_value in PRIMITIVES: return PRIMITIVES[teleport_value] raise DeserializationError( "Could not interpret %r as a teleport schema." % teleport_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 to_val(teleport_schema): """Convert a parsed teleport schema to a val schema."""
translated = _translate(teleport_schema) if isinstance(translated, BaseSchema): return translated return Schema(translated)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _dict_to_teleport(dict_value): """Convert a val schema dictionary to teleport."""
if len(dict_value) == 1: for key, value in dict_value.items(): if key is str: return {"Map": from_val(value)} optional = {} required = {} for key, value in dict_value.items(): if isinstance(key, Optional): optional[key.value] = from_val(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 from_val(val_schema): """Serialize a val schema to teleport."""
definition = getattr(val_schema, "definition", val_schema) if isinstance( val_schema, BaseSchema) else val_schema if isinstance(definition, dict): return _dict_to_teleport(definition) if isinstance(definition, list): # teleport only supports a single type by default if len(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def document(schema): """Print a documented teleport version of the schema."""
teleport_schema = from_val(schema) return json.dumps(teleport_schema, sort_keys=True, indent=2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def nice_identifier(): 'do not use uuid.uuid4, because it can block' big = reduce(mul, struct.unpack('<LLLL', os.urandom(16)), 1) big = big % 2**128 return uuid.UUID(int=big).hex
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _acquire_lock(self, identifier, atime=30, ltime=5): '''Acquire a lock for a given identifier. If the lock cannot be obtained immediately, keep trying at random intervals, up to 3 seconds, until `atime` has passed. Once the lock has been obtained, continue to hold it for `ltime`. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def re_acquire_lock(self, ltime=5): '''Re-acquire the lock. You must already own the lock; this is best called from within a :meth:`lock` block. :param int ltime: maximum time (in seconds) to own lock :return: the session lock identifier :raise rejester.exceptions.Envir...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def lock(self, atime=30, ltime=5, identifier=None): '''Context manager to acquire the namespace global lock. This is typically used for multi-step registry operations, such as a read-modify-write sequence:: with registry.lock() as session: d = session.get('dict', 'k...
<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_lock(self): '''Find out who currently owns the namespace global lock. This is purely a diagnostic tool. If you are trying to get the global lock, it is better to just call :meth:`lock`, which will atomically get the lock if possible and retry. :return: session identif...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def force_clear_lock(self): '''Kick out whoever currently owns the namespace global lock. This is intended as purely a last-resort tool. If another process has managed to get the global lock for a very long time, or if it requested the lock with a long expiration and then crash...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def update(self, dict_name, mapping=None, priorities=None, expire=None, locks=None): '''Add mapping to a dictionary, replacing previous values Can be called with only dict_name and expire to refresh the expiration time. NB: locks are only enforced if present, so nothing ...
<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_priorities(self, dict_name, priority): '''set all priorities in dict_name to priority :type priority: float or int ''' if self._session_lock_identifier is None: raise ProgrammerError('must acquire lock first') ## see comment above for script in update ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def popitem(self, dict_name, priority_min='-inf', priority_max='+inf'): '''Select an item and remove it. The item comes from `dict_name`, and has the lowest score at least `priority_min` and at most `priority_max`. If some item is found, remove it from `dict_name` and return it. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def popitem_move(self, from_dict, to_dict, priority_min='-inf', priority_max='+inf'): '''Select an item and move it to another dictionary. The item comes from `from_dict`, and has the lowest score at least `priority_min` and at most `priority_max`. If some item 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 move(self, from_dict, to_dict, mapping, priority=None): '''Move keys between dictionaries, possibly with changes. Every key in `mapping` is removed from `from_dict`, and added to `to_dict` with its corresponding value. The priority will be `priority`, if specified, or else its curr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def move_all(self, from_dict, to_dict): '''Move everything from one dictionary to another. This can be expensive if the source dictionary is large. This always requires a session lock. :param str from_dict: source dictionary :param str to_dict: destination dictionary ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def pull(self, dict_name): '''Get the entire contents of a single dictionary. This operates without a session lock, but is still atomic. In particular this will run even if someone else holds a session lock and you do not. This is only suitable for "small" dictionaries; if 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 filter(self, dict_name, priority_min='-inf', priority_max='+inf', start=0, limit=None): '''Get a subset of a dictionary. This retrieves only keys with priority scores greater than or equal to `priority_min` and less than or equal to `priority_max`. Of those keys, it 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 set_1to1(self, dict_name, key1, key2): '''Set two keys to be equal in a 1-to-1 mapping. Within `dict_name`, `key1` is set to `key2`, and `key2` is set to `key1`. This always requires a session lock. :param str dict_name: dictionary to update :param str key1: first ...
<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, dict_name, key, default=None, include_priority=False): '''Get the value for a specific key in a specific dictionary. If `include_priority` is false (default), returns the value for that key, or `default` (defaults to :const:`None`) if it is absent. If `include_priority` 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 set(self, dict_name, key, value, priority=None): '''Set a single value for a single key. This requires a session lock. :param str dict_name: name of the dictionary to update :param str key: key to update :param str value: value to assign to `key` :param int priority...
<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(self, dict_name): '''Delete an entire dictionary. This operation on its own is atomic and does not require a session lock, but a session lock is honored. :param str dict_name: name of the dictionary to delete :raises rejester.exceptions.LockError: if called with a se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def direct_call(self, *args): '''execute a direct redis call against this Registry instances namespaced keys. This is low level is should only be used for prototyping. arg[0] = redis function arg[1] = key --- will be namespaced before execution args[2:] = args to functi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ask(question): ''' Infinite loop to get yes or no answer or quit the script. ''' while True: ans = input(question) al = ans.lower() if match('^y(es)?$', al): return True elif match('^n(o)?$', al): return False elif match('^q(uit)?$', al...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_remote_user(request): """Parse basic HTTP_AUTHORIZATION and return user name """
if 'HTTP_AUTHORIZATION' not in request.environ: return authorization = request.environ['HTTP_AUTHORIZATION'] try: authmeth, auth = authorization.split(' ', 1) except ValueError: # not enough values to unpack return if authmeth.lower() != 'basic': return 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 basic_auth_tween_factory(handler, registry): """Do basic authentication, parse HTTP_AUTHORIZATION and set remote_user variable to request """
def basic_auth_tween(request): remote_user = get_remote_user(request) if remote_user is not None: request.environ['REMOTE_USER'] = remote_user[0] return handler(request) return basic_auth_tween
<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_triaxial(height, width, tools): '''Plot pandas dataframe containing an x, y, and z column''' import bokeh.plotting p = bokeh.plotting.figure(x_axis_type='datetime', plot_height=height, plot_width=width, title...
<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_data(path_dir): '''Load data, directory parameters, and accelerometer parameter names Args ---- path_dir: str Path to the data directory Returns ------- data: pandas.DataFrame Experiment data params_tag: dict A dictionary of parameters parsed from the 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 callback_checkbox(attr, old, new): '''Update visible data from parameters selectin in the CheckboxSelect''' import numpy for i in range(len(lines)): lines[i].visible = i in param_checkbox.active scats[i].visible = i in param_checkbox.active return 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 get_password(config): """Returns the password for a remote server It tries to fetch the password from the following locations in this order: 1. config file [...
password = config.get_option('remote.password') if password == '': user = config.get_option('remote.user') url = config.get_option('remote.url') url_obj = urlparse.urlparse(url) server = url_obj.hostname protocol = url_obj.scheme if HAS_GNOME_KEYRING_SUPPORT: ...