repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
YosaiProject/yosai | yosai/core/mgt/mgt.py | NativeSecurityManager.create_subject | def create_subject(self,
authc_token=None,
account_id=None,
existing_subject=None,
subject_context=None):
"""
Creates a ``Subject`` instance for the user represented by the given method
arguments.
... | python | def create_subject(self,
authc_token=None,
account_id=None,
existing_subject=None,
subject_context=None):
"""
Creates a ``Subject`` instance for the user represented by the given method
arguments.
... | [
"def",
"create_subject",
"(",
"self",
",",
"authc_token",
"=",
"None",
",",
"account_id",
"=",
"None",
",",
"existing_subject",
"=",
"None",
",",
"subject_context",
"=",
"None",
")",
":",
"if",
"subject_context",
"is",
"None",
":",
"# this that means a successfu... | Creates a ``Subject`` instance for the user represented by the given method
arguments.
It is an overloaded method, due to porting java to python, and is
consequently highly likely to be refactored.
It gets called in one of two ways:
1) when creating an anonymous subject, passin... | [
"Creates",
"a",
"Subject",
"instance",
"for",
"the",
"user",
"represented",
"by",
"the",
"given",
"method",
"arguments",
"."
] | 7f96aa6b837ceae9bf3d7387cd7e35f5ab032575 | https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/mgt/mgt.py#L514-L582 | train |
YosaiProject/yosai | yosai/core/mgt/mgt.py | NativeSecurityManager.login | def login(self, subject, authc_token):
"""
Login authenticates a user using an AuthenticationToken. If authentication is
successful AND the Authenticator has determined that authentication is
complete for the account, login constructs a Subject instance representing
the authenti... | python | def login(self, subject, authc_token):
"""
Login authenticates a user using an AuthenticationToken. If authentication is
successful AND the Authenticator has determined that authentication is
complete for the account, login constructs a Subject instance representing
the authenti... | [
"def",
"login",
"(",
"self",
",",
"subject",
",",
"authc_token",
")",
":",
"try",
":",
"# account_id is a SimpleIdentifierCollection",
"account_id",
"=",
"self",
".",
"authenticator",
".",
"authenticate_account",
"(",
"subject",
".",
"identifiers",
",",
"authc_token... | Login authenticates a user using an AuthenticationToken. If authentication is
successful AND the Authenticator has determined that authentication is
complete for the account, login constructs a Subject instance representing
the authenticated account's identity. Once a subject instance is constr... | [
"Login",
"authenticates",
"a",
"user",
"using",
"an",
"AuthenticationToken",
".",
"If",
"authentication",
"is",
"successful",
"AND",
"the",
"Authenticator",
"has",
"determined",
"that",
"authentication",
"is",
"complete",
"for",
"the",
"account",
"login",
"construct... | 7f96aa6b837ceae9bf3d7387cd7e35f5ab032575 | https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/mgt/mgt.py#L635-L684 | train |
YosaiProject/yosai | yosai/core/mgt/mgt.py | NativeSecurityManager.ensure_security_manager | def ensure_security_manager(self, subject_context):
"""
Determines whether there is a ``SecurityManager`` instance in the context,
and if not, adds 'self' to the context. This ensures that do_create_subject
will have access to a ``SecurityManager`` during Subject construction.
... | python | def ensure_security_manager(self, subject_context):
"""
Determines whether there is a ``SecurityManager`` instance in the context,
and if not, adds 'self' to the context. This ensures that do_create_subject
will have access to a ``SecurityManager`` during Subject construction.
... | [
"def",
"ensure_security_manager",
"(",
"self",
",",
"subject_context",
")",
":",
"if",
"(",
"subject_context",
".",
"resolve_security_manager",
"(",
")",
"is",
"not",
"None",
")",
":",
"msg",
"=",
"(",
"\"Subject Context resolved a security_manager \"",
"\"instance, s... | Determines whether there is a ``SecurityManager`` instance in the context,
and if not, adds 'self' to the context. This ensures that do_create_subject
will have access to a ``SecurityManager`` during Subject construction.
:param subject_context: the subject context data that may contain a
... | [
"Determines",
"whether",
"there",
"is",
"a",
"SecurityManager",
"instance",
"in",
"the",
"context",
"and",
"if",
"not",
"adds",
"self",
"to",
"the",
"context",
".",
"This",
"ensures",
"that",
"do_create_subject",
"will",
"have",
"access",
"to",
"a",
"SecurityM... | 7f96aa6b837ceae9bf3d7387cd7e35f5ab032575 | https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/mgt/mgt.py#L741-L763 | train |
YosaiProject/yosai | yosai/core/mgt/mgt.py | NativeSecurityManager.resolve_session | def resolve_session(self, subject_context):
"""
This method attempts to resolve any associated session based on the
context and returns a context that represents this resolved Session to
ensure it may be referenced, if needed, by the invoked do_create_subject
that performs actual... | python | def resolve_session(self, subject_context):
"""
This method attempts to resolve any associated session based on the
context and returns a context that represents this resolved Session to
ensure it may be referenced, if needed, by the invoked do_create_subject
that performs actual... | [
"def",
"resolve_session",
"(",
"self",
",",
"subject_context",
")",
":",
"if",
"(",
"subject_context",
".",
"resolve_session",
"(",
")",
"is",
"not",
"None",
")",
":",
"msg",
"=",
"(",
"\"Context already contains a session. Returning.\"",
")",
"logger",
".",
"d... | This method attempts to resolve any associated session based on the
context and returns a context that represents this resolved Session to
ensure it may be referenced, if needed, by the invoked do_create_subject
that performs actual ``Subject`` construction.
If there is a ``Session`` al... | [
"This",
"method",
"attempts",
"to",
"resolve",
"any",
"associated",
"session",
"based",
"on",
"the",
"context",
"and",
"returns",
"a",
"context",
"that",
"represents",
"this",
"resolved",
"Session",
"to",
"ensure",
"it",
"may",
"be",
"referenced",
"if",
"neede... | 7f96aa6b837ceae9bf3d7387cd7e35f5ab032575 | https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/mgt/mgt.py#L765-L801 | train |
YosaiProject/yosai | yosai/core/mgt/mgt.py | NativeSecurityManager.resolve_identifiers | def resolve_identifiers(self, subject_context):
"""
ensures that a subject_context has identifiers and if it doesn't will
attempt to locate them using heuristics
"""
session = subject_context.session
identifiers = subject_context.resolve_identifiers(session)
if (... | python | def resolve_identifiers(self, subject_context):
"""
ensures that a subject_context has identifiers and if it doesn't will
attempt to locate them using heuristics
"""
session = subject_context.session
identifiers = subject_context.resolve_identifiers(session)
if (... | [
"def",
"resolve_identifiers",
"(",
"self",
",",
"subject_context",
")",
":",
"session",
"=",
"subject_context",
".",
"session",
"identifiers",
"=",
"subject_context",
".",
"resolve_identifiers",
"(",
"session",
")",
"if",
"(",
"not",
"identifiers",
")",
":",
"ms... | ensures that a subject_context has identifiers and if it doesn't will
attempt to locate them using heuristics | [
"ensures",
"that",
"a",
"subject_context",
"has",
"identifiers",
"and",
"if",
"it",
"doesn",
"t",
"will",
"attempt",
"to",
"locate",
"them",
"using",
"heuristics"
] | 7f96aa6b837ceae9bf3d7387cd7e35f5ab032575 | https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/mgt/mgt.py#L819-L847 | train |
YosaiProject/yosai | yosai/core/mgt/mgt.py | NativeSecurityManager.logout | def logout(self, subject):
"""
Logs out the specified Subject from the system.
Note that most application developers should not call this method unless
they have a good reason for doing so. The preferred way to logout a
Subject is to call ``Subject.logout()``, not by calling ``... | python | def logout(self, subject):
"""
Logs out the specified Subject from the system.
Note that most application developers should not call this method unless
they have a good reason for doing so. The preferred way to logout a
Subject is to call ``Subject.logout()``, not by calling ``... | [
"def",
"logout",
"(",
"self",
",",
"subject",
")",
":",
"if",
"(",
"subject",
"is",
"None",
")",
":",
"msg",
"=",
"\"Subject argument cannot be None.\"",
"raise",
"ValueError",
"(",
"msg",
")",
"self",
".",
"before_logout",
"(",
"subject",
")",
"identifiers"... | Logs out the specified Subject from the system.
Note that most application developers should not call this method unless
they have a good reason for doing so. The preferred way to logout a
Subject is to call ``Subject.logout()``, not by calling ``SecurityManager.logout``
directly. Howe... | [
"Logs",
"out",
"the",
"specified",
"Subject",
"from",
"the",
"system",
"."
] | 7f96aa6b837ceae9bf3d7387cd7e35f5ab032575 | https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/mgt/mgt.py#L865-L903 | train |
YosaiProject/yosai | yosai/core/realm/realm.py | AccountStoreRealm.is_permitted | def is_permitted(self, identifiers, permission_s):
"""
If the authorization info cannot be obtained from the accountstore,
permission check tuple yields False.
:type identifiers: subject_abcs.IdentifierCollection
:param permission_s: a collection of one or more permissions, re... | python | def is_permitted(self, identifiers, permission_s):
"""
If the authorization info cannot be obtained from the accountstore,
permission check tuple yields False.
:type identifiers: subject_abcs.IdentifierCollection
:param permission_s: a collection of one or more permissions, re... | [
"def",
"is_permitted",
"(",
"self",
",",
"identifiers",
",",
"permission_s",
")",
":",
"identifier",
"=",
"identifiers",
".",
"primary_identifier",
"for",
"required",
"in",
"permission_s",
":",
"domain",
"=",
"Permission",
".",
"get_domain",
"(",
"required",
")"... | If the authorization info cannot be obtained from the accountstore,
permission check tuple yields False.
:type identifiers: subject_abcs.IdentifierCollection
:param permission_s: a collection of one or more permissions, represented
as string-based permissions or P... | [
"If",
"the",
"authorization",
"info",
"cannot",
"be",
"obtained",
"from",
"the",
"accountstore",
"permission",
"check",
"tuple",
"yields",
"False",
"."
] | 7f96aa6b837ceae9bf3d7387cd7e35f5ab032575 | https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/realm/realm.py#L377-L404 | train |
YosaiProject/yosai | yosai/core/realm/realm.py | AccountStoreRealm.has_role | def has_role(self, identifiers, required_role_s):
"""
Confirms whether a subject is a member of one or more roles.
If the authorization info cannot be obtained from the accountstore,
role check tuple yields False.
:type identifiers: subject_abcs.IdentifierCollection
:... | python | def has_role(self, identifiers, required_role_s):
"""
Confirms whether a subject is a member of one or more roles.
If the authorization info cannot be obtained from the accountstore,
role check tuple yields False.
:type identifiers: subject_abcs.IdentifierCollection
:... | [
"def",
"has_role",
"(",
"self",
",",
"identifiers",
",",
"required_role_s",
")",
":",
"identifier",
"=",
"identifiers",
".",
"primary_identifier",
"# assigned_role_s is a set",
"assigned_role_s",
"=",
"self",
".",
"get_authzd_roles",
"(",
"identifier",
")",
"if",
"n... | Confirms whether a subject is a member of one or more roles.
If the authorization info cannot be obtained from the accountstore,
role check tuple yields False.
:type identifiers: subject_abcs.IdentifierCollection
:param required_role_s: a collection of 1..N Role identifiers
:... | [
"Confirms",
"whether",
"a",
"subject",
"is",
"a",
"member",
"of",
"one",
"or",
"more",
"roles",
"."
] | 7f96aa6b837ceae9bf3d7387cd7e35f5ab032575 | https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/realm/realm.py#L406-L434 | train |
YosaiProject/yosai | yosai/web/session/session.py | WebSessionHandler.on_start | def on_start(self, session, session_context):
"""
Stores the Session's ID, usually as a Cookie, to associate with future
requests.
:param session: the session that was just ``createSession`` created
"""
session_id = session.session_id
web_registry = session_conte... | python | def on_start(self, session, session_context):
"""
Stores the Session's ID, usually as a Cookie, to associate with future
requests.
:param session: the session that was just ``createSession`` created
"""
session_id = session.session_id
web_registry = session_conte... | [
"def",
"on_start",
"(",
"self",
",",
"session",
",",
"session_context",
")",
":",
"session_id",
"=",
"session",
".",
"session_id",
"web_registry",
"=",
"session_context",
"[",
"'web_registry'",
"]",
"if",
"self",
".",
"is_session_id_cookie_enabled",
":",
"web_regi... | Stores the Session's ID, usually as a Cookie, to associate with future
requests.
:param session: the session that was just ``createSession`` created | [
"Stores",
"the",
"Session",
"s",
"ID",
"usually",
"as",
"a",
"Cookie",
"to",
"associate",
"with",
"future",
"requests",
"."
] | 7f96aa6b837ceae9bf3d7387cd7e35f5ab032575 | https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/web/session/session.py#L95-L112 | train |
YosaiProject/yosai | yosai/web/session/session.py | WebSessionStorageEvaluator.is_session_storage_enabled | def is_session_storage_enabled(self, subject=None):
"""
Returns ``True`` if session storage is generally available (as determined
by the super class's global configuration property is_session_storage_enabled
and no request-specific override has turned off session storage, False
o... | python | def is_session_storage_enabled(self, subject=None):
"""
Returns ``True`` if session storage is generally available (as determined
by the super class's global configuration property is_session_storage_enabled
and no request-specific override has turned off session storage, False
o... | [
"def",
"is_session_storage_enabled",
"(",
"self",
",",
"subject",
"=",
"None",
")",
":",
"if",
"subject",
".",
"get_session",
"(",
"False",
")",
":",
"# then use what already exists",
"return",
"True",
"if",
"not",
"self",
".",
"session_storage_enabled",
":",
"#... | Returns ``True`` if session storage is generally available (as determined
by the super class's global configuration property is_session_storage_enabled
and no request-specific override has turned off session storage, False
otherwise.
This means session storage is disabled if the is_sess... | [
"Returns",
"True",
"if",
"session",
"storage",
"is",
"generally",
"available",
"(",
"as",
"determined",
"by",
"the",
"super",
"class",
"s",
"global",
"configuration",
"property",
"is_session_storage_enabled",
"and",
"no",
"request",
"-",
"specific",
"override",
"h... | 7f96aa6b837ceae9bf3d7387cd7e35f5ab032575 | https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/web/session/session.py#L311-L343 | train |
YosaiProject/yosai | yosai/core/serialize/marshalling.py | default_marshaller | def default_marshaller(obj):
"""
Retrieve the state of the given object.
Calls the ``__getstate__()`` method of the object if available, otherwise returns the
``__dict__`` of the object.
:param obj: the object to marshal
:return: the marshalled object state
"""
if hasattr(obj, '__gets... | python | def default_marshaller(obj):
"""
Retrieve the state of the given object.
Calls the ``__getstate__()`` method of the object if available, otherwise returns the
``__dict__`` of the object.
:param obj: the object to marshal
:return: the marshalled object state
"""
if hasattr(obj, '__gets... | [
"def",
"default_marshaller",
"(",
"obj",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'__getstate__'",
")",
":",
"return",
"obj",
".",
"__getstate__",
"(",
")",
"try",
":",
"return",
"obj",
".",
"__dict__",
"except",
"AttributeError",
":",
"raise",
"TypeEr... | Retrieve the state of the given object.
Calls the ``__getstate__()`` method of the object if available, otherwise returns the
``__dict__`` of the object.
:param obj: the object to marshal
:return: the marshalled object state | [
"Retrieve",
"the",
"state",
"of",
"the",
"given",
"object",
"."
] | 7f96aa6b837ceae9bf3d7387cd7e35f5ab032575 | https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/serialize/marshalling.py#L5-L23 | train |
YosaiProject/yosai | yosai/core/serialize/marshalling.py | default_unmarshaller | def default_unmarshaller(instance, state):
"""
Restore the state of an object.
If the ``__setstate__()`` method exists on the instance, it is called with the state object
as the argument. Otherwise, the instance's ``__dict__`` is replaced with ``state``.
:param instance: an uninitialized instance
... | python | def default_unmarshaller(instance, state):
"""
Restore the state of an object.
If the ``__setstate__()`` method exists on the instance, it is called with the state object
as the argument. Otherwise, the instance's ``__dict__`` is replaced with ``state``.
:param instance: an uninitialized instance
... | [
"def",
"default_unmarshaller",
"(",
"instance",
",",
"state",
")",
":",
"if",
"hasattr",
"(",
"instance",
",",
"'__setstate__'",
")",
":",
"instance",
".",
"__setstate__",
"(",
"state",
")",
"else",
":",
"try",
":",
"instance",
".",
"__dict__",
".",
"updat... | Restore the state of an object.
If the ``__setstate__()`` method exists on the instance, it is called with the state object
as the argument. Otherwise, the instance's ``__dict__`` is replaced with ``state``.
:param instance: an uninitialized instance
:param state: the state object, as returned by :fun... | [
"Restore",
"the",
"state",
"of",
"an",
"object",
"."
] | 7f96aa6b837ceae9bf3d7387cd7e35f5ab032575 | https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/serialize/marshalling.py#L26-L44 | train |
YosaiProject/yosai | yosai/core/authc/authc.py | DefaultAuthenticator.do_authenticate_account | def do_authenticate_account(self, authc_token):
"""
Returns an account object only when the current token authenticates AND
the authentication process is complete, raising otherwise
:returns: Account
:raises AdditionalAuthenticationRequired: when additional tokens are required,... | python | def do_authenticate_account(self, authc_token):
"""
Returns an account object only when the current token authenticates AND
the authentication process is complete, raising otherwise
:returns: Account
:raises AdditionalAuthenticationRequired: when additional tokens are required,... | [
"def",
"do_authenticate_account",
"(",
"self",
",",
"authc_token",
")",
":",
"try",
":",
"realms",
"=",
"self",
".",
"token_realm_resolver",
"[",
"authc_token",
".",
"__class__",
"]",
"except",
"KeyError",
":",
"raise",
"KeyError",
"(",
"'Unsupported Token Type Pr... | Returns an account object only when the current token authenticates AND
the authentication process is complete, raising otherwise
:returns: Account
:raises AdditionalAuthenticationRequired: when additional tokens are required,
passing the accou... | [
"Returns",
"an",
"account",
"object",
"only",
"when",
"the",
"current",
"token",
"authenticates",
"AND",
"the",
"authentication",
"process",
"is",
"complete",
"raising",
"otherwise"
] | 7f96aa6b837ceae9bf3d7387cd7e35f5ab032575 | https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/authc/authc.py#L241-L274 | train |
YosaiProject/yosai | yosai/core/logging/formatters.py | JSONFormatter.extra_from_record | def extra_from_record(self, record):
"""Returns `extra` dict you passed to logger.
The `extra` keyword argument is used to populate the `__dict__` of
the `LogRecord`.
"""
return {
attr_name: record.__dict__[attr_name]
for attr_name in record.__dict__
... | python | def extra_from_record(self, record):
"""Returns `extra` dict you passed to logger.
The `extra` keyword argument is used to populate the `__dict__` of
the `LogRecord`.
"""
return {
attr_name: record.__dict__[attr_name]
for attr_name in record.__dict__
... | [
"def",
"extra_from_record",
"(",
"self",
",",
"record",
")",
":",
"return",
"{",
"attr_name",
":",
"record",
".",
"__dict__",
"[",
"attr_name",
"]",
"for",
"attr_name",
"in",
"record",
".",
"__dict__",
"if",
"attr_name",
"not",
"in",
"BUILTIN_ATTRS",
"}"
] | Returns `extra` dict you passed to logger.
The `extra` keyword argument is used to populate the `__dict__` of
the `LogRecord`. | [
"Returns",
"extra",
"dict",
"you",
"passed",
"to",
"logger",
"."
] | 7f96aa6b837ceae9bf3d7387cd7e35f5ab032575 | https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/logging/formatters.py#L37-L48 | train |
YosaiProject/yosai | yosai/core/subject/subject.py | SubjectStore.save | def save(self, subject):
"""
Saves the subject's state to the subject's ``Session`` only
if session storage is enabled for the subject. If session storage is
not enabled for the specific Subject, this method does nothing.
In either case, the argument Subject is returned directl... | python | def save(self, subject):
"""
Saves the subject's state to the subject's ``Session`` only
if session storage is enabled for the subject. If session storage is
not enabled for the specific Subject, this method does nothing.
In either case, the argument Subject is returned directl... | [
"def",
"save",
"(",
"self",
",",
"subject",
")",
":",
"if",
"(",
"self",
".",
"is_session_storage_enabled",
"(",
"subject",
")",
")",
":",
"self",
".",
"merge_identity",
"(",
"subject",
")",
"else",
":",
"msg",
"=",
"(",
"\"Session storage of subject state f... | Saves the subject's state to the subject's ``Session`` only
if session storage is enabled for the subject. If session storage is
not enabled for the specific Subject, this method does nothing.
In either case, the argument Subject is returned directly (a new
``Subject`` instance is not ... | [
"Saves",
"the",
"subject",
"s",
"state",
"to",
"the",
"subject",
"s",
"Session",
"only",
"if",
"session",
"storage",
"is",
"enabled",
"for",
"the",
"subject",
".",
"If",
"session",
"storage",
"is",
"not",
"enabled",
"for",
"the",
"specific",
"Subject",
"th... | 7f96aa6b837ceae9bf3d7387cd7e35f5ab032575 | https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/subject/subject.py#L656-L681 | train |
YosaiProject/yosai | yosai/core/subject/subject.py | SecurityManagerCreator.create_manager | def create_manager(self, yosai, settings, session_attributes):
"""
Order of execution matters. The sac must be set before the cache_handler is
instantiated so that the cache_handler's serialization manager instance
registers the sac.
"""
mgr_settings = SecurityManagerSet... | python | def create_manager(self, yosai, settings, session_attributes):
"""
Order of execution matters. The sac must be set before the cache_handler is
instantiated so that the cache_handler's serialization manager instance
registers the sac.
"""
mgr_settings = SecurityManagerSet... | [
"def",
"create_manager",
"(",
"self",
",",
"yosai",
",",
"settings",
",",
"session_attributes",
")",
":",
"mgr_settings",
"=",
"SecurityManagerSettings",
"(",
"settings",
")",
"attributes",
"=",
"mgr_settings",
".",
"attributes",
"realms",
"=",
"self",
".",
"_in... | Order of execution matters. The sac must be set before the cache_handler is
instantiated so that the cache_handler's serialization manager instance
registers the sac. | [
"Order",
"of",
"execution",
"matters",
".",
"The",
"sac",
"must",
"be",
"set",
"before",
"the",
"cache_handler",
"is",
"instantiated",
"so",
"that",
"the",
"cache_handler",
"s",
"serialization",
"manager",
"instance",
"registers",
"the",
"sac",
"."
] | 7f96aa6b837ceae9bf3d7387cd7e35f5ab032575 | https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/subject/subject.py#L1068-L1097 | train |
YosaiProject/yosai | yosai/core/authz/authz.py | ModularRealmAuthorizer.check_permission | def check_permission(self, identifiers, permission_s, logical_operator):
"""
like Yosai's authentication process, the authorization process will
raise an Exception to halt further authz checking once Yosai determines
that a Subject is unauthorized to receive the requested permission
... | python | def check_permission(self, identifiers, permission_s, logical_operator):
"""
like Yosai's authentication process, the authorization process will
raise an Exception to halt further authz checking once Yosai determines
that a Subject is unauthorized to receive the requested permission
... | [
"def",
"check_permission",
"(",
"self",
",",
"identifiers",
",",
"permission_s",
",",
"logical_operator",
")",
":",
"self",
".",
"assert_realms_configured",
"(",
")",
"permitted",
"=",
"self",
".",
"is_permitted_collective",
"(",
"identifiers",
",",
"permission_s",
... | like Yosai's authentication process, the authorization process will
raise an Exception to halt further authz checking once Yosai determines
that a Subject is unauthorized to receive the requested permission
:param identifiers: a collection of identifiers
:type identifiers: subject_abcs... | [
"like",
"Yosai",
"s",
"authentication",
"process",
"the",
"authorization",
"process",
"will",
"raise",
"an",
"Exception",
"to",
"halt",
"further",
"authz",
"checking",
"once",
"Yosai",
"determines",
"that",
"a",
"Subject",
"is",
"unauthorized",
"to",
"receive",
... | 7f96aa6b837ceae9bf3d7387cd7e35f5ab032575 | https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/authz/authz.py#L292-L316 | train |
YosaiProject/yosai | yosai/core/subject/identifier.py | SimpleIdentifierCollection.by_type | def by_type(self, identifier_class):
"""
returns all unique instances of a type of identifier
:param identifier_class: the class to match identifier with
:returns: a tuple
"""
myidentifiers = set()
for identifier in self.source_identifiers.values():
i... | python | def by_type(self, identifier_class):
"""
returns all unique instances of a type of identifier
:param identifier_class: the class to match identifier with
:returns: a tuple
"""
myidentifiers = set()
for identifier in self.source_identifiers.values():
i... | [
"def",
"by_type",
"(",
"self",
",",
"identifier_class",
")",
":",
"myidentifiers",
"=",
"set",
"(",
")",
"for",
"identifier",
"in",
"self",
".",
"source_identifiers",
".",
"values",
"(",
")",
":",
"if",
"(",
"isinstance",
"(",
"identifier",
",",
"identifie... | returns all unique instances of a type of identifier
:param identifier_class: the class to match identifier with
:returns: a tuple | [
"returns",
"all",
"unique",
"instances",
"of",
"a",
"type",
"of",
"identifier"
] | 7f96aa6b837ceae9bf3d7387cd7e35f5ab032575 | https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/subject/identifier.py#L101-L112 | train |
YosaiProject/yosai | yosai/core/session/session.py | CachingSessionStore.create | def create(self, session):
"""
caches the session and caches an entry to associate the cached session
with the subject
"""
sessionid = super().create(session) # calls _do_create and verify
self._cache(session, sessionid)
return sessionid | python | def create(self, session):
"""
caches the session and caches an entry to associate the cached session
with the subject
"""
sessionid = super().create(session) # calls _do_create and verify
self._cache(session, sessionid)
return sessionid | [
"def",
"create",
"(",
"self",
",",
"session",
")",
":",
"sessionid",
"=",
"super",
"(",
")",
".",
"create",
"(",
"session",
")",
"# calls _do_create and verify",
"self",
".",
"_cache",
"(",
"session",
",",
"sessionid",
")",
"return",
"sessionid"
] | caches the session and caches an entry to associate the cached session
with the subject | [
"caches",
"the",
"session",
"and",
"caches",
"an",
"entry",
"to",
"associate",
"the",
"cached",
"session",
"with",
"the",
"subject"
] | 7f96aa6b837ceae9bf3d7387cd7e35f5ab032575 | https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/session/session.py#L213-L220 | train |
YosaiProject/yosai | yosai/core/session/session.py | NativeSessionManager.start | def start(self, session_context):
"""
unlike shiro, yosai does not apply session timeouts from within the
start method of the SessionManager but rather defers timeout settings
responsibilities to the SimpleSession, which uses session_settings
"""
# is a SimpleSesson:
... | python | def start(self, session_context):
"""
unlike shiro, yosai does not apply session timeouts from within the
start method of the SessionManager but rather defers timeout settings
responsibilities to the SimpleSession, which uses session_settings
"""
# is a SimpleSesson:
... | [
"def",
"start",
"(",
"self",
",",
"session_context",
")",
":",
"# is a SimpleSesson:",
"session",
"=",
"self",
".",
"_create_session",
"(",
"session_context",
")",
"self",
".",
"session_handler",
".",
"on_start",
"(",
"session",
",",
"session_context",
")",
"mys... | unlike shiro, yosai does not apply session timeouts from within the
start method of the SessionManager but rather defers timeout settings
responsibilities to the SimpleSession, which uses session_settings | [
"unlike",
"shiro",
"yosai",
"does",
"not",
"apply",
"session",
"timeouts",
"from",
"within",
"the",
"start",
"method",
"of",
"the",
"SessionManager",
"but",
"rather",
"defers",
"timeout",
"settings",
"responsibilities",
"to",
"the",
"SimpleSession",
"which",
"uses... | 7f96aa6b837ceae9bf3d7387cd7e35f5ab032575 | https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/session/session.py#L921-L937 | train |
YosaiProject/yosai | yosai/core/conf/yosaisettings.py | LazySettings._setup | def _setup(self, name=None):
"""
Load the settings module referenced by env_var. This environment-
defined configuration process is called during the settings
configuration process.
"""
envvar = self.__dict__['env_var']
if envvar:
settings_file = os.en... | python | def _setup(self, name=None):
"""
Load the settings module referenced by env_var. This environment-
defined configuration process is called during the settings
configuration process.
"""
envvar = self.__dict__['env_var']
if envvar:
settings_file = os.en... | [
"def",
"_setup",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"envvar",
"=",
"self",
".",
"__dict__",
"[",
"'env_var'",
"]",
"if",
"envvar",
":",
"settings_file",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"envvar",
")",
"else",
":",
"settings_f... | Load the settings module referenced by env_var. This environment-
defined configuration process is called during the settings
configuration process. | [
"Load",
"the",
"settings",
"module",
"referenced",
"by",
"env_var",
".",
"This",
"environment",
"-",
"defined",
"configuration",
"process",
"is",
"called",
"during",
"the",
"settings",
"configuration",
"process",
"."
] | 7f96aa6b837ceae9bf3d7387cd7e35f5ab032575 | https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/conf/yosaisettings.py#L69-L88 | train |
YosaiProject/yosai | yosai/web/mgt/mgt.py | CookieRememberMeManager.remember_encrypted_identity | def remember_encrypted_identity(self, subject, encrypted):
"""
Base64-encodes the specified serialized byte array and sets that
base64-encoded String as the cookie value.
The ``subject`` instance is expected to be a ``WebSubject`` instance
with a web_registry handle so that an H... | python | def remember_encrypted_identity(self, subject, encrypted):
"""
Base64-encodes the specified serialized byte array and sets that
base64-encoded String as the cookie value.
The ``subject`` instance is expected to be a ``WebSubject`` instance
with a web_registry handle so that an H... | [
"def",
"remember_encrypted_identity",
"(",
"self",
",",
"subject",
",",
"encrypted",
")",
":",
"try",
":",
"# base 64 encode it and store as a cookie:",
"encoded",
"=",
"base64",
".",
"b64encode",
"(",
"encrypted",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"subject... | Base64-encodes the specified serialized byte array and sets that
base64-encoded String as the cookie value.
The ``subject`` instance is expected to be a ``WebSubject`` instance
with a web_registry handle so that an HTTP cookie may be set on an
outgoing response. If it is not a ``WebSub... | [
"Base64",
"-",
"encodes",
"the",
"specified",
"serialized",
"byte",
"array",
"and",
"sets",
"that",
"base64",
"-",
"encoded",
"String",
"as",
"the",
"cookie",
"value",
"."
] | 7f96aa6b837ceae9bf3d7387cd7e35f5ab032575 | https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/web/mgt/mgt.py#L156-L181 | train |
YosaiProject/yosai | yosai/web/mgt/mgt.py | CookieRememberMeManager.get_remembered_encrypted_identity | def get_remembered_encrypted_identity(self, subject_context):
"""
Returns a previously serialized identity byte array or None if the byte
array could not be acquired.
This implementation retrieves an HTTP cookie, Base64-decodes the cookie
value, and returns the resulting byte ar... | python | def get_remembered_encrypted_identity(self, subject_context):
"""
Returns a previously serialized identity byte array or None if the byte
array could not be acquired.
This implementation retrieves an HTTP cookie, Base64-decodes the cookie
value, and returns the resulting byte ar... | [
"def",
"get_remembered_encrypted_identity",
"(",
"self",
",",
"subject_context",
")",
":",
"if",
"(",
"self",
".",
"is_identity_removed",
"(",
"subject_context",
")",
")",
":",
"if",
"not",
"isinstance",
"(",
"subject_context",
",",
"web_subject_abcs",
".",
"WebSu... | Returns a previously serialized identity byte array or None if the byte
array could not be acquired.
This implementation retrieves an HTTP cookie, Base64-decodes the cookie
value, and returns the resulting byte array.
The ``subject_context`` instance is expected to be a ``WebSubjectCon... | [
"Returns",
"a",
"previously",
"serialized",
"identity",
"byte",
"array",
"or",
"None",
"if",
"the",
"byte",
"array",
"could",
"not",
"be",
"acquired",
"."
] | 7f96aa6b837ceae9bf3d7387cd7e35f5ab032575 | https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/web/mgt/mgt.py#L190-L235 | train |
jobec/django-auth-adfs | django_auth_adfs/config.py | _get_settings_class | def _get_settings_class():
"""
Get the AUTH_ADFS setting from the Django settings.
"""
if not hasattr(django_settings, "AUTH_ADFS"):
msg = "The configuration directive 'AUTH_ADFS' was not found in your Django settings"
raise ImproperlyConfigured(msg)
cls = django_settings.AUTH_ADFS.g... | python | def _get_settings_class():
"""
Get the AUTH_ADFS setting from the Django settings.
"""
if not hasattr(django_settings, "AUTH_ADFS"):
msg = "The configuration directive 'AUTH_ADFS' was not found in your Django settings"
raise ImproperlyConfigured(msg)
cls = django_settings.AUTH_ADFS.g... | [
"def",
"_get_settings_class",
"(",
")",
":",
"if",
"not",
"hasattr",
"(",
"django_settings",
",",
"\"AUTH_ADFS\"",
")",
":",
"msg",
"=",
"\"The configuration directive 'AUTH_ADFS' was not found in your Django settings\"",
"raise",
"ImproperlyConfigured",
"(",
"msg",
")",
... | Get the AUTH_ADFS setting from the Django settings. | [
"Get",
"the",
"AUTH_ADFS",
"setting",
"from",
"the",
"Django",
"settings",
"."
] | 07197be392724d16a6132b03d9eafb1d634749cf | https://github.com/jobec/django-auth-adfs/blob/07197be392724d16a6132b03d9eafb1d634749cf/django_auth_adfs/config.py#L33-L41 | train |
jobec/django-auth-adfs | django_auth_adfs/config.py | ProviderConfig.build_authorization_endpoint | def build_authorization_endpoint(self, request, disable_sso=None):
"""
This function returns the ADFS authorization URL.
Args:
request(django.http.request.HttpRequest): A django Request object
disable_sso(bool): Whether to disable single sign-on and force the ADFS server... | python | def build_authorization_endpoint(self, request, disable_sso=None):
"""
This function returns the ADFS authorization URL.
Args:
request(django.http.request.HttpRequest): A django Request object
disable_sso(bool): Whether to disable single sign-on and force the ADFS server... | [
"def",
"build_authorization_endpoint",
"(",
"self",
",",
"request",
",",
"disable_sso",
"=",
"None",
")",
":",
"self",
".",
"load_config",
"(",
")",
"redirect_to",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"REDIRECT_FIELD_NAME",
",",
"None",
")",
"if",
... | This function returns the ADFS authorization URL.
Args:
request(django.http.request.HttpRequest): A django Request object
disable_sso(bool): Whether to disable single sign-on and force the ADFS server to show a login prompt.
Returns:
str: The redirect URI | [
"This",
"function",
"returns",
"the",
"ADFS",
"authorization",
"URL",
"."
] | 07197be392724d16a6132b03d9eafb1d634749cf | https://github.com/jobec/django-auth-adfs/blob/07197be392724d16a6132b03d9eafb1d634749cf/django_auth_adfs/config.py#L283-L313 | train |
jobec/django-auth-adfs | django_auth_adfs/backend.py | AdfsBaseBackend.create_user | def create_user(self, claims):
"""
Create the user if it doesn't exist yet
Args:
claims (dict): claims from the access token
Returns:
django.contrib.auth.models.User: A Django user
"""
# Create the user
username_claim = settings.USERNAME_... | python | def create_user(self, claims):
"""
Create the user if it doesn't exist yet
Args:
claims (dict): claims from the access token
Returns:
django.contrib.auth.models.User: A Django user
"""
# Create the user
username_claim = settings.USERNAME_... | [
"def",
"create_user",
"(",
"self",
",",
"claims",
")",
":",
"# Create the user",
"username_claim",
"=",
"settings",
".",
"USERNAME_CLAIM",
"usermodel",
"=",
"get_user_model",
"(",
")",
"user",
",",
"created",
"=",
"usermodel",
".",
"objects",
".",
"get_or_create... | Create the user if it doesn't exist yet
Args:
claims (dict): claims from the access token
Returns:
django.contrib.auth.models.User: A Django user | [
"Create",
"the",
"user",
"if",
"it",
"doesn",
"t",
"exist",
"yet"
] | 07197be392724d16a6132b03d9eafb1d634749cf | https://github.com/jobec/django-auth-adfs/blob/07197be392724d16a6132b03d9eafb1d634749cf/django_auth_adfs/backend.py#L110-L130 | train |
jobec/django-auth-adfs | django_auth_adfs/backend.py | AdfsBaseBackend.update_user_attributes | def update_user_attributes(self, user, claims):
"""
Updates user attributes based on the CLAIM_MAPPING setting.
Args:
user (django.contrib.auth.models.User): User model instance
claims (dict): claims from the access token
"""
required_fields = [field.nam... | python | def update_user_attributes(self, user, claims):
"""
Updates user attributes based on the CLAIM_MAPPING setting.
Args:
user (django.contrib.auth.models.User): User model instance
claims (dict): claims from the access token
"""
required_fields = [field.nam... | [
"def",
"update_user_attributes",
"(",
"self",
",",
"user",
",",
"claims",
")",
":",
"required_fields",
"=",
"[",
"field",
".",
"name",
"for",
"field",
"in",
"user",
".",
"_meta",
".",
"fields",
"if",
"field",
".",
"blank",
"is",
"False",
"]",
"for",
"f... | Updates user attributes based on the CLAIM_MAPPING setting.
Args:
user (django.contrib.auth.models.User): User model instance
claims (dict): claims from the access token | [
"Updates",
"user",
"attributes",
"based",
"on",
"the",
"CLAIM_MAPPING",
"setting",
"."
] | 07197be392724d16a6132b03d9eafb1d634749cf | https://github.com/jobec/django-auth-adfs/blob/07197be392724d16a6132b03d9eafb1d634749cf/django_auth_adfs/backend.py#L132-L158 | train |
jobec/django-auth-adfs | django_auth_adfs/backend.py | AdfsBaseBackend.update_user_groups | def update_user_groups(self, user, claims):
"""
Updates user group memberships based on the GROUPS_CLAIM setting.
Args:
user (django.contrib.auth.models.User): User model instance
claims (dict): Claims from the access token
"""
if settings.GROUPS_CLAIM is... | python | def update_user_groups(self, user, claims):
"""
Updates user group memberships based on the GROUPS_CLAIM setting.
Args:
user (django.contrib.auth.models.User): User model instance
claims (dict): Claims from the access token
"""
if settings.GROUPS_CLAIM is... | [
"def",
"update_user_groups",
"(",
"self",
",",
"user",
",",
"claims",
")",
":",
"if",
"settings",
".",
"GROUPS_CLAIM",
"is",
"not",
"None",
":",
"# Update the user's group memberships",
"django_groups",
"=",
"[",
"group",
".",
"name",
"for",
"group",
"in",
"us... | Updates user group memberships based on the GROUPS_CLAIM setting.
Args:
user (django.contrib.auth.models.User): User model instance
claims (dict): Claims from the access token | [
"Updates",
"user",
"group",
"memberships",
"based",
"on",
"the",
"GROUPS_CLAIM",
"setting",
"."
] | 07197be392724d16a6132b03d9eafb1d634749cf | https://github.com/jobec/django-auth-adfs/blob/07197be392724d16a6132b03d9eafb1d634749cf/django_auth_adfs/backend.py#L160-L206 | train |
jobec/django-auth-adfs | django_auth_adfs/backend.py | AdfsBaseBackend.update_user_flags | def update_user_flags(self, user, claims):
"""
Updates user boolean attributes based on the BOOLEAN_CLAIM_MAPPING setting.
Args:
user (django.contrib.auth.models.User): User model instance
claims (dict): Claims from the access token
"""
if settings.GROUPS... | python | def update_user_flags(self, user, claims):
"""
Updates user boolean attributes based on the BOOLEAN_CLAIM_MAPPING setting.
Args:
user (django.contrib.auth.models.User): User model instance
claims (dict): Claims from the access token
"""
if settings.GROUPS... | [
"def",
"update_user_flags",
"(",
"self",
",",
"user",
",",
"claims",
")",
":",
"if",
"settings",
".",
"GROUPS_CLAIM",
"is",
"not",
"None",
":",
"if",
"settings",
".",
"GROUPS_CLAIM",
"in",
"claims",
":",
"access_token_groups",
"=",
"claims",
"[",
"settings",... | Updates user boolean attributes based on the BOOLEAN_CLAIM_MAPPING setting.
Args:
user (django.contrib.auth.models.User): User model instance
claims (dict): Claims from the access token | [
"Updates",
"user",
"boolean",
"attributes",
"based",
"on",
"the",
"BOOLEAN_CLAIM_MAPPING",
"setting",
"."
] | 07197be392724d16a6132b03d9eafb1d634749cf | https://github.com/jobec/django-auth-adfs/blob/07197be392724d16a6132b03d9eafb1d634749cf/django_auth_adfs/backend.py#L208-L246 | train |
jobec/django-auth-adfs | django_auth_adfs/views.py | OAuth2CallbackView.get | def get(self, request):
"""
Handles the redirect from ADFS to our site.
We try to process the passed authorization code and login the user.
Args:
request (django.http.request.HttpRequest): A Django Request object
"""
code = request.GET.get("code")
if... | python | def get(self, request):
"""
Handles the redirect from ADFS to our site.
We try to process the passed authorization code and login the user.
Args:
request (django.http.request.HttpRequest): A Django Request object
"""
code = request.GET.get("code")
if... | [
"def",
"get",
"(",
"self",
",",
"request",
")",
":",
"code",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"\"code\"",
")",
"if",
"not",
"code",
":",
"# Return an error message",
"return",
"render",
"(",
"request",
",",
"'django_auth_adfs/login_failed.html'",
... | Handles the redirect from ADFS to our site.
We try to process the passed authorization code and login the user.
Args:
request (django.http.request.HttpRequest): A Django Request object | [
"Handles",
"the",
"redirect",
"from",
"ADFS",
"to",
"our",
"site",
".",
"We",
"try",
"to",
"process",
"the",
"passed",
"authorization",
"code",
"and",
"login",
"the",
"user",
"."
] | 07197be392724d16a6132b03d9eafb1d634749cf | https://github.com/jobec/django-auth-adfs/blob/07197be392724d16a6132b03d9eafb1d634749cf/django_auth_adfs/views.py#L16-L62 | train |
jobec/django-auth-adfs | django_auth_adfs/rest_framework.py | AdfsAccessTokenAuthentication.authenticate | def authenticate(self, request):
"""
Returns a `User` if a correct access token has been supplied
in the Authorization header. Otherwise returns `None`.
"""
auth = get_authorization_header(request).split()
if not auth or auth[0].lower() != b'bearer':
return ... | python | def authenticate(self, request):
"""
Returns a `User` if a correct access token has been supplied
in the Authorization header. Otherwise returns `None`.
"""
auth = get_authorization_header(request).split()
if not auth or auth[0].lower() != b'bearer':
return ... | [
"def",
"authenticate",
"(",
"self",
",",
"request",
")",
":",
"auth",
"=",
"get_authorization_header",
"(",
"request",
")",
".",
"split",
"(",
")",
"if",
"not",
"auth",
"or",
"auth",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"!=",
"b'bearer'",
":",
"ret... | Returns a `User` if a correct access token has been supplied
in the Authorization header. Otherwise returns `None`. | [
"Returns",
"a",
"User",
"if",
"a",
"correct",
"access",
"token",
"has",
"been",
"supplied",
"in",
"the",
"Authorization",
"header",
".",
"Otherwise",
"returns",
"None",
"."
] | 07197be392724d16a6132b03d9eafb1d634749cf | https://github.com/jobec/django-auth-adfs/blob/07197be392724d16a6132b03d9eafb1d634749cf/django_auth_adfs/rest_framework.py#L20-L48 | train |
chemlab/chemlab | chemlab/qc/wavefunction.py | molecular_orbital | def molecular_orbital(coords, mocoeffs, gbasis):
'''Return a molecular orbital given the nuclei coordinates, as well as
molecular orbital coefficients and basis set specification as given by the cclib library.
The molecular orbital is represented as a function that takes x, y, z coordinates (in a vec... | python | def molecular_orbital(coords, mocoeffs, gbasis):
'''Return a molecular orbital given the nuclei coordinates, as well as
molecular orbital coefficients and basis set specification as given by the cclib library.
The molecular orbital is represented as a function that takes x, y, z coordinates (in a vec... | [
"def",
"molecular_orbital",
"(",
"coords",
",",
"mocoeffs",
",",
"gbasis",
")",
":",
"# Making a closure",
"def",
"f",
"(",
"x",
",",
"y",
",",
"z",
",",
"coords",
"=",
"coords",
",",
"mocoeffs",
"=",
"mocoeffs",
",",
"gbasis",
"=",
"gbasis",
")",
":",... | Return a molecular orbital given the nuclei coordinates, as well as
molecular orbital coefficients and basis set specification as given by the cclib library.
The molecular orbital is represented as a function that takes x, y, z coordinates (in a vectorized fashion)
and returns a real number. | [
"Return",
"a",
"molecular",
"orbital",
"given",
"the",
"nuclei",
"coordinates",
"as",
"well",
"as",
"molecular",
"orbital",
"coefficients",
"and",
"basis",
"set",
"specification",
"as",
"given",
"by",
"the",
"cclib",
"library",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/qc/wavefunction.py#L4-L18 | train |
chemlab/chemlab | chemlab/qc/wavefunction.py | getbfs | def getbfs(coords, gbasis):
"""Convenience function for both wavefunction and density based on PyQuante Ints.py."""
sym2powerlist = {
'S' : [(0,0,0)],
'P' : [(1,0,0),(0,1,0),(0,0,1)],
'D' : [(2,0,0),(0,2,0),(0,0,2),(1,1,0),(0,1,1),(1,0,1)],
'F' : [(3,0,0),(2,1,0),(2,0,1),(1,2,0)... | python | def getbfs(coords, gbasis):
"""Convenience function for both wavefunction and density based on PyQuante Ints.py."""
sym2powerlist = {
'S' : [(0,0,0)],
'P' : [(1,0,0),(0,1,0),(0,0,1)],
'D' : [(2,0,0),(0,2,0),(0,0,2),(1,1,0),(0,1,1),(1,0,1)],
'F' : [(3,0,0),(2,1,0),(2,0,1),(1,2,0)... | [
"def",
"getbfs",
"(",
"coords",
",",
"gbasis",
")",
":",
"sym2powerlist",
"=",
"{",
"'S'",
":",
"[",
"(",
"0",
",",
"0",
",",
"0",
")",
"]",
",",
"'P'",
":",
"[",
"(",
"1",
",",
"0",
",",
"0",
")",
",",
"(",
"0",
",",
"1",
",",
"0",
")"... | Convenience function for both wavefunction and density based on PyQuante Ints.py. | [
"Convenience",
"function",
"for",
"both",
"wavefunction",
"and",
"density",
"based",
"on",
"PyQuante",
"Ints",
".",
"py",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/qc/wavefunction.py#L21-L43 | train |
chemlab/chemlab | chemlab/qc/one.py | A_term | def A_term(i,r,u,l1,l2,PAx,PBx,CPx,gamma):
"""
THO eq. 2.18
>>> A_term(0,0,0,0,0,0,0,0,1)
1.0
>>> A_term(0,0,0,0,1,1,1,1,1)
1.0
>>> A_term(1,0,0,0,1,1,1,1,1)
-1.0
>>> A_term(0,0,0,1,1,1,1,1,1)
1.0
>>> A_term(1,0,0,1,1,1,1,1,1)
-2.0
>>> A_term(2,0,0,1,1,1,1,1,1)
1... | python | def A_term(i,r,u,l1,l2,PAx,PBx,CPx,gamma):
"""
THO eq. 2.18
>>> A_term(0,0,0,0,0,0,0,0,1)
1.0
>>> A_term(0,0,0,0,1,1,1,1,1)
1.0
>>> A_term(1,0,0,0,1,1,1,1,1)
-1.0
>>> A_term(0,0,0,1,1,1,1,1,1)
1.0
>>> A_term(1,0,0,1,1,1,1,1,1)
-2.0
>>> A_term(2,0,0,1,1,1,1,1,1)
1... | [
"def",
"A_term",
"(",
"i",
",",
"r",
",",
"u",
",",
"l1",
",",
"l2",
",",
"PAx",
",",
"PBx",
",",
"CPx",
",",
"gamma",
")",
":",
"return",
"pow",
"(",
"-",
"1",
",",
"i",
")",
"*",
"binomial_prefactor",
"(",
"i",
",",
"l1",
",",
"l2",
",",
... | THO eq. 2.18
>>> A_term(0,0,0,0,0,0,0,0,1)
1.0
>>> A_term(0,0,0,0,1,1,1,1,1)
1.0
>>> A_term(1,0,0,0,1,1,1,1,1)
-1.0
>>> A_term(0,0,0,1,1,1,1,1,1)
1.0
>>> A_term(1,0,0,1,1,1,1,1,1)
-2.0
>>> A_term(2,0,0,1,1,1,1,1,1)
1.0
>>> A_term(2,0,1,1,1,1,1,1,1)
-0.5
>>> A... | [
"THO",
"eq",
".",
"2",
".",
"18"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/qc/one.py#L203-L226 | train |
chemlab/chemlab | chemlab/qc/one.py | A_array | def A_array(l1,l2,PA,PB,CP,g):
"""
THO eq. 2.18 and 3.1
>>> A_array(0,0,0,0,0,1)
[1.0]
>>> A_array(0,1,1,1,1,1)
[1.0, -1.0]
>>> A_array(1,1,1,1,1,1)
[1.5, -2.5, 1.0]
"""
Imax = l1+l2+1
A = [0]*Imax
for i in range(Imax):
for r in range(int(floor(i/2)+1)):
... | python | def A_array(l1,l2,PA,PB,CP,g):
"""
THO eq. 2.18 and 3.1
>>> A_array(0,0,0,0,0,1)
[1.0]
>>> A_array(0,1,1,1,1,1)
[1.0, -1.0]
>>> A_array(1,1,1,1,1,1)
[1.5, -2.5, 1.0]
"""
Imax = l1+l2+1
A = [0]*Imax
for i in range(Imax):
for r in range(int(floor(i/2)+1)):
... | [
"def",
"A_array",
"(",
"l1",
",",
"l2",
",",
"PA",
",",
"PB",
",",
"CP",
",",
"g",
")",
":",
"Imax",
"=",
"l1",
"+",
"l2",
"+",
"1",
"A",
"=",
"[",
"0",
"]",
"*",
"Imax",
"for",
"i",
"in",
"range",
"(",
"Imax",
")",
":",
"for",
"r",
"in... | THO eq. 2.18 and 3.1
>>> A_array(0,0,0,0,0,1)
[1.0]
>>> A_array(0,1,1,1,1,1)
[1.0, -1.0]
>>> A_array(1,1,1,1,1,1)
[1.5, -2.5, 1.0] | [
"THO",
"eq",
".",
"2",
".",
"18",
"and",
"3",
".",
"1"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/qc/one.py#L228-L246 | train |
chemlab/chemlab | chemlab/qc/pgbf.py | pgbf._normalize | def _normalize(self):
"Normalize basis function. From THO eq. 2.2"
l,m,n = self.powers
self.norm = np.sqrt(pow(2,2*(l+m+n)+1.5)*
pow(self.exponent,l+m+n+1.5)/
fact2(2*l-1)/fact2(2*m-1)/
fact2(2*n-1)/pow(np.pi,1.5... | python | def _normalize(self):
"Normalize basis function. From THO eq. 2.2"
l,m,n = self.powers
self.norm = np.sqrt(pow(2,2*(l+m+n)+1.5)*
pow(self.exponent,l+m+n+1.5)/
fact2(2*l-1)/fact2(2*m-1)/
fact2(2*n-1)/pow(np.pi,1.5... | [
"def",
"_normalize",
"(",
"self",
")",
":",
"l",
",",
"m",
",",
"n",
"=",
"self",
".",
"powers",
"self",
".",
"norm",
"=",
"np",
".",
"sqrt",
"(",
"pow",
"(",
"2",
",",
"2",
"*",
"(",
"l",
"+",
"m",
"+",
"n",
")",
"+",
"1.5",
")",
"*",
... | Normalize basis function. From THO eq. 2.2 | [
"Normalize",
"basis",
"function",
".",
"From",
"THO",
"eq",
".",
"2",
".",
"2"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/qc/pgbf.py#L77-L84 | train |
chemlab/chemlab | chemlab/mviewer/representations/ballandstick.py | BallAndStickRepresentation.hide | def hide(self, selections):
'''Hide objects in this representation. BallAndStickRepresentation
support selections of atoms and bonds.
To hide the first atom and the first bond you can use the
following code::
from chemlab.mviewer.state import Selection
represent... | python | def hide(self, selections):
'''Hide objects in this representation. BallAndStickRepresentation
support selections of atoms and bonds.
To hide the first atom and the first bond you can use the
following code::
from chemlab.mviewer.state import Selection
represent... | [
"def",
"hide",
"(",
"self",
",",
"selections",
")",
":",
"if",
"'atoms'",
"in",
"selections",
":",
"self",
".",
"hidden_state",
"[",
"'atoms'",
"]",
"=",
"selections",
"[",
"'atoms'",
"]",
"self",
".",
"on_atom_hidden_changed",
"(",
")",
"if",
"'bonds'",
... | Hide objects in this representation. BallAndStickRepresentation
support selections of atoms and bonds.
To hide the first atom and the first bond you can use the
following code::
from chemlab.mviewer.state import Selection
representation.hide({'atoms': Selection([0], sys... | [
"Hide",
"objects",
"in",
"this",
"representation",
".",
"BallAndStickRepresentation",
"support",
"selections",
"of",
"atoms",
"and",
"bonds",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/mviewer/representations/ballandstick.py#L279-L310 | train |
chemlab/chemlab | chemlab/mviewer/representations/ballandstick.py | BallAndStickRepresentation.change_radius | def change_radius(self, selections, value):
'''Change the radius of each atom by a certain value
'''
if 'atoms' in selections:
atms = selections['atoms'].mask
if value is None:
self.radii_state.array[atms] = [vdw_radii.get(t) * 0.3 for t in self.... | python | def change_radius(self, selections, value):
'''Change the radius of each atom by a certain value
'''
if 'atoms' in selections:
atms = selections['atoms'].mask
if value is None:
self.radii_state.array[atms] = [vdw_radii.get(t) * 0.3 for t in self.... | [
"def",
"change_radius",
"(",
"self",
",",
"selections",
",",
"value",
")",
":",
"if",
"'atoms'",
"in",
"selections",
":",
"atms",
"=",
"selections",
"[",
"'atoms'",
"]",
".",
"mask",
"if",
"value",
"is",
"None",
":",
"self",
".",
"radii_state",
".",
"a... | Change the radius of each atom by a certain value | [
"Change",
"the",
"radius",
"of",
"each",
"atom",
"by",
"a",
"certain",
"value"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/mviewer/representations/ballandstick.py#L326-L337 | train |
chemlab/chemlab | chemlab/graphics/qt/qchemlabwidget.py | QChemlabWidget.paintGL | def paintGL(self):
'''GL function called each time a frame is drawn'''
if self.post_processing:
# Render to the first framebuffer
glBindFramebuffer(GL_FRAMEBUFFER, self.fb0)
glViewport(0, 0, self.width(), self.height())
status = glCheckFramebufferStatus(... | python | def paintGL(self):
'''GL function called each time a frame is drawn'''
if self.post_processing:
# Render to the first framebuffer
glBindFramebuffer(GL_FRAMEBUFFER, self.fb0)
glViewport(0, 0, self.width(), self.height())
status = glCheckFramebufferStatus(... | [
"def",
"paintGL",
"(",
"self",
")",
":",
"if",
"self",
".",
"post_processing",
":",
"# Render to the first framebuffer",
"glBindFramebuffer",
"(",
"GL_FRAMEBUFFER",
",",
"self",
".",
"fb0",
")",
"glViewport",
"(",
"0",
",",
"0",
",",
"self",
".",
"width",
"(... | GL function called each time a frame is drawn | [
"GL",
"function",
"called",
"each",
"time",
"a",
"frame",
"is",
"drawn"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/qt/qchemlabwidget.py#L153-L217 | train |
chemlab/chemlab | chemlab/graphics/qt/qchemlabwidget.py | QChemlabWidget.toimage | def toimage(self, width=None, height=None):
'''Return the current scene as a PIL Image.
**Example**
You can build your molecular viewer as usual and dump an image
at any resolution supported by the video card (up to the
memory limits)::
v = QtViewer()
... | python | def toimage(self, width=None, height=None):
'''Return the current scene as a PIL Image.
**Example**
You can build your molecular viewer as usual and dump an image
at any resolution supported by the video card (up to the
memory limits)::
v = QtViewer()
... | [
"def",
"toimage",
"(",
"self",
",",
"width",
"=",
"None",
",",
"height",
"=",
"None",
")",
":",
"from",
".",
"postprocessing",
"import",
"NoEffect",
"effect",
"=",
"NoEffect",
"(",
"self",
")",
"self",
".",
"post_processing",
".",
"append",
"(",
"effect"... | Return the current scene as a PIL Image.
**Example**
You can build your molecular viewer as usual and dump an image
at any resolution supported by the video card (up to the
memory limits)::
v = QtViewer()
# Add the renderers
v.add_renderer(...)
... | [
"Return",
"the",
"current",
"scene",
"as",
"a",
"PIL",
"Image",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/qt/qchemlabwidget.py#L318-L377 | train |
chemlab/chemlab | chemlab/md/ewald.py | _real | def _real(coords1, charges1, coords2, charges2, rcut, alpha, box):
"""Calculate ewald real part. Box has to be a cuboidal box you should
transform any other box shape to a cuboidal box before using this.
"""
n = coords1.shape[0]
m = coords2.shape[0]
# Unit vectors
a = box[0]
b = box... | python | def _real(coords1, charges1, coords2, charges2, rcut, alpha, box):
"""Calculate ewald real part. Box has to be a cuboidal box you should
transform any other box shape to a cuboidal box before using this.
"""
n = coords1.shape[0]
m = coords2.shape[0]
# Unit vectors
a = box[0]
b = box... | [
"def",
"_real",
"(",
"coords1",
",",
"charges1",
",",
"coords2",
",",
"charges2",
",",
"rcut",
",",
"alpha",
",",
"box",
")",
":",
"n",
"=",
"coords1",
".",
"shape",
"[",
"0",
"]",
"m",
"=",
"coords2",
".",
"shape",
"[",
"0",
"]",
"# Unit vectors",... | Calculate ewald real part. Box has to be a cuboidal box you should
transform any other box shape to a cuboidal box before using this. | [
"Calculate",
"ewald",
"real",
"part",
".",
"Box",
"has",
"to",
"be",
"a",
"cuboidal",
"box",
"you",
"should",
"transform",
"any",
"other",
"box",
"shape",
"to",
"a",
"cuboidal",
"box",
"before",
"using",
"this",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/md/ewald.py#L19-L57 | train |
chemlab/chemlab | chemlab/md/ewald.py | _reciprocal | def _reciprocal(coords1, charges1, coords2, charges2, kmax, kappa, box):
"""Calculate ewald reciprocal part. Box has to be a cuboidal box you should
transform any other box shape to a cuboidal box before using this.
"""
n = coords1.shape[0]
m = coords2.shape[0]
result = np.zeros(n, dtype=np... | python | def _reciprocal(coords1, charges1, coords2, charges2, kmax, kappa, box):
"""Calculate ewald reciprocal part. Box has to be a cuboidal box you should
transform any other box shape to a cuboidal box before using this.
"""
n = coords1.shape[0]
m = coords2.shape[0]
result = np.zeros(n, dtype=np... | [
"def",
"_reciprocal",
"(",
"coords1",
",",
"charges1",
",",
"coords2",
",",
"charges2",
",",
"kmax",
",",
"kappa",
",",
"box",
")",
":",
"n",
"=",
"coords1",
".",
"shape",
"[",
"0",
"]",
"m",
"=",
"coords2",
".",
"shape",
"[",
"0",
"]",
"result",
... | Calculate ewald reciprocal part. Box has to be a cuboidal box you should
transform any other box shape to a cuboidal box before using this. | [
"Calculate",
"ewald",
"reciprocal",
"part",
".",
"Box",
"has",
"to",
"be",
"a",
"cuboidal",
"box",
"you",
"should",
"transform",
"any",
"other",
"box",
"shape",
"to",
"a",
"cuboidal",
"box",
"before",
"using",
"this",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/md/ewald.py#L80-L128 | train |
chemlab/chemlab | chemlab/graphics/renderers/cylinder.py | CylinderRenderer.update_bounds | def update_bounds(self, bounds):
'''Update cylinders start and end positions
'''
starts = bounds[:,0,:]
ends = bounds[:,1,:]
self.bounds = bounds
self.lengths = np.sqrt(((ends - starts)**2).sum(axis=1))
vertices, normals, colors = self._process_refere... | python | def update_bounds(self, bounds):
'''Update cylinders start and end positions
'''
starts = bounds[:,0,:]
ends = bounds[:,1,:]
self.bounds = bounds
self.lengths = np.sqrt(((ends - starts)**2).sum(axis=1))
vertices, normals, colors = self._process_refere... | [
"def",
"update_bounds",
"(",
"self",
",",
"bounds",
")",
":",
"starts",
"=",
"bounds",
"[",
":",
",",
"0",
",",
":",
"]",
"ends",
"=",
"bounds",
"[",
":",
",",
"1",
",",
":",
"]",
"self",
".",
"bounds",
"=",
"bounds",
"self",
".",
"lengths",
"=... | Update cylinders start and end positions | [
"Update",
"cylinders",
"start",
"and",
"end",
"positions"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/renderers/cylinder.py#L72-L85 | train |
chemlab/chemlab | chemlab/io/trajectory.py | make_trajectory | def make_trajectory(first, filename, restart=False):
'''Factory function to easily create a trajectory object'''
mode = 'w'
if restart:
mode = 'a'
return Trajectory(first, filename, mode) | python | def make_trajectory(first, filename, restart=False):
'''Factory function to easily create a trajectory object'''
mode = 'w'
if restart:
mode = 'a'
return Trajectory(first, filename, mode) | [
"def",
"make_trajectory",
"(",
"first",
",",
"filename",
",",
"restart",
"=",
"False",
")",
":",
"mode",
"=",
"'w'",
"if",
"restart",
":",
"mode",
"=",
"'a'",
"return",
"Trajectory",
"(",
"first",
",",
"filename",
",",
"mode",
")"
] | Factory function to easily create a trajectory object | [
"Factory",
"function",
"to",
"easily",
"create",
"a",
"trajectory",
"object"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/io/trajectory.py#L60-L67 | train |
chemlab/chemlab | chemlab/db/utils.py | InsensitiveDict.has_key | def has_key(self, key):
"""Case insensitive test whether 'key' exists."""
k = self._lowerOrReturn(key)
return k in self.data | python | def has_key(self, key):
"""Case insensitive test whether 'key' exists."""
k = self._lowerOrReturn(key)
return k in self.data | [
"def",
"has_key",
"(",
"self",
",",
"key",
")",
":",
"k",
"=",
"self",
".",
"_lowerOrReturn",
"(",
"key",
")",
"return",
"k",
"in",
"self",
".",
"data"
] | Case insensitive test whether 'key' exists. | [
"Case",
"insensitive",
"test",
"whether",
"key",
"exists",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/db/utils.py#L44-L47 | train |
chemlab/chemlab | chemlab/graphics/renderers/sphere.py | SphereRenderer.update_positions | def update_positions(self, positions):
'''Update the sphere positions.
'''
sphs_verts = self.sphs_verts_radii.copy()
sphs_verts += positions.reshape(self.n_spheres, 1, 3)
self.tr.update_vertices(sphs_verts)
self.poslist = positions | python | def update_positions(self, positions):
'''Update the sphere positions.
'''
sphs_verts = self.sphs_verts_radii.copy()
sphs_verts += positions.reshape(self.n_spheres, 1, 3)
self.tr.update_vertices(sphs_verts)
self.poslist = positions | [
"def",
"update_positions",
"(",
"self",
",",
"positions",
")",
":",
"sphs_verts",
"=",
"self",
".",
"sphs_verts_radii",
".",
"copy",
"(",
")",
"sphs_verts",
"+=",
"positions",
".",
"reshape",
"(",
"self",
".",
"n_spheres",
",",
"1",
",",
"3",
")",
"self"... | Update the sphere positions. | [
"Update",
"the",
"sphere",
"positions",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/renderers/sphere.py#L86-L93 | train |
chemlab/chemlab | chemlab/core/serialization.py | isnamedtuple | def isnamedtuple(obj):
"""Heuristic check if an object is a namedtuple."""
return isinstance(obj, tuple) \
and hasattr(obj, "_fields") \
and hasattr(obj, "_asdict") \
and callable(obj._asdict) | python | def isnamedtuple(obj):
"""Heuristic check if an object is a namedtuple."""
return isinstance(obj, tuple) \
and hasattr(obj, "_fields") \
and hasattr(obj, "_asdict") \
and callable(obj._asdict) | [
"def",
"isnamedtuple",
"(",
"obj",
")",
":",
"return",
"isinstance",
"(",
"obj",
",",
"tuple",
")",
"and",
"hasattr",
"(",
"obj",
",",
"\"_fields\"",
")",
"and",
"hasattr",
"(",
"obj",
",",
"\"_asdict\"",
")",
"and",
"callable",
"(",
"obj",
".",
"_asdi... | Heuristic check if an object is a namedtuple. | [
"Heuristic",
"check",
"if",
"an",
"object",
"is",
"a",
"namedtuple",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/serialization.py#L10-L15 | train |
chemlab/chemlab | chemlab/md/analysis.py | running_coordination_number | def running_coordination_number(coordinates_a, coordinates_b, periodic,
binsize=0.002, cutoff=1.5):
"""This is the cumulative radial distribution
function, also called running coordination number"""
x, y = rdf(coordinates_a,
coordinates_b,
peri... | python | def running_coordination_number(coordinates_a, coordinates_b, periodic,
binsize=0.002, cutoff=1.5):
"""This is the cumulative radial distribution
function, also called running coordination number"""
x, y = rdf(coordinates_a,
coordinates_b,
peri... | [
"def",
"running_coordination_number",
"(",
"coordinates_a",
",",
"coordinates_b",
",",
"periodic",
",",
"binsize",
"=",
"0.002",
",",
"cutoff",
"=",
"1.5",
")",
":",
"x",
",",
"y",
"=",
"rdf",
"(",
"coordinates_a",
",",
"coordinates_b",
",",
"periodic",
"=",... | This is the cumulative radial distribution
function, also called running coordination number | [
"This",
"is",
"the",
"cumulative",
"radial",
"distribution",
"function",
"also",
"called",
"running",
"coordination",
"number"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/md/analysis.py#L59-L71 | train |
chemlab/chemlab | chemlab/graphics/renderers/line.py | LineRenderer.update_colors | def update_colors(self, colors):
"""Update the colors"""
colors = np.array(colors, dtype=np.uint8)
self._vbo_c.set_data(colors)
self._vbo_c.unbind() | python | def update_colors(self, colors):
"""Update the colors"""
colors = np.array(colors, dtype=np.uint8)
self._vbo_c.set_data(colors)
self._vbo_c.unbind() | [
"def",
"update_colors",
"(",
"self",
",",
"colors",
")",
":",
"colors",
"=",
"np",
".",
"array",
"(",
"colors",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
"self",
".",
"_vbo_c",
".",
"set_data",
"(",
"colors",
")",
"self",
".",
"_vbo_c",
".",
"unb... | Update the colors | [
"Update",
"the",
"colors"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/renderers/line.py#L71-L76 | train |
chemlab/chemlab | chemlab/mviewer/api/core.py | frames | def frames(skip=1):
'''Useful command to iterate on the trajectory frames. It can be
used in a for loop.
::
for i in frames():
coords = current_trajectory()[i]
# Do operation on coords
You can use the option *skip* to take every i :sup:`th` frame.
'''
... | python | def frames(skip=1):
'''Useful command to iterate on the trajectory frames. It can be
used in a for loop.
::
for i in frames():
coords = current_trajectory()[i]
# Do operation on coords
You can use the option *skip* to take every i :sup:`th` frame.
'''
... | [
"def",
"frames",
"(",
"skip",
"=",
"1",
")",
":",
"from",
"PyQt4",
"import",
"QtGui",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"viewer",
".",
"traj_controls",
".",
"max_index",
",",
"skip",
")",
":",
"viewer",
".",
"traj_controls",
".",
"goto_frame",
... | Useful command to iterate on the trajectory frames. It can be
used in a for loop.
::
for i in frames():
coords = current_trajectory()[i]
# Do operation on coords
You can use the option *skip* to take every i :sup:`th` frame. | [
"Useful",
"command",
"to",
"iterate",
"on",
"the",
"trajectory",
"frames",
".",
"It",
"can",
"be",
"used",
"in",
"a",
"for",
"loop",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/mviewer/api/core.py#L59-L77 | train |
chemlab/chemlab | chemlab/mviewer/api/display.py | display_system | def display_system(system, autozoom=True):
'''Display a `~chemlab.core.System` instance at screen'''
viewer.clear()
viewer.add_representation(BallAndStickRepresentation, system)
if autozoom:
autozoom_()
viewer.update()
msg(str(system)) | python | def display_system(system, autozoom=True):
'''Display a `~chemlab.core.System` instance at screen'''
viewer.clear()
viewer.add_representation(BallAndStickRepresentation, system)
if autozoom:
autozoom_()
viewer.update()
msg(str(system)) | [
"def",
"display_system",
"(",
"system",
",",
"autozoom",
"=",
"True",
")",
":",
"viewer",
".",
"clear",
"(",
")",
"viewer",
".",
"add_representation",
"(",
"BallAndStickRepresentation",
",",
"system",
")",
"if",
"autozoom",
":",
"autozoom_",
"(",
")",
"viewe... | Display a `~chemlab.core.System` instance at screen | [
"Display",
"a",
"~chemlab",
".",
"core",
".",
"System",
"instance",
"at",
"screen"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/mviewer/api/display.py#L13-L22 | train |
chemlab/chemlab | chemlab/mviewer/api/display.py | display_molecule | def display_molecule(mol, autozoom=True):
'''Display a `~chemlab.core.Molecule` instance in the viewer.
This function wraps the molecule in a system before displaying
it.
'''
s = System([mol])
display_system(s, autozoom=True) | python | def display_molecule(mol, autozoom=True):
'''Display a `~chemlab.core.Molecule` instance in the viewer.
This function wraps the molecule in a system before displaying
it.
'''
s = System([mol])
display_system(s, autozoom=True) | [
"def",
"display_molecule",
"(",
"mol",
",",
"autozoom",
"=",
"True",
")",
":",
"s",
"=",
"System",
"(",
"[",
"mol",
"]",
")",
"display_system",
"(",
"s",
",",
"autozoom",
"=",
"True",
")"
] | Display a `~chemlab.core.Molecule` instance in the viewer.
This function wraps the molecule in a system before displaying
it. | [
"Display",
"a",
"~chemlab",
".",
"core",
".",
"Molecule",
"instance",
"in",
"the",
"viewer",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/mviewer/api/display.py#L24-L32 | train |
chemlab/chemlab | chemlab/mviewer/api/display.py | load_molecule | def load_molecule(name, format=None):
'''Read a `~chemlab.core.Molecule` from a file.
.. seealso:: `chemlab.io.datafile`
'''
mol = datafile(name, format=format).read('molecule')
display_system(System([mol])) | python | def load_molecule(name, format=None):
'''Read a `~chemlab.core.Molecule` from a file.
.. seealso:: `chemlab.io.datafile`
'''
mol = datafile(name, format=format).read('molecule')
display_system(System([mol])) | [
"def",
"load_molecule",
"(",
"name",
",",
"format",
"=",
"None",
")",
":",
"mol",
"=",
"datafile",
"(",
"name",
",",
"format",
"=",
"format",
")",
".",
"read",
"(",
"'molecule'",
")",
"display_system",
"(",
"System",
"(",
"[",
"mol",
"]",
")",
")"
] | Read a `~chemlab.core.Molecule` from a file.
.. seealso:: `chemlab.io.datafile` | [
"Read",
"a",
"~chemlab",
".",
"core",
".",
"Molecule",
"from",
"a",
"file",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/mviewer/api/display.py#L54-L61 | train |
chemlab/chemlab | chemlab/mviewer/api/display.py | write_system | def write_system(filename, format=None):
'''Write the system currently displayed to a file.'''
datafile(filename, format=format, mode='w').write('system',
current_system()) | python | def write_system(filename, format=None):
'''Write the system currently displayed to a file.'''
datafile(filename, format=format, mode='w').write('system',
current_system()) | [
"def",
"write_system",
"(",
"filename",
",",
"format",
"=",
"None",
")",
":",
"datafile",
"(",
"filename",
",",
"format",
"=",
"format",
",",
"mode",
"=",
"'w'",
")",
".",
"write",
"(",
"'system'",
",",
"current_system",
"(",
")",
")"
] | Write the system currently displayed to a file. | [
"Write",
"the",
"system",
"currently",
"displayed",
"to",
"a",
"file",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/mviewer/api/display.py#L102-L105 | train |
chemlab/chemlab | chemlab/mviewer/api/display.py | write_molecule | def write_molecule(filename, format=None):
'''Write the system displayed in a file as a molecule.'''
datafile(filename, format=format,
mode='w').write('molecule',current_system()) | python | def write_molecule(filename, format=None):
'''Write the system displayed in a file as a molecule.'''
datafile(filename, format=format,
mode='w').write('molecule',current_system()) | [
"def",
"write_molecule",
"(",
"filename",
",",
"format",
"=",
"None",
")",
":",
"datafile",
"(",
"filename",
",",
"format",
"=",
"format",
",",
"mode",
"=",
"'w'",
")",
".",
"write",
"(",
"'molecule'",
",",
"current_system",
"(",
")",
")"
] | Write the system displayed in a file as a molecule. | [
"Write",
"the",
"system",
"displayed",
"in",
"a",
"file",
"as",
"a",
"molecule",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/mviewer/api/display.py#L107-L110 | train |
chemlab/chemlab | chemlab/mviewer/api/display.py | load_trajectory | def load_trajectory(name, skip=1, format=None):
'''Load a trajectory file into chemlab. You should call this
command after you load a `~chemlab.core.System` through
load_system or load_remote_system.
'''
df = datafile(name, format=format)
dt, coords = df.read('trajectory', skip=skip)
boxes ... | python | def load_trajectory(name, skip=1, format=None):
'''Load a trajectory file into chemlab. You should call this
command after you load a `~chemlab.core.System` through
load_system or load_remote_system.
'''
df = datafile(name, format=format)
dt, coords = df.read('trajectory', skip=skip)
boxes ... | [
"def",
"load_trajectory",
"(",
"name",
",",
"skip",
"=",
"1",
",",
"format",
"=",
"None",
")",
":",
"df",
"=",
"datafile",
"(",
"name",
",",
"format",
"=",
"format",
")",
"dt",
",",
"coords",
"=",
"df",
".",
"read",
"(",
"'trajectory'",
",",
"skip"... | Load a trajectory file into chemlab. You should call this
command after you load a `~chemlab.core.System` through
load_system or load_remote_system. | [
"Load",
"a",
"trajectory",
"file",
"into",
"chemlab",
".",
"You",
"should",
"call",
"this",
"command",
"after",
"you",
"load",
"a",
"~chemlab",
".",
"core",
".",
"System",
"through",
"load_system",
"or",
"load_remote_system",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/mviewer/api/display.py#L128-L158 | train |
chemlab/chemlab | chemlab/core/system.py | System.from_arrays | def from_arrays(cls, **kwargs):
'''Initialize a System from its constituent arrays. It is the
fastest way to initialize a System, well suited for
reading one or more big System from data files.
**Parameters**
The following parameters are required:
- ty... | python | def from_arrays(cls, **kwargs):
'''Initialize a System from its constituent arrays. It is the
fastest way to initialize a System, well suited for
reading one or more big System from data files.
**Parameters**
The following parameters are required:
- ty... | [
"def",
"from_arrays",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'mol_indices'",
"in",
"kwargs",
":",
"raise",
"DeprecationWarning",
"(",
"'The mol_indices argument is deprecated, use maps instead. (See from_arrays docstring)'",
")",
"return",
"super",
"(",
"... | Initialize a System from its constituent arrays. It is the
fastest way to initialize a System, well suited for
reading one or more big System from data files.
**Parameters**
The following parameters are required:
- type_array: An array of the types
- m... | [
"Initialize",
"a",
"System",
"from",
"its",
"constituent",
"arrays",
".",
"It",
"is",
"the",
"fastest",
"way",
"to",
"initialize",
"a",
"System",
"well",
"suited",
"for",
"reading",
"one",
"or",
"more",
"big",
"System",
"from",
"data",
"files",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/system.py#L145-L188 | train |
chemlab/chemlab | chemlab/core/system.py | System.minimum_image | def minimum_image(self):
"""Align the system according to the minimum image convention"""
if self.box_vectors is None:
raise ValueError('No periodic vectors defined')
else:
self.r_array = minimum_image(self.r_array, self.box_vectors.diagonal())
return sel... | python | def minimum_image(self):
"""Align the system according to the minimum image convention"""
if self.box_vectors is None:
raise ValueError('No periodic vectors defined')
else:
self.r_array = minimum_image(self.r_array, self.box_vectors.diagonal())
return sel... | [
"def",
"minimum_image",
"(",
"self",
")",
":",
"if",
"self",
".",
"box_vectors",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'No periodic vectors defined'",
")",
"else",
":",
"self",
".",
"r_array",
"=",
"minimum_image",
"(",
"self",
".",
"r_array",
",",... | Align the system according to the minimum image convention | [
"Align",
"the",
"system",
"according",
"to",
"the",
"minimum",
"image",
"convention"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/system.py#L196-L203 | train |
chemlab/chemlab | chemlab/core/system.py | System.where | def where(self, within_of=None, inplace=False, **kwargs):
"""Return indices that met the conditions"""
masks = super(System, self).where(inplace=inplace, **kwargs)
def index_to_mask(index, n):
val = np.zeros(n, dtype='bool')
val[index] = True
return v... | python | def where(self, within_of=None, inplace=False, **kwargs):
"""Return indices that met the conditions"""
masks = super(System, self).where(inplace=inplace, **kwargs)
def index_to_mask(index, n):
val = np.zeros(n, dtype='bool')
val[index] = True
return v... | [
"def",
"where",
"(",
"self",
",",
"within_of",
"=",
"None",
",",
"inplace",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"masks",
"=",
"super",
"(",
"System",
",",
"self",
")",
".",
"where",
"(",
"inplace",
"=",
"inplace",
",",
"*",
"*",
"kwa... | Return indices that met the conditions | [
"Return",
"indices",
"that",
"met",
"the",
"conditions"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/system.py#L252-L284 | train |
chemlab/chemlab | chemlab/qc/utils.py | _gser | def _gser(a,x):
"Series representation of Gamma. NumRec sect 6.1."
ITMAX=100
EPS=3.e-7
gln=lgamma(a)
assert(x>=0),'x < 0 in gser'
if x == 0 : return 0,gln
ap = a
delt = sum = 1./a
for i in range(ITMAX):
ap=ap+1.
delt=delt*x/ap
sum=sum+delt
if abs(del... | python | def _gser(a,x):
"Series representation of Gamma. NumRec sect 6.1."
ITMAX=100
EPS=3.e-7
gln=lgamma(a)
assert(x>=0),'x < 0 in gser'
if x == 0 : return 0,gln
ap = a
delt = sum = 1./a
for i in range(ITMAX):
ap=ap+1.
delt=delt*x/ap
sum=sum+delt
if abs(del... | [
"def",
"_gser",
"(",
"a",
",",
"x",
")",
":",
"ITMAX",
"=",
"100",
"EPS",
"=",
"3.e-7",
"gln",
"=",
"lgamma",
"(",
"a",
")",
"assert",
"(",
"x",
">=",
"0",
")",
",",
"'x < 0 in gser'",
"if",
"x",
"==",
"0",
":",
"return",
"0",
",",
"gln",
"ap... | Series representation of Gamma. NumRec sect 6.1. | [
"Series",
"representation",
"of",
"Gamma",
".",
"NumRec",
"sect",
"6",
".",
"1",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/qc/utils.py#L86-L105 | train |
chemlab/chemlab | chemlab/qc/utils.py | _gcf | def _gcf(a,x):
"Continued fraction representation of Gamma. NumRec sect 6.1"
ITMAX=100
EPS=3.e-7
FPMIN=1.e-30
gln=lgamma(a)
b=x+1.-a
c=1./FPMIN
d=1./b
h=d
for i in range(1,ITMAX+1):
an=-i*(i-a)
b=b+2.
d=an*d+b
if abs(d) < FPMIN: d=FPMIN
c=... | python | def _gcf(a,x):
"Continued fraction representation of Gamma. NumRec sect 6.1"
ITMAX=100
EPS=3.e-7
FPMIN=1.e-30
gln=lgamma(a)
b=x+1.-a
c=1./FPMIN
d=1./b
h=d
for i in range(1,ITMAX+1):
an=-i*(i-a)
b=b+2.
d=an*d+b
if abs(d) < FPMIN: d=FPMIN
c=... | [
"def",
"_gcf",
"(",
"a",
",",
"x",
")",
":",
"ITMAX",
"=",
"100",
"EPS",
"=",
"3.e-7",
"FPMIN",
"=",
"1.e-30",
"gln",
"=",
"lgamma",
"(",
"a",
")",
"b",
"=",
"x",
"+",
"1.",
"-",
"a",
"c",
"=",
"1.",
"/",
"FPMIN",
"d",
"=",
"1.",
"/",
"b"... | Continued fraction representation of Gamma. NumRec sect 6.1 | [
"Continued",
"fraction",
"representation",
"of",
"Gamma",
".",
"NumRec",
"sect",
"6",
".",
"1"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/qc/utils.py#L107-L132 | train |
chemlab/chemlab | chemlab/qc/utils.py | dmat | def dmat(c,nocc):
"Form the density matrix from the first nocc orbitals of c"
return np.dot(c[:,:nocc],c[:,:nocc].T) | python | def dmat(c,nocc):
"Form the density matrix from the first nocc orbitals of c"
return np.dot(c[:,:nocc],c[:,:nocc].T) | [
"def",
"dmat",
"(",
"c",
",",
"nocc",
")",
":",
"return",
"np",
".",
"dot",
"(",
"c",
"[",
":",
",",
":",
"nocc",
"]",
",",
"c",
"[",
":",
",",
":",
"nocc",
"]",
".",
"T",
")"
] | Form the density matrix from the first nocc orbitals of c | [
"Form",
"the",
"density",
"matrix",
"from",
"the",
"first",
"nocc",
"orbitals",
"of",
"c"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/qc/utils.py#L138-L140 | train |
chemlab/chemlab | chemlab/qc/utils.py | geigh | def geigh(H,S):
"Solve the generalized eigensystem Hc = ESc"
A = cholorth(S)
E,U = np.linalg.eigh(simx(H,A))
return E,np.dot(A,U) | python | def geigh(H,S):
"Solve the generalized eigensystem Hc = ESc"
A = cholorth(S)
E,U = np.linalg.eigh(simx(H,A))
return E,np.dot(A,U) | [
"def",
"geigh",
"(",
"H",
",",
"S",
")",
":",
"A",
"=",
"cholorth",
"(",
"S",
")",
"E",
",",
"U",
"=",
"np",
".",
"linalg",
".",
"eigh",
"(",
"simx",
"(",
"H",
",",
"A",
")",
")",
"return",
"E",
",",
"np",
".",
"dot",
"(",
"A",
",",
"U"... | Solve the generalized eigensystem Hc = ESc | [
"Solve",
"the",
"generalized",
"eigensystem",
"Hc",
"=",
"ESc"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/qc/utils.py#L168-L172 | train |
chemlab/chemlab | chemlab/utils/neighbors.py | _check_periodic | def _check_periodic(periodic):
'''Validate periodic input'''
periodic = np.array(periodic)
# If it is a matrix
if len(periodic.shape) == 2:
assert periodic.shape[0] == periodic.shape[1], 'periodic shoud be a square matrix or a flat array'
return np.diag(periodic)
elif len(periodic.s... | python | def _check_periodic(periodic):
'''Validate periodic input'''
periodic = np.array(periodic)
# If it is a matrix
if len(periodic.shape) == 2:
assert periodic.shape[0] == periodic.shape[1], 'periodic shoud be a square matrix or a flat array'
return np.diag(periodic)
elif len(periodic.s... | [
"def",
"_check_periodic",
"(",
"periodic",
")",
":",
"periodic",
"=",
"np",
".",
"array",
"(",
"periodic",
")",
"# If it is a matrix",
"if",
"len",
"(",
"periodic",
".",
"shape",
")",
"==",
"2",
":",
"assert",
"periodic",
".",
"shape",
"[",
"0",
"]",
"... | Validate periodic input | [
"Validate",
"periodic",
"input"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/utils/neighbors.py#L19-L30 | train |
chemlab/chemlab | chemlab/utils/neighbors.py | count_neighbors | def count_neighbors(coordinates_a, coordinates_b, periodic, r):
'''Count the neighbours number of neighbors.
:param np.ndarray coordinates_a: Either an array of coordinates of shape (N,3)
or a single point of shape (3,)
:param np.ndarray coordinates_b: Same as coordinat... | python | def count_neighbors(coordinates_a, coordinates_b, periodic, r):
'''Count the neighbours number of neighbors.
:param np.ndarray coordinates_a: Either an array of coordinates of shape (N,3)
or a single point of shape (3,)
:param np.ndarray coordinates_b: Same as coordinat... | [
"def",
"count_neighbors",
"(",
"coordinates_a",
",",
"coordinates_b",
",",
"periodic",
",",
"r",
")",
":",
"indices",
"=",
"nearest_neighbors",
"(",
"coordinates_a",
",",
"coordinates_b",
",",
"periodic",
",",
"r",
"=",
"r",
")",
"[",
"0",
"]",
"if",
"len"... | Count the neighbours number of neighbors.
:param np.ndarray coordinates_a: Either an array of coordinates of shape (N,3)
or a single point of shape (3,)
:param np.ndarray coordinates_b: Same as coordinates_a
:param np.ndarray periodic: Either a matrix of box vectors (3,... | [
"Count",
"the",
"neighbours",
"number",
"of",
"neighbors",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/utils/neighbors.py#L77-L97 | train |
chemlab/chemlab | chemlab/mviewer/api/appeareance.py | change_default_radii | def change_default_radii(def_map):
"""Change the default radii
"""
s = current_system()
rep = current_representation()
rep.radii_state.default = [def_map[t] for t in s.type_array]
rep.radii_state.reset() | python | def change_default_radii(def_map):
"""Change the default radii
"""
s = current_system()
rep = current_representation()
rep.radii_state.default = [def_map[t] for t in s.type_array]
rep.radii_state.reset() | [
"def",
"change_default_radii",
"(",
"def_map",
")",
":",
"s",
"=",
"current_system",
"(",
")",
"rep",
"=",
"current_representation",
"(",
")",
"rep",
".",
"radii_state",
".",
"default",
"=",
"[",
"def_map",
"[",
"t",
"]",
"for",
"t",
"in",
"s",
".",
"t... | Change the default radii | [
"Change",
"the",
"default",
"radii"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/mviewer/api/appeareance.py#L128-L134 | train |
chemlab/chemlab | chemlab/mviewer/api/appeareance.py | add_post_processing | def add_post_processing(effect, **options):
"""Apply a post processing effect.
**Parameters**
effect: string
The effect to be applied, choose between ``ssao``,
``outline``, ``fxaa``, ``gamma``.
**options:
Options used to initialize the effect, check the
:doc:`... | python | def add_post_processing(effect, **options):
"""Apply a post processing effect.
**Parameters**
effect: string
The effect to be applied, choose between ``ssao``,
``outline``, ``fxaa``, ``gamma``.
**options:
Options used to initialize the effect, check the
:doc:`... | [
"def",
"add_post_processing",
"(",
"effect",
",",
"*",
"*",
"options",
")",
":",
"from",
"chemlab",
".",
"graphics",
".",
"postprocessing",
"import",
"SSAOEffect",
",",
"OutlineEffect",
",",
"FXAAEffect",
",",
"GammaCorrectionEffect",
"pp_map",
"=",
"{",
"'ssao'... | Apply a post processing effect.
**Parameters**
effect: string
The effect to be applied, choose between ``ssao``,
``outline``, ``fxaa``, ``gamma``.
**options:
Options used to initialize the effect, check the
:doc:`chemlab.graphics.postprocessing` for a complete
... | [
"Apply",
"a",
"post",
"processing",
"effect",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/mviewer/api/appeareance.py#L192-L229 | train |
chemlab/chemlab | chemlab/core/spacegroup/cell.py | unit_vector | def unit_vector(x):
"""Return a unit vector in the same direction as x."""
y = np.array(x, dtype='float')
return y/norm(y) | python | def unit_vector(x):
"""Return a unit vector in the same direction as x."""
y = np.array(x, dtype='float')
return y/norm(y) | [
"def",
"unit_vector",
"(",
"x",
")",
":",
"y",
"=",
"np",
".",
"array",
"(",
"x",
",",
"dtype",
"=",
"'float'",
")",
"return",
"y",
"/",
"norm",
"(",
"y",
")"
] | Return a unit vector in the same direction as x. | [
"Return",
"a",
"unit",
"vector",
"in",
"the",
"same",
"direction",
"as",
"x",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/spacegroup/cell.py#L13-L16 | train |
chemlab/chemlab | chemlab/core/spacegroup/cell.py | angle | def angle(x, y):
"""Return the angle between vectors a and b in degrees."""
return arccos(dot(x, y)/(norm(x)*norm(y)))*180./pi | python | def angle(x, y):
"""Return the angle between vectors a and b in degrees."""
return arccos(dot(x, y)/(norm(x)*norm(y)))*180./pi | [
"def",
"angle",
"(",
"x",
",",
"y",
")",
":",
"return",
"arccos",
"(",
"dot",
"(",
"x",
",",
"y",
")",
"/",
"(",
"norm",
"(",
"x",
")",
"*",
"norm",
"(",
"y",
")",
")",
")",
"*",
"180.",
"/",
"pi"
] | Return the angle between vectors a and b in degrees. | [
"Return",
"the",
"angle",
"between",
"vectors",
"a",
"and",
"b",
"in",
"degrees",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/spacegroup/cell.py#L19-L21 | train |
chemlab/chemlab | chemlab/core/spacegroup/cell.py | metric_from_cell | def metric_from_cell(cell):
"""Calculates the metric matrix from cell, which is given in the
Cartesian system."""
cell = np.asarray(cell, dtype=float)
return np.dot(cell, cell.T) | python | def metric_from_cell(cell):
"""Calculates the metric matrix from cell, which is given in the
Cartesian system."""
cell = np.asarray(cell, dtype=float)
return np.dot(cell, cell.T) | [
"def",
"metric_from_cell",
"(",
"cell",
")",
":",
"cell",
"=",
"np",
".",
"asarray",
"(",
"cell",
",",
"dtype",
"=",
"float",
")",
"return",
"np",
".",
"dot",
"(",
"cell",
",",
"cell",
".",
"T",
")"
] | Calculates the metric matrix from cell, which is given in the
Cartesian system. | [
"Calculates",
"the",
"metric",
"matrix",
"from",
"cell",
"which",
"is",
"given",
"in",
"the",
"Cartesian",
"system",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/spacegroup/cell.py#L101-L105 | train |
chemlab/chemlab | chemlab/io/datafile.py | add_default_handler | def add_default_handler(ioclass, format, extension=None):
"""Register a new data handler for a given format in
the default handler list.
This is a convenience function used internally to setup the
default handlers. It can be used to add other handlers at
runtime even if this isn't a sug... | python | def add_default_handler(ioclass, format, extension=None):
"""Register a new data handler for a given format in
the default handler list.
This is a convenience function used internally to setup the
default handlers. It can be used to add other handlers at
runtime even if this isn't a sug... | [
"def",
"add_default_handler",
"(",
"ioclass",
",",
"format",
",",
"extension",
"=",
"None",
")",
":",
"if",
"format",
"in",
"_handler_map",
":",
"print",
"(",
"\"Warning: format {} already present.\"",
".",
"format",
"(",
"format",
")",
")",
"_handler_map",
"[",... | Register a new data handler for a given format in
the default handler list.
This is a convenience function used internally to setup the
default handlers. It can be used to add other handlers at
runtime even if this isn't a suggested practice.
**Parameters**
ioclass: IOHandle... | [
"Register",
"a",
"new",
"data",
"handler",
"for",
"a",
"given",
"format",
"in",
"the",
"default",
"handler",
"list",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/io/datafile.py#L39-L66 | train |
chemlab/chemlab | chemlab/utils/pbc.py | minimum_image | def minimum_image(coords, pbc):
"""
Wraps a vector collection of atom positions into the central periodic
image or primary simulation cell.
Parameters
----------
pos : :class:`numpy.ndarray`, (Nx3)
Vector collection of atom positions.
Returns
-------
wrap : :class:`numpy.ndarra... | python | def minimum_image(coords, pbc):
"""
Wraps a vector collection of atom positions into the central periodic
image or primary simulation cell.
Parameters
----------
pos : :class:`numpy.ndarray`, (Nx3)
Vector collection of atom positions.
Returns
-------
wrap : :class:`numpy.ndarra... | [
"def",
"minimum_image",
"(",
"coords",
",",
"pbc",
")",
":",
"# This will do the broadcasting",
"coords",
"=",
"np",
".",
"array",
"(",
"coords",
")",
"pbc",
"=",
"np",
".",
"array",
"(",
"pbc",
")",
"# For each coordinate this number represents which box we are in"... | Wraps a vector collection of atom positions into the central periodic
image or primary simulation cell.
Parameters
----------
pos : :class:`numpy.ndarray`, (Nx3)
Vector collection of atom positions.
Returns
-------
wrap : :class:`numpy.ndarray`, (Nx3)
Returns atomic positions wrapp... | [
"Wraps",
"a",
"vector",
"collection",
"of",
"atom",
"positions",
"into",
"the",
"central",
"periodic",
"image",
"or",
"primary",
"simulation",
"cell",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/utils/pbc.py#L6-L31 | train |
chemlab/chemlab | chemlab/utils/pbc.py | subtract_vectors | def subtract_vectors(a, b, periodic):
'''Returns the difference of the points vec_a - vec_b subject
to the periodic boundary conditions.
'''
r = a - b
delta = np.abs(r)
sign = np.sign(r)
return np.where(delta > 0.5 * periodic, sign * (periodic - delta), r) | python | def subtract_vectors(a, b, periodic):
'''Returns the difference of the points vec_a - vec_b subject
to the periodic boundary conditions.
'''
r = a - b
delta = np.abs(r)
sign = np.sign(r)
return np.where(delta > 0.5 * periodic, sign * (periodic - delta), r) | [
"def",
"subtract_vectors",
"(",
"a",
",",
"b",
",",
"periodic",
")",
":",
"r",
"=",
"a",
"-",
"b",
"delta",
"=",
"np",
".",
"abs",
"(",
"r",
")",
"sign",
"=",
"np",
".",
"sign",
"(",
"r",
")",
"return",
"np",
".",
"where",
"(",
"delta",
">",
... | Returns the difference of the points vec_a - vec_b subject
to the periodic boundary conditions. | [
"Returns",
"the",
"difference",
"of",
"the",
"points",
"vec_a",
"-",
"vec_b",
"subject",
"to",
"the",
"periodic",
"boundary",
"conditions",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/utils/pbc.py#L80-L88 | train |
chemlab/chemlab | chemlab/utils/pbc.py | add_vectors | def add_vectors(vec_a, vec_b, periodic):
'''Returns the sum of the points vec_a - vec_b subject
to the periodic boundary conditions.
'''
moved = noperiodic(np.array([vec_a, vec_b]), periodic)
return vec_a + vec_b | python | def add_vectors(vec_a, vec_b, periodic):
'''Returns the sum of the points vec_a - vec_b subject
to the periodic boundary conditions.
'''
moved = noperiodic(np.array([vec_a, vec_b]), periodic)
return vec_a + vec_b | [
"def",
"add_vectors",
"(",
"vec_a",
",",
"vec_b",
",",
"periodic",
")",
":",
"moved",
"=",
"noperiodic",
"(",
"np",
".",
"array",
"(",
"[",
"vec_a",
",",
"vec_b",
"]",
")",
",",
"periodic",
")",
"return",
"vec_a",
"+",
"vec_b"
] | Returns the sum of the points vec_a - vec_b subject
to the periodic boundary conditions. | [
"Returns",
"the",
"sum",
"of",
"the",
"points",
"vec_a",
"-",
"vec_b",
"subject",
"to",
"the",
"periodic",
"boundary",
"conditions",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/utils/pbc.py#L91-L97 | train |
chemlab/chemlab | chemlab/utils/pbc.py | distance_matrix | def distance_matrix(a, b, periodic):
'''Calculate a distrance matrix between coordinates sets a and b
'''
a = a
b = b[:, np.newaxis]
return periodic_distance(a, b, periodic) | python | def distance_matrix(a, b, periodic):
'''Calculate a distrance matrix between coordinates sets a and b
'''
a = a
b = b[:, np.newaxis]
return periodic_distance(a, b, periodic) | [
"def",
"distance_matrix",
"(",
"a",
",",
"b",
",",
"periodic",
")",
":",
"a",
"=",
"a",
"b",
"=",
"b",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
"return",
"periodic_distance",
"(",
"a",
",",
"b",
",",
"periodic",
")"
] | Calculate a distrance matrix between coordinates sets a and b | [
"Calculate",
"a",
"distrance",
"matrix",
"between",
"coordinates",
"sets",
"a",
"and",
"b"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/utils/pbc.py#L100-L105 | train |
chemlab/chemlab | chemlab/utils/pbc.py | geometric_center | def geometric_center(coords, periodic):
'''Geometric center taking into account periodic boundaries'''
max_vals = periodic
theta = 2 * np.pi * (coords / max_vals)
eps = np.cos(theta) * max_vals / (2 * np.pi)
zeta = np.sin(theta) * max_vals / (2 * np.pi)
eps_avg = eps.sum(axis=0)
zeta_avg = ... | python | def geometric_center(coords, periodic):
'''Geometric center taking into account periodic boundaries'''
max_vals = periodic
theta = 2 * np.pi * (coords / max_vals)
eps = np.cos(theta) * max_vals / (2 * np.pi)
zeta = np.sin(theta) * max_vals / (2 * np.pi)
eps_avg = eps.sum(axis=0)
zeta_avg = ... | [
"def",
"geometric_center",
"(",
"coords",
",",
"periodic",
")",
":",
"max_vals",
"=",
"periodic",
"theta",
"=",
"2",
"*",
"np",
".",
"pi",
"*",
"(",
"coords",
"/",
"max_vals",
")",
"eps",
"=",
"np",
".",
"cos",
"(",
"theta",
")",
"*",
"max_vals",
"... | Geometric center taking into account periodic boundaries | [
"Geometric",
"center",
"taking",
"into",
"account",
"periodic",
"boundaries"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/utils/pbc.py#L123-L134 | train |
chemlab/chemlab | chemlab/utils/pbc.py | radius_of_gyration | def radius_of_gyration(coords, periodic):
'''Calculate the square root of the mean distance squared from the center of gravity.
'''
gc = geometric_center(coords, periodic)
return (periodic_distance(coords, gc, periodic) ** 2).sum() / len(coords) | python | def radius_of_gyration(coords, periodic):
'''Calculate the square root of the mean distance squared from the center of gravity.
'''
gc = geometric_center(coords, periodic)
return (periodic_distance(coords, gc, periodic) ** 2).sum() / len(coords) | [
"def",
"radius_of_gyration",
"(",
"coords",
",",
"periodic",
")",
":",
"gc",
"=",
"geometric_center",
"(",
"coords",
",",
"periodic",
")",
"return",
"(",
"periodic_distance",
"(",
"coords",
",",
"gc",
",",
"periodic",
")",
"**",
"2",
")",
".",
"sum",
"("... | Calculate the square root of the mean distance squared from the center of gravity. | [
"Calculate",
"the",
"square",
"root",
"of",
"the",
"mean",
"distance",
"squared",
"from",
"the",
"center",
"of",
"gravity",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/utils/pbc.py#L137-L142 | train |
chemlab/chemlab | chemlab/libs/chemspipy.py | find | def find(query):
""" Search by Name, SMILES, InChI, InChIKey, etc. Returns first 100 Compounds """
assert type(query) == str or type(query) == str, 'query not a string object'
searchurl = 'http://www.chemspider.com/Search.asmx/SimpleSearch?query=%s&token=%s' % (urlquote(query), TOKEN)
response = urlopen... | python | def find(query):
""" Search by Name, SMILES, InChI, InChIKey, etc. Returns first 100 Compounds """
assert type(query) == str or type(query) == str, 'query not a string object'
searchurl = 'http://www.chemspider.com/Search.asmx/SimpleSearch?query=%s&token=%s' % (urlquote(query), TOKEN)
response = urlopen... | [
"def",
"find",
"(",
"query",
")",
":",
"assert",
"type",
"(",
"query",
")",
"==",
"str",
"or",
"type",
"(",
"query",
")",
"==",
"str",
",",
"'query not a string object'",
"searchurl",
"=",
"'http://www.chemspider.com/Search.asmx/SimpleSearch?query=%s&token=%s'",
"%"... | Search by Name, SMILES, InChI, InChIKey, etc. Returns first 100 Compounds | [
"Search",
"by",
"Name",
"SMILES",
"InChI",
"InChIKey",
"etc",
".",
"Returns",
"first",
"100",
"Compounds"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/libs/chemspipy.py#L213-L224 | train |
chemlab/chemlab | chemlab/libs/chemspipy.py | Compound.imageurl | def imageurl(self):
""" Return the URL of a png image of the 2D structure """
if self._imageurl is None:
self._imageurl = 'http://www.chemspider.com/ImagesHandler.ashx?id=%s' % self.csid
return self._imageurl | python | def imageurl(self):
""" Return the URL of a png image of the 2D structure """
if self._imageurl is None:
self._imageurl = 'http://www.chemspider.com/ImagesHandler.ashx?id=%s' % self.csid
return self._imageurl | [
"def",
"imageurl",
"(",
"self",
")",
":",
"if",
"self",
".",
"_imageurl",
"is",
"None",
":",
"self",
".",
"_imageurl",
"=",
"'http://www.chemspider.com/ImagesHandler.ashx?id=%s'",
"%",
"self",
".",
"csid",
"return",
"self",
".",
"_imageurl"
] | Return the URL of a png image of the 2D structure | [
"Return",
"the",
"URL",
"of",
"a",
"png",
"image",
"of",
"the",
"2D",
"structure"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/libs/chemspipy.py#L71-L75 | train |
chemlab/chemlab | chemlab/libs/chemspipy.py | Compound.loadextendedcompoundinfo | def loadextendedcompoundinfo(self):
""" Load extended compound info from the Mass Spec API """
apiurl = 'http://www.chemspider.com/MassSpecAPI.asmx/GetExtendedCompoundInfo?CSID=%s&token=%s' % (self.csid,TOKEN)
response = urlopen(apiurl)
tree = ET.parse(response)
mf = tree.find('{... | python | def loadextendedcompoundinfo(self):
""" Load extended compound info from the Mass Spec API """
apiurl = 'http://www.chemspider.com/MassSpecAPI.asmx/GetExtendedCompoundInfo?CSID=%s&token=%s' % (self.csid,TOKEN)
response = urlopen(apiurl)
tree = ET.parse(response)
mf = tree.find('{... | [
"def",
"loadextendedcompoundinfo",
"(",
"self",
")",
":",
"apiurl",
"=",
"'http://www.chemspider.com/MassSpecAPI.asmx/GetExtendedCompoundInfo?CSID=%s&token=%s'",
"%",
"(",
"self",
".",
"csid",
",",
"TOKEN",
")",
"response",
"=",
"urlopen",
"(",
"apiurl",
")",
"tree",
... | Load extended compound info from the Mass Spec API | [
"Load",
"extended",
"compound",
"info",
"from",
"the",
"Mass",
"Spec",
"API"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/libs/chemspipy.py#L154-L180 | train |
chemlab/chemlab | chemlab/libs/chemspipy.py | Compound.image | def image(self):
""" Return string containing PNG binary image data of 2D structure image """
if self._image is None:
apiurl = 'http://www.chemspider.com/Search.asmx/GetCompoundThumbnail?id=%s&token=%s' % (self.csid,TOKEN)
response = urlopen(apiurl)
tree = ET.parse(re... | python | def image(self):
""" Return string containing PNG binary image data of 2D structure image """
if self._image is None:
apiurl = 'http://www.chemspider.com/Search.asmx/GetCompoundThumbnail?id=%s&token=%s' % (self.csid,TOKEN)
response = urlopen(apiurl)
tree = ET.parse(re... | [
"def",
"image",
"(",
"self",
")",
":",
"if",
"self",
".",
"_image",
"is",
"None",
":",
"apiurl",
"=",
"'http://www.chemspider.com/Search.asmx/GetCompoundThumbnail?id=%s&token=%s'",
"%",
"(",
"self",
".",
"csid",
",",
"TOKEN",
")",
"response",
"=",
"urlopen",
"("... | Return string containing PNG binary image data of 2D structure image | [
"Return",
"string",
"containing",
"PNG",
"binary",
"image",
"data",
"of",
"2D",
"structure",
"image"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/libs/chemspipy.py#L183-L190 | train |
chemlab/chemlab | chemlab/libs/chemspipy.py | Compound.mol | def mol(self):
""" Return record in MOL format """
if self._mol is None:
apiurl = 'http://www.chemspider.com/MassSpecAPI.asmx/GetRecordMol?csid=%s&calc3d=false&token=%s' % (self.csid,TOKEN)
response = urlopen(apiurl)
tree = ET.parse(response)
self._mol = t... | python | def mol(self):
""" Return record in MOL format """
if self._mol is None:
apiurl = 'http://www.chemspider.com/MassSpecAPI.asmx/GetRecordMol?csid=%s&calc3d=false&token=%s' % (self.csid,TOKEN)
response = urlopen(apiurl)
tree = ET.parse(response)
self._mol = t... | [
"def",
"mol",
"(",
"self",
")",
":",
"if",
"self",
".",
"_mol",
"is",
"None",
":",
"apiurl",
"=",
"'http://www.chemspider.com/MassSpecAPI.asmx/GetRecordMol?csid=%s&calc3d=false&token=%s'",
"%",
"(",
"self",
".",
"csid",
",",
"TOKEN",
")",
"response",
"=",
"urlopen... | Return record in MOL format | [
"Return",
"record",
"in",
"MOL",
"format"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/libs/chemspipy.py#L193-L200 | train |
chemlab/chemlab | chemlab/libs/chemspipy.py | Compound.mol3d | def mol3d(self):
""" Return record in MOL format with 3D coordinates calculated """
if self._mol3d is None:
apiurl = 'http://www.chemspider.com/MassSpecAPI.asmx/GetRecordMol?csid=%s&calc3d=true&token=%s' % (self.csid,TOKEN)
response = urlopen(apiurl)
tree = ET.parse(r... | python | def mol3d(self):
""" Return record in MOL format with 3D coordinates calculated """
if self._mol3d is None:
apiurl = 'http://www.chemspider.com/MassSpecAPI.asmx/GetRecordMol?csid=%s&calc3d=true&token=%s' % (self.csid,TOKEN)
response = urlopen(apiurl)
tree = ET.parse(r... | [
"def",
"mol3d",
"(",
"self",
")",
":",
"if",
"self",
".",
"_mol3d",
"is",
"None",
":",
"apiurl",
"=",
"'http://www.chemspider.com/MassSpecAPI.asmx/GetRecordMol?csid=%s&calc3d=true&token=%s'",
"%",
"(",
"self",
".",
"csid",
",",
"TOKEN",
")",
"response",
"=",
"urlo... | Return record in MOL format with 3D coordinates calculated | [
"Return",
"record",
"in",
"MOL",
"format",
"with",
"3D",
"coordinates",
"calculated"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/libs/chemspipy.py#L203-L210 | train |
chemlab/chemlab | chemlab/graphics/renderers/ballandstick.py | BallAndStickRenderer.update_positions | def update_positions(self, r_array):
'''Update the coordinate array r_array'''
self.ar.update_positions(r_array)
if self.has_bonds:
self.br.update_positions(r_array) | python | def update_positions(self, r_array):
'''Update the coordinate array r_array'''
self.ar.update_positions(r_array)
if self.has_bonds:
self.br.update_positions(r_array) | [
"def",
"update_positions",
"(",
"self",
",",
"r_array",
")",
":",
"self",
".",
"ar",
".",
"update_positions",
"(",
"r_array",
")",
"if",
"self",
".",
"has_bonds",
":",
"self",
".",
"br",
".",
"update_positions",
"(",
"r_array",
")"
] | Update the coordinate array r_array | [
"Update",
"the",
"coordinate",
"array",
"r_array"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/renderers/ballandstick.py#L52-L57 | train |
chemlab/chemlab | chemlab/core/base.py | concatenate_attributes | def concatenate_attributes(attributes):
'''Concatenate InstanceAttribute to return a bigger one.'''
# We get a template/
tpl = attributes[0]
attr = InstanceAttribute(tpl.name, tpl.shape,
tpl.dtype, tpl.dim, alias=None)
# Special case, not a single array has size bi... | python | def concatenate_attributes(attributes):
'''Concatenate InstanceAttribute to return a bigger one.'''
# We get a template/
tpl = attributes[0]
attr = InstanceAttribute(tpl.name, tpl.shape,
tpl.dtype, tpl.dim, alias=None)
# Special case, not a single array has size bi... | [
"def",
"concatenate_attributes",
"(",
"attributes",
")",
":",
"# We get a template/",
"tpl",
"=",
"attributes",
"[",
"0",
"]",
"attr",
"=",
"InstanceAttribute",
"(",
"tpl",
".",
"name",
",",
"tpl",
".",
"shape",
",",
"tpl",
".",
"dtype",
",",
"tpl",
".",
... | Concatenate InstanceAttribute to return a bigger one. | [
"Concatenate",
"InstanceAttribute",
"to",
"return",
"a",
"bigger",
"one",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/base.py#L700-L712 | train |
chemlab/chemlab | chemlab/core/base.py | concatenate_fields | def concatenate_fields(fields, dim):
'Create an INstanceAttribute from a list of InstnaceFields'
if len(fields) == 0:
raise ValueError('fields cannot be an empty list')
if len(set((f.name, f.shape, f.dtype) for f in fields)) != 1:
raise ValueError('fields should have homogeneous name, s... | python | def concatenate_fields(fields, dim):
'Create an INstanceAttribute from a list of InstnaceFields'
if len(fields) == 0:
raise ValueError('fields cannot be an empty list')
if len(set((f.name, f.shape, f.dtype) for f in fields)) != 1:
raise ValueError('fields should have homogeneous name, s... | [
"def",
"concatenate_fields",
"(",
"fields",
",",
"dim",
")",
":",
"if",
"len",
"(",
"fields",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'fields cannot be an empty list'",
")",
"if",
"len",
"(",
"set",
"(",
"(",
"f",
".",
"name",
",",
"f",
".",
... | Create an INstanceAttribute from a list of InstnaceFields | [
"Create",
"an",
"INstanceAttribute",
"from",
"a",
"list",
"of",
"InstnaceFields"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/base.py#L714-L726 | train |
chemlab/chemlab | chemlab/core/base.py | normalize_index | def normalize_index(index):
"""normalize numpy index"""
index = np.asarray(index)
if len(index) == 0:
return index.astype('int')
if index.dtype == 'bool':
index = index.nonzero()[0]
elif index.dtype == 'int':
pass
else:
raise ValueError('Index should be ... | python | def normalize_index(index):
"""normalize numpy index"""
index = np.asarray(index)
if len(index) == 0:
return index.astype('int')
if index.dtype == 'bool':
index = index.nonzero()[0]
elif index.dtype == 'int':
pass
else:
raise ValueError('Index should be ... | [
"def",
"normalize_index",
"(",
"index",
")",
":",
"index",
"=",
"np",
".",
"asarray",
"(",
"index",
")",
"if",
"len",
"(",
"index",
")",
"==",
"0",
":",
"return",
"index",
".",
"astype",
"(",
"'int'",
")",
"if",
"index",
".",
"dtype",
"==",
"'bool'... | normalize numpy index | [
"normalize",
"numpy",
"index"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/base.py#L745-L758 | train |
chemlab/chemlab | chemlab/core/base.py | ChemicalEntity.to_dict | def to_dict(self):
"""Return a dict representing the ChemicalEntity that can be read back
using from_dict.
"""
ret = merge_dicts(self.__attributes__, self.__relations__, self.__fields__)
ret = {k : v.value for k,v in ret.items()}
ret['maps'] = {k : v.val... | python | def to_dict(self):
"""Return a dict representing the ChemicalEntity that can be read back
using from_dict.
"""
ret = merge_dicts(self.__attributes__, self.__relations__, self.__fields__)
ret = {k : v.value for k,v in ret.items()}
ret['maps'] = {k : v.val... | [
"def",
"to_dict",
"(",
"self",
")",
":",
"ret",
"=",
"merge_dicts",
"(",
"self",
".",
"__attributes__",
",",
"self",
".",
"__relations__",
",",
"self",
".",
"__fields__",
")",
"ret",
"=",
"{",
"k",
":",
"v",
".",
"value",
"for",
"k",
",",
"v",
"in"... | Return a dict representing the ChemicalEntity that can be read back
using from_dict. | [
"Return",
"a",
"dict",
"representing",
"the",
"ChemicalEntity",
"that",
"can",
"be",
"read",
"back",
"using",
"from_dict",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/base.py#L105-L114 | train |
chemlab/chemlab | chemlab/core/base.py | ChemicalEntity.from_json | def from_json(cls, string):
"""Create a ChemicalEntity from a json string
"""
exp_dict = json_to_data(string)
version = exp_dict.get('version', 0)
if version == 0:
return cls.from_dict(exp_dict)
elif version == 1:
return cls.from_dict(exp_dict)
... | python | def from_json(cls, string):
"""Create a ChemicalEntity from a json string
"""
exp_dict = json_to_data(string)
version = exp_dict.get('version', 0)
if version == 0:
return cls.from_dict(exp_dict)
elif version == 1:
return cls.from_dict(exp_dict)
... | [
"def",
"from_json",
"(",
"cls",
",",
"string",
")",
":",
"exp_dict",
"=",
"json_to_data",
"(",
"string",
")",
"version",
"=",
"exp_dict",
".",
"get",
"(",
"'version'",
",",
"0",
")",
"if",
"version",
"==",
"0",
":",
"return",
"cls",
".",
"from_dict",
... | Create a ChemicalEntity from a json string | [
"Create",
"a",
"ChemicalEntity",
"from",
"a",
"json",
"string"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/base.py#L117-L127 | train |
chemlab/chemlab | chemlab/core/base.py | ChemicalEntity.copy | def copy(self):
"""Create a copy of this ChemicalEntity
"""
inst = super(type(self), type(self)).empty(**self.dimensions)
# Need to copy all attributes, fields, relations
inst.__attributes__ = {k: v.copy() for k, v in self.__attributes__.items()}
inst.__... | python | def copy(self):
"""Create a copy of this ChemicalEntity
"""
inst = super(type(self), type(self)).empty(**self.dimensions)
# Need to copy all attributes, fields, relations
inst.__attributes__ = {k: v.copy() for k, v in self.__attributes__.items()}
inst.__... | [
"def",
"copy",
"(",
"self",
")",
":",
"inst",
"=",
"super",
"(",
"type",
"(",
"self",
")",
",",
"type",
"(",
"self",
")",
")",
".",
"empty",
"(",
"*",
"*",
"self",
".",
"dimensions",
")",
"# Need to copy all attributes, fields, relations",
"inst",
".",
... | Create a copy of this ChemicalEntity | [
"Create",
"a",
"copy",
"of",
"this",
"ChemicalEntity"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/base.py#L138-L151 | train |
chemlab/chemlab | chemlab/core/base.py | ChemicalEntity.copy_from | def copy_from(self, other):
"""Copy properties from another ChemicalEntity
"""
# Need to copy all attributes, fields, relations
self.__attributes__ = {k: v.copy() for k, v in other.__attributes__.items()}
self.__fields__ = {k: v.copy() for k, v in other.__fields__.items(... | python | def copy_from(self, other):
"""Copy properties from another ChemicalEntity
"""
# Need to copy all attributes, fields, relations
self.__attributes__ = {k: v.copy() for k, v in other.__attributes__.items()}
self.__fields__ = {k: v.copy() for k, v in other.__fields__.items(... | [
"def",
"copy_from",
"(",
"self",
",",
"other",
")",
":",
"# Need to copy all attributes, fields, relations",
"self",
".",
"__attributes__",
"=",
"{",
"k",
":",
"v",
".",
"copy",
"(",
")",
"for",
"k",
",",
"v",
"in",
"other",
".",
"__attributes__",
".",
"it... | Copy properties from another ChemicalEntity | [
"Copy",
"properties",
"from",
"another",
"ChemicalEntity"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/base.py#L153-L162 | train |
chemlab/chemlab | chemlab/core/base.py | ChemicalEntity.update | def update(self, dictionary):
"""Update the current chemical entity from a dictionary of attributes"""
allowed_attrs = list(self.__attributes__.keys())
allowed_attrs += [a.alias for a in self.__attributes__.values()]
for k in dictionary:
# We only update existing attributes
... | python | def update(self, dictionary):
"""Update the current chemical entity from a dictionary of attributes"""
allowed_attrs = list(self.__attributes__.keys())
allowed_attrs += [a.alias for a in self.__attributes__.values()]
for k in dictionary:
# We only update existing attributes
... | [
"def",
"update",
"(",
"self",
",",
"dictionary",
")",
":",
"allowed_attrs",
"=",
"list",
"(",
"self",
".",
"__attributes__",
".",
"keys",
"(",
")",
")",
"allowed_attrs",
"+=",
"[",
"a",
".",
"alias",
"for",
"a",
"in",
"self",
".",
"__attributes__",
"."... | Update the current chemical entity from a dictionary of attributes | [
"Update",
"the",
"current",
"chemical",
"entity",
"from",
"a",
"dictionary",
"of",
"attributes"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/base.py#L164-L172 | train |
chemlab/chemlab | chemlab/core/base.py | ChemicalEntity.subentity | def subentity(self, Entity, index):
"""Return child entity"""
dim = Entity.__dimension__
entity = Entity.empty()
if index >= self.dimensions[dim]:
raise ValueError('index {} out of bounds for dimension {} (size {})'
.format(index, dim, se... | python | def subentity(self, Entity, index):
"""Return child entity"""
dim = Entity.__dimension__
entity = Entity.empty()
if index >= self.dimensions[dim]:
raise ValueError('index {} out of bounds for dimension {} (size {})'
.format(index, dim, se... | [
"def",
"subentity",
"(",
"self",
",",
"Entity",
",",
"index",
")",
":",
"dim",
"=",
"Entity",
".",
"__dimension__",
"entity",
"=",
"Entity",
".",
"empty",
"(",
")",
"if",
"index",
">=",
"self",
".",
"dimensions",
"[",
"dim",
"]",
":",
"raise",
"Value... | Return child entity | [
"Return",
"child",
"entity"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/base.py#L343-L386 | train |
chemlab/chemlab | chemlab/core/base.py | ChemicalEntity.sub_dimension | def sub_dimension(self, index, dimension, propagate=True, inplace=False):
"""Return a ChemicalEntity sliced through a dimension.
If other dimensions depend on this one those are updated accordingly.
"""
filter_ = self._propagate_dim(index, dimension, propagate)
return se... | python | def sub_dimension(self, index, dimension, propagate=True, inplace=False):
"""Return a ChemicalEntity sliced through a dimension.
If other dimensions depend on this one those are updated accordingly.
"""
filter_ = self._propagate_dim(index, dimension, propagate)
return se... | [
"def",
"sub_dimension",
"(",
"self",
",",
"index",
",",
"dimension",
",",
"propagate",
"=",
"True",
",",
"inplace",
"=",
"False",
")",
":",
"filter_",
"=",
"self",
".",
"_propagate_dim",
"(",
"index",
",",
"dimension",
",",
"propagate",
")",
"return",
"s... | Return a ChemicalEntity sliced through a dimension.
If other dimensions depend on this one those are updated accordingly. | [
"Return",
"a",
"ChemicalEntity",
"sliced",
"through",
"a",
"dimension",
".",
"If",
"other",
"dimensions",
"depend",
"on",
"this",
"one",
"those",
"are",
"updated",
"accordingly",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/base.py#L446-L452 | train |
chemlab/chemlab | chemlab/core/base.py | ChemicalEntity.expand_dimension | def expand_dimension(self, newdim, dimension, maps={}, relations={}):
''' When we expand we need to provide new maps and relations as those
can't be inferred '''
for name, attr in self.__attributes__.items():
if attr.dim == dimension:
newattr = attr.copy()
... | python | def expand_dimension(self, newdim, dimension, maps={}, relations={}):
''' When we expand we need to provide new maps and relations as those
can't be inferred '''
for name, attr in self.__attributes__.items():
if attr.dim == dimension:
newattr = attr.copy()
... | [
"def",
"expand_dimension",
"(",
"self",
",",
"newdim",
",",
"dimension",
",",
"maps",
"=",
"{",
"}",
",",
"relations",
"=",
"{",
"}",
")",
":",
"for",
"name",
",",
"attr",
"in",
"self",
".",
"__attributes__",
".",
"items",
"(",
")",
":",
"if",
"att... | When we expand we need to provide new maps and relations as those
can't be inferred | [
"When",
"we",
"expand",
"we",
"need",
"to",
"provide",
"new",
"maps",
"and",
"relations",
"as",
"those",
"can",
"t",
"be",
"inferred"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/base.py#L461-L504 | train |
chemlab/chemlab | chemlab/core/base.py | ChemicalEntity.concat | def concat(self, other, inplace=False):
'''Concatenate two ChemicalEntity of the same kind'''
# Create new entity
if inplace:
obj = self
else:
obj = self.copy()
# Stitch every attribute
for name, attr in obj.__attributes__.items()... | python | def concat(self, other, inplace=False):
'''Concatenate two ChemicalEntity of the same kind'''
# Create new entity
if inplace:
obj = self
else:
obj = self.copy()
# Stitch every attribute
for name, attr in obj.__attributes__.items()... | [
"def",
"concat",
"(",
"self",
",",
"other",
",",
"inplace",
"=",
"False",
")",
":",
"# Create new entity",
"if",
"inplace",
":",
"obj",
"=",
"self",
"else",
":",
"obj",
"=",
"self",
".",
"copy",
"(",
")",
"# Stitch every attribute",
"for",
"name",
",",
... | Concatenate two ChemicalEntity of the same kind | [
"Concatenate",
"two",
"ChemicalEntity",
"of",
"the",
"same",
"kind"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/base.py#L544-L573 | train |
chemlab/chemlab | chemlab/core/base.py | ChemicalEntity.sub | def sub(self, inplace=False, **kwargs):
"""Return a entity where the conditions are met"""
filter_ = self.where(**kwargs)
return self.subindex(filter_, inplace) | python | def sub(self, inplace=False, **kwargs):
"""Return a entity where the conditions are met"""
filter_ = self.where(**kwargs)
return self.subindex(filter_, inplace) | [
"def",
"sub",
"(",
"self",
",",
"inplace",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"filter_",
"=",
"self",
".",
"where",
"(",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"subindex",
"(",
"filter_",
",",
"inplace",
")"
] | Return a entity where the conditions are met | [
"Return",
"a",
"entity",
"where",
"the",
"conditions",
"are",
"met"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/base.py#L636-L639 | train |
chemlab/chemlab | chemlab/core/attributes.py | InstanceArray.sub | def sub(self, index):
"""Return a sub-attribute"""
index = np.asarray(index)
if index.dtype == 'bool':
index = index.nonzero()[0]
if self.size < len(index):
raise ValueError('Can\'t subset "{}": index ({}) is bigger than the number of elements ({})'.forma... | python | def sub(self, index):
"""Return a sub-attribute"""
index = np.asarray(index)
if index.dtype == 'bool':
index = index.nonzero()[0]
if self.size < len(index):
raise ValueError('Can\'t subset "{}": index ({}) is bigger than the number of elements ({})'.forma... | [
"def",
"sub",
"(",
"self",
",",
"index",
")",
":",
"index",
"=",
"np",
".",
"asarray",
"(",
"index",
")",
"if",
"index",
".",
"dtype",
"==",
"'bool'",
":",
"index",
"=",
"index",
".",
"nonzero",
"(",
")",
"[",
"0",
"]",
"if",
"self",
".",
"size... | Return a sub-attribute | [
"Return",
"a",
"sub",
"-",
"attribute"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/attributes.py#L119-L135 | train |
chemlab/chemlab | chemlab/libs/cirpy.py | resolve | def resolve(input, representation, resolvers=None, **kwargs):
""" Resolve input to the specified output representation """
resultdict = query(input, representation, resolvers, **kwargs)
result = resultdict[0]['value'] if resultdict else None
if result and len(result) == 1:
result = result[0]
... | python | def resolve(input, representation, resolvers=None, **kwargs):
""" Resolve input to the specified output representation """
resultdict = query(input, representation, resolvers, **kwargs)
result = resultdict[0]['value'] if resultdict else None
if result and len(result) == 1:
result = result[0]
... | [
"def",
"resolve",
"(",
"input",
",",
"representation",
",",
"resolvers",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"resultdict",
"=",
"query",
"(",
"input",
",",
"representation",
",",
"resolvers",
",",
"*",
"*",
"kwargs",
")",
"result",
"=",
"re... | Resolve input to the specified output representation | [
"Resolve",
"input",
"to",
"the",
"specified",
"output",
"representation"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/libs/cirpy.py#L33-L39 | train |
chemlab/chemlab | chemlab/libs/cirpy.py | query | def query(input, representation, resolvers=None, **kwargs):
""" Get all results for resolving input to the specified output representation """
apiurl = API_BASE+'/%s/%s/xml' % (urlquote(input), representation)
if resolvers:
kwargs['resolver'] = ",".join(resolvers)
if kwargs:
apiurl+= '?%... | python | def query(input, representation, resolvers=None, **kwargs):
""" Get all results for resolving input to the specified output representation """
apiurl = API_BASE+'/%s/%s/xml' % (urlquote(input), representation)
if resolvers:
kwargs['resolver'] = ",".join(resolvers)
if kwargs:
apiurl+= '?%... | [
"def",
"query",
"(",
"input",
",",
"representation",
",",
"resolvers",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"apiurl",
"=",
"API_BASE",
"+",
"'/%s/%s/xml'",
"%",
"(",
"urlquote",
"(",
"input",
")",
",",
"representation",
")",
"if",
"resolvers",... | Get all results for resolving input to the specified output representation | [
"Get",
"all",
"results",
"for",
"resolving",
"input",
"to",
"the",
"specified",
"output",
"representation"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/libs/cirpy.py#L42-L64 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.