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 create_entry_file(self, filename, script_map, enapps): '''Creates an entry file for the given script map''' if len(script_map) == 0: return # create the entry file template = MakoTemplate(''' <%! import os %> // dynamic imports are within functions so they don't happen u...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def template_scripts(self, config, template_name): ''' Returns a list of scripts used by the given template object AND its ancestors. This runs a ProviderRun on the given template (as if it were being displayed). This allows the WEBPACK_PROVIDERS to provide the JS files to us. '...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def render_template(request, app, template_name, context=None, subdir="templates", def_name=None): ''' Convenience method that directly renders a template, given the app and template names. ''' return get_template(app, template_name, subdir).render(context, request, def_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 get_template_for_path(path, use_cache=True): ''' Convenience method that retrieves a template given a direct path to it. ''' dmp = apps.get_app_config('django_mako_plus') app_path, template_name = os.path.split(path) return dmp.engine.get_template_loader_for_path(app_path, use_cache=use_cach...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def render_template_for_path(request, path, context=None, use_cache=True, def_name=None): ''' Convenience method that directly renders a template, given a direct path to it. ''' return get_template_for_path(path, use_cache).render(context, request, def_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 qualified_name(obj): '''Returns the fully-qualified name of the given object''' if not hasattr(obj, '__module__'): obj = obj.__class__ module = obj.__module__ if module is None or module == str.__class__.__module__: return obj.__qualname__ return '{}.{}'.format(module, obj.__qual...
<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_default_link(self): '''Called when 'link' is not defined in the settings''' attrs = {} attrs["rel"] = "stylesheet" attrs["href"] ="{}?{:x}".format( os.path.join(settings.STATIC_URL, self.filepath).replace(os.path.sep, '/'), self.version_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 build_default_filepath(self): '''Called when 'filepath' is not defined in the settings''' return os.path.join( self.app_config.name, 'scripts', self.template_relpath + '.js', )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _toggle_autoescape(context, escape_on=True): ''' Internal method to toggle autoescaping on or off. This function needs access to the caller, so the calling method must be decorated with @supports_caller. ''' previous = is_autoescape(context) setattr(context.caller_stack, AUTOESCAPE_KEY, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def pretty_relpath(path, start): ''' Returns a relative path, but only if it doesn't start with a non-pretty parent directory ".." ''' relpath = os.path.relpath(path, start) if relpath.startswith('..'): return path return relpath
<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_decorated(cls, f): '''Returns True if the given function is decorated with @view_function''' real_func = inspect.unwrap(f) return real_func in cls.DECORATED_FUNCTIONS
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def run(self): '''Performs the run through the templates and their providers''' for tpl in self.templates: for provider in tpl.providers: provider.provide()
<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, content): '''Provider instances use this to write to the buffer''' self.buffer.write(content) if settings.DEBUG: self.buffer.write('\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 prepare_sort_key(self): ''' Triggered by view_function._sort_converters when our sort key should be created. This can't be called in the constructor because Django models might not be ready yet. ''' if isinstance(self.convert_type, str): try: app_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 needs_compile(self): '''Returns True if self.sourcepath is newer than self.targetpath''' try: source_mtime = os.stat(self.sourcepath).st_mtime except OSError: # no source for this template, so just return return False try: target_mtime = os.stat(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_template_debug(template_name, error): ''' This structure is what Django wants when errors occur in templates. It gives the user a nice stack trace in the...
) tback = RichTraceback(error, error.__traceback__) lines = stacktrace_template.render_unicode(tback=tback) return { 'message': '', 'source_lines': [ ( '', mark_safe(lines) ), ], 'before': '', 'during': '', 'after': '', 'top': 0, 'b...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def render_to_response(self, context=None, request=None, def_name=None, content_type=None, status=None, charset=None): ''' Renders the template and returns an HttpRequest object containing its content. This method returns a django.http.Http404 exception if the template is not found. If ...
<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_action_by_dest(self, parser, dest): '''Retrieves the given parser action object by its dest= attribute''' for action in parser._actions: if action.dest == dest: return action 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 message(self, msg='', level=1, tab=0): '''Print a message to the console''' if self.verbosity >= level: self.stdout.write('{}{}'.format(' ' * tab, msg))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def b58enc(uid): '''Encodes a UID to an 11-length string, encoded using base58 url-safe alphabet''' # note: i tested a buffer array too, but string concat was 2x faster if not isinstance(uid, int): raise ValueError('Invalid integer: {}'.format(uid)) if uid == 0: return BASE58CHARS[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 b58dec(enc_uid): '''Decodes a UID from base58, url-safe alphabet back to int.''' if isinstance(enc_uid, str): pass elif isinstance(enc_uid, bytes): enc_uid = enc_uid.decode('utf8') else: raise ValueError('Cannot decode this type: {}'.format(enc_uid)) uid = 0 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 match(self, fname, flevel, ftype): '''Returns the result score if the file matches this rule''' # if filetype is the same # and level isn't set or level is the same # and pattern matche the filename if self.filetype == ftype and (self.level is None or self.level == flevel) an...
<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_rules(self): '''Adds rules for the command line options''' dmp = apps.get_app_config('django_mako_plus') # the default rules = [ # files are included by default Rule('*', level=None, filetype=TYPE_FILE, score=1), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def copy_dir(self, source, dest, level=0): '''Copies the static files from one directory to another. If this command is run, we assume the user wants to overwrite any existing files.''' encoding = settings.DEFAULT_CHARSET or 'utf8' msglevel = 2 if level == 0 else 3 self.message('Directo...
<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_template_loader(self, subdir='templates'): '''App-specific function to get the current app's template loader''' if self.request is None: raise ValueError("this method can only be called after the view middleware is run. Check that `django_mako_plus.middleware` is in MIDDLEWARE.") ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ready(self): '''Called by Django when the app is ready for use.''' # set up the options self.options = {} self.options.update(DEFAULT_OPTIONS) for template_engine in settings.TEMPLATES: if template_engine.get('BACKEND', '').startswith('django_mako_plus'): ...
<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_app(self, app=None): ''' Registers an app as a "DMP-enabled" app. Normally, DMP does this automatically when included in urls.py. If app is None, the DEFAULT_APP is registered. ''' app = app or self.options['DEFAULT_APP'] if not app: rai...
<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, idx, default=''): '''Returns the element at idx, or default if idx is beyond the length of the list''' # if the index is beyond the length of the list, return '' if isinstance(idx, int) and (idx >= len(self) or idx < -1 * len(self)): return default # else do the...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _check_default(value, parameter, default_chars): '''Returns the default if the value is "empty"''' # not using a set here because it fails when value is unhashable if value in default_chars: if parameter.default is inspect.Parameter.empty: raise ValueError('Value was empty, but no de...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def parameter_converter(*convert_types): ''' Decorator that denotes a function as a url parameter converter. ''' def inner(func): for ct in convert_types: ParameterConverter._register_converter(func, ct) return func return 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 protocol(handler, cfg): """ Run all the stages in protocol Parameters handler : SystemHandler Container of initial conditions of simulation cfg : dict Import...
# Stages if 'stages' not in cfg: raise ValueError('Protocol must include stages of simulation') pos, vel, box = handler.positions, handler.velocities, handler.box stages = cfg.pop('stages') for stage_options in stages: options = DEFAULT_OPTIONS.copy() options.update(cfg) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def minimize(self, tolerance=None, max_iterations=None): """ Minimize energy of the system until meeting `tolerance` or performing `max_iterations`. """
if tolerance is None: tolerance = self.minimization_tolerance if max_iterations is None: max_iterations = self.minimization_max_iterations self.simulation.minimizeEnergy(tolerance * u.kilojoules_per_mole, max_iterations)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def simulate(self, steps=None): """ Advance simulation n steps """
if steps is None: steps = self.steps self.simulation.step(steps)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restraint_force(self, indices=None, strength=5.0): """ Force that restrains atoms to fix their positions, while allowing tiny movement to resolve severe clas...
if self.system.usesPeriodicBoundaryConditions(): expression = 'k*periodicdistance(x, y, z, x0, y0, z0)^2' else: expression = 'k*((x-x0)^2 + (y-y0)^2 + (z-z0)^2)' force = mm.CustomExternalForce(expression) force.addGlobalParameter('k', strength*u.kilocalories_per_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def subset(self, selector): """ Returns a list of atom indices corresponding to a MDTraj DSL query. Also will accept list of numbers, which will be coerced to in...
if isinstance(selector, (list, tuple)): return map(int, selector) selector = SELECTORS.get(selector, selector) mdtop = MDTrajTopology.from_openmm(self.handler.topology) return mdtop.select(selector)
<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_exceptions(self, verbose=True): """ Handle Ctrl+C and accidental exceptions and attempt to save the current state of the simulation """
try: yield except (KeyboardInterrupt, Exception) as ex: if not self.attempt_rescue: raise ex if isinstance(ex, KeyboardInterrupt): reraise = False answer = timed_input('\n\nDo you want to save current state? (y/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 backup_simulation(self): """ Creates an emergency report run, .state included """
path = self.new_filename(suffix='_emergency.state') self.simulation.saveState(path) uses_pbc = self.system.usesPeriodicBoundaryConditions() state_kw = dict(getPositions=True, getVelocities=True, getForces=True, enforcePeriodicBox=uses_pbc, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare_input(argv=None): """ Get, parse and prepare input file. """
p = ArgumentParser(description='InsiliChem Ommprotocol: ' 'easy to deploy MD protocols for OpenMM') p.add_argument('input', metavar='INPUT FILE', type=extant_file, help='YAML input file') p.add_argument('--version', action='version', version='%(prog)s v{}'.format(_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare_handler(cfg): """ Load all files into single object. """
positions, velocities, box = None, None, None _path = cfg.get('_path', './') forcefield = cfg.pop('forcefield', None) topology_args = sanitize_args_for_file(cfg.pop('topology'), _path) if 'checkpoint' in cfg: restart_args = sanitize_args_for_file(cfg.pop('checkpoint'), _path) resta...
<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_forcefield(*forcefields): """ Given a list of filenames, check which ones are `frcmods`. If so, convert them to ffxml. Else, just return them. """
for forcefield in forcefields: if forcefield.endswith('.frcmod'): gaffmol2 = os.path.splitext(forcefield)[0] + '.gaff.mol2' yield create_ffxml_file([gaffmol2], [forcefield]) else: yield forcefield
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def statexml2pdb(topology, state, output=None): """ Given an OpenMM xml file containing the state of the simulation, generate a PDB snapshot for easy visualizati...
state = Restart.from_xml(state) system = SystemHandler.load(topology, positions=state.positions) if output is None: output = topology + '.pdb' system.write_pdb(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 export_frame_coordinates(topology, trajectory, nframe, output=None): """ Extract a single frame structure from a trajectory. """
if output is None: basename, ext = os.path.splitext(trajectory) output = '{}.frame{}.inpcrd'.format(basename, nframe) # ParmEd sometimes struggles with certain PRMTOP files if os.path.splitext(topology)[1] in ('.top', '.prmtop'): top = AmberPrmtopFile(topology) mdtop = mdtr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def construct_include(self, node): """Include file referenced at node."""
filename = os.path.join(self._root, self.construct_scalar(node)) filename = os.path.abspath(filename) extension = os.path.splitext(filename)[1].lstrip('.') with open(filename, 'r') as f: if extension in ('yaml', 'yml'): return yaml.load(f, Loader=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 from_pdb(cls, path, forcefield=None, loader=PDBFile, strict=True, **kwargs): """ Loads topology, positions and, potentially, velocities and vectors, from a P...
pdb = loader(path) box = kwargs.pop('box', pdb.topology.getPeriodicBoxVectors()) positions = kwargs.pop('positions', pdb.positions) velocities = kwargs.pop('velocities', getattr(pdb, 'velocities', None)) if strict and not forcefield: from .md import FORCEFIELDS as 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 from_amber(cls, path, positions=None, strict=True, **kwargs): """ Loads Amber Parm7 parameters and topology file Parameters path : str Path to *.prmtop or *....
if strict and positions is None: raise ValueError('Amber TOP/PRMTOP files require initial positions.') prmtop = AmberPrmtopFile(path) box = kwargs.pop('box', prmtop.topology.getPeriodicBoxVectors()) return cls(master=prmtop, topology=prmtop.topology, positions=positions, box...
<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_charmm(cls, path, positions=None, forcefield=None, strict=True, **kwargs): """ Loads PSF Charmm structure from `path`. Requires `charmm_parameters`. Par...
psf = CharmmPsfFile(path) if strict and forcefield is None: raise ValueError('PSF files require key `forcefield`.') if strict and positions is None: raise ValueError('PSF files require key `positions`.') psf.parmset = CharmmParameterSet(*forcefield) psf.l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_desmond(cls, path, **kwargs): """ Loads a topology from a Desmond DMS file located at `path`. Arguments --------- path : str Path to a Desmond DMS file ...
dms = DesmondDMSFile(path) pos = kwargs.pop('positions', dms.getPositions()) return cls(master=dms, topology=dms.getTopology(), positions=pos, path=path, **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 from_gromacs(cls, path, positions=None, forcefield=None, strict=True, **kwargs): """ Loads a topology from a Gromacs TOP file located at `path`. Additional r...
if strict and positions is None: raise ValueError('Gromacs TOP files require initial positions.') box = kwargs.pop('box', None) top = GromacsTopFile(path, includeDir=forcefield, periodicBoxVectors=box) return cls(master=top, topology=top.topology, positions=positions, box=bo...
<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_parmed(cls, path, *args, **kwargs): """ Try to load a file automatically with ParmEd. Not guaranteed to work, but might be useful if it succeeds. Argume...
st = parmed.load_file(path, structure=True, *args, **kwargs) box = kwargs.pop('box', getattr(st, 'box', None)) velocities = kwargs.pop('velocities', getattr(st, 'velocities', None)) positions = kwargs.pop('positions', getattr(st, 'positions', None)) return cls(master=st, topolog...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pickle_load(path): """ Loads pickled topology. Careful with Python versions though! """
_, ext = os.path.splitext(path) topology = None if sys.version_info.major == 2: if ext == '.pickle2': with open(path, 'rb') as f: topology = pickle.load(f) elif ext in ('.pickle3', '.pickle'): with open(path, 'rb') as 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 create_system(self, **system_options): """ Create an OpenMM system for every supported topology file with given system options """
if self.master is None: raise ValueError('Handler {} is not able to create systems.'.format(self)) if isinstance(self.master, ForceField): system = self.master.createSystem(self.topology, **system_options) elif isinstance(self.master, (AmberPrmtopFile, GromacsTopFile, 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 write_pdb(self, path): """ Outputs a PDB file with the current contents of the system """
if self.master is None and self.positions is None: raise ValueError('Topology and positions are needed to write output files.') with open(path, 'w') as f: PDBFile.writeFile(self.topology, self.positions, 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 from_xsc(cls, path): """ Returns u.Quantity with box vectors from XSC file """
def parse(path): """ Open and parses an XSC file into its fields Parameters ---------- path : str Path to XSC file Returns ------- namedxsc : namedtuple A namedtuple with XSC field...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_csv(cls, path): """ Get box vectors from comma-separated values in file `path`. The csv file must containt only one line, which in turn can contain thre...
with open(path) as f: fields = map(float, next(f).split(',')) if len(fields) == 3: return u.Quantity([[fields[0], 0, 0], [0, fields[1], 0], [0, 0, fields[2]]], unit=u.nanometers) elif len(fields) == 9: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def describeNextReport(self, simulation): """Get information about the next report this object will generate. Parameters simulation : Simulation The Simulation t...
steps = self.interval - simulation.currentStep % self.interval return steps, False, False, False, False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assert_not_exists(path, sep='.'): """ If path exists, modify to add a counter in the filename. Useful for preventing accidental overrides. For example, if `f...
name, ext = os.path.splitext(path) i = 1 while os.path.exists(path): path = '{}{}{}{}'.format(name, sep, i, ext) i += 1 return path
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assertinstance(obj, types): """ Make sure object `obj` is of type `types`. Else, raise TypeError. """
if isinstance(obj, types): return obj raise TypeError('{} must be instance of {}'.format(obj, types))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extant_file(path): """ Check if file exists with argparse """
if not os.path.exists(path): raise argparse.ArgumentTypeError("{} does not exist".format(path)) return path
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort_key_for_numeric_suffixes(path, sep='.', suffix_index=-2): """ Sort files taking into account potentially absent suffixes like somefile.dcd somefile.1000...
chunks = path.split(sep) # Remove suffix from path and convert to int if chunks[suffix_index].isdigit(): return sep.join(chunks[:suffix_index] + chunks[suffix_index+1:]), int(chunks[suffix_index]) return path, 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 json_response(f, *args, **kwargs): """Wrap a view in JSON. This decorator runs the given function and looks out for ajax.AJAXError's, which it encodes into a...
try: result = f(*args, **kwargs) if isinstance(result, AJAXError): raise result except AJAXError as e: result = e.get_response() request = args[0] logger.warn('AJAXError: %d %s - %s', e.code, request.path, e.msg, exc_info=True, 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 endpoint_loader(request, application, model, **kwargs): """Load an AJAX endpoint. This will load either an ad-hoc endpoint or it will load up a model endpoin...
if request.method != "POST": raise AJAXError(400, _('Invalid HTTP method used.')) try: module = import_module('%s.endpoints' % application) except ImportError as e: if settings.DEBUG: raise e else: raise AJAXError(404, _('AJAX endpoint does not exist...
<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, request): """ List objects of a model. By default will show page 1 with 20 objects on it. **Usage**:: params = {"items_per_page":10,"page":2} //al...
max_items_per_page = getattr(self, 'max_per_page', getattr(settings, 'AJAX_MAX_PER_PAGE', 100)) requested_items_per_page = request.POST.get("items_per_page", 20) items_per_page = min(max_items_per_page, requested_items_per_page) current_page = requ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _extract_data(self, request): """Extract data from POST. Handles extracting a vanilla Python dict of values that are present in the given model. This also ha...
data = {} for field, val in six.iteritems(request.POST): if field in self.immutable_fields: continue # Ignore immutable fields silently. if field in self.fields: field_obj = self.model._meta.get_field(field) val = self._extract_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 _get_record(self): """Fetch a given record. Handles fetching a record from the database along with throwing an appropriate instance of ``AJAXError`. """
if not self.pk: raise AJAXError(400, _('Invalid request for record.')) try: return self.model.objects.get(pk=self.pk) except self.model.DoesNotExist: raise AJAXError(404, _('%s with id of "%s" not found.') % ( self.model.__name__, self.pk))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authenticate(self, request, application, method): """Authenticate the AJAX request. By default any request to fetch a model is allowed for any user, includin...
return self.authentication.is_authenticated(request, application, method)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def all(self, query=None): """ Gets all entries of a space. """
if query is None: query = {} if self.content_type_id is not None: query['content_type'] = self.content_type_id normalize_select(query) return super(EntriesProxy, self).all(query=query)
<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(self, entry_id, query=None): """ Gets a single entry by ID. """
if query is None: query = {} if self.content_type_id is not None: query['content_type'] = self.content_type_id normalize_select(query) return super(EntriesProxy, self).find(entry_id, query=query)
<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=None, **kwargs): """ Creates a webhook with given attributes. """
return super(WebhooksProxy, self).create(resource_id=None, attributes=attributes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def camel_case(snake_str): """ Returns a camel-cased version of a string. :param a_string: any :class:`str` object. Usage: "fooBar" """
components = snake_str.split('_') # We capitalize the first letter of each component except the first one # with the 'title' method and join them together. return components[0] + "".join(x.title() for x in components[1:])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_json(self): """ Returns the JSON representation of the environment. """
result = super(Environment, self).to_json() result.update({ 'name': self.name }) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def content_types(self): """ Provides access to content type management methods for content types of an environment. API reference: https://www.contentful.com/de...
return EnvironmentContentTypesProxy(self._client, self.space.id, 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 entries(self): """ Provides access to entry management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#...
return EnvironmentEntriesProxy(self._client, self.space.id, 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 assets(self): """ Provides access to asset management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/...
return EnvironmentAssetsProxy(self._client, self.space.id, 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 locales(self): """ Provides access to locale management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/...
return EnvironmentLocalesProxy(self._client, self.space.id, 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 ui_extensions(self): """ Provides access to UI extensions management methods. API reference: https://www.contentful.com/developers/docs/references/content-ma...
return EnvironmentUIExtensionsProxy(self._client, self.space.id, 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 base_url(klass, space_id='', resource_id=None, environment_id=None, **kwargs): """ Returns the URI for the resource. """
url = "spaces/{0}".format( space_id) if environment_id is not None: url = url = "{0}/environments/{1}".format(url, environment_id) url = "{0}/{1}".format( url, base_path_for(klass.__name__) ) if resource_id: 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 delete(self): """ Deletes the resource. """
return self._client._delete( self.__class__.base_url( self.sys['space'].id, self.sys['id'], environment_id=self._environment_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 update(self, attributes=None): """ Updates the resource with attributes. """
if attributes is None: attributes = {} headers = self.__class__.create_headers(attributes) headers.update(self._update_headers()) result = self._client._put( self._update_url(), self.__class__.create_attributes(attributes, self), header...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reload(self, result=None): """ Reloads the resource. """
if result is None: result = self._client._get( self.__class__.base_url( self.sys['space'].id, self.sys['id'], environment_id=self._environment_id ) ) self._update_from_resource(result) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_link(self): """ Returns a link for the resource. """
link_type = self.link_type if self.type == 'Link' else self.type return Link({'sys': {'linkType': link_type, 'id': self.sys.get('id')}}, client=self._client)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_json(self): """ Returns the JSON representation of the resource. """
result = { 'sys': {} } for k, v in self.sys.items(): if k in ['space', 'content_type', 'created_by', 'updated_by', 'published_by']: v = v.to_json() if k in ['created_at', 'updated_at', 'deleted_at', '...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fields_with_locales(self): """ Get fields with locales per field. """
result = {} for locale, fields in self._fields.items(): for k, v in fields.items(): real_field_id = self._real_field_id_for(k) if real_field_id not in result: result[real_field_id] = {} result[real_field_id][locale] = 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 to_json(self): """ Returns the JSON Representation of the resource. """
result = super(FieldsResource, self).to_json() result['fields'] = self.fields_with_locales() return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_updated(self): """ Checks if a resource has been updated since last publish. Returns False if resource has not been published before. """
if not self.is_published: return False return sanitize_date(self.sys['published_at']) < sanitize_date(self.sys['updated_at'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unpublish(self): """ Unpublishes the resource. """
self._client._delete( "{0}/published".format( self.__class__.base_url( self.sys['space'].id, self.sys['id'], environment_id=self._environment_id ), ), headers=self._update_headers() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def archive(self): """ Archives the resource. """
self._client._put( "{0}/archived".format( self.__class__.base_url( self.sys['space'].id, self.sys['id'], environment_id=self._environment_id ), ), {}, headers=self._updat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resolve(self, space_id=None, environment_id=None): """ Resolves link to a specific resource. """
proxy_method = getattr( self._client, base_path_for(self.link_type) ) if self.link_type == 'Space': return proxy_method().find(self.id) elif environment_id is not None: return proxy_method(space_id, environment_id).find(self.id) 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 url(self, **kwargs): """ Returns a formatted URL for the asset's File with serialized parameters. Usage: """
url = self.fields(self._locale()).get('file', {}).get('url', '') args = ['{0}={1}'.format(k, v) for k, v in kwargs.items()] if args: url += '?{0}'.format('&'.join(args)) 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 process(self): """ Calls the process endpoint for all locales of the asset. API reference: https://www.contentful.com/developers/docs/references/content-mana...
for locale in self._fields.keys(): self._client._put( "{0}/files/{1}/process".format( self.__class__.base_url( self.space.id, self.id, environment_id=self._environment_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 to_json(self): """ Returns the JSON Representation of the UI extension. """
result = super(UIExtension, self).to_json() result.update({ 'extension': self.extension }) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_json(self): """ Returns the JSON representation of the API key. """
result = super(ApiKey, self).to_json() result.update({ 'name': self.name, 'description': self.description, 'accessToken': self.access_token, 'environments': [e.to_json() for e in self.environments] }) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def all(self, usage_type, usage_period_id, api, query=None, *args, **kwargs): """ Gets all api usages by type for a given period an api. """
if query is None: query = {} mandatory_query = { 'filters[usagePeriod]': usage_period_id, 'filters[metric]': api } mandatory_query.update(query) return self.client._get( self._url(usage_type), mandatory_query, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def base_url(klass, space_id, resource_id=None, public=False, environment_id=None, **kwargs): """ Returns the URI for the content type. """
if public: environment_slug = "" if environment_id is not None: environment_slug = "/environments/{0}".format(environment_id) return "spaces/{0}{1}/public/content_types".format(space_id, environment_slug) return super(ContentType, klass).base_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 create_attributes(klass, attributes, previous_object=None): """ Attributes for content type creation. """
result = super(ContentType, klass).create_attributes(attributes, previous_object) if 'fields' not in result: result['fields'] = [] return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_json(self): """ Returns the JSON representation of the content type. """
result = super(ContentType, self).to_json() result.update({ 'name': self.name, 'description': self.description, 'displayField': self.display_field, 'fields': [f.to_json() for f in self.fields] }) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def editor_interfaces(self): """ Provides access to editor interface management methods for the given content type. API reference: https://www.contentful.com/dev...
return ContentTypeEditorInterfacesProxy(self._client, self.space.id, self._environment_id, 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 snapshots(self): """ Provides access to snapshot management methods for the given content type. API reference: https://www.contentful.com/developers/docs/ref...
return ContentTypeSnapshotsProxy(self._client, self.space.id, self._environment_id, 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 all(self, query=None, **kwargs): """ Gets all organizations. """
return super(OrganizationsProxy, self).all(query=query)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def base_url(klass, space_id, webhook_id, resource_id=None): """ Returns the URI for the webhook call. """
return "spaces/{0}/webhooks/{1}/calls/{2}".format( space_id, webhook_id, resource_id if resource_id is not None else '' )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_attributes(klass, attributes, previous_object=None): """Attributes for space creation."""
if previous_object is not None: return {'name': attributes.get('name', previous_object.name)} return { 'name': attributes.get('name', ''), 'defaultLocale': attributes['default_locale'] }