Search is not available for this dataset
text
stringlengths
75
104k
def cells_to_series(cells, args): """Convert a CellImpl into a Series. `args` must be a sequence of argkeys. `args` can be longer or shorter then the number of cell's parameters. If shorter, then defaults are filled if any, else raise error. If longer, then redundant args are ignored. """ ...
def clear_descendants(self, source, clear_source=True): """Remove all descendants of(reachable from) `source`. Args: source: Node descendants clear_source(bool): Remove origin too if True. Returns: set: The removed nodes. """ desc = nx.descend...
def clear_obj(self, obj): """"Remove all nodes with `obj` and their descendants.""" obj_nodes = self.get_nodes_with(obj) removed = set() for node in obj_nodes: if self.has_node(node): removed.update(self.clear_descendants(node)) return removed
def get_nodes_with(self, obj): """Return nodes with `obj`.""" result = set() if nx.__version__[0] == "1": nodes = self.nodes_iter() else: nodes = self.nodes for node in nodes: if node[OBJ] == obj: result.add(node) retu...
def add_path(self, nodes, **attr): """In replacement for Deprecated add_path method""" if nx.__version__[0] == "1": return super().add_path(nodes, **attr) else: return nx.add_path(self, nodes, **attr)
def rename(self, name): """Rename the model itself""" self._impl.system.rename_model(new_name=name, old_name=self.name)
def rename(self, name): """Rename self. Must be called only by its system.""" if is_valid_name(name): if name not in self.system.models: self.name = name return True # Rename success else: # Model name already exists return False ...
def clear_descendants(self, source, clear_source=True): """Clear values and nodes calculated from `source`.""" removed = self.cellgraph.clear_descendants(source, clear_source) for node in removed: del node[OBJ].data[node[KEY]]
def clear_obj(self, obj): """Clear values and nodes of `obj` and their dependants.""" removed = self.cellgraph.clear_obj(obj) for node in removed: del node[OBJ].data[node[KEY]]
def get_object(self, name): """Retrieve an object by a dotted name relative to the model.""" parts = name.split(".") space = self.spaces[parts.pop(0)] if parts: return space.get_object(".".join(parts)) else: return space
def restore_state(self, system): """Called after unpickling to restore some attributes manually.""" Impl.restore_state(self, system) BaseSpaceContainerImpl.restore_state(self, system) mapping = {} for node in self.cellgraph: if isinstance(node, tuple): ...
def get_dynamic_base(self, bases: tuple): """Create of get a base space for a tuple of bases""" try: return self._dynamic_bases_inverse[bases] except KeyError: name = self._dynamic_base_namer.get_next(self._dynamic_bases) base = self._new_space(name=name) ...
def check_mro(self, bases): """Check if C3 MRO is possible with given bases""" try: self.add_node("temp") for base in bases: nx.DiGraph.add_edge(self, base, "temp") result = self.get_mro("temp")[1:] finally: self.remove_node("temp...
def get_command_names(): """ Returns a list of command names supported """ ret = [] for f in os.listdir(COMMAND_MODULE_PATH): if os.path.isfile(os.path.join(COMMAND_MODULE_PATH, f)) and f.endswith(COMMAND_MODULE_SUFFIX): ret.append(f[:-len(COMMAND_MODULE_SUFFIX)]) return ret
def get(vals, key, default_val=None): """ Returns a dictionary value """ val = vals for part in key.split('.'): if isinstance(val, dict): val = val.get(part, None) if val is None: return default_val else: return default_val retu...
def parse_option_settings(option_settings): """ Parses option_settings as they are defined in the configuration file """ ret = [] for namespace, params in list(option_settings.items()): for key, value in list(params.items()): ret.append((namespace, key, value)) return ret
def parse_env_config(config, env_name): """ Parses an environment config """ all_env = get(config, 'app.all_environments', {}) env = get(config, 'app.environments.' + str(env_name), {}) return merge_dict(all_env, env)
def create_archive(directory, filename, config={}, ignore_predicate=None, ignored_files=['.git', '.svn']): """ Creates an archive from a directory and returns the file that was created. """ with zipfile.ZipFile(filename, 'w', compression=zipfile.ZIP_DEFLATED) as zip_file: root_len = len(os.p...
def add_config_files_to_archive(directory, filename, config={}): """ Adds configuration files to an existing archive """ with zipfile.ZipFile(filename, 'a') as zip_file: for conf in config: for conf, tree in list(conf.items()): if 'yaml' in tree: c...
def swap_environment_cnames(self, from_env_name, to_env_name): """ Swaps cnames for an environment """ self.ebs.swap_environment_cnames(source_environment_name=from_env_name, destination_environment_name=to_env_name)
def upload_archive(self, filename, key, auto_create_bucket=True): """ Uploads an application archive version to s3 """ try: bucket = self.s3.get_bucket(self.aws.bucket) if (( self.aws.region != 'us-east-1' and self.aws.region != 'eu-west-1') and ...
def create_application(self, description=None): """ Creats an application and sets the helpers current app_name to the created application """ out("Creating application " + str(self.app_name)) self.ebs.create_application(self.app_name, description=description)
def delete_application(self): """ Creats an application and sets the helpers current app_name to the created application """ out("Deleting application " + str(self.app_name)) self.ebs.delete_application(self.app_name, terminate_env_by_force=True)
def application_exists(self): """ Returns whether or not the given app_name exists """ response = self.ebs.describe_applications(application_names=[self.app_name]) return len(response['DescribeApplicationsResponse']['DescribeApplicationsResult']['Applications']) > 0
def create_environment(self, env_name, version_label=None, solution_stack_name=None, cname_prefix=None, description=None, option_settings=None, tier_name='WebServer', tier_type='Standard', tier_version='1.1'): """ Creates a new environment ""...
def environment_exists(self, env_name): """ Returns whether or not the given environment exists """ response = self.ebs.describe_environments(application_name=self.app_name, environment_names=[env_name], include_deleted=False) ret...
def rebuild_environment(self, env_name): """ Rebuilds an environment """ out("Rebuilding " + str(env_name)) self.ebs.rebuild_environment(environment_name=env_name)
def get_environments(self): """ Returns the environments """ response = self.ebs.describe_environments(application_name=self.app_name, include_deleted=False) return response['DescribeEnvironmentsResponse']['DescribeEnvironmentsResult']['Environments']
def delete_environment(self, environment_name): """ Deletes an environment """ self.ebs.terminate_environment(environment_name=environment_name, terminate_resources=True)
def update_environment(self, environment_name, description=None, option_settings=[], tier_type=None, tier_name=None, tier_version='1.0'): """ Updates an application version """ out("Updating environment: " + str(environment_name)) messages = self.ebs.va...
def environment_name_for_cname(self, env_cname): """ Returns an environment name for the given cname """ envs = self.get_environments() for env in envs: if env['Status'] != 'Terminated' \ and 'CNAME' in env \ and env['CNAME'] \ ...
def deploy_version(self, environment_name, version_label): """ Deploys a version to an environment """ out("Deploying " + str(version_label) + " to " + str(environment_name)) self.ebs.update_environment(environment_name=environment_name, version_label=version_label)
def get_versions(self): """ Returns the versions available """ response = self.ebs.describe_application_versions(application_name=self.app_name) return response['DescribeApplicationVersionsResponse']['DescribeApplicationVersionsResult']['ApplicationVersions']
def create_application_version(self, version_label, key): """ Creates an application version """ out("Creating application version " + str(version_label) + " for " + str(key)) self.ebs.create_application_version(self.app_name, version_label, ...
def delete_unused_versions(self, versions_to_keep=10): """ Deletes unused versions """ # get versions in use environments = self.ebs.describe_environments(application_name=self.app_name, include_deleted=False) environments = environments['DescribeEnvironmentsResponse']['...
def describe_events(self, environment_name, next_token=None, start_time=None): """ Describes events from the given environment """ events = self.ebs.describe_events( application_name=self.app_name, environment_name=environment_name, next_token=next_tok...
def wait_for_environments(self, environment_names, health=None, status=None, version_label=None, include_deleted=True, use_events=True): """ Waits for an environment to have the given version_label and to be in the green state """ # turn into a list...
def add_arguments(parser): """ adds arguments for the swap urls command """ parser.add_argument('-o', '--old-environment', help='Old environment name', required=True) parser.add_argument('-n', '--new-environment', help='New environment name', required=True)
def execute(helper, config, args): """ Swaps old and new URLs. If old_environment was active, new_environment will become the active environment """ old_env_name = args.old_environment new_env_name = args.new_environment # swap C-Names out("Assuming that {} is the currently active envir...
def execute(helper, config, args): """ dump command dumps things """ env = parse_env_config(config, args.environment) option_settings = env.get('option_settings', {}) settings = parse_option_settings(option_settings) for setting in settings: out(str(setting))
def cached_property(f): """Similar to `@property` but it calls the function just once and caches the result. The object has to can have ``__cache__`` attribute. If you define `__slots__` for optimization, the metaclass should be a :class:`CacheMeta`. """ @property @functools.wraps(f) ...
def execute(helper, config, args): """ Lists environments """ envs = config.get('app', {}).get('environments', []) out("Parsed environments:") for name, conf in list(envs.items()): out('\t'+name) envs = helper.get_environments() out("Deployed environments:") for env in envs: ...
def execute(helper, config, args): """ The init command """ # check to see if the application exists if not helper.application_exists(): helper.create_application(get(config, 'app.description')) else: out("Application "+get(config, 'app.app_name')+" exists") # create enviro...
def execute(helper, config, args): """ Deletes an environment """ helper.delete_application() # wait if not args.dont_wait: # get environments environment_names = [] for env in helper.get_environments(): environment_names.append(env['EnvironmentName']) ...
def execute(helper, config, args): """ Deletes an environment """ env_config = parse_env_config(config, args.environment) environments_to_wait_for_term = [] environments = helper.get_environments() for env in environments: if env['EnvironmentName'] == args.environment: ...
def execute(helper, config, args): """ Deploys to an environment """ version_label = args.version_label env_config = parse_env_config(config, args.environment) env_name = args.environment # upload or build an archive version_label = upload_application_archive( helper, env_config...
def add_arguments(parser): """ adds arguments for the deploy command """ parser.add_argument('-e', '--environment', help='Environment name', required=True) parser.add_argument('-w', '--dont-wait', help='Skip waiting for the init to finish', action='store_true') parser.add_argument('-...
def execute(helper, config, args): """ Deploys to an environment """ env_config = parse_env_config(config, args.environment) cname_prefix = env_config.get('cname_prefix', None) env_name = args.environment # change version if args.version_label: helper.deploy_version(env_name, ar...
def join_phonemes(*args): """Joins a Hangul letter from Korean phonemes.""" # Normalize arguments as onset, nucleus, coda. if len(args) == 1: # tuple of (onset, nucleus[, coda]) args = args[0] if len(args) == 2: args += (CODAS[0],) try: onset, nucleus, coda = args ...
def split_phonemes(letter, onset=True, nucleus=True, coda=True): """Splits Korean phonemes as known as "์ž์†Œ" from a Hangul letter. :returns: (onset, nucleus, coda) :raises ValueError: `letter` is not a Hangul single letter. """ if len(letter) != 1 or not is_hangul(letter): raise ValueError(...
def combine_words(word1, word2): """Combines two words. If the first word ends with a vowel and the initial letter of the second word is only consonant, it merges them into one letter:: >>> combine_words(u'๋‹ค', u'ใ„บ') ๋‹ญ >>> combine_words(u'๊ฐ€์˜ค', u'ใ„ด๋ˆ„๋ฆฌ') ๊ฐ€์˜จ๋ˆ„๋ฆฌ """ if word1 and word2 an...
def index_particles(particles): """Indexes :class:`Particle` objects. It returns a regex pattern which matches to any particle morphs and a dictionary indexes the given particles by regex groups. """ patterns, indices = [], {} for x, p in enumerate(particles): group = u'_%d' % x ...
def execute(helper, config, args): """ Waits for an environment to be healthy """ helper.wait_for_environments(args.environment, health=args.health)
def execute(helper, config, args): """ Lists environments """ versions = helper.get_versions() out("Deployed versions:") for version in versions: out(version)
def add_arguments(parser): """ Args for the init command """ parser.add_argument('-e', '--environment', help='Environment name', required=False, nargs='+') parser.add_argument('-w', '--dont-wait', help='Skip waiting for the app to be deleted', action='store_true')
def execute(helper, config, args): """ Updates environments """ environments = [] if args.environment: for env_name in args.environment: environments.append(env_name) else: for env_name, env_config in list(get(config, 'app.environments').items()): environm...
def execute(helper, config, args): """ Describes recent events for an environment. """ environment_name = args.environment (events, next_token) = helper.describe_events(environment_name, start_time=datetime.now().isoformat()) # swap C-Names for event in events: print(("["+event['Se...
def execute(helper, config, args): """ Rebuilds an environment """ env_config = parse_env_config(config, args.environment) helper.rebuild_environment(args.environment) # wait if not args.dont_wait: helper.wait_for_environments(args.environment, health='Green', status='Ready')
def generate_tolerances(morph1, morph2): """Generates all reasonable tolerant particle morphs:: >>> set(generate_tolerances(u'์ด', u'๊ฐ€')) set([u'์ด(๊ฐ€)', u'(์ด)๊ฐ€', u'๊ฐ€(์ด)', u'(๊ฐ€)์ด']) >>> set(generate_tolerances(u'์ด๋ฉด', u'๋ฉด')) set([u'(์ด)๋ฉด']) """ if morph1 == morph2: # Tolerance not requi...
def parse_tolerance_style(style, registry=None): """Resolves a tolerance style of the given tolerant particle morph:: >>> parse_tolerance_style(u'์€(๋Š”)') 0 >>> parse_tolerance_style(u'(์€)๋Š”') 1 >>> parse_tolerance_style(OPTIONAL_MORPH2_AND_MORPH1) 3 """ if isinstance(style, integer_t...
def execute(helper, config, args): """ Lists solution stacks """ out("Available solution stacks") for stack in helper.list_available_solution_stacks(): out(" "+str(stack)) return 0
def add_arguments(parser): """ adds arguments for the deploy command """ parser.add_argument('-e', '--environment', help='Environment name', required=True) parser.add_argument('-w', '--dont-wait', help='Skip waiting', action='store_true') parser.add_argument('-a', '--archive', help='Archive file...
def execute(helper, config, args): """ Deploys to an environment """ version_label = args.version_label archive = args.archive # get the environment configuration env_config = parse_env_config(config, args.environment) option_settings = parse_option_settings(env_config.get('option_setti...
def filter_only_significant(word): """Gets a word which removes insignificant letters at the end of the given word:: >>> pick_significant(u'๋„ฅ์Šจ(์ฝ”๋ฆฌ์•„)') ๋„ฅ์Šจ >>> pick_significant(u'๋ฉ”์ดํ”Œ์Šคํ† ๋ฆฌ...') ๋ฉ”์ดํ”Œ์Šคํ† ๋ฆฌ """ if not word: return word # Unwrap a complete parenthesis. if word.start...
def pick_coda_from_letter(letter): """Picks only a coda from a Hangul letter. It returns ``None`` if the given letter is not Hangul. """ try: __, __, coda = \ split_phonemes(letter, onset=False, nucleus=False, coda=True) except ValueError: return None else: r...
def pick_coda_from_decimal(decimal): """Picks only a coda from a decimal.""" decimal = Decimal(decimal) __, digits, exp = decimal.as_tuple() if exp < 0: return DIGIT_CODAS[digits[-1]] __, digits, exp = decimal.normalize().as_tuple() index = bisect_right(EXP_INDICES, exp) - 1 if index...
def deposit_fetcher(record_uuid, data): """Fetch a deposit identifier. :param record_uuid: Record UUID. :param data: Record content. :returns: A :class:`invenio_pidstore.fetchers.FetchedPID` that contains data['_deposit']['id'] as pid_value. """ return FetchedPID( provider=Depos...
def deposit_minter(record_uuid, data): """Mint a deposit identifier. A PID with the following characteristics is created: .. code-block:: python { "object_type": "rec", "object_uuid": record_uuid, "pid_value": "<new-pid-value>", "pid_type": "depid",...
def admin_permission_factory(): """Factory for creating a permission for an admin `deposit-admin-access`. If `invenio-access` module is installed, it returns a :class:`invenio_access.permissions.DynamicPermission` object. Otherwise, it returns a :class:`flask_principal.Permission` object. :returns...
def create_blueprint(endpoints): """Create Invenio-Deposit-UI blueprint. See: :data:`invenio_deposit.config.DEPOSIT_RECORDS_UI_ENDPOINTS`. :param endpoints: List of endpoints configuration. :returns: The configured blueprint. """ from invenio_records_ui.views import create_url_rule bluepr...
def default_view_method(pid, record, template=None): """Default view method. Sends ``record_viewed`` signal and renders template. """ record_viewed.send( current_app._get_current_object(), pid=pid, record=record, ) deposit_type = request.values.get('type') return r...
def create(cls, object_type=None, object_uuid=None, **kwargs): """Create a new deposit identifier. :param object_type: The object type (Default: ``None``) :param object_uuid: The object UUID (Default: ``None``) :param kwargs: It contains the pid value. """ assert 'pid_va...
def extract_actions_from_class(record_class): """Extract actions from class.""" for name in dir(record_class): method = getattr(record_class, name, None) if method and getattr(method, '__deposit_action__', False): yield method.__name__
def check_oauth2_scope(can_method, *myscopes): """Base permission factory that check OAuth2 scope and can_method. :param can_method: Permission check function that accept a record in input and return a boolean. :param myscopes: List of scopes required to permit the access. :returns: A :class:`f...
def can_elasticsearch(record): """Check if a given record is indexed. :param record: A record object. :returns: If the record is indexed returns `True`, otherwise `False`. """ search = request._methodview.search_class() search = search.get_record(str(record.id)) return search.count() == 1
def create_error_handlers(blueprint): """Create error handlers on blueprint.""" blueprint.errorhandler(PIDInvalidAction)(create_api_errorhandler( status=403, message='Invalid action' )) records_rest_error_handlers(blueprint)
def create_blueprint(endpoints): """Create Invenio-Deposit-REST blueprint. See: :data:`invenio_deposit.config.DEPOSIT_REST_ENDPOINTS`. :param endpoints: List of endpoints configuration. :returns: The configured blueprint. """ blueprint = Blueprint( 'invenio_deposit_rest', __nam...
def post(self, pid, record, action): """Handle deposit action. After the action is executed, a :class:`invenio_deposit.signals.post_action` signal is sent. Permission required: `update_permission_factory`. :param pid: Pid object (from url). :param record: Record object...
def get(self, pid, record): """Get files. Permission required: `read_permission_factory`. :param pid: Pid object (from url). :param record: Record object resolved from the pid. :returns: The files. """ return self.make_response(obj=record.files, pid=pid, record=...
def post(self, pid, record): """Handle POST deposit files. Permission required: `update_permission_factory`. :param pid: Pid object (from url). :param record: Record object resolved from the pid. """ # load the file uploaded_file = request.files['file'] ...
def put(self, pid, record): """Handle the sort of the files through the PUT deposit files. Expected input in body PUT: .. code-block:: javascript [ { "id": 1 }, { "id": 2 }, ...
def get(self, pid, record, key, version_id, **kwargs): """Get file. Permission required: `read_permission_factory`. :param pid: Pid object (from url). :param record: Record object resolved from the pid. :param key: Unique identifier for the file in the deposit. :param v...
def put(self, pid, record, key): """Handle the file rename through the PUT deposit file. Permission required: `update_permission_factory`. :param pid: Pid object (from url). :param record: Record object resolved from the pid. :param key: Unique identifier for the file in the de...
def delete(self, pid, record, key): """Handle DELETE deposit file. Permission required: `update_permission_factory`. :param pid: Pid object (from url). :param record: Record object resolved from the pid. :param key: Unique identifier for the file in the deposit. """ ...
def records(): """Load records.""" import pkg_resources from dojson.contrib.marc21 import marc21 from dojson.contrib.marc21.utils import create_record, split_blob from flask_login import login_user, logout_user from invenio_accounts.models import User from invenio_deposit.api import Deposit ...
def location(): """Load default location.""" d = current_app.config['DATADIR'] with db.session.begin_nested(): Location.query.delete() loc = Location(name='local', uri=d, default=True) db.session.add(loc) db.session.commit()
def jsonschemas(self): """Load deposit JSON schemas.""" _jsonschemas = { k: v['jsonschema'] for k, v in self.app.config['DEPOSIT_RECORDS_UI_ENDPOINTS'].items() if 'jsonschema' in v } return defaultdict( lambda: self.app.config['DEPOSIT_DEFA...
def schemaforms(self): """Load deposit schema forms.""" _schemaforms = { k: v['schemaform'] for k, v in self.app.config['DEPOSIT_RECORDS_UI_ENDPOINTS'].items() if 'schemaform' in v } return defaultdict( lambda: self.app.config['DEPOSIT_DEFA...
def init_app(self, app): """Flask application initialization. Initialize the UI endpoints. Connect all signals if `DEPOSIT_REGISTER_SIGNALS` is ``True``. :param app: An instance of :class:`flask.Flask`. """ self.init_config(app) app.register_blueprint(ui.create...
def init_app(self, app): """Flask application initialization. Initialize the REST endpoints. Connect all signals if `DEPOSIT_REGISTER_SIGNALS` is True. :param app: An instance of :class:`flask.Flask`. """ self.init_config(app) blueprint = rest.create_blueprint(...
def deposit_links_factory(pid): """Factory for record links generation. The dictionary is formed as: .. code-block:: python { 'files': '/url/to/files', 'publish': '/url/to/publish', 'edit': '/url/to/edit', 'discard': '/url/to/discard', ....
def process_minter(value): """Load minter from PIDStore registry based on given value. :param value: Name of the minter. :returns: The minter. """ try: return current_pidstore.minters[value] except KeyError: raise click.BadParameter( 'Unknown minter {0}. Please use o...
def process_schema(value): """Load schema from JSONSchema registry based on given value. :param value: Schema path, relative to the directory when it was registered. :returns: The schema absolute path. """ schemas = current_app.extensions['invenio-jsonschemas'].schemas try: retu...
def json_serializer(pid, data, *args): """Build a JSON Flask response using the given data. :param pid: The `invenio_pidstore.models.PersistentIdentifier` of the record. :param data: The record metadata. :returns: A Flask response with JSON data. :rtype: :py:class:`flask.Response`. """ ...
def file_serializer(obj): """Serialize a object. :param obj: A :class:`invenio_files_rest.models.ObjectVersion` instance. :returns: A dictionary with the fields to serialize. """ return { "id": str(obj.file_id), "filename": obj.key, "filesize": obj.file.size, "checks...
def json_files_serializer(objs, status=None): """JSON Files Serializer. :parma objs: A list of:class:`invenio_files_rest.models.ObjectVersion` instances. :param status: A HTTP Status. (Default: ``None``) :returns: A Flask response with JSON data. :rtype: :py:class:`flask.Response`. """ ...
def json_file_response(obj=None, pid=None, record=None, status=None): """JSON Files/File serializer. :param obj: A :class:`invenio_files_rest.models.ObjectVersion` instance or a :class:`invenio_records_files.api.FilesIterator` if it's a list of files. :param pid: PID value. (not used) :...
def index_deposit_after_publish(sender, action=None, pid=None, deposit=None): """Index the record after publishing. .. note:: if the record is not published, it doesn't index. :param sender: Who send the signal. :param action: Action executed by the sender. (Default: ``None``) :param pid: PID obje...
def index(method=None, delete=False): """Decorator to update index. :param method: Function wrapped. (Default: ``None``) :param delete: If `True` delete the indexed record. (Default: ``None``) """ if method is None: return partial(index, delete=delete) @wraps(method) def wrapper(se...
def has_status(method=None, status='draft'): """Check that deposit has a defined status (default: draft). :param method: Function executed if record has a defined status. (Default: ``None``) :param status: Defined status to check. (Default: ``'draft'``) """ if method is None: return...