code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def receive_offer(self, pkt): """Receive offer on SELECTING state.""" logger.debug("C2. Received OFFER?, in SELECTING state.") if isoffer(pkt): logger.debug("C2: T, OFFER received") self.offers.append(pkt) if len(self.offers) >= MAX_OFFERS_COLLECTED: ...
Receive offer on SELECTING state.
def get_changes(self, factory_name, global_factory=False, resources=None, task_handle=taskhandle.NullTaskHandle()): """Get the changes this refactoring makes `factory_name` indicates the name of the factory function to be added. If `global_factory` is `True` the factory wil...
Get the changes this refactoring makes `factory_name` indicates the name of the factory function to be added. If `global_factory` is `True` the factory will be global otherwise a static method is added to the class. `resources` can be a list of `rope.base.resource.File`\s that ...
def list_checks(ruleset, ruleset_file, debug, json, skip, tag, verbose, checks_paths): """ Print the checks. """ if ruleset and ruleset_file: raise click.BadOptionUsage( "Options '--ruleset' and '--file-ruleset' cannot be used together.") try: if not debug: l...
Print the checks.
def _build_conflict_target(self): """Builds the `conflict_target` for the ON CONFLICT clause.""" conflict_target = [] if not isinstance(self.query.conflict_target, list): raise SuspiciousOperation(( '%s is not a valid conflict target, specify ' ...
Builds the `conflict_target` for the ON CONFLICT clause.
def utc2local(date): """DokuWiki returns date with a +0000 timezone. This function convert *date* to the local time. """ date_offset = (datetime.now() - datetime.utcnow()) # Python < 2.7 don't have the 'total_seconds' method so calculate it by hand! date_offset = (date_offset.microseconds + ...
DokuWiki returns date with a +0000 timezone. This function convert *date* to the local time.
def render_surface_function(surfimg, funcimg=None, alphasurf=0.2, alphafunc=1.0, isosurf=0.5, isofunc=0.5, smoothsurf=None, smoothfunc=None, cmapsurf='grey', cmapfunc='red', filename=None, notebook=False, auto_open=False): """ ...
Render an image as a base surface and an optional collection of other image. ANTsR function: `renderSurfaceFunction` NOTE: The ANTsPy version of this function is actually completely different than the ANTsR version, although they should produce similar results. Arguments --------- surf...
def read_file(file_name, encoding='utf-8'): """ 读文本文件 :param encoding: :param file_name: :return: """ with open(file_name, 'rb') as f: data = f.read() if encoding is not None: data = data.decode(encoding) return data
读文本文件 :param encoding: :param file_name: :return:
def _filter_result(result, filter_functions=None): """ Filter result with given filter functions. :param result: an iterable object :param filter_functions: some filter functions :return: a filter object (filtered result) """ if filter_functions is not None: ...
Filter result with given filter functions. :param result: an iterable object :param filter_functions: some filter functions :return: a filter object (filtered result)
def exception(self, timeout=None): """Return the exception raised by the call that the future represents. Args: timeout: The number of seconds to wait for the exception if the future isn't done. If None, then there is no limit on the wait time. Retur...
Return the exception raised by the call that the future represents. Args: timeout: The number of seconds to wait for the exception if the future isn't done. If None, then there is no limit on the wait time. Returns: The exception raised by the ca...
def preconstrain_flag_page(self, magic_content): """ Preconstrain the data in the flag page. :param magic_content: The content of the magic page as a bytestring. """ for m, v in zip(magic_content, self.state.cgc.flag_bytes): self.preconstrain(m, v)
Preconstrain the data in the flag page. :param magic_content: The content of the magic page as a bytestring.
def skycoord_to_healpix(self, skycoord, return_offsets=False): """ Convert celestial coordinates to HEALPix indices (optionally with offsets). Note that this method requires that a celestial frame was specified when initializing HEALPix. If you don't know or need the celestial frame, yo...
Convert celestial coordinates to HEALPix indices (optionally with offsets). Note that this method requires that a celestial frame was specified when initializing HEALPix. If you don't know or need the celestial frame, you can instead use :meth:`~astropy_healpix.HEALPix.lonlat_to_healpix`. ...
def get_parameter(self, path, default=None, return_group=False): """ Reads hyperparameter from job configuration. If nothing found use given default. :param path: str :param default: * :param return_group: If true and path is a choice_group, we return the dict instead of the gr...
Reads hyperparameter from job configuration. If nothing found use given default. :param path: str :param default: * :param return_group: If true and path is a choice_group, we return the dict instead of the group name. :return: *
def add(name, beacon_data, **kwargs): ''' Add a beacon on the minion Args: name (str): Name of the beacon to configure beacon_data (dict): Dictionary or list containing configuration for beacon. Returns: dict: Boolean and status message on success or f...
Add a beacon on the minion Args: name (str): Name of the beacon to configure beacon_data (dict): Dictionary or list containing configuration for beacon. Returns: dict: Boolean and status message on success or failure of add. CLI Example: .. code-bloc...
def parse_schema(schema_file): """ parses the schema file and returns the columns that are later going to represent the columns of the genometric space dataframe :param schema_file: the path to the schema file :return: the columns of the schema file """ e = xml.etree.Elem...
parses the schema file and returns the columns that are later going to represent the columns of the genometric space dataframe :param schema_file: the path to the schema file :return: the columns of the schema file
def read(self, lenient=False): """ Read the PNG file and decode it. Returns (`width`, `height`, `pixels`, `metadata`). May use excessive memory. `pixels` are returned in boxed row flat pixel format. If the optional `lenient` argument evaluates to True, checksu...
Read the PNG file and decode it. Returns (`width`, `height`, `pixels`, `metadata`). May use excessive memory. `pixels` are returned in boxed row flat pixel format. If the optional `lenient` argument evaluates to True, checksum failures will raise warnings rather than exceptio...
def sub_menu(self): """Create daemon submenu """ submenu = gtk.Menu() self.start = gtk.ImageMenuItem("Start") self.stop = gtk.ImageMenuItem("Stop") self.restart = gtk.ImageMenuItem("Restart") self.status = gtk.ImageMenuItem("Status") self.start.show() ...
Create daemon submenu
def putParamset(self, remote, address, paramset, value): """Set paramsets manually""" if self._server is not None: return self._server.putParamset(remote, address, paramset, value)
Set paramsets manually
def on_before_trading(self, date_time): """开盘的时候检查,如果有持仓,就把持有天数 + 1""" if self.cta_call['pos'] > 0: self.cta_call['days'] += 1 if self.cta_put['pos'] > 0: self.cta_put['days'] += 1 self.cta_call['done'] = False self.cta_put['done'] = False
开盘的时候检查,如果有持仓,就把持有天数 + 1
def print_task_output(batch_client, job_id, task_ids, encoding=None): """Prints the stdout and stderr for each task specified. Originally in azure-batch-samples.Python.Batch.common.helpers :param batch_client: The batch client to use. :type batch_client: `batchserviceclient.BatchServiceClient` :par...
Prints the stdout and stderr for each task specified. Originally in azure-batch-samples.Python.Batch.common.helpers :param batch_client: The batch client to use. :type batch_client: `batchserviceclient.BatchServiceClient` :param str job_id: The id of the job to monitor. :param task_ids: The collect...
def render_tag(self, context, kwargs, nodelist): '''render content with "active" urls logic''' # load configuration from passed options self.load_configuration(**kwargs) # get request from context request = context['request'] # get full path from request self.fu...
render content with "active" urls logic
def find_in_registry(category = None, namespace = None, name = None): """ Find a given category/namespace/name combination in the registry category - string, see utils.inputs.registrycategories namespace - module namespace, see settings.NAMESPACE name - lowercase name of module """ selected_...
Find a given category/namespace/name combination in the registry category - string, see utils.inputs.registrycategories namespace - module namespace, see settings.NAMESPACE name - lowercase name of module
def get_interpolated_gap(self, tol=0.001, abs_tol=False, spin=None): """ Expects a DOS object and finds the gap Args: tol: tolerance in occupations for determining the gap abs_tol: Set to True for an absolute tolerance and False for a relative one. ...
Expects a DOS object and finds the gap Args: tol: tolerance in occupations for determining the gap abs_tol: Set to True for an absolute tolerance and False for a relative one. spin: Possible values are None - finds the gap in the summed densit...
def commit(self): """Commit a batch.""" assert self.batch is not None, "No active batch, call start() first" logger.debug("Comitting batch from %d sources...", len(self.batch)) # Determine item priority. by_priority = [] for name in self.batch.keys(): priori...
Commit a batch.
def list(self, all_pages=False, **kwargs): """Return a list of notification templates. Note here configuration-related fields like 'notification_configuration' and 'channels' will not be used even provided. If one or more filters are provided through keyword arguments, ...
Return a list of notification templates. Note here configuration-related fields like 'notification_configuration' and 'channels' will not be used even provided. If one or more filters are provided through keyword arguments, filter the results accordingly. If no filters...
def inheritance_patch(attrs): """Patch tango objects before they are processed by the metaclass.""" for key, obj in attrs.items(): if isinstance(obj, attribute): if getattr(obj, 'attr_write', None) == AttrWriteType.READ_WRITE: if not getattr(obj, 'fset', None): ...
Patch tango objects before they are processed by the metaclass.
def inherit_kwargs(inherit_func): """ TODO move to util_decor inherit_func = inspect_pdfs func = encoder.visualize.im_func """ import utool as ut keys, is_arbitrary = ut.get_kwargs(inherit_func) if is_arbitrary: keys += ['**kwargs'] kwargs_append = '\n'.join(keys) #from s...
TODO move to util_decor inherit_func = inspect_pdfs func = encoder.visualize.im_func
def get_vcs_details_output_vcs_details_node_vcs_mode(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_vcs_details = ET.Element("get_vcs_details") config = get_vcs_details output = ET.SubElement(get_vcs_details, "output") vcs_details = ...
Auto Generated Code
def bug(self, container: Container) -> Bug: """ Returns a description of the bug inside a given container. """ name = container.bug return self.__installation.bugs[name]
Returns a description of the bug inside a given container.
def debug(sequence): """ adds information to the sequence for better debugging, currently only an index property on each point in the sequence. """ points = [] for i, p in enumerate(sequence): copy = Point(p) copy['index'] = i points.append(copy) return sequence.__cla...
adds information to the sequence for better debugging, currently only an index property on each point in the sequence.
def get_device_info(self, bigip): '''Get device information about a specific BigIP device. :param bigip: bigip object --- device to inspect :returns: bigip object ''' coll = bigip.tm.cm.devices.get_collection() device = [device for device in coll if device.selfDevice ==...
Get device information about a specific BigIP device. :param bigip: bigip object --- device to inspect :returns: bigip object
def actions(connection): """List all actions.""" session = _make_session(connection=connection) for action in Action.ls(session=session): click.echo(f'{action.created} {action.action} {action.resource}')
List all actions.
def asini(b, orbit, solve_for=None): """ Create a constraint for asini in an orbit. If any of the required parameters ('asini', 'sma', 'incl') do not exist in the orbit, they will be created. :parameter b: the :class:`phoebe.frontend.bundle.Bundle` :parameter str orbit: the label of the orbit ...
Create a constraint for asini in an orbit. If any of the required parameters ('asini', 'sma', 'incl') do not exist in the orbit, they will be created. :parameter b: the :class:`phoebe.frontend.bundle.Bundle` :parameter str orbit: the label of the orbit in which this constraint should be built ...
def ControlFromHandle(handle: int) -> Control: """ Call IUIAutomation.ElementFromHandle with a native handle. handle: int, a native window handle. Return `Control` subclass. """ return Control.CreateControlFromElement(_AutomationClient.instance().IUIAutomation.ElementFromHandle(handle))
Call IUIAutomation.ElementFromHandle with a native handle. handle: int, a native window handle. Return `Control` subclass.
def get(self, request, **resources): """ Default GET method. Return instance (collection) by model. :return object: instance or collection from self model """ instance = resources.get(self._meta.name) if not instance is None: return instance return self.pa...
Default GET method. Return instance (collection) by model. :return object: instance or collection from self model
def imslic(img, n_segments=100, aspect=None): """ slic args : n_segments=100, compactness=10., max_iter=10, sigma=0, spacing=None, multichannel=True, convert2lab=None, enforce_connectivity=True, min_size_factor=0.5, max_size_factor=3, slic_zero=False mark_boundaries args: label_img, col...
slic args : n_segments=100, compactness=10., max_iter=10, sigma=0, spacing=None, multichannel=True, convert2lab=None, enforce_connectivity=True, min_size_factor=0.5, max_size_factor=3, slic_zero=False mark_boundaries args: label_img, color=(1, 1, 0), outline_color=None, mode='outer', background...
def set_to_cache(self): """ Add widget's attributes to Django's cache. Split the QuerySet, to not pickle the result set. """ queryset = self.get_queryset() cache.set(self._get_cache_key(), { 'queryset': [ queryset.none(), ...
Add widget's attributes to Django's cache. Split the QuerySet, to not pickle the result set.
def parse_file(path, format=None, encoding='utf-8', force_types=True): """A convenience wrapper of parse, which accepts path of file to parse. Args: path: path to file to parse format: explicitly override the guessed `inp` markup format encoding: file encoding, defaults to utf-8 ...
A convenience wrapper of parse, which accepts path of file to parse. Args: path: path to file to parse format: explicitly override the guessed `inp` markup format encoding: file encoding, defaults to utf-8 force_types: if `True`, integers, floats, booleans and none/null ...
def experiment_completed(self): """Checks the current state of the experiment to see whether it has completed. This makes use of the experiment server `/summary` route, which in turn uses :meth:`~Experiment.is_complete`. """ heroku_app = HerokuApp(self.app_id) status_url ...
Checks the current state of the experiment to see whether it has completed. This makes use of the experiment server `/summary` route, which in turn uses :meth:`~Experiment.is_complete`.
def is_disabled_action(view): """ Checks whether Link action is disabled. """ if not isinstance(view, core_views.ActionsViewSet): return False action = getattr(view, 'action', None) return action in view.disabled_actions if action is not None else False
Checks whether Link action is disabled.
def recv(self): """Returns the reply message or None if there was no reply.""" try: items = self.poller.poll(self.timeout) except KeyboardInterrupt: return # interrupted if items: # if we got a reply, process it msg = self.client.recv_mul...
Returns the reply message or None if there was no reply.
def _parse_results(self, raw_results, includes_qualifiers): """ Parse WMI query results in a more comprehensive form. Returns: List of WMI objects ``` [ { 'freemegabytes': 19742.0, 'name': 'C:', 'avgdiskbytesperwrite': ...
Parse WMI query results in a more comprehensive form. Returns: List of WMI objects ``` [ { 'freemegabytes': 19742.0, 'name': 'C:', 'avgdiskbytesperwrite': 1536.0 }, { 'freemegabytes': 19742.0, ...
def select_rows(self, rows): ''' Truncate internal arrays to keep only the specified rows. Args: rows (array): An integer or boolean array identifying the indices of rows to keep. ''' self.values = self.values.iloc[rows] self.index = self.index.iloc[r...
Truncate internal arrays to keep only the specified rows. Args: rows (array): An integer or boolean array identifying the indices of rows to keep.
def atomic_to_cim_xml(obj): """ Convert an "atomic" scalar value to a CIM-XML string and return that string. The returned CIM-XML string is ready for use as the text of a CIM-XML 'VALUE' element. Parameters: obj (:term:`CIM data type`, :term:`number`, :class:`py:datetime`): The ...
Convert an "atomic" scalar value to a CIM-XML string and return that string. The returned CIM-XML string is ready for use as the text of a CIM-XML 'VALUE' element. Parameters: obj (:term:`CIM data type`, :term:`number`, :class:`py:datetime`): The "atomic" input value. May be `None`. ...
def get_season_player_stats(self, season_key, player_key): """ Calling Season Player Stats API. Arg: season_key: key of the season player_key: key of the player Return: json data """ season_player_stats_url = self.api_path + "season/" + ...
Calling Season Player Stats API. Arg: season_key: key of the season player_key: key of the player Return: json data
def _drop_schema(self, force_drop=False): """ Drops the schema""" connection = connections[get_tenant_database_alias()] has_schema = hasattr(connection, 'schema_name') if has_schema and connection.schema_name not in (self.schema_name, get_public_schema_name()): raise Exceptio...
Drops the schema
def predict_moments(self, X): """ Full predictive distribution from Bayesian linear regression. Parameters ---------- X : ndarray (N*,d) array query input dataset (N* samples, d dimensions). Returns ------- Ey : ndarray The expect...
Full predictive distribution from Bayesian linear regression. Parameters ---------- X : ndarray (N*,d) array query input dataset (N* samples, d dimensions). Returns ------- Ey : ndarray The expected value of y* for the query inputs, X* of shape (...
def add_ecc_cgw(psr, gwtheta, gwphi, mc, dist, F, inc, psi, gamma0, e0, l0, q, nmax=100, nset=None, pd=None, periEv=True, psrTerm=True, tref=0, check=True, useFile=True): """ Simulate GW from eccentric SMBHB. Waveform models from Taylor et al. (2015) and Barack and Cutler (20...
Simulate GW from eccentric SMBHB. Waveform models from Taylor et al. (2015) and Barack and Cutler (2004). WARNING: This residual waveform is only accurate if the GW frequency is not significantly evolving over the observation time of the pulsar. :param psr: pulsar object :param gwtheta: Polar...
def jsonify_payload(self): """ Dump the payload to JSON """ # Assume already json serialized if isinstance(self.payload, string_types): return self.payload return json.dumps(self.payload, cls=StandardJSONEncoder)
Dump the payload to JSON
def _get_client(self): """ OSS2 Auth client Returns: oss2.Auth or oss2.StsAuth: client """ return (_oss.StsAuth if 'security_token' in self._storage_parameters else _oss.Auth if self._storage_parameters else _oss.AnonymousAuth)(**self....
OSS2 Auth client Returns: oss2.Auth or oss2.StsAuth: client
def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to conn...
Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is...
def return_buffer_contents(self, frame, force_unescaped=False): """Return the buffer contents of the frame.""" if not force_unescaped: if frame.eval_ctx.volatile: self.writeline('if context.eval_ctx.autoescape:') self.indent() self.writeline('r...
Return the buffer contents of the frame.
def _encode_secret_part_v2_v3(version, condition, root_key, ns): '''Creates a version 2 or version 3 secret part of the third party caveat. The returned data is not encrypted. The format has the following packed binary fields: version 2 or 3 [1 byte] root key length [n: uvarint] root key [n byt...
Creates a version 2 or version 3 secret part of the third party caveat. The returned data is not encrypted. The format has the following packed binary fields: version 2 or 3 [1 byte] root key length [n: uvarint] root key [n bytes] namespace length [n: uvarint] (v3 only) namespace [n bytes] ...
def ciphertext(self, be_secure=True): """Return the ciphertext of the EncryptedNumber. Choosing a random number is slow. Therefore, methods like :meth:`__add__` and :meth:`__mul__` take a shortcut and do not follow Paillier encryption fully - every encrypted sum or product shoul...
Return the ciphertext of the EncryptedNumber. Choosing a random number is slow. Therefore, methods like :meth:`__add__` and :meth:`__mul__` take a shortcut and do not follow Paillier encryption fully - every encrypted sum or product should be multiplied by r ** :attr:`~PaillierP...
def make_site_obj(argdict): '''Instantiate and return the site. This will be used for all commands''' d = os.getcwd() #'.' if 'directory' in argdict: d = argdict['directory'] try: s = s2site.Site(d) except: print "Could not instantiate site object." sys.exit() ret...
Instantiate and return the site. This will be used for all commands
def fromstring(cls, dis_string): """Create a DisRSTTree instance from a string containing a *.dis parse.""" temp = tempfile.NamedTemporaryFile(delete=False) temp.write(dis_string) temp.close() dis_tree = cls(dis_filepath=temp.name) os.unlink(temp.name) return dis_...
Create a DisRSTTree instance from a string containing a *.dis parse.
def RACCU_calc(TOP, P, POP): """ Calculate RACCU (Random accuracy unbiased). :param TOP: test outcome positive :type TOP : int :param P: condition positive :type P : int :param POP: population :type POP : int :return: RACCU as float """ try: result = ((TOP + P) / (2 ...
Calculate RACCU (Random accuracy unbiased). :param TOP: test outcome positive :type TOP : int :param P: condition positive :type P : int :param POP: population :type POP : int :return: RACCU as float
def remove_fetcher(self, fetcher): """Remove a running fetcher from the list of active fetchers. :Parameters: - `fetcher`: fetcher instance. :Types: - `fetcher`: `CacheFetcher`""" self._lock.acquire() try: for t, f in list(self._active_fetcher...
Remove a running fetcher from the list of active fetchers. :Parameters: - `fetcher`: fetcher instance. :Types: - `fetcher`: `CacheFetcher`
def close(self, suppress_logging=False): """ purges all connections. method closes ampq connection (disconnects) """ for publisher in self.publishers: try: publisher.close() except Exception as e: self.logger.error('Exception on closing Flopsy Publ...
purges all connections. method closes ampq connection (disconnects)
def handle_key_rotate(self, now): ''' Rotate the AES key rotation ''' to_rotate = False dfn = os.path.join(self.opts['cachedir'], '.dfn') try: stats = os.stat(dfn) # Basic Windows permissions don't distinguish between # user/group/all. ...
Rotate the AES key rotation
def clone(cls, repo_location, repo_dir=None, branch_or_tag=None, temp=False): """Clone repo at repo_location into repo_dir and checkout branch_or_tag. Defaults into current working directory if repo_dir is not supplied. If 'temp' is True, a temporary directory will be created for...
Clone repo at repo_location into repo_dir and checkout branch_or_tag. Defaults into current working directory if repo_dir is not supplied. If 'temp' is True, a temporary directory will be created for you and the repository will be cloned into it. The tempdir is scheduled for deletion (...
def trimquants(self, col: str, inf: float, sup: float): """ Remove superior and inferior quantiles from the dataframe :param col: column name :type col: str :param inf: inferior quantile :type inf: float :param sup: superior quantile :type sup: float ...
Remove superior and inferior quantiles from the dataframe :param col: column name :type col: str :param inf: inferior quantile :type inf: float :param sup: superior quantile :type sup: float :example: ``ds.trimquants("Col 1", 0.01, 0.99)``
def mine_get(tgt, fun, tgt_type='glob', opts=None): ''' Gathers the data from the specified minions' mine, pass in the target, function to look up and the target type ''' ret = {} serial = salt.payload.Serial(opts) checker = CkMinions(opts) _res = checker.check_minions( tgt, ...
Gathers the data from the specified minions' mine, pass in the target, function to look up and the target type
def GetElapsedMs(self): '''Retrieves the number of milliseconds that have passed in the virtual machine since it last started running on the server. The count of elapsed time restarts each time the virtual machine is powered on, resumed, or migrated using VMotion. This value cou...
Retrieves the number of milliseconds that have passed in the virtual machine since it last started running on the server. The count of elapsed time restarts each time the virtual machine is powered on, resumed, or migrated using VMotion. This value counts milliseconds, regardless of ...
def moments_XX(X, remove_mean=False, modify_data=False, weights=None, sparse_mode='auto', sparse_tol=0.0, column_selection=None, diag_only=False): r""" Computes the first two unnormalized moments of X Computes :math:`s = \sum_t x_t` and :math:`C = X^\top X` while exploiting zero or constant ...
r""" Computes the first two unnormalized moments of X Computes :math:`s = \sum_t x_t` and :math:`C = X^\top X` while exploiting zero or constant columns in the data matrix. Parameters ---------- X : ndarray (T, M) Data matrix remove_mean : bool True: remove column mean from the...
def _set_shape(self, shape): """Private on purpose.""" try: shape = (int(shape),) except TypeError: pass shp = list(shape) shp[0] = timetools.Period('366d')/self.simulationstep shp[0] = int(numpy.ceil(round(shp[0], 10))) getattr(self.fastac...
Private on purpose.
def get_me(self): """Return a LoggedInRedditor object. Note: This function is only intended to be used with an 'identity' providing OAuth2 grant. """ response = self.request_json(self.config['me']) user = objects.Redditor(self, response['name'], response) user.__...
Return a LoggedInRedditor object. Note: This function is only intended to be used with an 'identity' providing OAuth2 grant.
def colorize_text(self, text): """Colorize the text.""" # As originally implemented, this method acts upon all the contents of # the file as a single string using the MULTILINE option of the re # package. I believe this was ostensibly for performance reasons, but # it has a few s...
Colorize the text.
def _values(self): """Getter for series values (flattened)""" if self.interpolate: return [ val[0] for serie in self.series for val in serie.interpolated ] else: return super(Line, self)._values
Getter for series values (flattened)
def process_event(self, event, ipmicmd, seldata): """Modify an event according with OEM understanding. Given an event, allow an OEM module to augment it. For example, event data fields can have OEM bytes. Other times an OEM may wish to apply some transform to some field to suit their ...
Modify an event according with OEM understanding. Given an event, allow an OEM module to augment it. For example, event data fields can have OEM bytes. Other times an OEM may wish to apply some transform to some field to suit their conventions.
def publish_topology_closed(self, topology_id): """Publish a TopologyClosedEvent to all topology listeners. :Parameters: - `topology_id`: A unique identifier for the topology this server is a part of. """ event = TopologyClosedEvent(topology_id) for subscribe...
Publish a TopologyClosedEvent to all topology listeners. :Parameters: - `topology_id`: A unique identifier for the topology this server is a part of.
def select_pane(self, target_pane): """ Return selected :class:`Pane` through ``$ tmux select-pane``. Parameters ---------- target_pane : str 'target_pane', '-U' ,'-D', '-L', '-R', or '-l'. Return ------ :class:`Pane` """ if ...
Return selected :class:`Pane` through ``$ tmux select-pane``. Parameters ---------- target_pane : str 'target_pane', '-U' ,'-D', '-L', '-R', or '-l'. Return ------ :class:`Pane`
def company(random=random, *args, **kwargs): """ Produce a company name >>> mock_random.seed(0) >>> company(random=mock_random) 'faculty of applied chimp' >>> mock_random.seed(1) >>> company(random=mock_random) 'blistersecret studios' >>> mock_random.seed(2) >>> company(random=m...
Produce a company name >>> mock_random.seed(0) >>> company(random=mock_random) 'faculty of applied chimp' >>> mock_random.seed(1) >>> company(random=mock_random) 'blistersecret studios' >>> mock_random.seed(2) >>> company(random=mock_random) 'pooppooppoop studios' >>> mock_rando...
def _create_sot_file(self): """Create Source of Truth file to compare.""" # Bug on on NX-OS 6.2.16 where overwriting sot_file would take exceptionally long time # (over 12 minutes); so just delete the sot_file try: self._delete_file(filename="sot_file") except Except...
Create Source of Truth file to compare.
def discover_modules(self): ''' Return module sequence discovered from ``self.package_name`` Parameters ---------- None Returns ------- mods : sequence Sequence of module names within ``self.package_name`` Examples -------- ...
Return module sequence discovered from ``self.package_name`` Parameters ---------- None Returns ------- mods : sequence Sequence of module names within ``self.package_name`` Examples -------- >>> dw = ApiDocWriter('sphinx') ...
def add_page_if_missing(request): """ Returns ``feincms_page`` for request. """ try: page = Page.objects.for_request(request, best_match=True) return { 'leonardo_page': page, # DEPRECATED 'feincms_page': page, } except Page.DoesNotExist: ...
Returns ``feincms_page`` for request.
def update(self, reseed): """ Update that trail! :param reseed: Whether we are in the normal reseed cycle or not. """ if self._clear: for i in range(0, 3): self._screen.print_at(" ", self._x, ...
Update that trail! :param reseed: Whether we are in the normal reseed cycle or not.
def evaluate_world_model( real_env, hparams, world_model_dir, debug_video_path, split=tf.estimator.ModeKeys.EVAL, ): """Evaluate the world model (reward accuracy).""" frame_stack_size = hparams.frame_stack_size rollout_subsequences = [] def initial_frame_chooser(batch_size): assert batch_size == len...
Evaluate the world model (reward accuracy).
def get_too_few_non_zero_degree_day_warning( model_type, balance_point, degree_day_type, degree_days, minimum_non_zero ): """ Return an empty list or a single warning wrapped in a list regarding non-zero degree days for a set of degree days. Parameters ---------- model_type : :any:`str` ...
Return an empty list or a single warning wrapped in a list regarding non-zero degree days for a set of degree days. Parameters ---------- model_type : :any:`str` Model type (e.g., ``'cdd_hdd'``). balance_point : :any:`float` The balance point in question. degree_day_type : :any:...
def setWidth(self, vehID, width): """setWidth(string, double) -> None Sets the width in m for this vehicle. """ self._connection._sendDoubleCmd( tc.CMD_SET_VEHICLE_VARIABLE, tc.VAR_WIDTH, vehID, width)
setWidth(string, double) -> None Sets the width in m for this vehicle.
def get_preview_name(self): """Returns .SAFE name of full resolution L1C preview :return: name of preview file :rtype: str """ if self.safe_type == EsaSafeType.OLD_TYPE: name = _edit_name(self.tile_id, AwsConstants.PVI, delete_end=True) else: name ...
Returns .SAFE name of full resolution L1C preview :return: name of preview file :rtype: str
def set_listener_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB listener. .. versionadded:: 2016.3.0 CLI example: .. code-block:: Bash salt myminion boto_elb.set_listener_policy myelb 443 "[policy...
Set the policies of an ELB listener. .. versionadded:: 2016.3.0 CLI example: .. code-block:: Bash salt myminion boto_elb.set_listener_policy myelb 443 "[policy1,policy2]"
def create(self, vals, check=True): """ Overrides orm create method. @param self: The object pointer @param vals: dictionary of fields value. @return: new record set for hotel folio. """ if not 'service_lines' and 'folio_id' in vals: tmp_room_lines = v...
Overrides orm create method. @param self: The object pointer @param vals: dictionary of fields value. @return: new record set for hotel folio.
def create_index(self): """ Override to provide code for creating the target index. By default it will be created without any special settings or mappings. """ es = self._init_connection() if not es.indices.exists(index=self.index): es.indices.create(index=se...
Override to provide code for creating the target index. By default it will be created without any special settings or mappings.
def get_account_info(self): """ Returns a tuple for the number of containers and total bytes in the account. """ headers = self._manager.get_account_headers() return (headers.get("x-account-container-count"), headers.get("x-account-bytes-used"))
Returns a tuple for the number of containers and total bytes in the account.
def get_package_path(name): """Get the path to an installed package. name (unicode): Package name. RETURNS (Path): Path to installed package. """ name = name.lower() # use lowercase version to be safe # Here we're importing the module just to find it. This is worryingly # indirect, but it'...
Get the path to an installed package. name (unicode): Package name. RETURNS (Path): Path to installed package.
def write_incron_file_verbose(user, path): ''' Writes the contents of a file to a user's incrontab and return error message on error CLI Example: .. code-block:: bash salt '*' incron.write_incron_file_verbose root /tmp/new_incron ''' return __salt__['cmd.run_all'](_get_incron_cmdstr(p...
Writes the contents of a file to a user's incrontab and return error message on error CLI Example: .. code-block:: bash salt '*' incron.write_incron_file_verbose root /tmp/new_incron
def I(r, limbdark): ''' The standard quadratic limb darkening law. :param ndarray r: The radius vector :param limbdark: A :py:class:`pysyzygy.transit.LIMBDARK` instance containing the limb darkening law information :returns: The stellar intensity as a function of `r` ''' if...
The standard quadratic limb darkening law. :param ndarray r: The radius vector :param limbdark: A :py:class:`pysyzygy.transit.LIMBDARK` instance containing the limb darkening law information :returns: The stellar intensity as a function of `r`
def _output_function_label(self): """ Determines if we want to output the function label in assembly. We output the function label only when the original instruction does not output the function label. :return: True if we should output the function label, False otherwise. :rtype...
Determines if we want to output the function label in assembly. We output the function label only when the original instruction does not output the function label. :return: True if we should output the function label, False otherwise. :rtype: bool
def create(self, acl=None): '''Creates a directory, optionally include Acl argument to set permissions''' parent, name = getParentAndBase(self.path) json = { 'name': name } if acl is not None: json['acl'] = acl.to_api_param() response = self.client.postJsonHelper(Data...
Creates a directory, optionally include Acl argument to set permissions
def extract_files_from_dict(d): """Return any file objects from the provided dict. >>> extract_files_from_dict({ ... 'oauth_token': 'foo', ... 'track': { ... 'title': 'bar', ... 'asset_data': open('setup.py', 'rb') ... }}) # doctest:+ELLIPSIS {'track': {'asset_data': <...}} ""...
Return any file objects from the provided dict. >>> extract_files_from_dict({ ... 'oauth_token': 'foo', ... 'track': { ... 'title': 'bar', ... 'asset_data': open('setup.py', 'rb') ... }}) # doctest:+ELLIPSIS {'track': {'asset_data': <...}}
def from_raw_script(cls, raw_script): """Creates instance of `Command` from a list of script parts. :type raw_script: [basestring] :rtype: Command :raises: EmptyCommand """ script = format_raw_script(raw_script) if not script: raise EmptyCommand ...
Creates instance of `Command` from a list of script parts. :type raw_script: [basestring] :rtype: Command :raises: EmptyCommand
def are_equal(self, sp1, sp2): """ True if species are exactly the same, i.e., Fe2+ == Fe2+ but not Fe3+. and the spins are reversed. i.e., spin up maps to spin down, and vice versa. Args: sp1: First species. A dict of {specie/element: amt} as per the ...
True if species are exactly the same, i.e., Fe2+ == Fe2+ but not Fe3+. and the spins are reversed. i.e., spin up maps to spin down, and vice versa. Args: sp1: First species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite. s...
def output(self, _filename): """ _filename is not used Args: _filename(string) """ txt = '' for c in self.contracts: txt += "\nContract %s\n"%c.name table = PrettyTable(['Variable', 'Dependencies']) for v in c.s...
_filename is not used Args: _filename(string)
def radviz(X, y=None, ax=None, features=None, classes=None, color=None, colormap=None, alpha=1.0, **kwargs): """ Displays each feature as an axis around a circle surrounding a scatter plot whose points are each individual instance. This helper function is a quick wrapper to utilize the Radia...
Displays each feature as an axis around a circle surrounding a scatter plot whose points are each individual instance. This helper function is a quick wrapper to utilize the RadialVisualizer (Transformer) for one-off analysis. Parameters ---------- X : ndarray or DataFrame of shape n x m ...
def _load_assembly_mapping_data(filename): """ Load assembly mapping data. Parameters ---------- filename : str path to compressed archive with assembly mapping data Returns ------- assembly_mapping_data : dict dict of assembly maps if lo...
Load assembly mapping data. Parameters ---------- filename : str path to compressed archive with assembly mapping data Returns ------- assembly_mapping_data : dict dict of assembly maps if loading was successful, else None Notes ...
def _validate_data(data): """Validates the given data and raises an error if any non-allowed keys are provided or any required keys are missing. :param data: Data to send to API :type data: dict """ data_keys = set(data.keys()) extra_keys = data_keys - set(ALLOWED_KEYS) missing_keys = s...
Validates the given data and raises an error if any non-allowed keys are provided or any required keys are missing. :param data: Data to send to API :type data: dict
def _analyze_variable_attributes(self, attributes): """ Analyze event variable attributes :param attributes: The event variable attributes to parse. :return: None """ # Check for the indexed attribute if 'indexed' in attributes: self._indexed = attrib...
Analyze event variable attributes :param attributes: The event variable attributes to parse. :return: None
def _EvaluateElementsDataSize(self, context): """Evaluates elements data size. Args: context (DataTypeMapContext): data type map context. Returns: int: elements data size. Raises: MappingError: if the elements data size cannot be determined. """ elements_data_size = None ...
Evaluates elements data size. Args: context (DataTypeMapContext): data type map context. Returns: int: elements data size. Raises: MappingError: if the elements data size cannot be determined.
def p0f_impersonate(pkt, osgenre=None, osdetails=None, signature=None, extrahops=0, mtu=1500, uptime=None): """Modifies pkt so that p0f will think it has been sent by a specific OS. If osdetails is None, then we randomly pick up a personality matching osgenre. If osgenre and signature are also ...
Modifies pkt so that p0f will think it has been sent by a specific OS. If osdetails is None, then we randomly pick up a personality matching osgenre. If osgenre and signature are also None, we use a local signature (using p0f_getlocalsigs). If signature is specified (as a tuple), we use the signature. For now, only T...
def GetLocations(): """Return all cloud locations available to the calling alias.""" r = clc.v1.API.Call('post','Account/GetLocations',{}) if r['Success'] != True: if clc.args: clc.v1.output.Status('ERROR',3,'Error calling %s. Status code %s. %s' % ('Account/GetLocations',r['StatusCode'],r['Message'])) ...
Return all cloud locations available to the calling alias.