text stringlengths 81 112k |
|---|
Compiles a template from the given string.
This is one of the required methods of Django template engines.
def from_string(self, template_code):
'''
Compiles a template from the given string.
This is one of the required methods of Django template engines.
'''
dmp = apps.... |
Retrieves a template object from the pattern "app_name/template.html".
This is one of the required methods of Django template engines.
Because DMP templates are always app-specific (Django only searches
a global set of directories), the template_name MUST be in the format:
"app_name/tem... |
Returns a template loader object for the given app name in the given subdir.
For example, get_template_loader('homepage', 'styles') will return
a loader for the styles/ directory in the homepage app.
The app parameter can be either an app name or an AppConfig instance.
The subdir parame... |
Returns a template loader object for the given directory path.
For example, get_template_loader('/var/mytemplates/') will return
a loader for that specific directory.
Normally, you should not have to call this method. Django automatically
adds request.dmp.render() and request.dmp.rende... |
Triggered by the @converter_function decorator
def _register_converter(cls, conv_func, conv_type):
'''Triggered by the @converter_function decorator'''
cls.converters.append(ConverterFunctionInfo(conv_func, conv_type, len(cls.converters)))
cls._sort_converters() |
Sorts the converter functions
def _sort_converters(cls, app_ready=False):
'''Sorts the converter functions'''
# app_ready is True when called from DMP's AppConfig.ready()
# we can't sort before then because models aren't ready
cls._sorting_enabled = cls._sorting_enabled or app_ready
... |
Iterates the urlparams and converts them according to the
type hints in the current view function. This is the primary
function of the class.
def convert_parameters(self, request, *args, **kwargs):
'''
Iterates the urlparams and converts them according to the
type hints in the ... |
Converts a parameter value in the view function call.
value: value from request.dmp.urlparams to convert
The value will always be a string, even if empty '' (never None).
parameter: an instance of django_mako_plus.ViewParameter that holds this parameter's
... |
Creates an entry file for the given script map
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 imp... |
Maps templates in this app to their scripts. This function deep searches
app/templates/* for the templates of this app. Returns the following
dictionary with absolute paths:
{
( 'appname', 'template1' ): [ '/abs/path/to/scripts/template1.js', '/abs/path/to/scripts/supertemplate1.j... |
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.
def template_scripts(self, config, template_name):
'''
Returns ... |
Returns the redirect response for this exception.
def get_response(self, request, *args, **kwargs):
'''Returns the redirect response for this exception.'''
# normal process
response = HttpResponseRedirect(self.redirect_to)
response[REDIRECT_HEADER_KEY] = self.redirect_to
return ... |
Returns the redirect response for this exception.
def get_response(self, request):
'''Returns the redirect response for this exception.'''
# the redirect key is already placed in the response by HttpResponseJavascriptRedirect
return HttpResponseJavascriptRedirect(self.redirect_to, *self.args, *... |
Convenience method that calls get_template_loader() on the DMP
template engine instance.
def get_template_loader(app, subdir='templates'):
'''
Convenience method that calls get_template_loader() on the DMP
template engine instance.
'''
dmp = apps.get_app_config('django_mako_plus')
return dm... |
Convenience method that directly renders a template, given the app and template names.
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(ap... |
Convenience method that calls get_template_loader_for_path() on the DMP
template engine instance.
def get_template_loader_for_path(path, use_cache=True):
'''
Convenience method that calls get_template_loader_for_path() on the DMP
template engine instance.
'''
dmp = apps.get_app_config('django_m... |
Convenience method that retrieves a template given a direct path to it.
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)
re... |
Convenience method that directly renders a template, given a direct path to it.
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)... |
Returns the fully-qualified name of the given object
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.__q... |
Imports a fully-qualified name from a module:
cls = import_qualified('homepage.views.index.MyForm')
Raises an ImportError if it can't be ipmorted.
def import_qualified(name):
'''
Imports a fully-qualified name from a module:
cls = import_qualified('homepage.views.index.MyForm')
Rais... |
Returns the HTML for the given provider group (or all groups if None)
def links(tself, group=None):
'''Returns the HTML for the given provider group (or all groups if None)'''
pr = ProviderRun(tself, group)
pr.run()
return mark_safe(pr.getvalue()) |
Returns the HTML for the given provider group, using an app and template name.
This method should not normally be used (use links() instead). The use of
this method is when provider need to be called from regular python code instead
of from within a rendering template environment.
def template_links(reque... |
Returns the HTML for the given provider group, using a template object.
This method should not normally be used (use links() instead). The use of
this method is when provider need to be called from regular python code instead
of from within a rendering template environment.
def template_obj_links(request,... |
Called when 'link' is not defined in the settings
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.se... |
Called when 'filepath' is not defined in the settings
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',
) |
Mako tag to include a Django template withing the current DMP (Mako) template.
Since this is a Django template, it is search for using the Django search
algorithm (instead of the DMP app-based concept).
See https://docs.djangoproject.com/en/2.1/topics/templates/.
The current context is sent to the incl... |
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.
def _toggle_autoescape(context, escape_on=True):
'''
Internal method to toggle autoescaping on or off. This function
needs access to the caller,... |
Returns a relative path, but only if it doesn't start with a non-pretty parent directory ".."
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('..'):
... |
Returns True if the given function is decorated with @view_function
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 |
Initializes the providers (called from dmp app ready())
def initialize_providers(cls):
'''Initializes the providers (called from dmp app ready())'''
dmp = apps.get_app_config('django_mako_plus')
# regular content providers
cls.CONTENT_PROVIDERS = []
for provider_settings in dmp.... |
Performs the run through the templates and their providers
def run(self):
'''Performs the run through the templates and their providers'''
for tpl in self.templates:
for provider in tpl.providers:
provider.provide() |
Provider instances use this to write to the buffer
def write(self, content):
'''Provider instances use this to write to the buffer'''
self.buffer.write(content)
if settings.DEBUG:
self.buffer.write('\n') |
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.
def prepare_sort_key(self):
'''
Triggered by view_function._sort_converters when our sort key should be created.
This ca... |
Returns the command to run, as a list (see subprocess module)
def build_command(self):
'''Returns the command to run, as a list (see subprocess module)'''
# if defined in settings, run the function or return the string
if self.options['command']:
return self.options['command'](self)... |
Returns True if self.sourcepath is newer than self.targetpath
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
... |
Generator that iterates the template and its ancestors.
The order is from most specialized (furthest descendant) to
most general (furthest ancestor).
obj can be either:
1. Mako Template object
2. Mako `self` object (available within a rendering template)
def template_inheritance(obj):
... |
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.
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 erro... |
Returns the name of this template (if created from a file) or "string" if not
def name(self):
'''Returns the name of this template (if created from a file) or "string" if not'''
if self.mako_template.filename:
return os.path.basename(self.mako_template.filename)
return 'string' |
Renders a template using the Mako system. This method signature conforms to
the Django template API, which specifies that template.render() returns a string.
@context A dictionary of name=value variables to send to the template page. This can be a real dictionary
or a Djang... |
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 b... |
Retrieves the given parser action object by its dest= attribute
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 |
Placing this in execute because then subclass handle() don't have to call super
def execute(self, *args, **options):
'''Placing this in execute because then subclass handle() don't have to call super'''
if options['verbose']:
options['verbosity'] = 3
if options['quiet']:
... |
Print a message to the console
def message(self, msg='', level=1, tab=0):
'''Print a message to the console'''
if self.verbosity >= level:
self.stdout.write('{}{}'.format(' ' * tab, msg)) |
Encodes a UID to an 11-length string, encoded using base58 url-safe alphabet
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('Invali... |
Decodes a UID from base58, url-safe alphabet back to int.
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 decod... |
Minifies the source text (if needed)
def minify(text, minifier):
'''Minifies the source text (if needed)'''
# there really isn't a good way to know if a file is already minified.
# our heuristic is if source is more than 50 bytes greater of dest OR
# if a hard return is found in the first 50 chars, we ... |
Returns the result score if the file matches this rule
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 == f... |
Adds rules for the command line options
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=... |
Copies the static files from one directory to another. If this command is run, we assume the user wants to overwrite any existing files.
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 exist... |
Includes a DMP (Mako) template into a normal django template.
context: automatically provided
template_name: specified as "app/template"
def_name: optional block to render within the template
Example:
{% load django_mako_plus %}
{% dmp_include "homepage/bsnav_dj.html" %}
... |
App-specific render function that renders templates in the *current app*, attached to the request for convenience
def render(self, template, context=None, def_name=None, subdir='templates', content_type=None, status=None, charset=None):
'''App-specific render function that renders templates in the *current app... |
App-specific render function that renders templates in the *current app*, attached to the request for convenience
def render_to_string(self, template, context=None, def_name=None, subdir='templates'):
'''App-specific render function that renders templates in the *current app*, attached to the request for conve... |
App-specific function to get the current app's template loader
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. ... |
Called by Django when the app is ready for use.
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('BACKE... |
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.
def register_app(self, app=None):
'''
Registers an app as a "DMP-enabled" app. Normally, DMP does this
automatically when in... |
Returns true if the given app/app name is registered with DMP
def is_registered_app(self, app):
'''Returns true if the given app/app name is registered with DMP'''
if app is None:
return False
if isinstance(app, AppConfig):
app = app.name
return app in self.regis... |
Returns the element at idx, or default if idx is beyond the length of the list
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(... |
Converts to int or float:
'', '-', None convert to parameter default
Anything else uses int() or float() constructor
def convert_int(value, parameter):
'''
Converts to int or float:
'', '-', None convert to parameter default
Anything else uses int() or float() constructor
''... |
Converts to int or float:
'', '-', None convert to parameter default
Anything else uses int() or float() constructor
def convert_float(value, parameter):
'''
Converts to int or float:
'', '-', None convert to parameter default
Anything else uses int() or float() constructor
... |
Converts to decimal.Decimal:
'', '-', None convert to parameter default
Anything else uses Decimal constructor
def convert_decimal(value, parameter):
'''
Converts to decimal.Decimal:
'', '-', None convert to parameter default
Anything else uses Decimal constructor
'''
va... |
Converts to boolean (only the first char of the value is used):
'', '-', None convert to parameter default
'f', 'F', '0', False always convert to False
Anything else converts to True.
def convert_boolean(value, parameter, default=False):
'''
Converts to boolean (only the first char of t... |
Converts to datetime.datetime:
'', '-', None convert to parameter default
The first matching format in settings.DATETIME_INPUT_FORMATS converts to datetime
def convert_datetime(value, parameter):
'''
Converts to datetime.datetime:
'', '-', None convert to parameter default
The f... |
Converts to datetime.date:
'', '-', None convert to parameter default
The first matching format in settings.DATE_INPUT_FORMATS converts to datetime
def convert_date(value, parameter):
'''
Converts to datetime.date:
'', '-', None convert to parameter default
The first matching fo... |
Converts to a Model object.
'', '-', '0', None convert to parameter default
Anything else is assumed an object id and sent to `.get(id=value)`.
def convert_id_to_model(value, parameter):
'''
Converts to a Model object.
'', '-', '0', None convert to parameter default
Anything els... |
Returns the default if the value is "empty"
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:
... |
Decorator that denotes a function as a url parameter converter.
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 ... |
Run all the stages in protocol
Parameters
----------
handler : SystemHandler
Container of initial conditions of simulation
cfg : dict
Imported YAML file.
def protocol(handler, cfg):
"""
Run all the stages in protocol
Parameters
----------
handler : SystemHandler
... |
Launch MD simulation, which may consist of:
1. Optional minimization
2. Actual MD simulation, with n steps.
This method also handles reporters.
Returns
-------
positions, velocities : unit.Quantity([natoms, 3])
Position, velocity of each atom in the system
... |
Minimize energy of the system until meeting `tolerance` or
performing `max_iterations`.
def minimize(self, tolerance=None, max_iterations=None):
"""
Minimize energy of the system until meeting `tolerance` or
performing `max_iterations`.
"""
if tolerance is None:
... |
Advance simulation n steps
def simulate(self, steps=None):
"""
Advance simulation n steps
"""
if steps is None:
steps = self.steps
self.simulation.step(steps) |
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
def restraint_force(self, indices=None, strength=5.0):... |
Parameters
----------
atoms : tuple of tuple of int or str
Pair of atom indices to be restrained, with shape (n, 2),
like ((a1, a2), (a3, a4)). Items can be str compatible with MDTraj DSL.
distances : tuple of float
Equilibrium distances for each pair
... |
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.
def subset(self, selector):
"""
Returns a list of atom indices corresponding to a MDTraj DSL
query. Also will accept list of numbers, ... |
Handle Ctrl+C and accidental exceptions and attempt to save
the current state of the simulation
def handle_exceptions(self, verbose=True):
"""
Handle Ctrl+C and accidental exceptions and attempt to save
the current state of the simulation
"""
try:
yield
... |
Creates an emergency report run, .state included
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.usesPeriodicBoundaryCondition... |
Get, parse and prepare input file.
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,
... |
Load all files into single object.
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)
... |
Retrieve and delete (pop) system options from input configuration.
def prepare_system_options(cfg, defaults=None):
"""
Retrieve and delete (pop) system options from input configuration.
"""
d = {} if defaults is None else defaults.copy()
if 'nonbondedMethod' in cfg:
d['nonbondedMethod'] = w... |
Given a list of filenames, check which ones are `frcmods`. If so,
convert them to ffxml. Else, just return them.
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 force... |
Given an OpenMM xml file containing the state of the simulation,
generate a PDB snapshot for easy visualization.
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 = Resta... |
Extract a single frame structure from a trajectory.
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(ba... |
Include file referenced at node.
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(file... |
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
-----... |
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... |
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 : Syst... |
Loads a topology from a Desmond DMS file located at `path`.
Arguments
---------
path : str
Path to a Desmond DMS file
def from_desmond(cls, path, **kwargs):
"""
Loads a topology from a Desmond DMS file located at `path`.
Arguments
---------
... |
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
fo... |
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
def from_parmed(cls, path, *args, **kwargs):
"""
Try to load a file automatically with ... |
Loads pickled topology. Careful with Python versions though!
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':
... |
Create an OpenMM system for every supported topology file with given system options
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 ... |
Outputs a PDB file with the current contents of the system
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 fil... |
Returns u.Quantity with box vectors from XSC file
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
... |
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
... |
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
... |
Generate a report.
Parameters
----------
simulation : Simulation
The Simulation to generate a report for
state : State
The current state of the simulation
def report(self, simulation, state):
"""Generate a report.
Parameters
----------
... |
Generate a report.
Parameters
----------
simulation : Simulation
The Simulation to generate a report for
state : State
The current state of the simulation
def report(self, simulation, state):
"""Generate a report.
Parameters
----------
... |
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 chec... |
Make sure object `obj` is of type `types`. Else, raise TypeError.
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)) |
Check if file exists with argparse
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 |
Sort files taking into account potentially absent suffixes like
somefile.dcd
somefile.1000.dcd
somefile.2000.dcd
To be used with sorted(..., key=callable).
def sort_key_for_numeric_suffixes(path, sep='.', suffix_index=-2):
"""
Sort files taking into account potentially absent suffi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.