_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q261900
Deposit._publish_edited
validation
def _publish_edited(self): """Publish the deposit after for editing.""" record_pid, record = self.fetch_published() if record.revision_id == self['_deposit']['pid']['revision_id']: data = dict(self.dumps()) else: data = self.merge_with_published() data['$...
python
{ "resource": "" }
q261901
Deposit.publish
validation
def publish(self, pid=None, id_=None): """Publish a deposit. If it's the first time: * it calls the minter and set the following meta information inside the deposit: .. code-block:: python deposit['_deposit'] = { 'type': pid_type, ...
python
{ "resource": "" }
q261902
Deposit._prepare_edit
validation
def _prepare_edit(self, record): """Update selected keys. :param record: The record to prepare. """ data = record.dumps() # Keep current record revision for merging. data['_deposit']['pid']['revision_id'] = record.revision_id data['_deposit']['status'] = 'draft' ...
python
{ "resource": "" }
q261903
Deposit.edit
validation
def edit(self, pid=None): """Edit deposit. #. The signal :data:`invenio_records.signals.before_record_update` is sent before the edit execution. #. The following meta information are saved inside the deposit: .. code-block:: python deposit['_deposit']['pid'] = ...
python
{ "resource": "" }
q261904
Deposit.discard
validation
def discard(self, pid=None): """Discard deposit changes. #. The signal :data:`invenio_records.signals.before_record_update` is sent before the edit execution. #. It restores the last published version. #. The following meta information are saved inside the deposit: ...
python
{ "resource": "" }
q261905
Deposit.delete
validation
def delete(self, force=True, pid=None): """Delete deposit. Status required: ``'draft'``. :param force: Force deposit delete. (Default: ``True``) :param pid: Force pid object. (Default: ``None``) :returns: A new Deposit object. """ pid = pid or self.pid ...
python
{ "resource": "" }
q261906
Deposit.clear
validation
def clear(self, *args, **kwargs): """Clear only drafts. Status required: ``'draft'``. Meta information inside `_deposit` are preserved. """ super(Deposit, self).clear(*args, **kwargs)
python
{ "resource": "" }
q261907
Deposit.update
validation
def update(self, *args, **kwargs): """Update only drafts. Status required: ``'draft'``. Meta information inside `_deposit` are preserved. """ super(Deposit, self).update(*args, **kwargs)
python
{ "resource": "" }
q261908
Deposit.patch
validation
def patch(self, *args, **kwargs): """Patch only drafts. Status required: ``'draft'``. Meta information inside `_deposit` are preserved. """ return super(Deposit, self).patch(*args, **kwargs)
python
{ "resource": "" }
q261909
Deposit.files
validation
def files(self): """List of Files inside the deposit. Add validation on ``sort_by`` method: if, at the time of files access, the record is not a ``'draft'`` then a :exc:`invenio_pidstore.errors.PIDInvalidAction` is rised. """ files_ = super(Deposit, self).files ...
python
{ "resource": "" }
q261910
rst2node
validation
def rst2node(doc_name, data): """Converts a reStructuredText into its node """ if not data: return parser = docutils.parsers.rst.Parser() document = docutils.utils.new_document('<%s>' % doc_name) document.settings = docutils.frontend.OptionParser().get_default_values() document.setti...
python
{ "resource": "" }
q261911
setup
validation
def setup(app): """Hook the directives when Sphinx ask for it.""" if 'http' not in app.domains: httpdomain.setup(app) app.add_directive('autopyramid', RouteDirective)
python
{ "resource": "" }
q261912
api._parse_response
validation
def _parse_response(self, response): """Parses the API response and raises appropriate errors if raise_errors was set to True """ if not self._raise_errors: return response is_4xx_error = str(response.status_code)[0] == '4' is_5xx_error = str(response.status_...
python
{ "resource": "" }
q261913
api.templates
validation
def templates(self, timeout=None): """ API call to get a list of templates """ return self._api_request( self.TEMPLATES_ENDPOINT, self.HTTP_GET, timeout=timeout )
python
{ "resource": "" }
q261914
api.get_template
validation
def get_template(self, template_id, version=None, timeout=None): """ API call to get a specific template """ if (version): return self._api_request( self.TEMPLATES_VERSION_ENDPOINT % (template_id, version), self.HTTP_GET, timeout=timeout ...
python
{ "resource": "" }
q261915
api.create_template
validation
def create_template( self, name, subject, html, text='', timeout=None ): """ API call to create a template """ payload = { 'name': name, 'subject': subject, 'html': html, 'text': text } r...
python
{ "resource": "" }
q261916
api.create_new_locale
validation
def create_new_locale( self, template_id, locale, version_name, subject, text='', html='', timeout=None ): """ API call to create a new locale and version of a template """ payload = { 'locale': locale, 'name': v...
python
{ "resource": "" }
q261917
api.create_new_version
validation
def create_new_version( self, name, subject, text='', template_id=None, html=None, locale=None, timeout=None ): """ API call to create a new version of a template """ if(html): payload = { 'name': name, ...
python
{ "resource": "" }
q261918
api.update_template_version
validation
def update_template_version( self, name, subject, template_id, version_id, text='', html=None, timeout=None ): """ API call to update a template version """ if(html): payload = { 'name': name, ...
python
{ "resource": "" }
q261919
api.snippets
validation
def snippets(self, timeout=None): """ API call to get list of snippets """ return self._api_request( self.SNIPPETS_ENDPOINT, self.HTTP_GET, timeout=timeout )
python
{ "resource": "" }
q261920
api.get_snippet
validation
def get_snippet(self, snippet_id, timeout=None): """ API call to get a specific Snippet """ return self._api_request( self.SNIPPET_ENDPOINT % (snippet_id), self.HTTP_GET, timeout=timeout )
python
{ "resource": "" }
q261921
api.create_snippet
validation
def create_snippet(self, name, body, timeout=None): """ API call to create a Snippet """ payload = { 'name': name, 'body': body } return self._api_request( self.SNIPPETS_ENDPOINT, self.HTTP_POST, payload=payload, tim...
python
{ "resource": "" }
q261922
api._make_file_dict
validation
def _make_file_dict(self, f): """Make a dictionary with filename and base64 file data""" if isinstance(f, dict): file_obj = f['file'] if 'filename' in f: file_name = f['filename'] else: file_name = file_obj.name else: ...
python
{ "resource": "" }
q261923
api.send
validation
def send( self, email_id, recipient, email_data=None, sender=None, cc=None, bcc=None, tags=[], headers={}, esp_account=None, locale=None, email_version_name=None, inline=None, files=[], timeout=None ...
python
{ "resource": "" }
q261924
BatchAPI.execute
validation
def execute(self, timeout=None): """Execute all currently queued batch commands""" logger.debug(' > Batch API request (length %s)' % len(self._commands)) auth = self._build_http_auth() headers = self._build_request_headers() logger.debug('\tbatch headers: %s' % headers) ...
python
{ "resource": "" }
q261925
TabView.get_group_tabs
validation
def get_group_tabs(self): """ Return instances of all other tabs that are members of the tab's tab group. """ if self.tab_group is None: raise ImproperlyConfigured( "%s requires a definition of 'tab_group'" % self.__class__.__name__) ...
python
{ "resource": "" }
q261926
TabView._process_tabs
validation
def _process_tabs(self, tabs, current_tab, group_current_tab): """ Process and prepare tabs. This includes steps like updating references to the current tab, filtering out hidden tabs, sorting tabs etc... Args: tabs: The list of tabs to process. ...
python
{ "resource": "" }
q261927
TabView.get_context_data
validation
def get_context_data(self, **kwargs): """ Adds tab information to context. To retrieve a list of all group tab instances, use ``{{ tabs }}`` in your template. The id of the current tab is added as ``current_tab_id`` to the template context. If the current tab h...
python
{ "resource": "" }
q261928
normalize_name
validation
def normalize_name(s): """Convert a string into a valid python attribute name. This function is called to convert ASCII strings to something that can pass as python attribute name, to be used with namedtuples. >>> str(normalize_name('class')) 'class_' >>> str(normalize_name('a-name')) 'a_na...
python
{ "resource": "" }
q261929
schema
validation
def schema(tg): """ Convert the table and column descriptions of a `TableGroup` into specifications for the DB schema. :param ds: :return: A pair (tables, reference_tables). """ tables = {} for tname, table in tg.tabledict.items(): t = TableSpec.from_table_metadata(table) ...
python
{ "resource": "" }
q261930
Database.write
validation
def write(self, _force=False, _exists_ok=False, **items): """ Creates a db file with the core schema. :param force: If `True` an existing db file will be overwritten. """ if self.fname and self.fname.exists(): raise ValueError('db file already exists, use force=True ...
python
{ "resource": "" }
q261931
iterrows
validation
def iterrows(lines_or_file, namedtuples=False, dicts=False, encoding='utf-8', **kw): """Convenience factory function for csv reader. :param lines_or_file: Content to be read. Either a file handle, a file path or a list\ of strings. :param namedtuples: Yield namedtuples. :param dicts: Yield dicts. ...
python
{ "resource": "" }
q261932
rewrite
validation
def rewrite(fname, visitor, **kw): """Utility function to rewrite rows in tsv files. :param fname: Path of the dsv file to operate on. :param visitor: A callable that takes a line-number and a row as input and returns a \ (modified) row or None to filter out the row. :param kw: Keyword parameters a...
python
{ "resource": "" }
q261933
filter_rows_as_dict
validation
def filter_rows_as_dict(fname, filter_, **kw): """Rewrite a dsv file, filtering the rows. :param fname: Path to dsv file :param filter_: callable which accepts a `dict` with a row's data as single argument\ returning a `Boolean` indicating whether to keep the row (`True`) or to discard it \ `False`...
python
{ "resource": "" }
q261934
dump_grid
validation
def dump_grid(grid): """ Dump a single grid to its ZINC representation. """ header = 'ver:%s' % dump_str(str(grid._version), version=grid._version) if bool(grid.metadata): header += ' ' + dump_meta(grid.metadata, version=grid._version) columns = dump_columns(grid.column, version=grid._ve...
python
{ "resource": "" }
q261935
parse
validation
def parse(grid_str, mode=MODE_ZINC, charset='utf-8'): ''' Parse the given Zinc text and return the equivalent data. ''' # Decode incoming text (or python3 will whine!) if isinstance(grid_str, six.binary_type): grid_str = grid_str.decode(encoding=charset) # Split the separate grids up, t...
python
{ "resource": "" }
q261936
MetadataObject.append
validation
def append(self, key, value=MARKER, replace=True): ''' Append the item to the metadata. ''' return self.add_item(key, value, replace=replace)
python
{ "resource": "" }
q261937
MetadataObject.extend
validation
def extend(self, items, replace=True): ''' Append the items to the metadata. ''' if isinstance(items, dict) or isinstance(items, SortableDict): items = list(items.items()) for (key, value) in items: self.append(key, value, replace=replace)
python
{ "resource": "" }
q261938
Shape.regular_polygon
validation
def regular_polygon(cls, center, radius, n_vertices, start_angle=0, **kwargs): """Construct a regular polygon. Parameters ---------- center : array-like radius : float n_vertices : int start_angle : float, optional Where to put the first point, relati...
python
{ "resource": "" }
q261939
Shape.circle
validation
def circle(cls, center, radius, n_vertices=50, **kwargs): """Construct a circle. Parameters ---------- center : array-like radius : float n_vertices : int, optional Number of points to draw. Decrease for performance, increase for appearance. ...
python
{ "resource": "" }
q261940
Shape.rectangle
validation
def rectangle(cls, vertices, **kwargs): """Shortcut for creating a rectangle aligned with the screen axes from only two corners. Parameters ---------- vertices : array-like An array containing the ``[x, y]`` positions of two corners. kwargs Other keyword ...
python
{ "resource": "" }
q261941
Shape.from_dict
validation
def from_dict(cls, spec): """Create a |Shape| from a dictionary specification. Parameters ---------- spec : dict A dictionary with either the fields ``'center'`` and ``'radius'`` (for a circle), ``'center'``, ``'radius'``, and ``'n_vertices'`` (for a regular poly...
python
{ "resource": "" }
q261942
Shape._kwargs
validation
def _kwargs(self): """Keyword arguments for recreating the Shape from the vertices. """ return dict(color=self.color, velocity=self.velocity, colors=self.colors)
python
{ "resource": "" }
q261943
Shape.rotate
validation
def rotate(self, angle, center=None): """Rotate the shape, in-place. Parameters ---------- angle : float Angle to rotate, in radians counter-clockwise. center : array-like, optional Point about which to rotate. If not passed, the center of the...
python
{ "resource": "" }
q261944
Shape.flip_x
validation
def flip_x(self, center=None): """Flip the shape in the x direction, in-place. Parameters ---------- center : array-like, optional Point about which to flip. If not passed, the center of the shape will be used. """ if center is None: ...
python
{ "resource": "" }
q261945
Shape.flip_y
validation
def flip_y(self, center=None): """Flip the shape in the y direction, in-place. Parameters ---------- center : array-like, optional Point about which to flip. If not passed, the center of the shape will be used. """ if center is None: ...
python
{ "resource": "" }
q261946
Shape.flip
validation
def flip(self, angle, center=None): """ Flip the shape in an arbitrary direction. Parameters ---------- angle : array-like The angle, in radians counter-clockwise from the horizontal axis, defining the angle about which to flip the shape (of a line through `cente...
python
{ "resource": "" }
q261947
Shape.draw
validation
def draw(self): """Draw the shape in the current OpenGL context. """ if self.enabled: self._vertex_list.colors = self._gl_colors self._vertex_list.vertices = self._gl_vertices self._vertex_list.draw(pyglet.gl.GL_TRIANGLES)
python
{ "resource": "" }
q261948
Shape.update
validation
def update(self, dt): """Update the shape's position by moving it forward according to its velocity. Parameters ---------- dt : float """ self.translate(dt * self.velocity) self.rotate(dt * self.angular_velocity)
python
{ "resource": "" }
q261949
_map_timezones
validation
def _map_timezones(): """ Map the official Haystack timezone list to those recognised by pytz. """ tz_map = {} todo = HAYSTACK_TIMEZONES_SET.copy() for full_tz in pytz.all_timezones: # Finished case: if not bool(todo): # pragma: no cover # This is nearly impossible fo...
python
{ "resource": "" }
q261950
timezone
validation
def timezone(haystack_tz, version=LATEST_VER): """ Retrieve the Haystack timezone """ tz_map = get_tz_map(version=version) try: tz_name = tz_map[haystack_tz] except KeyError: raise ValueError('%s is not a recognised timezone on this host' \ % haystack_tz) retu...
python
{ "resource": "" }
q261951
_unescape
validation
def _unescape(s, uri=False): """ Iterative parser for string escapes. """ out = '' while len(s) > 0: c = s[0] if c == '\\': # Backslash escape esc_c = s[1] if esc_c in ('u', 'U'): # Unicode escape out += six.unichr(...
python
{ "resource": "" }
q261952
parse_grid
validation
def parse_grid(grid_data): """ Parse the incoming grid. """ try: # Split the grid up. grid_parts = NEWLINE_RE.split(grid_data) if len(grid_parts) < 2: raise ZincParseException('Malformed grid received', grid_data, 1, 1) # Grid and column m...
python
{ "resource": "" }
q261953
parse_scalar
validation
def parse_scalar(scalar_data, version): """ Parse a Project Haystack scalar in ZINC format. """ try: return hs_scalar[version].parseString(scalar_data, parseAll=True)[0] except pp.ParseException as pe: # Raise a new exception with the appropriate line number. raise ZincParseE...
python
{ "resource": "" }
q261954
SortableDict.add_item
validation
def add_item(self, key, value, after=False, index=None, pos_key=None, replace=True): """ Add an item at a specific location, possibly replacing the existing item. If after is True, we insert *after* the given index, otherwise we insert before. The position i...
python
{ "resource": "" }
q261955
dump
validation
def dump(grids, mode=MODE_ZINC): """ Dump the given grids in the specified over-the-wire format. """ if isinstance(grids, Grid): return dump_grid(grids, mode=mode) _dump = functools.partial(dump_grid, mode=mode) if mode == MODE_ZINC: return '\n'.join(map(_dump, grids)) elif m...
python
{ "resource": "" }
q261956
Grid._detect_or_validate
validation
def _detect_or_validate(self, val): ''' Detect the version used from the row content, or validate against the version if given. ''' if isinstance(val, list) \ or isinstance(val, dict) \ or isinstance(val, SortableDict) \ or isinstan...
python
{ "resource": "" }
q261957
Grid._assert_version
validation
def _assert_version(self, version): ''' Assert that the grid version is equal to or above the given value. If no version is set, set the version. ''' if self.nearest_version < version: if self._version_given: raise ValueError( '...
python
{ "resource": "" }
q261958
Version.nearest
validation
def nearest(self, ver): """ Retrieve the official version nearest the one given. """ if not isinstance(ver, Version): ver = Version(ver) if ver in OFFICIAL_VERSIONS: return ver # We might not have an exact match for that. # See if we have...
python
{ "resource": "" }
q261959
encrypt_files
validation
def encrypt_files(selected_host, only_link, file_name): """ Encrypts file with gpg and random generated password """ if ENCRYPTION_DISABLED: print('For encryption please install gpg') exit() passphrase = '%030x' % random.randrange(16**30) source_filename = file_name cmd = 'gp...
python
{ "resource": "" }
q261960
check_max_filesize
validation
def check_max_filesize(chosen_file, max_size): """ Checks file sizes for host """ if os.path.getsize(chosen_file) > max_size: return False else: return True
python
{ "resource": "" }
q261961
parse_arguments
validation
def parse_arguments(args, clone_list): """ Makes parsing arguments a function. """ returned_string="" host_number = args.host if args.show_list: print(generate_host_string(clone_list, "Available hosts: ")) exit() if args.decrypt: for i in args.files: print...
python
{ "resource": "" }
q261962
upload_files
validation
def upload_files(selected_file, selected_host, only_link, file_name): """ Uploads selected file to the host, thanks to the fact that every pomf.se based site has pretty much the same architecture. """ try: answer = requests.post( url=selected_host[0]+"upload.php", fil...
python
{ "resource": "" }
q261963
decrypt_files
validation
def decrypt_files(file_link): """ Decrypts file from entered links """ if ENCRYPTION_DISABLED: print('For decryption please install gpg') exit() try: parsed_link = re.findall(r'(.*/(.*))#(.{30})', file_link)[0] req = urllib.request.Request( parsed_link[0],...
python
{ "resource": "" }
q261964
DefinitionHandler.from_schema
validation
def from_schema(self, schema_node, base_name=None): """ Creates a Swagger definition from a colander schema. :param schema_node: Colander schema to be transformed into a Swagger definition. :param base_name: Schema alternative title. :rtype: dict ...
python
{ "resource": "" }
q261965
ParameterHandler.from_schema
validation
def from_schema(self, schema_node): """ Creates a list of Swagger params from a colander request schema. :param schema_node: Request schema to be transformed into Swagger. :param validators: Validators used in colander with the schema. :rtype: list ...
python
{ "resource": "" }
q261966
ParameterHandler.from_path
validation
def from_path(self, path): """ Create a list of Swagger path params from a cornice service path. :type path: string :rtype: list """ path_components = path.split('/') param_names = [comp[1:-1] for comp in path_components if comp.startswith(...
python
{ "resource": "" }
q261967
ParameterHandler._ref
validation
def _ref(self, param, base_name=None): """ Store a parameter schema and return a reference to it. :param schema: Swagger parameter definition. :param base_name: Name that should be used for the reference. :rtype: dict :returns: JSON pointer to th...
python
{ "resource": "" }
q261968
ResponseHandler.from_schema_mapping
validation
def from_schema_mapping(self, schema_mapping): """ Creates a Swagger response object from a dict of response schemas. :param schema_mapping: Dict with entries matching ``{status_code: response_schema}``. :rtype: dict :returns: Response schema. """ re...
python
{ "resource": "" }
q261969
ResponseHandler._ref
validation
def _ref(self, resp, base_name=None): """ Store a response schema and return a reference to it. :param schema: Swagger response definition. :param base_name: Name that should be used for the reference. :rtype: dict :returns: JSON pointer to the o...
python
{ "resource": "" }
q261970
CorniceSwagger.generate
validation
def generate(self, title=None, version=None, base_path=None, info=None, swagger=None, **kwargs): """Generate a Swagger 2.0 documentation. Keyword arguments may be used to provide additional information to build methods as such ignores. :param title: The name present...
python
{ "resource": "" }
q261971
CorniceSwagger._build_paths
validation
def _build_paths(self): """ Build the Swagger "paths" and "tags" attributes from cornice service definitions. """ paths = {} tags = [] for service in self.services: path, path_obj = self._extract_path_from_service(service) service_tags = ...
python
{ "resource": "" }
q261972
CorniceSwagger._extract_path_from_service
validation
def _extract_path_from_service(self, service): """ Extract path object and its parameters from service definitions. :param service: Cornice service to extract information from. :rtype: dict :returns: Path definition. """ path_obj = {} path =...
python
{ "resource": "" }
q261973
CorniceSwagger._extract_operation_from_view
validation
def _extract_operation_from_view(self, view, args): """ Extract swagger operation details from colander view definitions. :param view: View to extract information from. :param args: Arguments from the view decorator. :rtype: dict :returns: Operat...
python
{ "resource": "" }
q261974
CorniceSwagger._extract_transform_colander_schema
validation
def _extract_transform_colander_schema(self, args): """ Extract schema from view args and transform it using the pipeline of schema transformers :param args: Arguments from the view decorator. :rtype: colander.MappingSchema() :returns: View schema cloned and...
python
{ "resource": "" }
q261975
ParameterConverter.convert
validation
def convert(self, schema_node, definition_handler): """ Convert node schema into a parameter object. """ converted = { 'name': schema_node.name, 'in': self._in, 'required': schema_node.required } if schema_node.description: ...
python
{ "resource": "" }
q261976
merge_dicts
validation
def merge_dicts(base, changes): """Merge b into a recursively, without overwriting values. :param base: the dict that will be altered. :param changes: changes to update base. """ for k, v in changes.items(): if isinstance(v, dict): merge_dicts(base.setdefault(k, {}), v) ...
python
{ "resource": "" }
q261977
get_transition_viewset_method
validation
def get_transition_viewset_method(transition_name, **kwargs): ''' Create a viewset method for the provided `transition_name` ''' @detail_route(methods=['post'], **kwargs) def inner_func(self, request, pk=None, **kwargs): object = self.get_object() transition_method = getattr(object, ...
python
{ "resource": "" }
q261978
get_viewset_transition_action_mixin
validation
def get_viewset_transition_action_mixin(model, **kwargs): ''' Find all transitions defined on `model`, then create a corresponding viewset action method for each and apply it to `Mixin`. Finally, return `Mixin` ''' instance = model() class Mixin(object): save_after_transition = True...
python
{ "resource": "" }
q261979
fresh_cookies
validation
def fresh_cookies(ctx, mold=''): """Refresh the project from the original cookiecutter template.""" mold = mold or "https://github.com/Springerle/py-generic-project.git" # TODO: URL from config tmpdir = os.path.join(tempfile.gettempdir(), "cc-upgrade-pygments-markdown-lexer") if os.path.isdir('.git'):...
python
{ "resource": "" }
q261980
ci
validation
def ci(ctx): """Perform continuous integration tasks.""" opts = [''] # 'tox' makes no sense in Travis if os.environ.get('TRAVIS', '').lower() == 'true': opts += ['test.pytest'] else: opts += ['test.tox'] ctx.run("invoke --echo --pty clean --all build --docs check --reports{}".f...
python
{ "resource": "" }
q261981
py_hash
validation
def py_hash(key, num_buckets): """Generate a number in the range [0, num_buckets). Args: key (int): The key to hash. num_buckets (int): Number of buckets to use. Returns: The bucket number `key` computes to. Raises: ValueError: If `num_buckets` is not a positive number...
python
{ "resource": "" }
q261982
setup
validation
def setup(app): """ Initializer for Sphinx extension API. See http://www.sphinx-doc.org/en/stable/extdev/index.html#dev-extensions. """ lexer = MarkdownLexer() for alias in lexer.aliases: app.add_lexer(alias, lexer) return dict(version=__version__)
python
{ "resource": "" }
q261983
MdStat.load
validation
def load(self): """Return a dict of stats.""" ret = {} # Read the mdstat file with open(self.get_path(), 'r') as f: # lines is a list of line (with \n) lines = f.readlines() # First line: get the personalities # The "Personalities" line tells you...
python
{ "resource": "" }
q261984
MdStat.get_personalities
validation
def get_personalities(self, line): """Return a list of personalities readed from the input line.""" return [split('\W+', i)[1] for i in line.split(':')[1].split(' ') if i.startswith('[')]
python
{ "resource": "" }
q261985
MdStat.get_arrays
validation
def get_arrays(self, lines, personalities=[]): """Return a dict of arrays.""" ret = {} i = 0 while i < len(lines): try: # First array line: get the md device md_device = self.get_md_device_name(lines[i]) except IndexError: ...
python
{ "resource": "" }
q261986
MdStat.get_md_device
validation
def get_md_device(self, line, personalities=[]): """Return a dict of md device define in the line.""" ret = {} splitted = split('\W+', line) # Raid status # Active or 'started'. An inactive array is usually faulty. # Stopped arrays aren't visible here. ret['statu...
python
{ "resource": "" }
q261987
MdStat.get_md_status
validation
def get_md_status(self, line): """Return a dict of md status define in the line.""" ret = {} splitted = split('\W+', line) if len(splitted) < 7: ret['available'] = None ret['used'] = None ret['config'] = None else: # The final 2 en...
python
{ "resource": "" }
q261988
MdStat.get_components
validation
def get_components(self, line, with_type=True): """Return a dict of components in the line. key: device name (ex: 'sdc1') value: device role number """ ret = {} # Ignore (F) (see test 08) line2 = reduce(lambda x, y: x + y, split('\(.+\)', line)) if with_...
python
{ "resource": "" }
q261989
register_receivers
validation
def register_receivers(app, config): """Register signal receivers which send events.""" for event_name, event_config in config.items(): event_builders = [ obj_or_import_string(func) for func in event_config.get('event_builders', []) ] signal = obj_or_import_strin...
python
{ "resource": "" }
q261990
InternalMailbox.set_scheduled
validation
def set_scheduled(self): """ Returns True if state was successfully changed from idle to scheduled. """ with self._idle_lock: if self._idle: self._idle = False return True return False
python
{ "resource": "" }
q261991
StatsQueryResource.post
validation
def post(self, **kwargs): """Get statistics.""" data = request.get_json(force=False) if data is None: data = {} result = {} for query_name, config in data.items(): if config is None or not isinstance(config, dict) \ or (set(config.keys(...
python
{ "resource": "" }
q261992
StatAggregator._get_oldest_event_timestamp
validation
def _get_oldest_event_timestamp(self): """Search for the oldest event timestamp.""" # Retrieve the oldest event in order to start aggregation # from there query_events = Search( using=self.client, index=self.event_index )[0:1].sort( {'timestamp...
python
{ "resource": "" }
q261993
StatAggregator.get_bookmark
validation
def get_bookmark(self): """Get last aggregation date.""" if not Index(self.aggregation_alias, using=self.client).exists(): if not Index(self.event_index, using=self.client).exists(): return datetime.date.today() return...
python
{ "resource": "" }
q261994
StatAggregator.set_bookmark
validation
def set_bookmark(self): """Set bookmark for starting next aggregation.""" def _success_date(): bookmark = { 'date': self.new_bookmark or datetime.datetime.utcnow(). strftime(self.doc_id_suffix) } yield dict(_index=self.last_index_writt...
python
{ "resource": "" }
q261995
StatAggregator._format_range_dt
validation
def _format_range_dt(self, d): """Format range filter datetime to the closest aggregation interval.""" if not isinstance(d, six.string_types): d = d.isoformat() return '{0}||/{1}'.format( d, self.dt_rounding_map[self.aggregation_interval])
python
{ "resource": "" }
q261996
StatAggregator.agg_iter
validation
def agg_iter(self, lower_limit=None, upper_limit=None): """Aggregate and return dictionary to be indexed in ES.""" lower_limit = lower_limit or self.get_bookmark().isoformat() upper_limit = upper_limit or ( datetime.datetime.utcnow().replace(microsecond=0).isoformat()) aggreg...
python
{ "resource": "" }
q261997
StatAggregator.run
validation
def run(self, start_date=None, end_date=None, update_bookmark=True): """Calculate statistics aggregations.""" # If no events have been indexed there is nothing to aggregate if not Index(self.event_index, using=self.client).exists(): return lower_limit = start_date or self.get...
python
{ "resource": "" }
q261998
StatAggregator.list_bookmarks
validation
def list_bookmarks(self, start_date=None, end_date=None, limit=None): """List the aggregation's bookmarks.""" query = Search( using=self.client, index=self.aggregation_alias, doc_type=self.bookmark_doc_type ).sort({'date': {'order': 'desc'}}) range_ar...
python
{ "resource": "" }
q261999
StatAggregator.delete
validation
def delete(self, start_date=None, end_date=None): """Delete aggregation documents.""" aggs_query = Search( using=self.client, index=self.aggregation_alias, doc_type=self.aggregation_doc_type ).extra(_source=False) range_args = {} if start_date...
python
{ "resource": "" }