code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def __readimzmlmeta(self): """ This method should only be called by __init__. Initializes the imzmldict with frequently used metadata from the .imzML file. This method reads only a subset of the available meta information and may be extended in the future. The keys are named sim...
This method should only be called by __init__. Initializes the imzmldict with frequently used metadata from the .imzML file. This method reads only a subset of the available meta information and may be extended in the future. The keys are named similarly to the imzML names. Currently supported ...
def extract_tree(self, labels, without, suppress_unifurcations=True): '''Helper function for ``extract_tree_*`` functions''' if not isinstance(suppress_unifurcations, bool): raise TypeError("suppress_unifurcations must be a bool") if labels is not None and not isinstance(labels, set)...
Helper function for ``extract_tree_*`` functions
def rehearse(self, docs, sgd=None, losses=None, config=None): """Make a "rehearsal" update to the models in the pipeline, to prevent forgetting. Rehearsal updates run an initial copy of the model over some data, and update the model so its current predictions are more like the initial on...
Make a "rehearsal" update to the models in the pipeline, to prevent forgetting. Rehearsal updates run an initial copy of the model over some data, and update the model so its current predictions are more like the initial ones. This is useful for keeping a pre-trained model on-track, even...
def results(cls, function, group=None): """ Returns a numpy nparray representing the benchmark results of a function in a group. """ return numpy.array(cls._results[group][function])
Returns a numpy nparray representing the benchmark results of a function in a group.
def van_dec_2d(x, skip_connections, output_shape, first_depth, hparams=None): """The VAN decoder. Args: x: The analogy information to decode. skip_connections: The encoder layers which can be used as skip connections. output_shape: The shape of the desired output image. first_depth: The depth of th...
The VAN decoder. Args: x: The analogy information to decode. skip_connections: The encoder layers which can be used as skip connections. output_shape: The shape of the desired output image. first_depth: The depth of the first layer of the van image encoder. hparams: The python hparams. Returns...
def process_request(self, request): """ The actual middleware method, called on all incoming requests. This default implementation will ignore the middleware (return None) if the conditions specified in is_resource_protected aren't met. If they are, it then tests to see if the u...
The actual middleware method, called on all incoming requests. This default implementation will ignore the middleware (return None) if the conditions specified in is_resource_protected aren't met. If they are, it then tests to see if the user should be denied access via the denied_access_condit...
def critical_angle(pressure, u, v, heights, stormu, stormv): r"""Calculate the critical angle. The critical angle is the angle between the 10m storm-relative inflow vector and the 10m-500m shear vector. A critical angle near 90 degrees indicates that a storm in this environment on the indicated storm m...
r"""Calculate the critical angle. The critical angle is the angle between the 10m storm-relative inflow vector and the 10m-500m shear vector. A critical angle near 90 degrees indicates that a storm in this environment on the indicated storm motion vector is likely ingesting purely streamwise vorticity ...
def ccmod_setcoef(k): """Set the coefficient maps for the ccmod stage. The only parameter is the slice index `k` and there are no return values; all inputs and outputs are from and to global variables. """ # Set working coefficient maps for ccmod step and compute DFT of # coefficient maps Z and...
Set the coefficient maps for the ccmod stage. The only parameter is the slice index `k` and there are no return values; all inputs and outputs are from and to global variables.
def usage(asked_for=0): '''Exit with a usage string, used for bad argument or with -h''' exit = fsq.const('FSQ_SUCCESS') if asked_for else\ fsq.const('FSQ_FAIL_PERM') f = sys.stdout if asked_for else sys.stderr shout('{0} [opts] src_queue trg_queue host item_id [item_id [...]]'.format( ...
Exit with a usage string, used for bad argument or with -h
def ack(self, message, subscription_id=None, **kwargs): """Acknowledge receipt of a message. This only makes sense when the 'acknowledgement' flag was set for the relevant subscription. :param message: ID of the message to be acknowledged, OR a dictionary containing a fie...
Acknowledge receipt of a message. This only makes sense when the 'acknowledgement' flag was set for the relevant subscription. :param message: ID of the message to be acknowledged, OR a dictionary containing a field 'message-id'. :param subscription_id: ID of the associat...
def get_md5(string): """Get a string's MD5""" try: hasher = hashlib.md5() except BaseException: hasher = hashlib.new('md5', usedForSecurity=False) hasher.update(string) return hasher.hexdigest()
Get a string's MD5
def copy_images(images, source, target): """ Copy images to converted topology :param images: Images to copy :param source: Old Topology Directory :param target: Target topology files directory :return: True when an image cannot be found, otherwise false :rtype: bool """ image_err =...
Copy images to converted topology :param images: Images to copy :param source: Old Topology Directory :param target: Target topology files directory :return: True when an image cannot be found, otherwise false :rtype: bool
def refresh(self, item): """ Forces a refresh of a cached item. :param item: Client name. :type item: unicode | str :return: Items in the cache. :rtype: DockerHostItemCache.item_class """ client = self._clients[item].get_client() self[item] = val ...
Forces a refresh of a cached item. :param item: Client name. :type item: unicode | str :return: Items in the cache. :rtype: DockerHostItemCache.item_class
def on_resize(width, height): """Setup 3D projection""" glViewport(0, 0, width, height) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(30, 1.0*width/height, 0.1, 1000.0) glMatrixMode(GL_MODELVIEW) glLoadIdentity()
Setup 3D projection
def _get_arguments_for_execution(self, function_name, serialized_args): """Retrieve the arguments for the remote function. This retrieves the values for the arguments to the remote function that were passed in as object IDs. Arguments that were passed by value are not changed. This is c...
Retrieve the arguments for the remote function. This retrieves the values for the arguments to the remote function that were passed in as object IDs. Arguments that were passed by value are not changed. This is called by the worker that is executing the remote function. Args: ...
def spline_base1d(length, nr_knots = 20, spline_order = 5, marginal = None): """Computes a 1D spline basis Input: length: int length of each basis nr_knots: int Number of knots, i.e. number of basis functions. spline_order: int Order of the splin...
Computes a 1D spline basis Input: length: int length of each basis nr_knots: int Number of knots, i.e. number of basis functions. spline_order: int Order of the splines. marginal: array, optional Estimate of the marginal distribut...
def add(self, url: str, anything: Any) -> None: """ Register a URL pattern into\ the routes for later matching. It's possible to attach any kind of\ object to the pattern for later\ retrieving. A dict with methods and callbacks,\ for example. Anything really. ...
Register a URL pattern into\ the routes for later matching. It's possible to attach any kind of\ object to the pattern for later\ retrieving. A dict with methods and callbacks,\ for example. Anything really. Registration order does not matter.\ Adding a URL firs...
def write_stream (stream, holders, defaultsection=None): """Very simple writing in ini format. The simple stringification of each value in each Holder is printed, and no escaping is performed. (This is most relevant for multiline values or ones containing pound signs.) `None` values are skipped. Ar...
Very simple writing in ini format. The simple stringification of each value in each Holder is printed, and no escaping is performed. (This is most relevant for multiline values or ones containing pound signs.) `None` values are skipped. Arguments: stream A text stream to write to. holder...
def precess_coordinates(ra, dec, epoch_one, epoch_two, jd=None, mu_ra=0.0, mu_dec=0.0, outscalar=False): '''Precesses target coordinates `ra`, `dec` from `epoch_one` to `epoch_two`. This take...
Precesses target coordinates `ra`, `dec` from `epoch_one` to `epoch_two`. This takes into account the jd of the observations, as well as the proper motion of the target mu_ra, mu_dec. Adapted from J. D. Hartman's VARTOOLS/converttime.c [coordprecess]. Parameters ---------- ra,dec : float ...
def rr_history(self, ips): """Get the domains related to input ips. Args: ips: an enumerable of strings as ips Returns: An enumerable of resource records and features """ api_name = 'opendns-rr_history' fmt_url_path = u'dnsdb/ip/a/{0}.json' ...
Get the domains related to input ips. Args: ips: an enumerable of strings as ips Returns: An enumerable of resource records and features
def install(zone, nodataset=False, brand_opts=None): ''' Install the specified zone from the system. zone : string name of the zone nodataset : boolean do not create a ZFS file system brand_opts : string brand specific options to pass CLI Example: .. code-block:: b...
Install the specified zone from the system. zone : string name of the zone nodataset : boolean do not create a ZFS file system brand_opts : string brand specific options to pass CLI Example: .. code-block:: bash salt '*' zoneadm.install dolores salt '*' zo...
def user_choice(prompt, choices=("yes", "no"), default=None): """ Prompts the user for confirmation. The default value, if any, is capitalized. :param prompt: Information to display to the user. :param choices: an iterable of possible choices. :param default: default choice :return: the user's...
Prompts the user for confirmation. The default value, if any, is capitalized. :param prompt: Information to display to the user. :param choices: an iterable of possible choices. :param default: default choice :return: the user's choice
def execute_migrations(self, show_traceback=True): """ Executes all pending migrations across all capable databases """ all_migrations = get_pending_migrations(self.path, self.databases) if not len(all_migrations): sys.stdout.write("There are no migra...
Executes all pending migrations across all capable databases
def import_module(path): """ Import a module given a dotted *path* in the form of ``.name(.name)*``, and returns the last module (unlike ``__import__`` which just returns the first module). :param path: The dotted path to the module. """ mod = __import__(path, locals={}, globals={}) ...
Import a module given a dotted *path* in the form of ``.name(.name)*``, and returns the last module (unlike ``__import__`` which just returns the first module). :param path: The dotted path to the module.
def all_cities(): """ Get a list of all Backpage city names. Returns: list of city names as Strings """ cities = [] fname = pkg_resources.resource_filename(__name__, 'resources/CityPops.csv') with open(fname, 'rU') as csvfile: reader = csv.reader(csvfile, delimiter = ',') for row in reader: ...
Get a list of all Backpage city names. Returns: list of city names as Strings
def sector_shift(self): """ Property with current sector size shift. Actually sector size is 2 ** sector shift """ header = self.source.header return header.mini_sector_shift if self._is_mini \ else header.sector_shift
Property with current sector size shift. Actually sector size is 2 ** sector shift
def _extend_str(class_node, rvalue): """function to extend builtin str/unicode class""" code = dedent( """ class whatever(object): def join(self, iterable): return {rvalue} def replace(self, old, new, count=None): return {rvalue} def format(self, *args...
function to extend builtin str/unicode class
def addcomment(accountable, body): """ Add a comment to the given issue key. Accepts a body argument to be used as the comment's body. """ r = accountable.issue_add_comment(body) headers = sorted(['author_name', 'body', 'updated']) rows = [[v for k, v in sorted(r.items()) if k in headers]] ...
Add a comment to the given issue key. Accepts a body argument to be used as the comment's body.
def insert_child(self, child_pid, index=-1): """Insert a new child into a PID concept. Argument 'index' can take the following values: 0,1,2,... - insert child PID at the specified position -1 - insert the child PID at the last position None - insert child without or...
Insert a new child into a PID concept. Argument 'index' can take the following values: 0,1,2,... - insert child PID at the specified position -1 - insert the child PID at the last position None - insert child without order (no re-ordering is done) NOTE: If 'inde...
def uri(self): """Connection string to pass to `~pymongo.mongo_client.MongoClient`.""" if self._uds_path: uri = 'mongodb://%s' % (quote_plus(self._uds_path),) else: uri = 'mongodb://%s' % (format_addr(self._address),) return uri + '/?ssl=true' if self._ssl else ur...
Connection string to pass to `~pymongo.mongo_client.MongoClient`.
def get_authors(self, language): """ Return the list of this task's authors """ return self.gettext(language, self._author) if self._author else ""
Return the list of this task's authors
def get_last_scene_id(self, refresh=False): """Get last scene id. Refresh data from Vera if refresh is True, otherwise use local cache. Refresh is only needed if you're not using subscriptions. """ if refresh: self.refresh_complex_value('LastSceneID') sel...
Get last scene id. Refresh data from Vera if refresh is True, otherwise use local cache. Refresh is only needed if you're not using subscriptions.
def copyVarStatesFrom(self, particleState, varNames): """Copy specific variables from particleState into this particle. Parameters: -------------------------------------------------------------- particleState: dict produced by a particle's getState() method varNames: which variab...
Copy specific variables from particleState into this particle. Parameters: -------------------------------------------------------------- particleState: dict produced by a particle's getState() method varNames: which variables to copy
def byte_to_channels(self, byte): """ :return: list(int) """ # pylint: disable-msg=R0201 assert isinstance(byte, int) assert byte >= 0 assert byte < 256 result = [] for offset in range(0, 8): if byte & (1 << offset): ...
:return: list(int)
def index(path=None): """On all other routes, just return an example `curl` command.""" payload = { "username": "soandso", "message": "Hello bot", "vars": { "name": "Soandso", } } return Response(r"""Usage: curl -i \ -H "Content-Type: application/json" \ ...
On all other routes, just return an example `curl` command.
def result_to_dict(raw_result): """ Parse raw result from fetcher into readable dictionary Args: raw_result (dict) - raw data from `fetcher` Returns: dict - readable dictionary """ result = {} for channel_index, channel in enumerate(raw_result): channel_id, channe...
Parse raw result from fetcher into readable dictionary Args: raw_result (dict) - raw data from `fetcher` Returns: dict - readable dictionary
def run(self) -> None: """ 创建了 sock 的运行回调 """ if self.loop is None: return create_server = asyncio.ensure_future(self._run(), loop=self.loop) # type: ignore try: self.loop.run_until_complete(create_server) self.loop.run_until_complete(...
创建了 sock 的运行回调
def sbar(Ss): """ calculate average s,sigma from list of "s"s. """ if type(Ss) == list: Ss = np.array(Ss) npts = Ss.shape[0] Ss = Ss.transpose() avd, avs = [], [] # D=np.array([Ss[0],Ss[1],Ss[2],Ss[3]+0.5*(Ss[0]+Ss[1]),Ss[4]+0.5*(Ss[1]+Ss[2]),Ss[5]+0.5*(Ss[0]+Ss[2])]).transpose(...
calculate average s,sigma from list of "s"s.
def error_asymptotes(pca,**kwargs): """ Plots asymptotic error bounds for hyperbola on a stereonet. """ ax = kwargs.pop("ax",current_axes()) lon,lat = pca.plane_errors('upper', n=1000) ax.plot(lon,lat,'-') lon,lat = pca.plane_errors('lower', n=1000) ax.plot(lon,lat,'-') ax.pla...
Plots asymptotic error bounds for hyperbola on a stereonet.
def __get_constants(self): """ Gets the constants from the class that acts like a namespace for constants and adds them to the replace pairs. """ helper = ConstantClass(self._constants_class_name, self._io) helper.reload() constants = helper.constants() for name,...
Gets the constants from the class that acts like a namespace for constants and adds them to the replace pairs.
def console_print(con: tcod.console.Console, x: int, y: int, fmt: str) -> None: """Print a color formatted string on a console. Args: con (Console): Any Console instance. x (int): Character x position from the left. y (int): Character y position from the top. fmt (AnyStr): A uni...
Print a color formatted string on a console. Args: con (Console): Any Console instance. x (int): Character x position from the left. y (int): Character y position from the top. fmt (AnyStr): A unicode or bytes string optionaly using color codes. .. deprecated:: 8.5 Use ...
def _show_or_dump(self, dump=False, indent=3, lvl="", label_lvl="", first_call=True): # noqa: E501 """ Internal method that shows or dumps a hierarchical view of a packet. Called by show. :param dump: determine if it prints or returns the string value :param int indent: the siz...
Internal method that shows or dumps a hierarchical view of a packet. Called by show. :param dump: determine if it prints or returns the string value :param int indent: the size of indentation for each layer :param str lvl: additional information about the layer lvl :param str la...
def view_include(view_module, namespace=None, app_name=None): """ Includes view in the url, works similar to django include function. Auto imports all class based views that are subclass of ``URLView`` and all functional views that have been decorated with ``url_view``. :param view_module: object o...
Includes view in the url, works similar to django include function. Auto imports all class based views that are subclass of ``URLView`` and all functional views that have been decorated with ``url_view``. :param view_module: object of the module or string with importable path :param namespace: name of ...
def ParseOptions(cls, options, config_object, category=None, names=None): """Parses and validates arguments using the appropriate helpers. Args: options (argparse.Namespace): parser options. config_object (object): object to be configured by an argument helper. category (Optional[str]): categ...
Parses and validates arguments using the appropriate helpers. Args: options (argparse.Namespace): parser options. config_object (object): object to be configured by an argument helper. category (Optional[str]): category of helpers to apply to the group, such as storage, output, where No...
def update_check(self, entity, check, label=None, name=None, disabled=None, metadata=None, monitoring_zones_poll=None, timeout=None, period=None, target_alias=None, target_hostname=None, target_receiver=None): """ Updates an existing check with any of the parameters. ...
Updates an existing check with any of the parameters.
def ucas_download_playlist(url, output_dir = '.', merge = False, info_only = False, **kwargs): '''course page''' html = get_content(url) parts = re.findall( r'(getplaytitle.do\?.+)"', html) assert parts, 'No part found!' for part_path in parts: ucas_download('http://v.ucas.ac.cn/course/' +...
course page
def memoized_method(method=None, cache_factory=None): """ Memoize a class's method. Arguments are similar to to `memoized`, except that the cache container is specified with `cache_factory`: a function called with no arguments to create the caching container for the instance. Note that, unlike `me...
Memoize a class's method. Arguments are similar to to `memoized`, except that the cache container is specified with `cache_factory`: a function called with no arguments to create the caching container for the instance. Note that, unlike `memoized`, the result cache will be stored on the instance, ...
def _handle_log_rotations(self): ''' Rotate each handler's log file if necessary ''' for h in self.capture_handlers: if self._should_rotate_log(h): self._rotate_log(h)
Rotate each handler's log file if necessary
def get(session, api_key, **kwargs): """ Выполняет доступ к API. session - модуль requests или сессия из него api_key - строка ключа доступа к API rate - тариф, может быть `informers` или `forecast` lat, lon - широта и долгота ``` import yandex_weather_api import requests as req ...
Выполняет доступ к API. session - модуль requests или сессия из него api_key - строка ключа доступа к API rate - тариф, может быть `informers` или `forecast` lat, lon - широта и долгота ``` import yandex_weather_api import requests as req yandex_weather_api.get(req, "ЗАМЕНИ_МЕНЯ_КЛЮЧО...
def _check_conflict(cls, dirPath, name): """ Check whether the module of the given name conflicts with another module on the sys.path. :param dirPath: the directory from which the module was originally loaded :param name: the mpdule name """ old_sys_path = sys.path ...
Check whether the module of the given name conflicts with another module on the sys.path. :param dirPath: the directory from which the module was originally loaded :param name: the mpdule name
def get_netloc_and_auth(self, netloc, scheme): """ This override allows the auth information to be passed to svn via the --username and --password options instead of via the URL. """ if scheme == 'ssh': # The --username and --password options can't be used for ...
This override allows the auth information to be passed to svn via the --username and --password options instead of via the URL.
def encode(i, *, width=-1): """Encodes a nonnegative integer into syncsafe format When width > 0, then len(result) == width When width < 0, then len(result) >= abs(width) """ if i < 0: raise ValueError("value is negative") assert width != 0 data = byt...
Encodes a nonnegative integer into syncsafe format When width > 0, then len(result) == width When width < 0, then len(result) >= abs(width)
def readline(self, size=-1): '''This reads and returns one entire line. The newline at the end of line is returned as part of the string, unless the file ends without a newline. An empty string is returned if EOF is encountered immediately. This looks for a newline as a CR/LF pair (\\r\\...
This reads and returns one entire line. The newline at the end of line is returned as part of the string, unless the file ends without a newline. An empty string is returned if EOF is encountered immediately. This looks for a newline as a CR/LF pair (\\r\\n) even on UNIX because this is ...
def verify_chunks(self, chunks): ''' Verify the chunks in a list of low data structures ''' err = [] for chunk in chunks: err.extend(self.verify_data(chunk)) return err
Verify the chunks in a list of low data structures
def load_config(self, argv=None, aliases=None, flags=None): """Parse command line arguments and return as a Config object. Parameters ---------- args : optional, list If given, a list with the structure of sys.argv[1:] to parse arguments from. If not given, the inst...
Parse command line arguments and return as a Config object. Parameters ---------- args : optional, list If given, a list with the structure of sys.argv[1:] to parse arguments from. If not given, the instance's self.argv attribute (given at construction time) is us...
def p_rst(p): """ asm : RST expr """ val = p[2].eval() if val not in (0, 8, 16, 24, 32, 40, 48, 56): error(p.lineno(1), 'Invalid RST number %i' % val) p[0] = None return p[0] = Asm(p.lineno(1), 'RST %XH' % val)
asm : RST expr
def del_calc(db, job_id, user): """ Delete a calculation and all associated outputs, if possible. :param db: a :class:`openquake.server.dbapi.Db` instance :param job_id: job ID, can be an integer or a string :param user: username :returns: None if everything went fine or an error message ""...
Delete a calculation and all associated outputs, if possible. :param db: a :class:`openquake.server.dbapi.Db` instance :param job_id: job ID, can be an integer or a string :param user: username :returns: None if everything went fine or an error message
def _build(self, inputs): """Connects the `TileByDim` module into the graph. Args: inputs: `Tensor` to tile. Returns: The tiled tensor. """ shape_inputs = inputs.get_shape().as_list() rank = len(shape_inputs) # Builds default lists for multiples to pass to `tf.tile`. full_...
Connects the `TileByDim` module into the graph. Args: inputs: `Tensor` to tile. Returns: The tiled tensor.
def combine_action_handlers(*handlers): """ This function combines the given action handlers into a single function which will call all of them. """ # make sure each of the given handlers is callable for handler in handlers: # if the handler is not a function if not (isco...
This function combines the given action handlers into a single function which will call all of them.
def unpack_binary(self, offset, length=False): """ Returns raw binary data from the relative offset with the given length. Arguments: - `offset`: The relative offset from the start of the block. - `length`: The length of the binary blob. If zero, the empty string zero...
Returns raw binary data from the relative offset with the given length. Arguments: - `offset`: The relative offset from the start of the block. - `length`: The length of the binary blob. If zero, the empty string zero length is returned. Throws: - `OverrunBufferExcept...
def get_deffacts(self): """Return the existing deffacts sorted by the internal order""" return sorted(self._get_by_type(DefFacts), key=lambda d: d.order)
Return the existing deffacts sorted by the internal order
def finish(self): """ Finishes the load job. Called automatically when the connection closes. :return: The exit code returned when applying rows to the table """ if self.finished: return self.exit_code checkpoint_status = self.checkpoint() self.exit_c...
Finishes the load job. Called automatically when the connection closes. :return: The exit code returned when applying rows to the table
def defer_sync(self, func): """ Arrange for `func()` to execute on :class:`Broker` thread, blocking the current thread until a result or exception is available. :returns: Return value of `func()`. """ latch = Latch() def wrapper(): try: ...
Arrange for `func()` to execute on :class:`Broker` thread, blocking the current thread until a result or exception is available. :returns: Return value of `func()`.
def master_callback(self, m, master): '''process mavlink message m on master, sending any messages to recipients''' # see if it is handled by a specialised sysid connection sysid = m.get_srcSystem() mtype = m.get_type() if sysid in self.mpstate.sysid_outputs: self.mp...
process mavlink message m on master, sending any messages to recipients
def _templated(fn): """ Return a function which applies ``str.format(**ctl)`` to all results of ``fn(ctl)``. """ @functools.wraps(fn) def inner(ctl): return [i.format(**ctl) for i in fn(ctl)] return inner
Return a function which applies ``str.format(**ctl)`` to all results of ``fn(ctl)``.
def get_snippet(self, snippet_id, timeout=None): """ API call to get a specific Snippet """ return self._api_request( self.SNIPPET_ENDPOINT % (snippet_id), self.HTTP_GET, timeout=timeout )
API call to get a specific Snippet
def getlist(self, name: str, default: Any = None) -> List[Any]: """Return the entire list""" return super().get(name, default)
Return the entire list
def accuracy(conf_matrix): """ Given a confusion matrix, returns the accuracy. Accuracy Definition: http://research.ics.aalto.fi/events/eyechallenge2005/evaluation.shtml """ total, correct = 0.0, 0.0 for true_response, guess_dict in conf_matrix.items(): for guess, count in guess_dict.items(): if t...
Given a confusion matrix, returns the accuracy. Accuracy Definition: http://research.ics.aalto.fi/events/eyechallenge2005/evaluation.shtml
def writeln(self, string='', *args, **kwargs): """Writes a string into the source code _and_ appends a new line, applying indentation if required """ self.write(string + '\n', *args, **kwargs) self.on_new_line = True # If we're writing a block, increment indent for th...
Writes a string into the source code _and_ appends a new line, applying indentation if required
def get_rms(self): """Gets the root mean square of the score. If this system is based on grades, the RMS of the output score is returned. return: (decimal) - the median score *compliance: mandatory -- This method must be implemented.* """ return np.sqrt(np.mean...
Gets the root mean square of the score. If this system is based on grades, the RMS of the output score is returned. return: (decimal) - the median score *compliance: mandatory -- This method must be implemented.*
def result_pretty(self, number_of_runs=0, time_str=None, fbestever=None): """pretty print result. Returns ``self.result()`` """ if fbestever is None: fbestever = self.best.f s = (' after %i restart' + ('s' if number_of_runs > 1 else '')) \ ...
pretty print result. Returns ``self.result()``
def save(self, *args, **kwargs): """ saves creates or updates current resource returns new resource """ self._pre_save(*args, **kwargs) response = self._save(*args, **kwargs) response = self._post_save(response, *args, **kwargs) return response
saves creates or updates current resource returns new resource
def String(self, str): """Get an interned string from the reader, allows for example to speedup string name comparisons """ ret = libxml2mod.xmlTextReaderConstString(self._o, str) return ret
Get an interned string from the reader, allows for example to speedup string name comparisons
def delete_instance(self, instance_id, project_id=None): """ Deletes an existing Cloud Spanner instance. :param instance_id: The ID of the Cloud Spanner instance. :type instance_id: str :param project_id: Optional, the ID of the GCP project that owns the Cloud Spanner ...
Deletes an existing Cloud Spanner instance. :param instance_id: The ID of the Cloud Spanner instance. :type instance_id: str :param project_id: Optional, the ID of the GCP project that owns the Cloud Spanner database. If set to None or missing, the default project_id from the GCP co...
def unpack_shards(shards, stream_arn, session): """List[Dict] -> Dict[shard_id, Shard]. Each Shards' parent/children are hooked up with the other Shards in the list. """ if not shards: return {} # When unpacking tokens, shard id key is "shard_id" # When unpacking DescribeStream respons...
List[Dict] -> Dict[shard_id, Shard]. Each Shards' parent/children are hooked up with the other Shards in the list.
def extract(self, destination, format='csv', csv_delimiter=None, csv_header=True, compress=False): """Exports the table to GCS; blocks until complete. Args: destination: the destination URI(s). Can be a single URI or a list. format: the format to use for the exported data; one of 'csv', 'json', or ...
Exports the table to GCS; blocks until complete. Args: destination: the destination URI(s). Can be a single URI or a list. format: the format to use for the exported data; one of 'csv', 'json', or 'avro' (default 'csv'). csv_delimiter: for CSV exports, the field delimiter to use. Defaul...
def delete(event, saltenv='base', test=None): ''' Delete a reactor CLI Example: .. code-block:: bash salt-run reactor.delete 'salt/cloud/*/destroyed' ''' sevent = salt.utils.event.get_event( 'master', __opts__['sock_dir'], __opts__['transport'], ...
Delete a reactor CLI Example: .. code-block:: bash salt-run reactor.delete 'salt/cloud/*/destroyed'
def auth_recv(self): """ Handle peer's IKE_AUTH response. """ id_r = auth_data = None for p in self.packets[-1].payloads: if p._type == payloads.Type.IDr: id_r = p logger.debug('Got responder ID: {}'.format(dump(bytes(p)))) ...
Handle peer's IKE_AUTH response.
def connect_array(self, address, connection_key, connection_type, **kwargs): """Connect this array with another one. :param address: IP address or DNS name of other array. :type address: str :param connection_key: Connection key of other array. :type connection_key: str ...
Connect this array with another one. :param address: IP address or DNS name of other array. :type address: str :param connection_key: Connection key of other array. :type connection_key: str :param connection_type: Type(s) of connection desired. :type connection_type: li...
def write_sources_list(url, codename, filename='ceph.list', mode=0o644): """add deb repo to /etc/apt/sources.list.d/""" repo_path = os.path.join('/etc/apt/sources.list.d', filename) content = 'deb {url} {codename} main\n'.format( url=url, codename=codename, ) write_file(repo_path, co...
add deb repo to /etc/apt/sources.list.d/
def update_context(self, context, update_mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Updates the specified...
Updates the specified context. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.ContextsClient() >>> >>> # TODO: Initialize ``context``: >>> context = {} >>> >>> response = client.update_context(cont...
def comunicar_certificado_icpbrasil(self, certificado): """Sobrepõe :meth:`~satcfe.base.FuncoesSAT.comunicar_certificado_icpbrasil`. :return: Uma resposta SAT padrão. :rtype: satcfe.resposta.padrao.RespostaSAT """ resp = self._http_post('comunicarcertificadoicpbrasil', ...
Sobrepõe :meth:`~satcfe.base.FuncoesSAT.comunicar_certificado_icpbrasil`. :return: Uma resposta SAT padrão. :rtype: satcfe.resposta.padrao.RespostaSAT
def get_driver(self): ''' Get an already running instance of Webdriver. If there is none, it will create one. Returns: Webdriver - Selenium Webdriver instance. Usage:: driver = WTF_WEBDRIVER_MANAGER.new_driver() driver.get("http://the-internet.herok...
Get an already running instance of Webdriver. If there is none, it will create one. Returns: Webdriver - Selenium Webdriver instance. Usage:: driver = WTF_WEBDRIVER_MANAGER.new_driver() driver.get("http://the-internet.herokuapp.com") same_driver = WTF_W...
def _child(details): """Child A private function to figure out the child node type Arguments: details {dict} -- A dictionary describing a data point Returns: _NodeInterface """ # If the details are a list if isinstance(details, list): # Create a list of options for the key return OptionsNode(details...
Child A private function to figure out the child node type Arguments: details {dict} -- A dictionary describing a data point Returns: _NodeInterface
def _get_type(self, policy): """ Returns the type of the given policy :param string or dict policy: Policy data :return PolicyTypes: Type of the given policy. None, if type could not be inferred """ # Must handle intrinsic functions. Policy could be a primitive type or ...
Returns the type of the given policy :param string or dict policy: Policy data :return PolicyTypes: Type of the given policy. None, if type could not be inferred
def _do_read_config(self, config_file, pommanipext): """Reads config for a single job defined by section.""" parser = InterpolationConfigParser() dataset = parser.read(config_file) if config_file not in dataset: raise IOError("Config file %s not found." % config_file) ...
Reads config for a single job defined by section.
def list_(bank): ''' Lists entries stored in the specified bank. ''' redis_server = _get_redis_server() bank_redis_key = _get_bank_redis_key(bank) try: banks = redis_server.smembers(bank_redis_key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot list...
Lists entries stored in the specified bank.
def iterator_cycle(variables: VarType, parent: str) -> Iterable[VarMatrix]: """Cycle through a list of values a specified number of times Args: variables: The input variables for the creation of the range parent: The variable for which the values are being generated. Returns: A list of dic...
Cycle through a list of values a specified number of times Args: variables: The input variables for the creation of the range parent: The variable for which the values are being generated. Returns: A list of dictionaries mapping the parent to each value.
async def debug_create_unit(self, unit_spawn_commands: List[List[Union[UnitTypeId, int, Point2, Point3]]]): """ Usage example (will spawn 1 marine in the center of the map for player ID 1): await self._client.debug_create_unit([[UnitTypeId.MARINE, 1, self._game_info.map_center, 1]]) """ assert i...
Usage example (will spawn 1 marine in the center of the map for player ID 1): await self._client.debug_create_unit([[UnitTypeId.MARINE, 1, self._game_info.map_center, 1]])
def get_xml_type(val): """Returns the data type for the xml type attribute""" if type(val).__name__ in ('str', 'unicode'): return 'str' if type(val).__name__ in ('int', 'long'): return 'int' if type(val).__name__ == 'float': return 'float' if type(val).__name__ == 'bool': ...
Returns the data type for the xml type attribute
def partition(pred, iterable): """Partition an iterable. Arguments --------- pred : function A function that takes an element of the iterable and returns a boolen indicating to which partition it belongs iterable : iterable Returns ------- A two-tuple ...
Partition an iterable. Arguments --------- pred : function A function that takes an element of the iterable and returns a boolen indicating to which partition it belongs iterable : iterable Returns ------- A two-tuple of lists with the first list containin...
def _push_tag_buffer(self, data): """Write a pending tag attribute from *data* to the stack.""" if data.context & data.CX_QUOTED: self._emit_first(tokens.TagAttrQuote(char=data.quoter)) self._emit_all(self._pop()) buf = data.padding_buffer self._emit_first(tokens....
Write a pending tag attribute from *data* to the stack.
def calcinds(data, threshold, ignoret=None): """ Find indexes for data above (or below) given threshold. """ inds = [] for i in range(len(data['time'])): snr = data['snrs'][i] time = data['time'][i] if (threshold >= 0 and snr > threshold): if ignoret: inc...
Find indexes for data above (or below) given threshold.
def activities(self, name=None, pk=None, scope=None, **kwargs): # type: (Optional[str], Optional[str], Optional[str], **Any) -> List[Activity] """Search for activities with optional name, pk and scope filter. If additional `keyword=value` arguments are provided, these are added to the request p...
Search for activities with optional name, pk and scope filter. If additional `keyword=value` arguments are provided, these are added to the request parameters. Please refer to the documentation of the KE-chain API for additional query parameters. :param pk: id (primary key) of the activity to ...
def drop(self, index=None, columns=None): """Remove row data for target index and columns. Args: index: Target index to drop. columns: Target columns to drop. Returns: A new QueryCompiler. """ if self._is_transposed: return self.t...
Remove row data for target index and columns. Args: index: Target index to drop. columns: Target columns to drop. Returns: A new QueryCompiler.
def decrypt(self, ciphertext, encoder=encoding.RawEncoder): """ Decrypts the ciphertext using the ephemeral public key enclosed in the ciphertext and the SealedBox private key, returning the plaintext message. :param ciphertext: [:class:`bytes`] The encrypted message to decrypt ...
Decrypts the ciphertext using the ephemeral public key enclosed in the ciphertext and the SealedBox private key, returning the plaintext message. :param ciphertext: [:class:`bytes`] The encrypted message to decrypt :param encoder: The encoder used to decode the ciphertext. :retu...
def _save(self): """Saves the current state of this AssessmentSection to database. Should be called every time the question map changes. """ collection = JSONClientValidated('assessment', collection='AssessmentSection', ...
Saves the current state of this AssessmentSection to database. Should be called every time the question map changes.
def init_instance(self, key): """ Create an empty instance if it doesn't exist. If the instance already exists, this is a noop. """ with self._mor_lock: if key not in self._mor: self._mor[key] = {}
Create an empty instance if it doesn't exist. If the instance already exists, this is a noop.
def _find_longest_parent_path(path_set, path): """Finds the longest "parent-path" of 'path' in 'path_set'. This function takes and returns "path-like" strings which are strings made of strings separated by os.sep. No file access is performed here, so these strings need not correspond to actual files in some fi...
Finds the longest "parent-path" of 'path' in 'path_set'. This function takes and returns "path-like" strings which are strings made of strings separated by os.sep. No file access is performed here, so these strings need not correspond to actual files in some file-system.. This function returns the longest ance...
def load(self, value): """ enforce env > value when loading from file """ self.reset( value, validator=self.__dict__.get('validator'), env=self.__dict__.get('env'), )
enforce env > value when loading from file