code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def function(fname): """ Make a function to Function class """ def _f(func): class WrapFunction(Function): name = fname def __call__(self, *args, **kwargs): return func(*args, **kwargs) return WrapFunction return _f
Make a function to Function class
def _requirement_element(self, parent_element, req_data): """Adds requirement XML element.""" req_data = self._transform_result(req_data) if not req_data: return title = req_data.get("title") if not title: logger.warning("Skipping requirement, title is mi...
Adds requirement XML element.
def sort_direction(self): """ Return the direction in which the linked table is is sorted by this column ("asc" or "desc"), or None this column is unsorted. """ if self.table._meta.order_by == self.name: return "asc" elif self.table._meta.order_by == ("-" + ...
Return the direction in which the linked table is is sorted by this column ("asc" or "desc"), or None this column is unsorted.
def safe_compare_digest(val1, val2): """safe_compare_digest method. :param val1: string or bytes for compare :type val1: str | bytes :param val2: string or bytes for compare :type val2: str | bytes """ if len(val1) != len(val2): return False result = 0 if PY3 and isinstance...
safe_compare_digest method. :param val1: string or bytes for compare :type val1: str | bytes :param val2: string or bytes for compare :type val2: str | bytes
def sort_schemas(schemas): """Sort a list of SQL schemas in order""" def keyfun(v): x = SQL_SCHEMA_REGEXP.match(v).groups() # x3: 'DEV' should come before '' return (int(x[0]), x[1], int(x[2]) if x[2] else None, x[3] if x[3] else 'zzz', int(x[4])) return sorted(schem...
Sort a list of SQL schemas in order
def check_model(self, max_paths=1, max_path_length=5): """Check all the statements added to the ModelChecker. Parameters ---------- max_paths : Optional[int] The maximum number of specific paths to return for each Statement to be explained. Default: 1 max...
Check all the statements added to the ModelChecker. Parameters ---------- max_paths : Optional[int] The maximum number of specific paths to return for each Statement to be explained. Default: 1 max_path_length : Optional[int] The maximum length of spe...
def update_serviceprofile(self, host_id, vlan_id): """Top level method to update Service Profiles on UCS Manager. Calls all the methods responsible for the individual tasks that ultimately result in a vlan_id getting programed on a server's ethernet ports and the Fabric Interconnect's n...
Top level method to update Service Profiles on UCS Manager. Calls all the methods responsible for the individual tasks that ultimately result in a vlan_id getting programed on a server's ethernet ports and the Fabric Interconnect's network ports.
def _init_map(self): """stub""" QuestionFilesFormRecord._init_map(self) FirstAngleProjectionFormRecord._init_map(self) super(MultiChoiceOrthoQuestionFormRecord, self)._init_map()
stub
def _loadf(ins): """ Loads a floating point value from a memory address. If 2nd arg. start with '*', it is always treated as an indirect value. """ output = _float_oper(ins.quad[2]) output.extend(_fpush()) return output
Loads a floating point value from a memory address. If 2nd arg. start with '*', it is always treated as an indirect value.
def values_update(self, range, params=None, body=None): """Lower-level method that directly calls `spreadsheets.values.update <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update>`_. :param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/co...
Lower-level method that directly calls `spreadsheets.values.update <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update>`_. :param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of the values to update. :param dict ...
def _build_file_writer(cls, session: AppSession): '''Create the File Writer. Returns: FileWriter: An instance of :class:`.writer.BaseFileWriter`. ''' args = session.args if args.delete_after: return session.factory.new('FileWriter') # is a NullWriter ...
Create the File Writer. Returns: FileWriter: An instance of :class:`.writer.BaseFileWriter`.
def _control(self, state): """ Control device state. Possible states are ON or OFF. :param state: Switch to this state. """ # Renew subscription if necessary if not self._subscription_is_recent(): self._subscribe() cmd = MAGIC + CONTROL + self._mac...
Control device state. Possible states are ON or OFF. :param state: Switch to this state.
def assert_valid_rule_class(clazz): """ Asserts that a given rule clazz is valid by checking a number of its properties: - Rules must extend from LineRule or CommitRule - Rule classes must have id and name string attributes. The options_spec is optional, but if set, it must be a list of gitlin...
Asserts that a given rule clazz is valid by checking a number of its properties: - Rules must extend from LineRule or CommitRule - Rule classes must have id and name string attributes. The options_spec is optional, but if set, it must be a list of gitlint Options. - Rule classes must have a valid...
def p_values(self, p): """values : | values value VALUE_SEPARATOR | values value""" if len(p) == 1: p[0] = list() else: p[1].append(p[2]) p[0] = p[1]
values : | values value VALUE_SEPARATOR | values value
def generate_one(self): """Generate a single element. Returns ------- element An element from the domain. Examples ------- >>> generator = RepellentGenerator(['a', 'b']) >>> gen_item = generator.generate_one() >>> gen_ite...
Generate a single element. Returns ------- element An element from the domain. Examples ------- >>> generator = RepellentGenerator(['a', 'b']) >>> gen_item = generator.generate_one() >>> gen_item in ['a', 'b'] True
def _write_git_file_and_module_config(cls, working_tree_dir, module_abspath): """Writes a .git file containing a (preferably) relative path to the actual git module repository. It is an error if the module_abspath cannot be made into a relative path, relative to the working_tree_dir :note: will ...
Writes a .git file containing a (preferably) relative path to the actual git module repository. It is an error if the module_abspath cannot be made into a relative path, relative to the working_tree_dir :note: will overwrite existing files ! :note: as we rewrite both the git file as well as the ...
def uninstall(self): ''' Uninstall the module finder. If not installed, this will do nothing. After uninstallation, none of the newly loaded modules will be decorated (that is, everything will be back to normal). ''' if self.installed: sys.meta_path.remove(se...
Uninstall the module finder. If not installed, this will do nothing. After uninstallation, none of the newly loaded modules will be decorated (that is, everything will be back to normal).
def start(self): """Start the controller.""" if self.mode == "manual": return if self.ipython_dir != '~/.ipython': self.ipython_dir = os.path.abspath(os.path.expanduser(self.ipython_dir)) if self.log: stdout = open(os.path.join(self.ipython_dir, "{0...
Start the controller.
def host_info_getter(func, name=None): """ The decorated function is added to the process of collecting the host_info. This just adds the decorated function to the global ``sacred.host_info.host_info_gatherers`` dictionary. The functions from that dictionary are used when collecting the host info ...
The decorated function is added to the process of collecting the host_info. This just adds the decorated function to the global ``sacred.host_info.host_info_gatherers`` dictionary. The functions from that dictionary are used when collecting the host info using :py:func:`~sacred.host_info.get_host_info`...
def ParseOptions(cls, options, configuration_object): """Parses and validates options. Args: options (argparse.Namespace): parser options. configuration_object (CLITool): object to be configured by the argument helper. Raises: BadConfigObject: when the configuration object is o...
Parses and validates options. Args: options (argparse.Namespace): parser options. configuration_object (CLITool): object to be configured by the argument helper. Raises: BadConfigObject: when the configuration object is of the wrong type.
def parse_timezone(matches, default_timezone=UTC): """Parses ISO 8601 time zone specs into tzinfo offsets """ if matches["timezone"] == "Z": return UTC # This isn't strictly correct, but it's common to encounter dates without # timezones so I'll assume the default (which defaults to UTC). ...
Parses ISO 8601 time zone specs into tzinfo offsets
def description(self, request, id, description): """Updates the description of a gist Arguments: request: an initial request object id: the id of the gist we want to edit the description for description: the new description """ request.d...
Updates the description of a gist Arguments: request: an initial request object id: the id of the gist we want to edit the description for description: the new description
def size(self, filename: str) -> int: '''Get size of file. Coroutine. ''' yield from self._control_stream.write_command(Command('SIZE', filename)) reply = yield from self._control_stream.read_reply() self.raise_if_not_match('File size', ReplyCodes.file_status, reply) ...
Get size of file. Coroutine.
def create(self): """ Calls various methods sequentially in order to fully build the database. """ # Calls each of these methods in order. _populate_from_lines and # _update_relations must be implemented in subclasses. self._init_tables() self._populate_f...
Calls various methods sequentially in order to fully build the database.
def user_parse(data): """Parse information from the provider.""" yield 'id', data.get('id') yield 'username', data.get('username') yield 'discriminator', data.get('discriminator') yield 'picture', "https://cdn.discordapp.com/avatars/{}/{}.png".format( data.get('id'), ...
Parse information from the provider.
def lemke_howson(g, init_pivot=0, max_iter=10**6, capping=None, full_output=False): """ Find one mixed-action Nash equilibrium of a 2-player normal form game by the Lemke-Howson algorithm [2]_, implemented with "complementary pivoting" (see, e.g., von Stengel [3]_ for details). Par...
Find one mixed-action Nash equilibrium of a 2-player normal form game by the Lemke-Howson algorithm [2]_, implemented with "complementary pivoting" (see, e.g., von Stengel [3]_ for details). Parameters ---------- g : NormalFormGame NormalFormGame instance with 2 players. init_pivot : s...
def jsonify(resource): """Return a Flask ``Response`` object containing a JSON representation of *resource*. :param resource: The resource to act as the basis of the response """ response = flask.jsonify(resource.to_dict()) response = add_link_headers(response, resource.links()) return res...
Return a Flask ``Response`` object containing a JSON representation of *resource*. :param resource: The resource to act as the basis of the response
def object_exists_in_project(obj_id, proj_id): ''' :param obj_id: object ID :type obj_id: str :param proj_id: project ID :type proj_id: str Returns True if the specified data object can be found in the specified project. ''' if obj_id is None: raise ValueError("Expected obj_...
:param obj_id: object ID :type obj_id: str :param proj_id: project ID :type proj_id: str Returns True if the specified data object can be found in the specified project.
def score(self, X, y=None, **kwargs): """ Generates the Scikit-Learn classification report. Parameters ---------- X : ndarray or DataFrame of shape n x m A matrix of n instances with m features y : ndarray or Series of length n An array or series...
Generates the Scikit-Learn classification report. Parameters ---------- X : ndarray or DataFrame of shape n x m A matrix of n instances with m features y : ndarray or Series of length n An array or series of target or class values Returns ------...
def run_with_reloader(main_func, extra_files=None, interval=1): """Run the given function in an independent python interpreter.""" import signal signal.signal(signal.SIGTERM, lambda *args: sys.exit(0)) if os.environ.get('WERKZEUG_RUN_MAIN') == 'true': thread.start_new_thread(main_func, ()) ...
Run the given function in an independent python interpreter.
def get_data_source(self): """The method determines data source from product ID. :return: Data source of the product :rtype: DataSource :raises: ValueError """ product_type = self.product_id.split('_')[1] if product_type.endswith('L1C') or product_type == 'OPER':...
The method determines data source from product ID. :return: Data source of the product :rtype: DataSource :raises: ValueError
def record_run(record_type, print_session_id, **kwds): """ Record shell history. """ if print_session_id and record_type != 'init': raise RuntimeError( '--print-session-id should be used with --record-type=init') cfstore = ConfigStore() # SOMEDAY: Pass a list of environment ...
Record shell history.
def vm_ip(cls, vm_id): """Return the first usable ip address for this vm. Returns a (version, ip) tuple.""" vm_info = cls.info(vm_id) for iface in vm_info['ifaces']: if iface['type'] == 'private': continue for ip in iface['ips']: r...
Return the first usable ip address for this vm. Returns a (version, ip) tuple.
def save_pointings(self): """Print the currently defined FOVs""" import tkFileDialog f=tkFileDialog.asksaveasfile() i=0 if self.pointing_format.get()=='CFHT PH': f.write("""<?xml version = "1.0"?> <!DOCTYPE ASTRO SYSTEM "http://vizier.u-strasbg.fr/xml/astrores.dtd"> <ASTRO ...
Print the currently defined FOVs
def autodiscover(): """ Imports all available previews classes. """ from django.conf import settings for application in settings.INSTALLED_APPS: module = import_module(application) if module_has_submodule(module, 'emails'): emails = import_module('%s.emails' % applicatio...
Imports all available previews classes.
def minimum_needs_section_header_element(feature, parent): """Retrieve minimum needs section header string from definitions.""" _ = feature, parent # NOQA header = minimum_needs_section_header['string_format'] return header.capitalize()
Retrieve minimum needs section header string from definitions.
def is_descendant_of_vault(self, id_, vault_id): """Tests if an ``Id`` is a descendant of a vault. arg: id (osid.id.Id): an ``Id`` arg: vault_id (osid.id.Id): the ``Id`` of a vault return: (boolean) - ``true`` if the ``id`` is a descendant of the ``vault_id,`` ``f...
Tests if an ``Id`` is a descendant of a vault. arg: id (osid.id.Id): an ``Id`` arg: vault_id (osid.id.Id): the ``Id`` of a vault return: (boolean) - ``true`` if the ``id`` is a descendant of the ``vault_id,`` ``false`` otherwise raise: NotFound - ``vault_id`` not...
def get_docker_network(self, container_id, all_stats): """Return the container network usage using the Docker API (v1.0 or higher). Input: id is the full container id Output: a dict {'time_since_update': 3000, 'rx': 10, 'tx': 65}. with: time_since_update: number of seconds e...
Return the container network usage using the Docker API (v1.0 or higher). Input: id is the full container id Output: a dict {'time_since_update': 3000, 'rx': 10, 'tx': 65}. with: time_since_update: number of seconds elapsed between the latest grab rx: Number of byte rece...
def location(self): """Return the location of the printer.""" try: return self.data.get('identity').get('location') except (KeyError, AttributeError): return self.device_status_simple('')
Return the location of the printer.
def _run_code(code, run_globals, init_globals=None, mod_name=None, mod_fname=None, mod_loader=None, pkg_name=None): """Helper to run code in nominated namespace""" if init_globals is not None: run_globals.update(init_globals) run_globals.update(__name__ = mod_name, ...
Helper to run code in nominated namespace
def open(): global _MATLAB_RELEASE '''Opens MATLAB using specified connection (or DCOM+ protocol on Windows)where matlab_location ''' if is_win: ret = MatlabConnection() ret.open() return ret else: if settings.MATLAB_PATH != 'guess': matlab_path = settings.MA...
Opens MATLAB using specified connection (or DCOM+ protocol on Windows)where matlab_location
def listar(self, id_divisao=None, id_ambiente_logico=None): """Lista os ambientes filtrados conforme parâmetros informados. Se os dois parâmetros têm o valor None então retorna todos os ambientes. Se o id_divisao é diferente de None então retorna os ambientes filtrados pelo valor de id_...
Lista os ambientes filtrados conforme parâmetros informados. Se os dois parâmetros têm o valor None então retorna todos os ambientes. Se o id_divisao é diferente de None então retorna os ambientes filtrados pelo valor de id_divisao. Se o id_divisao e id_ambiente_logico são diferentes de...
def _get_relationships(model): """ Gets the necessary relationships for the resource by inspecting the sqlalchemy model for relationships. :param DeclarativeMeta model: The SQLAlchemy ORM model. :return: A tuple of Relationship/ListRelationship instances corresponding to the relationships o...
Gets the necessary relationships for the resource by inspecting the sqlalchemy model for relationships. :param DeclarativeMeta model: The SQLAlchemy ORM model. :return: A tuple of Relationship/ListRelationship instances corresponding to the relationships on the Model. :rtype: tuple
def configure_callbacks(app): """ Configure application callbacks """ @app.before_request def before_request(): """ Retrieve menu configuration before every request (this will return cached version if possible, else reload from database. """ from flask import session #...
Configure application callbacks
def _read_input_csv(in_file): """Parse useful details from SampleSheet CSV file. """ with io.open(in_file, newline=None) as in_handle: reader = csv.reader(in_handle) next(reader) # header for line in reader: if line: # empty lines (fc_id, lane, sample_id, ...
Parse useful details from SampleSheet CSV file.
def _evaluate(self,R,z,phi=0.,t=0.): """ NAME: _evaluate PURPOSE: evaluate the potential at R,z INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: Phi(R,z) ...
NAME: _evaluate PURPOSE: evaluate the potential at R,z INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: Phi(R,z) HISTORY: 2010-07-10 - Started - Bovy (NY...
def check(self, check_url=None): """ Checks whether a server is running. :param str check_url: URL where to check whether the server is running. Default is ``"http://{self.host}:{self.port}"``. """ if check_url is not None: self.check_url = s...
Checks whether a server is running. :param str check_url: URL where to check whether the server is running. Default is ``"http://{self.host}:{self.port}"``.
def get_sof_term(self, C, rup): """ In the case of the upper mantle events separate coefficients are considered for normal, reverse and strike-slip """ if rup.rake <= -45.0 and rup.rake >= -135.0: # Normal faulting return C["FN_UM"] elif rup.rake >...
In the case of the upper mantle events separate coefficients are considered for normal, reverse and strike-slip
def __grabHotkeys(self): """ Run during startup to grab global and specific hotkeys in all open windows """ c = self.app.configManager hotkeys = c.hotKeys + c.hotKeyFolders # Grab global hotkeys in root window for item in c.globalHotkeys: if item.enab...
Run during startup to grab global and specific hotkeys in all open windows
def _get_upsert_sql(queryset, model_objs, unique_fields, update_fields, returning, ignore_duplicate_updates=True, return_untouched=False): """ Generates the postgres specific sql necessary to perform an upsert (ON CONFLICT) INSERT INTO table_name (field1, field2) VALUES (1, 'two') ...
Generates the postgres specific sql necessary to perform an upsert (ON CONFLICT) INSERT INTO table_name (field1, field2) VALUES (1, 'two') ON CONFLICT (unique_field) DO UPDATE SET field2 = EXCLUDED.field2;
def dump(bqm, fp, vartype_header=False): """Dump a binary quadratic model to a string in COOrdinate format.""" for triplet in _iter_triplets(bqm, vartype_header): fp.write('%s\n' % triplet)
Dump a binary quadratic model to a string in COOrdinate format.
def run_command(self, command, arg=None, is_eval=False, member_id=None): """run command on replica set if member_id is specified command will be execute on this server if member_id is not specified command will be execute on the primary Args: command - command string ...
run command on replica set if member_id is specified command will be execute on this server if member_id is not specified command will be execute on the primary Args: command - command string arg - command argument is_eval - if True execute command as eval ...
def genesis_block_audit(genesis_block_stages, key_bundle=GENESIS_BLOCK_SIGNING_KEYS): """ Verify the authenticity of the stages of the genesis block, optionally with a given set of keys. Return True if valid Return False if not """ gpg2_path = find_gpg2() if gpg2_path is None: raise ...
Verify the authenticity of the stages of the genesis block, optionally with a given set of keys. Return True if valid Return False if not
def _Rforce(self,R,z,phi=0.,t=0.): """ NAME: _Rforce PURPOSE: evaluate the radial force for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: ...
NAME: _Rforce PURPOSE: evaluate the radial force for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: the radial force HISTORY: 2010-07-10...
def create_row_to_some_id_col_mapping(id_array): """ Parameters ---------- id_array : 1D ndarray. All elements of the array should be ints representing some id related to the corresponding row. Returns ------- rows_to_ids : 2D scipy sparse array. Will map each row of...
Parameters ---------- id_array : 1D ndarray. All elements of the array should be ints representing some id related to the corresponding row. Returns ------- rows_to_ids : 2D scipy sparse array. Will map each row of id_array to the unique values of `id_array`. The col...
def on_change_checkout(self): ''' When you change checkout or checkin update dummy field ----------------------------------------------------------- @param self: object pointer @return: raise warning depending on the validation ''' checkout_date = time.strftime(dt...
When you change checkout or checkin update dummy field ----------------------------------------------------------- @param self: object pointer @return: raise warning depending on the validation
def create_server(self, *args, **kwargs): """ Wraps :meth:`bang.providers.openstack.Nova.create_server` to apply hpcloud specialization, namely pulling IP addresses from the hpcloud's non-standard return values. """ # hpcloud's management console stuffs all of its tags i...
Wraps :meth:`bang.providers.openstack.Nova.create_server` to apply hpcloud specialization, namely pulling IP addresses from the hpcloud's non-standard return values.
def rnn(bptt, vocab_size, num_embed, nhid, num_layers, dropout, num_proj, batch_size): """ word embedding + LSTM Projected """ state_names = [] data = S.var('data') weight = S.var("encoder_weight", stype='row_sparse') embed = S.sparse.Embedding(data=data, weight=weight, input_dim=vocab_size, ...
word embedding + LSTM Projected
def _tf_restore_batch_dims(x, num_nonbatch_dims, prototype): """Reverse op of _tf_flatten_batch_dims. Un-flatten the first dimension of x to match all but the last num_nonbatch_dims dimensions of prototype. Args: x: a tf.Tensor with 1 + num_nonbatch_dims dimensions num_nonbatch_dims: an integer pr...
Reverse op of _tf_flatten_batch_dims. Un-flatten the first dimension of x to match all but the last num_nonbatch_dims dimensions of prototype. Args: x: a tf.Tensor with 1 + num_nonbatch_dims dimensions num_nonbatch_dims: an integer prototype: a tf.Tensor Returns: a tf.Tensor
def stop_subscribe(self): """ This function is used to stop the event loop created when subscribe is called. But this function doesn't stop the thread and should be avoided until its completely developed. """ asyncio.gather(*asyncio.Task.all_tasks()).cancel() self.event_loop.sto...
This function is used to stop the event loop created when subscribe is called. But this function doesn't stop the thread and should be avoided until its completely developed.
def add_resource( self, base_rule, base_view, alternate_view=None, alternate_rule=None, id_rule=None, app=None, ): """Add route or routes for a resource. :param str base_rule: The URL rule for the resource. This will be prefixed by...
Add route or routes for a resource. :param str base_rule: The URL rule for the resource. This will be prefixed by the API prefix. :param base_view: Class-based view for the resource. :param alternate_view: If specified, an alternate class-based view for the resource. Usu...
def search_commits(self, query, sort=github.GithubObject.NotSet, order=github.GithubObject.NotSet, **qualifiers): """ :calls: `GET /search/commits <http://developer.github.com/v3/search>`_ :param query: string :param sort: string ('author-date', 'committer-date') :param order: st...
:calls: `GET /search/commits <http://developer.github.com/v3/search>`_ :param query: string :param sort: string ('author-date', 'committer-date') :param order: string ('asc', 'desc') :param qualifiers: keyword dict query qualifiers :rtype: :class:`github.PaginatedList.PaginatedLi...
def clonemedium(medium, uuid_in=None, file_in=None, uuid_out=None, file_out=None, mformat=None, variant=None, existing=False, **kwargs): ''' Clone a new VM from an existing VM CLI...
Clone a new VM from an existing VM CLI Example: .. code-block:: bash salt 'hypervisor' vboxmanage.clonemedium <name> <new_name>
def save(self, inplace=True): """ Saves all modification to the marker on the server. :param inplace Apply edits on the current instance or get a new one. :return: Marker instance. """ modified_data = self._modified_data() if bool(modified_data): extra...
Saves all modification to the marker on the server. :param inplace Apply edits on the current instance or get a new one. :return: Marker instance.
def _to_dict(self, node): """convert (key, value) stored in this and the descendant nodes to dict items. :param node: node in form of list, or BLANK_NODE .. note:: Here key is in full form, rather than key of the individual node """ if node == BLANK_NODE: ...
convert (key, value) stored in this and the descendant nodes to dict items. :param node: node in form of list, or BLANK_NODE .. note:: Here key is in full form, rather than key of the individual node
def get_hkr_state(self): """Get the thermostate state.""" self.update() try: return { 126.5: 'off', 127.0: 'on', self.eco_temperature: 'eco', self.comfort_temperature: 'comfort' }[self.target_temperature] ...
Get the thermostate state.
def drawDisplay( self, painter, option, rect, text ): """ Handles the display drawing for this delegate. :param painter | <QPainter> option | <QStyleOption> rect | <QRect> text | <str> """ painter.se...
Handles the display drawing for this delegate. :param painter | <QPainter> option | <QStyleOption> rect | <QRect> text | <str>
async def _notify_update(self, name, change_type, change_info=None, directed_client=None): """Notify updates on a service to anyone who cares.""" for monitor in self._monitors: try: result = monitor(name, change_type, change_info, directed_client=directed_client) ...
Notify updates on a service to anyone who cares.
def gzip_dir(path, compresslevel=6): """ Gzips all files in a directory. Note that this is different from shutil.make_archive, which creates a tar archive. The aim of this method is to create gzipped files that can still be read using common Unix-style commands like zless or zcat. Args: ...
Gzips all files in a directory. Note that this is different from shutil.make_archive, which creates a tar archive. The aim of this method is to create gzipped files that can still be read using common Unix-style commands like zless or zcat. Args: path (str): Path to directory. compressl...
def get_instance(self, payload): """ Build an instance of FaxMediaInstance :param dict payload: Payload response from the API :returns: twilio.rest.fax.v1.fax.fax_media.FaxMediaInstance :rtype: twilio.rest.fax.v1.fax.fax_media.FaxMediaInstance """ return FaxMedi...
Build an instance of FaxMediaInstance :param dict payload: Payload response from the API :returns: twilio.rest.fax.v1.fax.fax_media.FaxMediaInstance :rtype: twilio.rest.fax.v1.fax.fax_media.FaxMediaInstance
def __analizar_evento(self, ret): "Comprueba y extrae el wvento informativo si existen en la respuesta XML" evt = ret.get('evento') if evt: self.Eventos = [evt] self.Evento = "%(codigo)s: %(descripcion)s" % evt
Comprueba y extrae el wvento informativo si existen en la respuesta XML
def _parse_saved_model(path): """Reads the savedmodel.pb file containing `SavedModel`.""" # Based on tensorflow/python/saved_model/loader.py implementation. path_to_pb = _get_saved_model_proto_path(path) file_content = tf_v1.gfile.Open(path_to_pb, "rb").read() saved_model = saved_model_pb2.SavedModel() try:...
Reads the savedmodel.pb file containing `SavedModel`.
def check_user(self, todays_facts): """check if we need to notify user perhaps""" interval = self.conf_notify_interval if interval <= 0 or interval >= 121: return now = dt.datetime.now() message = None last_activity = todays_facts[-1] if todays_facts else No...
check if we need to notify user perhaps
def get_notifications(self, **params): """https://developers.coinbase.com/api/v2#list-notifications""" response = self._get('v2', 'notifications', params=params) return self._make_api_object(response, Notification)
https://developers.coinbase.com/api/v2#list-notifications
def get_queryset(self): """ Returns queryset instance. :rtype: django.db.models.query.QuerySet. """ queryset = super(IndexView, self).get_queryset() search_form = self.get_search_form() if search_form.is_valid(): query_str = search_form.cleaned_...
Returns queryset instance. :rtype: django.db.models.query.QuerySet.
def extrap_sec(data, dist, depth, w1=1.0, w2=0): """ Extrapolates `data` to zones where the shallow stations are shadowed by the deep stations. The shadow region usually cannot be extrapolates via linear interpolation. The extrapolation is applied using the gradients of the `data` at a certain ...
Extrapolates `data` to zones where the shallow stations are shadowed by the deep stations. The shadow region usually cannot be extrapolates via linear interpolation. The extrapolation is applied using the gradients of the `data` at a certain level. Parameters ---------- data : array_like ...
def get_keys_from_ldap(self, username=None): """ Fetch keys from ldap. Args: username Username associated with keys to fetch (optional) Returns: Array of dictionaries in '{username: [public keys]}' format """ result_dict = {} filter = ['...
Fetch keys from ldap. Args: username Username associated with keys to fetch (optional) Returns: Array of dictionaries in '{username: [public keys]}' format
def pack(fmt, *args, **kwargs): """pack(fmt, v1, v2, ..., endian=None, target=None) Return a string containing the values v1, v2, ... packed according to the given format. The actual packing is performed by ``struct.pack`` but the byte order will be set according to the given `endian`, `target` or ...
pack(fmt, v1, v2, ..., endian=None, target=None) Return a string containing the values v1, v2, ... packed according to the given format. The actual packing is performed by ``struct.pack`` but the byte order will be set according to the given `endian`, `target` or byte order of the global target. A...
def set_fingerprint(fullpath, fingerprint=None): """ Set the last known modification time for a file """ try: fingerprint = fingerprint or utils.file_fingerprint(fullpath) record = model.FileFingerprint.get(file_path=fullpath) if record: record.set(fingerprint=fingerprint, ...
Set the last known modification time for a file
def transform(self, vector): """ Applies transformation on a vector or an RDD[Vector]. .. note:: In Python, transform cannot currently be used within an RDD transformation or action. Call transform directly on the RDD instead. :param vector: Vector or RDD of Vec...
Applies transformation on a vector or an RDD[Vector]. .. note:: In Python, transform cannot currently be used within an RDD transformation or action. Call transform directly on the RDD instead. :param vector: Vector or RDD of Vector to be transformed.
def get(self, timeout=None, block=True): """ Return the next enqueued object, or sleep waiting for one. :param float timeout: If not :data:`None`, specifies a timeout in seconds. :param bool block: If :data:`False`, immediately raise :class:`mitogen....
Return the next enqueued object, or sleep waiting for one. :param float timeout: If not :data:`None`, specifies a timeout in seconds. :param bool block: If :data:`False`, immediately raise :class:`mitogen.core.TimeoutError` if the latch is empty. :raises mi...
def Update(self, attribute=None): """Refresh an old attribute. Note that refreshing the attribute is asynchronous. It does not change anything about the current object - you need to reopen the same URN some time later to get fresh data. Attributes: CONTAINS - Refresh the content of the directory l...
Refresh an old attribute. Note that refreshing the attribute is asynchronous. It does not change anything about the current object - you need to reopen the same URN some time later to get fresh data. Attributes: CONTAINS - Refresh the content of the directory listing. Args: attribute: An at...
def uniform_spacings(N): """ Generate ordered uniform variates in O(N) time. Parameters ---------- N: int (>0) the expected number of uniform variates Returns ------- (N,) float ndarray the N ordered variates (ascending order) Note ---- This is equivalent to::...
Generate ordered uniform variates in O(N) time. Parameters ---------- N: int (>0) the expected number of uniform variates Returns ------- (N,) float ndarray the N ordered variates (ascending order) Note ---- This is equivalent to:: from numpy import rando...
def running_apps(device_id): """ Get running apps via HTTP GET. """ if not is_valid_device_id(device_id): abort(403) if device_id not in devices: abort(404) return jsonify(running_apps=devices[device_id].running_apps)
Get running apps via HTTP GET.
def f_remove_child(self, name, recursive=False, predicate=None): """Removes a child of the group. Note that groups and leaves are only removed from the current trajectory in RAM. If the trajectory is stored to disk, this data is not affected. Thus, removing children can be only be used ...
Removes a child of the group. Note that groups and leaves are only removed from the current trajectory in RAM. If the trajectory is stored to disk, this data is not affected. Thus, removing children can be only be used to free RAM memory! If you want to free memory on disk via your sto...
def transform(self, audio_f=None, jam=None, y=None, sr=None, crop=False): '''Apply the transformations to an audio file, and optionally JAMS object. Parameters ---------- audio_f : str Path to audio file jam : optional, `jams.JAMS`, str or file-like Opti...
Apply the transformations to an audio file, and optionally JAMS object. Parameters ---------- audio_f : str Path to audio file jam : optional, `jams.JAMS`, str or file-like Optional JAMS object/path to JAMS file/open file descriptor. If provided, th...
def type_errors(self, context=None): """Get a list of type errors which can occur during inference. Each TypeError is represented by a :class:`BadBinaryOperationMessage` , which holds the original exception. :returns: The list of possible type errors. :rtype: list(BadBinaryOper...
Get a list of type errors which can occur during inference. Each TypeError is represented by a :class:`BadBinaryOperationMessage` , which holds the original exception. :returns: The list of possible type errors. :rtype: list(BadBinaryOperationMessage)
def __get_ml_configuration_status(self, job_id): """ After invoking the create_ml_configuration async method, you can use this method to check on the status of the builder job. :param job_id: The identifier returned from create_ml_configuration :return: Job status """ ...
After invoking the create_ml_configuration async method, you can use this method to check on the status of the builder job. :param job_id: The identifier returned from create_ml_configuration :return: Job status
def add(self, pattern): """Decorator to add new dispatch functions.""" def wrap(f): self.functions.append((f, pattern)) return f return wrap
Decorator to add new dispatch functions.
def pool_delete(storage_pool, logger): """Storage Pool deletion, removes all the created disk images within the pool and the pool itself.""" path = etree.fromstring(storage_pool.XMLDesc(0)).find('.//path').text volumes_delete(storage_pool, logger) try: storage_pool.destroy() except libvirt...
Storage Pool deletion, removes all the created disk images within the pool and the pool itself.
def update_floatingip_statuses_cfg(self, context, router_id, fip_statuses): """Update operational status for one or several floating IPs. This is called by Cisco cfg agent to update the status of one or several floatingips. :param context: contains user information :param route...
Update operational status for one or several floating IPs. This is called by Cisco cfg agent to update the status of one or several floatingips. :param context: contains user information :param router_id: id of router associated with the floatingips :param router_id: dict with ...
def _get_centered_z1pt0(self, sites): """ Get z1pt0 centered on the Vs30- dependent avarage z1pt0(m) California and non-Japan regions """ #: California and non-Japan regions mean_z1pt0 = (-7.15 / 4.) * np.log(((sites.vs30) ** 4. + 570.94 ** 4.) ...
Get z1pt0 centered on the Vs30- dependent avarage z1pt0(m) California and non-Japan regions
def finalize_canonical_averages( number_of_nodes, ps, canonical_averages, alpha, ): """ Finalize canonical averages """ spanning_cluster = ( ( 'percolation_probability_mean' in canonical_averages.dtype.names ) and 'percolation_probability_m2' in canon...
Finalize canonical averages
def extras_msg(extras): """ Create an error message for extra items or properties. """ if len(extras) == 1: verb = "was" else: verb = "were" return ", ".join(repr(extra) for extra in extras), verb
Create an error message for extra items or properties.
def check_token_payment(name, token_price, stacks_payment_info): """ Check a token payment was enough and was of the right type Return {'status': True, 'tokens_paid': ..., 'token_units': ...} if so Return {'status': False} if not """ token_units = stacks_payment_info['token_units'] tokens_pa...
Check a token payment was enough and was of the right type Return {'status': True, 'tokens_paid': ..., 'token_units': ...} if so Return {'status': False} if not
def get(self, names, country_id=None, language_id=None, retheader=False): """ Look up gender for a list of names. Can optionally refine search with locale info. May make multiple requests if there are more names than can be retrieved in one call. :param names: List of na...
Look up gender for a list of names. Can optionally refine search with locale info. May make multiple requests if there are more names than can be retrieved in one call. :param names: List of names. :type names: Iterable[str] :param country_id: Optional ISO 3166-1 alpha-2...
def presnyields(self, *cycles, **keyw): """ This function calculates the presupernova yields of a full structure profile from a remnant mass, mrem, to the surface. Parameters ---------- cycles : variadic tuple cycle[0] is the cycle to perform the presupernova...
This function calculates the presupernova yields of a full structure profile from a remnant mass, mrem, to the surface. Parameters ---------- cycles : variadic tuple cycle[0] is the cycle to perform the presupernova yields calculations on. If cycle[1] is also sp...
def add_instance(model, _commit=True, **kwargs): """Add instance to database. :param model: a string, model name in rio.models :param _commit: control whether commit data to database or not. Default True. :param \*\*kwargs: persisted data. :return: instance id. """ try: model = get_...
Add instance to database. :param model: a string, model name in rio.models :param _commit: control whether commit data to database or not. Default True. :param \*\*kwargs: persisted data. :return: instance id.
def addSuffixToExtensions(toc): """ Returns a new TOC with proper library suffix for EXTENSION items. """ new_toc = TOC() for inm, fnm, typ in toc: if typ in ('EXTENSION', 'DEPENDENCY'): binext = os.path.splitext(fnm)[1] if not os.path.splitext(inm)[1] == binext: ...
Returns a new TOC with proper library suffix for EXTENSION items.
def add(self, command_template, job_class): """ Given a command template, add it as a job to the queue. """ job = JobTemplate(command_template.alias, command_template=command_template, depends_on=command_template.depends_on, queue=self.queue, job_class=job_class) ...
Given a command template, add it as a job to the queue.