_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q257700 | ContentExtractor.get_siblings_content | validation | def get_siblings_content(self, current_sibling, baselinescore_siblings_para):
"""
adds any siblings that may have a decent score to this node
"""
if current_sibling.tag == 'p' and self.parser.getText(current_sibling):
tmp = current_sibling
if tmp.tail:
... | python | {
"resource": ""
} |
q257701 | ContentExtractor.is_highlink_density | validation | def is_highlink_density(self, element):
"""
checks the density of links within a node,
is there not much text and most of it contains linky shit?
if so it's no good
"""
links = self.parser.getElementsByTag(element, tag='a')
if not links:
return False
... | python | {
"resource": ""
} |
q257702 | ContentExtractor.nodes_to_check | validation | def nodes_to_check(self, docs):
"""\
returns a list of nodes we want to search
on like paragraphs and tables
"""
nodes_to_check = []
for doc in docs:
for tag in ['p', 'pre', 'td']:
items = self.parser.getElementsByTag(doc, tag=tag)
... | python | {
"resource": ""
} |
q257703 | ContentExtractor.post_cleanup | validation | def post_cleanup(self):
"""\
remove any divs that looks like non-content,
clusters of links, or paras with no gusto
"""
parse_tags = ['p']
if self.config.parse_lists:
parse_tags.extend(['ul', 'ol'])
if self.config.parse_headers:
parse_tags.... | python | {
"resource": ""
} |
q257704 | TitleExtractor.get_title | validation | def get_title(self):
"""\
Fetch the article title and analyze it
"""
title = ''
# rely on opengraph in case we have the data
if "title" in list(self.article.opengraph.keys()):
return self.clean_title(self.article.opengraph['title'])
elif self.article.... | python | {
"resource": ""
} |
q257705 | MetasExtractor.get_canonical_link | validation | def get_canonical_link(self):
"""
if the article has meta canonical link set in the url
"""
if self.article.final_url:
kwargs = {'tag': 'link', 'attr': 'rel', 'value': 'canonical'}
meta = self.parser.getElementsByTag(self.article.doc, **kwargs)
if meta... | python | {
"resource": ""
} |
q257706 | Goose.close | validation | def close(self):
''' Close the network connection and perform any other required cleanup
Note:
Auto closed when using goose as a context manager or when garbage collected '''
if self.fetcher is not None:
self.shutdown_network()
self.finalizer.atexit = Fal... | python | {
"resource": ""
} |
q257707 | Goose.extract | validation | def extract(self, url=None, raw_html=None):
''' Extract the most likely article content from the html page
Args:
url (str): URL to pull and parse
raw_html (str): String representation of the HTML page
Returns:
Article: Representation of th... | python | {
"resource": ""
} |
q257708 | Goose.__crawl | validation | def __crawl(self, crawl_candidate):
''' wrap the crawling functionality '''
def crawler_wrapper(parser, parsers_lst, crawl_candidate):
try:
crawler = Crawler(self.config, self.fetcher)
article = crawler.crawl(crawl_candidate)
except (UnicodeDecodeE... | python | {
"resource": ""
} |
q257709 | smart_unicode | validation | def smart_unicode(string, encoding='utf-8', strings_only=False, errors='strict'):
"""
Returns a unicode object representing 's'. Treats bytestrings using the
'encoding' codec.
If strings_only is True, don't convert (some) non-string-like objects.
"""
# if isinstance(s, Promise):
# # The... | python | {
"resource": ""
} |
q257710 | force_unicode | validation | def force_unicode(string, encoding='utf-8', strings_only=False, errors='strict'):
"""
Similar to smart_unicode, except that lazy instances are resolved to
strings, rather than kept as lazy objects.
If strings_only is True, don't convert (some) non-string-like objects.
"""
# Handle the common ca... | python | {
"resource": ""
} |
q257711 | smart_str | validation | def smart_str(string, encoding='utf-8', strings_only=False, errors='strict'):
"""
Returns a bytestring version of 's', encoded as specified in 'encoding'.
If strings_only is True, don't convert (some) non-string-like objects.
"""
if strings_only and isinstance(string, (type(None), int)):
re... | python | {
"resource": ""
} |
q257712 | QuillAdmin.get_urls | validation | def get_urls(self):
"""Add URLs needed to handle image uploads."""
urls = patterns(
'',
url(r'^upload/$', self.admin_site.admin_view(self.handle_upload), name='quill-file-upload'),
)
return urls + super(QuillAdmin, self).get_urls() | python | {
"resource": ""
} |
q257713 | QuillAdmin.handle_upload | validation | def handle_upload(self, request):
"""Handle file uploads from WYSIWYG."""
if request.method != 'POST':
raise Http404
if request.is_ajax():
try:
filename = request.GET['quillUploadFile']
data = request
is_raw = True
... | python | {
"resource": ""
} |
q257714 | QuillEditorWidget.render | validation | def render(self, name, value, attrs={}):
"""Render the Quill WYSIWYG."""
if value is None:
value = ''
final_attrs = self.build_attrs(attrs, name=name)
quill_app = apps.get_app_config('quill')
quill_config = getattr(quill_app, self.config)
return mark_safe(ren... | python | {
"resource": ""
} |
q257715 | RichTextField.formfield | validation | def formfield(self, **kwargs):
"""Get the form for field."""
defaults = {
'form_class': RichTextFormField,
'config': self.config,
}
defaults.update(kwargs)
return super(RichTextField, self).formfield(**defaults) | python | {
"resource": ""
} |
q257716 | render_toolbar | validation | def render_toolbar(context, config):
"""Render the toolbar for the given config."""
quill_config = getattr(quill_app, config)
t = template.loader.get_template(quill_config['toolbar_template'])
return t.render(context) | python | {
"resource": ""
} |
q257717 | get_meta_image_url | validation | def get_meta_image_url(request, image):
"""
Resize an image for metadata tags, and return an absolute URL to it.
"""
rendition = image.get_rendition(filter='original')
return request.build_absolute_uri(rendition.url) | python | {
"resource": ""
} |
q257718 | check_mdrun_success | validation | def check_mdrun_success(logfile):
"""Check if ``mdrun`` finished successfully.
Analyses the output from ``mdrun`` in *logfile*. Right now we are
simply looking for the line "Finished mdrun on node" in the last 1kb of
the file. (The file must be seeakable.)
:Arguments:
*logfile* : filename
... | python | {
"resource": ""
} |
q257719 | get_double_or_single_prec_mdrun | validation | def get_double_or_single_prec_mdrun():
"""Return double precision ``mdrun`` or fall back to single precision.
This convenience function tries :func:`gromacs.mdrun_d` first and
if it cannot run it, falls back to :func:`gromacs.mdrun` (without
further checking).
.. versionadded:: 0.5.1
"""
t... | python | {
"resource": ""
} |
q257720 | MDrunner.commandline | validation | def commandline(self, **mpiargs):
"""Returns simple command line to invoke mdrun.
If :attr:`mpiexec` is set then :meth:`mpicommand` provides the mpi
launcher command that prefixes the actual ``mdrun`` invocation:
:attr:`mpiexec` [*mpiargs*] :attr:`mdrun` [*mdrun-args*]
The... | python | {
"resource": ""
} |
q257721 | MDrunner.mpicommand | validation | def mpicommand(self, *args, **kwargs):
"""Return a list of the mpi command portion of the commandline.
Only allows primitive mpi at the moment:
*mpiexec* -n *ncores* *mdrun* *mdrun-args*
(This is a primitive example for OpenMP. Override it for more
complicated cases.)
... | python | {
"resource": ""
} |
q257722 | MDrunnerMpich2Smpd.prehook | validation | def prehook(self, **kwargs):
"""Launch local smpd."""
cmd = ['smpd', '-s']
logger.info("Starting smpd: "+" ".join(cmd))
rc = subprocess.call(cmd)
return rc | python | {
"resource": ""
} |
q257723 | glob_parts | validation | def glob_parts(prefix, ext):
"""Find files from a continuation run"""
if ext.startswith('.'):
ext = ext[1:]
files = glob.glob(prefix+'.'+ext) + glob.glob(prefix+'.part[0-9][0-9][0-9][0-9].'+ext)
files.sort() # at least some rough sorting...
return files | python | {
"resource": ""
} |
q257724 | grompp_qtot | validation | def grompp_qtot(*args, **kwargs):
"""Run ``gromacs.grompp`` and return the total charge of the system.
:Arguments:
The arguments are the ones one would pass to :func:`gromacs.grompp`.
:Returns:
The total charge as reported
Some things to keep in mind:
* The stdout output of grompp ... | python | {
"resource": ""
} |
q257725 | _mdp_include_string | validation | def _mdp_include_string(dirs):
"""Generate a string that can be added to a mdp 'include = ' line."""
include_paths = [os.path.expanduser(p) for p in dirs]
return ' -I'.join([''] + include_paths) | python | {
"resource": ""
} |
q257726 | create_portable_topology | validation | def create_portable_topology(topol, struct, **kwargs):
"""Create a processed topology.
The processed (or portable) topology file does not contain any
``#include`` statements and hence can be easily copied around. It
also makes it possible to re-grompp without having any special itp
files available.... | python | {
"resource": ""
} |
q257727 | edit_txt | validation | def edit_txt(filename, substitutions, newname=None):
"""Primitive text file stream editor.
This function can be used to edit free-form text files such as the
topology file. By default it does an **in-place edit** of
*filename*. If *newname* is supplied then the edited
file is written to *newname*.
... | python | {
"resource": ""
} |
q257728 | make_ndx_captured | validation | def make_ndx_captured(**kwargs):
"""make_ndx that captures all output
Standard :func:`~gromacs.make_ndx` command with the input and
output pre-set in such a way that it can be conveniently used for
:func:`parse_ndxlist`.
Example::
ndx_groups = parse_ndxlist(make_ndx_captured(n=ndx)[0])
... | python | {
"resource": ""
} |
q257729 | parse_groups | validation | def parse_groups(output):
"""Parse ``make_ndx`` output and return groups as a list of dicts."""
groups = []
for line in output.split('\n'):
m = NDXGROUP.match(line)
if m:
d = m.groupdict()
groups.append({'name': d['GROUPNAME'],
'nr': int(d['... | python | {
"resource": ""
} |
q257730 | Frames.delete_frames | validation | def delete_frames(self):
"""Delete all frames."""
for frame in glob.glob(self.frameglob):
os.unlink(frame) | python | {
"resource": ""
} |
q257731 | IndexBuilder.gmx_resid | validation | def gmx_resid(self, resid):
"""Returns resid in the Gromacs index by transforming with offset."""
try:
gmx_resid = int(self.offset[resid])
except (TypeError, IndexError):
gmx_resid = resid + self.offset
except KeyError:
raise KeyError("offset must be a... | python | {
"resource": ""
} |
q257732 | IndexBuilder.combine | validation | def combine(self, name_all=None, out_ndx=None, operation='|', defaultgroups=False):
"""Combine individual groups into a single one and write output.
:Keywords:
name_all : string
Name of the combined group, ``None`` generates a name. [``None``]
out_ndx : filename
... | python | {
"resource": ""
} |
q257733 | IndexBuilder.cat | validation | def cat(self, out_ndx=None):
"""Concatenate input index files.
Generate a new index file that contains the default Gromacs index
groups (if a structure file was defined) and all index groups from the
input index files.
:Arguments:
out_ndx : filename
Nam... | python | {
"resource": ""
} |
q257734 | IndexBuilder._process_command | validation | def _process_command(self, command, name=None):
"""Process ``make_ndx`` command and return name and temp index file."""
self._command_counter += 1
if name is None:
name = "CMD{0:03d}".format(self._command_counter)
# Need to build it with two make_ndx calls because I cannot... | python | {
"resource": ""
} |
q257735 | IndexBuilder._process_range | validation | def _process_range(self, selection, name=None):
"""Process a range selection.
("S234", "A300", "CA") --> selected all CA in this range
("S234", "A300") --> selected all atoms in this range
.. Note:: Ignores residue type, only cares about the resid (but still required)
... | python | {
"resource": ""
} |
q257736 | IndexBuilder._translate_residue | validation | def _translate_residue(self, selection, default_atomname='CA'):
"""Translate selection for a single res to make_ndx syntax."""
m = self.RESIDUE.match(selection)
if not m:
errmsg = "Selection {selection!r} is not valid.".format(**vars())
logger.error(errmsg)
ra... | python | {
"resource": ""
} |
q257737 | IndexBuilder.check_output | validation | def check_output(self, make_ndx_output, message=None, err=None):
"""Simple tests to flag problems with a ``make_ndx`` run."""
if message is None:
message = ""
else:
message = '\n' + message
def format(output, w=60):
hrule = "====[ GromacsError (diagnos... | python | {
"resource": ""
} |
q257738 | Transformer.outfile | validation | def outfile(self, p):
"""Path for an output file.
If :attr:`outdir` is set then the path is
``outdir/basename(p)`` else just ``p``
"""
if self.outdir is not None:
return os.path.join(self.outdir, os.path.basename(p))
else:
return p | python | {
"resource": ""
} |
q257739 | Transformer.center_fit | validation | def center_fit(self, **kwargs):
"""Write compact xtc that is fitted to the tpr reference structure.
See :func:`gromacs.cbook.trj_fitandcenter` for details and
description of *kwargs* (including *input*, *input1*, *n* and
*n1* for how to supply custom index groups). The most important on... | python | {
"resource": ""
} |
q257740 | Transformer.fit | validation | def fit(self, xy=False, **kwargs):
"""Write xtc that is fitted to the tpr reference structure.
Runs :class:`gromacs.tools.trjconv` with appropriate arguments
for fitting. The most important *kwargs* are listed
here but in most cases the defaults should work.
Note that the defau... | python | {
"resource": ""
} |
q257741 | Transformer.strip_fit | validation | def strip_fit(self, **kwargs):
"""Strip water and fit to the remaining system.
First runs :meth:`strip_water` and then :meth:`fit`; see there
for arguments.
- *strip_input* is used for :meth:`strip_water` (but is only useful in
special cases, e.g. when there is no Protein gro... | python | {
"resource": ""
} |
q257742 | create | validation | def create(logger_name, logfile='gromacs.log'):
"""Create a top level logger.
- The file logger logs everything (including DEBUG).
- The console logger only logs INFO and above.
Logging to a file and the console.
See http://docs.python.org/library/logging.html?#logging-to-multiple-destination... | python | {
"resource": ""
} |
q257743 | get_configuration | validation | def get_configuration(filename=CONFIGNAME):
"""Reads and parses the configuration file.
Default values are loaded and then replaced with the values from
``~/.gromacswrapper.cfg`` if that file exists. The global
configuration instance :data:`gromacswrapper.config.cfg` is updated
as are a number of g... | python | {
"resource": ""
} |
q257744 | setup | validation | def setup(filename=CONFIGNAME):
"""Prepare a default GromacsWrapper global environment.
1) Create the global config file.
2) Create the directories in which the user can store template and config files.
This function can be run repeatedly without harm.
"""
# setup() must be separate and ... | python | {
"resource": ""
} |
q257745 | check_setup | validation | def check_setup():
"""Check if templates directories are setup and issue a warning and help.
Set the environment variable :envvar:`GROMACSWRAPPER_SUPPRESS_SETUP_CHECK`
skip the check and make it always return ``True``
:return ``True`` if directories were found and ``False`` otherwise
.. versio... | python | {
"resource": ""
} |
q257746 | get_tool_names | validation | def get_tool_names():
""" Get tool names from all configured groups.
:return: list of tool names
"""
names = []
for group in cfg.get('Gromacs', 'groups').split():
names.extend(cfg.get('Gromacs', group).split())
return names | python | {
"resource": ""
} |
q257747 | GMXConfigParser.configuration | validation | def configuration(self):
"""Dict of variables that we make available as globals in the module.
Can be used as ::
globals().update(GMXConfigParser.configuration) # update configdir, templatesdir ...
"""
configuration = {
'configfilename': self.... | python | {
"resource": ""
} |
q257748 | GMXConfigParser.getpath | validation | def getpath(self, section, option):
"""Return option as an expanded path."""
return os.path.expanduser(os.path.expandvars(self.get(section, option))) | python | {
"resource": ""
} |
q257749 | GMXConfigParser.getLogLevel | validation | def getLogLevel(self, section, option):
"""Return the textual representation of logging level 'option' or the number.
Note that option is always interpreted as an UPPERCASE string
and hence integer log levels will not be recognized.
.. SeeAlso: :mod:`logging` and :func:`logging... | python | {
"resource": ""
} |
q257750 | Collection._canonicalize | validation | def _canonicalize(self, filename):
"""Use .collection as extension unless provided"""
path, ext = os.path.splitext(filename)
if not ext:
ext = ".collection"
return path + ext | python | {
"resource": ""
} |
q257751 | scale_dihedrals | validation | def scale_dihedrals(mol, dihedrals, scale, banned_lines=None):
"""Scale dihedral angles"""
if banned_lines is None:
banned_lines = []
new_dihedrals = []
for dh in mol.dihedrals:
atypes = dh.atom1.get_atomtype(), dh.atom2.get_atomtype(), dh.atom3.get_atomt... | python | {
"resource": ""
} |
q257752 | scale_impropers | validation | def scale_impropers(mol, impropers, scale, banned_lines=None):
"""Scale improper dihedrals"""
if banned_lines is None:
banned_lines = []
new_impropers = []
for im in mol.impropers:
atypes = (im.atom1.get_atomtype(), im.atom2.get_atomtype(),
... | python | {
"resource": ""
} |
q257753 | besttype | validation | def besttype(x):
"""Convert string x to the most useful type, i.e. int, float or unicode string.
If x is a quoted string (single or double quotes) then the quotes
are stripped and the enclosed string returned.
.. Note::
Strings will be returned as Unicode strings (using :func:`to_unicode`).
... | python | {
"resource": ""
} |
q257754 | to_int64 | validation | def to_int64(a):
"""Return view of the recarray with all int32 cast to int64."""
# build new dtype and replace i4 --> i8
def promote_i4(typestr):
if typestr[1:] == 'i4':
typestr = typestr[0]+'i8'
return typestr
dtype = [(name, promote_i4(typestr)) for name,typestr in a.dtype... | python | {
"resource": ""
} |
q257755 | irecarray_to_py | validation | def irecarray_to_py(a):
"""Slow conversion of a recarray into a list of records with python types.
Get the field names from :attr:`a.dtype.names`.
:Returns: iterator so that one can handle big input arrays
"""
pytypes = [pyify(typestr) for name,typestr in a.dtype.descr]
def convert_record(r):
... | python | {
"resource": ""
} |
q257756 | XPM.col | validation | def col(self, c):
"""Parse colour specification"""
m = self.COLOUR.search(c)
if not m:
self.logger.fatal("Cannot parse colour specification %r.", c)
raise ParseError("XPM reader: Cannot parse colour specification {0!r}.".format(c))
value = m.group('value')
... | python | {
"resource": ""
} |
q257757 | Command.transform_args | validation | def transform_args(self, *args, **kwargs):
"""Transform arguments and return them as a list suitable for Popen."""
options = []
for option,value in kwargs.items():
if not option.startswith('-'):
# heuristic for turning key=val pairs into options
# (fai... | python | {
"resource": ""
} |
q257758 | Command.help | validation | def help(self, long=False):
"""Print help; same as using ``?`` in ``ipython``. long=True also gives call signature."""
print("\ncommand: {0!s}\n\n".format(self.command_name))
print(self.__doc__)
if long:
print("\ncall method: command():\n")
print(self.__call__.__d... | python | {
"resource": ""
} |
q257759 | GromacsCommand._combineargs | validation | def _combineargs(self, *args, **kwargs):
"""Add switches as 'options' with value True to the options dict."""
d = {arg: True for arg in args} # switches are kwargs with value True
d.update(kwargs)
return d | python | {
"resource": ""
} |
q257760 | GromacsCommand._build_arg_list | validation | def _build_arg_list(self, **kwargs):
"""Build list of arguments from the dict; keys must be valid gromacs flags."""
arglist = []
for flag, value in kwargs.items():
# XXX: check flag against allowed values
flag = str(flag)
if flag.startswith('_'):
... | python | {
"resource": ""
} |
q257761 | GromacsCommand.transform_args | validation | def transform_args(self,*args,**kwargs):
"""Combine arguments and turn them into gromacs tool arguments."""
newargs = self._combineargs(*args, **kwargs)
return self._build_arg_list(**newargs) | python | {
"resource": ""
} |
q257762 | GromacsCommand._get_gmx_docs | validation | def _get_gmx_docs(self):
"""Extract standard gromacs doc
Extract by running the program and chopping the header to keep from
'DESCRIPTION' onwards.
"""
if self._doc_cache is not None:
return self._doc_cache
try:
logging.disable(logging.CRITICAL)
... | python | {
"resource": ""
} |
q257763 | autoconvert | validation | def autoconvert(s):
"""Convert input to a numerical type if possible.
1. A non-string object is returned as it is
2. Try conversion to int, float, str.
"""
if type(s) is not str:
return s
for converter in int, float, str: # try them in increasing order of lenience
try:
... | python | {
"resource": ""
} |
q257764 | isstream | validation | def isstream(obj):
"""Detect if `obj` is a stream.
We consider anything a stream that has the methods
- ``close()``
and either set of the following
- ``read()``, ``readline()``, ``readlines()``
- ``write()``, ``writeline()``, ``writelines()``
:Arguments:
*obj*
stream or ... | python | {
"resource": ""
} |
q257765 | convert_aa_code | validation | def convert_aa_code(x):
"""Converts between 3-letter and 1-letter amino acid codes."""
if len(x) == 1:
return amino_acid_codes[x.upper()]
elif len(x) == 3:
return inverse_aa_codes[x.upper()]
else:
raise ValueError("Can only convert 1-letter or 3-letter amino acid codes, "
... | python | {
"resource": ""
} |
q257766 | in_dir | validation | def in_dir(directory, create=True):
"""Context manager to execute a code block in a directory.
* The directory is created if it does not exist (unless
create=False is set)
* At the end or after an exception code always returns to
the directory that was the current directory before entering
... | python | {
"resource": ""
} |
q257767 | unlink_f | validation | def unlink_f(path):
"""Unlink path but do not complain if file does not exist."""
try:
os.unlink(path)
except OSError as err:
if err.errno != errno.ENOENT:
raise | python | {
"resource": ""
} |
q257768 | remove_legend | validation | def remove_legend(ax=None):
"""Remove legend for axes or gca.
See http://osdir.com/ml/python.matplotlib.general/2005-07/msg00285.html
"""
from pylab import gca, draw
if ax is None:
ax = gca()
ax.legend_ = None
draw() | python | {
"resource": ""
} |
q257769 | FileUtils.filename | validation | def filename(self,filename=None,ext=None,set_default=False,use_my_ext=False):
"""Supply a file name for the class object.
Typical uses::
fn = filename() ---> <default_filename>
fn = filename('name.ext') ---> 'name'
fn = filename(ext='pickle') ---> <defaul... | python | {
"resource": ""
} |
q257770 | FileUtils.check_file_exists | validation | def check_file_exists(self, filename, resolve='exception', force=None):
"""If a file exists then continue with the action specified in ``resolve``.
``resolve`` must be one of
"ignore"
always return ``False``
"indicate"
return ``True`` if it exists
"w... | python | {
"resource": ""
} |
q257771 | Timedelta.strftime | validation | def strftime(self, fmt="%d:%H:%M:%S"):
"""Primitive string formatter.
The only directives understood are the following:
============ ==========================
Directive meaning
============ ==========================
%d day as integer
... | python | {
"resource": ""
} |
q257772 | start_logging | validation | def start_logging(logfile="gromacs.log"):
"""Start logging of messages to file and console.
The default logfile is named ``gromacs.log`` and messages are
logged with the tag *gromacs*.
"""
from . import log
log.create("gromacs", logfile=logfile)
logging.getLogger("gromacs").info("GromacsWra... | python | {
"resource": ""
} |
q257773 | stop_logging | validation | def stop_logging():
"""Stop logging to logfile and console."""
from . import log
logger = logging.getLogger("gromacs")
logger.info("GromacsWrapper %s STOPPED logging", get_version())
log.clear_handlers(logger) | python | {
"resource": ""
} |
q257774 | tool_factory | validation | def tool_factory(clsname, name, driver, base=GromacsCommand):
""" Factory for GromacsCommand derived types. """
clsdict = {
'command_name': name,
'driver': driver,
'__doc__': property(base._get_gmx_docs)
}
return type(clsname, (base,), clsdict) | python | {
"resource": ""
} |
q257775 | find_executables | validation | def find_executables(path):
""" Find executables in a path.
Searches executables in a directory excluding some know commands
unusable with GromacsWrapper.
:param path: dirname to search for
:return: list of executables
"""
execs = []
for exe in os.listdir(path):
fullexe = os.pa... | python | {
"resource": ""
} |
q257776 | load_v4_tools | validation | def load_v4_tools():
""" Load Gromacs 4.x tools automatically using some heuristic.
Tries to load tools (1) in configured tool groups (2) and fails back to
automatic detection from ``GMXBIN`` (3) then to a prefilled list.
Also load any extra tool configured in ``~/.gromacswrapper.cfg``
:return: ... | python | {
"resource": ""
} |
q257777 | merge_ndx | validation | def merge_ndx(*args):
""" Takes one or more index files and optionally one structure file and
returns a path for a new merged index file.
:param args: index files and zero or one structure file
:return: path for the new merged index file
"""
ndxs = []
struct = None
for fname in args:
... | python | {
"resource": ""
} |
q257778 | break_array | validation | def break_array(a, threshold=numpy.pi, other=None):
"""Create a array which masks jumps >= threshold.
Extra points are inserted between two subsequent values whose
absolute difference differs by more than threshold (default is
pi).
Other can be a secondary array which is also masked according to
... | python | {
"resource": ""
} |
q257779 | XVG.ma | validation | def ma(self):
"""Represent data as a masked array.
The array is returned with column-first indexing, i.e. for a data file with
columns X Y1 Y2 Y3 ... the array a will be a[0] = X, a[1] = Y1, ... .
inf and nan are filtered via :func:`numpy.isfinite`.
"""
a = self.array
... | python | {
"resource": ""
} |
q257780 | XVG._tcorrel | validation | def _tcorrel(self, nstep=100, **kwargs):
"""Correlation "time" of data.
The 0-th column of the data is interpreted as a time and the
decay of the data is computed from the autocorrelation
function (using FFT).
.. SeeAlso:: :func:`numkit.timeseries.tcorrel`
"""
t... | python | {
"resource": ""
} |
q257781 | XVG.set_correlparameters | validation | def set_correlparameters(self, **kwargs):
"""Set and change the parameters for calculations with correlation functions.
The parameters persist until explicitly changed.
:Keywords:
*nstep*
only process every *nstep* data point to speed up the FFT; if
le... | python | {
"resource": ""
} |
q257782 | XVG.parse | validation | def parse(self, stride=None):
"""Read and cache the file as a numpy array.
Store every *stride* line of data; if ``None`` then the class default is used.
The array is returned with column-first indexing, i.e. for a data file with
columns X Y1 Y2 Y3 ... the array a will be a[0] = X, a[1... | python | {
"resource": ""
} |
q257783 | XVG.plot | validation | def plot(self, **kwargs):
"""Plot xvg file data.
The first column of the data is always taken as the abscissa
X. Additional columns are plotted as ordinates Y1, Y2, ...
In the special case that there is only a single column then this column
is plotted against the index, i.e. (N... | python | {
"resource": ""
} |
q257784 | topology | validation | def topology(struct=None, protein='protein',
top='system.top', dirname='top',
posres="posres.itp",
ff="oplsaa", water="tip4p",
**pdb2gmx_args):
"""Build Gromacs topology files from pdb.
:Keywords:
*struct*
input structure (**required**)
... | python | {
"resource": ""
} |
q257785 | make_main_index | validation | def make_main_index(struct, selection='"Protein"', ndx='main.ndx', oldndx=None):
"""Make index file with the special groups.
This routine adds the group __main__ and the group __environment__
to the end of the index file. __main__ contains what the user
defines as the *central* and *most important* par... | python | {
"resource": ""
} |
q257786 | get_lipid_vdwradii | validation | def get_lipid_vdwradii(outdir=os.path.curdir, libdir=None):
"""Find vdwradii.dat and add special entries for lipids.
See :data:`gromacs.setup.vdw_lipid_resnames` for lipid
resnames. Add more if necessary.
"""
vdwradii_dat = os.path.join(outdir, "vdwradii.dat")
if libdir is not None:
fi... | python | {
"resource": ""
} |
q257787 | solvate | validation | def solvate(struct='top/protein.pdb', top='top/system.top',
distance=0.9, boxtype='dodecahedron',
concentration=0, cation='NA', anion='CL',
water='tip4p', solvent_name='SOL', with_membrane=False,
ndx = 'main.ndx', mainselection = '"Protein"',
dirname='solvate'... | python | {
"resource": ""
} |
q257788 | energy_minimize | validation | def energy_minimize(dirname='em', mdp=config.templates['em.mdp'],
struct='solvate/ionized.gro', top='top/system.top',
output='em.pdb', deffnm="em",
mdrunner=None, mdrun_args=None,
**kwargs):
"""Energy minimize the system.
This sets... | python | {
"resource": ""
} |
q257789 | em_schedule | validation | def em_schedule(**kwargs):
"""Run multiple energy minimizations one after each other.
:Keywords:
*integrators*
list of integrators (from 'l-bfgs', 'cg', 'steep')
[['bfgs', 'steep']]
*nsteps*
list of maximum number of steps; one for each integrator in
in t... | python | {
"resource": ""
} |
q257790 | MD_restrained | validation | def MD_restrained(dirname='MD_POSRES', **kwargs):
"""Set up MD with position restraints.
Additional itp files should be in the same directory as the top file.
Many of the keyword arguments below already have sensible values. Note that
setting *mainselection* = ``None`` will disable many of the automat... | python | {
"resource": ""
} |
q257791 | MD | validation | def MD(dirname='MD', **kwargs):
"""Set up equilibrium MD.
Additional itp files should be in the same directory as the top file.
Many of the keyword arguments below already have sensible values. Note that
setting *mainselection* = ``None`` will disable many of the automated
choices and is often rec... | python | {
"resource": ""
} |
q257792 | generate_submit_scripts | validation | def generate_submit_scripts(templates, prefix=None, deffnm='md', jobname='MD', budget=None,
mdrun_opts=None, walltime=1.0, jobarray_string=None, startdir=None,
npme=None, **kwargs):
"""Write scripts for queuing systems.
This sets up queuing system run sc... | python | {
"resource": ""
} |
q257793 | generate_submit_array | validation | def generate_submit_array(templates, directories, **kwargs):
"""Generate a array job.
For each ``work_dir`` in *directories*, the array job will
1. cd into ``work_dir``
2. run the job as detailed in the template
It will use all the queuing system directives found in the
template. If more comp... | python | {
"resource": ""
} |
q257794 | QueuingSystem.isMine | validation | def isMine(self, scriptname):
"""Primitive queuing system detection; only looks at suffix at the moment."""
suffix = os.path.splitext(scriptname)[1].lower()
if suffix.startswith('.'):
suffix = suffix[1:]
return self.suffix == suffix | python | {
"resource": ""
} |
q257795 | Molecule.anumb_to_atom | validation | def anumb_to_atom(self, anumb):
'''Returns the atom object corresponding to an atom number'''
assert isinstance(anumb, int), "anumb must be integer"
if not self._anumb_to_atom: # empty dictionary
if self.atoms:
for atom in self.atoms:
self._an... | python | {
"resource": ""
} |
q257796 | total_regular_pixels_from_mask | validation | def total_regular_pixels_from_mask(mask):
"""Compute the total number of unmasked regular pixels in a masks."""
total_regular_pixels = 0
for y in range(mask.shape[0]):
for x in range(mask.shape[1]):
if not mask[y, x]:
total_regular_pixels += 1
return total_regular_... | python | {
"resource": ""
} |
q257797 | mask_circular_annular_from_shape_pixel_scale_and_radii | validation | def mask_circular_annular_from_shape_pixel_scale_and_radii(shape, pixel_scale, inner_radius_arcsec, outer_radius_arcsec,
centre=(0.0, 0.0)):
"""Compute an annular masks from an input inner and outer masks radius and regular shape."""
mask = np.full(sha... | python | {
"resource": ""
} |
q257798 | mask_blurring_from_mask_and_psf_shape | validation | def mask_blurring_from_mask_and_psf_shape(mask, psf_shape):
"""Compute a blurring masks from an input masks and psf shape.
The blurring masks corresponds to all pixels which are outside of the masks but will have a fraction of their \
light blur into the masked region due to PSF convolution."""
blurri... | python | {
"resource": ""
} |
q257799 | edge_pixels_from_mask | validation | def edge_pixels_from_mask(mask):
"""Compute a 1D array listing all edge pixel indexes in the masks. An edge pixel is a pixel which is not fully \
surrounding by False masks values i.e. it is on an edge."""
edge_pixel_total = total_edge_pixels_from_mask(mask)
edge_pixels = np.zeros(edge_pixel_total)
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.