positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def log(message, level=None): """Write a message to the juju log""" command = ['juju-log'] if level: command += ['-l', level] if not isinstance(message, six.string_types): message = repr(message) command += [message[:SH_MAX_ARG]] # Missing juju-log should not cause failures in un...
Write a message to the juju log
def parse_known_chained(self, args=None): """ Parse the argument directly to the function used for setup This function parses the command line arguments to the function that has been used for the :meth:`setup_args` method. Parameters ---------- args: list ...
Parse the argument directly to the function used for setup This function parses the command line arguments to the function that has been used for the :meth:`setup_args` method. Parameters ---------- args: list The arguments parsed to the :meth:`parse_args` function...
def _g(self, h, xp, s): """Density function for blow and hop moves""" nphi = sum(self.phi) return (nphi / 2.0) * log(2 * pi) + nphi * \ log(s) + 0.5 * sum((h - xp) ** 2) / (s ** 2)
Density function for blow and hop moves
def prepare_notification(self, *, subscribers=None, instance=None, loop=None, notify_external=True): """Sets up a and configures an `~.utils.Executor`:class: instance.""" # merge callbacks added to the class level with those added to the # instance, giving the former...
Sets up a and configures an `~.utils.Executor`:class: instance.
def _reorder_csv(d, filename=""): """ Preserve the csv column ordering before writing back out to CSV file. Keep column data consistent with JSONLD column number alignment. { "var1" : {"number": 1, "values": [] }, "var2": {"number": 1, "values": [] } } :param dict d: csv data :param str filenam...
Preserve the csv column ordering before writing back out to CSV file. Keep column data consistent with JSONLD column number alignment. { "var1" : {"number": 1, "values": [] }, "var2": {"number": 1, "values": [] } } :param dict d: csv data :param str filename: Filename :return dict: csv data
def list_components(self, dependency_order=True): """ Lists the Components by dependency resolving. Usage:: >>> manager = Manager(("./manager/tests/tests_manager/resources/components/core",)) >>> manager.register_components() True >>> manager.lis...
Lists the Components by dependency resolving. Usage:: >>> manager = Manager(("./manager/tests/tests_manager/resources/components/core",)) >>> manager.register_components() True >>> manager.list_components() [u'core.tests_component_a', u'core.tests_co...
def create(self, root=None, namespace=None): """Create a sequence element with the given root. @param root: The C{etree.Element} to root the sequence at, if C{None} a new one will be created.. @result: A L{SequenceItem} with the given root. @raises L{ECResponseError}: If the...
Create a sequence element with the given root. @param root: The C{etree.Element} to root the sequence at, if C{None} a new one will be created.. @result: A L{SequenceItem} with the given root. @raises L{ECResponseError}: If the given C{root} has a bad tag.
def split_label_fuzzy(self, label): """ Splits a label entered as user input. It's more flexible in it's syntax parsing than the L{split_label_strict} method, as it allows the exclamation mark (B{C{!}}) to be omitted. The ambiguity is resolved by searching the modules in the sna...
Splits a label entered as user input. It's more flexible in it's syntax parsing than the L{split_label_strict} method, as it allows the exclamation mark (B{C{!}}) to be omitted. The ambiguity is resolved by searching the modules in the snapshot to guess if a label refers to a module or ...
def find_min_signature(ufunc, dtypes_in): """Determine the minimum matching ufunc signature for given dtypes. Parameters ---------- ufunc : str or numpy.ufunc Ufunc whose signatures are to be considered. dtypes_in : Sequence of objects specifying input dtypes. Its length must match ...
Determine the minimum matching ufunc signature for given dtypes. Parameters ---------- ufunc : str or numpy.ufunc Ufunc whose signatures are to be considered. dtypes_in : Sequence of objects specifying input dtypes. Its length must match the number of inputs of ``ufunc``, and it...
def from_template_string(string, **kwargs): """ Reads the given SMTP formatted template, and creates a new Mail object using the information. :type string: str :param string: The SMTP formatted template. :type kwargs: str :param kwargs: Variables to replace in the template. :rtype: M...
Reads the given SMTP formatted template, and creates a new Mail object using the information. :type string: str :param string: The SMTP formatted template. :type kwargs: str :param kwargs: Variables to replace in the template. :rtype: Mail :return: The resulting mail.
def get_multi_exposure_analysis_question(hazard, exposures): """Construct analysis question based on hazard and exposures. :param hazard: A hazard definition. :type hazard: dict :param exposure: A list of exposure definition. :type exposure: list :returns: Analysis question based on reporting...
Construct analysis question based on hazard and exposures. :param hazard: A hazard definition. :type hazard: dict :param exposure: A list of exposure definition. :type exposure: list :returns: Analysis question based on reporting standards. :rtype: str
def get_algorithm(algorithm): """Returns the wire format string and the hash module to use for the specified TSIG algorithm @rtype: (string, hash constructor) @raises NotImplementedError: I{algorithm} is not supported """ global _hashes if _hashes is None: _setup_hashes() if i...
Returns the wire format string and the hash module to use for the specified TSIG algorithm @rtype: (string, hash constructor) @raises NotImplementedError: I{algorithm} is not supported
def extract_calc_id_datadir(filename, datadir=None): """ Extract the calculation ID from the given filename or integer: >>> extract_calc_id_datadir('/mnt/ssd/oqdata/calc_25.hdf5') (25, '/mnt/ssd/oqdata') >>> extract_calc_id_datadir('/mnt/ssd/oqdata/wrong_name.hdf5') Traceback (most recent call ...
Extract the calculation ID from the given filename or integer: >>> extract_calc_id_datadir('/mnt/ssd/oqdata/calc_25.hdf5') (25, '/mnt/ssd/oqdata') >>> extract_calc_id_datadir('/mnt/ssd/oqdata/wrong_name.hdf5') Traceback (most recent call last): ... ValueError: Cannot extract calc_id from /mn...
def perform_exe_expansion(self): """ This function will look through the executables section of the ConfigParser object and replace any values using macros with full paths. For any values that look like ${which:lalapps_tmpltbank} will be replaced with the equivalent of...
This function will look through the executables section of the ConfigParser object and replace any values using macros with full paths. For any values that look like ${which:lalapps_tmpltbank} will be replaced with the equivalent of which(lalapps_tmpltbank) Otherwise values w...
def on_unexpected_error(e): # pragma: no cover """Catch-all error handler Unexpected errors will be handled by this function. """ sys.stderr.write('Unexpected error: {} ({})\n'.format( str(e), e.__class__.__name__)) sys.stderr.write('See file slam_error.log for additional details.\n') ...
Catch-all error handler Unexpected errors will be handled by this function.
def figure( key=None, width=400, height=500, lighting=True, controls=True, controls_vr=False, controls_light=False, debug=False, **kwargs ): """Create a new figure if no key is given, or return the figure associated with key. :param key: Python object that identifies this fi...
Create a new figure if no key is given, or return the figure associated with key. :param key: Python object that identifies this figure :param int width: pixel width of WebGL canvas :param int height: .. height .. :param bool lighting: use lighting or not :param bool controls: show controls or not...
def get_string(self, origin=None): """Read the next token and interpret it as a string. @raises dns.exception.SyntaxError: @rtype: string """ token = self.get().unescape() if not (token.is_identifier() or token.is_quoted_string()): raise dns.exception.Syntax...
Read the next token and interpret it as a string. @raises dns.exception.SyntaxError: @rtype: string
def info(name): ''' Return user information CLI Example: .. code-block:: bash salt '*' user.info root ''' ret = {} try: data = pwd.getpwnam(name) ret['gid'] = data.pw_gid ret['groups'] = list_groups(name) ret['home'] = data.pw_dir ret['name'...
Return user information CLI Example: .. code-block:: bash salt '*' user.info root
def _DownloadAuthUrl(self, url, dest_dir): """Download a Google Storage URL using an authentication token. If the token cannot be fetched, fallback to unauthenticated download. Args: url: string, the URL to download. dest_dir: string, the path to a directory for storing metadata scripts. ...
Download a Google Storage URL using an authentication token. If the token cannot be fetched, fallback to unauthenticated download. Args: url: string, the URL to download. dest_dir: string, the path to a directory for storing metadata scripts. Returns: string, the path to the file storin...
def get_iam_account(l, args, user_name): """Return the local Account for a user name, by fetching User and looking up the arn. """ iam = get_resource(args, 'iam') user = iam.User(user_name) user.load() return l.find_or_new_account(user.arn)
Return the local Account for a user name, by fetching User and looking up the arn.
def scan(cls, formats=ALL_CODE_TYPES, camera=-1): """ Shortcut only one at a time will work... """ app = AndroidApplication.instance() r = app.create_future() #: Initiate a scan pkg = BarcodePackage.instance() pkg.setBarcodeResultListener(pkg.getId()) pkg.onB...
Shortcut only one at a time will work...
def list_submodules(module_name: str) -> List[str]: # pylint: disable=invalid-sequence-index """ List full names of all the submodules in the given module. :param module_name: name of the module of which the submodules will be listed """ _module = importlib.import_module(module_name) return [...
List full names of all the submodules in the given module. :param module_name: name of the module of which the submodules will be listed
def get_base_branch(): # type: () -> str """ Return the base branch for the current branch. This function will first try to guess the base branch and if it can't it will let the user choose the branch from the list of all local branches. Returns: str: The name of the branch the current bra...
Return the base branch for the current branch. This function will first try to guess the base branch and if it can't it will let the user choose the branch from the list of all local branches. Returns: str: The name of the branch the current branch is based on.
def read (self, files): """Read settings from given config files. @raises: LinkCheckerError on syntax errors in the config file(s) """ assert isinstance(files, list), "Invalid file list %r" % files try: self.read_ok = super(LCConfigParser, self).read(files) ...
Read settings from given config files. @raises: LinkCheckerError on syntax errors in the config file(s)
def get_rupture_surface(mag, nodal_plane, hypocenter, msr, rupture_aspect_ratio, upper_seismogenic_depth, lower_seismogenic_depth, mesh_spacing=1.0): """ Create and return rupture surface object with given properties. :param mag: Magnitude value, used...
Create and return rupture surface object with given properties. :param mag: Magnitude value, used to calculate rupture dimensions, see :meth:`_get_rupture_dimensions`. :param nodal_plane: Instance of :class:`openquake.hazardlib.geo.nodalplane.NodalPlane` describing the rupture o...
def json(self): """Custom JSON encoder""" output = {} for filename in self.data: output[filename] = [] for secret_hash in self.data[filename]: tmp = self.data[filename][secret_hash].json() del tmp['filename'] # Because filename will map t...
Custom JSON encoder
def setup(self, name_filters=['*.py', '*.pyw'], show_all=False, single_click_to_open=False): """Setup tree widget""" self.setup_view() self.set_name_filters(name_filters) self.show_all = show_all self.single_click_to_open = single_click_to_open ...
Setup tree widget
def timestamp(self, value): """ The local time when the message was written. Must follow the format 'Mmm DD HH:MM:SS'. If the day of the month is less than 10, then it MUST be represented as a space and then the number. """ if not self._timestamp_is_val...
The local time when the message was written. Must follow the format 'Mmm DD HH:MM:SS'. If the day of the month is less than 10, then it MUST be represented as a space and then the number.
def _process_file_continue_request(self, request: BaseRequest): '''Modify the request to resume downloading file.''' if os.path.exists(self._filename): size = os.path.getsize(self._filename) request.set_continue(size) self._file_continue_requested = True ...
Modify the request to resume downloading file.
def get_target_temperature(self): """ Returns the actual target temperature. Attention: Returns None if the value can't be queried or is unknown. """ value = self.box.homeautoswitch("gethkrtsoll", self.actor_id) self.target_temperature = self.__get_temp(value) ret...
Returns the actual target temperature. Attention: Returns None if the value can't be queried or is unknown.
def filename(self): """ Name if the MOP formatted file to parse. @rtype: basestring @return: filename """ if self._filename is None: self._filename = storage.get_file(self.basename, self.ccd, ...
Name if the MOP formatted file to parse. @rtype: basestring @return: filename
def safe_chmod(path, mode): """Set the permissions mode on path, but only if it differs from the current mode. """ if stat.S_IMODE(os.stat(path).st_mode) != mode: os.chmod(path, mode)
Set the permissions mode on path, but only if it differs from the current mode.
def _RetryLoop(self, func, timeout=None): """Retries an operation until success or deadline. Args: func: The function to run. Must take a timeout, in seconds, as a single parameter. If it raises grpc.RpcError and deadline has not be reached, it will be run again. timeout: Retries ...
Retries an operation until success or deadline. Args: func: The function to run. Must take a timeout, in seconds, as a single parameter. If it raises grpc.RpcError and deadline has not be reached, it will be run again. timeout: Retries will continue until timeout seconds have passed.
def _check(self): """Check that spectrum has legal combination of attributes.""" # Run the super method super(Spectrum, self)._check() err_str = None has_data = self._KEYS.DATA in self has_wave = self._KEYS.WAVELENGTHS in self has_flux = self._KEYS.FLUXES in self...
Check that spectrum has legal combination of attributes.
def reload(self): """ Reload file info and metadata * name * sha * pickcode """ res = self.api._req_file(self.fid) data = res['data'][0] self.name = data['file_name'] self.sha = data['sha1'] self.pickcode = data['pick_code']
Reload file info and metadata * name * sha * pickcode
def add_root_family(self, family_id): """Adds a root family. arg: family_id (osid.id.Id): the ``Id`` of a family raise: AlreadyExists - ``family_id`` is already in hierarchy raise: NotFound - ``family_id`` not found raise: NullArgument - ``family_id`` is ``null`` r...
Adds a root family. arg: family_id (osid.id.Id): the ``Id`` of a family raise: AlreadyExists - ``family_id`` is already in hierarchy raise: NotFound - ``family_id`` not found raise: NullArgument - ``family_id`` is ``null`` raise: OperationFailed - unable to complete reque...
def _read_from_hdx(self, object_type, value, fieldname='id', action=None, **kwargs): # type: (str, str, str, Optional[str], Any) -> Tuple[bool, Union[Dict, str]] """Makes a read call to HDX passing in given parameter. Args: object_type (str): Description of HD...
Makes a read call to HDX passing in given parameter. Args: object_type (str): Description of HDX object type (for messages) value (str): Value of HDX field fieldname (str): HDX field name. Defaults to id. action (Optional[str]): Replacement CKAN action url to use...
def analyze(self, handle, filename): """Submit a file for analysis. :type handle: File handle :param handle: Handle to file to upload for analysis. :type filename: str :param filename: File name. :rtype: str :return: File ID as a string """ ...
Submit a file for analysis. :type handle: File handle :param handle: Handle to file to upload for analysis. :type filename: str :param filename: File name. :rtype: str :return: File ID as a string
def bind(topic, signal=None, kind=MIDDLE, nice=-1): """ This is a decorator function, so you should use it as: @bind('init') def process_init(a, b): ... """ def f(func): if not topic in _receivers: receivers = _receivers[topic] = [] ...
This is a decorator function, so you should use it as: @bind('init') def process_init(a, b): ...
def fatal( callingClass, astr_key, astr_extraMsg="" ): ''' Convenience dispatcher to the error_exit() method. Will raise "fatal" error, i.e. terminate script. ''' b_exitToOS = True report( callingClass, astr_key, b_exitToOS, astr_extraMsg )
Convenience dispatcher to the error_exit() method. Will raise "fatal" error, i.e. terminate script.
def are_equivalent(*args, **kwargs): """Indicate if arguments passed to this function are equivalent. .. hint:: This checker operates recursively on the members contained within iterables and :class:`dict <python:dict>` objects. .. caution:: If you only pass one argument to this checke...
Indicate if arguments passed to this function are equivalent. .. hint:: This checker operates recursively on the members contained within iterables and :class:`dict <python:dict>` objects. .. caution:: If you only pass one argument to this checker - even if it is an iterable - the ch...
def get(self, sensor_type='temperature_core'): """Get sensors list.""" self.__update__() if sensor_type == 'temperature_core': ret = [s for s in self.sensors_list if s['unit'] == SENSOR_TEMP_UNIT] elif sensor_type == 'fan_speed': ret = [s for s in self.sensors_lis...
Get sensors list.
def register_service(self, service): """ Register service into the system. Called by Services. """ if service not in self.services: self.services.append(service)
Register service into the system. Called by Services.
def get_hops(self, start, end=None, forward=True): """ Computes the hop distance to all nodes centered around a specified node. First order neighbours are at hop 1, their neigbours are at hop 2 etc. Uses :py:meth:`forw_bfs` or :py:meth:`back_bfs` depending on the value of the forward ...
Computes the hop distance to all nodes centered around a specified node. First order neighbours are at hop 1, their neigbours are at hop 2 etc. Uses :py:meth:`forw_bfs` or :py:meth:`back_bfs` depending on the value of the forward parameter. If the distance between all neighbouring nodes is 1 t...
def iparallel_progbar(mapper, iterable, nprocs=None, starmap=False, flatmap=False, shuffle=False, verbose=True, verbose_flatmap=None, max_cache=-1, **kwargs): """Performs a parallel mapping of the given iterable, reporting a progress bar as values get returned. Yields objects as soon as th...
Performs a parallel mapping of the given iterable, reporting a progress bar as values get returned. Yields objects as soon as they're computed, but does not guarantee that they'll be in the correct order. :param mapper: The mapping function to apply to elements of the iterable :param iterable: The iterable...
def get(self, rel_path, cb=None): '''Return the file path referenced but rel_path, or None if it can't be found. If an upstream is declared, it will try to get the file from the upstream before declaring failure. ''' import shutil global_logger.debug( "LC {} ...
Return the file path referenced but rel_path, or None if it can't be found. If an upstream is declared, it will try to get the file from the upstream before declaring failure.
def get_next_create_state(self, state, ret): """Return the next create state from previous state. """ if ret: if state == fw_const.FABRIC_PREPARE_DONE_STATE: return state else: return state + 1 else: return state
Return the next create state from previous state.
def load_tasks(self, cmd, params, args): """implements loader interface, return (tasks, config)""" return generate_tasks('taskname that shows up in log', self._gen_tasks()), self.DOIT_CONFIG
implements loader interface, return (tasks, config)
def functions_shadowed(self): ''' Return the list of functions shadowed Returns: list(core.Function) ''' candidates = [c.functions_not_inherited for c in self.contract.inheritance] candidates = [candidate for sublist in candidates for candidate in sublist...
Return the list of functions shadowed Returns: list(core.Function)
def _set_view(self): """Assign a view to current graph""" if self.logarithmic: view_class = PolarLogView else: view_class = PolarView self.view = view_class( self.width - self.margin_box.x, self.height - self.margin_box.y, self._box ...
Assign a view to current graph
def get_bb_intersections(recording): """ Get all intersections of the bounding boxes of strokes. Parameters ---------- recording : list of lists of integers Returns ------- A symmetrical matrix which indicates if two bounding boxes intersect. """ intersections = numpy.zeros((le...
Get all intersections of the bounding boxes of strokes. Parameters ---------- recording : list of lists of integers Returns ------- A symmetrical matrix which indicates if two bounding boxes intersect.
def get_text_contents(self): """Fetch the decoded text contents of a Unicode encoded Entry. Since this should return the text contents from the file system, we check to see into what sort of subclass we should morph this Entry.""" try: self = self.disambiguate(must_e...
Fetch the decoded text contents of a Unicode encoded Entry. Since this should return the text contents from the file system, we check to see into what sort of subclass we should morph this Entry.
def get_repositories_by_query(self, repository_query): """Gets a list of ``Repositories`` matching the given repository query. arg: repository_query (osid.repository.RepositoryQuery): the repository query return: (osid.repository.RepositoryList) - the returned ...
Gets a list of ``Repositories`` matching the given repository query. arg: repository_query (osid.repository.RepositoryQuery): the repository query return: (osid.repository.RepositoryList) - the returned ``RepositoryList`` raise: NullArgument - ``repository_qu...
def contains_c_extension(module: ModuleType, import_all_submodules: bool = True, include_external_imports: bool = False, seen: List[ModuleType] = None) -> bool: """ Extends :func:`is_c_extension` by asking: is this module, or any of its ...
Extends :func:`is_c_extension` by asking: is this module, or any of its submodules, a C extension? Args: module: Previously imported module object to be tested. import_all_submodules: explicitly import all submodules of this module? include_external_imports: check modules in other packa...
def stop(self, sig=signal.SIGTERM): """ stop the scheduler and stop all processes """ if self.pid is None: self.pid = self.read_pid() if self.pid is None: sp = BackgroundProcess.objects.filter(pk=1).first() if sp: self.pid = sp...
stop the scheduler and stop all processes
def foreground_mask( self, tolerance, ignore_black=True, use_hsv=False, scale=8, bgmodel=None): """Creates a binary image mask for the foreground of an image against a uniformly colored background. The background is assumed to be th...
Creates a binary image mask for the foreground of an image against a uniformly colored background. The background is assumed to be the mode value of the histogram for each of the color channels. Parameters ---------- tolerance : int A +/- level from the detected mean...
def _callback_internal(self, kwargs): """Used to execute callbacks on asynchronous pipelines.""" logging.debug('Callback %s(*%s, **%s)#%s with params: %r', self._class_path, _short_repr(self.args), _short_repr(self.kwargs), self._pipeline_key.name(), kwargs) return self.c...
Used to execute callbacks on asynchronous pipelines.
def normalize_scientific_notation(s, ignore_commas=True, verbosity=1): """Produce a string convertable with float(s), if possible, fixing some common scientific notations Deletes commas and allows addition. >>> normalize_scientific_notation(' -123 x 10^-45 ') '-123e-45' >>> normalize_scientific_not...
Produce a string convertable with float(s), if possible, fixing some common scientific notations Deletes commas and allows addition. >>> normalize_scientific_notation(' -123 x 10^-45 ') '-123e-45' >>> normalize_scientific_notation(' -1+1,234 x 10^-5,678 ') '1233e-5678' >>> normalize_scientific_...
def _findlinestarts(code_object): """ Find the offsets in a byte code which are the start of source lines. Generate pairs (offset, lineno) as described in Python/compile.c. This is a modified version of dis.findlinestarts. This version allows multiple "line starts" with the sam...
Find the offsets in a byte code which are the start of source lines. Generate pairs (offset, lineno) as described in Python/compile.c. This is a modified version of dis.findlinestarts. This version allows multiple "line starts" with the same line number. (The dis version conditions its...
def _to_mongo_query(query): """ Convert the query received by the Sacred Web API to a MongoDB query. Takes a query in format {"type": "and", "filters": [ {"field": "host.hostname", "operator": "==", "value": "ntbacer"}, {"type": "or", "filters": [ {"field":...
Convert the query received by the Sacred Web API to a MongoDB query. Takes a query in format {"type": "and", "filters": [ {"field": "host.hostname", "operator": "==", "value": "ntbacer"}, {"type": "or", "filters": [ {"field": "result", "operator": "==", "value": 2403.52}, ...
def get(remote_path, local_path='', recursive=False, preserve_times=False, **kwargs): ''' Transfer files and directories from remote host to the localhost of the Minion. remote_path Path to retrieve from remote host. Since this is evaluated by scp on the ...
Transfer files and directories from remote host to the localhost of the Minion. remote_path Path to retrieve from remote host. Since this is evaluated by scp on the remote host, shell wildcards and environment variables may be used. recursive: ``False`` Transfer files and directori...
def cell_language(source): """Return cell language and language options, if any""" if source: line = source[0] if line.startswith('%%'): magic = line[2:] if ' ' in magic: lang, magic_args = magic.split(' ', 1) else: lang = magic...
Return cell language and language options, if any
def convert_from_file(cls, input_file=None, output_file=None, output_format='json', indent=2, compact=False): """Convert to json, properties or yaml :param input_file: input file, if not specified stdin :param output_file: output file, if not specified stdout :param output_format: json,...
Convert to json, properties or yaml :param input_file: input file, if not specified stdin :param output_file: output file, if not specified stdout :param output_format: json, properties or yaml :return: json, properties or yaml string representation
def definition( self, text, definition): """*genarate a MMD definition* **Key Arguments:** - ``text`` -- the text to define - ``definition`` -- the definition **Return:** - ``definition`` -- the MMD style definition ...
*genarate a MMD definition* **Key Arguments:** - ``text`` -- the text to define - ``definition`` -- the definition **Return:** - ``definition`` -- the MMD style definition **Usage:** To genarate a MMD definition: .. code-block:: py...
def find_thirdparty_marshaller_plugins(): """ Find, but don't load, all third party marshaller plugins. Third party marshaller plugins declare the entry point ``'hdf5storage.marshallers.plugins'`` with the name being the Marshaller API version and the target being a function that returns a ``tuple`...
Find, but don't load, all third party marshaller plugins. Third party marshaller plugins declare the entry point ``'hdf5storage.marshallers.plugins'`` with the name being the Marshaller API version and the target being a function that returns a ``tuple`` or ``list`` of all the marshallers provided by t...
def log_url (self, url_data): """ Log URL data in custom XML format. """ self.xml_starttag(u'urldata') if self.has_part('url'): self.xml_tag(u"url", unicode(url_data.base_url)) if url_data.name and self.has_part('name'): self.xml_tag(u"name", unico...
Log URL data in custom XML format.
def __create_table_if_not_exists(self): # type: () -> None """Creates table in Dynamodb resource if it doesn't exist and create_table is set as True. :rtype: None :raises: PersistenceException: When `create_table` fails on dynamodb resource. """ if se...
Creates table in Dynamodb resource if it doesn't exist and create_table is set as True. :rtype: None :raises: PersistenceException: When `create_table` fails on dynamodb resource.
def delete_password(service, username): """Delete the password for the username of the service. """ try: # set up the call for security. call = subprocess.Popen(['security', 'delete-generic-password', ...
Delete the password for the username of the service.
def data_kva_compare(db_data, user_data): """Validate key/value data in KeyValueArray. Args: db_data (list): The data store in Redis. user_data (dict): The user provided data. Returns: bool: True if the data passed validation. """ for kv_data...
Validate key/value data in KeyValueArray. Args: db_data (list): The data store in Redis. user_data (dict): The user provided data. Returns: bool: True if the data passed validation.
def oauth_manager(self, oauth_manager): """Use the oauth manager to enable oauth for API :param oauth_manager: the oauth manager """ @self.app.before_request def before_request(): endpoint = request.endpoint resource = self.app.view_functions[endpoint].vi...
Use the oauth manager to enable oauth for API :param oauth_manager: the oauth manager
def _item_in_context(lines, item, context): """Determines if a WorkItem falls within an anchor. This only returns True if a WorkItems start-/stop-pos range is *completely* within an anchor, not just if it overalaps. """ start_offset = _line_and_col_to_offset(lines, item.start_pos[0], ...
Determines if a WorkItem falls within an anchor. This only returns True if a WorkItems start-/stop-pos range is *completely* within an anchor, not just if it overalaps.
def _handle_component(sourcekey, comp_dict): """Make the source objects and write the xml for a component """ if comp_dict.comp_key is None: fullkey = sourcekey else: fullkey = "%s_%s" % (sourcekey, comp_dict.comp_key) srcdict = make_sources(fullkey, comp_...
Make the source objects and write the xml for a component
def get_learning_rate(learning_rate, hidden_size, learning_rate_warmup_steps): """Calculate learning rate with linear warmup and rsqrt decay.""" with tf.name_scope("learning_rate"): warmup_steps = tf.to_float(learning_rate_warmup_steps) step = tf.to_float(tf.train.get_or_create_global_step()) learning_...
Calculate learning rate with linear warmup and rsqrt decay.
def invoked(self, ctx): """Method called when the command is invoked.""" if not ctx.ansi.is_enabled: print("You need color support to use this demo") else: print(ctx.ansi.cmd('erase_display')) self._demo_fg_color(ctx) self._demo_bg_color(ctx) ...
Method called when the command is invoked.
def tar_extract(cls, tar_comp_file_path): """Extract tar.gz or tar bz2 file. It behaves like - tar xzf tar_gz_file_path - tar xjf tar_bz2_file_path It raises tarfile.ReadError if the file is broken. """ try: with contextlib.closing(tarfile.open(ta...
Extract tar.gz or tar bz2 file. It behaves like - tar xzf tar_gz_file_path - tar xjf tar_bz2_file_path It raises tarfile.ReadError if the file is broken.
def to_raw_xml(source): """ Convert various representations of an XML structure to a normal XML string. Args: source -- The source object to be converted - ET.Element, dict or string. Returns: A rew xml string matching the source object. >>> to_raw_xml("<content/>") ...
Convert various representations of an XML structure to a normal XML string. Args: source -- The source object to be converted - ET.Element, dict or string. Returns: A rew xml string matching the source object. >>> to_raw_xml("<content/>") '<content/>' >>> to_raw_x...
def list_download_tasks(self, need_task_info=1, start=0, limit=10, asc=0, create_time=None, status=None, source_url=None, remote_path=None, expires=None, **kwargs): """查询离线下载任务ID列表及任务信息. :param need_task_info: 是否需要返回任务信息: ...
查询离线下载任务ID列表及任务信息. :param need_task_info: 是否需要返回任务信息: * 0:不需要 * 1:需要,默认为1 :param start: 查询任务起始位置,默认为0。 :param limit: 设定返回任务数量,默认为10。 :param asc: * 0:降序,默认值 * 1:升序 :param create_...
def detect_vec(df, max_anoms=0.10, direction='pos', alpha=0.05, period=None, only_last=False, threshold=None, e_value=False, longterm_period=None, plot=False, y_log=False, xlabel='', ylabel='count', title=None, verbose=False): """ Anomaly Detection Usi...
Anomaly Detection Using Seasonal Hybrid ESD Test A technique for detecting anomalies in seasonal univariate time series where the input is a series of observations. Args: x: Time series as a column data frame, list, or vector, where the column consists of the observations. max_anoms: Maximum ...
def download(self, id, directory_path='.', checksum=True): """Download a product. Uses the filename on the server for the downloaded file, e.g. "S1A_EW_GRDH_1SDH_20141003T003840_20141003T003920_002658_002F54_4DD1.zip". Incomplete downloads are continued and complete files are skipped. ...
Download a product. Uses the filename on the server for the downloaded file, e.g. "S1A_EW_GRDH_1SDH_20141003T003840_20141003T003920_002658_002F54_4DD1.zip". Incomplete downloads are continued and complete files are skipped. Parameters ---------- id : string ...
def Shape(docs, drop=0.0): """Get word shapes.""" ids = numpy.zeros((sum(len(doc) for doc in docs),), dtype="i") i = 0 for doc in docs: for token in doc: ids[i] = token.shape i += 1 return ids, None
Get word shapes.
def addkey(ctx, key): """ Add a private key to the wallet """ if not key: while True: key = click.prompt( "Private Key (wif) [Enter to quit]", hide_input=True, show_default=False, default="exit", ) if...
Add a private key to the wallet
def fastalite(handle): """Return a sequence of namedtuple objects from a fasta file with attributes (id, description, seq) given open file-like object ``handle`` """ Seq = namedtuple('Seq', ['id', 'description', 'seq']) header, seq = '', [] for line in handle: if line.startswith('...
Return a sequence of namedtuple objects from a fasta file with attributes (id, description, seq) given open file-like object ``handle``
def newidfobject(self, key, aname='', defaultvalues=True, **kwargs): """ Add a new idfobject to the model. If you don't specify a value for a field, the default value will be set. For example :: newidfobject("CONSTRUCTION") newidfobject("CONSTRUCTION", ...
Add a new idfobject to the model. If you don't specify a value for a field, the default value will be set. For example :: newidfobject("CONSTRUCTION") newidfobject("CONSTRUCTION", Name='Interior Ceiling_class', Outside_Layer='LW Concrete', ...
def register_file(self, file, parent, ensure_uniqueness=False): """ Registers given file in the Model. :param file: File to register. :type file: unicode :param parent: FileNode parent. :type parent: GraphModelNode :param ensure_uniqueness: Ensure registrar uniqu...
Registers given file in the Model. :param file: File to register. :type file: unicode :param parent: FileNode parent. :type parent: GraphModelNode :param ensure_uniqueness: Ensure registrar uniqueness. :type ensure_uniqueness: bool :return: FileNode. :rty...
def usage_records(self): """ Access the usage_records :returns: twilio.rest.wireless.v1.sim.usage_record.UsageRecordList :rtype: twilio.rest.wireless.v1.sim.usage_record.UsageRecordList """ if self._usage_records is None: self._usage_records = UsageRecordList...
Access the usage_records :returns: twilio.rest.wireless.v1.sim.usage_record.UsageRecordList :rtype: twilio.rest.wireless.v1.sim.usage_record.UsageRecordList
def _write(self, session, openFile, replaceParamFile=None): """ ProjectFileEvent Write to File Method """ openFile.write( text( yaml.dump([evt.as_yml() for evt in self.events.order_by(ProjectFileEvent.name, ...
ProjectFileEvent Write to File Method
def exists(self, digest): """ Check if a blob exists :param digest: Hex digest of the blob :return: Boolean indicating existence of the blob """ return self.conn.client.blob_exists(self.container_name, digest)
Check if a blob exists :param digest: Hex digest of the blob :return: Boolean indicating existence of the blob
def timestamp_file(): """Opens a file for tracking the time of the last version check""" config_dir = os.path.join( os.path.expanduser("~"), BaseGlobalConfig.config_local_dir ) if not os.path.exists(config_dir): os.mkdir(config_dir) timestamp_file = os.path.join(config_dir, "cumulu...
Opens a file for tracking the time of the last version check
def send(self, request): """ Send a request to the server and wait for its response. Args: request (Request): Reference to a request object that is sent to the server. Returns: Response: The response from the server to the request. """ self._connection.c...
Send a request to the server and wait for its response. Args: request (Request): Reference to a request object that is sent to the server. Returns: Response: The response from the server to the request.
def as_dictionary(self): """ Return the parameter as a dictionary. :return: dict """ return { "name": self.name, "type": self.type, "value": remove_0x_prefix(self.value) if self.type == 'bytes32' else self.value }
Return the parameter as a dictionary. :return: dict
def loc(parser, start): # type: (Parser, int) -> Optional[Loc] """Returns a location object, used to identify the place in the source that created a given parsed object.""" if parser.options["no_location"]: return None if parser.options["no_source"]: return Loc(start, parser.prev_en...
Returns a location object, used to identify the place in the source that created a given parsed object.
def execl(self, lpCmdLine, **kwargs): """ Starts a new process for debugging. This method uses a command line string. To use a list of arguments instead, use L{execv}. @see: L{attach}, L{detach} @type lpCmdLine: str @param lpCmdLine: Command line string to exe...
Starts a new process for debugging. This method uses a command line string. To use a list of arguments instead, use L{execv}. @see: L{attach}, L{detach} @type lpCmdLine: str @param lpCmdLine: Command line string to execute. The first token must be the debugee exec...
def dump_conndata(self): """Developer tool for debugging forensics.""" attrs = vars(self) return ', '.join("%s: %s" % item for item in attrs.items())
Developer tool for debugging forensics.
def get_properties(attributes): """Return tuple of names of defined properties. :type attributes: dict :rtype: list """ return [key for key, value in six.iteritems(attributes) if isinstance(value, property)]
Return tuple of names of defined properties. :type attributes: dict :rtype: list
def abort(self): """Abort the SBI (and associated PBs).""" self.set_status('aborted') DB.remove_from_list('{}:active'.format(self._type), self._id) DB.append_to_list('{}:aborted'.format(self._type), self._id) sbi_pb_ids = ast.literal_eval( DB.get_hash_value(self._key,...
Abort the SBI (and associated PBs).
def jit_load(self): """ Import and instantiate this JIT object Returns ------- """ try: model = importlib.import_module('.' + self.model, 'andes.models') device = getattr(model, self.device) self.system.__dict__[self.name] = device(se...
Import and instantiate this JIT object Returns -------
def _connect(contact_points=None, port=None, cql_user=None, cql_pass=None, protocol_version=None): ''' Connect to a Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str or list of str :param cql_u...
Connect to a Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str or list of str :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The ...
def run(self): """Build the Fortran library, all python extensions and the docs.""" print('---- BUILDING ----') _build.run(self) # build documentation print('---- BUILDING DOCS ----') docdir = os.path.join(self.build_lib, 'pyshtools', 'doc') self.mkpath(docdir) ...
Build the Fortran library, all python extensions and the docs.
def get_id(self): """ Force the object saveing to get an id""" _id = self._meta.get("id", None) if _id is None: _id = self.save() return _id
Force the object saveing to get an id
def discard_between( self, min_rank=None, max_rank=None, min_score=None, max_score=None, ): """ Remove members whose ranking is between *min_rank* and *max_rank* OR whose score is between *min_score* and *max_score* (both ranges inclusive). If ...
Remove members whose ranking is between *min_rank* and *max_rank* OR whose score is between *min_score* and *max_score* (both ranges inclusive). If no bounds are specified, no members will be removed.