Search is not available for this dataset
text
stringlengths
75
104k
def revoke(self, revocation_reason, uid=None, revocation_message=None, compromise_occurrence_date=None): """ Revoke a managed object stored by a KMIP appliance. Args: revocation_reason (RevocationReasonCode): An enumeration indicating the revocation re...
def encrypt(self, data, uid=None, cryptographic_parameters=None, iv_counter_nonce=None): """ Encrypt data using the specified encryption key and parameters. Args: data (bytes): The bytes to encrypt. Required. uid (string): The unique ID of the encryption ...
def signature_verify(self, message, signature, uid=None, cryptographic_parameters=None): """ Verify a message signature using the specified signing key. Args: message (bytes): The bytes of the signed message. Required. signature (bytes): The byte...
def mac(self, data, uid=None, algorithm=None): """ Get the message authentication code for data. Args: data (string): The data to be MACed. uid (string): The unique ID of the managed object that is the key to use for the MAC operation. algorit...
def _build_cryptographic_parameters(self, value): """ Build a CryptographicParameters struct from a dictionary. Args: value (dict): A dictionary containing the key/value pairs for a CryptographicParameters struct. Returns: None: if value is None ...
def _build_encryption_key_information(self, value): """ Build an EncryptionKeyInformation struct from a dictionary. Args: value (dict): A dictionary containing the key/value pairs for a EncryptionKeyInformation struct. Returns: EncryptionKeyInfor...
def _build_mac_signature_key_information(self, value): """ Build an MACSignatureKeyInformation struct from a dictionary. Args: value (dict): A dictionary containing the key/value pairs for a MACSignatureKeyInformation struct. Returns: MACSignatur...
def _build_key_wrapping_specification(self, value): """ Build a KeyWrappingSpecification struct from a dictionary. Args: value (dict): A dictionary containing the key/value pairs for a KeyWrappingSpecification struct. Returns: KeyWrappingSpecific...
def _build_common_attributes(self, operation_policy_name=None): ''' Build a list of common attributes that are shared across symmetric as well as asymmetric objects ''' common_attributes = [] if operation_policy_name: common_attributes.append( ...
def _build_name_attribute(self, name=None): ''' Build a name attribute, returned in a list for ease of use in the caller ''' name_list = [] if name: name_list.append(self.attribute_factory.create_attribute( enums.AttributeType.NAME, ...
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the QueryRequestPayload object and decode it into its constituent parts. Args: input_buffer (Stream): A data stream containing encoded object data, supporting a ...
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Write the data encoding the QueryRequestPayload object to a stream. Args: output_buffer (Stream): A data stream in which to encode object data, supporting a write method; usually a Bytearray...
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the QueryResponsePayload object and decode it into its constituent parts. Args: input_buffer (Stream): A data stream containing encoded object data, supporting a...
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Write the data encoding the QueryResponsePayload object to a stream. Args: output_buffer (Stream): A data stream in which to encode object data, supporting a write method; usually a Bytearra...
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the GetAttributes response payload and decode it into its constituent parts. Args: input_buffer (stream): A data stream containing encoded object data, supportin...
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Write the data encoding the GetAttributes response payload to a stream. Args: output_buffer (stream): A data stream in which to encode object data, supporting a write method; usually...
def get_single(group, name, path=None): """Find a single entry point. Returns an :class:`EntryPoint` object, or raises :exc:`NoSuchEntryPoint` if no match is found. """ for config, distro in iter_files_distros(path=path): if (group in config) and (name in config[group]): epstr =...
def get_group_named(group, path=None): """Find a group of entry points with unique names. Returns a dictionary of names to :class:`EntryPoint` objects. """ result = {} for ep in get_group_all(group, path=path): if ep.name not in result: result[ep.name] = ep return result
def get_group_all(group, path=None): """Find all entry points in a group. Returns a list of :class:`EntryPoint` objects. """ result = [] for config, distro in iter_files_distros(path=path): if group in config: for name, epstr in config[group].items(): with BadEnt...
def load(self): """Load the object to which this entry point refers. """ mod = import_module(self.module_name) obj = mod if self.object_name: for attr in self.object_name.split('.'): obj = getattr(obj, attr) return obj
def from_string(cls, epstr, name, distro=None): """Parse an entry point from the syntax in entry_points.txt :param str epstr: The entry point string (not including 'name =') :param str name: The name of this entry point :param Distribution distro: The distribution in which the entry poi...
def live(): """Run livereload server""" from livereload import Server server = Server(app) map(server.watch, glob2.glob("application/pages/**/*.*")) # pages map(server.watch, glob2.glob("application/macros/**/*.html")) # macros map(server.watch, glob2.glob("application/static/**/*.*")) # pu...
def generate_project(args): """New project.""" # Project templates path src = os.path.join(dirname(abspath(__file__)), 'project') project_name = args.get('<project>') if not project_name: logger.warning('Project name cannot be empty.') return # Destination project path dst...
def generate_controller(args): """Generate controller, include the controller file, template & css & js directories.""" controller_template = os.path.join(dirname(abspath(__file__)), 'templates/controller.py') test_template = os.path.join(dirname(abspath(__file__)), 'templates/unittest.py') controller_n...
def generate_action(args): """Generate action.""" controller = args.get('<controller>') action = args.get('<action>') with_template = args.get('-t') current_path = os.getcwd() logger.info('Start generating action.') controller_file_path = os.path.join(current_path, 'application/controllers...
def generate_form(args): """Generate form.""" form_name = args.get('<form>') logger.info('Start generating form.') _generate_form(form_name) logger.info('Finish generating form.')
def generate_model(args): """Generate model.""" model_name = args.get('<model>') if not model_name: logger.warning('Model name cannot be empty.') return logger.info('Start generating model.') model_template = os.path.join(dirname(abspath(__file__)), 'templates/model.py') curren...
def generate_macro(args): """Genarate macro.""" macro = args.get('<macro>').replace('-', '_') category = args.get('<category>') if not macro: logger.warning('Macro name cannot be empty.') return logger.info('Start generating macro.') current_path = os.getcwd() if category...
def _mkdir_p(path): """mkdir -p path""" try: os.makedirs(path) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise else: logger.info("New: %s%s", path, os.path.sep)
def _rewrite_and_copy(src_file, dst_file, project_name): """Replace vars and copy.""" # Create temp file fh, abs_path = mkstemp() with io.open(abs_path, 'w', encoding='utf-8') as new_file: with io.open(src_file, 'r', encoding='utf-8') as old_file: for line in old_file: ...
def timesince(value): """Friendly time gap""" if not value: return "" if not isinstance(value, datetime.date): return value now = datetime.datetime.now() delta = now - value if value > now: return "right now" elif delta.days > 365: return '%d years ago' % (...
def check_url(form, field): """Check url schema.""" url = field.data.strip() if not url: return result = urlparse(url) if result.scheme == "": field.data = "http://%s" % re.sub(r'^:?/*', '', url)
def encode(something): """Encode something with SECRET_KEY.""" secret_key = current_app.config.get('SECRET_KEY') s = URLSafeSerializer(secret_key) return s.dumps(something)
def decode(something): """Decode something with SECRET_KEY.""" secret_key = current_app.config.get('SECRET_KEY') s = URLSafeSerializer(secret_key) try: return s.loads(something) except BadSignature: return None
def jsonify(func): """JSON decorator.""" @functools.wraps(func) def wrapper(*args, **kwargs): r = func(*args, **kwargs) if isinstance(r, tuple): code, data = r else: code, data = 200, r return Response(json.dumps(data), status=code, mimetype='applicat...
def absolute_url_for(endpoint, **values): """Absolute url for endpoint.""" config = current_app.config site_domain = config.get('SITE_DOMAIN') relative_url = url_for(endpoint, **values) return join_url(site_domain, relative_url)
def load_config(): """Load config.""" mode = os.environ.get('MODE') try: if mode == 'PRODUCTION': from .production import ProductionConfig return ProductionConfig elif mode == 'TESTING': from .testing import TestingConfig return TestingConfig ...
def signin_user(user, permenent=True): """Sign in user.""" session.permanent = permenent session['user_id'] = user.id
def get_current_user(): """Get current user.""" if not 'user_id' in session: return None user = User.query.filter(User.id == session['user_id']).first() if not user: signout_user() return None return user
def signin(): """Signin""" form = SigninForm() if form.validate_on_submit(): signin_user(form.user) return redirect(url_for('site.index')) return render_template('account/signin/signin.html', form=form)
def signup(): """Signup""" form = SignupForm() if form.validate_on_submit(): params = form.data.copy() params.pop('repassword') user = User(**params) db.session.add(user) db.session.commit() signin_user(user) return redirect(url_for('site.index')) ...
def create_app(): """Create Flask app.""" config = load_config() app = Flask(__name__) app.config.from_object(config) # Proxy fix app.wsgi_app = ProxyFix(app.wsgi_app) # CSRF protect CsrfProtect(app) if app.debug or app.testing: DebugToolbarExtension(app) # Serve...
def register_jinja(app): """Register jinja filters, vars, functions.""" import jinja2 from .utils import filters, permissions, helpers if app.debug or app.testing: my_loader = jinja2.ChoiceLoader([ app.jinja_loader, jinja2.FileSystemLoader([ os.path.join(...
def register_routes(app): """Register routes.""" from . import controllers from flask.blueprints import Blueprint for module in _import_submodules_from_package(controllers): bp = getattr(module, 'bp') if bp and isinstance(bp, Blueprint): app.register_blueprint(bp)
def register_error_handle(app): """Register HTTP error pages.""" @app.errorhandler(403) def page_403(error): return render_template('site/403/403.html'), 403 @app.errorhandler(404) def page_404(error): return render_template('site/404/404.html'), 404 @app.errorhandler(500) ...
def register_hooks(app): """Register hooks.""" @app.before_request def before_request(): g.user = get_current_user() if g.user and g.user.is_admin: g._before_request_time = time.time() @app.after_request def after_request(response): if hasattr(g, '_before_reques...
def _dataframe_to_csv(writer, dataframe, delimiter, with_header): """serialize the dataframe with different delimiters""" encoding_writer = codecs.getwriter('utf-8')(writer) dataframe.to_csv( path_or_buf=encoding_writer, sep=delimiter, header=with_header, index=False )
def _dataframe_from_csv(reader, delimiter, with_header, skipspace): """Returns csv data as a pandas Dataframe object""" sep = delimiter header = 0 if not with_header: header = None return pd.read_csv( reader, header=header, sep=sep, skipinitialspace=skipspace...
def serialize_dataframe(writer, data_type_id, dataframe): """ Serialize a dataframe. Parameters ---------- writer : file File-like object to write to. Must be opened in binary mode. data_type_id : dict Serialization format to use. See the azureml.DataTypeIds class for co...
def deserialize_dataframe(reader, data_type_id): """ Deserialize a dataframe. Parameters ---------- reader : file File-like object to read from. Must be opened in binary mode. data_type_id : dict Serialization format of the raw data. See the azureml.DataTypeIds class for...
def _update_from_dataframe(self, dataframe, data_type_id=None, name=None, description=None): """ Serialize the specified DataFrame and replace the existing dataset. Parameters ---------- dataframe : pandas.DataFrame Data to serialize. ...
def _update_from_raw_data(self, raw_data, data_type_id=None, name=None, description=None): """ Upload already serialized raw data and replace the existing dataset. Parameters ---------- raw_data: bytes Dataset contents to upload. ...
def contents_url(self): """Full URL to the dataset contents.""" loc = self.download_location return loc.base_uri + loc.location + loc.access_credential
def add_from_dataframe(self, dataframe, data_type_id, name, description): """ Serialize the specified DataFrame and upload it as a new dataset. Parameters ---------- dataframe : pandas.DataFrame Data to serialize. data_type_id : str Format to seri...
def add_from_raw_data(self, raw_data, data_type_id, name, description): """ Upload already serialized raw data as a new dataset. Parameters ---------- raw_data: bytes Dataset contents to upload. data_type_id : str Serialization format of the raw d...
def open(self): '''Open and return a stream for the dataset contents.''' return self.workspace._rest.open_intermediate_dataset_contents( self.workspace.workspace_id, self.experiment.experiment_id, self.node_id, self.port_name )
def read_as_binary(self): '''Read and return the dataset contents as binary.''' return self.workspace._rest.read_intermediate_dataset_contents_binary( self.workspace.workspace_id, self.experiment.experiment_id, self.node_id, self.port_name )
def read_as_text(self): '''Read and return the dataset contents as text.''' return self.workspace._rest.read_intermediate_dataset_contents_text( self.workspace.workspace_id, self.experiment.experiment_id, self.node_id, self.port_name )
def _to_dataframe(self): """Read and return the dataset contents as a pandas DataFrame.""" #TODO: figure out why passing in the opened stream directly gives invalid data data = self.read_as_binary() reader = BytesIO(data) return deserialize_dataframe(reader, self.data_type_id)
def get_intermediate_dataset(self, node_id, port_name, data_type_id): """ Get an intermediate dataset. Parameters ---------- node_id : str Module node id from the experiment graph. port_name : str Output port of the module. data_type_id : ...
def get_experiments(self, workspace_id): """Runs HTTP GET request to retrieve the list of experiments.""" api_path = self.EXPERIMENTS_URI_FMT.format(workspace_id) return self._send_get_req(api_path)
def get_datasets(self, workspace_id): """Runs HTTP GET request to retrieve the list of datasets.""" api_path = self.DATASOURCES_URI_FMT.format(workspace_id) return self._send_get_req(api_path)
def get_dataset(self, workspace_id, dataset_id): """Runs HTTP GET request to retrieve a single dataset.""" api_path = self.DATASOURCE_URI_FMT.format(workspace_id, dataset_id) return self._send_get_req(api_path)
def publish(func_or_workspace_id, workspace_id_or_token = None, workspace_token_or_none = None, files=(), endpoint=None): '''publishes a callable function or decorates a function to be published. Returns a callable, iterable object. Calling the object will invoke the published service. Iterating the object will...
def service(url, api_key, help_url = None): '''Marks a function as having been published and causes all invocations to go to the remote operationalized service. >>> @service(url, api_key) >>> def f(a, b): >>> pass ''' def do_publish(func): return published(url, api_key, help_url, func, None) re...
def types(**args): """Specifies the types used for the arguments of a published service. @types(a=int, b = str) def f(a, b): pass """ def l(func): if hasattr(func, '__annotations__'): func.__annotations__.update(args) else: func.__annotations__ = args return ...
def returns(type): """Specifies the return type for a published service. @returns(int) def f(...): pass """ def l(func): if hasattr(func, '__annotations__'): func.__annotations__['return'] = type else: func.__annotations__ = {'return': type} return func r...
def attach(name, contents = None): """attaches a file to the payload to be uploaded. If contents is omitted the file is read from disk. If name is a tuple it specifies the on-disk filename and the destination filename. """ def do_attach(func): if hasattr(func, '__attachments__'): func.__att...
def find_globals(code): """walks the byte code to find the variables which are actually globals""" cur_byte = 0 byte_code = code.co_code names = set() while cur_byte < len(byte_code): op = ord(byte_code[cur_byte]) if op >= dis.HAVE_ARGUMENT: ...
def map(self, *args): """maps the function onto multiple inputs. The input should be multiple sequences. The sequences will be zipped together forming the positional arguments for the call. This is equivalent to map(func, ...) but is executed with a single network call.""" call_args = [self._map_args...
def copy(self): """Create a copy of this pen.""" pen = Pen() pen.__dict__ = self.__dict__.copy() return pen
def lookup_color(c): """Return RGBA values of color c c should be either an X11 color or a brewer color set and index e.g. "navajowhite", "greens3/2" """ import sys import gi gi.require_version('Gtk', '3.0') gi.require_version('PangoCairo', '1.0') from gi.repository import Gdk ...
def draw(self, cr, highlight=False, bounding=None): """Draw this shape with the given cairo context""" if bounding is None or self._intersects(bounding): self._draw(cr, highlight, bounding)
def _cubic_bernstein_extrema(p0, p1, p2, p3): """ Find extremas of a function of real domain defined by evaluating a cubic bernstein polynomial of given bernstein coefficients. """ # compute coefficients of derivative a = 3.*(p3-p0+3.*(p1-p2)) b = 6.*(p0+p2-2.*p1)...
def _cubic_bernstein(p0, p1, p2, p3, t): """ Evaluate polynomial of given bernstein coefficients using de Casteljau's algorithm. """ u = 1 - t return p0*(u**3) + 3*t*u*(p1*u + p2*t) + p3*(t**3)
def _build_choices(self): """Build choices list runtime using 'sitetree_tree' tag""" tree_token = u'sitetree_tree from "%s" template "%s"' % (self.tree, self.template) context_kwargs = {'current_app': 'admin'} context = template.Context(context_kwargs) if VERSION >= (1, 8) else template...
def options_getter(command_options): """Compatibility function to get rid of optparse in management commands after Django 1.10. :param tuple command_options: tuple with `CommandOption` objects. """ def get_options(option_func=None): from optparse import make_option from django.core.man...
def get_sitetree(): """Returns SiteTree (thread-singleton) object, implementing utility methods. :rtype: SiteTree """ sitetree = getattr(_THREAD_LOCAL, _THREAD_SITETREE, None) if sitetree is None: sitetree = SiteTree() setattr(_THREAD_LOCAL, _THREAD_SITETREE, sitetree) return ...
def register_items_hook(func): """Registers a hook callable to process tree items right before they are passed to templates. Callable should be able to: a) handle ``tree_items`` and ``tree_sender`` key params. ``tree_items`` will contain a list of extended TreeItem objects ready to pass to...
def register_dynamic_trees(trees, *args, **kwargs): """Registers dynamic trees to be available for `sitetree` runtime. Expects `trees` to be an iterable with structures created with `compose_dynamic_tree()`. Example:: register_dynamic_trees( # Get all the trees from `my_app`. ...
def compose_dynamic_tree(src, target_tree_alias=None, parent_tree_item_alias=None, include_trees=None): """Returns a structure describing a dynamic sitetree.utils The structure can be built from various sources, :param str|iterable src: If a string is passed to `src`, it'll be treated as the name of an app...
def init(self): """Initializes local cache from Django cache.""" # Drop cache flag set by .reset() method. cache.get('sitetrees_reset') and self.empty(init=False) self.cache = cache.get( 'sitetrees', {'sitetrees': {}, 'parents': {}, 'items_by_ids': {}, 'tree_aliases': {}})
def empty(self, **kwargs): """Empties cached sitetree data.""" cache.delete('sitetrees') cache.delete('sitetrees_reset') kwargs.get('init', True) and self.init()
def get_entry(self, entry_name, key): """Returns cache entry parameter value by its name. :param str|unicode entry_name: :param key: :return: """ return self.cache[entry_name].get(key, False)
def update_entry_value(self, entry_name, key, value): """Updates cache entry parameter with new data. :param str|unicode entry_name: :param key: :param value: """ if key not in self.cache[entry_name]: self.cache[entry_name][key] = {} self.cache[entry...
def set_entry(self, entry_name, key, value): """Replaces entire cache entry parameter data by its name with new data. :param str|unicode entry_name: :param key: :param value: """ self.cache[entry_name][key] = value
def init(self, context): """Initializes sitetree to handle new request. :param Context|None context: """ self.cache = Cache() self.current_page_context = context self.current_request = context.get('request', None) if context else None self.current_lang = get_lang...
def resolve_tree_i18n_alias(self, alias): """Resolves internationalized tree alias. Verifies whether a separate sitetree is available for currently active language. If so, returns i18n alias. If not, returns the initial alias. :param str|unicode alias: :rtype: str|unicode ...
def attach_dynamic_tree_items(tree_alias, src_tree_items): """Attaches dynamic sitetrees items registered with `register_dynamic_trees()` to an initial (source) items list. :param str|unicode tree_alias: :param list src_tree_items: :rtype: list """ if not _DYNAMI...
def current_app_is_admin(self): """Returns boolean whether current application is Admin contrib. :rtype: bool """ is_admin = self._current_app_is_admin if is_admin is None: context = self.current_page_context current_app = getattr( # Try ...
def get_sitetree(self, alias): """Gets site tree items from the given site tree. Caches result to dictionary. Returns (tree alias, tree items) tuple. :param str|unicode alias: :rtype: tuple """ cache_ = self.cache get_cache_entry = cache_.get_entry ...
def calculate_item_depth(self, tree_alias, item_id, depth=0): """Calculates depth of the item in the tree. :param str|unicode tree_alias: :param int item_id: :param int depth: :rtype: int """ item = self.get_item_by_id(tree_alias, item_id) if hasattr(ite...
def get_tree_current_item(self, tree_alias): """Resolves current tree item of 'tree_alias' tree matching current request path against URL of given tree item. :param str|unicode tree_alias: :rtype: TreeItemBase """ current_item = self._current_items.get(tree_alias, _UNSET...
def url(self, sitetree_item, context=None): """Resolves item's URL. :param TreeItemBase sitetree_item: TreeItemBase heir object, 'url' property of which is processed as URL pattern or simple URL. :param Context context: :rtype: str|unicode """ context = con...
def init_tree(self, tree_alias, context): """Initializes sitetree in memory. Returns tuple with resolved tree alias and items on success. On fail returns (None, None). :param str|unicode tree_alias: :param Context context: :rtype: tuple """ request = co...
def get_current_page_attr(self, attr_name, tree_alias, context): """Returns an arbitrary attribute of a sitetree item resolved as current for current page. :param str|unicode attr_name: :param str|unicode tree_alias: :param Context context: :rtype: str|unicode """ ...
def get_ancestor_level(self, current_item, depth=1): """Returns ancestor of level `deep` recursively :param TreeItemBase current_item: :param int depth: :rtype: TreeItemBase """ if current_item.parent is None: return current_item if depth <= 1: ...
def menu(self, tree_alias, tree_branches, context): """Builds and returns menu structure for 'sitetree_menu' tag. :param str|unicode tree_alias: :param str|unicode tree_branches: :param Context context: :rtype: list|str """ tree_alias, sitetree_items = self.init_...
def apply_hook(self, items, sender): """Applies item processing hook, registered with ``register_item_hook()`` to items supplied, and returns processed list. Returns initial items list if no hook is registered. :param list items: :param str|unicode sender: menu, breadcrumbs, si...
def check_access(self, item, context): """Checks whether a current user has an access to a certain item. :param TreeItemBase item: :param Context context: :rtype: bool """ if hasattr(self.current_request.user.is_authenticated, '__call__'): authenticated = sel...