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 until called
DMP_CONTEXT.loadBundle({
%for (app, template), script_paths in script_map.items():
"${ app }/${ template }": () => [
%for path in script_paths:
import(/* webpackMode: "eager" */ "./${ os.path.relpath(path, os.path.dirname(filename)) }"),
%endfor
],
%endfor
})
''')
content = template.render(
enapps=enapps,
script_map=script_map,
filename=filename,
).strip()
# ensure the parent directories exist
if not os.path.exists(os.path.dirname(filename)):
os.makedirs(os.path.dirname(filename))
# if the file exists, then consider the options
file_exists = os.path.exists(filename)
if file_exists and self.running_inline:
# running inline means that we're in debug mode and webpack is likely watching, so
# we don't want to recreate the entry file (and cause webpack to constantly reload)
# unless we have changes
with open(filename, 'r') as fin:
if content == fin.read():
return False
if file_exists and not self.options.get('overwrite'):
raise CommandError('Refusing to destroy existing file: {} (use --overwrite option or remove the file)'.format(filename))
# if we get here, write the file
self.message('Creating {}'.format(os.path.relpath(filename, settings.BASE_DIR)), level=3)
with open(filename, 'w') as fout:
fout.write(content)
return 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 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.
'''
dmp = apps.get_app_config('django_mako_plus')
template_obj = dmp.engine.get_template_loader(config, create=True).get_mako_template(template_name, force=True)
mako_context = create_mako_context(template_obj)
inner_run = WebpackProviderRun(mako_context['self'])
inner_run.run()
scripts = []
for tpl in inner_run.templates:
for p in tpl.providers:
if os.path.exists(p.absfilepath):
scripts.append(p.absfilepath)
return scripts |
<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_cache).get_template(template_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 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.__qualname__) |
<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,
)
attrs.update(self.options['link_attrs'])
attrs["data-context"] = self.provider_run.uid # can't be overridden
return '<link{} />'.format(flatatt(attrs)) |
<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, escape_on)
try:
context['caller'].body()
finally:
setattr(context.caller_stack, AUTOESCAPE_KEY, previous) |
<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_name, model_name = self.convert_type.split('.')
except ValueError:
raise ImproperlyConfigured('"{}" is not a valid converter type. String-based converter types must be specified in "app.Model" format.'.format(self.convert_type))
try:
self.convert_type = apps.get_model(app_name, model_name)
except LookupError as e:
raise ImproperlyConfigured('"{}" is not a valid model name. {}'.format(self.convert_type, e))
# we reverse sort by ( len(mro), source code order ) so subclasses match first
# on same types, last declared method sorts first
self.sort_key = ( -1 * len(inspect.getmro(self.convert_type)), -1 * self.source_order ) |
<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(self.targetpath).st_mtime
except OSError: # target doesn't exist, so compile
return True
# both source and target exist, so compile if source newer
return source_mtime > target_mtime |
<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 error page during debug. ''' # This is taken from mako.exceptions.html_error_template(), which has an issue # in Py3 where files get loaded as bytes but `lines = src.split('\n')` below # splits with a string. Not sure if this is a bug or if I'm missing something, # but doing a custom debugging template allows a workaround as well as a custom # DMP look. # I used to have a file in the templates directory for this, but too many users # reported TemplateNotFound errors. This function is a bit of a hack, but it only # happens during development (and mako.exceptions does this same thing). # /justification stacktrace_template = MakoTemplate(r""" <%! from mako.exceptions import syntax_highlight, pygments_html_formatter %> <style> .stacktrace { margin:5px 5px 5px 5px; } .highlight { padding:0px 10px 0px 10px; background-color:#9F9FDF; } .nonhighlight { padding:0px; background-color:#DFDFDF; } .sample { padding:10px; margin:10px 10px 10px 10px; font-family:monospace; } .sampleline { padding:0px 10px 0px 10px; } .sourceline { margin:5px 5px 10px 5px; font-family:monospace;} .location { font-size:80%; } .highlight { white-space:pre; } .sampleline { white-space:pre; } % if pygments_html_formatter: ${pygments_html_formatter.get_style_defs() | n} .linenos { min-width: 2.5em; text-align: right; } pre { margin: 0; } .syntax-highlighted { padding: 0 10px; } .syntax-highlightedtable { border-spacing: 1px; } .nonhighlight { border-top: 1px solid #DFDFDF; border-bottom: 1px solid #DFDFDF; } .stacktrace .nonhighlight { margin: 5px 15px 10px; } .sourceline { margin: 0 0; font-family:monospace; } .code { background-color: #F8F8F8; width: 100%; } .error .code { background-color: #FFBDBD; } .error .syntax-highlighted { background-color: #FFBDBD; } % endif ## adjustments to Django css table.source { background-color: #fdfdfd; } table.source > tbody > tr > th { width: auto; } table.source > tbody > tr > td { font-family: inherit; white-space: normal; padding: 15px; } #template { background-color: #b3daff; } </style> <% src = tback.source line = tback.lineno if isinstance(src, bytes):
src = src.decode() if src: lines = src.split('\n') else: lines = None %> <h3>${tback.errorname}: ${tback.message}</h3> % if lines: <div class="sample"> <div class="nonhighlight"> % for index in range(max(0, line-4),min(len(lines), line+5)):
<% if pygments_html_formatter: pygments_html_formatter.linenostart = index + 1 %> % if index + 1 == line: <% if pygments_html_formatter: old_cssclass = pygments_html_formatter.cssclass pygments_html_formatter.cssclass = 'error ' + old_cssclass %> ${lines[index] | n,syntax_highlight(language='mako')} <% if pygments_html_formatter: pygments_html_formatter.cssclass = old_cssclass %> % else: ${lines[index] | n,syntax_highlight(language='mako')} % endif % endfor </div> </div> % endif <div class="stacktrace"> % for (filename, lineno, function, line) in tback.reverse_traceback: <div class="location">${filename}, line ${lineno}:</div> <div class="nonhighlight"> <% if pygments_html_formatter: pygments_html_formatter.linenostart = lineno %> <div class="sourceline">${line | n,syntax_highlight(filename)}</div> </div> % endfor </div> """ | )
tback = RichTraceback(error, error.__traceback__)
lines = stacktrace_template.render_unicode(tback=tback)
return {
'message': '',
'source_lines': [
( '', mark_safe(lines) ),
],
'before': '',
'during': '',
'after': '',
'top': 0,
'bottom': 0,
'total': 0,
'line': tback.lineno or 0,
'name': template_name,
'start': 0,
'end': 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 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 the template raises a django_mako_plus.RedirectException, the browser is redirected to
the given page, and a new request from the browser restarts the entire DMP routing process.
If the template raises a django_mako_plus.InternalRedirectException, the entire DMP
routing process is restarted internally (the browser doesn't see the redirect).
@request The request context from Django. If this is None, any TEMPLATE_CONTEXT_PROCESSORS defined in your settings
file will be ignored but the template will otherwise render fine.
@template The template file path to render. This is relative to the app_path/controller_TEMPLATES_DIR/ directory.
For example, to render app_path/templates/page1, set template="page1.html", assuming you have
set up the variables as described in the documentation above.
@context A dictionary of name=value variables to send to the template page. This can be a real dictionary
or a Django Context object.
@def_name Limits output to a specific top-level Mako <%block> or <%def> section within the template.
For example, def_name="foo" will call <%block name="foo"></%block> or <%def name="foo()"></def> within the template.
@content_type The MIME type of the response. Defaults to settings.DEFAULT_CONTENT_TYPE (usually 'text/html').
@status The HTTP response status code. Defaults to 200 (OK).
@charset The charset to encode the processed template string (the output) with. Defaults to settings.DEFAULT_CHARSET (usually 'utf-8').
The method triggers two signals:
1. dmp_signal_pre_render_template: you can (optionally) return a new Mako Template object from a receiver to replace
the normal template object that is used for the render operation.
2. dmp_signal_post_render_template: you can (optionally) return a string to replace the string from the normal
template object render.
'''
try:
if content_type is None:
content_type = mimetypes.types_map.get(os.path.splitext(self.mako_template.filename)[1].lower(), settings.DEFAULT_CONTENT_TYPE)
if charset is None:
charset = settings.DEFAULT_CHARSET
if status is None:
status = 200
content = self.render(context=context, request=request, def_name=def_name)
return HttpResponse(content.encode(charset), content_type='%s; charset=%s' % (content_type, charset), status=status)
except RedirectException: # redirect to another page
e = sys.exc_info()[1]
if request is None:
log.info('a template redirected processing to %s', e.redirect_to)
else:
log.info('view function %s.%s redirected processing to %s', request.dmp.module, request.dmp.function, e.redirect_to)
# send the signal
dmp = apps.get_app_config('django_mako_plus')
if dmp.options['SIGNALS']:
dmp_signal_redirect_exception.send(sender=sys.modules[__name__], request=request, exc=e)
# send the browser the redirect command
return e.get_response(request) |
<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]
enc_uid = ""
while uid:
uid, r = divmod(uid, 58)
enc_uid = BASE58CHARS[r] + enc_uid
return enc_uid |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def 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:
for i, ch in enumerate(enc_uid):
uid = (uid * 58) + BASE58INDEX[ch]
except KeyError:
raise ValueError('Invalid character: "{}" ("{}", index 5)'.format(ch, enc_uid, i))
return uid |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def 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) and fnmatch.fnmatch(fname, self.pattern):
return self.score
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 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),
# files at the app level are skipped
Rule('*', level=0, filetype=TYPE_FILE, score=-2),
# directories are recursed by default
Rule('*', level=None, filetype=TYPE_DIRECTORY, score=1),
# directories at the app level are skipped
Rule('*', level=0, filetype=TYPE_DIRECTORY, score=-2),
# media, scripts, styles directories are what we want to copy
Rule('media', level=0, filetype=TYPE_DIRECTORY, score=6),
Rule('scripts', level=0, filetype=TYPE_DIRECTORY, score=6),
Rule('styles', level=0, filetype=TYPE_DIRECTORY, score=6),
# ignore the template cache directories
Rule(dmp.options['TEMPLATES_CACHE_DIR'], level=None, filetype=TYPE_DIRECTORY, score=-3),
# ignore python cache directories
Rule('__pycache__', level=None, filetype=TYPE_DIRECTORY, score=-3),
# ignore compiled python files
Rule('*.pyc', level=None, filetype=TYPE_FILE, score=-3),
]
# include rules have score of 50 because they trump all initial rules
for pattern in (self.options.get('include_dir') or []):
self.message('Setting rule - recurse directories: {}'.format(pattern), 1)
rules.append(Rule(pattern, level=None, filetype=TYPE_DIRECTORY, score=50))
for pattern in (self.options.get('include_file') or []):
self.message('Setting rule - include files: {}'.format(pattern), 1)
rules.append(Rule(pattern, level=None, filetype=TYPE_FILE, score=50))
# skip rules have score of 100 because they trump everything, including the includes from the command line
for pattern in (self.options.get('skip_dir') or []):
self.message('Setting rule - skip directories: {}'.format(pattern), 1)
rules.append(Rule(pattern, level=None, filetype=TYPE_DIRECTORY, score=-100))
for pattern in (self.options.get('skip_file') or []):
self.message('Setting rule - skip files: {}'.format(pattern), 1)
rules.append(Rule(pattern, level=None, filetype=TYPE_FILE, score=-100))
return rules |
<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('Directory: {}'.format(source), msglevel, level)
# create a directory for this app
if not os.path.exists(dest):
self.message('Creating directory: {}'.format(dest), msglevel, level+1)
os.mkdir(dest)
# go through the files in this app
for fname in os.listdir(source):
source_path = os.path.join(source, fname)
dest_path = os.path.join(dest, fname)
ext = os.path.splitext(fname)[1].lower()
# get the score for this file
score = 0
for rule in self.rules:
score += rule.match(fname, level, TYPE_DIRECTORY if os.path.isdir(source_path) else TYPE_FILE)
# if score is not above zero, we skip this file
if score <= 0:
self.message('Skipping file with score {}: {}'.format(score, source_path), msglevel, level+1)
continue
### if we get here, we need to copy the file ###
# if a directory, recurse to it
if os.path.isdir(source_path):
self.message('Creating directory with score {}: {}'.format(score, source_path), msglevel, level+1)
# create it in the destination and recurse
if not os.path.exists(dest_path):
os.mkdir(dest_path)
elif not os.path.isdir(dest_path): # could be a file or link
os.unlink(dest_path)
os.mkdir(dest_path)
self.copy_dir(source_path, dest_path, level+1)
# if a regular Javscript file, run through the static file processors (scripts group)
elif ext == '.js' and not self.options.get('no_minify') and jsmin:
self.message('Including and minifying file with score {}: {}'.format(score, source_path), msglevel, level+1)
with open(source_path, encoding=encoding) as fin:
with open(dest_path, 'w', encoding=encoding) as fout:
minified = minify(fin.read(), jsmin)
fout.write(minified)
# if a CSS file, run through the static file processors (styles group)
elif ext == '.css' and not self.options.get('no_minify') and cssmin:
self.message('Including and minifying file with score {}: {}'.format(score, source_path), msglevel, level+1)
with open(source_path, encoding=encoding) as fin:
with open(dest_path, 'w', encoding=encoding) as fout:
minified = minify(fin.read(), cssmin)
fout.write(minified)
# otherwise, just copy the file
else:
self.message('Including file with score {}: {}'.format(score, source_path), msglevel, level+1)
shutil.copy2(source_path, dest_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 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.")
dmp = apps.get_app_config('django_mako_plus')
return dmp.engine.get_template_loader(self.app, subdir) |
<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'):
self.options.update(template_engine.get('OPTIONS', {}))
# dmp-enabled apps registry
self.registration_lock = threading.RLock()
self.registered_apps = {}
# init the template engine
self.engine = engines['django_mako_plus']
# default imports on every compiled template
self.template_imports = [
'import django_mako_plus',
'import django.utils.html', # used in template.py
]
self.template_imports.extend(self.options['DEFAULT_TEMPLATE_IMPORTS'])
# initialize the list of providers
ProviderRun.initialize_providers()
# set up the parameter converters (can't import until apps are set up)
from .converter.base import ParameterConverter
ParameterConverter._sort_converters(app_ready=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 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:
raise ImproperlyConfigured('An app name is required because DEFAULT_APP is empty - please use a '
'valid app name or set the DEFAULT_APP in settings')
if isinstance(app, str):
app = apps.get_app_config(app)
# since this only runs at startup, this lock doesn't affect performance
with self.registration_lock:
# short circuit if already registered
if app.name in self.registered_apps:
return
# first time for this app, so add to our dictionary
self.registered_apps[app.name] = app
# set up the template, script, and style renderers
# these create and cache just by accessing them
self.engine.get_template_loader(app, 'templates', create=True)
self.engine.get_template_loader(app, 'scripts', create=True)
self.engine.get_template_loader(app, 'styles', create=True)
# send the registration signal
if self.options['SIGNALS']:
dmp_signal_register_app.send(sender=self, app_config=app) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def 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 regular list function (for int, slice types, etc.)
return super().__getitem__(idx) |
<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 default value is given in view function for parameter: {} ({})'.format(parameter.position, parameter.name))
return parameter.default
return value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def 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 Imported YAML file. """ |
# 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)
stage_system_options = prepare_system_options(stage_options)
options.update(stage_options)
options['system_options'].update(stage_system_options)
stage = Stage(handler, positions=pos, velocities=vel, box=box,
total_stages=len(stages), **options)
pos, vel, box = stage.run()
del stage |
<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 clashes and so on. Returns ------- force : simtk.openmm.CustomExternalForce A custom force to restrain the selected atoms """ |
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_mole/u.angstroms**2)
force.addPerParticleParameter('x0')
force.addPerParticleParameter('y0')
force.addPerParticleParameter('z0')
positions = self.positions if self.positions is not None else self.handler.positions
if indices is None:
indices = range(self.handler.topology.getNumAtoms())
for i, index in enumerate(indices):
force.addParticle(i, positions[index].value_in_unit(u.nanometers))
return force |
<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 int and returned. """ |
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): ')
if answer and answer.lower() not in ('y', 'yes'):
if verbose:
sys.exit('Ok, bye!')
else:
reraise = True
logger.error('\n\nAn error occurred: %s', ex)
if verbose:
logger.info('Saving state...')
try:
self.backup_simulation()
except Exception:
if verbose:
logger.error('FAILED :(')
else:
if verbose:
logger.info('SUCCESS!')
finally:
if reraise:
raise ex
sys.exit() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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,
getParameters=True, getEnergy=True)
state = self.simulation.context.getState(**state_kw)
for reporter in self.simulation.reporters:
if not isinstance(reporter, app.StateDataReporter):
reporter.report(self.simulation, state) |
<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(__version__))
p.add_argument('-c', '--check', action='store_true',
help='Validate input file only')
args = p.parse_args(argv if argv else sys.argv[1:])
jinja_env = jinja2.Environment(trim_blocks=True, lstrip_blocks=True)
# Load config file
with open(args.input) as f:
rendered = jinja_env.from_string(f.read()).render()
cfg = yaml.load(rendered, Loader=YamlLoader)
# Paths and dirs
from .md import SYSTEM_OPTIONS
cfg['_path'] = os.path.abspath(args.input)
cfg['system_options'] = prepare_system_options(cfg, defaults=SYSTEM_OPTIONS)
cfg['outputpath'] = sanitize_path_for_file(cfg.get('outputpath', '.'), args.input)
if not args.check:
with ignored_exceptions(OSError):
os.makedirs(cfg['outputpath'])
handler = prepare_handler(cfg)
return handler, cfg, args |
<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)
restart = Restart.load(*restart_args)
positions = restart.positions
velocities = restart.velocities
box = restart.box
if 'positions' in cfg:
positions_args = sanitize_args_for_file(cfg.pop('positions'), _path)
positions = Positions.load(*positions_args)
box = BoxVectors.load(*positions_args)
if 'velocities' in cfg:
velocities_args = sanitize_args_for_file(cfg.pop('velocities'), _path)
velocities = Velocities.load(*velocities_args)
if 'box' in cfg:
box_args = sanitize_args_for_file(cfg.pop('box'), _path)
box = BoxVectors.load(*box_args)
options = {}
for key in 'positions velocities box forcefield'.split():
value = locals()[key]
if value is not None:
options[key] = value
return SystemHandler.load(*topology_args, **options) |
<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 visualization. """ |
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 = mdtraj.Topology.from_openmm(top.topology)
traj = mdtraj.load_frame(trajectory, int(nframe), top=mdtop)
structure = parmed.openmm.load_topology(top.topology, system=top.createSystem())
structure.box_vectors = top.topology.getPeriodicBoxVectors()
else: # standard protocol (the topology is loaded twice, though)
traj = mdtraj.load_frame(trajectory, int(nframe), top=topology)
structure = parmed.load_file(topology)
structure.positions = traj.openmm_positions(0)
if traj.unitcell_vectors is not None: # if frame provides box vectors, use those
structure.box_vectors = traj.openmm_boxes(0)
structure.save(output, overwrite=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 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)
else:
return ''.join(f.readlines()) |
<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 PDB or PDBx file Parameters path : str Path to PDB/PDBx file forcefields : list of str Paths to FFXML and/or FRCMOD forcefields. REQUIRED. Returns ------- pdb : SystemHandler SystemHandler with topology, positions, and, potentially, velocities and box vectors. Forcefields are embedded in the `master` attribute. """ |
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 forcefield
logger.info('! Forcefields for PDB not specified. Using default: %s',
', '.join(forcefield))
pdb.forcefield = ForceField(*list(process_forcefield(*forcefield)))
return cls(master=pdb.forcefield, topology=pdb.topology, positions=positions,
velocities=velocities, box=box, 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_amber(cls, path, positions=None, strict=True, **kwargs):
""" Loads Amber Parm7 parameters and topology file Parameters path : str Path to *.prmtop or *.top file positions : simtk.unit.Quantity Atomic positions Returns ------- prmtop : SystemHandler SystemHandler with topology """ |
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=box,
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_charmm(cls, path, positions=None, forcefield=None, strict=True, **kwargs):
""" Loads PSF Charmm structure from `path`. Requires `charmm_parameters`. Parameters path : str Path to PSF file forcefield : list of str Paths to Charmm parameters files, such as *.par or *.str. REQUIRED Returns ------- psf : SystemHandler SystemHandler with topology. Charmm parameters are embedded in the `master` attribute. """ |
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.loadParameters(psf.parmset)
return cls(master=psf, topology=psf.topology, positions=positions, 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_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 root directory for parameters can be specified with `forcefield`. Arguments --------- path : str Path to a Gromacs TOP file positions : simtk.unit.Quantity Atomic positions forcefield : str, optional Root directory for parameter files """ |
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=box,
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_parmed(cls, path, *args, **kwargs):
""" Try to load a file automatically with ParmEd. Not guaranteed to work, but might be useful if it succeeds. Arguments --------- path : str Path to file that ParmEd can load """ |
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, topology=st.topology, positions=positions, box=box,
velocities=velocities, 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 _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:
topology = pickle.load(f, protocol=3)
elif sys.version_info.major == 3:
if ext == '.pickle2':
with open(path, 'rb') as f:
topology = pickle.load(f)
elif ext in ('.pickle3', '.pickle'):
with open(path, 'rb') as f:
topology = pickle.load(f)
if topology is None:
raise ValueError('File {} is not compatible with this version'.format(path))
return topology |
<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, DesmondDMSFile)):
system = self.master.createSystem(**system_options)
elif isinstance(self.master, CharmmPsfFile):
if not hasattr(self.master, 'parmset'):
raise ValueError('PSF topology files require Charmm parameters.')
system = self.master.createSystem(self.master.parmset, **system_options)
else:
raise NotImplementedError('Handler {} is not able to create systems.'.format(self))
if self.has_box:
system.setDefaultPeriodicBoxVectors(*self.box)
return system |
<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 fields as names
"""
with open(path) as f:
lines = f.readlines()
NamedXsc = namedtuple('NamedXsc', lines[1].split()[1:])
return NamedXsc(*map(float, lines[2].split()))
xsc = parse(path)
return u.Quantity([[xsc.a_x, xsc.a_y, xsc.a_z],
[xsc.b_x, xsc.b_y, xsc.b_z],
[xsc.c_x, xsc.c_y, xsc.c_z]], unit=u.angstroms) |
<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 three values (orthogonal vectors) or nine values (triclinic box). The values should be in nanometers. Parameters path : str Path to CSV file Returns ------- vectors : simtk.unit.Quantity([3, 3], unit=nanometers """ |
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:
return u.Quantity([fields[0:3],
fields[3:6],
fields[6:9]], unit=u.nanometers)
else:
raise ValueError('This type of CSV is not supported. Please '
'provide a comma-separated list of three or nine '
'floats in a single-line 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 describeNextReport(self, simulation):
"""Get information about the next report this object will generate. Parameters simulation : Simulation The Simulation to generate a report for Returns ------- tuple A five element tuple. The first element is the number of steps until the next report. The remaining elements specify whether that report will require positions, velocities, forces, and energies respectively. """ |
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 `file.txt` exists, check if `file.1.txt` also exists. Repeat until we find a non-existing version, such as `file.12.txt`. Parameters path : str Path to be checked Returns ------- newpath : str A modified version of path with a counter right before the extension. """ |
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.dcd somefile.2000.dcd """ |
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 proper HttpResponse object. If an unknown error is thrown it's encoded as a 500. All errors are then packaged up with an appropriate Content-Type and a JSON body that you can inspect in JavaScript on the client. They look like: { "message": "Error message here.", "code": 500 } Please keep in mind that raw exception messages could very well be exposed to the client if a non-AJAXError is thrown. """ |
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={
'status_code': e.code,
'request': request
}
)
except Http404 as e:
result = AJAXError(404, e.__str__()).get_response()
except Exception as e:
import sys
exc_info = sys.exc_info()
type, message, trace = exc_info
if settings.DEBUG:
import traceback
tb = [{'file': l[0], 'line': l[1], 'in': l[2], 'code': l[3]} for
l in traceback.extract_tb(trace)]
result = AJAXError(500, message, traceback=tb).get_response()
else:
result = AJAXError(500, "Internal server error.").get_response()
request = args[0]
logger.error('Internal Server Error: %s' % request.path,
exc_info=exc_info,
extra={
'status_code': 500,
'request': request
}
)
result['Content-Type'] = 'application/json'
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 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 endpoint depending on what it finds. It first attempts to load ``model`` as if it were an ad-hoc endpoint. Alternatively, it will attempt to see if there is a ``ModelEndpoint`` for the given ``model``. """ |
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.'))
if hasattr(module, model):
# This is an ad-hoc endpoint
endpoint = getattr(module, model)
else:
# This is a model endpoint
method = kwargs.get('method', 'create').lower()
try:
del kwargs['method']
except:
pass
try:
model_endpoint = ajax.endpoint.load(model, application, method,
**kwargs)
if not model_endpoint.authenticate(request, application, method):
raise AJAXError(403, _('User is not authorized.'))
endpoint = getattr(model_endpoint, method, False)
if not endpoint:
raise AJAXError(404, _('Invalid method.'))
except NotRegistered:
raise AJAXError(500, _('Invalid model.'))
data = endpoint(request)
if isinstance(data, HttpResponse):
return data
if isinstance(data, EnvelopedResponse):
envelope = data.metadata
payload = data.data
else:
envelope = {}
payload = data
envelope.update({
'success': True,
'data': payload,
})
return HttpResponse(json.dumps(envelope, cls=DjangoJSONEncoder,
separators=(',', ':'))) |
<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} //all params are optional $.post("/ajax/{app}/{model}/list.json"),params) """ |
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 = request.POST.get("current_page", 1)
if not self.can_list(request.user):
raise AJAXError(403, _("Access to this endpoint is forbidden"))
objects = self.get_queryset(request)
paginator = Paginator(objects, items_per_page)
try:
page = paginator.page(current_page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
page = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), return empty list.
page = EmptyPageResult()
data = [encoder.encode(record) for record in page.object_list]
return EnvelopedResponse(data=data, metadata={'total': paginator.count}) |
<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 handles instances of ``ForeignKey`` and will convert those to the appropriate object instances from the database. In other words, it will see that user is a ``ForeignKey`` to Django's ``User`` class, assume the value is an appropriate pk, and load up that record. """ |
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_value(val)
if isinstance(field_obj, models.ForeignKey):
if field_obj.null and not val:
clean_value = None
else:
clean_value = field_obj.rel.to.objects.get(pk=val)
else:
clean_value = field_obj.to_python(val)
data[smart_str(field)] = clean_value
return 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_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, including anonymous users. All other methods minimally require that the user is already logged in. Most likely you will want to lock down who can edit and delete various models. To do this, just override this method in your child class. """ |
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/developers/docs/references/content-management-api/#/reference/content-types :return: :class:`EnvironmentContentTypesProxy <contentful_management.space_content_types_proxy.EnvironmentContentTypesProxy>` object. :rtype: contentful.space_content_types_proxy.EnvironmentContentTypesProxy Usage: <EnvironmentContentTypesProxy space_id="cfexampleapi" environment_id="master"> """ |
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/#/reference/entries :return: :class:`EnvironmentEntriesProxy <contentful_management.environment_entries_proxy.EnvironmentEntriesProxy>` object. :rtype: contentful.environment_entries_proxy.EnvironmentEntriesProxy Usage: <EnvironmentEntriesProxy space_id="cfexampleapi" environment_id="master"> """ |
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/#/reference/assets :return: :class:`EnvironmentAssetsProxy <contentful_management.environment_assets_proxy.EnvironmentAssetsProxy>` object. :rtype: contentful.environment_assets_proxy.EnvironmentAssetsProxy Usage: <EnvironmentAssetsProxy space_id="cfexampleapi" environment_id="master"> """ |
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/#/reference/locales :return: :class:`EnvironmentLocalesProxy <contentful_management.environment_locales_proxy.EnvironmentLocalesProxy>` object. :rtype: contentful.environment_locales_proxy.EnvironmentLocalesProxy Usage: <EnvironmentLocalesProxy space_id="cfexampleapi" environment_id="master"> """ |
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-management-api/#/reference/ui-extensions :return: :class:`EnvironmentUIExtensionsProxy <contentful_management.ui_extensions_proxy.EnvironmentUIExtensionsProxy>` object. :rtype: contentful.ui_extensions_proxy.EnvironmentUIExtensionsProxy Usage: <EnvironmentUIExtensionsProxy space_id="cfexampleapi" environment_id="master"> """ |
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 = "{0}/{1}".format(url, resource_id)
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 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),
headers=headers
)
self._update_from_resource(result)
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 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)
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 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',
'first_published_at', 'published_at', 'expires_at']:
v = v.isoformat()
result['sys'][camel_case(k)] = v
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 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._serialize_value(v)
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 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()
)
return self.reload() |
<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._update_headers()
)
return self.reload() |
<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)
else:
return proxy_method(space_id).find(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 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-management-api/#/reference/assets/asset-processing """ |
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
),
locale
),
{},
headers=self._update_headers()
)
return self.reload() |
<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,
headers={
'x-contentful-enable-alpha-feature': 'usage-insights'
}
) |
<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(
space_id,
resource_id=resource_id,
environment_id=environment_id,
**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_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/developers/docs/references/content-management-api/#/reference/editor-interface :return: :class:`ContentTypeEditorInterfacesProxy <contentful_management.content_type_editor_interfaces_proxy.ContentTypeEditorInterfacesProxy>` object. :rtype: contentful.content_type_editor_interfaces_proxy.ContentTypeEditorInterfacesProxy Usage: <ContentTypeEditorInterfacesProxy space_id="cfexampleapi" environment_id="master" content_type_id="cat"> """ |
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/references/content-management-api/#/reference/snapshots/content-type-snapshots-collection :return: :class:`ContentTypeSnapshotsProxy <contentful_management.content_type_snapshots_proxy.ContentTypeSnapshotsProxy>` object. :rtype: contentful.content_type_snapshots_proxy.ContentTypeSnapshotsProxy Usage: <ContentTypeSnapshotsProxy space_id="cfexampleapi" environment_id="master" content_type_id="cat"> """ |
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']
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.