code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _get_init_containers(self): """When using git to retrieve the DAGs, use the GitSync Init Container""" # If we're using volume claims to mount the dags, no init container is needed if self.kube_config.dags_volume_claim or \ self.kube_config.dags_volume_host or self.kube_config.dags...
When using git to retrieve the DAGs, use the GitSync Init Container
def operator_relocate(self, graph, solution, op_diff_round_digits, anim): """applies Relocate inter-route operator to solution Takes every node from every route and calculates savings when inserted into all possible positions in other routes. Insertion is done at position with m...
applies Relocate inter-route operator to solution Takes every node from every route and calculates savings when inserted into all possible positions in other routes. Insertion is done at position with max. saving and procedure starts over again with newly created graph as input....
def from_dict(cls, d): """ Create an instance from a dictionary. """ assert isinstance(d, dict) init_args = dict() for key, is_required in cls.dictionary_attributes.iteritems(): try: init_args[key] = d[key] except KeyError: ...
Create an instance from a dictionary.
def binary(self): """Load and return the path to the native engine binary.""" lib_name = '{}.so'.format(NATIVE_ENGINE_MODULE) lib_path = os.path.join(safe_mkdtemp(), lib_name) try: with closing(pkg_resources.resource_stream(__name__, lib_name)) as input_fp: # NB: The header stripping code ...
Load and return the path to the native engine binary.
def add_download(self, info, future): """ Hand off a download to the Downloads plugin, if it is present. Parameters ---------- info : `~ginga.misc.Bunch.Bunch` A bunch of information about the URI as returned by `ginga.util.iohelper.get_fileinfo()` ...
Hand off a download to the Downloads plugin, if it is present. Parameters ---------- info : `~ginga.misc.Bunch.Bunch` A bunch of information about the URI as returned by `ginga.util.iohelper.get_fileinfo()` future : `~ginga.misc.Future.Future` A futu...
def upload_service_version(self, service_zip_file, mode='production', service_version='default', service_id=None, **kwargs): ''' upload_service_version(self, service_zip_file, mode='production', service_version='default', service_id=None, **kwargs) Upload a service version to Opereto :...
upload_service_version(self, service_zip_file, mode='production', service_version='default', service_id=None, **kwargs) Upload a service version to Opereto :Parameters: * *service_zip_file* (`string`) -- zip file location containing service and service specification * *mode* (`string`)...
def _justify(texts, max_len, mode='right'): """ Perform ljust, center, rjust against string or list-like """ if mode == 'left': return [x.ljust(max_len) for x in texts] elif mode == 'center': return [x.center(max_len) for x in texts] else: return [x.rjust(max_len) for x i...
Perform ljust, center, rjust against string or list-like
def plot_info(self, dvs): ''' Plots miscellaneous de-trending information on the data validation summary figure. :param dvs: A :py:class:`dvs.DVS` figure instance ''' axl, axc, axr = dvs.title() axc.annotate("%s %d" % (self._mission.IDSTRING, self.ID), ...
Plots miscellaneous de-trending information on the data validation summary figure. :param dvs: A :py:class:`dvs.DVS` figure instance
def rupdate(source, target): ''' recursively update nested dictionaries see: http://stackoverflow.com/a/3233356/1289080 ''' for k, v in target.iteritems(): if isinstance(v, Mapping): r = rupdate(source.get(k, {}), v) source[k] = r else: source[k] =...
recursively update nested dictionaries see: http://stackoverflow.com/a/3233356/1289080
def get_file_metadata(self, secure_data_path, version=None): """Get just the metadata for a file, not the content""" if not version: version = "CURRENT" payload = {'versionId': str(version)} secret_resp = head_with_retry(str.join('', [self.cerberus_url, '/v1/secure-file/', s...
Get just the metadata for a file, not the content
def crossref_paths(self): """Just like crossrefs, but all the targets are munged to :all.""" return set( [address.new(repo=x.repo, path=x.path) for x in self.crossrefs])
Just like crossrefs, but all the targets are munged to :all.
def add_method(self, loop, callback): """Add a coroutine function Args: loop: The :class:`event loop <asyncio.BaseEventLoop>` instance on which to schedule callbacks callback: The :term:`coroutine function` to add """ f, obj = get_method_vars(call...
Add a coroutine function Args: loop: The :class:`event loop <asyncio.BaseEventLoop>` instance on which to schedule callbacks callback: The :term:`coroutine function` to add
def gml_to_geojson(el): """Given an lxml Element of a GML geometry, returns a dict in GeoJSON format.""" if el.get('srsName') not in ('urn:ogc:def:crs:EPSG::4326', None): if el.get('srsName') == 'EPSG:4326': return _gmlv2_to_geojson(el) else: raise NotImplementedError("Un...
Given an lxml Element of a GML geometry, returns a dict in GeoJSON format.
def convert_entry_to_path(path): # type: (Dict[S, Union[S, bool, Tuple[S], List[S]]]) -> S """Convert a pipfile entry to a string""" if not isinstance(path, Mapping): raise TypeError("expecting a mapping, received {0!r}".format(path)) if not any(key in path for key in ["file", "path"]): ...
Convert a pipfile entry to a string
def AddPathInfo(self, path_info): """Updates existing path information of the path record.""" if self._path_type != path_info.path_type: message = "Incompatible path types: `%s` and `%s`" raise ValueError(message % (self._path_type, path_info.path_type)) if self._components != path_info.compone...
Updates existing path information of the path record.
def main(args=None): """Call the CLI interface and wait for the result.""" retcode = 0 try: ci = CliInterface() args = ci.parser.parse_args() result = args.func(args) if result is not None: print(result) retcode = 0 except Exception: retcode = ...
Call the CLI interface and wait for the result.
def write_json(self, chunk, code=None, headers=None): """A convenient method that binds `chunk`, `code`, `headers` together chunk could be any type of (str, dict, list) """ assert chunk is not None, 'None cound not be written in write_json' self.set_header("Content-Type", "appli...
A convenient method that binds `chunk`, `code`, `headers` together chunk could be any type of (str, dict, list)
def distance_to_point(self, point): """ Computes the absolute distance from the plane to the point :param point: Point for which distance is computed :return: Distance between the plane and the point """ return np.abs(np.dot(self.normal_vector, point) + self.d)
Computes the absolute distance from the plane to the point :param point: Point for which distance is computed :return: Distance between the plane and the point
def create_file(self, path, message, content, branch=github.GithubObject.NotSet, committer=github.GithubObject.NotSet, author=github.GithubObject.NotSet): """Create a file in this repository. :calls: `PUT /repos/:owner/:repo/contents/:path <ht...
Create a file in this repository. :calls: `PUT /repos/:owner/:repo/contents/:path <http://developer.github.com/v3/repos/contents#create-a-file>`_ :param path: string, (required), path of the file in the repository :param message: string, (required), commit message :param content: string...
def do_imageplaceholder(parser, token): """ Method that parse the imageplaceholder template tag. """ name, params = parse_placeholder(parser, token) return ImagePlaceholderNode(name, **params)
Method that parse the imageplaceholder template tag.
def exec_action(module, action, module_parameter=None, action_parameter=None, state_only=False): ''' Execute an arbitrary action on a module. module name of the module to be executed action name of the module's action to be run module_parameter additional params passed to ...
Execute an arbitrary action on a module. module name of the module to be executed action name of the module's action to be run module_parameter additional params passed to the defined module action_parameter additional params passed to the defined action state_on...
def read(self, length, timeout=None): """Read up to `length` number of bytes from the serial port with an optional timeout. `timeout` can be positive for a timeout in seconds, 0 for a non-blocking read, or negative or None for a blocking read that will block until `length` numbe...
Read up to `length` number of bytes from the serial port with an optional timeout. `timeout` can be positive for a timeout in seconds, 0 for a non-blocking read, or negative or None for a blocking read that will block until `length` number of bytes are read. Default is a blocking ...
def _external_request(self, method, url, *args, **kwargs): """ Wrapper for requests.get with useragent automatically set. And also all requests are reponses are cached. """ self.last_url = url if url in self.responses.keys() and method == 'get': return self.re...
Wrapper for requests.get with useragent automatically set. And also all requests are reponses are cached.
def write_eps(matrix, version, out, scale=1, border=None, color='#000', background=None): """\ Serializes the QR Code as EPS document. :param matrix: The matrix to serialize. :param int version: The (Micro) QR code version :param out: Filename or a file-like object supporting to write...
\ Serializes the QR Code as EPS document. :param matrix: The matrix to serialize. :param int version: The (Micro) QR code version :param out: Filename or a file-like object supporting to write strings. :param scale: Indicates the size of a single module (default: 1 which corresponds to ...
def __insert_action(self, revision): """ Handle the insert action type. Creates new document to be created in this collection. This allows you to stage a creation of an object :param dict revision: The revision dictionary """ revision["patch"]["_id"] = ObjectI...
Handle the insert action type. Creates new document to be created in this collection. This allows you to stage a creation of an object :param dict revision: The revision dictionary
def read_envvar_file(name, extension): """ Read values from a file provided as a environment variable ``NAME_CONFIG_FILE``. :param name: environment variable prefix to look for (without the ``_CONFIG_FILE``) :param extension: *(unused)* :return: a `.Configuration`, possibly `.NotConfigu...
Read values from a file provided as a environment variable ``NAME_CONFIG_FILE``. :param name: environment variable prefix to look for (without the ``_CONFIG_FILE``) :param extension: *(unused)* :return: a `.Configuration`, possibly `.NotConfigured`
def compactor_daemon(conf_file): """ Run the compactor daemon. :param conf_file: Name of the configuration file. """ eventlet.monkey_patch() conf = config.Config(conf_file=conf_file) compactor.compactor(conf)
Run the compactor daemon. :param conf_file: Name of the configuration file.
def flatten(d, reducer='tuple', inverse=False): """Flatten dict-like object. Parameters ---------- d: dict-like object The dict that will be flattened. reducer: {'tuple', 'path', function} (default: 'tuple') The key joining method. If a function is given, the function will be ...
Flatten dict-like object. Parameters ---------- d: dict-like object The dict that will be flattened. reducer: {'tuple', 'path', function} (default: 'tuple') The key joining method. If a function is given, the function will be used to reduce. 'tuple': The resulting key wi...
def getSimilarTermsForExpression(self, body, contextId=None, posType=None, getFingerprint=None, startIndex=0, maxResults=10, sparsity=1.0): """Get similar terms for the contexts of an expression Args: body, ExpressionOperation: The JSON encoded expression to be evaluated (required) ...
Get similar terms for the contexts of an expression Args: body, ExpressionOperation: The JSON encoded expression to be evaluated (required) contextId, int: The identifier of a context (optional) posType, str: Part of speech (optional) getFingerprint, bool: Configu...
def get_data(self, linesep=os.linesep): """ Serialize the section and return it as bytes :return bytes """ stream = BytesIO() self.store(stream, linesep) return stream.getvalue()
Serialize the section and return it as bytes :return bytes
def get(self, key, filepath): """Get configuration parameter. Reads 'key' configuration parameter from the configuration file given in 'filepath'. Configuration parameter in 'key' must follow the schema <section>.<option> . :param key: key to get :param filepath: config...
Get configuration parameter. Reads 'key' configuration parameter from the configuration file given in 'filepath'. Configuration parameter in 'key' must follow the schema <section>.<option> . :param key: key to get :param filepath: configuration file
def get_applicable_overlays(self, error_bundle): """ Given an error bundle, a list of overlays that are present in the current package or subpackage are returned. """ content_paths = self.get_triples(subject='content') if not content_paths: return set() ...
Given an error bundle, a list of overlays that are present in the current package or subpackage are returned.
def timestamp_to_microseconds(timestamp): """Convert a timestamp string into a microseconds value :param timestamp :return time in microseconds """ timestamp_str = datetime.datetime.strptime(timestamp, ISO_DATETIME_REGEX) epoch_time_secs = calendar.timegm(timestamp_str.timetuple()) epoch_tim...
Convert a timestamp string into a microseconds value :param timestamp :return time in microseconds
def _map_relation(c, language='any'): """ Map related concept or collection, leaving out the relations. :param c: the concept or collection to map :param string language: Language to render the relation's label in :rtype: :class:`dict` """ label = c.label(language) return { 'id'...
Map related concept or collection, leaving out the relations. :param c: the concept or collection to map :param string language: Language to render the relation's label in :rtype: :class:`dict`
def fix_deplist(deps): """ Turn a dependency list into lowercase, and make sure all entries that are just a string become a tuple of strings """ deps = [ ((dep.lower(),) if not isinstance(dep, (list, tuple)) else tuple([dep_entry.lower() for dep_entry i...
Turn a dependency list into lowercase, and make sure all entries that are just a string become a tuple of strings
def jpl_horizons_ephemeris( log, objectId, mjd, obscode=500, verbose=False): """Given a known solar-system object ID (human-readable name, MPC number or MPC packed format) and one or more specific epochs, return the calculated ephemerides **Key Arguments:** - ``...
Given a known solar-system object ID (human-readable name, MPC number or MPC packed format) and one or more specific epochs, return the calculated ephemerides **Key Arguments:** - ``log`` -- logger - ``objectId`` -- human-readable name, MPC number or MPC packed format id of the solar-system object...
def multiple_paths_parser(value): """Parses data_path argument. Parameters ---------- value : str a string of data paths separated by ":". Returns ------- value : list a list of strings indicating each data paths. """ if isinstance(value, six.string_types): ...
Parses data_path argument. Parameters ---------- value : str a string of data paths separated by ":". Returns ------- value : list a list of strings indicating each data paths.
def array_equivalent(left, right, strict_nan=False): """ True if two arrays, left and right, have equal non-NaN elements, and NaNs in corresponding locations. False otherwise. It is assumed that left and right are NumPy arrays of the same dtype. The behavior of this function (particularly with resp...
True if two arrays, left and right, have equal non-NaN elements, and NaNs in corresponding locations. False otherwise. It is assumed that left and right are NumPy arrays of the same dtype. The behavior of this function (particularly with respect to NaNs) is not defined if the dtypes are different. ...
def stop(ctx, yes): """Stops the tensorboard deployment for project/experiment/experiment group if it exists. Uses [Caching](/references/polyaxon-cli/#caching) Examples: stopping project tensorboard \b ```bash $ polyaxon tensorboard stop ``` Examples: stopping experiment group tensor...
Stops the tensorboard deployment for project/experiment/experiment group if it exists. Uses [Caching](/references/polyaxon-cli/#caching) Examples: stopping project tensorboard \b ```bash $ polyaxon tensorboard stop ``` Examples: stopping experiment group tensorboard \b ```bash ...
def _post_start(self): """Set stdout to non-blocking VLC does not always return a newline when reading status so in order to be lazy and still use the read API without caring about how much output there is we switch stdout to nonblocking mode and just read a large chunk of datin...
Set stdout to non-blocking VLC does not always return a newline when reading status so in order to be lazy and still use the read API without caring about how much output there is we switch stdout to nonblocking mode and just read a large chunk of datin order to be lazy and still use th...
def paintEvent(self, event): """ Paints the background for the dock toolbar. :param event | <QPaintEvent> """ x = 1 y = 1 w = self.width() h = self.height() clr_a = QColor(220, 220, 220) clr_b = QColor(190...
Paints the background for the dock toolbar. :param event | <QPaintEvent>
def _drawForeground(self, scene, painter, rect): """ Draws the backgroud for a particular scene within the charts. :param scene | <XChartScene> painter | <QPainter> rect | <QRectF> """ rect = scene.sceneRect() ...
Draws the backgroud for a particular scene within the charts. :param scene | <XChartScene> painter | <QPainter> rect | <QRectF>
def find_guests(names, path=None): ''' Return a dict of hosts and named guests path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 ''' ret = {} names = names.split(',') for data in _list_iter(path=path): host,...
Return a dict of hosts and named guests path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0
def parse_stream(self, stream: BytesIO, context=None): """ Parse some python object from the stream. :param stream: Stream from which the data is read and parsed. :param context: Optional context dictionary. """ if context is None: context = Context() ...
Parse some python object from the stream. :param stream: Stream from which the data is read and parsed. :param context: Optional context dictionary.
def verify(self): """ Access the Verify Twilio Domain :returns: Verify Twilio Domain :rtype: twilio.rest.verify.Verify """ if self._verify is None: from twilio.rest.verify import Verify self._verify = Verify(self) return self._verify
Access the Verify Twilio Domain :returns: Verify Twilio Domain :rtype: twilio.rest.verify.Verify
def normalize_so_name(name): """ Handle different types of python installations """ if "cpython" in name: return os.path.splitext(os.path.splitext(name)[0])[0] # XXX: Special handling for Fedora python2 distribution # See: https://github.com/python-rope/rope/issues/211 if name == "ti...
Handle different types of python installations
def detect_branchings(self): """Detect all branchings up to `n_branchings`. Writes Attributes ----------------- segs : np.ndarray List of integer index arrays. segs_tips : np.ndarray List of indices of the tips of segments. """ logg.m(' ...
Detect all branchings up to `n_branchings`. Writes Attributes ----------------- segs : np.ndarray List of integer index arrays. segs_tips : np.ndarray List of indices of the tips of segments.
def chr(self): """the reference chromosome. greedy return the first chromosome in exon array :return: chromosome :rtype: string """ if len(self.exons)==0: sys.stderr.write("WARNING can't return chromsome with nothing here\n") return None return self._rngs[0].chr
the reference chromosome. greedy return the first chromosome in exon array :return: chromosome :rtype: string
def _check_rel(attrs, rel_whitelist, rel_blacklist): """ Check a link's relations against the whitelist or blacklist. First, this will reject based on blacklist. Next, if there is a whitelist, there must be at least one rel that matches. To explicitly allow links without a rel you can ...
Check a link's relations against the whitelist or blacklist. First, this will reject based on blacklist. Next, if there is a whitelist, there must be at least one rel that matches. To explicitly allow links without a rel you can add None to the whitelist (e.g. ['in-reply-to',None])
def draw_line(self, img, pixmapper, pt1, pt2, colour, linewidth): '''draw a line on the image''' pix1 = pixmapper(pt1) pix2 = pixmapper(pt2) (width, height) = image_shape(img) (ret, pix1, pix2) = cv2.clipLine((0, 0, width, height), pix1, pix2) if ret is False: ...
draw a line on the image
def load_models(*chain, **kwargs): """ Decorator to load a chain of models from the given parameters. This works just like :func:`load_model` and accepts the same parameters, with some small differences. :param chain: The chain is a list of tuples of (``model``, ``attributes``, ``parameter``). ...
Decorator to load a chain of models from the given parameters. This works just like :func:`load_model` and accepts the same parameters, with some small differences. :param chain: The chain is a list of tuples of (``model``, ``attributes``, ``parameter``). Lists and tuples can be used interchangeably. A...
def verify_item_signature(signature_attribute, encrypted_item, verification_key, crypto_config): # type: (dynamodb_types.BINARY_ATTRIBUTE, dynamodb_types.ITEM, DelegatedKey, CryptoConfig) -> None """Verify the item signature. :param dict signature_attribute: Item signature DynamoDB attribute value :par...
Verify the item signature. :param dict signature_attribute: Item signature DynamoDB attribute value :param dict encrypted_item: Encrypted DynamoDB item :param DelegatedKey verification_key: DelegatedKey to use to calculate the signature :param CryptoConfig crypto_config: Cryptographic configuration
def get_overall_services_health(self) -> str: """Get the overall health of all the services. Returns: str, overall health status """ services_health_status = self.get_services_health() # Evaluate overall health health_status = all(status == "Healthy" for st...
Get the overall health of all the services. Returns: str, overall health status
def _wrap_handling(kwargs): """ Starts running a queue handler and creates a log file for the queue.""" _configure_logging(kwargs, extract=False) # Main job, make the listener to the queue start receiving message for writing to disk. handler=kwargs['handler'] graceful_exit = kwargs['graceful_exit'] ...
Starts running a queue handler and creates a log file for the queue.
def OnApprove(self, event): """File approve event handler""" if not self.main_window.safe_mode: return msg = _(u"You are going to approve and trust a file that\n" u"you have not created yourself.\n" u"After proceeding, the file is executed.\n \n" ...
File approve event handler
def to_dict(self): """convert detailed proxy info into a dict Returns: dict: A dict with four keys: ``addr``, ``protocol``, ``weight`` and ``last_checked`` """ return dict( addr=self.addr, protocol=self.protocol, weight=s...
convert detailed proxy info into a dict Returns: dict: A dict with four keys: ``addr``, ``protocol``, ``weight`` and ``last_checked``
def http_adapter_kwargs(): """ Provides Zenpy's default HTTPAdapter args for those users providing their own adapter. """ return dict( # Transparently retry requests that are safe to retry, with the exception of 429. This is handled # in the Api._call_api() metho...
Provides Zenpy's default HTTPAdapter args for those users providing their own adapter.
def timeline_list(self, id, max_id=None, min_id=None, since_id=None, limit=None): """ Fetches a timeline containing all the toots by users in a given list. Returns a list of `toot dicts`_. """ id = self.__unpack_id(id) return self.timeline('list/{0}'.format(id), max_id=m...
Fetches a timeline containing all the toots by users in a given list. Returns a list of `toot dicts`_.
def parse(self, request): """ Parse request content. :return dict: parsed data. """ if request.method in ('POST', 'PUT', 'PATCH'): content_type = self.determine_content(request) if content_type: split = content_type.split(';', 1) ...
Parse request content. :return dict: parsed data.
def _match_serializers_by_accept_headers(self, serializers, default_media_type): """Match serializer by `Accept` headers.""" # Bail out fast if no accept headers were given. if len(request.accept_mimetypes) == 0: return serializers[default...
Match serializer by `Accept` headers.
def _connected(self, sock): """When the socket is writtable, the socket is ready to be used.""" logger.debug('socket connected, building protocol') self.protocol = self.factory.build(self.loop) self.connection = Connection(self.loop, self.sock, self.addr, self.protocol, self)...
When the socket is writtable, the socket is ready to be used.
def check_permissions(self, request): """Permission checking for DRF.""" objs = [None] if hasattr(self, 'get_perms_objects'): objs = self.get_perms_objects() else: if hasattr(self, 'get_object'): try: objs = [self.get_object()] ...
Permission checking for DRF.
def _write_rigid_information(xml_file, rigid_bodies): """Write rigid body information. Parameters ---------- xml_file : file object The file object of the hoomdxml file being written rigid_bodies : list, len=n_particles The rigid body that each particle belongs to (-1 for none) ...
Write rigid body information. Parameters ---------- xml_file : file object The file object of the hoomdxml file being written rigid_bodies : list, len=n_particles The rigid body that each particle belongs to (-1 for none)
def is_address_valid(self, address): """ Determines if an address is a valid user mode address. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address is a valid user mode address. @raise WindowsError: An exce...
Determines if an address is a valid user mode address. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address is a valid user mode address. @raise WindowsError: An exception is raised on error.
def p_NonAnyType_domString(p): """NonAnyType : DOMString TypeSuffix""" p[0] = helper.unwrapTypeSuffix(model.SimpleType( type=model.SimpleType.DOMSTRING), p[2])
NonAnyType : DOMString TypeSuffix
def gather_categories(imap, header, categories=None): """ Find the user specified categories in the map and create a dictionary to contain the relevant data for each type within the categories. Multiple categories will have their types combined such that each possible combination will have its own entry...
Find the user specified categories in the map and create a dictionary to contain the relevant data for each type within the categories. Multiple categories will have their types combined such that each possible combination will have its own entry in the dictionary. :type imap: dict :param imap: The...
def active_editor_buffer(self): """ The active EditorBuffer or None. """ if self.active_tab and self.active_tab.active_window: return self.active_tab.active_window.editor_buffer
The active EditorBuffer or None.
def update_range(self, share_name, directory_name, file_name, data, start_range, end_range, content_md5=None, timeout=None): ''' Writes the bytes specified by the request body into the specified range. :param str share_name: Name of existing share. ...
Writes the bytes specified by the request body into the specified range. :param str share_name: Name of existing share. :param str directory_name: The path to the directory. :param str file_name: Name of existing file. :param bytes data: ...
def fetchChildren(self): """ Fetches children. The actual work is done by _fetchAllChildren. Descendant classes should typically override that method instead of this one. """ assert self._canFetchChildren, "canFetchChildren must be True" try: childIte...
Fetches children. The actual work is done by _fetchAllChildren. Descendant classes should typically override that method instead of this one.
def set_chassis_datacenter(location, host=None, admin_username=None, admin_password=None): ''' Set the location of the chassis. location The name of the datacenter to be set on the chassis. host The chassis host...
Set the location of the chassis. location The name of the datacenter to be set on the chassis. host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. CLI Example: .. code-block::...
def pca(U, centre=False): """Compute the PCA basis for columns of input array `U`. Parameters ---------- U : array_like 2D data array with rows corresponding to different variables and columns corresponding to different observations center : bool, optional (default False) Flag ind...
Compute the PCA basis for columns of input array `U`. Parameters ---------- U : array_like 2D data array with rows corresponding to different variables and columns corresponding to different observations center : bool, optional (default False) Flag indicating whether to centre data ...
def CheckVlogArguments(filename, clean_lines, linenum, error): """Checks that VLOG() is only used for defining a logging level. For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and VLOG(FATAL) are not. Args: filename: The name of the current file. clean_lines: A CleansedLines i...
Checks that VLOG() is only used for defining a logging level. For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and VLOG(FATAL) are not. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to ...
def get(self, name, default="", parent_search=False, multikeys_search=False, __settings_temp=None, __rank_recursion=0): """ Récupération d'une configuration le paramètre ```name``` peut être soit un nom ou un chemin vers la valeur (séparateur /) ```parent_search``` est le boolean qui indique si on doi...
Récupération d'une configuration le paramètre ```name``` peut être soit un nom ou un chemin vers la valeur (séparateur /) ```parent_search``` est le boolean qui indique si on doit chercher la valeur dans la hiérarchie plus haute. Si la chaîne "/document/host/val" retourne None, on recherche dans "/doc...
def getCandScoresMapFromSamplesFile(self, profile, sampleFileName): """ Returns a dictonary that associates the integer representation of each candidate with the Bayesian utilities we approximate from the samples we generated into a file. :ivar Profile profile: A Profile object that re...
Returns a dictonary that associates the integer representation of each candidate with the Bayesian utilities we approximate from the samples we generated into a file. :ivar Profile profile: A Profile object that represents an election profile. :ivar str sampleFileName: The name of the input fi...
def update(self): """Update object properties.""" current_time = int(time.time()) last_refresh = 0 if self._last_refresh is None else self._last_refresh if current_time >= (last_refresh + self._refresh_rate): self.get_cameras_properties() self.get_ambient_sensor_...
Update object properties.
def base_prompt(self, prompt): """Extract the base prompt pattern.""" if prompt is None: return None if not self.device.is_target: return prompt pattern = pattern_manager.pattern(self.platform, "prompt_dynamic", compiled=False) pattern = pattern.format(pro...
Extract the base prompt pattern.
def updatePhysicalInterface(self, physicalInterfaceId, name, schemaId, description=None): """ Update a physical interface. Parameters: - physicalInterfaceId (string) - name (string) - schemaId (string) - description (string, optional) Throws APIExc...
Update a physical interface. Parameters: - physicalInterfaceId (string) - name (string) - schemaId (string) - description (string, optional) Throws APIException on failure.
def dump_children(self, f, indent=''): """Dump the children of the current section to a file-like object""" for child in self.__order: child.dump(f, indent+' ')
Dump the children of the current section to a file-like object
def init_app(self, app): """ Initialize this class with the specified :class:`flask.Flask` application :param app: The Flask application. """ self.__app = app self.__app.before_first_request(self.__setup) self.tracer.enabled = self.__app.config.get('TRACE_ENABL...
Initialize this class with the specified :class:`flask.Flask` application :param app: The Flask application.
def sendPassword(self, password): """send password""" pw = (password + '\0' * 8)[:8] #make sure its 8 chars long, zero padded des = RFBDes(pw) response = des.encrypt(self._challenge) self.transport.write(response)
send password
def restart(name, runas=None): ''' Unloads and reloads a launchd service. Raises an error if the service fails to reload :param str name: Service label, file name, or full path :param str runas: User to run launchctl commands :return: ``True`` if successful :rtype: bool CLI Example:...
Unloads and reloads a launchd service. Raises an error if the service fails to reload :param str name: Service label, file name, or full path :param str runas: User to run launchctl commands :return: ``True`` if successful :rtype: bool CLI Example: .. code-block:: bash salt '*...
def is_streamable(self): """Returns True if the artist is streamable.""" return bool( _number( _extract(self._request(self.ws_prefix + ".getInfo", True), "streamable") ) )
Returns True if the artist is streamable.
def connect(self, config): """Connect to database with given configuration, which may be a dict or a path to a pymatgen-db configuration. """ if isinstance(config, str): conn = dbutil.get_database(config_file=config) elif isinstance(config, dict): conn = d...
Connect to database with given configuration, which may be a dict or a path to a pymatgen-db configuration.
def zero_pad(data, count, right=True): """ Parameters -------- data : (n,) 1D array count : int Minimum length of result array Returns -------- padded : (m,) 1D array where m >= count """ if len(data) == 0: return np.zeros(count) elif len(data) < co...
Parameters -------- data : (n,) 1D array count : int Minimum length of result array Returns -------- padded : (m,) 1D array where m >= count
def smoothing_window(data, window=[1, 1, 1]): """ This is a smoothing functionality so we can fix misclassifications. It will run a sliding window of form [border, smoothing, border] on the signal and if the border elements are the same it will change the smooth elements to match the border...
This is a smoothing functionality so we can fix misclassifications. It will run a sliding window of form [border, smoothing, border] on the signal and if the border elements are the same it will change the smooth elements to match the border. An example would be for a window of [2, 1, 2...
def from_string(dir_string): '''Returns the correct constant for a given string. @raises InvalidDirectionError ''' dir_string = dir_string.upper() if dir_string == UP: return UP elif dir_string == DOWN: return DOWN elif dir_string == LEFT: return LEFT elif dir_s...
Returns the correct constant for a given string. @raises InvalidDirectionError
def dict_has_all_keys(self, keys): """ Create a boolean SArray by checking the keys of an SArray of dictionaries. An element of the output SArray is True if the corresponding input element's dictionary has all of the given keys. Fails on SArrays whose data type is not ``dict``. ...
Create a boolean SArray by checking the keys of an SArray of dictionaries. An element of the output SArray is True if the corresponding input element's dictionary has all of the given keys. Fails on SArrays whose data type is not ``dict``. Parameters ---------- keys : li...
def auto_model_name_recognize(model_name): """ 自动将 site-user 识别成 SiteUser :param model_name: :return: """ name_list = model_name.split('-') return ''.join(['%s%s' % (name[0].upper(), name[1:]) for name in name_list])
自动将 site-user 识别成 SiteUser :param model_name: :return:
def _describe_tree(self, prefix, with_transform): """Helper function to actuall construct the tree""" extra = ': "%s"' % self.name if self.name is not None else '' if with_transform: extra += (' [%s]' % self.transform.__class__.__name__) output = '' if len(prefix) > 0...
Helper function to actuall construct the tree
def date_added(self, date_added): """ Updates the security labels date_added Args: date_added: Converted to %Y-%m-%dT%H:%M:%SZ date format """ date_added = self._utils.format_datetime(date_added, date_format='%Y-%m-%dT%H:%M:%SZ') self._data['dateAdded'] = da...
Updates the security labels date_added Args: date_added: Converted to %Y-%m-%dT%H:%M:%SZ date format
def _validate_data(self, data: dict): """ Validates data against provider schema. Raises :class:`~notifiers.exceptions.BadArguments` if relevant :param data: Data to validate :raises: :class:`~notifiers.exceptions.BadArguments` """ log.debug("validating provided data") ...
Validates data against provider schema. Raises :class:`~notifiers.exceptions.BadArguments` if relevant :param data: Data to validate :raises: :class:`~notifiers.exceptions.BadArguments`
def _flatten_dicts(self, dicts): """Flatten a dict :param dicts: Flatten a dict :type dicts: list(dict) """ d = dict() list_of_dicts = [d.get() for d in dicts or []] return {k: v for d in list_of_dicts for k, v in d.items()}
Flatten a dict :param dicts: Flatten a dict :type dicts: list(dict)
def process_call(self, i2c_addr, register, value, force=None): """ Executes a SMBus Process Call, sending a 16-bit value and receiving a 16-bit response :param i2c_addr: i2c address :type i2c_addr: int :param register: Register to read/write to :type register: int ...
Executes a SMBus Process Call, sending a 16-bit value and receiving a 16-bit response :param i2c_addr: i2c address :type i2c_addr: int :param register: Register to read/write to :type register: int :param value: Word value to transmit :type value: int :param forc...
def _get_enterprise_admin_users_batch(self, start, end): """ Returns a batched queryset of User objects. """ LOGGER.info('Fetching new batch of enterprise admin users from indexes: %s to %s', start, end) return User.objects.filter(groups__name=ENTERPRISE_DATA_API_ACCESS_GROUP, is...
Returns a batched queryset of User objects.
def text_antialias(self, flag=True): """text antialias :param flag: True or False. (default is True) :type flag: bool """ antialias = pgmagick.DrawableTextAntialias(flag) self.drawer.append(antialias)
text antialias :param flag: True or False. (default is True) :type flag: bool
def show_vcs_output_vcs_nodes_vcs_node_info_node_fabric_state(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_vcs = ET.Element("show_vcs") config = show_vcs output = ET.SubElement(show_vcs, "output") vcs_nodes = ET.SubElement(output,...
Auto Generated Code
def read(self,filename,min_length,slide_sec=0,buffer=0): """ Parse the science segments from the segwizard output contained in file. @param filename: input text file containing a list of science segments generated by segwizard. @param min_length: only append science segments that are longer than min...
Parse the science segments from the segwizard output contained in file. @param filename: input text file containing a list of science segments generated by segwizard. @param min_length: only append science segments that are longer than min_length. @param slide_sec: Slide each ScienceSegment by:: ...
def get(self, prefix, url, schema_version=None): """ Get the cached object """ if not self.cache_dir: return None filename = self._get_cache_file(prefix, url) try: with open(filename, 'rb') as file: item = pickle.load(file) if schema_...
Get the cached object
def related_linkage_states_and_scoped_variables(self, state_ids, scoped_variables): """ TODO: document """ # find all related transitions related_transitions = {'enclosed': [], 'ingoing': [], 'outgoing': []} for t in self.transitions.values(): # check if internal of ...
TODO: document
def rmfile(path): """Ensure file deleted also on *Windows* where read-only files need special treatment.""" if osp.isfile(path): if is_win: os.chmod(path, 0o777) os.remove(path)
Ensure file deleted also on *Windows* where read-only files need special treatment.