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 listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
briney/abutils | abutils/utils/mongodb.py | get_collections | def get_collections(db, collection=None, prefix=None, suffix=None):
'''
Returns a sorted list of collection names found in ``db``.
Arguments:
db (Database): A pymongo Database object. Can be obtained
with ``get_db``.
collection (str): Name of a collection. If the collection is
present in the MongoDB database, a single-element list will
be returned with the collecion name. If not, an empty list
will be returned. This option is primarly included to allow
for quick checking to see if a collection name is present.
Default is None, which results in this option being ignored.
prefix (str): If supplied, only collections that begin with
``prefix`` will be returned.
suffix (str): If supplied, only collections that end with
``suffix`` will be returned.
Returns:
list: A sorted list of collection names.
'''
if collection is not None:
return [collection, ]
collections = db.collection_names(include_system_collections=False)
if prefix is not None:
collections = [c for c in collections if c.startswith(prefix)]
if suffix is not None:
collections = [c for c in collections if c.endswith(suffix)]
return sorted(collections) | python | def get_collections(db, collection=None, prefix=None, suffix=None):
'''
Returns a sorted list of collection names found in ``db``.
Arguments:
db (Database): A pymongo Database object. Can be obtained
with ``get_db``.
collection (str): Name of a collection. If the collection is
present in the MongoDB database, a single-element list will
be returned with the collecion name. If not, an empty list
will be returned. This option is primarly included to allow
for quick checking to see if a collection name is present.
Default is None, which results in this option being ignored.
prefix (str): If supplied, only collections that begin with
``prefix`` will be returned.
suffix (str): If supplied, only collections that end with
``suffix`` will be returned.
Returns:
list: A sorted list of collection names.
'''
if collection is not None:
return [collection, ]
collections = db.collection_names(include_system_collections=False)
if prefix is not None:
collections = [c for c in collections if c.startswith(prefix)]
if suffix is not None:
collections = [c for c in collections if c.endswith(suffix)]
return sorted(collections) | [
"def",
"get_collections",
"(",
"db",
",",
"collection",
"=",
"None",
",",
"prefix",
"=",
"None",
",",
"suffix",
"=",
"None",
")",
":",
"if",
"collection",
"is",
"not",
"None",
":",
"return",
"[",
"collection",
",",
"]",
"collections",
"=",
"db",
".",
... | Returns a sorted list of collection names found in ``db``.
Arguments:
db (Database): A pymongo Database object. Can be obtained
with ``get_db``.
collection (str): Name of a collection. If the collection is
present in the MongoDB database, a single-element list will
be returned with the collecion name. If not, an empty list
will be returned. This option is primarly included to allow
for quick checking to see if a collection name is present.
Default is None, which results in this option being ignored.
prefix (str): If supplied, only collections that begin with
``prefix`` will be returned.
suffix (str): If supplied, only collections that end with
``suffix`` will be returned.
Returns:
list: A sorted list of collection names. | [
"Returns",
"a",
"sorted",
"list",
"of",
"collection",
"names",
"found",
"in",
"db",
"."
] | 944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b | https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/utils/mongodb.py#L118-L151 | train | 42,600 |
briney/abutils | abutils/utils/mongodb.py | rename_collection | def rename_collection(db, collection, new_name):
'''
Renames a MongoDB collection.
Arguments:
db (Database): A pymongo Database object. Can be obtained
with ``get_db``.
collection (str): Name of the collection to be renamed.
new_name (str, func): ``new_name`` can be one of two things::
1. The new collection name, as a string.
2. A function which, when passed the current collection name,
returns the new collection name. If the function
returns an empty string, the collection will not be
renamed.
'''
if hasattr(new_name, '__call__'):
_new = new_name(collection)
if _new == '':
return
else:
_new = new_name
c = db[collection]
c.rename(_new) | python | def rename_collection(db, collection, new_name):
'''
Renames a MongoDB collection.
Arguments:
db (Database): A pymongo Database object. Can be obtained
with ``get_db``.
collection (str): Name of the collection to be renamed.
new_name (str, func): ``new_name`` can be one of two things::
1. The new collection name, as a string.
2. A function which, when passed the current collection name,
returns the new collection name. If the function
returns an empty string, the collection will not be
renamed.
'''
if hasattr(new_name, '__call__'):
_new = new_name(collection)
if _new == '':
return
else:
_new = new_name
c = db[collection]
c.rename(_new) | [
"def",
"rename_collection",
"(",
"db",
",",
"collection",
",",
"new_name",
")",
":",
"if",
"hasattr",
"(",
"new_name",
",",
"'__call__'",
")",
":",
"_new",
"=",
"new_name",
"(",
"collection",
")",
"if",
"_new",
"==",
"''",
":",
"return",
"else",
":",
"... | Renames a MongoDB collection.
Arguments:
db (Database): A pymongo Database object. Can be obtained
with ``get_db``.
collection (str): Name of the collection to be renamed.
new_name (str, func): ``new_name`` can be one of two things::
1. The new collection name, as a string.
2. A function which, when passed the current collection name,
returns the new collection name. If the function
returns an empty string, the collection will not be
renamed. | [
"Renames",
"a",
"MongoDB",
"collection",
"."
] | 944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b | https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/utils/mongodb.py#L154-L180 | train | 42,601 |
briney/abutils | abutils/utils/mongodb.py | update | def update(field, value, db, collection, match=None):
'''
Updates MongoDB documents.
Sets ``field`` equal to ``value`` for all documents that
meet ``match`` criteria.
Arguments:
field (str): Field to update.
value (str): Update value.
db (Database): A pymongo Database object.
collection (str): Collection name.
match (dict): A dictionary containing the match criteria, for example::
{'seq_id': {'$in': ['a', 'b', 'c']}, 'cdr3_len': {'$gte': 18}}
'''
c = db[collection]
match = match if match is not None else {}
# check MongoDB version to use appropriate update command
if db.client.server_info()['version'].startswith('2'):
c.update(match, {'$set': {field: value}}, multi=True)
else:
c.update_many(match, {'$set': {field: value}}) | python | def update(field, value, db, collection, match=None):
'''
Updates MongoDB documents.
Sets ``field`` equal to ``value`` for all documents that
meet ``match`` criteria.
Arguments:
field (str): Field to update.
value (str): Update value.
db (Database): A pymongo Database object.
collection (str): Collection name.
match (dict): A dictionary containing the match criteria, for example::
{'seq_id': {'$in': ['a', 'b', 'c']}, 'cdr3_len': {'$gte': 18}}
'''
c = db[collection]
match = match if match is not None else {}
# check MongoDB version to use appropriate update command
if db.client.server_info()['version'].startswith('2'):
c.update(match, {'$set': {field: value}}, multi=True)
else:
c.update_many(match, {'$set': {field: value}}) | [
"def",
"update",
"(",
"field",
",",
"value",
",",
"db",
",",
"collection",
",",
"match",
"=",
"None",
")",
":",
"c",
"=",
"db",
"[",
"collection",
"]",
"match",
"=",
"match",
"if",
"match",
"is",
"not",
"None",
"else",
"{",
"}",
"# check MongoDB vers... | Updates MongoDB documents.
Sets ``field`` equal to ``value`` for all documents that
meet ``match`` criteria.
Arguments:
field (str): Field to update.
value (str): Update value.
db (Database): A pymongo Database object.
collection (str): Collection name.
match (dict): A dictionary containing the match criteria, for example::
{'seq_id': {'$in': ['a', 'b', 'c']}, 'cdr3_len': {'$gte': 18}} | [
"Updates",
"MongoDB",
"documents",
"."
] | 944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b | https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/utils/mongodb.py#L183-L210 | train | 42,602 |
briney/abutils | abutils/utils/mongodb.py | mongoimport | def mongoimport(json, database,
ip='localhost', port=27017,
user=None, password=None,
delim='_', delim1=None, delim2=None,
delim_occurance=1, delim1_occurance=1, delim2_occurance=1):
'''
Performs mongoimport on one or more json files.
Args:
json: Can be one of several things:
- path to a single JSON file
- an iterable (list or tuple) of one or more JSON file paths
- path to a directory containing one or more JSON files
database (str): Name of the database into which the JSON files
will be imported
ip (str): IP address of the MongoDB server. Default is ``localhost``.
port (int): Port of the MongoDB database. Default is ``27017``.
user (str): Username for the MongoDB database, if authentication is enabled.
Default is ``None``, which results in attempting connection without
authentication.
password (str): Password for the MongoDB database, if authentication is enabled.
Default is ``None``, which results in attempting connection without
authentication.
delim (str): Delimiter, when generating collection names using a single delimiter.
Default is ``_``
delim_occurance (int): Occurance at which to split filename when using a
single delimiter. Default is ``1``
delim1 (str): Left delimiter when splitting with two delimiters. Default is None.
delim1_occurance (int): Occurance of ``delim1`` at which to split filename.
Default is ``1``
delim2 (str): Right delimiter when splitting with two delimiters. Default is None.
delim2_occurance (int): Occurance of ``delim2`` at which to split filename.
Default is ``1``
'''
logger = log.get_logger('mongodb')
_print_mongoimport_info(logger)
if type(json) in (list, tuple):
pass
elif os.path.isdir(json):
from abtools.utils.pipeline import list_files
json = list_files(json)
else:
json = [json, ]
jsons = sorted([os.path.expanduser(j) for j in json if j.endswith('.json')])
collections = _get_import_collections(jsons, delim, delim_occurance,
delim1, delim1_occurance,
delim2, delim2_occurance)
logger.info('Found {} files to import'.format(len(jsons)))
logger.info('')
for i, (json_file, collection) in enumerate(zip(jsons, collections)):
logger.info('[ {} ] {} --> {}'.format(i + 1, os.path.basename(json_file), collection))
# logger.info("Performing mongoimport on {}.".format(os.path.basename(json_file)))
# logger.info("Importing the file into collection {}.".format(collection))
if all([user, password]):
host = '--host {} --port {} -username {} -password {}'.format(ip, port, user, password)
else:
host = '--host {} --port {}'.format(ip, port)
mongo_cmd = "mongoimport {} --db {} --collection {} --file {}".format(
host, database, collection, json_file)
mongo = sp.Popen(mongo_cmd, shell=True, stdout=sp.PIPE, stderr=sp.PIPE)
stdout, stderr = mongo.communicate() | python | def mongoimport(json, database,
ip='localhost', port=27017,
user=None, password=None,
delim='_', delim1=None, delim2=None,
delim_occurance=1, delim1_occurance=1, delim2_occurance=1):
'''
Performs mongoimport on one or more json files.
Args:
json: Can be one of several things:
- path to a single JSON file
- an iterable (list or tuple) of one or more JSON file paths
- path to a directory containing one or more JSON files
database (str): Name of the database into which the JSON files
will be imported
ip (str): IP address of the MongoDB server. Default is ``localhost``.
port (int): Port of the MongoDB database. Default is ``27017``.
user (str): Username for the MongoDB database, if authentication is enabled.
Default is ``None``, which results in attempting connection without
authentication.
password (str): Password for the MongoDB database, if authentication is enabled.
Default is ``None``, which results in attempting connection without
authentication.
delim (str): Delimiter, when generating collection names using a single delimiter.
Default is ``_``
delim_occurance (int): Occurance at which to split filename when using a
single delimiter. Default is ``1``
delim1 (str): Left delimiter when splitting with two delimiters. Default is None.
delim1_occurance (int): Occurance of ``delim1`` at which to split filename.
Default is ``1``
delim2 (str): Right delimiter when splitting with two delimiters. Default is None.
delim2_occurance (int): Occurance of ``delim2`` at which to split filename.
Default is ``1``
'''
logger = log.get_logger('mongodb')
_print_mongoimport_info(logger)
if type(json) in (list, tuple):
pass
elif os.path.isdir(json):
from abtools.utils.pipeline import list_files
json = list_files(json)
else:
json = [json, ]
jsons = sorted([os.path.expanduser(j) for j in json if j.endswith('.json')])
collections = _get_import_collections(jsons, delim, delim_occurance,
delim1, delim1_occurance,
delim2, delim2_occurance)
logger.info('Found {} files to import'.format(len(jsons)))
logger.info('')
for i, (json_file, collection) in enumerate(zip(jsons, collections)):
logger.info('[ {} ] {} --> {}'.format(i + 1, os.path.basename(json_file), collection))
# logger.info("Performing mongoimport on {}.".format(os.path.basename(json_file)))
# logger.info("Importing the file into collection {}.".format(collection))
if all([user, password]):
host = '--host {} --port {} -username {} -password {}'.format(ip, port, user, password)
else:
host = '--host {} --port {}'.format(ip, port)
mongo_cmd = "mongoimport {} --db {} --collection {} --file {}".format(
host, database, collection, json_file)
mongo = sp.Popen(mongo_cmd, shell=True, stdout=sp.PIPE, stderr=sp.PIPE)
stdout, stderr = mongo.communicate() | [
"def",
"mongoimport",
"(",
"json",
",",
"database",
",",
"ip",
"=",
"'localhost'",
",",
"port",
"=",
"27017",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
",",
"delim",
"=",
"'_'",
",",
"delim1",
"=",
"None",
",",
"delim2",
"=",
"None",
... | Performs mongoimport on one or more json files.
Args:
json: Can be one of several things:
- path to a single JSON file
- an iterable (list or tuple) of one or more JSON file paths
- path to a directory containing one or more JSON files
database (str): Name of the database into which the JSON files
will be imported
ip (str): IP address of the MongoDB server. Default is ``localhost``.
port (int): Port of the MongoDB database. Default is ``27017``.
user (str): Username for the MongoDB database, if authentication is enabled.
Default is ``None``, which results in attempting connection without
authentication.
password (str): Password for the MongoDB database, if authentication is enabled.
Default is ``None``, which results in attempting connection without
authentication.
delim (str): Delimiter, when generating collection names using a single delimiter.
Default is ``_``
delim_occurance (int): Occurance at which to split filename when using a
single delimiter. Default is ``1``
delim1 (str): Left delimiter when splitting with two delimiters. Default is None.
delim1_occurance (int): Occurance of ``delim1`` at which to split filename.
Default is ``1``
delim2 (str): Right delimiter when splitting with two delimiters. Default is None.
delim2_occurance (int): Occurance of ``delim2`` at which to split filename.
Default is ``1`` | [
"Performs",
"mongoimport",
"on",
"one",
"or",
"more",
"json",
"files",
"."
] | 944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b | https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/utils/mongodb.py#L239-L312 | train | 42,603 |
AtteqCom/zsl | src/zsl/application/service_application.py | get_settings_from_profile | def get_settings_from_profile(profile, profile_dir=None):
# type: (str, Any)->str
""""Returns the configuration file path for the given profile.
:param profile: Profile name to be used.
:param profile_dir: The directory where the profile configuration file should reside. It
may be also a module, and then the directory of the module is used.
:return: Configuration file path.
"""
if profile_dir is None:
import settings
profile_dir = settings
if hasattr(profile_dir, '__file__'):
profile_dir = os.path.dirname(profile_dir.__file__)
return os.path.join(profile_dir, '{0}.cfg'.format(profile)) | python | def get_settings_from_profile(profile, profile_dir=None):
# type: (str, Any)->str
""""Returns the configuration file path for the given profile.
:param profile: Profile name to be used.
:param profile_dir: The directory where the profile configuration file should reside. It
may be also a module, and then the directory of the module is used.
:return: Configuration file path.
"""
if profile_dir is None:
import settings
profile_dir = settings
if hasattr(profile_dir, '__file__'):
profile_dir = os.path.dirname(profile_dir.__file__)
return os.path.join(profile_dir, '{0}.cfg'.format(profile)) | [
"def",
"get_settings_from_profile",
"(",
"profile",
",",
"profile_dir",
"=",
"None",
")",
":",
"# type: (str, Any)->str",
"if",
"profile_dir",
"is",
"None",
":",
"import",
"settings",
"profile_dir",
"=",
"settings",
"if",
"hasattr",
"(",
"profile_dir",
",",
"'__fi... | Returns the configuration file path for the given profile.
:param profile: Profile name to be used.
:param profile_dir: The directory where the profile configuration file should reside. It
may be also a module, and then the directory of the module is used.
:return: Configuration file path. | [
"Returns",
"the",
"configuration",
"file",
"path",
"for",
"the",
"given",
"profile",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/application/service_application.py#L39-L55 | train | 42,604 |
AtteqCom/zsl | src/zsl/application/service_application.py | ServiceApplication._get_app_module | def _get_app_module(self):
# type: () -> Callable
"""Returns a module which binds the current app and configuration.
:return: configuration callback
:rtype: Callable
"""
def configure(binder):
# type: (Binder) -> Callable
binder.bind(ServiceApplication, to=self, scope=singleton)
binder.bind(Config, to=self.config, scope=singleton)
return configure | python | def _get_app_module(self):
# type: () -> Callable
"""Returns a module which binds the current app and configuration.
:return: configuration callback
:rtype: Callable
"""
def configure(binder):
# type: (Binder) -> Callable
binder.bind(ServiceApplication, to=self, scope=singleton)
binder.bind(Config, to=self.config, scope=singleton)
return configure | [
"def",
"_get_app_module",
"(",
"self",
")",
":",
"# type: () -> Callable",
"def",
"configure",
"(",
"binder",
")",
":",
"# type: (Binder) -> Callable",
"binder",
".",
"bind",
"(",
"ServiceApplication",
",",
"to",
"=",
"self",
",",
"scope",
"=",
"singleton",
")",... | Returns a module which binds the current app and configuration.
:return: configuration callback
:rtype: Callable | [
"Returns",
"a",
"module",
"which",
"binds",
"the",
"current",
"app",
"and",
"configuration",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/application/service_application.py#L130-L143 | train | 42,605 |
AtteqCom/zsl | src/zsl/application/service_application.py | ServiceApplication._configure_injector | def _configure_injector(self, modules):
"""Create the injector and install the modules.
There is a necessary order of calls. First we have to bind `Config` and
`Zsl`, then we need to register the app into the global stack and then
we can install all other modules, which can use `Zsl` and `Config`
injection.
:param modules: list of injection modules
:type modules: list
"""
self._register()
self._create_injector()
self._bind_core()
self._bind_modules(modules)
self.logger.debug("Injector configuration with modules {0}.".format(modules))
self._dependencies_initialized = True | python | def _configure_injector(self, modules):
"""Create the injector and install the modules.
There is a necessary order of calls. First we have to bind `Config` and
`Zsl`, then we need to register the app into the global stack and then
we can install all other modules, which can use `Zsl` and `Config`
injection.
:param modules: list of injection modules
:type modules: list
"""
self._register()
self._create_injector()
self._bind_core()
self._bind_modules(modules)
self.logger.debug("Injector configuration with modules {0}.".format(modules))
self._dependencies_initialized = True | [
"def",
"_configure_injector",
"(",
"self",
",",
"modules",
")",
":",
"self",
".",
"_register",
"(",
")",
"self",
".",
"_create_injector",
"(",
")",
"self",
".",
"_bind_core",
"(",
")",
"self",
".",
"_bind_modules",
"(",
"modules",
")",
"self",
".",
"logg... | Create the injector and install the modules.
There is a necessary order of calls. First we have to bind `Config` and
`Zsl`, then we need to register the app into the global stack and then
we can install all other modules, which can use `Zsl` and `Config`
injection.
:param modules: list of injection modules
:type modules: list | [
"Create",
"the",
"injector",
"and",
"install",
"the",
"modules",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/application/service_application.py#L145-L161 | train | 42,606 |
AtteqCom/zsl | src/zsl/application/modules/cache_module.py | RedisCacheInjectionModule.configure | def configure(self, binder):
# type: (Binder) -> None
"""Initializer of the cache - creates the Redis cache module as the
default cache infrastructure. The module is bound to `RedisCacheModule`
and `CacheModule` keys. The initializer also creates `RedisIdHelper`
and bounds it to `RedisIdHelper` and `IdHelper` keys.
:param Binder binder: The binder object holding the binding context, we\
add cache to the binder.
"""
redis_cache_module = RedisCacheModule()
binder.bind(
RedisCacheModule,
to=redis_cache_module,
scope=singleton
)
binder.bind(
CacheModule,
to=redis_cache_module,
scope=singleton
)
redis_id_helper = RedisIdHelper()
binder.bind(
RedisIdHelper,
to=redis_id_helper,
scope=singleton
)
binder.bind(
IdHelper,
to=redis_id_helper,
scope=singleton
)
logging.debug("Created RedisCache binding.") | python | def configure(self, binder):
# type: (Binder) -> None
"""Initializer of the cache - creates the Redis cache module as the
default cache infrastructure. The module is bound to `RedisCacheModule`
and `CacheModule` keys. The initializer also creates `RedisIdHelper`
and bounds it to `RedisIdHelper` and `IdHelper` keys.
:param Binder binder: The binder object holding the binding context, we\
add cache to the binder.
"""
redis_cache_module = RedisCacheModule()
binder.bind(
RedisCacheModule,
to=redis_cache_module,
scope=singleton
)
binder.bind(
CacheModule,
to=redis_cache_module,
scope=singleton
)
redis_id_helper = RedisIdHelper()
binder.bind(
RedisIdHelper,
to=redis_id_helper,
scope=singleton
)
binder.bind(
IdHelper,
to=redis_id_helper,
scope=singleton
)
logging.debug("Created RedisCache binding.") | [
"def",
"configure",
"(",
"self",
",",
"binder",
")",
":",
"# type: (Binder) -> None",
"redis_cache_module",
"=",
"RedisCacheModule",
"(",
")",
"binder",
".",
"bind",
"(",
"RedisCacheModule",
",",
"to",
"=",
"redis_cache_module",
",",
"scope",
"=",
"singleton",
"... | Initializer of the cache - creates the Redis cache module as the
default cache infrastructure. The module is bound to `RedisCacheModule`
and `CacheModule` keys. The initializer also creates `RedisIdHelper`
and bounds it to `RedisIdHelper` and `IdHelper` keys.
:param Binder binder: The binder object holding the binding context, we\
add cache to the binder. | [
"Initializer",
"of",
"the",
"cache",
"-",
"creates",
"the",
"Redis",
"cache",
"module",
"as",
"the",
"default",
"cache",
"infrastructure",
".",
"The",
"module",
"is",
"bound",
"to",
"RedisCacheModule",
"and",
"CacheModule",
"keys",
".",
"The",
"initializer",
"... | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/application/modules/cache_module.py#L22-L56 | train | 42,607 |
briney/abutils | abutils/utils/decorators.py | lazy_property | def lazy_property(func):
'''
Wraps a property to provide lazy evaluation. Eliminates boilerplate.
Also provides for setting and deleting the property.
Use as you would use the @property decorator::
# OLD:
class MyClass():
def __init__():
self._compute = None
@property
def compute(self):
if self._compute is None:
# computationally intense stuff
# ...
# ...
self._compute = result
return self._compute
@compute.setter
def compute(self, value):
self._compute = value
# NEW:
class MyClass():
def __init__():
pass
@lazy_property
def compute(self):
# computationally intense stuff
# ...
# ...
return result
.. note:
Properties wrapped with ``lazy_property`` are only evaluated once.
If the instance state changes, lazy properties will not be automatically
re-evaulated and the update must be explicitly called for::
c = MyClass(data)
prop = c.lazy_property
# If you update some data that affects c.lazy_property
c.data = new_data
# c.lazy_property won't change
prop == c.lazy_property # TRUE
# If you want to update c.lazy_property, you can delete it, which will
# force it to be recomputed (with the new data) the next time you use it
del c.lazy_property
new_prop = c.lazy_property
new_prop == prop # FALSE
'''
attr_name = '_lazy_' + func.__name__
@property
def _lazy_property(self):
if not hasattr(self, attr_name):
setattr(self, attr_name, func(self))
return getattr(self, attr_name)
@_lazy_property.deleter
def _lazy_property(self):
if hasattr(self, attr_name):
delattr(self, attr_name)
@_lazy_property.setter
def _lazy_property(self, value):
setattr(self, attr_name, value)
return _lazy_property | python | def lazy_property(func):
'''
Wraps a property to provide lazy evaluation. Eliminates boilerplate.
Also provides for setting and deleting the property.
Use as you would use the @property decorator::
# OLD:
class MyClass():
def __init__():
self._compute = None
@property
def compute(self):
if self._compute is None:
# computationally intense stuff
# ...
# ...
self._compute = result
return self._compute
@compute.setter
def compute(self, value):
self._compute = value
# NEW:
class MyClass():
def __init__():
pass
@lazy_property
def compute(self):
# computationally intense stuff
# ...
# ...
return result
.. note:
Properties wrapped with ``lazy_property`` are only evaluated once.
If the instance state changes, lazy properties will not be automatically
re-evaulated and the update must be explicitly called for::
c = MyClass(data)
prop = c.lazy_property
# If you update some data that affects c.lazy_property
c.data = new_data
# c.lazy_property won't change
prop == c.lazy_property # TRUE
# If you want to update c.lazy_property, you can delete it, which will
# force it to be recomputed (with the new data) the next time you use it
del c.lazy_property
new_prop = c.lazy_property
new_prop == prop # FALSE
'''
attr_name = '_lazy_' + func.__name__
@property
def _lazy_property(self):
if not hasattr(self, attr_name):
setattr(self, attr_name, func(self))
return getattr(self, attr_name)
@_lazy_property.deleter
def _lazy_property(self):
if hasattr(self, attr_name):
delattr(self, attr_name)
@_lazy_property.setter
def _lazy_property(self, value):
setattr(self, attr_name, value)
return _lazy_property | [
"def",
"lazy_property",
"(",
"func",
")",
":",
"attr_name",
"=",
"'_lazy_'",
"+",
"func",
".",
"__name__",
"@",
"property",
"def",
"_lazy_property",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"attr_name",
")",
":",
"setattr",
"(",
... | Wraps a property to provide lazy evaluation. Eliminates boilerplate.
Also provides for setting and deleting the property.
Use as you would use the @property decorator::
# OLD:
class MyClass():
def __init__():
self._compute = None
@property
def compute(self):
if self._compute is None:
# computationally intense stuff
# ...
# ...
self._compute = result
return self._compute
@compute.setter
def compute(self, value):
self._compute = value
# NEW:
class MyClass():
def __init__():
pass
@lazy_property
def compute(self):
# computationally intense stuff
# ...
# ...
return result
.. note:
Properties wrapped with ``lazy_property`` are only evaluated once.
If the instance state changes, lazy properties will not be automatically
re-evaulated and the update must be explicitly called for::
c = MyClass(data)
prop = c.lazy_property
# If you update some data that affects c.lazy_property
c.data = new_data
# c.lazy_property won't change
prop == c.lazy_property # TRUE
# If you want to update c.lazy_property, you can delete it, which will
# force it to be recomputed (with the new data) the next time you use it
del c.lazy_property
new_prop = c.lazy_property
new_prop == prop # FALSE | [
"Wraps",
"a",
"property",
"to",
"provide",
"lazy",
"evaluation",
".",
"Eliminates",
"boilerplate",
".",
"Also",
"provides",
"for",
"setting",
"and",
"deleting",
"the",
"property",
"."
] | 944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b | https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/utils/decorators.py#L29-L106 | train | 42,608 |
briney/abutils | abutils/core/sequence.py | Sequence.region | def region(self, start=0, end=None):
'''
Returns a region of ``Sequence.sequence``, in FASTA format.
If called without kwargs, the entire sequence will be returned.
Args:
start (int): Start position of the region to be returned. Default
is 0.
end (int): End position of the region to be returned. Negative values
will function as they do when slicing strings.
Returns:
str: A region of ``Sequence.sequence``, in FASTA format
'''
if end is None:
end = len(self.sequence)
return '>{}\n{}'.format(self.id, self.sequence[start:end]) | python | def region(self, start=0, end=None):
'''
Returns a region of ``Sequence.sequence``, in FASTA format.
If called without kwargs, the entire sequence will be returned.
Args:
start (int): Start position of the region to be returned. Default
is 0.
end (int): End position of the region to be returned. Negative values
will function as they do when slicing strings.
Returns:
str: A region of ``Sequence.sequence``, in FASTA format
'''
if end is None:
end = len(self.sequence)
return '>{}\n{}'.format(self.id, self.sequence[start:end]) | [
"def",
"region",
"(",
"self",
",",
"start",
"=",
"0",
",",
"end",
"=",
"None",
")",
":",
"if",
"end",
"is",
"None",
":",
"end",
"=",
"len",
"(",
"self",
".",
"sequence",
")",
"return",
"'>{}\\n{}'",
".",
"format",
"(",
"self",
".",
"id",
",",
"... | Returns a region of ``Sequence.sequence``, in FASTA format.
If called without kwargs, the entire sequence will be returned.
Args:
start (int): Start position of the region to be returned. Default
is 0.
end (int): End position of the region to be returned. Negative values
will function as they do when slicing strings.
Returns:
str: A region of ``Sequence.sequence``, in FASTA format | [
"Returns",
"a",
"region",
"of",
"Sequence",
".",
"sequence",
"in",
"FASTA",
"format",
"."
] | 944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b | https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/core/sequence.py#L252-L272 | train | 42,609 |
AtteqCom/zsl | src/zsl/utils/string_helper.py | underscore_to_camelcase | def underscore_to_camelcase(value, first_upper=True):
"""Transform string from underscore_string to camelCase.
:param value: string with underscores
:param first_upper: the result will have its first character in upper case
:type value: str
:return: string in CamelCase or camelCase according to the first_upper
:rtype: str
:Example:
>>> underscore_to_camelcase('camel_case')
'CamelCase'
>>> underscore_to_camelcase('camel_case', False)
'camelCase'
"""
value = str(value)
camelized = "".join(x.title() if x else '_' for x in value.split("_"))
if not first_upper:
camelized = camelized[0].lower() + camelized[1:]
return camelized | python | def underscore_to_camelcase(value, first_upper=True):
"""Transform string from underscore_string to camelCase.
:param value: string with underscores
:param first_upper: the result will have its first character in upper case
:type value: str
:return: string in CamelCase or camelCase according to the first_upper
:rtype: str
:Example:
>>> underscore_to_camelcase('camel_case')
'CamelCase'
>>> underscore_to_camelcase('camel_case', False)
'camelCase'
"""
value = str(value)
camelized = "".join(x.title() if x else '_' for x in value.split("_"))
if not first_upper:
camelized = camelized[0].lower() + camelized[1:]
return camelized | [
"def",
"underscore_to_camelcase",
"(",
"value",
",",
"first_upper",
"=",
"True",
")",
":",
"value",
"=",
"str",
"(",
"value",
")",
"camelized",
"=",
"\"\"",
".",
"join",
"(",
"x",
".",
"title",
"(",
")",
"if",
"x",
"else",
"'_'",
"for",
"x",
"in",
... | Transform string from underscore_string to camelCase.
:param value: string with underscores
:param first_upper: the result will have its first character in upper case
:type value: str
:return: string in CamelCase or camelCase according to the first_upper
:rtype: str
:Example:
>>> underscore_to_camelcase('camel_case')
'CamelCase'
>>> underscore_to_camelcase('camel_case', False)
'camelCase' | [
"Transform",
"string",
"from",
"underscore_string",
"to",
"camelCase",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/string_helper.py#L20-L39 | train | 42,610 |
AtteqCom/zsl | src/zsl/utils/string_helper.py | et_node_to_string | def et_node_to_string(et_node, default=''):
"""Simple method to get stripped text from node or ``default`` string if None is given.
:param et_node: Element or None
:param default: string returned if None is given, default ``''``
:type et_node: xml.etree.ElementTree.Element, None
:type default: str
:return: text from node or default
:rtype: str
"""
return str(et_node.text).strip() if et_node is not None and et_node.text else default | python | def et_node_to_string(et_node, default=''):
"""Simple method to get stripped text from node or ``default`` string if None is given.
:param et_node: Element or None
:param default: string returned if None is given, default ``''``
:type et_node: xml.etree.ElementTree.Element, None
:type default: str
:return: text from node or default
:rtype: str
"""
return str(et_node.text).strip() if et_node is not None and et_node.text else default | [
"def",
"et_node_to_string",
"(",
"et_node",
",",
"default",
"=",
"''",
")",
":",
"return",
"str",
"(",
"et_node",
".",
"text",
")",
".",
"strip",
"(",
")",
"if",
"et_node",
"is",
"not",
"None",
"and",
"et_node",
".",
"text",
"else",
"default"
] | Simple method to get stripped text from node or ``default`` string if None is given.
:param et_node: Element or None
:param default: string returned if None is given, default ``''``
:type et_node: xml.etree.ElementTree.Element, None
:type default: str
:return: text from node or default
:rtype: str | [
"Simple",
"method",
"to",
"get",
"stripped",
"text",
"from",
"node",
"or",
"default",
"string",
"if",
"None",
"is",
"given",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/string_helper.py#L58-L69 | train | 42,611 |
AtteqCom/zsl | src/zsl/utils/string_helper.py | addslashes | def addslashes(s, escaped_chars=None):
"""Add slashes for given characters. Default is for ``\`` and ``'``.
:param s: string
:param escaped_chars: list of characters to prefix with a slash ``\``
:return: string with slashed characters
:rtype: str
:Example:
>>> addslashes("'")
"\\'"
"""
if escaped_chars is None:
escaped_chars = ["\\", "'", ]
# l = ["\\", '"', "'", "\0", ]
for i in escaped_chars:
if i in s:
s = s.replace(i, '\\' + i)
return s | python | def addslashes(s, escaped_chars=None):
"""Add slashes for given characters. Default is for ``\`` and ``'``.
:param s: string
:param escaped_chars: list of characters to prefix with a slash ``\``
:return: string with slashed characters
:rtype: str
:Example:
>>> addslashes("'")
"\\'"
"""
if escaped_chars is None:
escaped_chars = ["\\", "'", ]
# l = ["\\", '"', "'", "\0", ]
for i in escaped_chars:
if i in s:
s = s.replace(i, '\\' + i)
return s | [
"def",
"addslashes",
"(",
"s",
",",
"escaped_chars",
"=",
"None",
")",
":",
"if",
"escaped_chars",
"is",
"None",
":",
"escaped_chars",
"=",
"[",
"\"\\\\\"",
",",
"\"'\"",
",",
"]",
"# l = [\"\\\\\", '\"', \"'\", \"\\0\", ]",
"for",
"i",
"in",
"escaped_chars",
... | Add slashes for given characters. Default is for ``\`` and ``'``.
:param s: string
:param escaped_chars: list of characters to prefix with a slash ``\``
:return: string with slashed characters
:rtype: str
:Example:
>>> addslashes("'")
"\\'" | [
"Add",
"slashes",
"for",
"given",
"characters",
".",
"Default",
"is",
"for",
"\\",
"and",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/string_helper.py#L85-L104 | train | 42,612 |
briney/abutils | abutils/utils/alignment.py | mafft | def mafft(sequences=None, alignment_file=None, fasta=None, fmt='fasta', threads=-1, as_file=False,
reorder=True, print_stdout=False, print_stderr=False, mafft_bin=None):
'''
Performs multiple sequence alignment with MAFFT.
Args:
sequences (list): Sequences to be aligned. ``sequences`` can be one of four things:
1. a FASTA-formatted string
2. a list of BioPython ``SeqRecord`` objects
3. a list of AbTools ``Sequence`` objects
4. a list of lists/tuples, of the format ``[sequence_id, sequence]``
alignment_file (str): Path for the output alignment file. If not supplied,
a name will be generated using ``tempfile.NamedTemporaryFile()``.
fasta (str): Path to a FASTA-formatted file of sequences. Used as an
alternative to ``sequences`` when suppling a FASTA file.
fmt (str): Format of the alignment. Options are 'fasta', 'phylip', and 'clustal'. Default
is 'fasta'.
threads (int): Number of threads for MAFFT to use. Default is ``-1``, which
results in MAFFT using ``multiprocessing.cpu_count()`` threads.
as_file (bool): If ``True``, returns a path to the alignment file. If ``False``,
returns a BioPython ``MultipleSeqAlignment`` object (obtained by calling
``Bio.AlignIO.read()`` on the alignment file).
print_stdout (bool): If ``True``, prints MAFFT's standard output. Default is ``False``.
print_stderr (bool): If ``True``, prints MAFFT's standard error. Default is ``False``.
mafft_bin (str): Path to MAFFT executable. ``abutils`` includes built-in MAFFT binaries
for MacOS and Linux, however, if a different MAFFT binary can be provided. Default is
``None``, which results in using the appropriate built-in MAFFT binary.
Returns:
Returns a BioPython ``MultipleSeqAlignment`` object, unless ``as_file`` is ``True``,
in which case the path to the alignment file is returned.
'''
if sequences:
fasta_string = _get_fasta_string(sequences)
fasta_file = tempfile.NamedTemporaryFile(delete=False)
fasta_file.close()
ffile = fasta_file.name
with open(ffile, 'w') as f:
f.write(fasta_string)
elif fasta:
ffile = fasta
if alignment_file is None:
alignment_file = tempfile.NamedTemporaryFile(delete=False).name
aln_format = ''
if fmt.lower() == 'clustal':
aln_format = '--clustalout '
if fmt.lower() == 'phylip':
aln_format = '--phylipout '
if reorder:
aln_format += '--reorder '
if mafft_bin is None:
mafft_bin = 'mafft'
# mod_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# mafft_bin = os.path.join(BINARY_DIR, 'mafft_{}'.format(platform.system().lower()))
mafft_cline = '{} --thread {} {}{} > {}'.format(mafft_bin, threads, aln_format, ffile, alignment_file)
mafft = sp.Popen(str(mafft_cline),
stdout=sp.PIPE,
stderr=sp.PIPE,
universal_newlines=True,
shell=True)
stdout, stderr = mafft.communicate()
if print_stdout:
print(mafft_cline)
print(stdout)
if print_stderr:
print(stderr)
os.unlink(ffile)
if os.stat(alignment_file).st_size == 0:
return None
if as_file:
return alignment_file
aln = AlignIO.read(open(alignment_file), fmt)
os.unlink(alignment_file)
return aln | python | def mafft(sequences=None, alignment_file=None, fasta=None, fmt='fasta', threads=-1, as_file=False,
reorder=True, print_stdout=False, print_stderr=False, mafft_bin=None):
'''
Performs multiple sequence alignment with MAFFT.
Args:
sequences (list): Sequences to be aligned. ``sequences`` can be one of four things:
1. a FASTA-formatted string
2. a list of BioPython ``SeqRecord`` objects
3. a list of AbTools ``Sequence`` objects
4. a list of lists/tuples, of the format ``[sequence_id, sequence]``
alignment_file (str): Path for the output alignment file. If not supplied,
a name will be generated using ``tempfile.NamedTemporaryFile()``.
fasta (str): Path to a FASTA-formatted file of sequences. Used as an
alternative to ``sequences`` when suppling a FASTA file.
fmt (str): Format of the alignment. Options are 'fasta', 'phylip', and 'clustal'. Default
is 'fasta'.
threads (int): Number of threads for MAFFT to use. Default is ``-1``, which
results in MAFFT using ``multiprocessing.cpu_count()`` threads.
as_file (bool): If ``True``, returns a path to the alignment file. If ``False``,
returns a BioPython ``MultipleSeqAlignment`` object (obtained by calling
``Bio.AlignIO.read()`` on the alignment file).
print_stdout (bool): If ``True``, prints MAFFT's standard output. Default is ``False``.
print_stderr (bool): If ``True``, prints MAFFT's standard error. Default is ``False``.
mafft_bin (str): Path to MAFFT executable. ``abutils`` includes built-in MAFFT binaries
for MacOS and Linux, however, if a different MAFFT binary can be provided. Default is
``None``, which results in using the appropriate built-in MAFFT binary.
Returns:
Returns a BioPython ``MultipleSeqAlignment`` object, unless ``as_file`` is ``True``,
in which case the path to the alignment file is returned.
'''
if sequences:
fasta_string = _get_fasta_string(sequences)
fasta_file = tempfile.NamedTemporaryFile(delete=False)
fasta_file.close()
ffile = fasta_file.name
with open(ffile, 'w') as f:
f.write(fasta_string)
elif fasta:
ffile = fasta
if alignment_file is None:
alignment_file = tempfile.NamedTemporaryFile(delete=False).name
aln_format = ''
if fmt.lower() == 'clustal':
aln_format = '--clustalout '
if fmt.lower() == 'phylip':
aln_format = '--phylipout '
if reorder:
aln_format += '--reorder '
if mafft_bin is None:
mafft_bin = 'mafft'
# mod_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# mafft_bin = os.path.join(BINARY_DIR, 'mafft_{}'.format(platform.system().lower()))
mafft_cline = '{} --thread {} {}{} > {}'.format(mafft_bin, threads, aln_format, ffile, alignment_file)
mafft = sp.Popen(str(mafft_cline),
stdout=sp.PIPE,
stderr=sp.PIPE,
universal_newlines=True,
shell=True)
stdout, stderr = mafft.communicate()
if print_stdout:
print(mafft_cline)
print(stdout)
if print_stderr:
print(stderr)
os.unlink(ffile)
if os.stat(alignment_file).st_size == 0:
return None
if as_file:
return alignment_file
aln = AlignIO.read(open(alignment_file), fmt)
os.unlink(alignment_file)
return aln | [
"def",
"mafft",
"(",
"sequences",
"=",
"None",
",",
"alignment_file",
"=",
"None",
",",
"fasta",
"=",
"None",
",",
"fmt",
"=",
"'fasta'",
",",
"threads",
"=",
"-",
"1",
",",
"as_file",
"=",
"False",
",",
"reorder",
"=",
"True",
",",
"print_stdout",
"... | Performs multiple sequence alignment with MAFFT.
Args:
sequences (list): Sequences to be aligned. ``sequences`` can be one of four things:
1. a FASTA-formatted string
2. a list of BioPython ``SeqRecord`` objects
3. a list of AbTools ``Sequence`` objects
4. a list of lists/tuples, of the format ``[sequence_id, sequence]``
alignment_file (str): Path for the output alignment file. If not supplied,
a name will be generated using ``tempfile.NamedTemporaryFile()``.
fasta (str): Path to a FASTA-formatted file of sequences. Used as an
alternative to ``sequences`` when suppling a FASTA file.
fmt (str): Format of the alignment. Options are 'fasta', 'phylip', and 'clustal'. Default
is 'fasta'.
threads (int): Number of threads for MAFFT to use. Default is ``-1``, which
results in MAFFT using ``multiprocessing.cpu_count()`` threads.
as_file (bool): If ``True``, returns a path to the alignment file. If ``False``,
returns a BioPython ``MultipleSeqAlignment`` object (obtained by calling
``Bio.AlignIO.read()`` on the alignment file).
print_stdout (bool): If ``True``, prints MAFFT's standard output. Default is ``False``.
print_stderr (bool): If ``True``, prints MAFFT's standard error. Default is ``False``.
mafft_bin (str): Path to MAFFT executable. ``abutils`` includes built-in MAFFT binaries
for MacOS and Linux, however, if a different MAFFT binary can be provided. Default is
``None``, which results in using the appropriate built-in MAFFT binary.
Returns:
Returns a BioPython ``MultipleSeqAlignment`` object, unless ``as_file`` is ``True``,
in which case the path to the alignment file is returned. | [
"Performs",
"multiple",
"sequence",
"alignment",
"with",
"MAFFT",
"."
] | 944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b | https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/utils/alignment.py#L66-L154 | train | 42,613 |
briney/abutils | abutils/utils/alignment.py | muscle | def muscle(sequences=None, alignment_file=None, fasta=None,
fmt='fasta', as_file=False, maxiters=None, diags=False,
gap_open=None, gap_extend=None, muscle_bin=None):
'''
Performs multiple sequence alignment with MUSCLE.
Args:
sequences (list): Sequences to be aligned. ``sequences`` can be one of four things:
1. a FASTA-formatted string
2. a list of BioPython ``SeqRecord`` objects
3. a list of AbTools ``Sequence`` objects
4. a list of lists/tuples, of the format ``[sequence_id, sequence]``
alignment_file (str): Path for the output alignment file. If not supplied,
a name will be generated using ``tempfile.NamedTemporaryFile()``.
fasta (str): Path to a FASTA-formatted file of sequences. Used as an
alternative to ``sequences`` when suppling a FASTA file.
fmt (str): Format of the alignment. Options are 'fasta' and 'clustal'. Default
is 'fasta'.
threads (int): Number of threads (CPU cores) for MUSCLE to use. Default is ``-1``, which
results in MUSCLE using all available cores.
as_file (bool): If ``True``, returns a path to the alignment file. If ``False``,
returns a BioPython ``MultipleSeqAlignment`` object (obtained by calling
``Bio.AlignIO.read()`` on the alignment file).
maxiters (int): Passed directly to MUSCLE using the ``-maxiters`` flag.
diags (int): Passed directly to MUSCLE using the ``-diags`` flag.
gap_open (float): Passed directly to MUSCLE using the ``-gapopen`` flag. Ignored
if ``gap_extend`` is not also provided.
gap_extend (float): Passed directly to MUSCLE using the ``-gapextend`` flag. Ignored
if ``gap_open`` is not also provided.
muscle_bin (str): Path to MUSCLE executable. ``abutils`` includes built-in MUSCLE binaries
for MacOS and Linux, however, if a different MUSCLE binary can be provided. Default is
``None``, which results in using the appropriate built-in MUSCLE binary.
Returns:
Returns a BioPython ``MultipleSeqAlignment`` object, unless ``as_file`` is ``True``,
in which case the path to the alignment file is returned.
'''
if sequences:
fasta_string = _get_fasta_string(sequences)
elif fasta:
fasta_string = open(fasta, 'r').read()
if muscle_bin is None:
# mod_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
muscle_bin = os.path.join(BINARY_DIR, 'muscle_{}'.format(platform.system().lower()))
aln_format = ''
if fmt == 'clustal':
aln_format = ' -clwstrict'
muscle_cline = '{}{} '.format(muscle_bin, aln_format)
if maxiters is not None:
muscle_cline += ' -maxiters {}'.format(maxiters)
if diags:
muscle_cline += ' -diags'
if all([gap_open is not None, gap_extend is not None]):
muscle_cline += ' -gapopen {} -gapextend {}'.format(gap_open, gap_extend)
muscle = sp.Popen(str(muscle_cline),
stdin=sp.PIPE,
stdout=sp.PIPE,
stderr=sp.PIPE,
universal_newlines=True,
shell=True)
if sys.version_info[0] > 2:
alignment = muscle.communicate(input=fasta_string)[0]
else:
alignment = unicode(muscle.communicate(input=fasta_string)[0], 'utf-8')
aln = AlignIO.read(StringIO(alignment), fmt)
if as_file:
if not alignment_file:
alignment_file = tempfile.NamedTemporaryFile().name
AlignIO.write(aln, alignment_file, fmt)
return alignment_file
return aln | python | def muscle(sequences=None, alignment_file=None, fasta=None,
fmt='fasta', as_file=False, maxiters=None, diags=False,
gap_open=None, gap_extend=None, muscle_bin=None):
'''
Performs multiple sequence alignment with MUSCLE.
Args:
sequences (list): Sequences to be aligned. ``sequences`` can be one of four things:
1. a FASTA-formatted string
2. a list of BioPython ``SeqRecord`` objects
3. a list of AbTools ``Sequence`` objects
4. a list of lists/tuples, of the format ``[sequence_id, sequence]``
alignment_file (str): Path for the output alignment file. If not supplied,
a name will be generated using ``tempfile.NamedTemporaryFile()``.
fasta (str): Path to a FASTA-formatted file of sequences. Used as an
alternative to ``sequences`` when suppling a FASTA file.
fmt (str): Format of the alignment. Options are 'fasta' and 'clustal'. Default
is 'fasta'.
threads (int): Number of threads (CPU cores) for MUSCLE to use. Default is ``-1``, which
results in MUSCLE using all available cores.
as_file (bool): If ``True``, returns a path to the alignment file. If ``False``,
returns a BioPython ``MultipleSeqAlignment`` object (obtained by calling
``Bio.AlignIO.read()`` on the alignment file).
maxiters (int): Passed directly to MUSCLE using the ``-maxiters`` flag.
diags (int): Passed directly to MUSCLE using the ``-diags`` flag.
gap_open (float): Passed directly to MUSCLE using the ``-gapopen`` flag. Ignored
if ``gap_extend`` is not also provided.
gap_extend (float): Passed directly to MUSCLE using the ``-gapextend`` flag. Ignored
if ``gap_open`` is not also provided.
muscle_bin (str): Path to MUSCLE executable. ``abutils`` includes built-in MUSCLE binaries
for MacOS and Linux, however, if a different MUSCLE binary can be provided. Default is
``None``, which results in using the appropriate built-in MUSCLE binary.
Returns:
Returns a BioPython ``MultipleSeqAlignment`` object, unless ``as_file`` is ``True``,
in which case the path to the alignment file is returned.
'''
if sequences:
fasta_string = _get_fasta_string(sequences)
elif fasta:
fasta_string = open(fasta, 'r').read()
if muscle_bin is None:
# mod_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
muscle_bin = os.path.join(BINARY_DIR, 'muscle_{}'.format(platform.system().lower()))
aln_format = ''
if fmt == 'clustal':
aln_format = ' -clwstrict'
muscle_cline = '{}{} '.format(muscle_bin, aln_format)
if maxiters is not None:
muscle_cline += ' -maxiters {}'.format(maxiters)
if diags:
muscle_cline += ' -diags'
if all([gap_open is not None, gap_extend is not None]):
muscle_cline += ' -gapopen {} -gapextend {}'.format(gap_open, gap_extend)
muscle = sp.Popen(str(muscle_cline),
stdin=sp.PIPE,
stdout=sp.PIPE,
stderr=sp.PIPE,
universal_newlines=True,
shell=True)
if sys.version_info[0] > 2:
alignment = muscle.communicate(input=fasta_string)[0]
else:
alignment = unicode(muscle.communicate(input=fasta_string)[0], 'utf-8')
aln = AlignIO.read(StringIO(alignment), fmt)
if as_file:
if not alignment_file:
alignment_file = tempfile.NamedTemporaryFile().name
AlignIO.write(aln, alignment_file, fmt)
return alignment_file
return aln | [
"def",
"muscle",
"(",
"sequences",
"=",
"None",
",",
"alignment_file",
"=",
"None",
",",
"fasta",
"=",
"None",
",",
"fmt",
"=",
"'fasta'",
",",
"as_file",
"=",
"False",
",",
"maxiters",
"=",
"None",
",",
"diags",
"=",
"False",
",",
"gap_open",
"=",
"... | Performs multiple sequence alignment with MUSCLE.
Args:
sequences (list): Sequences to be aligned. ``sequences`` can be one of four things:
1. a FASTA-formatted string
2. a list of BioPython ``SeqRecord`` objects
3. a list of AbTools ``Sequence`` objects
4. a list of lists/tuples, of the format ``[sequence_id, sequence]``
alignment_file (str): Path for the output alignment file. If not supplied,
a name will be generated using ``tempfile.NamedTemporaryFile()``.
fasta (str): Path to a FASTA-formatted file of sequences. Used as an
alternative to ``sequences`` when suppling a FASTA file.
fmt (str): Format of the alignment. Options are 'fasta' and 'clustal'. Default
is 'fasta'.
threads (int): Number of threads (CPU cores) for MUSCLE to use. Default is ``-1``, which
results in MUSCLE using all available cores.
as_file (bool): If ``True``, returns a path to the alignment file. If ``False``,
returns a BioPython ``MultipleSeqAlignment`` object (obtained by calling
``Bio.AlignIO.read()`` on the alignment file).
maxiters (int): Passed directly to MUSCLE using the ``-maxiters`` flag.
diags (int): Passed directly to MUSCLE using the ``-diags`` flag.
gap_open (float): Passed directly to MUSCLE using the ``-gapopen`` flag. Ignored
if ``gap_extend`` is not also provided.
gap_extend (float): Passed directly to MUSCLE using the ``-gapextend`` flag. Ignored
if ``gap_open`` is not also provided.
muscle_bin (str): Path to MUSCLE executable. ``abutils`` includes built-in MUSCLE binaries
for MacOS and Linux, however, if a different MUSCLE binary can be provided. Default is
``None``, which results in using the appropriate built-in MUSCLE binary.
Returns:
Returns a BioPython ``MultipleSeqAlignment`` object, unless ``as_file`` is ``True``,
in which case the path to the alignment file is returned. | [
"Performs",
"multiple",
"sequence",
"alignment",
"with",
"MUSCLE",
"."
] | 944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b | https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/utils/alignment.py#L157-L243 | train | 42,614 |
briney/abutils | abutils/utils/alignment.py | local_alignment | def local_alignment(query, target=None, targets=None, match=3, mismatch=-2,
gap_open=-5, gap_extend=-2, matrix=None, aa=False, gap_open_penalty=None, gap_extend_penalty=None):
'''
Striped Smith-Waterman local pairwise alignment.
Args:
query: Query sequence. ``query`` can be one of four things:
1. a nucleotide or amino acid sequence, as a string
2. a Biopython ``SeqRecord`` object
3. an AbTools ``Sequence`` object
4. a list/tuple of the format ``[seq_id, sequence]``
target: A single target sequence. ``target`` can be anything that
``query`` accepts.
targets (list): A list of target sequences, to be proccssed iteratively.
Each element in the ``targets`` list can be anything accepted by
``query``.
match (int): Match score. Should be a positive integer. Default is 3.
mismatch (int): Mismatch score. Should be a negative integer. Default is -2.
gap_open (int): Penalty for opening gaps. Should be a negative integer.
Default is -5.
gap_extend (int): Penalty for extending gaps. Should be a negative
integer. Default is -2.
matrix (str, dict): Alignment scoring matrix. Two options for passing the
alignment matrix:
- The name of a built-in matrix. Current options are ``blosum62`` and ``pam250``.
- A nested dictionary, giving an alignment score for each residue pair. Should be formatted
such that retrieving the alignment score for A and G is accomplished by::
matrix['A']['G']
aa (bool): Must be set to ``True`` if aligning amino acid sequences. Default
is ``False``.
Returns:
If a single target sequence is provided (via ``target``), a single ``SSWAlignment``
object will be returned. If multiple target sequences are supplied (via ``targets``),
a list of ``SSWAlignment`` objects will be returned.
'''
if aa and not matrix:
err = 'ERROR: You must supply a scoring matrix for amino acid alignments'
raise RuntimeError(err)
if not target and not targets:
err = 'ERROR: You must supply a target sequence (or sequences).'
raise RuntimeError(err)
if target:
targets = [target, ]
# to maintain backward compatibility with earlier AbTools API
if gap_open_penalty is not None:
gap_open = -1 * gap_open_penalty
if gap_extend_penalty is not None:
gap_extend = -1 * gap_extend_penalty
alignments = []
for t in targets:
try:
alignment = SSWAlignment(query=query,
target=t,
match=match,
mismatch=mismatch,
matrix=matrix,
gap_open=-1 * gap_open,
gap_extend=-1 * gap_extend,
aa=aa)
alignments.append(alignment)
except IndexError:
continue
if len(alignments) == 1:
return alignments[0]
return alignments | python | def local_alignment(query, target=None, targets=None, match=3, mismatch=-2,
gap_open=-5, gap_extend=-2, matrix=None, aa=False, gap_open_penalty=None, gap_extend_penalty=None):
'''
Striped Smith-Waterman local pairwise alignment.
Args:
query: Query sequence. ``query`` can be one of four things:
1. a nucleotide or amino acid sequence, as a string
2. a Biopython ``SeqRecord`` object
3. an AbTools ``Sequence`` object
4. a list/tuple of the format ``[seq_id, sequence]``
target: A single target sequence. ``target`` can be anything that
``query`` accepts.
targets (list): A list of target sequences, to be proccssed iteratively.
Each element in the ``targets`` list can be anything accepted by
``query``.
match (int): Match score. Should be a positive integer. Default is 3.
mismatch (int): Mismatch score. Should be a negative integer. Default is -2.
gap_open (int): Penalty for opening gaps. Should be a negative integer.
Default is -5.
gap_extend (int): Penalty for extending gaps. Should be a negative
integer. Default is -2.
matrix (str, dict): Alignment scoring matrix. Two options for passing the
alignment matrix:
- The name of a built-in matrix. Current options are ``blosum62`` and ``pam250``.
- A nested dictionary, giving an alignment score for each residue pair. Should be formatted
such that retrieving the alignment score for A and G is accomplished by::
matrix['A']['G']
aa (bool): Must be set to ``True`` if aligning amino acid sequences. Default
is ``False``.
Returns:
If a single target sequence is provided (via ``target``), a single ``SSWAlignment``
object will be returned. If multiple target sequences are supplied (via ``targets``),
a list of ``SSWAlignment`` objects will be returned.
'''
if aa and not matrix:
err = 'ERROR: You must supply a scoring matrix for amino acid alignments'
raise RuntimeError(err)
if not target and not targets:
err = 'ERROR: You must supply a target sequence (or sequences).'
raise RuntimeError(err)
if target:
targets = [target, ]
# to maintain backward compatibility with earlier AbTools API
if gap_open_penalty is not None:
gap_open = -1 * gap_open_penalty
if gap_extend_penalty is not None:
gap_extend = -1 * gap_extend_penalty
alignments = []
for t in targets:
try:
alignment = SSWAlignment(query=query,
target=t,
match=match,
mismatch=mismatch,
matrix=matrix,
gap_open=-1 * gap_open,
gap_extend=-1 * gap_extend,
aa=aa)
alignments.append(alignment)
except IndexError:
continue
if len(alignments) == 1:
return alignments[0]
return alignments | [
"def",
"local_alignment",
"(",
"query",
",",
"target",
"=",
"None",
",",
"targets",
"=",
"None",
",",
"match",
"=",
"3",
",",
"mismatch",
"=",
"-",
"2",
",",
"gap_open",
"=",
"-",
"5",
",",
"gap_extend",
"=",
"-",
"2",
",",
"matrix",
"=",
"None",
... | Striped Smith-Waterman local pairwise alignment.
Args:
query: Query sequence. ``query`` can be one of four things:
1. a nucleotide or amino acid sequence, as a string
2. a Biopython ``SeqRecord`` object
3. an AbTools ``Sequence`` object
4. a list/tuple of the format ``[seq_id, sequence]``
target: A single target sequence. ``target`` can be anything that
``query`` accepts.
targets (list): A list of target sequences, to be proccssed iteratively.
Each element in the ``targets`` list can be anything accepted by
``query``.
match (int): Match score. Should be a positive integer. Default is 3.
mismatch (int): Mismatch score. Should be a negative integer. Default is -2.
gap_open (int): Penalty for opening gaps. Should be a negative integer.
Default is -5.
gap_extend (int): Penalty for extending gaps. Should be a negative
integer. Default is -2.
matrix (str, dict): Alignment scoring matrix. Two options for passing the
alignment matrix:
- The name of a built-in matrix. Current options are ``blosum62`` and ``pam250``.
- A nested dictionary, giving an alignment score for each residue pair. Should be formatted
such that retrieving the alignment score for A and G is accomplished by::
matrix['A']['G']
aa (bool): Must be set to ``True`` if aligning amino acid sequences. Default
is ``False``.
Returns:
If a single target sequence is provided (via ``target``), a single ``SSWAlignment``
object will be returned. If multiple target sequences are supplied (via ``targets``),
a list of ``SSWAlignment`` objects will be returned. | [
"Striped",
"Smith",
"-",
"Waterman",
"local",
"pairwise",
"alignment",
"."
] | 944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b | https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/utils/alignment.py#L279-L361 | train | 42,615 |
briney/abutils | abutils/utils/alignment.py | global_alignment | def global_alignment(query, target=None, targets=None, match=3, mismatch=-2, gap_open=-5, gap_extend=-2,
score_match=None, score_mismatch=None, score_gap_open=None,
score_gap_extend=None, matrix=None, aa=False):
'''
Needleman-Wunch global pairwise alignment.
With ``global_alignment``, you can score an alignment using different
paramaters than were used to compute the alignment. This allows you to
compute pure identity scores (match=1, mismatch=0) on pairs of sequences
for which those alignment parameters would be unsuitable. For example::
seq1 = 'ATGCAGC'
seq2 = 'ATCAAGC'
using identity scoring params (match=1, all penalties are 0) for both alignment
and scoring produces the following alignment::
ATGCA-GC
|| || ||
AT-CAAGC
with an alignment score of 6 and an alignment length of 8 (identity = 75%). But
what if we want to calculate the identity of a gapless alignment? Using::
global_alignment(seq1, seq2,
gap_open=20,
score_match=1,
score_mismatch=0,
score_gap_open=10,
score_gap_extend=1)
we get the following alignment::
ATGCAGC
|| |||
ATCAAGC
which has an score of 5 and an alignment length of 7 (identity = 71%). Obviously,
this is an overly simple example (it would be much easier to force gapless alignment
by just iterating over each sequence and counting the matches), but there are several
real-life cases in which different alignment and scoring paramaters are desirable.
Args:
query: Query sequence. ``query`` can be one of four things:
1. a nucleotide or amino acid sequence, as a string
2. a Biopython ``SeqRecord`` object
3. an AbTools ``Sequence`` object
4. a list/tuple of the format ``[seq_id, sequence]``
target: A single target sequence. ``target`` can be anything that
``query`` accepts.
targets (list): A list of target sequences, to be proccssed iteratively.
Each element in the ``targets`` list can be anything accepted by
``query``.
match (int): Match score for alignment. Should be a positive integer. Default is 3.
mismatch (int): Mismatch score for alignment. Should be a negative integer. Default is -2.
gap_open (int): Penalty for opening gaps in alignment. Should be a negative integer.
Default is -5.
gap_extend (int): Penalty for extending gaps in alignment. Should be a negative
integer. Default is -2.
score_match (int): Match score for scoring the alignment. Should be a positive integer.
Default is to use the score from ``match`` or ``matrix``, whichever is provided.
score_mismatch (int): Mismatch score for scoring the alignment. Should be a negative
integer. Default is to use the score from ``mismatch`` or ``matrix``, whichever
is provided.
score_gap_open (int): Gap open penalty for scoring the alignment. Should be a negative
integer. Default is to use ``gap_open``.
score_gap_extend (int): Gap extend penalty for scoring the alignment. Should be a negative
integer. Default is to use ``gap_extend``.
matrix (str, dict): Alignment scoring matrix. Two options for passing the alignment matrix:
- The name of a built-in matrix. Current options are ``blosum62`` and ``pam250``.
- A nested dictionary, giving an alignment score for each residue pair. Should be
formatted such that retrieving the alignment score for A and G is accomplished by::
matrix['A']['G']
aa (bool): Must be set to ``True`` if aligning amino acid sequences. Default
is ``False``.
Returns:
If a single target sequence is provided (via ``target``), a single ``NWAlignment``
object will be returned. If multiple target sequences are supplied (via ``targets``),
a list of ``NWAlignment`` objects will be returned.
'''
if not target and not targets:
err = 'ERROR: You must supply a target sequence (or sequences).'
raise RuntimeError(err)
if target:
targets = [target, ]
if type(targets) not in (list, tuple):
err = 'ERROR: ::targets:: requires an iterable (list or tuple).'
err += 'For a single sequence, use ::target::'
raise RuntimeError(err)
alignments = []
for t in targets:
alignment = NWAlignment(query=query,
target=t,
match=match,
mismatch=mismatch,
gap_open=gap_open,
gap_extend=gap_extend,
score_match=score_match,
score_mismatch=score_mismatch,
score_gap_open=score_gap_open,
score_gap_extend=score_gap_extend,
matrix=matrix,
aa=aa)
alignments.append(alignment)
if target is not None:
return alignments[0]
return alignments | python | def global_alignment(query, target=None, targets=None, match=3, mismatch=-2, gap_open=-5, gap_extend=-2,
score_match=None, score_mismatch=None, score_gap_open=None,
score_gap_extend=None, matrix=None, aa=False):
'''
Needleman-Wunch global pairwise alignment.
With ``global_alignment``, you can score an alignment using different
paramaters than were used to compute the alignment. This allows you to
compute pure identity scores (match=1, mismatch=0) on pairs of sequences
for which those alignment parameters would be unsuitable. For example::
seq1 = 'ATGCAGC'
seq2 = 'ATCAAGC'
using identity scoring params (match=1, all penalties are 0) for both alignment
and scoring produces the following alignment::
ATGCA-GC
|| || ||
AT-CAAGC
with an alignment score of 6 and an alignment length of 8 (identity = 75%). But
what if we want to calculate the identity of a gapless alignment? Using::
global_alignment(seq1, seq2,
gap_open=20,
score_match=1,
score_mismatch=0,
score_gap_open=10,
score_gap_extend=1)
we get the following alignment::
ATGCAGC
|| |||
ATCAAGC
which has an score of 5 and an alignment length of 7 (identity = 71%). Obviously,
this is an overly simple example (it would be much easier to force gapless alignment
by just iterating over each sequence and counting the matches), but there are several
real-life cases in which different alignment and scoring paramaters are desirable.
Args:
query: Query sequence. ``query`` can be one of four things:
1. a nucleotide or amino acid sequence, as a string
2. a Biopython ``SeqRecord`` object
3. an AbTools ``Sequence`` object
4. a list/tuple of the format ``[seq_id, sequence]``
target: A single target sequence. ``target`` can be anything that
``query`` accepts.
targets (list): A list of target sequences, to be proccssed iteratively.
Each element in the ``targets`` list can be anything accepted by
``query``.
match (int): Match score for alignment. Should be a positive integer. Default is 3.
mismatch (int): Mismatch score for alignment. Should be a negative integer. Default is -2.
gap_open (int): Penalty for opening gaps in alignment. Should be a negative integer.
Default is -5.
gap_extend (int): Penalty for extending gaps in alignment. Should be a negative
integer. Default is -2.
score_match (int): Match score for scoring the alignment. Should be a positive integer.
Default is to use the score from ``match`` or ``matrix``, whichever is provided.
score_mismatch (int): Mismatch score for scoring the alignment. Should be a negative
integer. Default is to use the score from ``mismatch`` or ``matrix``, whichever
is provided.
score_gap_open (int): Gap open penalty for scoring the alignment. Should be a negative
integer. Default is to use ``gap_open``.
score_gap_extend (int): Gap extend penalty for scoring the alignment. Should be a negative
integer. Default is to use ``gap_extend``.
matrix (str, dict): Alignment scoring matrix. Two options for passing the alignment matrix:
- The name of a built-in matrix. Current options are ``blosum62`` and ``pam250``.
- A nested dictionary, giving an alignment score for each residue pair. Should be
formatted such that retrieving the alignment score for A and G is accomplished by::
matrix['A']['G']
aa (bool): Must be set to ``True`` if aligning amino acid sequences. Default
is ``False``.
Returns:
If a single target sequence is provided (via ``target``), a single ``NWAlignment``
object will be returned. If multiple target sequences are supplied (via ``targets``),
a list of ``NWAlignment`` objects will be returned.
'''
if not target and not targets:
err = 'ERROR: You must supply a target sequence (or sequences).'
raise RuntimeError(err)
if target:
targets = [target, ]
if type(targets) not in (list, tuple):
err = 'ERROR: ::targets:: requires an iterable (list or tuple).'
err += 'For a single sequence, use ::target::'
raise RuntimeError(err)
alignments = []
for t in targets:
alignment = NWAlignment(query=query,
target=t,
match=match,
mismatch=mismatch,
gap_open=gap_open,
gap_extend=gap_extend,
score_match=score_match,
score_mismatch=score_mismatch,
score_gap_open=score_gap_open,
score_gap_extend=score_gap_extend,
matrix=matrix,
aa=aa)
alignments.append(alignment)
if target is not None:
return alignments[0]
return alignments | [
"def",
"global_alignment",
"(",
"query",
",",
"target",
"=",
"None",
",",
"targets",
"=",
"None",
",",
"match",
"=",
"3",
",",
"mismatch",
"=",
"-",
"2",
",",
"gap_open",
"=",
"-",
"5",
",",
"gap_extend",
"=",
"-",
"2",
",",
"score_match",
"=",
"No... | Needleman-Wunch global pairwise alignment.
With ``global_alignment``, you can score an alignment using different
paramaters than were used to compute the alignment. This allows you to
compute pure identity scores (match=1, mismatch=0) on pairs of sequences
for which those alignment parameters would be unsuitable. For example::
seq1 = 'ATGCAGC'
seq2 = 'ATCAAGC'
using identity scoring params (match=1, all penalties are 0) for both alignment
and scoring produces the following alignment::
ATGCA-GC
|| || ||
AT-CAAGC
with an alignment score of 6 and an alignment length of 8 (identity = 75%). But
what if we want to calculate the identity of a gapless alignment? Using::
global_alignment(seq1, seq2,
gap_open=20,
score_match=1,
score_mismatch=0,
score_gap_open=10,
score_gap_extend=1)
we get the following alignment::
ATGCAGC
|| |||
ATCAAGC
which has an score of 5 and an alignment length of 7 (identity = 71%). Obviously,
this is an overly simple example (it would be much easier to force gapless alignment
by just iterating over each sequence and counting the matches), but there are several
real-life cases in which different alignment and scoring paramaters are desirable.
Args:
query: Query sequence. ``query`` can be one of four things:
1. a nucleotide or amino acid sequence, as a string
2. a Biopython ``SeqRecord`` object
3. an AbTools ``Sequence`` object
4. a list/tuple of the format ``[seq_id, sequence]``
target: A single target sequence. ``target`` can be anything that
``query`` accepts.
targets (list): A list of target sequences, to be proccssed iteratively.
Each element in the ``targets`` list can be anything accepted by
``query``.
match (int): Match score for alignment. Should be a positive integer. Default is 3.
mismatch (int): Mismatch score for alignment. Should be a negative integer. Default is -2.
gap_open (int): Penalty for opening gaps in alignment. Should be a negative integer.
Default is -5.
gap_extend (int): Penalty for extending gaps in alignment. Should be a negative
integer. Default is -2.
score_match (int): Match score for scoring the alignment. Should be a positive integer.
Default is to use the score from ``match`` or ``matrix``, whichever is provided.
score_mismatch (int): Mismatch score for scoring the alignment. Should be a negative
integer. Default is to use the score from ``mismatch`` or ``matrix``, whichever
is provided.
score_gap_open (int): Gap open penalty for scoring the alignment. Should be a negative
integer. Default is to use ``gap_open``.
score_gap_extend (int): Gap extend penalty for scoring the alignment. Should be a negative
integer. Default is to use ``gap_extend``.
matrix (str, dict): Alignment scoring matrix. Two options for passing the alignment matrix:
- The name of a built-in matrix. Current options are ``blosum62`` and ``pam250``.
- A nested dictionary, giving an alignment score for each residue pair. Should be
formatted such that retrieving the alignment score for A and G is accomplished by::
matrix['A']['G']
aa (bool): Must be set to ``True`` if aligning amino acid sequences. Default
is ``False``.
Returns:
If a single target sequence is provided (via ``target``), a single ``NWAlignment``
object will be returned. If multiple target sequences are supplied (via ``targets``),
a list of ``NWAlignment`` objects will be returned. | [
"Needleman",
"-",
"Wunch",
"global",
"pairwise",
"alignment",
"."
] | 944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b | https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/utils/alignment.py#L390-L518 | train | 42,616 |
AtteqCom/zsl | src/zsl/utils/import_helper.py | fetch_class | def fetch_class(full_class_name):
"""Fetches the given class.
:param string full_class_name: Name of the class to be fetched.
"""
(module_name, class_name) = full_class_name.rsplit('.', 1)
module = importlib.import_module(module_name)
return getattr(module, class_name) | python | def fetch_class(full_class_name):
"""Fetches the given class.
:param string full_class_name: Name of the class to be fetched.
"""
(module_name, class_name) = full_class_name.rsplit('.', 1)
module = importlib.import_module(module_name)
return getattr(module, class_name) | [
"def",
"fetch_class",
"(",
"full_class_name",
")",
":",
"(",
"module_name",
",",
"class_name",
")",
"=",
"full_class_name",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"module_name",
")",
"return",
"getatt... | Fetches the given class.
:param string full_class_name: Name of the class to be fetched. | [
"Fetches",
"the",
"given",
"class",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/import_helper.py#L12-L19 | train | 42,617 |
datacamp/protowhat | protowhat/checks/check_simple.py | has_chosen | def has_chosen(state, correct, msgs):
"""Verify exercises of the type MultipleChoiceExercise
Args:
state: State instance describing student and solution code. Can be omitted if used with Ex().
correct: index of correct option, where 1 is the first option.
msgs : list of feedback messages corresponding to each option.
:Example:
The following SCT is for a multiple choice exercise with 2 options, the first
of which is correct.::
Ex().has_chosen(1, ['Correct!', 'Incorrect. Try again!'])
"""
ctxt = {}
exec(state.student_code, globals(), ctxt)
sel_indx = ctxt["selected_option"]
if sel_indx != correct:
state.report(Feedback(msgs[sel_indx - 1]))
else:
state.reporter.success_msg = msgs[correct - 1]
return state | python | def has_chosen(state, correct, msgs):
"""Verify exercises of the type MultipleChoiceExercise
Args:
state: State instance describing student and solution code. Can be omitted if used with Ex().
correct: index of correct option, where 1 is the first option.
msgs : list of feedback messages corresponding to each option.
:Example:
The following SCT is for a multiple choice exercise with 2 options, the first
of which is correct.::
Ex().has_chosen(1, ['Correct!', 'Incorrect. Try again!'])
"""
ctxt = {}
exec(state.student_code, globals(), ctxt)
sel_indx = ctxt["selected_option"]
if sel_indx != correct:
state.report(Feedback(msgs[sel_indx - 1]))
else:
state.reporter.success_msg = msgs[correct - 1]
return state | [
"def",
"has_chosen",
"(",
"state",
",",
"correct",
",",
"msgs",
")",
":",
"ctxt",
"=",
"{",
"}",
"exec",
"(",
"state",
".",
"student_code",
",",
"globals",
"(",
")",
",",
"ctxt",
")",
"sel_indx",
"=",
"ctxt",
"[",
"\"selected_option\"",
"]",
"if",
"s... | Verify exercises of the type MultipleChoiceExercise
Args:
state: State instance describing student and solution code. Can be omitted if used with Ex().
correct: index of correct option, where 1 is the first option.
msgs : list of feedback messages corresponding to each option.
:Example:
The following SCT is for a multiple choice exercise with 2 options, the first
of which is correct.::
Ex().has_chosen(1, ['Correct!', 'Incorrect. Try again!']) | [
"Verify",
"exercises",
"of",
"the",
"type",
"MultipleChoiceExercise"
] | a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc | https://github.com/datacamp/protowhat/blob/a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc/protowhat/checks/check_simple.py#L4-L27 | train | 42,618 |
datacamp/protowhat | protowhat/checks/check_logic.py | check_or | def check_or(state, *tests):
"""Test whether at least one SCT passes.
If all of the tests fail, the feedback of the first test will be presented to the student.
Args:
state: State instance describing student and solution code, can be omitted if used with Ex()
tests: one or more sub-SCTs to run
:Example:
The SCT below tests that the student typed either 'SELECT' or 'WHERE' (or both).. ::
Ex().check_or(
has_code('SELECT'),
has_code('WHERE')
)
The SCT below checks that a SELECT statement has at least a WHERE c or LIMIT clause.. ::
Ex().check_node('SelectStmt', 0).check_or(
check_edge('where_clause'),
check_edge('limit_clause')
)
"""
success = False
first_feedback = None
for test in iter_tests(tests):
try:
multi(state, test)
success = True
except TestFail as e:
if not first_feedback:
first_feedback = e.feedback
if success:
return state # todo: add test
state.report(first_feedback) | python | def check_or(state, *tests):
"""Test whether at least one SCT passes.
If all of the tests fail, the feedback of the first test will be presented to the student.
Args:
state: State instance describing student and solution code, can be omitted if used with Ex()
tests: one or more sub-SCTs to run
:Example:
The SCT below tests that the student typed either 'SELECT' or 'WHERE' (or both).. ::
Ex().check_or(
has_code('SELECT'),
has_code('WHERE')
)
The SCT below checks that a SELECT statement has at least a WHERE c or LIMIT clause.. ::
Ex().check_node('SelectStmt', 0).check_or(
check_edge('where_clause'),
check_edge('limit_clause')
)
"""
success = False
first_feedback = None
for test in iter_tests(tests):
try:
multi(state, test)
success = True
except TestFail as e:
if not first_feedback:
first_feedback = e.feedback
if success:
return state # todo: add test
state.report(first_feedback) | [
"def",
"check_or",
"(",
"state",
",",
"*",
"tests",
")",
":",
"success",
"=",
"False",
"first_feedback",
"=",
"None",
"for",
"test",
"in",
"iter_tests",
"(",
"tests",
")",
":",
"try",
":",
"multi",
"(",
"state",
",",
"test",
")",
"success",
"=",
"Tru... | Test whether at least one SCT passes.
If all of the tests fail, the feedback of the first test will be presented to the student.
Args:
state: State instance describing student and solution code, can be omitted if used with Ex()
tests: one or more sub-SCTs to run
:Example:
The SCT below tests that the student typed either 'SELECT' or 'WHERE' (or both).. ::
Ex().check_or(
has_code('SELECT'),
has_code('WHERE')
)
The SCT below checks that a SELECT statement has at least a WHERE c or LIMIT clause.. ::
Ex().check_node('SelectStmt', 0).check_or(
check_edge('where_clause'),
check_edge('limit_clause')
) | [
"Test",
"whether",
"at",
"least",
"one",
"SCT",
"passes",
"."
] | a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc | https://github.com/datacamp/protowhat/blob/a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc/protowhat/checks/check_logic.py#L77-L114 | train | 42,619 |
datacamp/protowhat | protowhat/checks/check_logic.py | check_correct | def check_correct(state, check, diagnose):
"""Allows feedback from a diagnostic SCT, only if a check SCT fails.
Args:
state: State instance describing student and solution code. Can be omitted if used with Ex().
check: An sct chain that must succeed.
diagnose: An sct chain to run if the check fails.
:Example:
The SCT below tests whether students query result is correct, before running diagnostic SCTs.. ::
Ex().check_correct(
check_result(),
check_node('SelectStmt')
)
"""
feedback = None
try:
multi(state, check)
except TestFail as e:
feedback = e.feedback
# todo: let if from except wrap try-except
# only once teach uses force_diagnose
try:
multi(state, diagnose)
except TestFail as e:
if feedback is not None or state.force_diagnose:
feedback = e.feedback
if feedback is not None:
state.report(feedback)
return state | python | def check_correct(state, check, diagnose):
"""Allows feedback from a diagnostic SCT, only if a check SCT fails.
Args:
state: State instance describing student and solution code. Can be omitted if used with Ex().
check: An sct chain that must succeed.
diagnose: An sct chain to run if the check fails.
:Example:
The SCT below tests whether students query result is correct, before running diagnostic SCTs.. ::
Ex().check_correct(
check_result(),
check_node('SelectStmt')
)
"""
feedback = None
try:
multi(state, check)
except TestFail as e:
feedback = e.feedback
# todo: let if from except wrap try-except
# only once teach uses force_diagnose
try:
multi(state, diagnose)
except TestFail as e:
if feedback is not None or state.force_diagnose:
feedback = e.feedback
if feedback is not None:
state.report(feedback)
return state | [
"def",
"check_correct",
"(",
"state",
",",
"check",
",",
"diagnose",
")",
":",
"feedback",
"=",
"None",
"try",
":",
"multi",
"(",
"state",
",",
"check",
")",
"except",
"TestFail",
"as",
"e",
":",
"feedback",
"=",
"e",
".",
"feedback",
"# todo: let if fro... | Allows feedback from a diagnostic SCT, only if a check SCT fails.
Args:
state: State instance describing student and solution code. Can be omitted if used with Ex().
check: An sct chain that must succeed.
diagnose: An sct chain to run if the check fails.
:Example:
The SCT below tests whether students query result is correct, before running diagnostic SCTs.. ::
Ex().check_correct(
check_result(),
check_node('SelectStmt')
) | [
"Allows",
"feedback",
"from",
"a",
"diagnostic",
"SCT",
"only",
"if",
"a",
"check",
"SCT",
"fails",
"."
] | a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc | https://github.com/datacamp/protowhat/blob/a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc/protowhat/checks/check_logic.py#L117-L151 | train | 42,620 |
datacamp/protowhat | protowhat/checks/check_logic.py | fail | def fail(state, msg="fail"):
"""Always fails the SCT, with an optional msg.
This function takes a single argument, ``msg``, that is the feedback given to the student.
Note that this would be a terrible idea for grading submissions, but may be useful while writing SCTs.
For example, failing a test will highlight the code as if the previous test/check had failed.
"""
_msg = state.build_message(msg)
state.report(Feedback(_msg, state))
return state | python | def fail(state, msg="fail"):
"""Always fails the SCT, with an optional msg.
This function takes a single argument, ``msg``, that is the feedback given to the student.
Note that this would be a terrible idea for grading submissions, but may be useful while writing SCTs.
For example, failing a test will highlight the code as if the previous test/check had failed.
"""
_msg = state.build_message(msg)
state.report(Feedback(_msg, state))
return state | [
"def",
"fail",
"(",
"state",
",",
"msg",
"=",
"\"fail\"",
")",
":",
"_msg",
"=",
"state",
".",
"build_message",
"(",
"msg",
")",
"state",
".",
"report",
"(",
"Feedback",
"(",
"_msg",
",",
"state",
")",
")",
"return",
"state"
] | Always fails the SCT, with an optional msg.
This function takes a single argument, ``msg``, that is the feedback given to the student.
Note that this would be a terrible idea for grading submissions, but may be useful while writing SCTs.
For example, failing a test will highlight the code as if the previous test/check had failed. | [
"Always",
"fails",
"the",
"SCT",
"with",
"an",
"optional",
"msg",
"."
] | a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc | https://github.com/datacamp/protowhat/blob/a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc/protowhat/checks/check_logic.py#L175-L185 | train | 42,621 |
AtteqCom/zsl | src/zsl/utils/xml_helper.py | required_attributes | def required_attributes(element, *attributes):
"""Check element for required attributes. Raise ``NotValidXmlException`` on error.
:param element: ElementTree element
:param attributes: list of attributes names to check
:raises NotValidXmlException: if some argument is missing
"""
if not reduce(lambda still_valid, param: still_valid and param in element.attrib, attributes, True):
raise NotValidXmlException(msg_err_missing_attributes(element.tag, *attributes)) | python | def required_attributes(element, *attributes):
"""Check element for required attributes. Raise ``NotValidXmlException`` on error.
:param element: ElementTree element
:param attributes: list of attributes names to check
:raises NotValidXmlException: if some argument is missing
"""
if not reduce(lambda still_valid, param: still_valid and param in element.attrib, attributes, True):
raise NotValidXmlException(msg_err_missing_attributes(element.tag, *attributes)) | [
"def",
"required_attributes",
"(",
"element",
",",
"*",
"attributes",
")",
":",
"if",
"not",
"reduce",
"(",
"lambda",
"still_valid",
",",
"param",
":",
"still_valid",
"and",
"param",
"in",
"element",
".",
"attrib",
",",
"attributes",
",",
"True",
")",
":",... | Check element for required attributes. Raise ``NotValidXmlException`` on error.
:param element: ElementTree element
:param attributes: list of attributes names to check
:raises NotValidXmlException: if some argument is missing | [
"Check",
"element",
"for",
"required",
"attributes",
".",
"Raise",
"NotValidXmlException",
"on",
"error",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/xml_helper.py#L22-L30 | train | 42,622 |
AtteqCom/zsl | src/zsl/utils/xml_helper.py | required_items | def required_items(element, children, attributes):
"""Check an xml element to include given attributes and children.
:param element: ElementTree element
:param children: list of XPaths to check
:param attributes: list of attributes names to check
:raises NotValidXmlException: if some argument is missing
:raises NotValidXmlException: if some child is missing
"""
required_elements(element, *children)
required_attributes(element, *attributes) | python | def required_items(element, children, attributes):
"""Check an xml element to include given attributes and children.
:param element: ElementTree element
:param children: list of XPaths to check
:param attributes: list of attributes names to check
:raises NotValidXmlException: if some argument is missing
:raises NotValidXmlException: if some child is missing
"""
required_elements(element, *children)
required_attributes(element, *attributes) | [
"def",
"required_items",
"(",
"element",
",",
"children",
",",
"attributes",
")",
":",
"required_elements",
"(",
"element",
",",
"*",
"children",
")",
"required_attributes",
"(",
"element",
",",
"*",
"attributes",
")"
] | Check an xml element to include given attributes and children.
:param element: ElementTree element
:param children: list of XPaths to check
:param attributes: list of attributes names to check
:raises NotValidXmlException: if some argument is missing
:raises NotValidXmlException: if some child is missing | [
"Check",
"an",
"xml",
"element",
"to",
"include",
"given",
"attributes",
"and",
"children",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/xml_helper.py#L46-L56 | train | 42,623 |
AtteqCom/zsl | src/zsl/utils/xml_helper.py | attrib_to_dict | def attrib_to_dict(element, *args, **kwargs):
"""For an ElementTree ``element`` extract specified attributes. If an attribute does not exists, its value will be
``None``.
attrib_to_dict(element, 'attr_a', 'attr_b') -> {'attr_a': 'value', 'attr_a': 'value'}
Mapping between xml attributes and dictionary keys is done with kwargs.
attrib_to_dict(element, my_new_name = 'xml_atribute_name', ..)
"""
if len(args) > 0:
return {key: element.get(key) for key in args}
if len(kwargs) > 0:
return {new_key: element.get(old_key) for new_key, old_key in viewitems(kwargs)}
return element.attrib | python | def attrib_to_dict(element, *args, **kwargs):
"""For an ElementTree ``element`` extract specified attributes. If an attribute does not exists, its value will be
``None``.
attrib_to_dict(element, 'attr_a', 'attr_b') -> {'attr_a': 'value', 'attr_a': 'value'}
Mapping between xml attributes and dictionary keys is done with kwargs.
attrib_to_dict(element, my_new_name = 'xml_atribute_name', ..)
"""
if len(args) > 0:
return {key: element.get(key) for key in args}
if len(kwargs) > 0:
return {new_key: element.get(old_key) for new_key, old_key in viewitems(kwargs)}
return element.attrib | [
"def",
"attrib_to_dict",
"(",
"element",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"args",
")",
">",
"0",
":",
"return",
"{",
"key",
":",
"element",
".",
"get",
"(",
"key",
")",
"for",
"key",
"in",
"args",
"}",
"if"... | For an ElementTree ``element`` extract specified attributes. If an attribute does not exists, its value will be
``None``.
attrib_to_dict(element, 'attr_a', 'attr_b') -> {'attr_a': 'value', 'attr_a': 'value'}
Mapping between xml attributes and dictionary keys is done with kwargs.
attrib_to_dict(element, my_new_name = 'xml_atribute_name', ..) | [
"For",
"an",
"ElementTree",
"element",
"extract",
"specified",
"attributes",
".",
"If",
"an",
"attribute",
"does",
"not",
"exists",
"its",
"value",
"will",
"be",
"None",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/xml_helper.py#L81-L96 | train | 42,624 |
AtteqCom/zsl | src/zsl/utils/xml_helper.py | get_xml_root | def get_xml_root(xml_path):
"""Load and parse an xml by given xml_path and return its root.
:param xml_path: URL to a xml file
:type xml_path: str
:return: xml root
"""
r = requests.get(xml_path)
root = ET.fromstring(r.content)
return root | python | def get_xml_root(xml_path):
"""Load and parse an xml by given xml_path and return its root.
:param xml_path: URL to a xml file
:type xml_path: str
:return: xml root
"""
r = requests.get(xml_path)
root = ET.fromstring(r.content)
return root | [
"def",
"get_xml_root",
"(",
"xml_path",
")",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"xml_path",
")",
"root",
"=",
"ET",
".",
"fromstring",
"(",
"r",
".",
"content",
")",
"return",
"root"
] | Load and parse an xml by given xml_path and return its root.
:param xml_path: URL to a xml file
:type xml_path: str
:return: xml root | [
"Load",
"and",
"parse",
"an",
"xml",
"by",
"given",
"xml_path",
"and",
"return",
"its",
"root",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/xml_helper.py#L99-L108 | train | 42,625 |
AtteqCom/zsl | src/zsl/utils/xml_helper.py | element_to_int | def element_to_int(element, attribute=None):
"""Convert ``element`` object to int. If attribute is not given, convert ``element.text``.
:param element: ElementTree element
:param attribute: attribute name
:type attribute: str
:returns: integer
:rtype: int
"""
if attribute is not None:
return int(element.get(attribute))
else:
return int(element.text) | python | def element_to_int(element, attribute=None):
"""Convert ``element`` object to int. If attribute is not given, convert ``element.text``.
:param element: ElementTree element
:param attribute: attribute name
:type attribute: str
:returns: integer
:rtype: int
"""
if attribute is not None:
return int(element.get(attribute))
else:
return int(element.text) | [
"def",
"element_to_int",
"(",
"element",
",",
"attribute",
"=",
"None",
")",
":",
"if",
"attribute",
"is",
"not",
"None",
":",
"return",
"int",
"(",
"element",
".",
"get",
"(",
"attribute",
")",
")",
"else",
":",
"return",
"int",
"(",
"element",
".",
... | Convert ``element`` object to int. If attribute is not given, convert ``element.text``.
:param element: ElementTree element
:param attribute: attribute name
:type attribute: str
:returns: integer
:rtype: int | [
"Convert",
"element",
"object",
"to",
"int",
".",
"If",
"attribute",
"is",
"not",
"given",
"convert",
"element",
".",
"text",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/xml_helper.py#L111-L123 | train | 42,626 |
AtteqCom/zsl | src/zsl/application/containers/container.py | IoCContainer.modules | def modules(cls):
"""Collect all the public class attributes.
All class attributes should be a DI modules, this method collects them
and returns as a list.
:return: list of DI modules
:rtype: list[Union[Module, Callable]]
"""
members = inspect.getmembers(cls, lambda a: not (inspect.isroutine(a) and a.__name__ == 'modules'))
modules = [module for name, module in members if not name.startswith('_')]
return modules | python | def modules(cls):
"""Collect all the public class attributes.
All class attributes should be a DI modules, this method collects them
and returns as a list.
:return: list of DI modules
:rtype: list[Union[Module, Callable]]
"""
members = inspect.getmembers(cls, lambda a: not (inspect.isroutine(a) and a.__name__ == 'modules'))
modules = [module for name, module in members if not name.startswith('_')]
return modules | [
"def",
"modules",
"(",
"cls",
")",
":",
"members",
"=",
"inspect",
".",
"getmembers",
"(",
"cls",
",",
"lambda",
"a",
":",
"not",
"(",
"inspect",
".",
"isroutine",
"(",
"a",
")",
"and",
"a",
".",
"__name__",
"==",
"'modules'",
")",
")",
"modules",
... | Collect all the public class attributes.
All class attributes should be a DI modules, this method collects them
and returns as a list.
:return: list of DI modules
:rtype: list[Union[Module, Callable]] | [
"Collect",
"all",
"the",
"public",
"class",
"attributes",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/application/containers/container.py#L24-L35 | train | 42,627 |
briney/abutils | abutils/core/pair.py | get_pairs | def get_pairs(db, collection, experiment=None, subject=None, group=None, name='seq_id',
delim=None, delim_occurance=1, pairs_only=False, h_selection_func=None, l_selection_func=None):
'''
Gets sequences and assigns them to the appropriate mAb pair, based on the sequence name.
Inputs:
::db:: is a pymongo database connection object
::collection:: is the collection name, as a string
If ::subject:: is provided, only sequences with a 'subject' field matching ::subject:: will
be included. ::subject:: can be either a single subject (as a string) or an iterable
(list or tuple) of subject strings.
If ::group:: is provided, only sequences with a 'group' field matching ::group:: will
be included. ::group:: can be either a single group (as a string) or an iterable
(list or tuple) of group strings.
::name:: is the dict key of the field to be used to group the sequences into pairs.
Default is 'seq_id'
::delim:: is an optional delimiter used to truncate the contents of the ::name:: field.
Default is None, which results in no name truncation.
::delim_occurance:: is the occurance of the delimiter at which to trim. Trimming is performed
as delim.join(name.split(delim)[:delim_occurance]), so setting delim_occurance to -1 will
trucate after the last occurance of delim. Default is 1.
::pairs_only:: setting to True results in only truly paired sequences (pair.is_pair == True)
will be returned. Default is False.
Returns a list of Pair objects, one for each mAb pair.
'''
match = {}
if subject is not None:
if type(subject) in (list, tuple):
match['subject'] = {'$in': subject}
elif type(subject) in STR_TYPES:
match['subject'] = subject
if group is not None:
if type(group) in (list, tuple):
match['group'] = {'$in': group}
elif type(group) in STR_TYPES:
match['group'] = group
if experiment is not None:
if type(experiment) in (list, tuple):
match['experiment'] = {'$in': experiment}
elif type(experiment) in STR_TYPES:
match['experiment'] = experiment
seqs = list(db[collection].find(match))
return assign_pairs(seqs, name=name, delim=delim,
delim_occurance=delim_occurance, pairs_only=pairs_only,
h_selection_func=h_selection_func, l_selection_func=l_selection_func) | python | def get_pairs(db, collection, experiment=None, subject=None, group=None, name='seq_id',
delim=None, delim_occurance=1, pairs_only=False, h_selection_func=None, l_selection_func=None):
'''
Gets sequences and assigns them to the appropriate mAb pair, based on the sequence name.
Inputs:
::db:: is a pymongo database connection object
::collection:: is the collection name, as a string
If ::subject:: is provided, only sequences with a 'subject' field matching ::subject:: will
be included. ::subject:: can be either a single subject (as a string) or an iterable
(list or tuple) of subject strings.
If ::group:: is provided, only sequences with a 'group' field matching ::group:: will
be included. ::group:: can be either a single group (as a string) or an iterable
(list or tuple) of group strings.
::name:: is the dict key of the field to be used to group the sequences into pairs.
Default is 'seq_id'
::delim:: is an optional delimiter used to truncate the contents of the ::name:: field.
Default is None, which results in no name truncation.
::delim_occurance:: is the occurance of the delimiter at which to trim. Trimming is performed
as delim.join(name.split(delim)[:delim_occurance]), so setting delim_occurance to -1 will
trucate after the last occurance of delim. Default is 1.
::pairs_only:: setting to True results in only truly paired sequences (pair.is_pair == True)
will be returned. Default is False.
Returns a list of Pair objects, one for each mAb pair.
'''
match = {}
if subject is not None:
if type(subject) in (list, tuple):
match['subject'] = {'$in': subject}
elif type(subject) in STR_TYPES:
match['subject'] = subject
if group is not None:
if type(group) in (list, tuple):
match['group'] = {'$in': group}
elif type(group) in STR_TYPES:
match['group'] = group
if experiment is not None:
if type(experiment) in (list, tuple):
match['experiment'] = {'$in': experiment}
elif type(experiment) in STR_TYPES:
match['experiment'] = experiment
seqs = list(db[collection].find(match))
return assign_pairs(seqs, name=name, delim=delim,
delim_occurance=delim_occurance, pairs_only=pairs_only,
h_selection_func=h_selection_func, l_selection_func=l_selection_func) | [
"def",
"get_pairs",
"(",
"db",
",",
"collection",
",",
"experiment",
"=",
"None",
",",
"subject",
"=",
"None",
",",
"group",
"=",
"None",
",",
"name",
"=",
"'seq_id'",
",",
"delim",
"=",
"None",
",",
"delim_occurance",
"=",
"1",
",",
"pairs_only",
"=",... | Gets sequences and assigns them to the appropriate mAb pair, based on the sequence name.
Inputs:
::db:: is a pymongo database connection object
::collection:: is the collection name, as a string
If ::subject:: is provided, only sequences with a 'subject' field matching ::subject:: will
be included. ::subject:: can be either a single subject (as a string) or an iterable
(list or tuple) of subject strings.
If ::group:: is provided, only sequences with a 'group' field matching ::group:: will
be included. ::group:: can be either a single group (as a string) or an iterable
(list or tuple) of group strings.
::name:: is the dict key of the field to be used to group the sequences into pairs.
Default is 'seq_id'
::delim:: is an optional delimiter used to truncate the contents of the ::name:: field.
Default is None, which results in no name truncation.
::delim_occurance:: is the occurance of the delimiter at which to trim. Trimming is performed
as delim.join(name.split(delim)[:delim_occurance]), so setting delim_occurance to -1 will
trucate after the last occurance of delim. Default is 1.
::pairs_only:: setting to True results in only truly paired sequences (pair.is_pair == True)
will be returned. Default is False.
Returns a list of Pair objects, one for each mAb pair. | [
"Gets",
"sequences",
"and",
"assigns",
"them",
"to",
"the",
"appropriate",
"mAb",
"pair",
"based",
"on",
"the",
"sequence",
"name",
"."
] | 944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b | https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/core/pair.py#L328-L374 | train | 42,628 |
briney/abutils | abutils/core/pair.py | assign_pairs | def assign_pairs(seqs, name='seq_id', delim=None, delim_occurance=1, pairs_only=False,
h_selection_func=None, l_selection_func=None):
'''
Assigns sequences to the appropriate mAb pair, based on the sequence name.
Inputs:
::seqs:: is a list of dicts, of the format returned by querying a MongoDB containing
Abstar output.
::name:: is the dict key of the field to be used to group the sequences into pairs.
Default is 'seq_id'
::delim:: is an optional delimiter used to truncate the contents of the ::name:: field.
Default is None, which results in no name truncation.
::delim_occurance:: is the occurance of the delimiter at which to trim. Trimming is performed
as delim.join(name.split(delim)[:delim_occurance]), so setting delim_occurance to -1 will
trucate after the last occurance of delim. Default is 1.
::pairs_only:: setting to True results in only truly paired sequences (pair.is_pair == True)
will be returned. Default is False.
Returns a list of Pair objects, one for each mAb pair.
'''
pdict = {}
for s in seqs:
if delim is not None:
pname = delim.join(s[name].split(delim)[:delim_occurance])
else:
pname = s[name]
if pname not in pdict:
pdict[pname] = [s, ]
else:
pdict[pname].append(s)
pairs = [Pair(pdict[n], name=n,
h_selection_func=h_selection_func,
l_selection_func=l_selection_func) for n in pdict.keys()]
if pairs_only:
pairs = [p for p in pairs if p.is_pair]
return pairs | python | def assign_pairs(seqs, name='seq_id', delim=None, delim_occurance=1, pairs_only=False,
h_selection_func=None, l_selection_func=None):
'''
Assigns sequences to the appropriate mAb pair, based on the sequence name.
Inputs:
::seqs:: is a list of dicts, of the format returned by querying a MongoDB containing
Abstar output.
::name:: is the dict key of the field to be used to group the sequences into pairs.
Default is 'seq_id'
::delim:: is an optional delimiter used to truncate the contents of the ::name:: field.
Default is None, which results in no name truncation.
::delim_occurance:: is the occurance of the delimiter at which to trim. Trimming is performed
as delim.join(name.split(delim)[:delim_occurance]), so setting delim_occurance to -1 will
trucate after the last occurance of delim. Default is 1.
::pairs_only:: setting to True results in only truly paired sequences (pair.is_pair == True)
will be returned. Default is False.
Returns a list of Pair objects, one for each mAb pair.
'''
pdict = {}
for s in seqs:
if delim is not None:
pname = delim.join(s[name].split(delim)[:delim_occurance])
else:
pname = s[name]
if pname not in pdict:
pdict[pname] = [s, ]
else:
pdict[pname].append(s)
pairs = [Pair(pdict[n], name=n,
h_selection_func=h_selection_func,
l_selection_func=l_selection_func) for n in pdict.keys()]
if pairs_only:
pairs = [p for p in pairs if p.is_pair]
return pairs | [
"def",
"assign_pairs",
"(",
"seqs",
",",
"name",
"=",
"'seq_id'",
",",
"delim",
"=",
"None",
",",
"delim_occurance",
"=",
"1",
",",
"pairs_only",
"=",
"False",
",",
"h_selection_func",
"=",
"None",
",",
"l_selection_func",
"=",
"None",
")",
":",
"pdict",
... | Assigns sequences to the appropriate mAb pair, based on the sequence name.
Inputs:
::seqs:: is a list of dicts, of the format returned by querying a MongoDB containing
Abstar output.
::name:: is the dict key of the field to be used to group the sequences into pairs.
Default is 'seq_id'
::delim:: is an optional delimiter used to truncate the contents of the ::name:: field.
Default is None, which results in no name truncation.
::delim_occurance:: is the occurance of the delimiter at which to trim. Trimming is performed
as delim.join(name.split(delim)[:delim_occurance]), so setting delim_occurance to -1 will
trucate after the last occurance of delim. Default is 1.
::pairs_only:: setting to True results in only truly paired sequences (pair.is_pair == True)
will be returned. Default is False.
Returns a list of Pair objects, one for each mAb pair. | [
"Assigns",
"sequences",
"to",
"the",
"appropriate",
"mAb",
"pair",
"based",
"on",
"the",
"sequence",
"name",
"."
] | 944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b | https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/core/pair.py#L377-L413 | train | 42,629 |
briney/abutils | abutils/core/pair.py | deduplicate | def deduplicate(pairs, aa=False, ignore_primer_regions=False):
'''
Removes duplicate sequences from a list of Pair objects.
If a Pair has heavy and light chains, both chains must identically match heavy and light chains
from another Pair to be considered a duplicate. If a Pair has only a single chain,
identical matches to that chain will cause the single chain Pair to be considered a duplicate,
even if the comparison Pair has both chains.
Note that identical sequences are identified by simple string comparison, so sequences of
different length that are identical over the entirety of the shorter sequence are not
considered duplicates.
By default, comparison is made on the nucleotide sequence. To use the amino acid sequence instead,
set aa=True.
'''
nr_pairs = []
just_pairs = [p for p in pairs if p.is_pair]
single_chains = [p for p in pairs if not p.is_pair]
_pairs = just_pairs + single_chains
for p in _pairs:
duplicates = []
for nr in nr_pairs:
identical = True
vdj = 'vdj_aa' if aa else 'vdj_nt'
offset = 4 if aa else 12
if p.heavy is not None:
if nr.heavy is None:
identical = False
else:
heavy = p.heavy[vdj][offset:-offset] if ignore_primer_regions else p.heavy[vdj]
nr_heavy = nr.heavy[vdj][offset:-offset] if ignore_primer_regions else nr.heavy[vdj]
if heavy != nr_heavy:
identical = False
if p.light is not None:
if nr.light is None:
identical = False
else:
light = p.light[vdj][offset:-offset] if ignore_primer_regions else p.light[vdj]
nr_light = nr.light[vdj][offset:-offset] if ignore_primer_regions else nr.light[vdj]
if light != nr_light:
identical = False
duplicates.append(identical)
if any(duplicates):
continue
else:
nr_pairs.append(p)
return nr_pairs | python | def deduplicate(pairs, aa=False, ignore_primer_regions=False):
'''
Removes duplicate sequences from a list of Pair objects.
If a Pair has heavy and light chains, both chains must identically match heavy and light chains
from another Pair to be considered a duplicate. If a Pair has only a single chain,
identical matches to that chain will cause the single chain Pair to be considered a duplicate,
even if the comparison Pair has both chains.
Note that identical sequences are identified by simple string comparison, so sequences of
different length that are identical over the entirety of the shorter sequence are not
considered duplicates.
By default, comparison is made on the nucleotide sequence. To use the amino acid sequence instead,
set aa=True.
'''
nr_pairs = []
just_pairs = [p for p in pairs if p.is_pair]
single_chains = [p for p in pairs if not p.is_pair]
_pairs = just_pairs + single_chains
for p in _pairs:
duplicates = []
for nr in nr_pairs:
identical = True
vdj = 'vdj_aa' if aa else 'vdj_nt'
offset = 4 if aa else 12
if p.heavy is not None:
if nr.heavy is None:
identical = False
else:
heavy = p.heavy[vdj][offset:-offset] if ignore_primer_regions else p.heavy[vdj]
nr_heavy = nr.heavy[vdj][offset:-offset] if ignore_primer_regions else nr.heavy[vdj]
if heavy != nr_heavy:
identical = False
if p.light is not None:
if nr.light is None:
identical = False
else:
light = p.light[vdj][offset:-offset] if ignore_primer_regions else p.light[vdj]
nr_light = nr.light[vdj][offset:-offset] if ignore_primer_regions else nr.light[vdj]
if light != nr_light:
identical = False
duplicates.append(identical)
if any(duplicates):
continue
else:
nr_pairs.append(p)
return nr_pairs | [
"def",
"deduplicate",
"(",
"pairs",
",",
"aa",
"=",
"False",
",",
"ignore_primer_regions",
"=",
"False",
")",
":",
"nr_pairs",
"=",
"[",
"]",
"just_pairs",
"=",
"[",
"p",
"for",
"p",
"in",
"pairs",
"if",
"p",
".",
"is_pair",
"]",
"single_chains",
"=",
... | Removes duplicate sequences from a list of Pair objects.
If a Pair has heavy and light chains, both chains must identically match heavy and light chains
from another Pair to be considered a duplicate. If a Pair has only a single chain,
identical matches to that chain will cause the single chain Pair to be considered a duplicate,
even if the comparison Pair has both chains.
Note that identical sequences are identified by simple string comparison, so sequences of
different length that are identical over the entirety of the shorter sequence are not
considered duplicates.
By default, comparison is made on the nucleotide sequence. To use the amino acid sequence instead,
set aa=True. | [
"Removes",
"duplicate",
"sequences",
"from",
"a",
"list",
"of",
"Pair",
"objects",
"."
] | 944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b | https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/core/pair.py#L416-L463 | train | 42,630 |
briney/abutils | abutils/core/pair.py | Pair.fasta | def fasta(self, key='vdj_nt', append_chain=True):
'''
Returns the sequence pair as a fasta string. If the Pair object contains
both heavy and light chain sequences, both will be returned as a single string.
By default, the fasta string contains the 'vdj_nt' sequence for each chain. To change,
use the <key> option to select an alternate sequence.
By default, the chain (heavy or light) will be appended to the sequence name:
>MySequence_heavy
To just use the pair name (which will result in duplicate sequence names for Pair objects
with both heavy and light chains), set <append_chain> to False.
'''
fastas = []
for s, chain in [(self.heavy, 'heavy'), (self.light, 'light')]:
if s is not None:
c = '_{}'.format(chain) if append_chain else ''
fastas.append('>{}{}\n{}'.format(s['seq_id'], c, s[key]))
return '\n'.join(fastas) | python | def fasta(self, key='vdj_nt', append_chain=True):
'''
Returns the sequence pair as a fasta string. If the Pair object contains
both heavy and light chain sequences, both will be returned as a single string.
By default, the fasta string contains the 'vdj_nt' sequence for each chain. To change,
use the <key> option to select an alternate sequence.
By default, the chain (heavy or light) will be appended to the sequence name:
>MySequence_heavy
To just use the pair name (which will result in duplicate sequence names for Pair objects
with both heavy and light chains), set <append_chain> to False.
'''
fastas = []
for s, chain in [(self.heavy, 'heavy'), (self.light, 'light')]:
if s is not None:
c = '_{}'.format(chain) if append_chain else ''
fastas.append('>{}{}\n{}'.format(s['seq_id'], c, s[key]))
return '\n'.join(fastas) | [
"def",
"fasta",
"(",
"self",
",",
"key",
"=",
"'vdj_nt'",
",",
"append_chain",
"=",
"True",
")",
":",
"fastas",
"=",
"[",
"]",
"for",
"s",
",",
"chain",
"in",
"[",
"(",
"self",
".",
"heavy",
",",
"'heavy'",
")",
",",
"(",
"self",
".",
"light",
... | Returns the sequence pair as a fasta string. If the Pair object contains
both heavy and light chain sequences, both will be returned as a single string.
By default, the fasta string contains the 'vdj_nt' sequence for each chain. To change,
use the <key> option to select an alternate sequence.
By default, the chain (heavy or light) will be appended to the sequence name:
>MySequence_heavy
To just use the pair name (which will result in duplicate sequence names for Pair objects
with both heavy and light chains), set <append_chain> to False. | [
"Returns",
"the",
"sequence",
"pair",
"as",
"a",
"fasta",
"string",
".",
"If",
"the",
"Pair",
"object",
"contains",
"both",
"heavy",
"and",
"light",
"chain",
"sequences",
"both",
"will",
"be",
"returned",
"as",
"a",
"single",
"string",
"."
] | 944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b | https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/core/pair.py#L305-L325 | train | 42,631 |
briney/abutils | abutils/utils/color.py | cmap_from_color | def cmap_from_color(color, dark=False):
'''
Generates a matplotlib colormap from a single color.
Colormap will be built, by default, from white to ``color``.
Args:
color: Can be one of several things:
1. Hex code
2. HTML color name
3. RGB tuple
dark (bool): If ``True``, colormap will be built from ``color`` to
black. Default is ``False``, which builds a colormap from
white to ``color``.
Returns:
colormap: A matplotlib colormap
'''
if dark:
return sns.dark_palette(color, as_cmap=True)
else:
return sns.light_palette(color, as_cmap=True) | python | def cmap_from_color(color, dark=False):
'''
Generates a matplotlib colormap from a single color.
Colormap will be built, by default, from white to ``color``.
Args:
color: Can be one of several things:
1. Hex code
2. HTML color name
3. RGB tuple
dark (bool): If ``True``, colormap will be built from ``color`` to
black. Default is ``False``, which builds a colormap from
white to ``color``.
Returns:
colormap: A matplotlib colormap
'''
if dark:
return sns.dark_palette(color, as_cmap=True)
else:
return sns.light_palette(color, as_cmap=True) | [
"def",
"cmap_from_color",
"(",
"color",
",",
"dark",
"=",
"False",
")",
":",
"if",
"dark",
":",
"return",
"sns",
".",
"dark_palette",
"(",
"color",
",",
"as_cmap",
"=",
"True",
")",
"else",
":",
"return",
"sns",
".",
"light_palette",
"(",
"color",
",",... | Generates a matplotlib colormap from a single color.
Colormap will be built, by default, from white to ``color``.
Args:
color: Can be one of several things:
1. Hex code
2. HTML color name
3. RGB tuple
dark (bool): If ``True``, colormap will be built from ``color`` to
black. Default is ``False``, which builds a colormap from
white to ``color``.
Returns:
colormap: A matplotlib colormap | [
"Generates",
"a",
"matplotlib",
"colormap",
"from",
"a",
"single",
"color",
"."
] | 944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b | https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/utils/color.py#L44-L70 | train | 42,632 |
datacamp/protowhat | protowhat/checks/check_funcs.py | has_code | def has_code(
state,
text,
incorrect_msg="Check the {ast_path}. The checker expected to find {text}.",
fixed=False,
):
"""Test whether the student code contains text.
Args:
state: State instance describing student and solution code. Can be omitted if used with Ex().
text : text that student code must contain. Can be a regex pattern or a simple string.
incorrect_msg: feedback message if text is not in student code.
fixed: whether to match text exactly, rather than using regular expressions.
Note:
Functions like ``check_node`` focus on certain parts of code.
Using these functions followed by ``has_code`` will only look
in the code being focused on.
:Example:
If the student code is.. ::
SELECT a FROM b WHERE id < 100
Then the first test below would (unfortunately) pass, but the second would fail..::
# contained in student code
Ex().has_code(text="id < 10")
# the $ means that you are matching the end of a line
Ex().has_code(text="id < 10$")
By setting ``fixed = True``, you can search for fixed strings::
# without fixed = True, '*' matches any character
Ex().has_code(text="SELECT * FROM b") # passes
Ex().has_code(text="SELECT \\\\* FROM b") # fails
Ex().has_code(text="SELECT * FROM b", fixed=True) # fails
You can check only the code corresponding to the WHERE clause, using ::
where = Ex().check_node('SelectStmt', 0).check_edge('where_clause')
where.has_code(text = "id < 10)
"""
stu_ast = state.student_ast
stu_code = state.student_code
# fallback on using complete student code if no ast
ParseError = state.ast_dispatcher.ParseError
def get_text(ast, code):
if isinstance(ast, ParseError):
return code
try:
return ast.get_text(code)
except:
return code
stu_text = get_text(stu_ast, stu_code)
_msg = incorrect_msg.format(
ast_path=state.get_ast_path() or "highlighted code", text=text
)
# either simple text matching or regex test
res = text in stu_text if fixed else re.search(text, stu_text)
if not res:
state.report(Feedback(_msg))
return state | python | def has_code(
state,
text,
incorrect_msg="Check the {ast_path}. The checker expected to find {text}.",
fixed=False,
):
"""Test whether the student code contains text.
Args:
state: State instance describing student and solution code. Can be omitted if used with Ex().
text : text that student code must contain. Can be a regex pattern or a simple string.
incorrect_msg: feedback message if text is not in student code.
fixed: whether to match text exactly, rather than using regular expressions.
Note:
Functions like ``check_node`` focus on certain parts of code.
Using these functions followed by ``has_code`` will only look
in the code being focused on.
:Example:
If the student code is.. ::
SELECT a FROM b WHERE id < 100
Then the first test below would (unfortunately) pass, but the second would fail..::
# contained in student code
Ex().has_code(text="id < 10")
# the $ means that you are matching the end of a line
Ex().has_code(text="id < 10$")
By setting ``fixed = True``, you can search for fixed strings::
# without fixed = True, '*' matches any character
Ex().has_code(text="SELECT * FROM b") # passes
Ex().has_code(text="SELECT \\\\* FROM b") # fails
Ex().has_code(text="SELECT * FROM b", fixed=True) # fails
You can check only the code corresponding to the WHERE clause, using ::
where = Ex().check_node('SelectStmt', 0).check_edge('where_clause')
where.has_code(text = "id < 10)
"""
stu_ast = state.student_ast
stu_code = state.student_code
# fallback on using complete student code if no ast
ParseError = state.ast_dispatcher.ParseError
def get_text(ast, code):
if isinstance(ast, ParseError):
return code
try:
return ast.get_text(code)
except:
return code
stu_text = get_text(stu_ast, stu_code)
_msg = incorrect_msg.format(
ast_path=state.get_ast_path() or "highlighted code", text=text
)
# either simple text matching or regex test
res = text in stu_text if fixed else re.search(text, stu_text)
if not res:
state.report(Feedback(_msg))
return state | [
"def",
"has_code",
"(",
"state",
",",
"text",
",",
"incorrect_msg",
"=",
"\"Check the {ast_path}. The checker expected to find {text}.\"",
",",
"fixed",
"=",
"False",
",",
")",
":",
"stu_ast",
"=",
"state",
".",
"student_ast",
"stu_code",
"=",
"state",
".",
"stude... | Test whether the student code contains text.
Args:
state: State instance describing student and solution code. Can be omitted if used with Ex().
text : text that student code must contain. Can be a regex pattern or a simple string.
incorrect_msg: feedback message if text is not in student code.
fixed: whether to match text exactly, rather than using regular expressions.
Note:
Functions like ``check_node`` focus on certain parts of code.
Using these functions followed by ``has_code`` will only look
in the code being focused on.
:Example:
If the student code is.. ::
SELECT a FROM b WHERE id < 100
Then the first test below would (unfortunately) pass, but the second would fail..::
# contained in student code
Ex().has_code(text="id < 10")
# the $ means that you are matching the end of a line
Ex().has_code(text="id < 10$")
By setting ``fixed = True``, you can search for fixed strings::
# without fixed = True, '*' matches any character
Ex().has_code(text="SELECT * FROM b") # passes
Ex().has_code(text="SELECT \\\\* FROM b") # fails
Ex().has_code(text="SELECT * FROM b", fixed=True) # fails
You can check only the code corresponding to the WHERE clause, using ::
where = Ex().check_node('SelectStmt', 0).check_edge('where_clause')
where.has_code(text = "id < 10) | [
"Test",
"whether",
"the",
"student",
"code",
"contains",
"text",
"."
] | a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc | https://github.com/datacamp/protowhat/blob/a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc/protowhat/checks/check_funcs.py#L172-L243 | train | 42,633 |
datacamp/protowhat | protowhat/checks/check_funcs.py | has_equal_ast | def has_equal_ast(
state,
incorrect_msg="Check the {ast_path}. {extra}",
sql=None,
start=["expression", "subquery", "sql_script"][0],
exact=None,
):
"""Test whether the student and solution code have identical AST representations
Args:
state: State instance describing student and solution code. Can be omitted if used with Ex().
incorrect_msg: feedback message if student and solution ASTs don't match
sql : optional code to use instead of the solution ast that is zoomed in on.
start: if ``sql`` arg is used, the parser rule to parse the sql code.
One of 'expression' (the default), 'subquery', or 'sql_script'.
exact: whether to require an exact match (True), or only that the
student AST contains the solution AST. If not specified, this
defaults to ``True`` if ``sql`` is not specified, and to ``False``
if ``sql`` is specified. You can always specify it manually.
:Example:
Example 1 - Suppose the solution code is ::
SELECT * FROM cities
and you want to verify whether the `FROM` part is correct: ::
Ex().check_node('SelectStmt').from_clause().has_equal_ast()
Example 2 - Suppose the solution code is ::
SELECT * FROM b WHERE id > 1 AND name = 'filip'
Then the following SCT makes sure ``id > 1`` was used somewhere in the WHERE clause.::
Ex().check_node('SelectStmt') \\/
.check_edge('where_clause') \\/
.has_equal_ast(sql = 'id > 1')
"""
ast = state.ast_dispatcher.ast_mod
sol_ast = state.solution_ast if sql is None else ast.parse(sql, start)
# if sql is set, exact defaults to False.
# if sql not set, exact defaults to True.
if exact is None:
exact = sql is None
stu_rep = repr(state.student_ast)
sol_rep = repr(sol_ast)
def get_str(ast, code, sql):
if sql:
return sql
if isinstance(ast, str):
return ast
try:
return ast.get_text(code)
except:
return None
sol_str = get_str(state.solution_ast, state.solution_code, sql)
_msg = incorrect_msg.format(
ast_path=state.get_ast_path() or "highlighted code",
extra="The checker expected to find `{}` in there.".format(sol_str)
if sol_str
else "Something is missing.",
)
if (exact and (sol_rep != stu_rep)) or (not exact and (sol_rep not in stu_rep)):
state.report(Feedback(_msg))
return state | python | def has_equal_ast(
state,
incorrect_msg="Check the {ast_path}. {extra}",
sql=None,
start=["expression", "subquery", "sql_script"][0],
exact=None,
):
"""Test whether the student and solution code have identical AST representations
Args:
state: State instance describing student and solution code. Can be omitted if used with Ex().
incorrect_msg: feedback message if student and solution ASTs don't match
sql : optional code to use instead of the solution ast that is zoomed in on.
start: if ``sql`` arg is used, the parser rule to parse the sql code.
One of 'expression' (the default), 'subquery', or 'sql_script'.
exact: whether to require an exact match (True), or only that the
student AST contains the solution AST. If not specified, this
defaults to ``True`` if ``sql`` is not specified, and to ``False``
if ``sql`` is specified. You can always specify it manually.
:Example:
Example 1 - Suppose the solution code is ::
SELECT * FROM cities
and you want to verify whether the `FROM` part is correct: ::
Ex().check_node('SelectStmt').from_clause().has_equal_ast()
Example 2 - Suppose the solution code is ::
SELECT * FROM b WHERE id > 1 AND name = 'filip'
Then the following SCT makes sure ``id > 1`` was used somewhere in the WHERE clause.::
Ex().check_node('SelectStmt') \\/
.check_edge('where_clause') \\/
.has_equal_ast(sql = 'id > 1')
"""
ast = state.ast_dispatcher.ast_mod
sol_ast = state.solution_ast if sql is None else ast.parse(sql, start)
# if sql is set, exact defaults to False.
# if sql not set, exact defaults to True.
if exact is None:
exact = sql is None
stu_rep = repr(state.student_ast)
sol_rep = repr(sol_ast)
def get_str(ast, code, sql):
if sql:
return sql
if isinstance(ast, str):
return ast
try:
return ast.get_text(code)
except:
return None
sol_str = get_str(state.solution_ast, state.solution_code, sql)
_msg = incorrect_msg.format(
ast_path=state.get_ast_path() or "highlighted code",
extra="The checker expected to find `{}` in there.".format(sol_str)
if sol_str
else "Something is missing.",
)
if (exact and (sol_rep != stu_rep)) or (not exact and (sol_rep not in stu_rep)):
state.report(Feedback(_msg))
return state | [
"def",
"has_equal_ast",
"(",
"state",
",",
"incorrect_msg",
"=",
"\"Check the {ast_path}. {extra}\"",
",",
"sql",
"=",
"None",
",",
"start",
"=",
"[",
"\"expression\"",
",",
"\"subquery\"",
",",
"\"sql_script\"",
"]",
"[",
"0",
"]",
",",
"exact",
"=",
"None",
... | Test whether the student and solution code have identical AST representations
Args:
state: State instance describing student and solution code. Can be omitted if used with Ex().
incorrect_msg: feedback message if student and solution ASTs don't match
sql : optional code to use instead of the solution ast that is zoomed in on.
start: if ``sql`` arg is used, the parser rule to parse the sql code.
One of 'expression' (the default), 'subquery', or 'sql_script'.
exact: whether to require an exact match (True), or only that the
student AST contains the solution AST. If not specified, this
defaults to ``True`` if ``sql`` is not specified, and to ``False``
if ``sql`` is specified. You can always specify it manually.
:Example:
Example 1 - Suppose the solution code is ::
SELECT * FROM cities
and you want to verify whether the `FROM` part is correct: ::
Ex().check_node('SelectStmt').from_clause().has_equal_ast()
Example 2 - Suppose the solution code is ::
SELECT * FROM b WHERE id > 1 AND name = 'filip'
Then the following SCT makes sure ``id > 1`` was used somewhere in the WHERE clause.::
Ex().check_node('SelectStmt') \\/
.check_edge('where_clause') \\/
.has_equal_ast(sql = 'id > 1') | [
"Test",
"whether",
"the",
"student",
"and",
"solution",
"code",
"have",
"identical",
"AST",
"representations"
] | a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc | https://github.com/datacamp/protowhat/blob/a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc/protowhat/checks/check_funcs.py#L247-L319 | train | 42,634 |
AtteqCom/zsl | src/zsl/utils/cache_helper.py | cache_model | def cache_model(key_params, timeout='default'):
"""
Caching decorator for app models in task.perform
"""
def decorator_fn(fn):
return CacheModelDecorator().decorate(key_params, timeout, fn)
return decorator_fn | python | def cache_model(key_params, timeout='default'):
"""
Caching decorator for app models in task.perform
"""
def decorator_fn(fn):
return CacheModelDecorator().decorate(key_params, timeout, fn)
return decorator_fn | [
"def",
"cache_model",
"(",
"key_params",
",",
"timeout",
"=",
"'default'",
")",
":",
"def",
"decorator_fn",
"(",
"fn",
")",
":",
"return",
"CacheModelDecorator",
"(",
")",
".",
"decorate",
"(",
"key_params",
",",
"timeout",
",",
"fn",
")",
"return",
"decor... | Caching decorator for app models in task.perform | [
"Caching",
"decorator",
"for",
"app",
"models",
"in",
"task",
".",
"perform"
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/cache_helper.py#L126-L133 | train | 42,635 |
opencivicdata/pupa | pupa/importers/base.py | omnihash | def omnihash(obj):
""" recursively hash unhashable objects """
if isinstance(obj, set):
return hash(frozenset(omnihash(e) for e in obj))
elif isinstance(obj, (tuple, list)):
return hash(tuple(omnihash(e) for e in obj))
elif isinstance(obj, dict):
return hash(frozenset((k, omnihash(v)) for k, v in obj.items()))
else:
return hash(obj) | python | def omnihash(obj):
""" recursively hash unhashable objects """
if isinstance(obj, set):
return hash(frozenset(omnihash(e) for e in obj))
elif isinstance(obj, (tuple, list)):
return hash(tuple(omnihash(e) for e in obj))
elif isinstance(obj, dict):
return hash(frozenset((k, omnihash(v)) for k, v in obj.items()))
else:
return hash(obj) | [
"def",
"omnihash",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"set",
")",
":",
"return",
"hash",
"(",
"frozenset",
"(",
"omnihash",
"(",
"e",
")",
"for",
"e",
"in",
"obj",
")",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"(",
"tup... | recursively hash unhashable objects | [
"recursively",
"hash",
"unhashable",
"objects"
] | 18e0ddc4344804987ee0f2227bf600375538dbd5 | https://github.com/opencivicdata/pupa/blob/18e0ddc4344804987ee0f2227bf600375538dbd5/pupa/importers/base.py#L18-L27 | train | 42,636 |
opencivicdata/pupa | pupa/importers/base.py | items_differ | def items_differ(jsonitems, dbitems, subfield_dict):
""" check whether or not jsonitems and dbitems differ """
# short circuit common cases
if len(jsonitems) == len(dbitems) == 0:
# both are empty
return False
elif len(jsonitems) != len(dbitems):
# if lengths differ, they're definitely different
return True
original_jsonitems = jsonitems
jsonitems = copy.deepcopy(jsonitems)
keys = jsonitems[0].keys()
# go over dbitems looking for matches
for dbitem in dbitems:
order = getattr(dbitem, 'order', None)
match = None
for i, jsonitem in enumerate(jsonitems):
# check if all keys (excluding subfields) match
for k in keys:
if k not in subfield_dict and getattr(dbitem, k) != jsonitem.get(k, None):
break
else:
# all fields match so far, possibly equal, just check subfields now
for k in subfield_dict:
jsonsubitems = jsonitem[k]
dbsubitems = list(getattr(dbitem, k).all())
if items_differ(jsonsubitems, dbsubitems, subfield_dict[k][2]):
break
else:
# if the dbitem sets 'order', then the order matters
if order is not None and int(order) != original_jsonitems.index(jsonitem):
break
# these items are equal, so let's mark it for removal
match = i
break
if match is not None:
# item exists in both, remove from jsonitems
jsonitems.pop(match)
else:
# exists in db but not json
return True
# if we get here, jsonitems has to be empty because we asserted that the length was
# the same and we found a match for each thing in dbitems, here's a safety check just in case
if jsonitems: # pragma: no cover
return True
return False | python | def items_differ(jsonitems, dbitems, subfield_dict):
""" check whether or not jsonitems and dbitems differ """
# short circuit common cases
if len(jsonitems) == len(dbitems) == 0:
# both are empty
return False
elif len(jsonitems) != len(dbitems):
# if lengths differ, they're definitely different
return True
original_jsonitems = jsonitems
jsonitems = copy.deepcopy(jsonitems)
keys = jsonitems[0].keys()
# go over dbitems looking for matches
for dbitem in dbitems:
order = getattr(dbitem, 'order', None)
match = None
for i, jsonitem in enumerate(jsonitems):
# check if all keys (excluding subfields) match
for k in keys:
if k not in subfield_dict and getattr(dbitem, k) != jsonitem.get(k, None):
break
else:
# all fields match so far, possibly equal, just check subfields now
for k in subfield_dict:
jsonsubitems = jsonitem[k]
dbsubitems = list(getattr(dbitem, k).all())
if items_differ(jsonsubitems, dbsubitems, subfield_dict[k][2]):
break
else:
# if the dbitem sets 'order', then the order matters
if order is not None and int(order) != original_jsonitems.index(jsonitem):
break
# these items are equal, so let's mark it for removal
match = i
break
if match is not None:
# item exists in both, remove from jsonitems
jsonitems.pop(match)
else:
# exists in db but not json
return True
# if we get here, jsonitems has to be empty because we asserted that the length was
# the same and we found a match for each thing in dbitems, here's a safety check just in case
if jsonitems: # pragma: no cover
return True
return False | [
"def",
"items_differ",
"(",
"jsonitems",
",",
"dbitems",
",",
"subfield_dict",
")",
":",
"# short circuit common cases",
"if",
"len",
"(",
"jsonitems",
")",
"==",
"len",
"(",
"dbitems",
")",
"==",
"0",
":",
"# both are empty",
"return",
"False",
"elif",
"len",... | check whether or not jsonitems and dbitems differ | [
"check",
"whether",
"or",
"not",
"jsonitems",
"and",
"dbitems",
"differ"
] | 18e0ddc4344804987ee0f2227bf600375538dbd5 | https://github.com/opencivicdata/pupa/blob/18e0ddc4344804987ee0f2227bf600375538dbd5/pupa/importers/base.py#L30-L81 | train | 42,637 |
opencivicdata/pupa | pupa/importers/base.py | BaseImporter.resolve_json_id | def resolve_json_id(self, json_id, allow_no_match=False):
"""
Given an id found in scraped JSON, return a DB id for the object.
params:
json_id: id from json
allow_no_match: just return None if id can't be resolved
returns:
database id
raises:
ValueError if id couldn't be resolved
"""
if not json_id:
return None
if json_id.startswith('~'):
# keep caches of all the pseudo-ids to avoid doing 1000s of lookups during import
if json_id not in self.pseudo_id_cache:
spec = get_pseudo_id(json_id)
spec = self.limit_spec(spec)
if isinstance(spec, Q):
objects = self.model_class.objects.filter(spec)
else:
objects = self.model_class.objects.filter(**spec)
ids = {each.id for each in objects}
if len(ids) == 1:
self.pseudo_id_cache[json_id] = ids.pop()
errmsg = None
elif not ids:
errmsg = 'cannot resolve pseudo id to {}: {}'.format(
self.model_class.__name__, json_id)
else:
errmsg = 'multiple objects returned for {} pseudo id {}: {}'.format(
self.model_class.__name__, json_id, ids)
# either raise or log error
if errmsg:
if not allow_no_match:
raise UnresolvedIdError(errmsg)
else:
self.error(errmsg)
self.pseudo_id_cache[json_id] = None
# return the cached object
return self.pseudo_id_cache[json_id]
# get the id that the duplicate points to, or use self
json_id = self.duplicates.get(json_id, json_id)
try:
return self.json_to_db_id[json_id]
except KeyError:
raise UnresolvedIdError('cannot resolve id: {}'.format(json_id)) | python | def resolve_json_id(self, json_id, allow_no_match=False):
"""
Given an id found in scraped JSON, return a DB id for the object.
params:
json_id: id from json
allow_no_match: just return None if id can't be resolved
returns:
database id
raises:
ValueError if id couldn't be resolved
"""
if not json_id:
return None
if json_id.startswith('~'):
# keep caches of all the pseudo-ids to avoid doing 1000s of lookups during import
if json_id not in self.pseudo_id_cache:
spec = get_pseudo_id(json_id)
spec = self.limit_spec(spec)
if isinstance(spec, Q):
objects = self.model_class.objects.filter(spec)
else:
objects = self.model_class.objects.filter(**spec)
ids = {each.id for each in objects}
if len(ids) == 1:
self.pseudo_id_cache[json_id] = ids.pop()
errmsg = None
elif not ids:
errmsg = 'cannot resolve pseudo id to {}: {}'.format(
self.model_class.__name__, json_id)
else:
errmsg = 'multiple objects returned for {} pseudo id {}: {}'.format(
self.model_class.__name__, json_id, ids)
# either raise or log error
if errmsg:
if not allow_no_match:
raise UnresolvedIdError(errmsg)
else:
self.error(errmsg)
self.pseudo_id_cache[json_id] = None
# return the cached object
return self.pseudo_id_cache[json_id]
# get the id that the duplicate points to, or use self
json_id = self.duplicates.get(json_id, json_id)
try:
return self.json_to_db_id[json_id]
except KeyError:
raise UnresolvedIdError('cannot resolve id: {}'.format(json_id)) | [
"def",
"resolve_json_id",
"(",
"self",
",",
"json_id",
",",
"allow_no_match",
"=",
"False",
")",
":",
"if",
"not",
"json_id",
":",
"return",
"None",
"if",
"json_id",
".",
"startswith",
"(",
"'~'",
")",
":",
"# keep caches of all the pseudo-ids to avoid doing 1000s... | Given an id found in scraped JSON, return a DB id for the object.
params:
json_id: id from json
allow_no_match: just return None if id can't be resolved
returns:
database id
raises:
ValueError if id couldn't be resolved | [
"Given",
"an",
"id",
"found",
"in",
"scraped",
"JSON",
"return",
"a",
"DB",
"id",
"for",
"the",
"object",
"."
] | 18e0ddc4344804987ee0f2227bf600375538dbd5 | https://github.com/opencivicdata/pupa/blob/18e0ddc4344804987ee0f2227bf600375538dbd5/pupa/importers/base.py#L130-L185 | train | 42,638 |
opencivicdata/pupa | pupa/importers/base.py | BaseImporter.import_directory | def import_directory(self, datadir):
""" import a JSON directory into the database """
def json_stream():
# load all json, mapped by json_id
for fname in glob.glob(os.path.join(datadir, self._type + '_*.json')):
with open(fname) as f:
yield json.load(f)
return self.import_data(json_stream()) | python | def import_directory(self, datadir):
""" import a JSON directory into the database """
def json_stream():
# load all json, mapped by json_id
for fname in glob.glob(os.path.join(datadir, self._type + '_*.json')):
with open(fname) as f:
yield json.load(f)
return self.import_data(json_stream()) | [
"def",
"import_directory",
"(",
"self",
",",
"datadir",
")",
":",
"def",
"json_stream",
"(",
")",
":",
"# load all json, mapped by json_id",
"for",
"fname",
"in",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"datadir",
",",
"self",
".",
... | import a JSON directory into the database | [
"import",
"a",
"JSON",
"directory",
"into",
"the",
"database"
] | 18e0ddc4344804987ee0f2227bf600375538dbd5 | https://github.com/opencivicdata/pupa/blob/18e0ddc4344804987ee0f2227bf600375538dbd5/pupa/importers/base.py#L187-L196 | train | 42,639 |
opencivicdata/pupa | pupa/importers/base.py | BaseImporter._prepare_imports | def _prepare_imports(self, dicts):
""" filters the import stream to remove duplicates
also serves as a good place to override if anything special has to be done to the
order of the import stream (see OrganizationImporter)
"""
# hash(json): id
seen_hashes = {}
for data in dicts:
json_id = data.pop('_id')
# map duplicates (using omnihash to tell if json dicts are identical-ish)
objhash = omnihash(data)
if objhash not in seen_hashes:
seen_hashes[objhash] = json_id
yield json_id, data
else:
self.duplicates[json_id] = seen_hashes[objhash] | python | def _prepare_imports(self, dicts):
""" filters the import stream to remove duplicates
also serves as a good place to override if anything special has to be done to the
order of the import stream (see OrganizationImporter)
"""
# hash(json): id
seen_hashes = {}
for data in dicts:
json_id = data.pop('_id')
# map duplicates (using omnihash to tell if json dicts are identical-ish)
objhash = omnihash(data)
if objhash not in seen_hashes:
seen_hashes[objhash] = json_id
yield json_id, data
else:
self.duplicates[json_id] = seen_hashes[objhash] | [
"def",
"_prepare_imports",
"(",
"self",
",",
"dicts",
")",
":",
"# hash(json): id",
"seen_hashes",
"=",
"{",
"}",
"for",
"data",
"in",
"dicts",
":",
"json_id",
"=",
"data",
".",
"pop",
"(",
"'_id'",
")",
"# map duplicates (using omnihash to tell if json dicts are ... | filters the import stream to remove duplicates
also serves as a good place to override if anything special has to be done to the
order of the import stream (see OrganizationImporter) | [
"filters",
"the",
"import",
"stream",
"to",
"remove",
"duplicates"
] | 18e0ddc4344804987ee0f2227bf600375538dbd5 | https://github.com/opencivicdata/pupa/blob/18e0ddc4344804987ee0f2227bf600375538dbd5/pupa/importers/base.py#L198-L217 | train | 42,640 |
opencivicdata/pupa | pupa/importers/base.py | BaseImporter.import_data | def import_data(self, data_items):
""" import a bunch of dicts together """
# keep counts of all actions
record = {
'insert': 0, 'update': 0, 'noop': 0,
'start': utcnow(),
'records': {
'insert': [],
'update': [],
'noop': [],
}
}
for json_id, data in self._prepare_imports(data_items):
obj_id, what = self.import_item(data)
self.json_to_db_id[json_id] = obj_id
record['records'][what].append(obj_id)
record[what] += 1
# all objects are loaded, a perfect time to do inter-object resolution and other tasks
self.postimport()
record['end'] = utcnow()
return {self._type: record} | python | def import_data(self, data_items):
""" import a bunch of dicts together """
# keep counts of all actions
record = {
'insert': 0, 'update': 0, 'noop': 0,
'start': utcnow(),
'records': {
'insert': [],
'update': [],
'noop': [],
}
}
for json_id, data in self._prepare_imports(data_items):
obj_id, what = self.import_item(data)
self.json_to_db_id[json_id] = obj_id
record['records'][what].append(obj_id)
record[what] += 1
# all objects are loaded, a perfect time to do inter-object resolution and other tasks
self.postimport()
record['end'] = utcnow()
return {self._type: record} | [
"def",
"import_data",
"(",
"self",
",",
"data_items",
")",
":",
"# keep counts of all actions",
"record",
"=",
"{",
"'insert'",
":",
"0",
",",
"'update'",
":",
"0",
",",
"'noop'",
":",
"0",
",",
"'start'",
":",
"utcnow",
"(",
")",
",",
"'records'",
":",
... | import a bunch of dicts together | [
"import",
"a",
"bunch",
"of",
"dicts",
"together"
] | 18e0ddc4344804987ee0f2227bf600375538dbd5 | https://github.com/opencivicdata/pupa/blob/18e0ddc4344804987ee0f2227bf600375538dbd5/pupa/importers/base.py#L219-L243 | train | 42,641 |
opencivicdata/pupa | pupa/importers/base.py | BaseImporter.import_item | def import_item(self, data):
""" function used by import_data """
what = 'noop'
# remove the JSON _id (may still be there if called directly)
data.pop('_id', None)
# add fields/etc.
data = self.apply_transformers(data)
data = self.prepare_for_db(data)
try:
obj = self.get_object(data)
except self.model_class.DoesNotExist:
obj = None
# remove pupa_id which does not belong in the OCD data models
pupa_id = data.pop('pupa_id', None)
# pull related fields off
related = {}
for field in self.related_models:
related[field] = data.pop(field)
# obj existed, check if we need to do an update
if obj:
if obj.id in self.json_to_db_id.values():
raise DuplicateItemError(data, obj, related.get('sources', []))
# check base object for changes
for key, value in data.items():
if getattr(obj, key) != value and key not in obj.locked_fields:
setattr(obj, key, value)
what = 'update'
updated = self._update_related(obj, related, self.related_models)
if updated:
what = 'update'
if what == 'update':
obj.save()
# need to create the data
else:
what = 'insert'
try:
obj = self.model_class.objects.create(**data)
except Exception as e:
raise DataImportError('{} while importing {} as {}'.format(e, data,
self.model_class))
self._create_related(obj, related, self.related_models)
if pupa_id:
Identifier.objects.get_or_create(identifier=pupa_id,
jurisdiction_id=self.jurisdiction_id,
defaults={'content_object': obj})
return obj.id, what | python | def import_item(self, data):
""" function used by import_data """
what = 'noop'
# remove the JSON _id (may still be there if called directly)
data.pop('_id', None)
# add fields/etc.
data = self.apply_transformers(data)
data = self.prepare_for_db(data)
try:
obj = self.get_object(data)
except self.model_class.DoesNotExist:
obj = None
# remove pupa_id which does not belong in the OCD data models
pupa_id = data.pop('pupa_id', None)
# pull related fields off
related = {}
for field in self.related_models:
related[field] = data.pop(field)
# obj existed, check if we need to do an update
if obj:
if obj.id in self.json_to_db_id.values():
raise DuplicateItemError(data, obj, related.get('sources', []))
# check base object for changes
for key, value in data.items():
if getattr(obj, key) != value and key not in obj.locked_fields:
setattr(obj, key, value)
what = 'update'
updated = self._update_related(obj, related, self.related_models)
if updated:
what = 'update'
if what == 'update':
obj.save()
# need to create the data
else:
what = 'insert'
try:
obj = self.model_class.objects.create(**data)
except Exception as e:
raise DataImportError('{} while importing {} as {}'.format(e, data,
self.model_class))
self._create_related(obj, related, self.related_models)
if pupa_id:
Identifier.objects.get_or_create(identifier=pupa_id,
jurisdiction_id=self.jurisdiction_id,
defaults={'content_object': obj})
return obj.id, what | [
"def",
"import_item",
"(",
"self",
",",
"data",
")",
":",
"what",
"=",
"'noop'",
"# remove the JSON _id (may still be there if called directly)",
"data",
".",
"pop",
"(",
"'_id'",
",",
"None",
")",
"# add fields/etc.",
"data",
"=",
"self",
".",
"apply_transformers",... | function used by import_data | [
"function",
"used",
"by",
"import_data"
] | 18e0ddc4344804987ee0f2227bf600375538dbd5 | https://github.com/opencivicdata/pupa/blob/18e0ddc4344804987ee0f2227bf600375538dbd5/pupa/importers/base.py#L245-L301 | train | 42,642 |
opencivicdata/pupa | pupa/utils/topsort.py | Network.leaf_nodes | def leaf_nodes(self):
"""
Return an interable of nodes with no edges pointing at them. This is
helpful to find all nodes without dependencies.
"""
# Now contains all nodes that contain dependencies.
deps = {item for sublist in self.edges.values() for item in sublist}
# contains all nodes *without* any dependencies (leaf nodes)
return self.nodes - deps | python | def leaf_nodes(self):
"""
Return an interable of nodes with no edges pointing at them. This is
helpful to find all nodes without dependencies.
"""
# Now contains all nodes that contain dependencies.
deps = {item for sublist in self.edges.values() for item in sublist}
# contains all nodes *without* any dependencies (leaf nodes)
return self.nodes - deps | [
"def",
"leaf_nodes",
"(",
"self",
")",
":",
"# Now contains all nodes that contain dependencies.",
"deps",
"=",
"{",
"item",
"for",
"sublist",
"in",
"self",
".",
"edges",
".",
"values",
"(",
")",
"for",
"item",
"in",
"sublist",
"}",
"# contains all nodes *without*... | Return an interable of nodes with no edges pointing at them. This is
helpful to find all nodes without dependencies. | [
"Return",
"an",
"interable",
"of",
"nodes",
"with",
"no",
"edges",
"pointing",
"at",
"them",
".",
"This",
"is",
"helpful",
"to",
"find",
"all",
"nodes",
"without",
"dependencies",
"."
] | 18e0ddc4344804987ee0f2227bf600375538dbd5 | https://github.com/opencivicdata/pupa/blob/18e0ddc4344804987ee0f2227bf600375538dbd5/pupa/utils/topsort.py#L45-L53 | train | 42,643 |
opencivicdata/pupa | pupa/utils/topsort.py | Network.sort | def sort(self):
"""
Return an iterable of nodes, toplogically sorted to correctly import
dependencies before leaf nodes.
"""
while self.nodes:
iterated = False
for node in self.leaf_nodes():
iterated = True
self.prune_node(node)
yield node
if not iterated:
raise CyclicGraphError("Sorting has found a cyclic graph.") | python | def sort(self):
"""
Return an iterable of nodes, toplogically sorted to correctly import
dependencies before leaf nodes.
"""
while self.nodes:
iterated = False
for node in self.leaf_nodes():
iterated = True
self.prune_node(node)
yield node
if not iterated:
raise CyclicGraphError("Sorting has found a cyclic graph.") | [
"def",
"sort",
"(",
"self",
")",
":",
"while",
"self",
".",
"nodes",
":",
"iterated",
"=",
"False",
"for",
"node",
"in",
"self",
".",
"leaf_nodes",
"(",
")",
":",
"iterated",
"=",
"True",
"self",
".",
"prune_node",
"(",
"node",
")",
"yield",
"node",
... | Return an iterable of nodes, toplogically sorted to correctly import
dependencies before leaf nodes. | [
"Return",
"an",
"iterable",
"of",
"nodes",
"toplogically",
"sorted",
"to",
"correctly",
"import",
"dependencies",
"before",
"leaf",
"nodes",
"."
] | 18e0ddc4344804987ee0f2227bf600375538dbd5 | https://github.com/opencivicdata/pupa/blob/18e0ddc4344804987ee0f2227bf600375538dbd5/pupa/utils/topsort.py#L80-L92 | train | 42,644 |
opencivicdata/pupa | pupa/utils/topsort.py | Network.cycles | def cycles(self):
"""
Fairly expensive cycle detection algorithm. This method
will return the shortest unique cycles that were detected.
Debug usage may look something like:
print("The following cycles were found:")
for cycle in network.cycles():
print(" ", " -> ".join(cycle))
"""
def walk_node(node, seen):
"""
Walk each top-level node we know about, and recurse
along the graph.
"""
if node in seen:
yield (node,)
return
seen.add(node)
for edge in self.edges[node]:
for cycle in walk_node(edge, set(seen)):
yield (node,) + cycle
# First, let's get a iterable of all known cycles.
cycles = chain.from_iterable(
(walk_node(node, set()) for node in self.nodes))
shortest = set()
# Now, let's go through and sift through the cycles, finding
# the shortest unique cycle known, ignoring cycles which contain
# already known cycles.
for cycle in sorted(cycles, key=len):
for el in shortest:
if set(el).issubset(set(cycle)):
break
else:
shortest.add(cycle)
# And return that unique list.
return shortest | python | def cycles(self):
"""
Fairly expensive cycle detection algorithm. This method
will return the shortest unique cycles that were detected.
Debug usage may look something like:
print("The following cycles were found:")
for cycle in network.cycles():
print(" ", " -> ".join(cycle))
"""
def walk_node(node, seen):
"""
Walk each top-level node we know about, and recurse
along the graph.
"""
if node in seen:
yield (node,)
return
seen.add(node)
for edge in self.edges[node]:
for cycle in walk_node(edge, set(seen)):
yield (node,) + cycle
# First, let's get a iterable of all known cycles.
cycles = chain.from_iterable(
(walk_node(node, set()) for node in self.nodes))
shortest = set()
# Now, let's go through and sift through the cycles, finding
# the shortest unique cycle known, ignoring cycles which contain
# already known cycles.
for cycle in sorted(cycles, key=len):
for el in shortest:
if set(el).issubset(set(cycle)):
break
else:
shortest.add(cycle)
# And return that unique list.
return shortest | [
"def",
"cycles",
"(",
"self",
")",
":",
"def",
"walk_node",
"(",
"node",
",",
"seen",
")",
":",
"\"\"\"\n Walk each top-level node we know about, and recurse\n along the graph.\n \"\"\"",
"if",
"node",
"in",
"seen",
":",
"yield",
"(",
"nod... | Fairly expensive cycle detection algorithm. This method
will return the shortest unique cycles that were detected.
Debug usage may look something like:
print("The following cycles were found:")
for cycle in network.cycles():
print(" ", " -> ".join(cycle)) | [
"Fairly",
"expensive",
"cycle",
"detection",
"algorithm",
".",
"This",
"method",
"will",
"return",
"the",
"shortest",
"unique",
"cycles",
"that",
"were",
"detected",
"."
] | 18e0ddc4344804987ee0f2227bf600375538dbd5 | https://github.com/opencivicdata/pupa/blob/18e0ddc4344804987ee0f2227bf600375538dbd5/pupa/utils/topsort.py#L105-L145 | train | 42,645 |
opencivicdata/pupa | pupa/scrape/popolo.py | pseudo_organization | def pseudo_organization(organization, classification, default=None):
""" helper for setting an appropriate ID for organizations """
if organization and classification:
raise ScrapeValueError('cannot specify both classification and organization')
elif classification:
return _make_pseudo_id(classification=classification)
elif organization:
if isinstance(organization, Organization):
return organization._id
elif isinstance(organization, str):
return organization
else:
return _make_pseudo_id(**organization)
elif default is not None:
return _make_pseudo_id(classification=default)
else:
return None | python | def pseudo_organization(organization, classification, default=None):
""" helper for setting an appropriate ID for organizations """
if organization and classification:
raise ScrapeValueError('cannot specify both classification and organization')
elif classification:
return _make_pseudo_id(classification=classification)
elif organization:
if isinstance(organization, Organization):
return organization._id
elif isinstance(organization, str):
return organization
else:
return _make_pseudo_id(**organization)
elif default is not None:
return _make_pseudo_id(classification=default)
else:
return None | [
"def",
"pseudo_organization",
"(",
"organization",
",",
"classification",
",",
"default",
"=",
"None",
")",
":",
"if",
"organization",
"and",
"classification",
":",
"raise",
"ScrapeValueError",
"(",
"'cannot specify both classification and organization'",
")",
"elif",
"... | helper for setting an appropriate ID for organizations | [
"helper",
"for",
"setting",
"an",
"appropriate",
"ID",
"for",
"organizations"
] | 18e0ddc4344804987ee0f2227bf600375538dbd5 | https://github.com/opencivicdata/pupa/blob/18e0ddc4344804987ee0f2227bf600375538dbd5/pupa/scrape/popolo.py#L214-L230 | train | 42,646 |
opencivicdata/pupa | pupa/scrape/popolo.py | Person.add_membership | def add_membership(self, name_or_org, role='member', **kwargs):
"""
add a membership in an organization and return the membership
object in case there are more details to add
"""
if isinstance(name_or_org, Organization):
membership = Membership(person_id=self._id,
person_name=self.name,
organization_id=name_or_org._id,
role=role, **kwargs)
else:
membership = Membership(person_id=self._id,
person_name=self.name,
organization_id=_make_pseudo_id(name=name_or_org),
role=role, **kwargs)
self._related.append(membership)
return membership | python | def add_membership(self, name_or_org, role='member', **kwargs):
"""
add a membership in an organization and return the membership
object in case there are more details to add
"""
if isinstance(name_or_org, Organization):
membership = Membership(person_id=self._id,
person_name=self.name,
organization_id=name_or_org._id,
role=role, **kwargs)
else:
membership = Membership(person_id=self._id,
person_name=self.name,
organization_id=_make_pseudo_id(name=name_or_org),
role=role, **kwargs)
self._related.append(membership)
return membership | [
"def",
"add_membership",
"(",
"self",
",",
"name_or_org",
",",
"role",
"=",
"'member'",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"name_or_org",
",",
"Organization",
")",
":",
"membership",
"=",
"Membership",
"(",
"person_id",
"=",
"self"... | add a membership in an organization and return the membership
object in case there are more details to add | [
"add",
"a",
"membership",
"in",
"an",
"organization",
"and",
"return",
"the",
"membership",
"object",
"in",
"case",
"there",
"are",
"more",
"details",
"to",
"add"
] | 18e0ddc4344804987ee0f2227bf600375538dbd5 | https://github.com/opencivicdata/pupa/blob/18e0ddc4344804987ee0f2227bf600375538dbd5/pupa/scrape/popolo.py#L104-L120 | train | 42,647 |
opencivicdata/pupa | pupa/scrape/base.py | Scraper.save_object | def save_object(self, obj):
"""
Save object to disk as JSON.
Generally shouldn't be called directly.
"""
obj.pre_save(self.jurisdiction.jurisdiction_id)
filename = '{0}_{1}.json'.format(obj._type, obj._id).replace('/', '-')
self.info('save %s %s as %s', obj._type, obj, filename)
self.debug(json.dumps(OrderedDict(sorted(obj.as_dict().items())),
cls=utils.JSONEncoderPlus, indent=4, separators=(',', ': ')))
self.output_names[obj._type].add(filename)
with open(os.path.join(self.datadir, filename), 'w') as f:
json.dump(obj.as_dict(), f, cls=utils.JSONEncoderPlus)
# validate after writing, allows for inspection on failure
try:
obj.validate()
except ValueError as ve:
if self.strict_validation:
raise ve
else:
self.warning(ve)
# after saving and validating, save subordinate objects
for obj in obj._related:
self.save_object(obj) | python | def save_object(self, obj):
"""
Save object to disk as JSON.
Generally shouldn't be called directly.
"""
obj.pre_save(self.jurisdiction.jurisdiction_id)
filename = '{0}_{1}.json'.format(obj._type, obj._id).replace('/', '-')
self.info('save %s %s as %s', obj._type, obj, filename)
self.debug(json.dumps(OrderedDict(sorted(obj.as_dict().items())),
cls=utils.JSONEncoderPlus, indent=4, separators=(',', ': ')))
self.output_names[obj._type].add(filename)
with open(os.path.join(self.datadir, filename), 'w') as f:
json.dump(obj.as_dict(), f, cls=utils.JSONEncoderPlus)
# validate after writing, allows for inspection on failure
try:
obj.validate()
except ValueError as ve:
if self.strict_validation:
raise ve
else:
self.warning(ve)
# after saving and validating, save subordinate objects
for obj in obj._related:
self.save_object(obj) | [
"def",
"save_object",
"(",
"self",
",",
"obj",
")",
":",
"obj",
".",
"pre_save",
"(",
"self",
".",
"jurisdiction",
".",
"jurisdiction_id",
")",
"filename",
"=",
"'{0}_{1}.json'",
".",
"format",
"(",
"obj",
".",
"_type",
",",
"obj",
".",
"_id",
")",
"."... | Save object to disk as JSON.
Generally shouldn't be called directly. | [
"Save",
"object",
"to",
"disk",
"as",
"JSON",
"."
] | 18e0ddc4344804987ee0f2227bf600375538dbd5 | https://github.com/opencivicdata/pupa/blob/18e0ddc4344804987ee0f2227bf600375538dbd5/pupa/scrape/base.py#L76-L106 | train | 42,648 |
opencivicdata/pupa | pupa/scrape/base.py | BaseModel.validate | def validate(self, schema=None):
"""
Validate that we have a valid object.
On error, this will raise a `ScrapeValueError`
This also expects that the schemas assume that omitting required
in the schema asserts the field is optional, not required. This is
due to upstream schemas being in JSON Schema v3, and not validictory's
modified syntax.
^ TODO: FIXME
"""
if schema is None:
schema = self._schema
type_checker = Draft3Validator.TYPE_CHECKER.redefine(
"datetime", lambda c, d: isinstance(d, (datetime.date, datetime.datetime))
)
ValidatorCls = jsonschema.validators.extend(Draft3Validator, type_checker=type_checker)
validator = ValidatorCls(schema, format_checker=FormatChecker())
errors = [str(error) for error in validator.iter_errors(self.as_dict())]
if errors:
raise ScrapeValueError('validation of {} {} failed: {}'.format(
self.__class__.__name__, self._id, '\n\t'+'\n\t'.join(errors)
)) | python | def validate(self, schema=None):
"""
Validate that we have a valid object.
On error, this will raise a `ScrapeValueError`
This also expects that the schemas assume that omitting required
in the schema asserts the field is optional, not required. This is
due to upstream schemas being in JSON Schema v3, and not validictory's
modified syntax.
^ TODO: FIXME
"""
if schema is None:
schema = self._schema
type_checker = Draft3Validator.TYPE_CHECKER.redefine(
"datetime", lambda c, d: isinstance(d, (datetime.date, datetime.datetime))
)
ValidatorCls = jsonschema.validators.extend(Draft3Validator, type_checker=type_checker)
validator = ValidatorCls(schema, format_checker=FormatChecker())
errors = [str(error) for error in validator.iter_errors(self.as_dict())]
if errors:
raise ScrapeValueError('validation of {} {} failed: {}'.format(
self.__class__.__name__, self._id, '\n\t'+'\n\t'.join(errors)
)) | [
"def",
"validate",
"(",
"self",
",",
"schema",
"=",
"None",
")",
":",
"if",
"schema",
"is",
"None",
":",
"schema",
"=",
"self",
".",
"_schema",
"type_checker",
"=",
"Draft3Validator",
".",
"TYPE_CHECKER",
".",
"redefine",
"(",
"\"datetime\"",
",",
"lambda"... | Validate that we have a valid object.
On error, this will raise a `ScrapeValueError`
This also expects that the schemas assume that omitting required
in the schema asserts the field is optional, not required. This is
due to upstream schemas being in JSON Schema v3, and not validictory's
modified syntax.
^ TODO: FIXME | [
"Validate",
"that",
"we",
"have",
"a",
"valid",
"object",
"."
] | 18e0ddc4344804987ee0f2227bf600375538dbd5 | https://github.com/opencivicdata/pupa/blob/18e0ddc4344804987ee0f2227bf600375538dbd5/pupa/scrape/base.py#L171-L196 | train | 42,649 |
opencivicdata/pupa | pupa/scrape/base.py | SourceMixin.add_source | def add_source(self, url, *, note=''):
""" Add a source URL from which data was collected """
new = {'url': url, 'note': note}
self.sources.append(new) | python | def add_source(self, url, *, note=''):
""" Add a source URL from which data was collected """
new = {'url': url, 'note': note}
self.sources.append(new) | [
"def",
"add_source",
"(",
"self",
",",
"url",
",",
"*",
",",
"note",
"=",
"''",
")",
":",
"new",
"=",
"{",
"'url'",
":",
"url",
",",
"'note'",
":",
"note",
"}",
"self",
".",
"sources",
".",
"append",
"(",
"new",
")"
] | Add a source URL from which data was collected | [
"Add",
"a",
"source",
"URL",
"from",
"which",
"data",
"was",
"collected"
] | 18e0ddc4344804987ee0f2227bf600375538dbd5 | https://github.com/opencivicdata/pupa/blob/18e0ddc4344804987ee0f2227bf600375538dbd5/pupa/scrape/base.py#L222-L225 | train | 42,650 |
molpopgen/fwdpy11 | fwdpy11/_evolve_genomes.py | evolve_genomes | def evolve_genomes(rng, pop, params, recorder=None):
"""
Evolve a population without tree sequence recordings. In other words,
complete genomes must be simulated and tracked.
:param rng: random number generator
:type rng: :class:`fwdpy11.GSLrng`
:param pop: A population
:type pop: :class:`fwdpy11.DiploidPopulation`
:param params: simulation parameters
:type params: :class:`fwdpy11.ModelParams`
:param recorder: (None) A temporal sampler/data recorder.
:type recorder: callable
.. note::
If recorder is None,
then :class:`fwdpy11.RecordNothing` will be used.
"""
import warnings
# Test parameters while suppressing warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore")
# Will throw exception if anything is wrong:
params.validate()
from ._fwdpy11 import MutationRegions
from ._fwdpy11 import evolve_without_tree_sequences
from ._fwdpy11 import dispatch_create_GeneticMap
pneutral = params.mutrate_n/(params.mutrate_n+params.mutrate_s)
mm = MutationRegions.create(pneutral, params.nregions, params.sregions)
rm = dispatch_create_GeneticMap(params.recrate, params.recregions)
if recorder is None:
from ._fwdpy11 import RecordNothing
recorder = RecordNothing()
evolve_without_tree_sequences(rng, pop, params.demography,
params.mutrate_n, params.mutrate_s,
params.recrate, mm, rm, params.gvalue,
recorder, params.pself, params.prune_selected) | python | def evolve_genomes(rng, pop, params, recorder=None):
"""
Evolve a population without tree sequence recordings. In other words,
complete genomes must be simulated and tracked.
:param rng: random number generator
:type rng: :class:`fwdpy11.GSLrng`
:param pop: A population
:type pop: :class:`fwdpy11.DiploidPopulation`
:param params: simulation parameters
:type params: :class:`fwdpy11.ModelParams`
:param recorder: (None) A temporal sampler/data recorder.
:type recorder: callable
.. note::
If recorder is None,
then :class:`fwdpy11.RecordNothing` will be used.
"""
import warnings
# Test parameters while suppressing warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore")
# Will throw exception if anything is wrong:
params.validate()
from ._fwdpy11 import MutationRegions
from ._fwdpy11 import evolve_without_tree_sequences
from ._fwdpy11 import dispatch_create_GeneticMap
pneutral = params.mutrate_n/(params.mutrate_n+params.mutrate_s)
mm = MutationRegions.create(pneutral, params.nregions, params.sregions)
rm = dispatch_create_GeneticMap(params.recrate, params.recregions)
if recorder is None:
from ._fwdpy11 import RecordNothing
recorder = RecordNothing()
evolve_without_tree_sequences(rng, pop, params.demography,
params.mutrate_n, params.mutrate_s,
params.recrate, mm, rm, params.gvalue,
recorder, params.pself, params.prune_selected) | [
"def",
"evolve_genomes",
"(",
"rng",
",",
"pop",
",",
"params",
",",
"recorder",
"=",
"None",
")",
":",
"import",
"warnings",
"# Test parameters while suppressing warnings",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"warnings",
".",
"simplefilter",... | Evolve a population without tree sequence recordings. In other words,
complete genomes must be simulated and tracked.
:param rng: random number generator
:type rng: :class:`fwdpy11.GSLrng`
:param pop: A population
:type pop: :class:`fwdpy11.DiploidPopulation`
:param params: simulation parameters
:type params: :class:`fwdpy11.ModelParams`
:param recorder: (None) A temporal sampler/data recorder.
:type recorder: callable
.. note::
If recorder is None,
then :class:`fwdpy11.RecordNothing` will be used. | [
"Evolve",
"a",
"population",
"without",
"tree",
"sequence",
"recordings",
".",
"In",
"other",
"words",
"complete",
"genomes",
"must",
"be",
"simulated",
"and",
"tracked",
"."
] | 7a5905f0f0a09e24ae5b0f39d22017499e81ea9e | https://github.com/molpopgen/fwdpy11/blob/7a5905f0f0a09e24ae5b0f39d22017499e81ea9e/fwdpy11/_evolve_genomes.py#L21-L61 | train | 42,651 |
molpopgen/fwdpy11 | fwdpy11/_tables_to_tskit.py | _initializeIndividualTable | def _initializeIndividualTable(pop, tc):
"""
Returns node ID -> individual map
"""
# First, alive individuals:
individal_nodes = {}
for i in range(pop.N):
individal_nodes[2*i] = i
individal_nodes[2*i+1] = i
metadata_strings = _generate_individual_metadata(pop.diploid_metadata, tc)
# Now, preserved nodes
num_ind_nodes = pop.N
for i in pop.ancient_sample_metadata:
assert i not in individal_nodes, "indivudal record error"
individal_nodes[i.nodes[0]] = num_ind_nodes
individal_nodes[i.nodes[1]] = num_ind_nodes
num_ind_nodes += 1
metadata_strings.extend(_generate_individual_metadata(
pop.ancient_sample_metadata, tc))
md, mdo = tskit.pack_bytes(metadata_strings)
flags = [0 for i in range(pop.N+len(pop.ancient_sample_metadata))]
tc.individuals.set_columns(flags=flags, metadata=md, metadata_offset=mdo)
return individal_nodes | python | def _initializeIndividualTable(pop, tc):
"""
Returns node ID -> individual map
"""
# First, alive individuals:
individal_nodes = {}
for i in range(pop.N):
individal_nodes[2*i] = i
individal_nodes[2*i+1] = i
metadata_strings = _generate_individual_metadata(pop.diploid_metadata, tc)
# Now, preserved nodes
num_ind_nodes = pop.N
for i in pop.ancient_sample_metadata:
assert i not in individal_nodes, "indivudal record error"
individal_nodes[i.nodes[0]] = num_ind_nodes
individal_nodes[i.nodes[1]] = num_ind_nodes
num_ind_nodes += 1
metadata_strings.extend(_generate_individual_metadata(
pop.ancient_sample_metadata, tc))
md, mdo = tskit.pack_bytes(metadata_strings)
flags = [0 for i in range(pop.N+len(pop.ancient_sample_metadata))]
tc.individuals.set_columns(flags=flags, metadata=md, metadata_offset=mdo)
return individal_nodes | [
"def",
"_initializeIndividualTable",
"(",
"pop",
",",
"tc",
")",
":",
"# First, alive individuals:",
"individal_nodes",
"=",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"pop",
".",
"N",
")",
":",
"individal_nodes",
"[",
"2",
"*",
"i",
"]",
"=",
"i",
"indiv... | Returns node ID -> individual map | [
"Returns",
"node",
"ID",
"-",
">",
"individual",
"map"
] | 7a5905f0f0a09e24ae5b0f39d22017499e81ea9e | https://github.com/molpopgen/fwdpy11/blob/7a5905f0f0a09e24ae5b0f39d22017499e81ea9e/fwdpy11/_tables_to_tskit.py#L65-L90 | train | 42,652 |
molpopgen/fwdpy11 | fwdpy11/_tables_to_tskit.py | dump_tables_to_tskit | def dump_tables_to_tskit(pop):
"""
Converts fwdpy11.TableCollection to an
tskit.TreeSequence
"""
node_view = np.array(pop.tables.nodes, copy=True)
node_view['time'] -= node_view['time'].max()
node_view['time'][np.where(node_view['time'] != 0.0)[0]] *= -1.0
edge_view = np.array(pop.tables.edges, copy=False)
mut_view = np.array(pop.tables.mutations, copy=False)
tc = tskit.TableCollection(pop.tables.genome_length)
# We must initialize population and individual
# tables before we can do anything else.
# Attempting to set population to anything
# other than -1 in an tskit.NodeTable will
# raise an exception if the PopulationTable
# isn't set up.
_initializePopulationTable(node_view, tc)
node_to_individual = _initializeIndividualTable(pop, tc)
individual = [-1 for i in range(len(node_view))]
for k, v in node_to_individual.items():
individual[k] = v
flags = [1]*2*pop.N + [0]*(len(node_view) - 2*pop.N)
# Bug fixed in 0.3.1: add preserved nodes to samples list
for i in pop.tables.preserved_nodes:
flags[i] = 1
tc.nodes.set_columns(flags=flags, time=node_view['time'],
population=node_view['population'],
individual=individual)
tc.edges.set_columns(left=edge_view['left'],
right=edge_view['right'],
parent=edge_view['parent'],
child=edge_view['child'])
mpos = np.array([pop.mutations[i].pos for i in mut_view['key']])
ancestral_state = np.zeros(len(mut_view), dtype=np.int8)+ord('0')
ancestral_state_offset = np.arange(len(mut_view)+1, dtype=np.uint32)
tc.sites.set_columns(position=mpos,
ancestral_state=ancestral_state,
ancestral_state_offset=ancestral_state_offset)
derived_state = np.zeros(len(mut_view), dtype=np.int8)+ord('1')
md, mdo = _generate_mutation_metadata(pop)
tc.mutations.set_columns(site=np.arange(len(mpos), dtype=np.int32),
node=mut_view['node'],
derived_state=derived_state,
derived_state_offset=ancestral_state_offset,
metadata=md,
metadata_offset=mdo)
return tc.tree_sequence() | python | def dump_tables_to_tskit(pop):
"""
Converts fwdpy11.TableCollection to an
tskit.TreeSequence
"""
node_view = np.array(pop.tables.nodes, copy=True)
node_view['time'] -= node_view['time'].max()
node_view['time'][np.where(node_view['time'] != 0.0)[0]] *= -1.0
edge_view = np.array(pop.tables.edges, copy=False)
mut_view = np.array(pop.tables.mutations, copy=False)
tc = tskit.TableCollection(pop.tables.genome_length)
# We must initialize population and individual
# tables before we can do anything else.
# Attempting to set population to anything
# other than -1 in an tskit.NodeTable will
# raise an exception if the PopulationTable
# isn't set up.
_initializePopulationTable(node_view, tc)
node_to_individual = _initializeIndividualTable(pop, tc)
individual = [-1 for i in range(len(node_view))]
for k, v in node_to_individual.items():
individual[k] = v
flags = [1]*2*pop.N + [0]*(len(node_view) - 2*pop.N)
# Bug fixed in 0.3.1: add preserved nodes to samples list
for i in pop.tables.preserved_nodes:
flags[i] = 1
tc.nodes.set_columns(flags=flags, time=node_view['time'],
population=node_view['population'],
individual=individual)
tc.edges.set_columns(left=edge_view['left'],
right=edge_view['right'],
parent=edge_view['parent'],
child=edge_view['child'])
mpos = np.array([pop.mutations[i].pos for i in mut_view['key']])
ancestral_state = np.zeros(len(mut_view), dtype=np.int8)+ord('0')
ancestral_state_offset = np.arange(len(mut_view)+1, dtype=np.uint32)
tc.sites.set_columns(position=mpos,
ancestral_state=ancestral_state,
ancestral_state_offset=ancestral_state_offset)
derived_state = np.zeros(len(mut_view), dtype=np.int8)+ord('1')
md, mdo = _generate_mutation_metadata(pop)
tc.mutations.set_columns(site=np.arange(len(mpos), dtype=np.int32),
node=mut_view['node'],
derived_state=derived_state,
derived_state_offset=ancestral_state_offset,
metadata=md,
metadata_offset=mdo)
return tc.tree_sequence() | [
"def",
"dump_tables_to_tskit",
"(",
"pop",
")",
":",
"node_view",
"=",
"np",
".",
"array",
"(",
"pop",
".",
"tables",
".",
"nodes",
",",
"copy",
"=",
"True",
")",
"node_view",
"[",
"'time'",
"]",
"-=",
"node_view",
"[",
"'time'",
"]",
".",
"max",
"("... | Converts fwdpy11.TableCollection to an
tskit.TreeSequence | [
"Converts",
"fwdpy11",
".",
"TableCollection",
"to",
"an",
"tskit",
".",
"TreeSequence"
] | 7a5905f0f0a09e24ae5b0f39d22017499e81ea9e | https://github.com/molpopgen/fwdpy11/blob/7a5905f0f0a09e24ae5b0f39d22017499e81ea9e/fwdpy11/_tables_to_tskit.py#L93-L145 | train | 42,653 |
molpopgen/fwdpy11 | fwdpy11/ezparams.py | mslike | def mslike(pop, **kwargs):
"""
Function to establish default parameters
for a single-locus simulation for standard pop-gen
modeling scenarios.
:params pop: An instance of :class:`fwdpy11.DiploidPopulation`
:params kwargs: Keyword arguments.
"""
import fwdpy11
if isinstance(pop, fwdpy11.DiploidPopulation) is False:
raise ValueError("incorrect pop type: " + str(type(pop)))
defaults = {'simlen': 10*pop.N,
'beg': 0.0,
'end': 1.0,
'theta': 100.0,
'pneutral': 1.0,
'rho': 100.0,
'dfe': None
}
for key, value in kwargs.items():
if key in defaults:
defaults[key] = value
import numpy as np
params = {'demography': np.array([pop.N]*defaults['simlen'],
dtype=np.uint32),
'nregions': [fwdpy11.Region(defaults['beg'],
defaults['end'], 1.0)],
'recregions': [fwdpy11.Region(defaults['beg'],
defaults['end'], 1.0)],
'rates': ((defaults['pneutral']*defaults['theta'])/(4.0*pop.N),
((1.0-defaults['pneutral'])*defaults['theta']) /
(4.0*pop.N),
defaults['rho']/(4.0*float(pop.N))),
'gvalue': fwdpy11.Multiplicative(2.0)
}
if defaults['dfe'] is None:
params['sregions'] = []
else:
params['sregions'] = [defaults['dfe']]
return params | python | def mslike(pop, **kwargs):
"""
Function to establish default parameters
for a single-locus simulation for standard pop-gen
modeling scenarios.
:params pop: An instance of :class:`fwdpy11.DiploidPopulation`
:params kwargs: Keyword arguments.
"""
import fwdpy11
if isinstance(pop, fwdpy11.DiploidPopulation) is False:
raise ValueError("incorrect pop type: " + str(type(pop)))
defaults = {'simlen': 10*pop.N,
'beg': 0.0,
'end': 1.0,
'theta': 100.0,
'pneutral': 1.0,
'rho': 100.0,
'dfe': None
}
for key, value in kwargs.items():
if key in defaults:
defaults[key] = value
import numpy as np
params = {'demography': np.array([pop.N]*defaults['simlen'],
dtype=np.uint32),
'nregions': [fwdpy11.Region(defaults['beg'],
defaults['end'], 1.0)],
'recregions': [fwdpy11.Region(defaults['beg'],
defaults['end'], 1.0)],
'rates': ((defaults['pneutral']*defaults['theta'])/(4.0*pop.N),
((1.0-defaults['pneutral'])*defaults['theta']) /
(4.0*pop.N),
defaults['rho']/(4.0*float(pop.N))),
'gvalue': fwdpy11.Multiplicative(2.0)
}
if defaults['dfe'] is None:
params['sregions'] = []
else:
params['sregions'] = [defaults['dfe']]
return params | [
"def",
"mslike",
"(",
"pop",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"fwdpy11",
"if",
"isinstance",
"(",
"pop",
",",
"fwdpy11",
".",
"DiploidPopulation",
")",
"is",
"False",
":",
"raise",
"ValueError",
"(",
"\"incorrect pop type: \"",
"+",
"str",
"(",... | Function to establish default parameters
for a single-locus simulation for standard pop-gen
modeling scenarios.
:params pop: An instance of :class:`fwdpy11.DiploidPopulation`
:params kwargs: Keyword arguments. | [
"Function",
"to",
"establish",
"default",
"parameters",
"for",
"a",
"single",
"-",
"locus",
"simulation",
"for",
"standard",
"pop",
"-",
"gen",
"modeling",
"scenarios",
"."
] | 7a5905f0f0a09e24ae5b0f39d22017499e81ea9e | https://github.com/molpopgen/fwdpy11/blob/7a5905f0f0a09e24ae5b0f39d22017499e81ea9e/fwdpy11/ezparams.py#L21-L62 | train | 42,654 |
opencivicdata/pupa | pupa/importers/people.py | PersonImporter.limit_spec | def limit_spec(self, spec):
"""
Whenever we do a Pseudo ID lookup from the database, we need to limit
based on the memberships -> organization -> jurisdiction, so we scope
the resolution.
"""
if list(spec.keys()) == ['name']:
# if we're just resolving on name, include other names
return ((Q(name=spec['name']) | Q(other_names__name=spec['name'])) &
Q(memberships__organization__jurisdiction_id=self.jurisdiction_id))
spec['memberships__organization__jurisdiction_id'] = self.jurisdiction_id
return spec | python | def limit_spec(self, spec):
"""
Whenever we do a Pseudo ID lookup from the database, we need to limit
based on the memberships -> organization -> jurisdiction, so we scope
the resolution.
"""
if list(spec.keys()) == ['name']:
# if we're just resolving on name, include other names
return ((Q(name=spec['name']) | Q(other_names__name=spec['name'])) &
Q(memberships__organization__jurisdiction_id=self.jurisdiction_id))
spec['memberships__organization__jurisdiction_id'] = self.jurisdiction_id
return spec | [
"def",
"limit_spec",
"(",
"self",
",",
"spec",
")",
":",
"if",
"list",
"(",
"spec",
".",
"keys",
"(",
")",
")",
"==",
"[",
"'name'",
"]",
":",
"# if we're just resolving on name, include other names",
"return",
"(",
"(",
"Q",
"(",
"name",
"=",
"spec",
"[... | Whenever we do a Pseudo ID lookup from the database, we need to limit
based on the memberships -> organization -> jurisdiction, so we scope
the resolution. | [
"Whenever",
"we",
"do",
"a",
"Pseudo",
"ID",
"lookup",
"from",
"the",
"database",
"we",
"need",
"to",
"limit",
"based",
"on",
"the",
"memberships",
"-",
">",
"organization",
"-",
">",
"jurisdiction",
"so",
"we",
"scope",
"the",
"resolution",
"."
] | 18e0ddc4344804987ee0f2227bf600375538dbd5 | https://github.com/opencivicdata/pupa/blob/18e0ddc4344804987ee0f2227bf600375538dbd5/pupa/importers/people.py#L37-L48 | train | 42,655 |
molpopgen/fwdpy11 | fwdpy11/_model_params.py | ModelParams.validate | def validate(self):
"""
Error check model params.
:raises TypeError: Throws TypeError if validation fails.
"""
if self.nregions is None:
raise TypeError("neutral regions cannot be None")
if self.sregions is None:
raise TypeError("selected regions cannot be None")
if self.recregions is None:
raise TypeError("recombination regions cannot be None")
if self.demography is None:
raise TypeError("demography cannot be None")
if self.prune_selected is None:
raise TypeError("prune_selected cannot be None")
if self.gvalue is None:
raise TypeError("gvalue cannot be None")
if self.rates is None:
raise TypeError("rates cannot be None") | python | def validate(self):
"""
Error check model params.
:raises TypeError: Throws TypeError if validation fails.
"""
if self.nregions is None:
raise TypeError("neutral regions cannot be None")
if self.sregions is None:
raise TypeError("selected regions cannot be None")
if self.recregions is None:
raise TypeError("recombination regions cannot be None")
if self.demography is None:
raise TypeError("demography cannot be None")
if self.prune_selected is None:
raise TypeError("prune_selected cannot be None")
if self.gvalue is None:
raise TypeError("gvalue cannot be None")
if self.rates is None:
raise TypeError("rates cannot be None") | [
"def",
"validate",
"(",
"self",
")",
":",
"if",
"self",
".",
"nregions",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"\"neutral regions cannot be None\"",
")",
"if",
"self",
".",
"sregions",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"\"selected regions c... | Error check model params.
:raises TypeError: Throws TypeError if validation fails. | [
"Error",
"check",
"model",
"params",
"."
] | 7a5905f0f0a09e24ae5b0f39d22017499e81ea9e | https://github.com/molpopgen/fwdpy11/blob/7a5905f0f0a09e24ae5b0f39d22017499e81ea9e/fwdpy11/_model_params.py#L171-L191 | train | 42,656 |
opencivicdata/pupa | pupa/importers/organizations.py | OrganizationImporter._prepare_imports | def _prepare_imports(self, dicts):
""" an override for prepare imports that sorts the imports by parent_id dependencies """
# all pseudo parent ids we've seen
pseudo_ids = set()
# pseudo matches
pseudo_matches = {}
# get prepared imports from parent
prepared = dict(super(OrganizationImporter, self)._prepare_imports(dicts))
# collect parent pseudo_ids
for _, data in prepared.items():
parent_id = data.get('parent_id', None) or ''
if parent_id.startswith('~'):
pseudo_ids.add(parent_id)
# turn pseudo_ids into a tuple of dictionaries
pseudo_ids = [(ppid, get_pseudo_id(ppid)) for ppid in pseudo_ids]
# loop over all data again, finding the pseudo ids true json id
for json_id, data in prepared.items():
# check if this matches one of our ppids
for ppid, spec in pseudo_ids:
match = True
for k, v in spec.items():
if data[k] != v:
match = False
break
if match:
if ppid in pseudo_matches:
raise UnresolvedIdError('multiple matches for pseudo id: ' + ppid)
pseudo_matches[ppid] = json_id
# toposort the nodes so parents are imported first
network = Network()
in_network = set()
import_order = []
for json_id, data in prepared.items():
parent_id = data.get('parent_id', None)
# resolve pseudo_ids to their json id before building the network
if parent_id in pseudo_matches:
parent_id = pseudo_matches[parent_id]
network.add_node(json_id)
if parent_id:
# Right. There's an import dep. We need to add the edge from
# the parent to the current node, so that we import the parent
# before the current node.
network.add_edge(parent_id, json_id)
# resolve the sorted import order
for jid in network.sort():
import_order.append((jid, prepared[jid]))
in_network.add(jid)
# ensure all data made it into network (paranoid check, should never fail)
if in_network != set(prepared.keys()): # pragma: no cover
raise PupaInternalError("import is missing nodes in network set")
return import_order | python | def _prepare_imports(self, dicts):
""" an override for prepare imports that sorts the imports by parent_id dependencies """
# all pseudo parent ids we've seen
pseudo_ids = set()
# pseudo matches
pseudo_matches = {}
# get prepared imports from parent
prepared = dict(super(OrganizationImporter, self)._prepare_imports(dicts))
# collect parent pseudo_ids
for _, data in prepared.items():
parent_id = data.get('parent_id', None) or ''
if parent_id.startswith('~'):
pseudo_ids.add(parent_id)
# turn pseudo_ids into a tuple of dictionaries
pseudo_ids = [(ppid, get_pseudo_id(ppid)) for ppid in pseudo_ids]
# loop over all data again, finding the pseudo ids true json id
for json_id, data in prepared.items():
# check if this matches one of our ppids
for ppid, spec in pseudo_ids:
match = True
for k, v in spec.items():
if data[k] != v:
match = False
break
if match:
if ppid in pseudo_matches:
raise UnresolvedIdError('multiple matches for pseudo id: ' + ppid)
pseudo_matches[ppid] = json_id
# toposort the nodes so parents are imported first
network = Network()
in_network = set()
import_order = []
for json_id, data in prepared.items():
parent_id = data.get('parent_id', None)
# resolve pseudo_ids to their json id before building the network
if parent_id in pseudo_matches:
parent_id = pseudo_matches[parent_id]
network.add_node(json_id)
if parent_id:
# Right. There's an import dep. We need to add the edge from
# the parent to the current node, so that we import the parent
# before the current node.
network.add_edge(parent_id, json_id)
# resolve the sorted import order
for jid in network.sort():
import_order.append((jid, prepared[jid]))
in_network.add(jid)
# ensure all data made it into network (paranoid check, should never fail)
if in_network != set(prepared.keys()): # pragma: no cover
raise PupaInternalError("import is missing nodes in network set")
return import_order | [
"def",
"_prepare_imports",
"(",
"self",
",",
"dicts",
")",
":",
"# all pseudo parent ids we've seen",
"pseudo_ids",
"=",
"set",
"(",
")",
"# pseudo matches",
"pseudo_matches",
"=",
"{",
"}",
"# get prepared imports from parent",
"prepared",
"=",
"dict",
"(",
"super",
... | an override for prepare imports that sorts the imports by parent_id dependencies | [
"an",
"override",
"for",
"prepare",
"imports",
"that",
"sorts",
"the",
"imports",
"by",
"parent_id",
"dependencies"
] | 18e0ddc4344804987ee0f2227bf600375538dbd5 | https://github.com/opencivicdata/pupa/blob/18e0ddc4344804987ee0f2227bf600375538dbd5/pupa/importers/organizations.py#L61-L122 | train | 42,657 |
molpopgen/fwdpy11 | fwdpy11/_evolvets.py | evolvets | def evolvets(rng, pop, params, simplification_interval, recorder=None,
suppress_table_indexing=False, record_gvalue_matrix=False,
stopping_criterion=None,
track_mutation_counts=False,
remove_extinct_variants=True):
"""
Evolve a population with tree sequence recording
:param rng: random number generator
:type rng: :class:`fwdpy11.GSLrng`
:param pop: A population
:type pop: :class:`fwdpy11.DiploidPopulation`
:param params: simulation parameters
:type params: :class:`fwdpy11.ModelParams`
:param simplification_interval: Number of generations between simplifications.
:type simplification_interval: int
:param recorder: (None) A temporal sampler/data recorder.
:type recorder: callable
:param suppress_table_indexing: (False) Prevents edge table indexing until end of simulation
:type suppress_table_indexing: boolean
:param record_gvalue_matrix: (False) Whether to record genetic values into :attr:`fwdpy11.Population.genetic_values`.
:type record_gvalue_matrix: boolean
The recording of genetic values into :attr:`fwdpy11.Population.genetic_values` is supprssed by default. First, it
is redundant with :attr:`fwdpy11.DiploidMetadata.g` for the common case of mutational effects on a single trait.
Second, we save some memory by not tracking these matrices. However, it is useful to track these data for some
cases when simulating multivariate mutational effects (pleiotropy).
.. note::
If recorder is None,
then :class:`fwdpy11.NoAncientSamples` will be used.
"""
import warnings
# Currently, we do not support simulating neutral mutations
# during tree sequence simulations, so we make sure that there
# are no neutral regions/rates:
if len(params.nregions) != 0:
raise ValueError(
"Simulation of neutral mutations on tree sequences not supported (yet).")
# Test parameters while suppressing warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore")
# Will throw exception if anything is wrong:
params.validate()
if recorder is None:
from ._fwdpy11 import NoAncientSamples
recorder = NoAncientSamples()
if stopping_criterion is None:
from ._fwdpy11 import _no_stopping
stopping_criterion = _no_stopping
from ._fwdpy11 import MutationRegions
from ._fwdpy11 import dispatch_create_GeneticMap
from ._fwdpy11 import evolve_with_tree_sequences
# TODO: update to allow neutral mutations
pneutral = 0
mm = MutationRegions.create(pneutral, params.nregions, params.sregions)
rm = dispatch_create_GeneticMap(params.recrate, params.recregions)
from ._fwdpy11 import SampleRecorder
sr = SampleRecorder()
evolve_with_tree_sequences(rng, pop, sr, simplification_interval,
params.demography, params.mutrate_s,
mm, rm, params.gvalue,
recorder, stopping_criterion,
params.pself, params.prune_selected is False,
suppress_table_indexing, record_gvalue_matrix,
track_mutation_counts,
remove_extinct_variants) | python | def evolvets(rng, pop, params, simplification_interval, recorder=None,
suppress_table_indexing=False, record_gvalue_matrix=False,
stopping_criterion=None,
track_mutation_counts=False,
remove_extinct_variants=True):
"""
Evolve a population with tree sequence recording
:param rng: random number generator
:type rng: :class:`fwdpy11.GSLrng`
:param pop: A population
:type pop: :class:`fwdpy11.DiploidPopulation`
:param params: simulation parameters
:type params: :class:`fwdpy11.ModelParams`
:param simplification_interval: Number of generations between simplifications.
:type simplification_interval: int
:param recorder: (None) A temporal sampler/data recorder.
:type recorder: callable
:param suppress_table_indexing: (False) Prevents edge table indexing until end of simulation
:type suppress_table_indexing: boolean
:param record_gvalue_matrix: (False) Whether to record genetic values into :attr:`fwdpy11.Population.genetic_values`.
:type record_gvalue_matrix: boolean
The recording of genetic values into :attr:`fwdpy11.Population.genetic_values` is supprssed by default. First, it
is redundant with :attr:`fwdpy11.DiploidMetadata.g` for the common case of mutational effects on a single trait.
Second, we save some memory by not tracking these matrices. However, it is useful to track these data for some
cases when simulating multivariate mutational effects (pleiotropy).
.. note::
If recorder is None,
then :class:`fwdpy11.NoAncientSamples` will be used.
"""
import warnings
# Currently, we do not support simulating neutral mutations
# during tree sequence simulations, so we make sure that there
# are no neutral regions/rates:
if len(params.nregions) != 0:
raise ValueError(
"Simulation of neutral mutations on tree sequences not supported (yet).")
# Test parameters while suppressing warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore")
# Will throw exception if anything is wrong:
params.validate()
if recorder is None:
from ._fwdpy11 import NoAncientSamples
recorder = NoAncientSamples()
if stopping_criterion is None:
from ._fwdpy11 import _no_stopping
stopping_criterion = _no_stopping
from ._fwdpy11 import MutationRegions
from ._fwdpy11 import dispatch_create_GeneticMap
from ._fwdpy11 import evolve_with_tree_sequences
# TODO: update to allow neutral mutations
pneutral = 0
mm = MutationRegions.create(pneutral, params.nregions, params.sregions)
rm = dispatch_create_GeneticMap(params.recrate, params.recregions)
from ._fwdpy11 import SampleRecorder
sr = SampleRecorder()
evolve_with_tree_sequences(rng, pop, sr, simplification_interval,
params.demography, params.mutrate_s,
mm, rm, params.gvalue,
recorder, stopping_criterion,
params.pself, params.prune_selected is False,
suppress_table_indexing, record_gvalue_matrix,
track_mutation_counts,
remove_extinct_variants) | [
"def",
"evolvets",
"(",
"rng",
",",
"pop",
",",
"params",
",",
"simplification_interval",
",",
"recorder",
"=",
"None",
",",
"suppress_table_indexing",
"=",
"False",
",",
"record_gvalue_matrix",
"=",
"False",
",",
"stopping_criterion",
"=",
"None",
",",
"track_m... | Evolve a population with tree sequence recording
:param rng: random number generator
:type rng: :class:`fwdpy11.GSLrng`
:param pop: A population
:type pop: :class:`fwdpy11.DiploidPopulation`
:param params: simulation parameters
:type params: :class:`fwdpy11.ModelParams`
:param simplification_interval: Number of generations between simplifications.
:type simplification_interval: int
:param recorder: (None) A temporal sampler/data recorder.
:type recorder: callable
:param suppress_table_indexing: (False) Prevents edge table indexing until end of simulation
:type suppress_table_indexing: boolean
:param record_gvalue_matrix: (False) Whether to record genetic values into :attr:`fwdpy11.Population.genetic_values`.
:type record_gvalue_matrix: boolean
The recording of genetic values into :attr:`fwdpy11.Population.genetic_values` is supprssed by default. First, it
is redundant with :attr:`fwdpy11.DiploidMetadata.g` for the common case of mutational effects on a single trait.
Second, we save some memory by not tracking these matrices. However, it is useful to track these data for some
cases when simulating multivariate mutational effects (pleiotropy).
.. note::
If recorder is None,
then :class:`fwdpy11.NoAncientSamples` will be used. | [
"Evolve",
"a",
"population",
"with",
"tree",
"sequence",
"recording"
] | 7a5905f0f0a09e24ae5b0f39d22017499e81ea9e | https://github.com/molpopgen/fwdpy11/blob/7a5905f0f0a09e24ae5b0f39d22017499e81ea9e/fwdpy11/_evolvets.py#L21-L94 | train | 42,658 |
molpopgen/fwdpy11 | fwdpy11/demography.py | exponential_size_change | def exponential_size_change(Nstart, Nstop, time):
"""
Generate a list of population sizes
according to exponential size_change model
:param Nstart: population size at onset of size change
:param Nstop: Population size to reach at end of size change
:param time: Time (in generations) to get from Nstart to Nstop
:return: A list of integers representing population size over time.
.. versionadded:: 0.1.1
"""
if time < 1:
raise RuntimeError("time must be >= 1")
if Nstart < 1 or Nstop < 1:
raise RuntimeError("Nstart and Nstop must both be >= 1")
G = math.exp((math.log(Nstop) - math.log(Nstart))/time)
rv = []
for i in range(time):
rv.append(round(Nstart*pow(G, i+1)))
return rv | python | def exponential_size_change(Nstart, Nstop, time):
"""
Generate a list of population sizes
according to exponential size_change model
:param Nstart: population size at onset of size change
:param Nstop: Population size to reach at end of size change
:param time: Time (in generations) to get from Nstart to Nstop
:return: A list of integers representing population size over time.
.. versionadded:: 0.1.1
"""
if time < 1:
raise RuntimeError("time must be >= 1")
if Nstart < 1 or Nstop < 1:
raise RuntimeError("Nstart and Nstop must both be >= 1")
G = math.exp((math.log(Nstop) - math.log(Nstart))/time)
rv = []
for i in range(time):
rv.append(round(Nstart*pow(G, i+1)))
return rv | [
"def",
"exponential_size_change",
"(",
"Nstart",
",",
"Nstop",
",",
"time",
")",
":",
"if",
"time",
"<",
"1",
":",
"raise",
"RuntimeError",
"(",
"\"time must be >= 1\"",
")",
"if",
"Nstart",
"<",
"1",
"or",
"Nstop",
"<",
"1",
":",
"raise",
"RuntimeError",
... | Generate a list of population sizes
according to exponential size_change model
:param Nstart: population size at onset of size change
:param Nstop: Population size to reach at end of size change
:param time: Time (in generations) to get from Nstart to Nstop
:return: A list of integers representing population size over time.
.. versionadded:: 0.1.1 | [
"Generate",
"a",
"list",
"of",
"population",
"sizes",
"according",
"to",
"exponential",
"size_change",
"model"
] | 7a5905f0f0a09e24ae5b0f39d22017499e81ea9e | https://github.com/molpopgen/fwdpy11/blob/7a5905f0f0a09e24ae5b0f39d22017499e81ea9e/fwdpy11/demography.py#L4-L25 | train | 42,659 |
markdrago/pgsanity | pgsanity/pgsanity.py | check_file | def check_file(filename=None, show_filename=False, add_semicolon=False):
"""
Check whether an input file is valid PostgreSQL. If no filename is
passed, STDIN is checked.
Returns a status code: 0 if the input is valid, 1 if invalid.
"""
# either work with sys.stdin or open the file
if filename is not None:
with open(filename, "r") as filelike:
sql_string = filelike.read()
else:
with sys.stdin as filelike:
sql_string = sys.stdin.read()
success, msg = check_string(sql_string, add_semicolon=add_semicolon)
# report results
result = 0
if not success:
# possibly show the filename with the error message
prefix = ""
if show_filename and filename is not None:
prefix = filename + ": "
print(prefix + msg)
result = 1
return result | python | def check_file(filename=None, show_filename=False, add_semicolon=False):
"""
Check whether an input file is valid PostgreSQL. If no filename is
passed, STDIN is checked.
Returns a status code: 0 if the input is valid, 1 if invalid.
"""
# either work with sys.stdin or open the file
if filename is not None:
with open(filename, "r") as filelike:
sql_string = filelike.read()
else:
with sys.stdin as filelike:
sql_string = sys.stdin.read()
success, msg = check_string(sql_string, add_semicolon=add_semicolon)
# report results
result = 0
if not success:
# possibly show the filename with the error message
prefix = ""
if show_filename and filename is not None:
prefix = filename + ": "
print(prefix + msg)
result = 1
return result | [
"def",
"check_file",
"(",
"filename",
"=",
"None",
",",
"show_filename",
"=",
"False",
",",
"add_semicolon",
"=",
"False",
")",
":",
"# either work with sys.stdin or open the file",
"if",
"filename",
"is",
"not",
"None",
":",
"with",
"open",
"(",
"filename",
","... | Check whether an input file is valid PostgreSQL. If no filename is
passed, STDIN is checked.
Returns a status code: 0 if the input is valid, 1 if invalid. | [
"Check",
"whether",
"an",
"input",
"file",
"is",
"valid",
"PostgreSQL",
".",
"If",
"no",
"filename",
"is",
"passed",
"STDIN",
"is",
"checked",
"."
] | 3bd391be1c5f0e2ce041652bdaf1d6b54424c6d8 | https://github.com/markdrago/pgsanity/blob/3bd391be1c5f0e2ce041652bdaf1d6b54424c6d8/pgsanity/pgsanity.py#L17-L44 | train | 42,660 |
markdrago/pgsanity | pgsanity/pgsanity.py | check_string | def check_string(sql_string, add_semicolon=False):
"""
Check whether a string is valid PostgreSQL. Returns a boolean
indicating validity and a message from ecpg, which will be an
empty string if the input was valid, or a description of the
problem otherwise.
"""
prepped_sql = sqlprep.prepare_sql(sql_string, add_semicolon=add_semicolon)
success, msg = ecpg.check_syntax(prepped_sql)
return success, msg | python | def check_string(sql_string, add_semicolon=False):
"""
Check whether a string is valid PostgreSQL. Returns a boolean
indicating validity and a message from ecpg, which will be an
empty string if the input was valid, or a description of the
problem otherwise.
"""
prepped_sql = sqlprep.prepare_sql(sql_string, add_semicolon=add_semicolon)
success, msg = ecpg.check_syntax(prepped_sql)
return success, msg | [
"def",
"check_string",
"(",
"sql_string",
",",
"add_semicolon",
"=",
"False",
")",
":",
"prepped_sql",
"=",
"sqlprep",
".",
"prepare_sql",
"(",
"sql_string",
",",
"add_semicolon",
"=",
"add_semicolon",
")",
"success",
",",
"msg",
"=",
"ecpg",
".",
"check_synta... | Check whether a string is valid PostgreSQL. Returns a boolean
indicating validity and a message from ecpg, which will be an
empty string if the input was valid, or a description of the
problem otherwise. | [
"Check",
"whether",
"a",
"string",
"is",
"valid",
"PostgreSQL",
".",
"Returns",
"a",
"boolean",
"indicating",
"validity",
"and",
"a",
"message",
"from",
"ecpg",
"which",
"will",
"be",
"an",
"empty",
"string",
"if",
"the",
"input",
"was",
"valid",
"or",
"a"... | 3bd391be1c5f0e2ce041652bdaf1d6b54424c6d8 | https://github.com/markdrago/pgsanity/blob/3bd391be1c5f0e2ce041652bdaf1d6b54424c6d8/pgsanity/pgsanity.py#L46-L55 | train | 42,661 |
markdrago/pgsanity | pgsanity/ecpg.py | check_syntax | def check_syntax(string):
""" Check syntax of a string of PostgreSQL-dialect SQL """
args = ["ecpg", "-o", "-", "-"]
with open(os.devnull, "w") as devnull:
try:
proc = subprocess.Popen(args, shell=False,
stdout=devnull,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
_, err = proc.communicate(string)
except OSError:
msg = "Unable to execute 'ecpg', you likely need to install it.'"
raise OSError(msg)
if proc.returncode == 0:
return (True, "")
else:
return (False, parse_error(err)) | python | def check_syntax(string):
""" Check syntax of a string of PostgreSQL-dialect SQL """
args = ["ecpg", "-o", "-", "-"]
with open(os.devnull, "w") as devnull:
try:
proc = subprocess.Popen(args, shell=False,
stdout=devnull,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
_, err = proc.communicate(string)
except OSError:
msg = "Unable to execute 'ecpg', you likely need to install it.'"
raise OSError(msg)
if proc.returncode == 0:
return (True, "")
else:
return (False, parse_error(err)) | [
"def",
"check_syntax",
"(",
"string",
")",
":",
"args",
"=",
"[",
"\"ecpg\"",
",",
"\"-o\"",
",",
"\"-\"",
",",
"\"-\"",
"]",
"with",
"open",
"(",
"os",
".",
"devnull",
",",
"\"w\"",
")",
"as",
"devnull",
":",
"try",
":",
"proc",
"=",
"subprocess",
... | Check syntax of a string of PostgreSQL-dialect SQL | [
"Check",
"syntax",
"of",
"a",
"string",
"of",
"PostgreSQL",
"-",
"dialect",
"SQL"
] | 3bd391be1c5f0e2ce041652bdaf1d6b54424c6d8 | https://github.com/markdrago/pgsanity/blob/3bd391be1c5f0e2ce041652bdaf1d6b54424c6d8/pgsanity/ecpg.py#L6-L24 | train | 42,662 |
QualiSystems/vCenterShell | package/cloudshell/cp/vcenter/common/vcenter/vmomi_service.py | pyVmomiService.find_datacenter_by_name | def find_datacenter_by_name(self, si, path, name):
"""
Finds datacenter in the vCenter or returns "None"
:param si: pyvmomi 'ServiceInstance'
:param path: the path to find the object ('dc' or 'dc/folder' or 'dc/folder/folder/etc...')
:param name: the datacenter name to return
"""
return self.find_obj_by_path(si, path, name, self.Datacenter) | python | def find_datacenter_by_name(self, si, path, name):
"""
Finds datacenter in the vCenter or returns "None"
:param si: pyvmomi 'ServiceInstance'
:param path: the path to find the object ('dc' or 'dc/folder' or 'dc/folder/folder/etc...')
:param name: the datacenter name to return
"""
return self.find_obj_by_path(si, path, name, self.Datacenter) | [
"def",
"find_datacenter_by_name",
"(",
"self",
",",
"si",
",",
"path",
",",
"name",
")",
":",
"return",
"self",
".",
"find_obj_by_path",
"(",
"si",
",",
"path",
",",
"name",
",",
"self",
".",
"Datacenter",
")"
] | Finds datacenter in the vCenter or returns "None"
:param si: pyvmomi 'ServiceInstance'
:param path: the path to find the object ('dc' or 'dc/folder' or 'dc/folder/folder/etc...')
:param name: the datacenter name to return | [
"Finds",
"datacenter",
"in",
"the",
"vCenter",
"or",
"returns",
"None"
] | e2e24cd938a92a68f4a8e6a860810d3ef72aae6d | https://github.com/QualiSystems/vCenterShell/blob/e2e24cd938a92a68f4a8e6a860810d3ef72aae6d/package/cloudshell/cp/vcenter/common/vcenter/vmomi_service.py#L93-L101 | train | 42,663 |
QualiSystems/vCenterShell | package/cloudshell/cp/vcenter/common/vcenter/vmomi_service.py | pyVmomiService.find_network_by_name | def find_network_by_name(self, si, path, name):
"""
Finds network in the vCenter or returns "None"
:param si: pyvmomi 'ServiceInstance'
:param path: the path to find the object ('dc' or 'dc/folder' or 'dc/folder/folder/etc...')
:param name: the datastore name to return
"""
return self.find_obj_by_path(si, path, name, self.Network) | python | def find_network_by_name(self, si, path, name):
"""
Finds network in the vCenter or returns "None"
:param si: pyvmomi 'ServiceInstance'
:param path: the path to find the object ('dc' or 'dc/folder' or 'dc/folder/folder/etc...')
:param name: the datastore name to return
"""
return self.find_obj_by_path(si, path, name, self.Network) | [
"def",
"find_network_by_name",
"(",
"self",
",",
"si",
",",
"path",
",",
"name",
")",
":",
"return",
"self",
".",
"find_obj_by_path",
"(",
"si",
",",
"path",
",",
"name",
",",
"self",
".",
"Network",
")"
] | Finds network in the vCenter or returns "None"
:param si: pyvmomi 'ServiceInstance'
:param path: the path to find the object ('dc' or 'dc/folder' or 'dc/folder/folder/etc...')
:param name: the datastore name to return | [
"Finds",
"network",
"in",
"the",
"vCenter",
"or",
"returns",
"None"
] | e2e24cd938a92a68f4a8e6a860810d3ef72aae6d | https://github.com/QualiSystems/vCenterShell/blob/e2e24cd938a92a68f4a8e6a860810d3ef72aae6d/package/cloudshell/cp/vcenter/common/vcenter/vmomi_service.py#L184-L192 | train | 42,664 |
QualiSystems/vCenterShell | package/cloudshell/cp/vcenter/common/vcenter/vmomi_service.py | pyVmomiService.find_vm_by_name | def find_vm_by_name(self, si, path, name):
"""
Finds vm in the vCenter or returns "None"
:param si: pyvmomi 'ServiceInstance'
:param path: the path to find the object ('dc' or 'dc/folder' or 'dc/folder/folder/etc...')
:param name: the vm name to return
"""
return self.find_obj_by_path(si, path, name, self.VM) | python | def find_vm_by_name(self, si, path, name):
"""
Finds vm in the vCenter or returns "None"
:param si: pyvmomi 'ServiceInstance'
:param path: the path to find the object ('dc' or 'dc/folder' or 'dc/folder/folder/etc...')
:param name: the vm name to return
"""
return self.find_obj_by_path(si, path, name, self.VM) | [
"def",
"find_vm_by_name",
"(",
"self",
",",
"si",
",",
"path",
",",
"name",
")",
":",
"return",
"self",
".",
"find_obj_by_path",
"(",
"si",
",",
"path",
",",
"name",
",",
"self",
".",
"VM",
")"
] | Finds vm in the vCenter or returns "None"
:param si: pyvmomi 'ServiceInstance'
:param path: the path to find the object ('dc' or 'dc/folder' or 'dc/folder/folder/etc...')
:param name: the vm name to return | [
"Finds",
"vm",
"in",
"the",
"vCenter",
"or",
"returns",
"None"
] | e2e24cd938a92a68f4a8e6a860810d3ef72aae6d | https://github.com/QualiSystems/vCenterShell/blob/e2e24cd938a92a68f4a8e6a860810d3ef72aae6d/package/cloudshell/cp/vcenter/common/vcenter/vmomi_service.py#L194-L202 | train | 42,665 |
QualiSystems/vCenterShell | package/cloudshell/cp/vcenter/common/vcenter/vmomi_service.py | pyVmomiService.find_obj_by_path | def find_obj_by_path(self, si, path, name, type_name):
"""
Finds object in the vCenter or returns "None"
:param si: pyvmomi 'ServiceInstance'
:param path: the path to find the object ('dc' or 'dc/folder' or 'dc/folder/folder/etc...')
:param name: the object name to return
:param type_name: the name of the type, can be (vm, network, host, datastore)
"""
folder = self.get_folder(si, path)
if folder is None:
raise ValueError('vmomi managed object not found at: {0}'.format(path))
look_in = None
if hasattr(folder, type_name):
look_in = getattr(folder, type_name)
if hasattr(folder, self.ChildEntity):
look_in = folder
if look_in is None:
raise ValueError('vmomi managed object not found at: {0}'.format(path))
search_index = si.content.searchIndex
'#searches for the specific vm in the folder'
return search_index.FindChild(look_in, name) | python | def find_obj_by_path(self, si, path, name, type_name):
"""
Finds object in the vCenter or returns "None"
:param si: pyvmomi 'ServiceInstance'
:param path: the path to find the object ('dc' or 'dc/folder' or 'dc/folder/folder/etc...')
:param name: the object name to return
:param type_name: the name of the type, can be (vm, network, host, datastore)
"""
folder = self.get_folder(si, path)
if folder is None:
raise ValueError('vmomi managed object not found at: {0}'.format(path))
look_in = None
if hasattr(folder, type_name):
look_in = getattr(folder, type_name)
if hasattr(folder, self.ChildEntity):
look_in = folder
if look_in is None:
raise ValueError('vmomi managed object not found at: {0}'.format(path))
search_index = si.content.searchIndex
'#searches for the specific vm in the folder'
return search_index.FindChild(look_in, name) | [
"def",
"find_obj_by_path",
"(",
"self",
",",
"si",
",",
"path",
",",
"name",
",",
"type_name",
")",
":",
"folder",
"=",
"self",
".",
"get_folder",
"(",
"si",
",",
"path",
")",
"if",
"folder",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'vmomi manag... | Finds object in the vCenter or returns "None"
:param si: pyvmomi 'ServiceInstance'
:param path: the path to find the object ('dc' or 'dc/folder' or 'dc/folder/folder/etc...')
:param name: the object name to return
:param type_name: the name of the type, can be (vm, network, host, datastore) | [
"Finds",
"object",
"in",
"the",
"vCenter",
"or",
"returns",
"None"
] | e2e24cd938a92a68f4a8e6a860810d3ef72aae6d | https://github.com/QualiSystems/vCenterShell/blob/e2e24cd938a92a68f4a8e6a860810d3ef72aae6d/package/cloudshell/cp/vcenter/common/vcenter/vmomi_service.py#L204-L228 | train | 42,666 |
QualiSystems/vCenterShell | package/cloudshell/cp/vcenter/common/vcenter/vmomi_service.py | pyVmomiService.get_folder | def get_folder(self, si, path, root=None):
"""
Finds folder in the vCenter or returns "None"
:param si: pyvmomi 'ServiceInstance'
:param path: the path to find the object ('dc' or 'dc/folder' or 'dc/folder/folder/etc...')
"""
search_index = si.content.searchIndex
sub_folder = root if root else si.content.rootFolder
if not path:
return sub_folder
paths = [p for p in path.split("/") if p]
child = None
try:
new_root = search_index.FindChild(sub_folder, paths[0])
if new_root:
child = self.get_folder(si, '/'.join(paths[1:]), new_root)
except:
child = None
if child is None and hasattr(sub_folder, self.ChildEntity):
new_root = search_index.FindChild(sub_folder, paths[0])
if new_root:
child = self.get_folder(si, '/'.join(paths[1:]), new_root)
if child is None and hasattr(sub_folder, self.VM):
new_root = search_index.FindChild(sub_folder.vmFolder, paths[0])
if new_root:
child = self.get_folder(si, '/'.join(paths[1:]), new_root)
if child is None and hasattr(sub_folder, self.Datastore):
new_root = search_index.FindChild(sub_folder.datastoreFolder, paths[0])
if new_root:
child = self.get_folder(si, '/'.join(paths[1:]), new_root)
if child is None and hasattr(sub_folder, self.Network):
new_root = search_index.FindChild(sub_folder.networkFolder, paths[0])
if new_root:
child = self.get_folder(si, '/'.join(paths[1:]), new_root)
if child is None and hasattr(sub_folder, self.Host):
new_root = search_index.FindChild(sub_folder.hostFolder, paths[0])
if new_root:
child = self.get_folder(si, '/'.join(paths[1:]), new_root)
if child is None and hasattr(sub_folder, self.Datacenter):
new_root = search_index.FindChild(sub_folder.datacenterFolder, paths[0])
if new_root:
child = self.get_folder(si, '/'.join(paths[1:]), new_root)
if child is None and hasattr(sub_folder, 'resourcePool'):
new_root = search_index.FindChild(sub_folder.resourcePool, paths[0])
if new_root:
child = self.get_folder(si, '/'.join(paths[1:]), new_root)
return child | python | def get_folder(self, si, path, root=None):
"""
Finds folder in the vCenter or returns "None"
:param si: pyvmomi 'ServiceInstance'
:param path: the path to find the object ('dc' or 'dc/folder' or 'dc/folder/folder/etc...')
"""
search_index = si.content.searchIndex
sub_folder = root if root else si.content.rootFolder
if not path:
return sub_folder
paths = [p for p in path.split("/") if p]
child = None
try:
new_root = search_index.FindChild(sub_folder, paths[0])
if new_root:
child = self.get_folder(si, '/'.join(paths[1:]), new_root)
except:
child = None
if child is None and hasattr(sub_folder, self.ChildEntity):
new_root = search_index.FindChild(sub_folder, paths[0])
if new_root:
child = self.get_folder(si, '/'.join(paths[1:]), new_root)
if child is None and hasattr(sub_folder, self.VM):
new_root = search_index.FindChild(sub_folder.vmFolder, paths[0])
if new_root:
child = self.get_folder(si, '/'.join(paths[1:]), new_root)
if child is None and hasattr(sub_folder, self.Datastore):
new_root = search_index.FindChild(sub_folder.datastoreFolder, paths[0])
if new_root:
child = self.get_folder(si, '/'.join(paths[1:]), new_root)
if child is None and hasattr(sub_folder, self.Network):
new_root = search_index.FindChild(sub_folder.networkFolder, paths[0])
if new_root:
child = self.get_folder(si, '/'.join(paths[1:]), new_root)
if child is None and hasattr(sub_folder, self.Host):
new_root = search_index.FindChild(sub_folder.hostFolder, paths[0])
if new_root:
child = self.get_folder(si, '/'.join(paths[1:]), new_root)
if child is None and hasattr(sub_folder, self.Datacenter):
new_root = search_index.FindChild(sub_folder.datacenterFolder, paths[0])
if new_root:
child = self.get_folder(si, '/'.join(paths[1:]), new_root)
if child is None and hasattr(sub_folder, 'resourcePool'):
new_root = search_index.FindChild(sub_folder.resourcePool, paths[0])
if new_root:
child = self.get_folder(si, '/'.join(paths[1:]), new_root)
return child | [
"def",
"get_folder",
"(",
"self",
",",
"si",
",",
"path",
",",
"root",
"=",
"None",
")",
":",
"search_index",
"=",
"si",
".",
"content",
".",
"searchIndex",
"sub_folder",
"=",
"root",
"if",
"root",
"else",
"si",
".",
"content",
".",
"rootFolder",
"if",... | Finds folder in the vCenter or returns "None"
:param si: pyvmomi 'ServiceInstance'
:param path: the path to find the object ('dc' or 'dc/folder' or 'dc/folder/folder/etc...') | [
"Finds",
"folder",
"in",
"the",
"vCenter",
"or",
"returns",
"None"
] | e2e24cd938a92a68f4a8e6a860810d3ef72aae6d | https://github.com/QualiSystems/vCenterShell/blob/e2e24cd938a92a68f4a8e6a860810d3ef72aae6d/package/cloudshell/cp/vcenter/common/vcenter/vmomi_service.py#L245-L304 | train | 42,667 |
QualiSystems/vCenterShell | package/cloudshell/cp/vcenter/common/vcenter/vmomi_service.py | pyVmomiService.get_obj | def get_obj(self, content, vimtype, name):
"""
Return an object by name for a specific type, if name is None the
first found object is returned
:param content: pyvmomi content object
:param vimtype: the type of object too search
:param name: the object name to return
"""
obj = None
container = self._get_all_objects_by_type(content, vimtype)
# If no name was given will return the first object from list of a objects matching the given vimtype type
for c in container.view:
if name:
if c.name == name:
obj = c
break
else:
obj = c
break
return obj | python | def get_obj(self, content, vimtype, name):
"""
Return an object by name for a specific type, if name is None the
first found object is returned
:param content: pyvmomi content object
:param vimtype: the type of object too search
:param name: the object name to return
"""
obj = None
container = self._get_all_objects_by_type(content, vimtype)
# If no name was given will return the first object from list of a objects matching the given vimtype type
for c in container.view:
if name:
if c.name == name:
obj = c
break
else:
obj = c
break
return obj | [
"def",
"get_obj",
"(",
"self",
",",
"content",
",",
"vimtype",
",",
"name",
")",
":",
"obj",
"=",
"None",
"container",
"=",
"self",
".",
"_get_all_objects_by_type",
"(",
"content",
",",
"vimtype",
")",
"# If no name was given will return the first object from list o... | Return an object by name for a specific type, if name is None the
first found object is returned
:param content: pyvmomi content object
:param vimtype: the type of object too search
:param name: the object name to return | [
"Return",
"an",
"object",
"by",
"name",
"for",
"a",
"specific",
"type",
"if",
"name",
"is",
"None",
"the",
"first",
"found",
"object",
"is",
"returned"
] | e2e24cd938a92a68f4a8e6a860810d3ef72aae6d | https://github.com/QualiSystems/vCenterShell/blob/e2e24cd938a92a68f4a8e6a860810d3ef72aae6d/package/cloudshell/cp/vcenter/common/vcenter/vmomi_service.py#L315-L338 | train | 42,668 |
QualiSystems/vCenterShell | package/cloudshell/cp/vcenter/commands/save_sandbox.py | SaveAppCommand.save_app | def save_app(self, si, logger, vcenter_data_model, reservation_id, save_app_actions, cancellation_context):
"""
Cretaes an artifact of an app, that can later be restored
:param vcenter_data_model: VMwarevCenterResourceModel
:param vim.ServiceInstance si: py_vmomi service instance
:type si: vim.ServiceInstance
:param logger: Logger
:type logger: cloudshell.core.logger.qs_logger.get_qs_logger
:param list[SaveApp] save_app_actions:
:param cancellation_context:
"""
results = []
logger.info('Save Sandbox command starting on ' + vcenter_data_model.default_datacenter)
if not save_app_actions:
raise Exception('Failed to save app, missing data in request.')
actions_grouped_by_save_types = groupby(save_app_actions, lambda x: x.actionParams.saveDeploymentModel)
# artifactSaver or artifactHandler are different ways to save artifacts. For example, currently
# we clone a vm, thenk take a snapshot. restore will be to deploy from linked snapshot
# a future artifact handler we might develop is save vm to OVF file and restore from file.
artifactSaversToActions = {ArtifactHandler.factory(k,
self.pyvmomi_service,
vcenter_data_model,
si,
logger,
self.deployer,
reservation_id,
self.resource_model_parser,
self.snapshot_saver,
self.task_waiter,
self.folder_manager,
self.port_group_configurer,
self.cs)
: list(g)
for k, g in actions_grouped_by_save_types}
self.validate_requested_save_types_supported(artifactSaversToActions,
logger,
results)
error_results = [r for r in results if not r.success]
if not error_results:
logger.info('Handling Save App requests')
results = self._execute_save_actions_using_pool(artifactSaversToActions,
cancellation_context,
logger,
results)
logger.info('Completed Save Sandbox command')
else:
logger.error('Some save app requests were not valid, Save Sandbox command failed.')
return results | python | def save_app(self, si, logger, vcenter_data_model, reservation_id, save_app_actions, cancellation_context):
"""
Cretaes an artifact of an app, that can later be restored
:param vcenter_data_model: VMwarevCenterResourceModel
:param vim.ServiceInstance si: py_vmomi service instance
:type si: vim.ServiceInstance
:param logger: Logger
:type logger: cloudshell.core.logger.qs_logger.get_qs_logger
:param list[SaveApp] save_app_actions:
:param cancellation_context:
"""
results = []
logger.info('Save Sandbox command starting on ' + vcenter_data_model.default_datacenter)
if not save_app_actions:
raise Exception('Failed to save app, missing data in request.')
actions_grouped_by_save_types = groupby(save_app_actions, lambda x: x.actionParams.saveDeploymentModel)
# artifactSaver or artifactHandler are different ways to save artifacts. For example, currently
# we clone a vm, thenk take a snapshot. restore will be to deploy from linked snapshot
# a future artifact handler we might develop is save vm to OVF file and restore from file.
artifactSaversToActions = {ArtifactHandler.factory(k,
self.pyvmomi_service,
vcenter_data_model,
si,
logger,
self.deployer,
reservation_id,
self.resource_model_parser,
self.snapshot_saver,
self.task_waiter,
self.folder_manager,
self.port_group_configurer,
self.cs)
: list(g)
for k, g in actions_grouped_by_save_types}
self.validate_requested_save_types_supported(artifactSaversToActions,
logger,
results)
error_results = [r for r in results if not r.success]
if not error_results:
logger.info('Handling Save App requests')
results = self._execute_save_actions_using_pool(artifactSaversToActions,
cancellation_context,
logger,
results)
logger.info('Completed Save Sandbox command')
else:
logger.error('Some save app requests were not valid, Save Sandbox command failed.')
return results | [
"def",
"save_app",
"(",
"self",
",",
"si",
",",
"logger",
",",
"vcenter_data_model",
",",
"reservation_id",
",",
"save_app_actions",
",",
"cancellation_context",
")",
":",
"results",
"=",
"[",
"]",
"logger",
".",
"info",
"(",
"'Save Sandbox command starting on '",... | Cretaes an artifact of an app, that can later be restored
:param vcenter_data_model: VMwarevCenterResourceModel
:param vim.ServiceInstance si: py_vmomi service instance
:type si: vim.ServiceInstance
:param logger: Logger
:type logger: cloudshell.core.logger.qs_logger.get_qs_logger
:param list[SaveApp] save_app_actions:
:param cancellation_context: | [
"Cretaes",
"an",
"artifact",
"of",
"an",
"app",
"that",
"can",
"later",
"be",
"restored"
] | e2e24cd938a92a68f4a8e6a860810d3ef72aae6d | https://github.com/QualiSystems/vCenterShell/blob/e2e24cd938a92a68f4a8e6a860810d3ef72aae6d/package/cloudshell/cp/vcenter/commands/save_sandbox.py#L38-L91 | train | 42,669 |
openfisca/country-template | openfisca_country_template/variables/benefits.py | housing_allowance.formula_1980 | def formula_1980(household, period, parameters):
'''
To compute this allowance, the 'rent' value must be provided for the same month, but 'housing_occupancy_status' is not necessary.
'''
return household('rent', period) * parameters(period).benefits.housing_allowance | python | def formula_1980(household, period, parameters):
'''
To compute this allowance, the 'rent' value must be provided for the same month, but 'housing_occupancy_status' is not necessary.
'''
return household('rent', period) * parameters(period).benefits.housing_allowance | [
"def",
"formula_1980",
"(",
"household",
",",
"period",
",",
"parameters",
")",
":",
"return",
"household",
"(",
"'rent'",
",",
"period",
")",
"*",
"parameters",
"(",
"period",
")",
".",
"benefits",
".",
"housing_allowance"
] | To compute this allowance, the 'rent' value must be provided for the same month, but 'housing_occupancy_status' is not necessary. | [
"To",
"compute",
"this",
"allowance",
"the",
"rent",
"value",
"must",
"be",
"provided",
"for",
"the",
"same",
"month",
"but",
"housing_occupancy_status",
"is",
"not",
"necessary",
"."
] | b469ec97fecaf273d3a59deffa2ad13b727bde32 | https://github.com/openfisca/country-template/blob/b469ec97fecaf273d3a59deffa2ad13b727bde32/openfisca_country_template/variables/benefits.py#L47-L51 | train | 42,670 |
QualiSystems/vCenterShell | package/cloudshell/cp/vcenter/commands/command_orchestrator.py | CommandOrchestrator.deploy_from_template | def deploy_from_template(self, context, deploy_action, cancellation_context):
"""
Deploy From Template Command, will deploy vm from template
:param CancellationContext cancellation_context:
:param ResourceCommandContext context: the context of the command
:param DeployApp deploy_action:
:return DeployAppResult deploy results
"""
deploy_from_template_model = self.resource_model_parser.convert_to_resource_model(
attributes=deploy_action.actionParams.deployment.attributes,
resource_model_type=vCenterVMFromTemplateResourceModel)
data_holder = DeployFromTemplateDetails(deploy_from_template_model, deploy_action.actionParams.appName)
deploy_result_action = self.command_wrapper.execute_command_with_connection(
context,
self.deploy_command.execute_deploy_from_template,
data_holder,
cancellation_context,
self.folder_manager)
deploy_result_action.actionId = deploy_action.actionId
return deploy_result_action | python | def deploy_from_template(self, context, deploy_action, cancellation_context):
"""
Deploy From Template Command, will deploy vm from template
:param CancellationContext cancellation_context:
:param ResourceCommandContext context: the context of the command
:param DeployApp deploy_action:
:return DeployAppResult deploy results
"""
deploy_from_template_model = self.resource_model_parser.convert_to_resource_model(
attributes=deploy_action.actionParams.deployment.attributes,
resource_model_type=vCenterVMFromTemplateResourceModel)
data_holder = DeployFromTemplateDetails(deploy_from_template_model, deploy_action.actionParams.appName)
deploy_result_action = self.command_wrapper.execute_command_with_connection(
context,
self.deploy_command.execute_deploy_from_template,
data_holder,
cancellation_context,
self.folder_manager)
deploy_result_action.actionId = deploy_action.actionId
return deploy_result_action | [
"def",
"deploy_from_template",
"(",
"self",
",",
"context",
",",
"deploy_action",
",",
"cancellation_context",
")",
":",
"deploy_from_template_model",
"=",
"self",
".",
"resource_model_parser",
".",
"convert_to_resource_model",
"(",
"attributes",
"=",
"deploy_action",
"... | Deploy From Template Command, will deploy vm from template
:param CancellationContext cancellation_context:
:param ResourceCommandContext context: the context of the command
:param DeployApp deploy_action:
:return DeployAppResult deploy results | [
"Deploy",
"From",
"Template",
"Command",
"will",
"deploy",
"vm",
"from",
"template"
] | e2e24cd938a92a68f4a8e6a860810d3ef72aae6d | https://github.com/QualiSystems/vCenterShell/blob/e2e24cd938a92a68f4a8e6a860810d3ef72aae6d/package/cloudshell/cp/vcenter/commands/command_orchestrator.py#L218-L240 | train | 42,671 |
QualiSystems/vCenterShell | package/cloudshell/cp/vcenter/commands/command_orchestrator.py | CommandOrchestrator.deploy_from_image | def deploy_from_image(self, context, deploy_action, cancellation_context):
"""
Deploy From Image Command, will deploy vm from ovf image
:param CancellationContext cancellation_context:
:param ResourceCommandContext context: the context of the command
:param DeployApp deploy_action:
:return str deploy results
"""
deploy_action.actionParams.deployment.attributes['vCenter Name'] = context.resource.name
deploy_from_image_model = self.resource_model_parser.convert_to_resource_model(
attributes=deploy_action.actionParams.deployment.attributes,
resource_model_type=vCenterVMFromImageResourceModel)
data_holder = DeployFromImageDetails(deploy_from_image_model, deploy_action.actionParams.appName)
# execute command
deploy_result_action = self.command_wrapper.execute_command_with_connection(
context,
self.deploy_command.execute_deploy_from_image,
data_holder,
context.resource,
cancellation_context,
self.folder_manager)
deploy_result_action.actionId = deploy_action.actionId
return deploy_result_action | python | def deploy_from_image(self, context, deploy_action, cancellation_context):
"""
Deploy From Image Command, will deploy vm from ovf image
:param CancellationContext cancellation_context:
:param ResourceCommandContext context: the context of the command
:param DeployApp deploy_action:
:return str deploy results
"""
deploy_action.actionParams.deployment.attributes['vCenter Name'] = context.resource.name
deploy_from_image_model = self.resource_model_parser.convert_to_resource_model(
attributes=deploy_action.actionParams.deployment.attributes,
resource_model_type=vCenterVMFromImageResourceModel)
data_holder = DeployFromImageDetails(deploy_from_image_model, deploy_action.actionParams.appName)
# execute command
deploy_result_action = self.command_wrapper.execute_command_with_connection(
context,
self.deploy_command.execute_deploy_from_image,
data_holder,
context.resource,
cancellation_context,
self.folder_manager)
deploy_result_action.actionId = deploy_action.actionId
return deploy_result_action | [
"def",
"deploy_from_image",
"(",
"self",
",",
"context",
",",
"deploy_action",
",",
"cancellation_context",
")",
":",
"deploy_action",
".",
"actionParams",
".",
"deployment",
".",
"attributes",
"[",
"'vCenter Name'",
"]",
"=",
"context",
".",
"resource",
".",
"n... | Deploy From Image Command, will deploy vm from ovf image
:param CancellationContext cancellation_context:
:param ResourceCommandContext context: the context of the command
:param DeployApp deploy_action:
:return str deploy results | [
"Deploy",
"From",
"Image",
"Command",
"will",
"deploy",
"vm",
"from",
"ovf",
"image"
] | e2e24cd938a92a68f4a8e6a860810d3ef72aae6d | https://github.com/QualiSystems/vCenterShell/blob/e2e24cd938a92a68f4a8e6a860810d3ef72aae6d/package/cloudshell/cp/vcenter/commands/command_orchestrator.py#L293-L318 | train | 42,672 |
QualiSystems/vCenterShell | package/cloudshell/cp/vcenter/commands/command_orchestrator.py | CommandOrchestrator.disconnect_all | def disconnect_all(self, context, ports):
"""
Disconnect All Command, will the assign all the vnics on the vm to the default network,
which is sign to be disconnected
:param models.QualiDriverModels.ResourceRemoteCommandContext context: the context the command runs on
:param list[string] ports: the ports of the connection between the remote resource and the local resource, NOT IN USE!!!
"""
resource_details = self._parse_remote_model(context)
# execute command
res = self.command_wrapper.execute_command_with_connection(
context,
self.virtual_switch_disconnect_command.disconnect_all,
resource_details.vm_uuid)
return set_command_result(result=res, unpicklable=False) | python | def disconnect_all(self, context, ports):
"""
Disconnect All Command, will the assign all the vnics on the vm to the default network,
which is sign to be disconnected
:param models.QualiDriverModels.ResourceRemoteCommandContext context: the context the command runs on
:param list[string] ports: the ports of the connection between the remote resource and the local resource, NOT IN USE!!!
"""
resource_details = self._parse_remote_model(context)
# execute command
res = self.command_wrapper.execute_command_with_connection(
context,
self.virtual_switch_disconnect_command.disconnect_all,
resource_details.vm_uuid)
return set_command_result(result=res, unpicklable=False) | [
"def",
"disconnect_all",
"(",
"self",
",",
"context",
",",
"ports",
")",
":",
"resource_details",
"=",
"self",
".",
"_parse_remote_model",
"(",
"context",
")",
"# execute command",
"res",
"=",
"self",
".",
"command_wrapper",
".",
"execute_command_with_connection",
... | Disconnect All Command, will the assign all the vnics on the vm to the default network,
which is sign to be disconnected
:param models.QualiDriverModels.ResourceRemoteCommandContext context: the context the command runs on
:param list[string] ports: the ports of the connection between the remote resource and the local resource, NOT IN USE!!! | [
"Disconnect",
"All",
"Command",
"will",
"the",
"assign",
"all",
"the",
"vnics",
"on",
"the",
"vm",
"to",
"the",
"default",
"network",
"which",
"is",
"sign",
"to",
"be",
"disconnected"
] | e2e24cd938a92a68f4a8e6a860810d3ef72aae6d | https://github.com/QualiSystems/vCenterShell/blob/e2e24cd938a92a68f4a8e6a860810d3ef72aae6d/package/cloudshell/cp/vcenter/commands/command_orchestrator.py#L321-L336 | train | 42,673 |
QualiSystems/vCenterShell | package/cloudshell/cp/vcenter/commands/command_orchestrator.py | CommandOrchestrator.DeleteInstance | def DeleteInstance(self, context, ports):
"""
Destroy Vm Command, will only destroy the vm and will not remove the resource
:param models.QualiDriverModels.ResourceRemoteCommandContext context: the context the command runs on
:param list[string] ports: the ports of the connection between the remote resource and the local resource, NOT IN USE!!!
"""
resource_details = self._parse_remote_model(context)
# execute command
res = self.command_wrapper.execute_command_with_connection(
context,
self.destroy_virtual_machine_command.DeleteInstance,
resource_details.vm_uuid,
resource_details.fullname)
return set_command_result(result=res, unpicklable=False) | python | def DeleteInstance(self, context, ports):
"""
Destroy Vm Command, will only destroy the vm and will not remove the resource
:param models.QualiDriverModels.ResourceRemoteCommandContext context: the context the command runs on
:param list[string] ports: the ports of the connection between the remote resource and the local resource, NOT IN USE!!!
"""
resource_details = self._parse_remote_model(context)
# execute command
res = self.command_wrapper.execute_command_with_connection(
context,
self.destroy_virtual_machine_command.DeleteInstance,
resource_details.vm_uuid,
resource_details.fullname)
return set_command_result(result=res, unpicklable=False) | [
"def",
"DeleteInstance",
"(",
"self",
",",
"context",
",",
"ports",
")",
":",
"resource_details",
"=",
"self",
".",
"_parse_remote_model",
"(",
"context",
")",
"# execute command",
"res",
"=",
"self",
".",
"command_wrapper",
".",
"execute_command_with_connection",
... | Destroy Vm Command, will only destroy the vm and will not remove the resource
:param models.QualiDriverModels.ResourceRemoteCommandContext context: the context the command runs on
:param list[string] ports: the ports of the connection between the remote resource and the local resource, NOT IN USE!!! | [
"Destroy",
"Vm",
"Command",
"will",
"only",
"destroy",
"the",
"vm",
"and",
"will",
"not",
"remove",
"the",
"resource"
] | e2e24cd938a92a68f4a8e6a860810d3ef72aae6d | https://github.com/QualiSystems/vCenterShell/blob/e2e24cd938a92a68f4a8e6a860810d3ef72aae6d/package/cloudshell/cp/vcenter/commands/command_orchestrator.py#L358-L372 | train | 42,674 |
QualiSystems/vCenterShell | package/cloudshell/cp/vcenter/commands/delete_saved_sandbox.py | DeleteSavedSandboxCommand.delete_sandbox | def delete_sandbox(self, si, logger, vcenter_data_model, delete_sandbox_actions, cancellation_context):
"""
Deletes a saved sandbox's artifacts
:param vcenter_data_model: VMwarevCenterResourceModel
:param vim.ServiceInstance si: py_vmomi service instance
:type si: vim.ServiceInstance
:param logger: Logger
:type logger: cloudshell.core.logger.qs_logger.get_qs_logger
:param list[SaveApp] delete_sandbox_actions:
:param cancellation_context:
"""
results = []
logger.info('Deleting saved sandbox command starting on ' + vcenter_data_model.default_datacenter)
if not delete_sandbox_actions:
raise Exception('Failed to delete saved sandbox, missing data in request.')
actions_grouped_by_save_types = groupby(delete_sandbox_actions, lambda x: x.actionParams.saveDeploymentModel)
artifactHandlersToActions = {ArtifactHandler.factory(k,
self.pyvmomi_service,
vcenter_data_model,
si,
logger,
self.deployer,
None,
self.resource_model_parser,
self.snapshot_saver,
self.task_waiter,
self.folder_manager,
self.pg,
self.cs): list(g)
for k, g in actions_grouped_by_save_types}
self._validate_save_deployment_models(artifactHandlersToActions, delete_sandbox_actions, results)
error_results = [r for r in results if not r.success]
if not error_results:
results = self._execute_delete_saved_sandbox(artifactHandlersToActions,
cancellation_context,
logger,
results)
return results | python | def delete_sandbox(self, si, logger, vcenter_data_model, delete_sandbox_actions, cancellation_context):
"""
Deletes a saved sandbox's artifacts
:param vcenter_data_model: VMwarevCenterResourceModel
:param vim.ServiceInstance si: py_vmomi service instance
:type si: vim.ServiceInstance
:param logger: Logger
:type logger: cloudshell.core.logger.qs_logger.get_qs_logger
:param list[SaveApp] delete_sandbox_actions:
:param cancellation_context:
"""
results = []
logger.info('Deleting saved sandbox command starting on ' + vcenter_data_model.default_datacenter)
if not delete_sandbox_actions:
raise Exception('Failed to delete saved sandbox, missing data in request.')
actions_grouped_by_save_types = groupby(delete_sandbox_actions, lambda x: x.actionParams.saveDeploymentModel)
artifactHandlersToActions = {ArtifactHandler.factory(k,
self.pyvmomi_service,
vcenter_data_model,
si,
logger,
self.deployer,
None,
self.resource_model_parser,
self.snapshot_saver,
self.task_waiter,
self.folder_manager,
self.pg,
self.cs): list(g)
for k, g in actions_grouped_by_save_types}
self._validate_save_deployment_models(artifactHandlersToActions, delete_sandbox_actions, results)
error_results = [r for r in results if not r.success]
if not error_results:
results = self._execute_delete_saved_sandbox(artifactHandlersToActions,
cancellation_context,
logger,
results)
return results | [
"def",
"delete_sandbox",
"(",
"self",
",",
"si",
",",
"logger",
",",
"vcenter_data_model",
",",
"delete_sandbox_actions",
",",
"cancellation_context",
")",
":",
"results",
"=",
"[",
"]",
"logger",
".",
"info",
"(",
"'Deleting saved sandbox command starting on '",
"+... | Deletes a saved sandbox's artifacts
:param vcenter_data_model: VMwarevCenterResourceModel
:param vim.ServiceInstance si: py_vmomi service instance
:type si: vim.ServiceInstance
:param logger: Logger
:type logger: cloudshell.core.logger.qs_logger.get_qs_logger
:param list[SaveApp] delete_sandbox_actions:
:param cancellation_context: | [
"Deletes",
"a",
"saved",
"sandbox",
"s",
"artifacts"
] | e2e24cd938a92a68f4a8e6a860810d3ef72aae6d | https://github.com/QualiSystems/vCenterShell/blob/e2e24cd938a92a68f4a8e6a860810d3ef72aae6d/package/cloudshell/cp/vcenter/commands/delete_saved_sandbox.py#L35-L79 | train | 42,675 |
QualiSystems/vCenterShell | package/cloudshell/cp/vcenter/commands/save_snapshot.py | SaveSnapshotCommand.save_snapshot | def save_snapshot(self, si, logger, vm_uuid, snapshot_name, save_memory):
"""
Creates a snapshot of the current state of the virtual machine
:param vim.ServiceInstance si: py_vmomi service instance
:type si: vim.ServiceInstance
:param logger: Logger
:type logger: cloudshell.core.logger.qs_logger.get_qs_logger
:param vm_uuid: UUID of the virtual machine
:type vm_uuid: str
:param snapshot_name: Snapshot name to save the snapshot to
:type snapshot_name: str
:param save_memory: Snapshot the virtual machine's memory. Lookup, Yes / No
:type save_memory: str
"""
vm = self.pyvmomi_service.find_by_uuid(si, vm_uuid)
snapshot_path_to_be_created = SaveSnapshotCommand._get_snapshot_name_to_be_created(snapshot_name, vm)
save_vm_memory_to_snapshot = SaveSnapshotCommand._get_save_vm_memory_to_snapshot(save_memory)
SaveSnapshotCommand._verify_snapshot_uniquness(snapshot_path_to_be_created, vm)
task = self._create_snapshot(logger, snapshot_name, vm, save_vm_memory_to_snapshot)
self.task_waiter.wait_for_task(task=task, logger=logger, action_name='Create Snapshot')
return snapshot_path_to_be_created | python | def save_snapshot(self, si, logger, vm_uuid, snapshot_name, save_memory):
"""
Creates a snapshot of the current state of the virtual machine
:param vim.ServiceInstance si: py_vmomi service instance
:type si: vim.ServiceInstance
:param logger: Logger
:type logger: cloudshell.core.logger.qs_logger.get_qs_logger
:param vm_uuid: UUID of the virtual machine
:type vm_uuid: str
:param snapshot_name: Snapshot name to save the snapshot to
:type snapshot_name: str
:param save_memory: Snapshot the virtual machine's memory. Lookup, Yes / No
:type save_memory: str
"""
vm = self.pyvmomi_service.find_by_uuid(si, vm_uuid)
snapshot_path_to_be_created = SaveSnapshotCommand._get_snapshot_name_to_be_created(snapshot_name, vm)
save_vm_memory_to_snapshot = SaveSnapshotCommand._get_save_vm_memory_to_snapshot(save_memory)
SaveSnapshotCommand._verify_snapshot_uniquness(snapshot_path_to_be_created, vm)
task = self._create_snapshot(logger, snapshot_name, vm, save_vm_memory_to_snapshot)
self.task_waiter.wait_for_task(task=task, logger=logger, action_name='Create Snapshot')
return snapshot_path_to_be_created | [
"def",
"save_snapshot",
"(",
"self",
",",
"si",
",",
"logger",
",",
"vm_uuid",
",",
"snapshot_name",
",",
"save_memory",
")",
":",
"vm",
"=",
"self",
".",
"pyvmomi_service",
".",
"find_by_uuid",
"(",
"si",
",",
"vm_uuid",
")",
"snapshot_path_to_be_created",
... | Creates a snapshot of the current state of the virtual machine
:param vim.ServiceInstance si: py_vmomi service instance
:type si: vim.ServiceInstance
:param logger: Logger
:type logger: cloudshell.core.logger.qs_logger.get_qs_logger
:param vm_uuid: UUID of the virtual machine
:type vm_uuid: str
:param snapshot_name: Snapshot name to save the snapshot to
:type snapshot_name: str
:param save_memory: Snapshot the virtual machine's memory. Lookup, Yes / No
:type save_memory: str | [
"Creates",
"a",
"snapshot",
"of",
"the",
"current",
"state",
"of",
"the",
"virtual",
"machine"
] | e2e24cd938a92a68f4a8e6a860810d3ef72aae6d | https://github.com/QualiSystems/vCenterShell/blob/e2e24cd938a92a68f4a8e6a860810d3ef72aae6d/package/cloudshell/cp/vcenter/commands/save_snapshot.py#L22-L48 | train | 42,676 |
QualiSystems/vCenterShell | package/cloudshell/cp/vcenter/common/utilites/common_name.py | generate_unique_name | def generate_unique_name(name_prefix, reservation_id=None):
"""
Generate a unique name.
Method generate a guid and adds the first 8 characteres of the new guid to 'name_prefix'.
If reservation id is provided than the first 4 chars of the generated guid are taken and the last 4
of the reservation id
"""
if reservation_id and isinstance(reservation_id, str) and len(reservation_id) >= 4:
unique_id = str(uuid.uuid4())[:4] + "-" + reservation_id[-4:]
else:
unique_id = str(uuid.uuid4())[:8]
return name_prefix + "_" + unique_id | python | def generate_unique_name(name_prefix, reservation_id=None):
"""
Generate a unique name.
Method generate a guid and adds the first 8 characteres of the new guid to 'name_prefix'.
If reservation id is provided than the first 4 chars of the generated guid are taken and the last 4
of the reservation id
"""
if reservation_id and isinstance(reservation_id, str) and len(reservation_id) >= 4:
unique_id = str(uuid.uuid4())[:4] + "-" + reservation_id[-4:]
else:
unique_id = str(uuid.uuid4())[:8]
return name_prefix + "_" + unique_id | [
"def",
"generate_unique_name",
"(",
"name_prefix",
",",
"reservation_id",
"=",
"None",
")",
":",
"if",
"reservation_id",
"and",
"isinstance",
"(",
"reservation_id",
",",
"str",
")",
"and",
"len",
"(",
"reservation_id",
")",
">=",
"4",
":",
"unique_id",
"=",
... | Generate a unique name.
Method generate a guid and adds the first 8 characteres of the new guid to 'name_prefix'.
If reservation id is provided than the first 4 chars of the generated guid are taken and the last 4
of the reservation id | [
"Generate",
"a",
"unique",
"name",
".",
"Method",
"generate",
"a",
"guid",
"and",
"adds",
"the",
"first",
"8",
"characteres",
"of",
"the",
"new",
"guid",
"to",
"name_prefix",
".",
"If",
"reservation",
"id",
"is",
"provided",
"than",
"the",
"first",
"4",
... | e2e24cd938a92a68f4a8e6a860810d3ef72aae6d | https://github.com/QualiSystems/vCenterShell/blob/e2e24cd938a92a68f4a8e6a860810d3ef72aae6d/package/cloudshell/cp/vcenter/common/utilites/common_name.py#L6-L17 | train | 42,677 |
QualiSystems/vCenterShell | package/cloudshell/cp/vcenter/commands/disconnect_dvswitch.py | VirtualSwitchToMachineDisconnectCommand.remove_interfaces_from_vm_task | def remove_interfaces_from_vm_task(self, virtual_machine, filter_function=None):
"""
Remove interface from VM
@see https://www.vmware.com/support/developer/vc-sdk/visdk41pubs/ApiReference/vim.VirtualMachine.html#reconfigure
:param virtual_machine: <vim.vm object>
:param filter_function: function that gets the device and decide if it should be deleted
:return: Task or None
"""
device_change = []
for device in virtual_machine.config.hardware.device:
if isinstance(device, vim.vm.device.VirtualEthernetCard) and \
(filter_function is None or filter_function(device)):
nicspec = vim.vm.device.VirtualDeviceSpec()
nicspec.operation = vim.vm.device.VirtualDeviceSpec.Operation.remove
nicspec.device = device
device_change.append(nicspec)
if len(device_change) > 0:
return self.pyvmomi_service.vm_reconfig_task(virtual_machine, device_change)
return None | python | def remove_interfaces_from_vm_task(self, virtual_machine, filter_function=None):
"""
Remove interface from VM
@see https://www.vmware.com/support/developer/vc-sdk/visdk41pubs/ApiReference/vim.VirtualMachine.html#reconfigure
:param virtual_machine: <vim.vm object>
:param filter_function: function that gets the device and decide if it should be deleted
:return: Task or None
"""
device_change = []
for device in virtual_machine.config.hardware.device:
if isinstance(device, vim.vm.device.VirtualEthernetCard) and \
(filter_function is None or filter_function(device)):
nicspec = vim.vm.device.VirtualDeviceSpec()
nicspec.operation = vim.vm.device.VirtualDeviceSpec.Operation.remove
nicspec.device = device
device_change.append(nicspec)
if len(device_change) > 0:
return self.pyvmomi_service.vm_reconfig_task(virtual_machine, device_change)
return None | [
"def",
"remove_interfaces_from_vm_task",
"(",
"self",
",",
"virtual_machine",
",",
"filter_function",
"=",
"None",
")",
":",
"device_change",
"=",
"[",
"]",
"for",
"device",
"in",
"virtual_machine",
".",
"config",
".",
"hardware",
".",
"device",
":",
"if",
"is... | Remove interface from VM
@see https://www.vmware.com/support/developer/vc-sdk/visdk41pubs/ApiReference/vim.VirtualMachine.html#reconfigure
:param virtual_machine: <vim.vm object>
:param filter_function: function that gets the device and decide if it should be deleted
:return: Task or None | [
"Remove",
"interface",
"from",
"VM"
] | e2e24cd938a92a68f4a8e6a860810d3ef72aae6d | https://github.com/QualiSystems/vCenterShell/blob/e2e24cd938a92a68f4a8e6a860810d3ef72aae6d/package/cloudshell/cp/vcenter/commands/disconnect_dvswitch.py#L101-L120 | train | 42,678 |
QualiSystems/vCenterShell | package/cloudshell/cp/vcenter/commands/refresh_ip.py | RefreshIpCommand.refresh_ip | def refresh_ip(self, si, logger, session, vcenter_data_model, resource_model, cancellation_context,
app_request_json):
"""
Refreshes IP address of virtual machine and updates Address property on the resource
:param vim.ServiceInstance si: py_vmomi service instance
:param logger:
:param vCenterShell.driver.SecureCloudShellApiSession session: cloudshell session
:param GenericDeployedAppResourceModel resource_model: UUID of Virtual Machine
:param VMwarevCenterResourceModel vcenter_data_model: the vcenter data model attributes
:param cancellation_context:
"""
self._do_not_run_on_static_vm(app_request_json=app_request_json)
default_network = VMLocation.combine(
[vcenter_data_model.default_datacenter, vcenter_data_model.holding_network])
match_function = self.ip_manager.get_ip_match_function(
self._get_ip_refresh_ip_regex(resource_model.vm_custom_params))
timeout = self._get_ip_refresh_timeout(resource_model.vm_custom_params)
vm = self.pyvmomi_service.find_by_uuid(si, resource_model.vm_uuid)
ip_res = self.ip_manager.get_ip(vm, default_network, match_function, cancellation_context, timeout, logger)
if ip_res.reason == IpReason.Timeout:
raise ValueError('IP address of VM \'{0}\' could not be obtained during {1} seconds'
.format(resource_model.fullname, timeout))
if ip_res.reason == IpReason.Success:
self._update_resource_address_with_retry(session=session,
resource_name=resource_model.fullname,
ip_address=ip_res.ip_address)
return ip_res.ip_address | python | def refresh_ip(self, si, logger, session, vcenter_data_model, resource_model, cancellation_context,
app_request_json):
"""
Refreshes IP address of virtual machine and updates Address property on the resource
:param vim.ServiceInstance si: py_vmomi service instance
:param logger:
:param vCenterShell.driver.SecureCloudShellApiSession session: cloudshell session
:param GenericDeployedAppResourceModel resource_model: UUID of Virtual Machine
:param VMwarevCenterResourceModel vcenter_data_model: the vcenter data model attributes
:param cancellation_context:
"""
self._do_not_run_on_static_vm(app_request_json=app_request_json)
default_network = VMLocation.combine(
[vcenter_data_model.default_datacenter, vcenter_data_model.holding_network])
match_function = self.ip_manager.get_ip_match_function(
self._get_ip_refresh_ip_regex(resource_model.vm_custom_params))
timeout = self._get_ip_refresh_timeout(resource_model.vm_custom_params)
vm = self.pyvmomi_service.find_by_uuid(si, resource_model.vm_uuid)
ip_res = self.ip_manager.get_ip(vm, default_network, match_function, cancellation_context, timeout, logger)
if ip_res.reason == IpReason.Timeout:
raise ValueError('IP address of VM \'{0}\' could not be obtained during {1} seconds'
.format(resource_model.fullname, timeout))
if ip_res.reason == IpReason.Success:
self._update_resource_address_with_retry(session=session,
resource_name=resource_model.fullname,
ip_address=ip_res.ip_address)
return ip_res.ip_address | [
"def",
"refresh_ip",
"(",
"self",
",",
"si",
",",
"logger",
",",
"session",
",",
"vcenter_data_model",
",",
"resource_model",
",",
"cancellation_context",
",",
"app_request_json",
")",
":",
"self",
".",
"_do_not_run_on_static_vm",
"(",
"app_request_json",
"=",
"ap... | Refreshes IP address of virtual machine and updates Address property on the resource
:param vim.ServiceInstance si: py_vmomi service instance
:param logger:
:param vCenterShell.driver.SecureCloudShellApiSession session: cloudshell session
:param GenericDeployedAppResourceModel resource_model: UUID of Virtual Machine
:param VMwarevCenterResourceModel vcenter_data_model: the vcenter data model attributes
:param cancellation_context: | [
"Refreshes",
"IP",
"address",
"of",
"virtual",
"machine",
"and",
"updates",
"Address",
"property",
"on",
"the",
"resource"
] | e2e24cd938a92a68f4a8e6a860810d3ef72aae6d | https://github.com/QualiSystems/vCenterShell/blob/e2e24cd938a92a68f4a8e6a860810d3ef72aae6d/package/cloudshell/cp/vcenter/commands/refresh_ip.py#L25-L60 | train | 42,679 |
QualiSystems/vCenterShell | package/cloudshell/cp/vcenter/common/cloud_shell/conn_details_retriever.py | ResourceConnectionDetailsRetriever.get_connection_details | def get_connection_details(session, vcenter_resource_model, resource_context):
"""
Methods retrieves the connection details from the vcenter resource model attributes.
:param CloudShellAPISession session:
:param VMwarevCenterResourceModel vcenter_resource_model: Instance of VMwarevCenterResourceModel
:param ResourceContextDetails resource_context: the context of the command
"""
session = session
resource_context = resource_context
# get vCenter connection details from vCenter resource
user = vcenter_resource_model.user
vcenter_url = resource_context.address
password = session.DecryptPassword(vcenter_resource_model.password).Value
return VCenterConnectionDetails(vcenter_url, user, password) | python | def get_connection_details(session, vcenter_resource_model, resource_context):
"""
Methods retrieves the connection details from the vcenter resource model attributes.
:param CloudShellAPISession session:
:param VMwarevCenterResourceModel vcenter_resource_model: Instance of VMwarevCenterResourceModel
:param ResourceContextDetails resource_context: the context of the command
"""
session = session
resource_context = resource_context
# get vCenter connection details from vCenter resource
user = vcenter_resource_model.user
vcenter_url = resource_context.address
password = session.DecryptPassword(vcenter_resource_model.password).Value
return VCenterConnectionDetails(vcenter_url, user, password) | [
"def",
"get_connection_details",
"(",
"session",
",",
"vcenter_resource_model",
",",
"resource_context",
")",
":",
"session",
"=",
"session",
"resource_context",
"=",
"resource_context",
"# get vCenter connection details from vCenter resource",
"user",
"=",
"vcenter_resource_mo... | Methods retrieves the connection details from the vcenter resource model attributes.
:param CloudShellAPISession session:
:param VMwarevCenterResourceModel vcenter_resource_model: Instance of VMwarevCenterResourceModel
:param ResourceContextDetails resource_context: the context of the command | [
"Methods",
"retrieves",
"the",
"connection",
"details",
"from",
"the",
"vcenter",
"resource",
"model",
"attributes",
"."
] | e2e24cd938a92a68f4a8e6a860810d3ef72aae6d | https://github.com/QualiSystems/vCenterShell/blob/e2e24cd938a92a68f4a8e6a860810d3ef72aae6d/package/cloudshell/cp/vcenter/common/cloud_shell/conn_details_retriever.py#L7-L24 | train | 42,680 |
QualiSystems/vCenterShell | package/cloudshell/cp/vcenter/vm/deploy.py | VirtualMachineDeployer.deploy_from_linked_clone | def deploy_from_linked_clone(self, si, logger, data_holder, vcenter_data_model, reservation_id,
cancellation_context):
"""
deploy Cloned VM From VM Command, will deploy vm from a snapshot
:param cancellation_context:
:param si:
:param logger:
:param data_holder:
:param vcenter_data_model:
:param str reservation_id:
:rtype DeployAppResult:
:return:
"""
template_resource_model = data_holder.template_resource_model
return self._deploy_a_clone(si=si,
logger=logger,
app_name=data_holder.app_name,
template_name=template_resource_model.vcenter_vm,
other_params=template_resource_model,
vcenter_data_model=vcenter_data_model,
reservation_id=reservation_id,
cancellation_context=cancellation_context,
snapshot=template_resource_model.vcenter_vm_snapshot) | python | def deploy_from_linked_clone(self, si, logger, data_holder, vcenter_data_model, reservation_id,
cancellation_context):
"""
deploy Cloned VM From VM Command, will deploy vm from a snapshot
:param cancellation_context:
:param si:
:param logger:
:param data_holder:
:param vcenter_data_model:
:param str reservation_id:
:rtype DeployAppResult:
:return:
"""
template_resource_model = data_holder.template_resource_model
return self._deploy_a_clone(si=si,
logger=logger,
app_name=data_holder.app_name,
template_name=template_resource_model.vcenter_vm,
other_params=template_resource_model,
vcenter_data_model=vcenter_data_model,
reservation_id=reservation_id,
cancellation_context=cancellation_context,
snapshot=template_resource_model.vcenter_vm_snapshot) | [
"def",
"deploy_from_linked_clone",
"(",
"self",
",",
"si",
",",
"logger",
",",
"data_holder",
",",
"vcenter_data_model",
",",
"reservation_id",
",",
"cancellation_context",
")",
":",
"template_resource_model",
"=",
"data_holder",
".",
"template_resource_model",
"return"... | deploy Cloned VM From VM Command, will deploy vm from a snapshot
:param cancellation_context:
:param si:
:param logger:
:param data_holder:
:param vcenter_data_model:
:param str reservation_id:
:rtype DeployAppResult:
:return: | [
"deploy",
"Cloned",
"VM",
"From",
"VM",
"Command",
"will",
"deploy",
"vm",
"from",
"a",
"snapshot"
] | e2e24cd938a92a68f4a8e6a860810d3ef72aae6d | https://github.com/QualiSystems/vCenterShell/blob/e2e24cd938a92a68f4a8e6a860810d3ef72aae6d/package/cloudshell/cp/vcenter/vm/deploy.py#L38-L63 | train | 42,681 |
QualiSystems/vCenterShell | package/cloudshell/cp/vcenter/vm/deploy.py | VirtualMachineDeployer.deploy_clone_from_vm | def deploy_clone_from_vm(self, si, logger, data_holder, vcenter_data_model, reservation_id, cancellation_context):
"""
deploy Cloned VM From VM Command, will deploy vm from another vm
:param cancellation_context:
:param reservation_id:
:param si:
:param logger:
:type data_holder:
:type vcenter_data_model:
:rtype DeployAppResult:
:return:
"""
template_resource_model = data_holder.template_resource_model
return self._deploy_a_clone(si,
logger,
data_holder.app_name,
template_resource_model.vcenter_vm,
template_resource_model,
vcenter_data_model,
reservation_id,
cancellation_context) | python | def deploy_clone_from_vm(self, si, logger, data_holder, vcenter_data_model, reservation_id, cancellation_context):
"""
deploy Cloned VM From VM Command, will deploy vm from another vm
:param cancellation_context:
:param reservation_id:
:param si:
:param logger:
:type data_holder:
:type vcenter_data_model:
:rtype DeployAppResult:
:return:
"""
template_resource_model = data_holder.template_resource_model
return self._deploy_a_clone(si,
logger,
data_holder.app_name,
template_resource_model.vcenter_vm,
template_resource_model,
vcenter_data_model,
reservation_id,
cancellation_context) | [
"def",
"deploy_clone_from_vm",
"(",
"self",
",",
"si",
",",
"logger",
",",
"data_holder",
",",
"vcenter_data_model",
",",
"reservation_id",
",",
"cancellation_context",
")",
":",
"template_resource_model",
"=",
"data_holder",
".",
"template_resource_model",
"return",
... | deploy Cloned VM From VM Command, will deploy vm from another vm
:param cancellation_context:
:param reservation_id:
:param si:
:param logger:
:type data_holder:
:type vcenter_data_model:
:rtype DeployAppResult:
:return: | [
"deploy",
"Cloned",
"VM",
"From",
"VM",
"Command",
"will",
"deploy",
"vm",
"from",
"another",
"vm"
] | e2e24cd938a92a68f4a8e6a860810d3ef72aae6d | https://github.com/QualiSystems/vCenterShell/blob/e2e24cd938a92a68f4a8e6a860810d3ef72aae6d/package/cloudshell/cp/vcenter/vm/deploy.py#L65-L86 | train | 42,682 |
NASA-AMMOS/AIT-Core | ait/core/util.py | crc32File | def crc32File(filename, skip=0):
"""Computes the CRC-32 of the contents of filename, optionally
skipping a certain number of bytes at the beginning of the file.
"""
with open(filename, 'rb') as stream:
discard = stream.read(skip)
return zlib.crc32(stream.read()) & 0xffffffff | python | def crc32File(filename, skip=0):
"""Computes the CRC-32 of the contents of filename, optionally
skipping a certain number of bytes at the beginning of the file.
"""
with open(filename, 'rb') as stream:
discard = stream.read(skip)
return zlib.crc32(stream.read()) & 0xffffffff | [
"def",
"crc32File",
"(",
"filename",
",",
"skip",
"=",
"0",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"stream",
":",
"discard",
"=",
"stream",
".",
"read",
"(",
"skip",
")",
"return",
"zlib",
".",
"crc32",
"(",
"stream",
".... | Computes the CRC-32 of the contents of filename, optionally
skipping a certain number of bytes at the beginning of the file. | [
"Computes",
"the",
"CRC",
"-",
"32",
"of",
"the",
"contents",
"of",
"filename",
"optionally",
"skipping",
"a",
"certain",
"number",
"of",
"bytes",
"at",
"the",
"beginning",
"of",
"the",
"file",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/util.py#L197-L203 | train | 42,683 |
NASA-AMMOS/AIT-Core | ait/core/util.py | getDefaultDict | def getDefaultDict(modname, config_key, loader, reload=False, filename=None):
"""Returns default AIT dictonary for modname
This helper function encapulates the core logic necessary to
(re)load, cache (via util.ObjectCache), and return the default
dictionary. For example, in ait.core.cmd:
def getDefaultDict(reload=False):
return ait.util.getDefaultDict(__name__, 'cmddict', CmdDict, reload)
"""
module = sys.modules[modname]
default = getattr(module, 'DefaultDict', None)
if filename is None:
filename = ait.config.get('%s.filename' % config_key, None)
if filename is not None and (default is None or reload is True):
try:
default = ObjectCache(filename, loader).load()
setattr(module, 'DefaultDict', default)
except IOError, e:
msg = 'Could not load default %s "%s": %s'
log.error(msg, config_key, filename, str(e))
return default or loader() | python | def getDefaultDict(modname, config_key, loader, reload=False, filename=None):
"""Returns default AIT dictonary for modname
This helper function encapulates the core logic necessary to
(re)load, cache (via util.ObjectCache), and return the default
dictionary. For example, in ait.core.cmd:
def getDefaultDict(reload=False):
return ait.util.getDefaultDict(__name__, 'cmddict', CmdDict, reload)
"""
module = sys.modules[modname]
default = getattr(module, 'DefaultDict', None)
if filename is None:
filename = ait.config.get('%s.filename' % config_key, None)
if filename is not None and (default is None or reload is True):
try:
default = ObjectCache(filename, loader).load()
setattr(module, 'DefaultDict', default)
except IOError, e:
msg = 'Could not load default %s "%s": %s'
log.error(msg, config_key, filename, str(e))
return default or loader() | [
"def",
"getDefaultDict",
"(",
"modname",
",",
"config_key",
",",
"loader",
",",
"reload",
"=",
"False",
",",
"filename",
"=",
"None",
")",
":",
"module",
"=",
"sys",
".",
"modules",
"[",
"modname",
"]",
"default",
"=",
"getattr",
"(",
"module",
",",
"'... | Returns default AIT dictonary for modname
This helper function encapulates the core logic necessary to
(re)load, cache (via util.ObjectCache), and return the default
dictionary. For example, in ait.core.cmd:
def getDefaultDict(reload=False):
return ait.util.getDefaultDict(__name__, 'cmddict', CmdDict, reload) | [
"Returns",
"default",
"AIT",
"dictonary",
"for",
"modname"
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/util.py#L226-L250 | train | 42,684 |
NASA-AMMOS/AIT-Core | ait/core/util.py | toBCD | def toBCD (n):
"""Converts the number n into Binary Coded Decimal."""
bcd = 0
bits = 0
while True:
n, r = divmod(n, 10)
bcd |= (r << bits)
if n is 0:
break
bits += 4
return bcd | python | def toBCD (n):
"""Converts the number n into Binary Coded Decimal."""
bcd = 0
bits = 0
while True:
n, r = divmod(n, 10)
bcd |= (r << bits)
if n is 0:
break
bits += 4
return bcd | [
"def",
"toBCD",
"(",
"n",
")",
":",
"bcd",
"=",
"0",
"bits",
"=",
"0",
"while",
"True",
":",
"n",
",",
"r",
"=",
"divmod",
"(",
"n",
",",
"10",
")",
"bcd",
"|=",
"(",
"r",
"<<",
"bits",
")",
"if",
"n",
"is",
"0",
":",
"break",
"bits",
"+=... | Converts the number n into Binary Coded Decimal. | [
"Converts",
"the",
"number",
"n",
"into",
"Binary",
"Coded",
"Decimal",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/util.py#L258-L271 | train | 42,685 |
NASA-AMMOS/AIT-Core | ait/core/util.py | listAllFiles | def listAllFiles (directory, suffix=None, abspath=False):
"""Returns the list of all files within the input directory and
all subdirectories.
"""
files = []
directory = expandPath(directory)
for dirpath, dirnames, filenames in os.walk(directory, followlinks=True):
if suffix:
filenames = [f for f in filenames if f.endswith(suffix)]
for filename in filenames:
filepath = os.path.join(dirpath, filename)
if not abspath:
filepath = os.path.relpath(filepath, start=directory)
# os.path.join(path, filename)
files.append(filepath)
return files | python | def listAllFiles (directory, suffix=None, abspath=False):
"""Returns the list of all files within the input directory and
all subdirectories.
"""
files = []
directory = expandPath(directory)
for dirpath, dirnames, filenames in os.walk(directory, followlinks=True):
if suffix:
filenames = [f for f in filenames if f.endswith(suffix)]
for filename in filenames:
filepath = os.path.join(dirpath, filename)
if not abspath:
filepath = os.path.relpath(filepath, start=directory)
# os.path.join(path, filename)
files.append(filepath)
return files | [
"def",
"listAllFiles",
"(",
"directory",
",",
"suffix",
"=",
"None",
",",
"abspath",
"=",
"False",
")",
":",
"files",
"=",
"[",
"]",
"directory",
"=",
"expandPath",
"(",
"directory",
")",
"for",
"dirpath",
",",
"dirnames",
",",
"filenames",
"in",
"os",
... | Returns the list of all files within the input directory and
all subdirectories. | [
"Returns",
"the",
"list",
"of",
"all",
"files",
"within",
"the",
"input",
"directory",
"and",
"all",
"subdirectories",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/util.py#L414-L435 | train | 42,686 |
NASA-AMMOS/AIT-Core | ait/core/util.py | ObjectCache.dirty | def dirty(self):
"""True if the cache needs to be updated, False otherwise"""
return not os.path.exists(self.cachename) or \
(os.path.getmtime(self.filename) >
os.path.getmtime(self.cachename)) | python | def dirty(self):
"""True if the cache needs to be updated, False otherwise"""
return not os.path.exists(self.cachename) or \
(os.path.getmtime(self.filename) >
os.path.getmtime(self.cachename)) | [
"def",
"dirty",
"(",
"self",
")",
":",
"return",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"cachename",
")",
"or",
"(",
"os",
".",
"path",
".",
"getmtime",
"(",
"self",
".",
"filename",
")",
">",
"os",
".",
"path",
".",
"getmtime... | True if the cache needs to be updated, False otherwise | [
"True",
"if",
"the",
"cache",
"needs",
"to",
"be",
"updated",
"False",
"otherwise"
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/util.py#L64-L68 | train | 42,687 |
NASA-AMMOS/AIT-Core | ait/core/util.py | ObjectCache.load | def load(self):
"""Loads the Python object
Loads the Python object, either via loader(filename) or the
pickled cache file, whichever was modified most recently.
"""
if self._dict is None:
if self.dirty:
self._dict = self._loader(self.filename)
self.cache()
else:
with open(self.cachename, 'rb') as stream:
self._dict = cPickle.load(stream)
return self._dict | python | def load(self):
"""Loads the Python object
Loads the Python object, either via loader(filename) or the
pickled cache file, whichever was modified most recently.
"""
if self._dict is None:
if self.dirty:
self._dict = self._loader(self.filename)
self.cache()
else:
with open(self.cachename, 'rb') as stream:
self._dict = cPickle.load(stream)
return self._dict | [
"def",
"load",
"(",
"self",
")",
":",
"if",
"self",
".",
"_dict",
"is",
"None",
":",
"if",
"self",
".",
"dirty",
":",
"self",
".",
"_dict",
"=",
"self",
".",
"_loader",
"(",
"self",
".",
"filename",
")",
"self",
".",
"cache",
"(",
")",
"else",
... | Loads the Python object
Loads the Python object, either via loader(filename) or the
pickled cache file, whichever was modified most recently. | [
"Loads",
"the",
"Python",
"object"
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/util.py#L85-L99 | train | 42,688 |
NASA-AMMOS/AIT-Core | ait/core/server/plugin.py | DataArchive.process | def process(self, input_data, topic=None, **kwargs):
"""
Splits tuple received from PacketHandler into packet UID and packet message.
Decodes packet and inserts into database backend.
Logs any exceptions raised.
Params:
input_data: message received from inbound stream through PacketHandler
topic: name of inbound stream message received from
**kwargs: any args required for connected to the backend
"""
try:
split = input_data[1:-1].split(',', 1)
uid, pkt = int(split[0]), split[1]
defn = self.packet_dict[uid]
decoded = tlm.Packet(defn, data=bytearray(pkt))
self.dbconn.insert(decoded, **kwargs)
except Exception as e:
log.error('Data archival failed with error: {}.'.format(e)) | python | def process(self, input_data, topic=None, **kwargs):
"""
Splits tuple received from PacketHandler into packet UID and packet message.
Decodes packet and inserts into database backend.
Logs any exceptions raised.
Params:
input_data: message received from inbound stream through PacketHandler
topic: name of inbound stream message received from
**kwargs: any args required for connected to the backend
"""
try:
split = input_data[1:-1].split(',', 1)
uid, pkt = int(split[0]), split[1]
defn = self.packet_dict[uid]
decoded = tlm.Packet(defn, data=bytearray(pkt))
self.dbconn.insert(decoded, **kwargs)
except Exception as e:
log.error('Data archival failed with error: {}.'.format(e)) | [
"def",
"process",
"(",
"self",
",",
"input_data",
",",
"topic",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"split",
"=",
"input_data",
"[",
"1",
":",
"-",
"1",
"]",
".",
"split",
"(",
"','",
",",
"1",
")",
"uid",
",",
"pkt",
... | Splits tuple received from PacketHandler into packet UID and packet message.
Decodes packet and inserts into database backend.
Logs any exceptions raised.
Params:
input_data: message received from inbound stream through PacketHandler
topic: name of inbound stream message received from
**kwargs: any args required for connected to the backend | [
"Splits",
"tuple",
"received",
"from",
"PacketHandler",
"into",
"packet",
"UID",
"and",
"packet",
"message",
".",
"Decodes",
"packet",
"and",
"inserts",
"into",
"database",
"backend",
".",
"Logs",
"any",
"exceptions",
"raised",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/server/plugin.py#L102-L120 | train | 42,689 |
NASA-AMMOS/AIT-Core | ait/core/dmc.py | getUTCDatetimeDOY | def getUTCDatetimeDOY(days=0, hours=0, minutes=0, seconds=0):
"""getUTCDatetimeDOY -> datetime
Returns the UTC current datetime with the input timedelta arguments (days, hours, minutes, seconds)
added to current date. Returns ISO-8601 datetime format for day of year:
YYYY-DDDTHH:mm:ssZ
"""
return (datetime.datetime.utcnow() +
datetime.timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)).strftime(DOY_Format) | python | def getUTCDatetimeDOY(days=0, hours=0, minutes=0, seconds=0):
"""getUTCDatetimeDOY -> datetime
Returns the UTC current datetime with the input timedelta arguments (days, hours, minutes, seconds)
added to current date. Returns ISO-8601 datetime format for day of year:
YYYY-DDDTHH:mm:ssZ
"""
return (datetime.datetime.utcnow() +
datetime.timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)).strftime(DOY_Format) | [
"def",
"getUTCDatetimeDOY",
"(",
"days",
"=",
"0",
",",
"hours",
"=",
"0",
",",
"minutes",
"=",
"0",
",",
"seconds",
"=",
"0",
")",
":",
"return",
"(",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"+",
"datetime",
".",
"timedelta",
"(",
"d... | getUTCDatetimeDOY -> datetime
Returns the UTC current datetime with the input timedelta arguments (days, hours, minutes, seconds)
added to current date. Returns ISO-8601 datetime format for day of year:
YYYY-DDDTHH:mm:ssZ | [
"getUTCDatetimeDOY",
"-",
">",
"datetime"
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/dmc.py#L59-L69 | train | 42,690 |
NASA-AMMOS/AIT-Core | ait/core/dmc.py | UTCLeapSeconds._update_leap_second_data | def _update_leap_second_data(self):
""" Updates the systems leap second information
Pulls the latest leap second information from
https://www.ietf.org/timezones/data/leap-seconds.list
and updates the leapsecond config file.
Raises:
ValueError: If the connection to IETF does not return 200
IOError: If the path to the leap seconds file is not valid
"""
log.info('Attempting to acquire latest leapsecond data')
ls_file = ait.config.get(
'leapseconds.filename',
os.path.join(ait.config._directory, _DEFAULT_FILE_NAME)
)
url = 'https://www.ietf.org/timezones/data/leap-seconds.list'
r = requests.get(url)
if r.status_code != 200:
msg = 'Unable to locate latest timezone data. Connection to IETF failed'
log.error(msg)
raise ValueError(msg)
text = r.text.split('\n')
lines = [l for l in text if l.startswith('#@') or not l.startswith('#')]
data = {'valid': None, 'leapseconds': []}
data['valid'] = datetime.datetime(1900, 1, 1) + datetime.timedelta(seconds=int(lines[0].split('\t')[1]))
leap = 1
for l in lines[1:-1]:
t = datetime.datetime(1900, 1, 1) + datetime.timedelta(seconds=int(l.split('\t')[0]))
if t < GPS_Epoch:
continue
data['leapseconds'].append((t, leap))
leap += 1
self._data = data
with open(ls_file, 'w') as outfile:
pickle.dump(data, outfile) | python | def _update_leap_second_data(self):
""" Updates the systems leap second information
Pulls the latest leap second information from
https://www.ietf.org/timezones/data/leap-seconds.list
and updates the leapsecond config file.
Raises:
ValueError: If the connection to IETF does not return 200
IOError: If the path to the leap seconds file is not valid
"""
log.info('Attempting to acquire latest leapsecond data')
ls_file = ait.config.get(
'leapseconds.filename',
os.path.join(ait.config._directory, _DEFAULT_FILE_NAME)
)
url = 'https://www.ietf.org/timezones/data/leap-seconds.list'
r = requests.get(url)
if r.status_code != 200:
msg = 'Unable to locate latest timezone data. Connection to IETF failed'
log.error(msg)
raise ValueError(msg)
text = r.text.split('\n')
lines = [l for l in text if l.startswith('#@') or not l.startswith('#')]
data = {'valid': None, 'leapseconds': []}
data['valid'] = datetime.datetime(1900, 1, 1) + datetime.timedelta(seconds=int(lines[0].split('\t')[1]))
leap = 1
for l in lines[1:-1]:
t = datetime.datetime(1900, 1, 1) + datetime.timedelta(seconds=int(l.split('\t')[0]))
if t < GPS_Epoch:
continue
data['leapseconds'].append((t, leap))
leap += 1
self._data = data
with open(ls_file, 'w') as outfile:
pickle.dump(data, outfile) | [
"def",
"_update_leap_second_data",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"'Attempting to acquire latest leapsecond data'",
")",
"ls_file",
"=",
"ait",
".",
"config",
".",
"get",
"(",
"'leapseconds.filename'",
",",
"os",
".",
"path",
".",
"join",
"(",
... | Updates the systems leap second information
Pulls the latest leap second information from
https://www.ietf.org/timezones/data/leap-seconds.list
and updates the leapsecond config file.
Raises:
ValueError: If the connection to IETF does not return 200
IOError: If the path to the leap seconds file is not valid | [
"Updates",
"the",
"systems",
"leap",
"second",
"information"
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/dmc.py#L307-L351 | train | 42,691 |
NASA-AMMOS/AIT-Core | ait/core/server/server.py | Server.wait | def wait(self):
"""
Starts all greenlets for concurrent processing.
Joins over all greenlets that are not servers.
"""
for greenlet in (self.greenlets + self.servers):
log.info("Starting {} greenlet...".format(greenlet))
greenlet.start()
gevent.joinall(self.greenlets) | python | def wait(self):
"""
Starts all greenlets for concurrent processing.
Joins over all greenlets that are not servers.
"""
for greenlet in (self.greenlets + self.servers):
log.info("Starting {} greenlet...".format(greenlet))
greenlet.start()
gevent.joinall(self.greenlets) | [
"def",
"wait",
"(",
"self",
")",
":",
"for",
"greenlet",
"in",
"(",
"self",
".",
"greenlets",
"+",
"self",
".",
"servers",
")",
":",
"log",
".",
"info",
"(",
"\"Starting {} greenlet...\"",
".",
"format",
"(",
"greenlet",
")",
")",
"greenlet",
".",
"sta... | Starts all greenlets for concurrent processing.
Joins over all greenlets that are not servers. | [
"Starts",
"all",
"greenlets",
"for",
"concurrent",
"processing",
".",
"Joins",
"over",
"all",
"greenlets",
"that",
"are",
"not",
"servers",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/server/server.py#L41-L50 | train | 42,692 |
NASA-AMMOS/AIT-Core | ait/core/server/server.py | Server._load_streams | def _load_streams(self):
"""
Reads, parses and creates streams specified in config.yaml.
"""
common_err_msg = 'No valid {} stream configurations found. '
specific_err_msg = {'inbound': 'No data will be received (or displayed).',
'outbound': 'No data will be published.'}
err_msgs = {}
for stream_type in ['inbound', 'outbound']:
err_msgs[stream_type] = common_err_msg.format(stream_type) + specific_err_msg[stream_type]
streams = ait.config.get('server.{}-streams'.format(stream_type))
if streams is None:
log.warn(err_msgs[stream_type])
else:
for index, s in enumerate(streams):
try:
if stream_type == 'inbound':
strm = self._create_inbound_stream(s['stream'])
if type(strm) == PortInputStream:
self.servers.append(strm)
else:
self.inbound_streams.append(strm)
elif stream_type == 'outbound':
strm = self._create_outbound_stream(s['stream'])
self.outbound_streams.append(strm)
log.info('Added {} stream {}'.format(stream_type, strm))
except Exception:
exc_type, value, tb = sys.exc_info()
log.error('{} creating {} stream {}: {}'.format(exc_type,
stream_type,
index,
value))
if not self.inbound_streams and not self.servers:
log.warn(err_msgs['inbound'])
if not self.outbound_streams:
log.warn(err_msgs['outbound']) | python | def _load_streams(self):
"""
Reads, parses and creates streams specified in config.yaml.
"""
common_err_msg = 'No valid {} stream configurations found. '
specific_err_msg = {'inbound': 'No data will be received (or displayed).',
'outbound': 'No data will be published.'}
err_msgs = {}
for stream_type in ['inbound', 'outbound']:
err_msgs[stream_type] = common_err_msg.format(stream_type) + specific_err_msg[stream_type]
streams = ait.config.get('server.{}-streams'.format(stream_type))
if streams is None:
log.warn(err_msgs[stream_type])
else:
for index, s in enumerate(streams):
try:
if stream_type == 'inbound':
strm = self._create_inbound_stream(s['stream'])
if type(strm) == PortInputStream:
self.servers.append(strm)
else:
self.inbound_streams.append(strm)
elif stream_type == 'outbound':
strm = self._create_outbound_stream(s['stream'])
self.outbound_streams.append(strm)
log.info('Added {} stream {}'.format(stream_type, strm))
except Exception:
exc_type, value, tb = sys.exc_info()
log.error('{} creating {} stream {}: {}'.format(exc_type,
stream_type,
index,
value))
if not self.inbound_streams and not self.servers:
log.warn(err_msgs['inbound'])
if not self.outbound_streams:
log.warn(err_msgs['outbound']) | [
"def",
"_load_streams",
"(",
"self",
")",
":",
"common_err_msg",
"=",
"'No valid {} stream configurations found. '",
"specific_err_msg",
"=",
"{",
"'inbound'",
":",
"'No data will be received (or displayed).'",
",",
"'outbound'",
":",
"'No data will be published.'",
"}",
"err... | Reads, parses and creates streams specified in config.yaml. | [
"Reads",
"parses",
"and",
"creates",
"streams",
"specified",
"in",
"config",
".",
"yaml",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/server/server.py#L52-L90 | train | 42,693 |
NASA-AMMOS/AIT-Core | ait/core/server/server.py | Server._create_inbound_stream | def _create_inbound_stream(self, config=None):
"""
Creates an inbound stream from its config.
Params:
config: stream configuration as read by ait.config
Returns:
stream: a Stream
Raises:
ValueError: if any of the required config values are missing
"""
if config is None:
raise ValueError('No stream config to create stream from.')
name = self._get_stream_name(config)
stream_handlers = self._get_stream_handlers(config, name)
stream_input = config.get('input', None)
if stream_input is None:
raise(cfg.AitConfigMissing('inbound stream {}\'s input'.format(name)))
if type(stream_input[0]) is int:
return PortInputStream(name,
stream_input,
stream_handlers,
zmq_args={'zmq_context': self.broker.context,
'zmq_proxy_xsub_url': self.broker.XSUB_URL,
'zmq_proxy_xpub_url': self.broker.XPUB_URL})
else:
return ZMQStream(name,
stream_input,
stream_handlers,
zmq_args={'zmq_context': self.broker.context,
'zmq_proxy_xsub_url': self.broker.XSUB_URL,
'zmq_proxy_xpub_url': self.broker.XPUB_URL}) | python | def _create_inbound_stream(self, config=None):
"""
Creates an inbound stream from its config.
Params:
config: stream configuration as read by ait.config
Returns:
stream: a Stream
Raises:
ValueError: if any of the required config values are missing
"""
if config is None:
raise ValueError('No stream config to create stream from.')
name = self._get_stream_name(config)
stream_handlers = self._get_stream_handlers(config, name)
stream_input = config.get('input', None)
if stream_input is None:
raise(cfg.AitConfigMissing('inbound stream {}\'s input'.format(name)))
if type(stream_input[0]) is int:
return PortInputStream(name,
stream_input,
stream_handlers,
zmq_args={'zmq_context': self.broker.context,
'zmq_proxy_xsub_url': self.broker.XSUB_URL,
'zmq_proxy_xpub_url': self.broker.XPUB_URL})
else:
return ZMQStream(name,
stream_input,
stream_handlers,
zmq_args={'zmq_context': self.broker.context,
'zmq_proxy_xsub_url': self.broker.XSUB_URL,
'zmq_proxy_xpub_url': self.broker.XPUB_URL}) | [
"def",
"_create_inbound_stream",
"(",
"self",
",",
"config",
"=",
"None",
")",
":",
"if",
"config",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'No stream config to create stream from.'",
")",
"name",
"=",
"self",
".",
"_get_stream_name",
"(",
"config",
")",... | Creates an inbound stream from its config.
Params:
config: stream configuration as read by ait.config
Returns:
stream: a Stream
Raises:
ValueError: if any of the required config values are missing | [
"Creates",
"an",
"inbound",
"stream",
"from",
"its",
"config",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/server/server.py#L119-L152 | train | 42,694 |
NASA-AMMOS/AIT-Core | ait/core/server/server.py | Server._create_outbound_stream | def _create_outbound_stream(self, config=None):
"""
Creates an outbound stream from its config.
Params:
config: stream configuration as read by ait.config
Returns:
stream: a Stream
Raises:
ValueError: if any of the required config values are missing
"""
if config is None:
raise ValueError('No stream config to create stream from.')
name = self._get_stream_name(config)
stream_handlers = self._get_stream_handlers(config, name)
stream_input = config.get('input', None)
stream_output = config.get('output', None)
if type(stream_output) is int:
return PortOutputStream(name,
stream_input,
stream_output,
stream_handlers,
zmq_args={'zmq_context': self.broker.context,
'zmq_proxy_xsub_url': self.broker.XSUB_URL,
'zmq_proxy_xpub_url': self.broker.XPUB_URL})
else:
if stream_output is not None:
log.warn("Output of stream {} is not an integer port. "
"Stream outputs can only be ports.".format(name))
return ZMQStream(name,
stream_input,
stream_handlers,
zmq_args={'zmq_context': self.broker.context,
'zmq_proxy_xsub_url': self.broker.XSUB_URL,
'zmq_proxy_xpub_url': self.broker.XPUB_URL}) | python | def _create_outbound_stream(self, config=None):
"""
Creates an outbound stream from its config.
Params:
config: stream configuration as read by ait.config
Returns:
stream: a Stream
Raises:
ValueError: if any of the required config values are missing
"""
if config is None:
raise ValueError('No stream config to create stream from.')
name = self._get_stream_name(config)
stream_handlers = self._get_stream_handlers(config, name)
stream_input = config.get('input', None)
stream_output = config.get('output', None)
if type(stream_output) is int:
return PortOutputStream(name,
stream_input,
stream_output,
stream_handlers,
zmq_args={'zmq_context': self.broker.context,
'zmq_proxy_xsub_url': self.broker.XSUB_URL,
'zmq_proxy_xpub_url': self.broker.XPUB_URL})
else:
if stream_output is not None:
log.warn("Output of stream {} is not an integer port. "
"Stream outputs can only be ports.".format(name))
return ZMQStream(name,
stream_input,
stream_handlers,
zmq_args={'zmq_context': self.broker.context,
'zmq_proxy_xsub_url': self.broker.XSUB_URL,
'zmq_proxy_xpub_url': self.broker.XPUB_URL}) | [
"def",
"_create_outbound_stream",
"(",
"self",
",",
"config",
"=",
"None",
")",
":",
"if",
"config",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'No stream config to create stream from.'",
")",
"name",
"=",
"self",
".",
"_get_stream_name",
"(",
"config",
")"... | Creates an outbound stream from its config.
Params:
config: stream configuration as read by ait.config
Returns:
stream: a Stream
Raises:
ValueError: if any of the required config values are missing | [
"Creates",
"an",
"outbound",
"stream",
"from",
"its",
"config",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/server/server.py#L154-L190 | train | 42,695 |
NASA-AMMOS/AIT-Core | ait/core/server/server.py | Server._create_handler | def _create_handler(self, config):
"""
Creates a handler from its config.
Params:
config: handler config
Returns:
handler instance
"""
if config is None:
raise ValueError('No handler config to create handler from.')
if 'name' not in config:
raise ValueError('Handler name is required.')
handler_name = config['name']
# try to create handler
module_name = handler_name.rsplit('.', 1)[0]
class_name = handler_name.rsplit('.', 1)[-1]
module = import_module(module_name)
handler_class = getattr(module, class_name)
instance = handler_class(**config)
return instance | python | def _create_handler(self, config):
"""
Creates a handler from its config.
Params:
config: handler config
Returns:
handler instance
"""
if config is None:
raise ValueError('No handler config to create handler from.')
if 'name' not in config:
raise ValueError('Handler name is required.')
handler_name = config['name']
# try to create handler
module_name = handler_name.rsplit('.', 1)[0]
class_name = handler_name.rsplit('.', 1)[-1]
module = import_module(module_name)
handler_class = getattr(module, class_name)
instance = handler_class(**config)
return instance | [
"def",
"_create_handler",
"(",
"self",
",",
"config",
")",
":",
"if",
"config",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'No handler config to create handler from.'",
")",
"if",
"'name'",
"not",
"in",
"config",
":",
"raise",
"ValueError",
"(",
"'Handler n... | Creates a handler from its config.
Params:
config: handler config
Returns:
handler instance | [
"Creates",
"a",
"handler",
"from",
"its",
"config",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/server/server.py#L192-L215 | train | 42,696 |
NASA-AMMOS/AIT-Core | ait/core/server/server.py | Server._load_plugins | def _load_plugins(self):
"""
Reads, parses and creates plugins specified in config.yaml.
"""
plugins = ait.config.get('server.plugins')
if plugins is None:
log.warn('No plugins specified in config.')
else:
for index, p in enumerate(plugins):
try:
plugin = self._create_plugin(p['plugin'])
self.plugins.append(plugin)
log.info('Added plugin {}'.format(plugin))
except Exception:
exc_type, value, tb = sys.exc_info()
log.error('{} creating plugin {}: {}'.format(exc_type,
index,
value))
if not self.plugins:
log.warn('No valid plugin configurations found. No plugins will be added.') | python | def _load_plugins(self):
"""
Reads, parses and creates plugins specified in config.yaml.
"""
plugins = ait.config.get('server.plugins')
if plugins is None:
log.warn('No plugins specified in config.')
else:
for index, p in enumerate(plugins):
try:
plugin = self._create_plugin(p['plugin'])
self.plugins.append(plugin)
log.info('Added plugin {}'.format(plugin))
except Exception:
exc_type, value, tb = sys.exc_info()
log.error('{} creating plugin {}: {}'.format(exc_type,
index,
value))
if not self.plugins:
log.warn('No valid plugin configurations found. No plugins will be added.') | [
"def",
"_load_plugins",
"(",
"self",
")",
":",
"plugins",
"=",
"ait",
".",
"config",
".",
"get",
"(",
"'server.plugins'",
")",
"if",
"plugins",
"is",
"None",
":",
"log",
".",
"warn",
"(",
"'No plugins specified in config.'",
")",
"else",
":",
"for",
"index... | Reads, parses and creates plugins specified in config.yaml. | [
"Reads",
"parses",
"and",
"creates",
"plugins",
"specified",
"in",
"config",
".",
"yaml",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/server/server.py#L217-L238 | train | 42,697 |
NASA-AMMOS/AIT-Core | ait/core/server/server.py | Server._create_plugin | def _create_plugin(self, config):
"""
Creates a plugin from its config.
Params:
config: plugin configuration as read by ait.config
Returns:
plugin: a Plugin
Raises:
ValueError: if any of the required config values are missing
"""
if config is None:
raise ValueError('No plugin config to create plugin from.')
name = config.pop('name', None)
if name is None:
raise(cfg.AitConfigMissing('plugin name'))
# TODO I don't think we actually care about this being unique? Left over from
# previous conversations about stuff?
module_name = name.rsplit('.', 1)[0]
class_name = name.rsplit('.', 1)[-1]
if class_name in [x.name for x in (self.outbound_streams +
self.inbound_streams +
self.servers +
self.plugins)]:
raise ValueError(
'Plugin "{}" already loaded. Only one plugin of a given name is allowed'.
format(class_name)
)
plugin_inputs = config.pop('inputs', None)
if plugin_inputs is None:
log.warn('No plugin inputs specified for {}'.format(name))
plugin_inputs = [ ]
subscribers = config.pop('outputs', None)
if subscribers is None:
log.warn('No plugin outputs specified for {}'.format(name))
subscribers = [ ]
# try to create plugin
module = import_module(module_name)
plugin_class = getattr(module, class_name)
instance = plugin_class(plugin_inputs,
subscribers,
zmq_args={'zmq_context': self.broker.context,
'zmq_proxy_xsub_url': self.broker.XSUB_URL,
'zmq_proxy_xpub_url': self.broker.XPUB_URL},
**config
)
return instance | python | def _create_plugin(self, config):
"""
Creates a plugin from its config.
Params:
config: plugin configuration as read by ait.config
Returns:
plugin: a Plugin
Raises:
ValueError: if any of the required config values are missing
"""
if config is None:
raise ValueError('No plugin config to create plugin from.')
name = config.pop('name', None)
if name is None:
raise(cfg.AitConfigMissing('plugin name'))
# TODO I don't think we actually care about this being unique? Left over from
# previous conversations about stuff?
module_name = name.rsplit('.', 1)[0]
class_name = name.rsplit('.', 1)[-1]
if class_name in [x.name for x in (self.outbound_streams +
self.inbound_streams +
self.servers +
self.plugins)]:
raise ValueError(
'Plugin "{}" already loaded. Only one plugin of a given name is allowed'.
format(class_name)
)
plugin_inputs = config.pop('inputs', None)
if plugin_inputs is None:
log.warn('No plugin inputs specified for {}'.format(name))
plugin_inputs = [ ]
subscribers = config.pop('outputs', None)
if subscribers is None:
log.warn('No plugin outputs specified for {}'.format(name))
subscribers = [ ]
# try to create plugin
module = import_module(module_name)
plugin_class = getattr(module, class_name)
instance = plugin_class(plugin_inputs,
subscribers,
zmq_args={'zmq_context': self.broker.context,
'zmq_proxy_xsub_url': self.broker.XSUB_URL,
'zmq_proxy_xpub_url': self.broker.XPUB_URL},
**config
)
return instance | [
"def",
"_create_plugin",
"(",
"self",
",",
"config",
")",
":",
"if",
"config",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'No plugin config to create plugin from.'",
")",
"name",
"=",
"config",
".",
"pop",
"(",
"'name'",
",",
"None",
")",
"if",
"name",
... | Creates a plugin from its config.
Params:
config: plugin configuration as read by ait.config
Returns:
plugin: a Plugin
Raises:
ValueError: if any of the required config values are missing | [
"Creates",
"a",
"plugin",
"from",
"its",
"config",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/server/server.py#L240-L292 | train | 42,698 |
NASA-AMMOS/AIT-Core | ait/core/bin/ait_create_dirs.py | createDirStruct | def createDirStruct(paths, verbose=True):
'''Loops ait.config._datapaths from AIT_CONFIG and creates a directory.
Replaces year and doy with the respective year and day-of-year.
If neither are given as arguments, current UTC day and year are used.
Args:
paths:
[optional] list of directory paths you would like to create.
doy and year will be replaced by the datetime day and year, respectively.
datetime:
UTC Datetime string in ISO 8601 Format YYYY-MM-DDTHH:mm:ssZ
'''
for k, path in paths.items():
p = None
try:
pathlist = path if type(path) is list else [ path ]
for p in pathlist:
os.makedirs(p)
if verbose:
log.info('Creating directory: ' + p)
except OSError, e:
#print path
if e.errno == errno.EEXIST and os.path.isdir(p):
pass
else:
raise
return True | python | def createDirStruct(paths, verbose=True):
'''Loops ait.config._datapaths from AIT_CONFIG and creates a directory.
Replaces year and doy with the respective year and day-of-year.
If neither are given as arguments, current UTC day and year are used.
Args:
paths:
[optional] list of directory paths you would like to create.
doy and year will be replaced by the datetime day and year, respectively.
datetime:
UTC Datetime string in ISO 8601 Format YYYY-MM-DDTHH:mm:ssZ
'''
for k, path in paths.items():
p = None
try:
pathlist = path if type(path) is list else [ path ]
for p in pathlist:
os.makedirs(p)
if verbose:
log.info('Creating directory: ' + p)
except OSError, e:
#print path
if e.errno == errno.EEXIST and os.path.isdir(p):
pass
else:
raise
return True | [
"def",
"createDirStruct",
"(",
"paths",
",",
"verbose",
"=",
"True",
")",
":",
"for",
"k",
",",
"path",
"in",
"paths",
".",
"items",
"(",
")",
":",
"p",
"=",
"None",
"try",
":",
"pathlist",
"=",
"path",
"if",
"type",
"(",
"path",
")",
"is",
"list... | Loops ait.config._datapaths from AIT_CONFIG and creates a directory.
Replaces year and doy with the respective year and day-of-year.
If neither are given as arguments, current UTC day and year are used.
Args:
paths:
[optional] list of directory paths you would like to create.
doy and year will be replaced by the datetime day and year, respectively.
datetime:
UTC Datetime string in ISO 8601 Format YYYY-MM-DDTHH:mm:ssZ | [
"Loops",
"ait",
".",
"config",
".",
"_datapaths",
"from",
"AIT_CONFIG",
"and",
"creates",
"a",
"directory",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/bin/ait_create_dirs.py#L129-L159 | train | 42,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.