Search is not available for this dataset
text
stringlengths
75
104k
def _add_edges(self, ast_node, trunk=None): """"Add all bonds in the SMARTS string as edges in the graph.""" atom_indices = self._atom_indices for atom in ast_node.tail: if atom.head == 'atom': atom_idx = atom_indices[id(atom)] if atom.is_first_kid and...
def _add_label_edges(self): """Add edges between all atoms with the same atom_label in rings.""" labels = self.ast.select('atom_label') if not labels: return # We need each individual label and atoms with multiple ring labels # would yield e.g. the string '12' so spl...
def find_matches(self, topology): """Return sets of atoms that match this SMARTS pattern in a topology. Notes: ------ When this function gets used in atomtyper.py, we actively modify the white- and blacklists of the atoms in `topology` after finding a match. This means t...
def candidate_pairs_iter(self): """Iterator over candidate pairs of nodes in G1 and G2.""" # All computations are done using the current state! G2_nodes = self.G2_nodes # First we compute the inout-terminal sets. T1_inout = set(self.inout_1.keys()) - set(self.core_1.keys()) ...
def find_atomtypes(topology, forcefield, max_iter=10): """Determine atomtypes for all atoms. Parameters ---------- topology : simtk.openmm.app.Topology The topology that we are trying to atomtype. forcefield : foyer.Forcefield The forcefield object. max_iter : int, optional, def...
def _load_rules(forcefield): """Load atomtyping rules from a forcefield into SMARTSGraphs. """ rules = dict() for rule_name, smarts in forcefield.atomTypeDefinitions.items(): overrides = forcefield.atomTypeOverrides.get(rule_name) if overrides is not None: overrides = set(overrid...
def _iterate_rules(rules, topology, max_iter): """Iteratively run all the rules until the white- and backlists converge. Parameters ---------- rules : dict A dictionary mapping rule names (typically atomtype names) to SMARTSGraphs that evaluate those rules. topology : simtk.openmm.a...
def _resolve_atomtypes(topology): """Determine the final atomtypes from the white- and blacklists. """ for atom in topology.atoms(): atomtype = [rule_name for rule_name in atom.whitelist - atom.blacklist] if len(atomtype) == 1: atom.id = atomtype[0] elif len(atomtype) > 1: ...
def generate_topology(non_omm_topology, non_element_types=None, residues=None): """Create an OpenMM Topology from another supported topology structure.""" if non_element_types is None: non_element_types = set() if isinstance(non_omm_topology, pmd.Structure): return _topology_from_pa...
def _topology_from_parmed(structure, non_element_types): """Convert a ParmEd Structure to an OpenMM Topology.""" topology = app.Topology() residues = dict() for pmd_residue in structure.residues: chain = topology.addChain() omm_residue = topology.addResidue(pmd_residue.name, chain) ...
def _topology_from_residue(res): """Converts a openmm.app.Topology.Residue to openmm.app.Topology. Parameters ---------- res : openmm.app.Topology.Residue An individual residue in an openmm.app.Topology Returns ------- topology : openmm.app.Topology The generated topology ...
def _check_independent_residues(topology): """Check to see if residues will constitute independent graphs.""" for res in topology.residues(): atoms_in_residue = set([atom for atom in res.atoms()]) bond_partners_in_residue = [item for sublist in [atom.bond_partners for atom in res.atoms()] for it...
def _update_atomtypes(unatomtyped_topology, res_name, prototype): """Update atomtypes in residues in a topology using a prototype topology. Atomtypes are updated when residues in each topology have matching names. Parameters ---------- unatomtyped_topology : openmm.app.Topology Topology la...
def registerAtomType(self, parameters): """Register a new atom type. """ name = parameters['name'] if name in self._atomTypes: raise ValueError('Found multiple definitions for atom type: ' + name) atom_class = parameters['class'] mass = _convertParameterToNumber(param...
def apply(self, topology, references_file=None, use_residue_map=True, assert_bond_params=True, assert_angle_params=True, assert_dihedral_params=True, assert_improper_params=False, *args, **kwargs): """Apply the force field to a molecular structure Parameters ...
def run_atomtyping(self, topology, use_residue_map=True): """Atomtype the topology Parameters ---------- topology : openmm.app.Topology Molecular structure to find atom types of use_residue_map : boolean, optional, default=True Store atomtyped topologies ...
def createSystem(self, topology, nonbondedMethod=NoCutoff, nonbondedCutoff=1.0 * u.nanometer, constraints=None, rigidWater=True, removeCMMotion=True, hydrogenMass=None, **args): """Construct an OpenMM System representing a Topology with this force f...
def run(command, encoding=None, decode=True, cwd=None): """Run a command [cmd, arg1, arg2, ...]. Returns the output (stdout + stderr). Raises CommandFailed in cases of error. """ if not encoding: encoding = locale.getpreferredencoding() try: with open(os.devnull, 'rb') as devnu...
def cd(directory): """Change the current working directory, temporarily. Use as a context manager: with cd(d): ... """ old_dir = os.getcwd() try: os.chdir(directory) yield finally: os.chdir(old_dir)
def mkdtemp(hint=''): """Create a temporary directory, then clean it up. Use as a context manager: with mkdtemp('-purpose'): ... """ dirname = tempfile.mkdtemp(prefix='check-manifest-', suffix=hint) try: yield dirname finally: rmtree(dirname)
def chmod_plus(path, add_bits=stat.S_IWUSR): """Change a file's mode by adding a few bits. Like chmod +<bits> <path> in a Unix shell. """ try: os.chmod(path, stat.S_IMODE(os.stat(path).st_mode) | add_bits) except OSError: # pragma: nocover pass
def rmtree(path): """A version of rmtree that can deal with read-only files and directories. Needed because the stock shutil.rmtree() fails with an access error when there are read-only files in the directory on Windows, or when the directory itself is read-only on Unix. """ def onerror(func, p...
def copy_files(filelist, destdir): """Copy a list of files to destdir, preserving directory structure. File names should be relative to the current working directory. """ for filename in filelist: destfile = os.path.join(destdir, filename) # filename should not be absolute, but let's do...
def get_one_file_in(dirname): """Return the pathname of the one file in a directory. Raises if the directory has no files or more than one file. """ files = os.listdir(dirname) if len(files) > 1: raise Failure('More than one file exists in %s:\n%s' % (dirname, '\n'.joi...
def unicodify(filename): """Make sure filename is Unicode. Because the tarfile module on Python 2 doesn't return Unicode. """ if isinstance(filename, bytes): return filename.decode(locale.getpreferredencoding()) else: return filename
def get_archive_file_list(archive_filename): """Return the list of files in an archive. Supports .tar.gz and .zip. """ if archive_filename.endswith('.zip'): with closing(zipfile.ZipFile(archive_filename)) as zf: return add_directories(zf.namelist()) elif archive_filename.endswit...
def strip_toplevel_name(filelist): """Strip toplevel name from a file list. >>> strip_toplevel_name(['a', 'a/b', 'a/c', 'a/c/d']) ['b', 'c', 'c/d'] >>> strip_toplevel_name(['a/b', 'a/c', 'a/c/d']) ['b', 'c', 'c/d'] """ if not filelist: return filelist prefix = ...
def detect_vcs(): """Detect the version control system used for the current directory.""" location = os.path.abspath('.') while True: for vcs in Git, Mercurial, Bazaar, Subversion: if vcs.detect(location): return vcs parent = os.path.dirname(location) if p...
def normalize_name(name): """Some VCS print directory names with trailing slashes. Strip them. Easiest is to normalize the path. And encodings may trip us up too, especially when comparing lists of files. Plus maybe lowercase versus uppercase. """ name = os.path.normpath(name) name = uni...
def add_directories(names): """Git/Mercurial/zip files omit directories, let's add them back.""" res = list(names) seen = set(names) for name in names: while True: name = os.path.dirname(name) if not name or name in seen: break res.append(name)...
def read_config(): """Read configuration from file if possible.""" # XXX modifies global state, which is kind of evil config = _load_config() if config.get(CFG_IGNORE_DEFAULT_RULES[1], False): del IGNORE[:] if CFG_IGNORE[1] in config: IGNORE.extend(p for p in config[CFG_IGNORE[1]] if...
def _load_config(): """Searches for config files, reads them and returns a dictionary Looks for a ``check-manifest`` section in ``pyproject.toml``, ``setup.cfg``, and ``tox.ini``, in that order. The first file that exists and has that section will be loaded and returned as a dictionary. """ ...
def read_manifest(): """Read existing configuration from MANIFEST.in. We use that to ignore anything the MANIFEST.in ignores. """ # XXX modifies global state, which is kind of evil if not os.path.isfile('MANIFEST.in'): return ignore, ignore_regexps = _get_ignore_from_manifest('MANIFEST....
def _get_ignore_from_manifest(filename): """Gather the various ignore patterns from a MANIFEST.in. Returns a list of standard ignore patterns and a list of regular expressions to ignore. """ class MyTextFile(TextFile): def error(self, msg, line=None): # pragma: nocover # (this...
def _get_ignore_from_manifest_lines(lines): """Gather the various ignore patterns from a MANIFEST.in. 'lines' should be a list of strings with comments removed and continuation lines joined. Returns a list of standard ignore patterns and a list of regular expressions to ignore. """ ignore ...
def file_matches(filename, patterns): """Does this filename match any of the patterns?""" return any(fnmatch.fnmatch(filename, pat) or fnmatch.fnmatch(os.path.basename(filename), pat) for pat in patterns)
def file_matches_regexps(filename, patterns): """Does this filename match any of the regular expressions?""" return any(re.match(pat, filename) for pat in patterns)
def strip_sdist_extras(filelist): """Strip generated files that are only present in source distributions. We also strip files that are ignored for other reasons, like command line arguments, setup.cfg rules or MANIFEST.in rules. """ return [name for name in filelist if not file_matches(...
def find_suggestions(filelist): """Suggest MANIFEST.in patterns for missing files.""" suggestions = set() unknowns = [] for filename in filelist: if os.path.isdir(filename): # it's impossible to add empty directories via MANIFEST.in anyway, # and non-empty directories wil...
def extract_version_from_filename(filename): """Extract version number from sdist filename.""" filename = os.path.splitext(os.path.basename(filename))[0] if filename.endswith('.tar'): filename = os.path.splitext(filename)[0] return filename.partition('-')[2]
def check_manifest(source_tree='.', create=False, update=False, python=sys.executable): """Compare a generated source distribution with list of files in a VCS. Returns True if the manifest is fine. """ all_ok = True if os.path.sep in python: python = os.path.abspath(pytho...
def zest_releaser_check(data): """Check the completeness of MANIFEST.in before the release. This is an entry point for zest.releaser. See the documentation at https://zestreleaser.readthedocs.io/en/latest/entrypoints.html """ from zest.releaser.utils import ask source_tree = data['workingdir']...
def get_versioned_files(cls): """List all files versioned by git in the current directory.""" files = cls._git_ls_files() submodules = cls._list_submodules() for subdir in submodules: subdir = os.path.relpath(subdir).replace(os.path.sep, '/') files += add_prefix_t...
def get_versioned_files(cls): """List all files versioned in Bazaar in the current directory.""" encoding = cls._get_terminal_encoding() output = run(['bzr', 'ls', '-VR'], encoding=encoding) return output.splitlines()
def get_versioned_files(cls): """List all files under SVN control in the current directory.""" output = run(['svn', 'st', '-vq', '--xml'], decode=False) tree = ET.XML(output) return sorted(entry.get('path') for entry in tree.findall('.//entry') if cls.is_interesting...
def is_interesting(entry): """Is this entry interesting? ``entry`` is an XML node representing one entry of the svn status XML output. It looks like this:: <entry path="unchanged.txt"> <wc-status item="normal" revision="1" props="none"> <commit revisi...
def validate(self): """ Check if the formats of principals and actions are valid. :return: True, if the policy is valid :raises: InvalidApplicationPolicyError """ if not self.principals: raise InvalidApplicationPolicyError(error_message='principals not provid...
def publish_application(template, sar_client=None): """ Create a new application or new application version in SAR. :param template: Content of a packaged YAML or JSON SAM template :type template: str_or_dict :param sar_client: The boto3 client used to access SAR :type sar_client: boto3.client ...
def update_application_metadata(template, application_id, sar_client=None): """ Update the application metadata. :param template: Content of a packaged YAML or JSON SAM template :type template: str_or_dict :param application_id: The Amazon Resource Name (ARN) of the application :type applicatio...
def _get_template_dict(template): """ Parse string template and or copy dictionary template. :param template: Content of a packaged YAML or JSON SAM template :type template: str_or_dict :return: Template as a dictionary :rtype: dict :raises ValueError """ if isinstance(template, str...
def _create_application_request(app_metadata, template): """ Construct the request body to create application. :param app_metadata: Object containing app metadata :type app_metadata: ApplicationMetadata :param template: A packaged YAML or JSON SAM template :type template: str :return: SAR C...
def _update_application_request(app_metadata, application_id): """ Construct the request body to update application. :param app_metadata: Object containing app metadata :type app_metadata: ApplicationMetadata :param application_id: The Amazon Resource Name (ARN) of the application :type applica...
def _create_application_version_request(app_metadata, application_id, template): """ Construct the request body to create application version. :param app_metadata: Object containing app metadata :type app_metadata: ApplicationMetadata :param application_id: The Amazon Resource Name (ARN) of the app...
def _wrap_client_error(e): """ Wrap botocore ClientError exception into ServerlessRepoClientError. :param e: botocore exception :type e: ClientError :return: S3PermissionsRequired or InvalidS3UriError or general ServerlessRepoClientError """ error_code = e.response['Error']['Code'] mess...
def _get_publish_details(actions, app_metadata_template): """ Get the changed application details after publishing. :param actions: Actions taken during publishing :type actions: list of str :param app_metadata_template: Original template definitions of app metadata :type app_metadata_template:...
def validate(self, required_props): """ Check if the required application metadata properties have been populated. :param required_props: List of required properties :type required_props: list :return: True, if the metadata is valid :raises: InvalidApplicationMetadataErr...
def yaml_dump(dict_to_dump): """ Dump the dictionary as a YAML document. :param dict_to_dump: Data to be serialized as YAML :type dict_to_dump: dict :return: YAML document :rtype: str """ yaml.SafeDumper.add_representer(OrderedDict, _dict_representer) return yaml.safe_dump(dict_to_d...
def parse_template(template_str): """ Parse the SAM template. :param template_str: A packaged YAML or json CloudFormation template :type template_str: str :return: Dictionary with keys defined in the template :rtype: dict """ try: # PyYAML doesn't support json as well as it shou...
def get_app_metadata(template_dict): """ Get the application metadata from a SAM template. :param template_dict: SAM template as a dictionary :type template_dict: dict :return: Application metadata as defined in the template :rtype: ApplicationMetadata :raises ApplicationMetadataNotFoundErr...
def parse_application_id(text): """ Extract the application id from input text. :param text: text to parse :type text: str :return: application id if found in the input :rtype: str """ result = re.search(APPLICATION_ID_PATTERN, text) return result.group(0) if result else None
def strip_app_metadata(template_dict): """ Strip the "AWS::ServerlessRepo::Application" metadata section from template. :param template_dict: SAM template as a dictionary :type template_dict: dict :return: stripped template content :rtype: str """ if SERVERLESS_REPO_APPLICATION not in t...
def make_application_private(application_id, sar_client=None): """ Set the application to be private. :param application_id: The Amazon Resource Name (ARN) of the application :type application_id: str :param sar_client: The boto3 client used to access SAR :type sar_client: boto3.client :rai...
def share_application_with_accounts(application_id, account_ids, sar_client=None): """ Share the application privately with given AWS account IDs. :param application_id: The Amazon Resource Name (ARN) of the application :type application_id: str :param account_ids: List of AWS account IDs, or * ...
def extract_args(cls, *args): """ Takes any arguments like a model and crud, or just one of those, in any order, and return a model and crud. """ model = None crudbuilder = None for arg in args: if issubclass(arg, models.Model): model ...
def register(self, *args, **kwargs): """ Register a crud. Two unordered arguments are accepted, at least one should be passed: - a model, - a crudbuilder class """ assert len(args) <= 2, 'register takes at most 2 args' assert len(args) > 0, 'register tak...
def construct_formset(self): """ Returns an instance of the inline formset """ if not self.inline_model or not self.parent_model: msg = "Parent and Inline models are required in {}".format(self.__class__.__name__) raise NotModelException(msg) return inlin...
def get_factory_kwargs(self): """ Returns the keyword arguments for calling the formset factory """ kwargs = {} kwargs.update({ 'can_delete': self.can_delete, 'extra': self.extra, 'exclude': self.exclude, 'fields': self.fields, ...
def plural(text): """ >>> plural('activity') 'activities' """ aberrant = { 'knife': 'knives', 'self': 'selves', 'elf': 'elves', 'life': 'lives', 'hoof': 'hooves', 'leaf': 'leaves', 'echo': 'echoes', 'embargo': 'embargoes', ...
def mixedToUnder(s): # pragma: no cover """ Sample: >>> mixedToUnder("FooBarBaz") 'foo_bar_baz' Special case for ID: >>> mixedToUnder("FooBarID") 'foo_bar_id' """ if s.endswith('ID'): return mixedToUnder(s[:-2] + "_id") trans = _mixedToUnderRE.sub(mixedT...
def underToMixed(name): """ >>> underToMixed('some_large_model_name_perhaps') 'someLargeModelNamePerhaps' >>> underToMixed('exception_for_id') 'exceptionForID' """ if name.endswith('_id'): return underToMixed(name[:-3] + "ID") return _underToMixedRE.sub(lambda m: m.group(0)[1].u...
def import_crud(app): ''' Import crud module and register all model cruds which it contains ''' try: app_path = import_module(app).__path__ except (AttributeError, ImportError): return None try: imp.find_module('crud', app_path) except ImportError: return No...
def get_model_class(self): """Returns model class""" try: c = ContentType.objects.get(app_label=self.app, model=self.model) except ContentType.DoesNotExist: # try another kind of resolution # fixes a situation where a proxy model is defined in some external ap...
def get_verbose_field_name(instance, field_name): """ Returns verbose_name for a field. """ fields = [field.name for field in instance._meta.fields] if field_name in fields: return instance._meta.get_field(field_name).verbose_name else: return field_name
def generate_modelform(self): """Generate modelform from Django modelform_factory""" model_class = self.get_model_class excludes = self.modelform_excludes if self.modelform_excludes else [] _ObjectForm = modelform_factory(model_class, exclude=excludes) return _ObjectForm
def get_template(self, tname): """ - Get custom template from CRUD class, if it is defined in it - No custom template in CRUD class, then use the default template """ if self.custom_templates and self.custom_templates.get(tname, None): return self.custom_templates.ge...
def generate_list_view(self): """Generate class based view for ListView""" name = model_class_form(self.model + 'ListView') list_args = dict( model=self.get_model_class, context_object_name=plural(self.model), template_name=self.get_template('list'), ...
def generate_create_view(self): """Generate class based view for CreateView""" name = model_class_form(self.model + 'CreateView') create_args = dict( form_class=self.get_actual_form('create'), model=self.get_model_class, template_name=self.get_template('creat...
def generate_detail_view(self): """Generate class based view for DetailView""" name = model_class_form(self.model + 'DetailView') detail_args = dict( detailview_excludes=self.detailview_excludes, model=self.get_model_class, template_name=self.get_template('de...
def generate_update_view(self): """Generate class based view for UpdateView""" name = model_class_form(self.model + 'UpdateView') update_args = dict( form_class=self.get_actual_form('update'), model=self.get_model_class, template_name=self.get_template('updat...
def generate_delete_view(self): """Generate class based view for DeleteView""" name = model_class_form(self.model + 'DeleteView') delete_args = dict( model=self.get_model_class, template_name=self.get_template('delete'), permissions=self.view_permission('dele...
def incoming_references(self, client=None, query={}): """Fetches all entries referencing the entry API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters/links-to-asset :param client Client instance :param query: (optiona...
def build(self): """Creates the objects from the JSON response""" if self.json['sys']['type'] == 'Array': if any(k in self.json for k in ['nextSyncUrl', 'nextPageUrl']): return SyncPage( self.json, default_locale=self.default_locale, ...
def get(cls, content_type_id): """ Fetches a Content Type from the Cache. """ for content_type in cls.__CACHE__: if content_type.sys.get('id') == content_type_id: return content_type return None
def get_error(response): """Gets Error by HTTP Status Code""" errors = { 400: BadRequestError, 401: UnauthorizedError, 403: AccessDeniedError, 404: NotFoundError, 429: RateLimitExceededError, 500: ServerError, 502: BadGatewayError, 503: ServiceUna...
def field_for(self, field_id): """Fetches the field for the given Field ID. :param field_id: ID for Field to fetch. :return: :class:`ContentTypeField <ContentTypeField>` object. :rtype: contentful.ContentTypeField """ for field in self.fields: if field.id ==...
def coerce(self, value, **kwargs): """Coerces value to Location object""" Location = namedtuple('Location', ['lat', 'lon']) return Location(float(value.get('lat')), float(value.get('lon')))
def coerce(self, value, **kwargs): """Coerces array items with proper coercion.""" result = [] for v in value: result.append(self._coercion.coerce(v, **kwargs)) return result
def coerce(self, value, includes=None, errors=None, resources=None, default_locale='en-US', locale=None): """Coerces Rich Text properly.""" if includes is None: includes = [] if errors is None: errors = [] return self._coerce_block( value, ...
def coerce(self, value, **kwargs): """Coerces the value to the proper type.""" if value is None: return None return self._coercion.coerce(value, **kwargs)
def content_type(self, content_type_id, query=None): """Fetches a Content Type by ID. API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/content-types/content-type/get-a-single-content-type :param content_type_id: The ID of the target Content ...
def entry(self, entry_id, query=None): """Fetches an Entry by ID. API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/entries/entry/get-a-single-entry :param entry_id: The ID of the target Entry. :param query: (optional) Dict with API o...
def entries(self, query=None): """Fetches all Entries from the Space (up to the set limit, can be modified in `query`). API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/entries/entries-collection/get-all-entries-of-a-space :param query: (opt...
def asset(self, asset_id, query=None): """Fetches an Asset by ID. API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/assets/asset/get-a-single-asset :param asset_id: The ID of the target Asset. :param query: (optional) Dict with API op...
def assets(self, query=None): """Fetches all Assets from the Space (up to the set limit, can be modified in `query`). API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/assets/assets-collection/get-all-assets-of-a-space :param query: (optional...
def locales(self, query=None): """Fetches all Locales from the Environment (up to the set limit, can be modified in `query`). # TODO: fix url API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/assets/assets-collection/get-all-assets-of-a-space ...
def sync(self, query=None): """Fetches content from the Sync API. API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/synchronization/initial-synchronization/query-entries :param query: (optional) Dict with API options. :return: :class:...
def _normalize_select(self, query): """ If the query contains the :select operator, we enforce :sys properties. The SDK requires sys.type to function properly, but as other of our SDKs require more parts of the :sys properties, we decided that every SDK should include the complet...
def _request_headers(self): """ Sets the default Request Headers. """ headers = { 'X-Contentful-User-Agent': self._contentful_user_agent(), 'Content-Type': 'application/vnd.contentful.delivery.v{0}+json'.format( # noqa: E501 self.api_version ...
def _url(self, url): """ Creates the Request URL. """ protocol = 'https' if self.https else 'http' return '{0}://{1}/spaces/{2}{3}'.format( protocol, self.api_url, self.space_id, url )
def _normalize_query(self, query): """ Converts Arrays in the query to comma separaters lists for proper API handling. """ for k, v in query.items(): if isinstance(v, list): query[k] = ','.join([str(e) for e in v])