code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def easybake(css_in, html_in=sys.stdin, html_out=sys.stdout, last_step=None, coverage_file=None, use_repeatable_ids=False): """Process the given HTML file stream with the css stream.""" html_doc = etree.parse(html_in) oven = Oven(css_in, use_repeatable_ids) oven.bake(html_doc, last_step) ...
Process the given HTML file stream with the css stream.
def FailoverInstance(r, instance, iallocator=None, ignore_consistency=False, target_node=None): """Does a failover of an instance. @type instance: string @param instance: Instance name @type iallocator: string @param iallocator: Iallocator for deciding the target node for ...
Does a failover of an instance. @type instance: string @param instance: Instance name @type iallocator: string @param iallocator: Iallocator for deciding the target node for shared-storage instances @type ignore_consistency: bool @param ignore_consistency: Whether to ignore disk consist...
def render(self): """ Returns the ``struct`` format and list of the size and value. The format is derived from the size primitive and the length of the resulting encoded value (e.g. the format for a string of 'foo' ends up as 'h3s'. .. note :: The value is exp...
Returns the ``struct`` format and list of the size and value. The format is derived from the size primitive and the length of the resulting encoded value (e.g. the format for a string of 'foo' ends up as 'h3s'. .. note :: The value is expected to be string-able (wrapped in ``...
def get_parameter(self, name): """Get a parameter.""" default_value = "$%!)(INVALID)(!%$" value = self.lib.tdGetDeviceParameter(self.id, name, default_value) if value == default_value: raise AttributeError(name) return value
Get a parameter.
def show_progress(name, **kwargs): ''' Sets up a :class:`ProgressBarHandler` to handle progess logs for a given module. Parameters ---------- name : string The module name of the progress logger to use. For example, :class:`skl_groups.divergences.KNNDivergenceEstimator` ...
Sets up a :class:`ProgressBarHandler` to handle progess logs for a given module. Parameters ---------- name : string The module name of the progress logger to use. For example, :class:`skl_groups.divergences.KNNDivergenceEstimator` uses ``'skl_groups.divergences.knn.progress'``....
def skull_strip(dset,suffix='_ns',prefix=None,unifize=True): '''attempts to cleanly remove skull from ``dset``''' return available_method('skull_strip')(dset,suffix,prefix,unifize)
attempts to cleanly remove skull from ``dset``
def POPFQ(cpu): """ Pops stack into EFLAGS register. :param cpu: current CPU. """ mask = 0x00000001 | 0x00000004 | 0x00000010 | 0x00000040 | 0x00000080 | 0x00000400 | 0x00000800 cpu.EFLAGS = (cpu.EFLAGS & ~mask) | cpu.pop(64) & mask
Pops stack into EFLAGS register. :param cpu: current CPU.
def get_rectangle(self): """Gets the coordinates of the rectangle, in which the tree can be put. Returns: tupel: (x1, y1, x2, y2) """ rec = [self.pos[0], self.pos[1]]*2 for age in self.nodes: for node in age: # Check max/min for x/y coords...
Gets the coordinates of the rectangle, in which the tree can be put. Returns: tupel: (x1, y1, x2, y2)
def __handle_events(self): """This is the place to put all event handeling.""" events = pygame.event.get() for event in events: if event.type == pygame.QUIT: self.exit()
This is the place to put all event handeling.
def values_clear(self, range): """Lower-level method that directly calls `spreadsheets.values.clear <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/clear>`_. :param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of th...
Lower-level method that directly calls `spreadsheets.values.clear <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/clear>`_. :param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of the values to clear. :returns: `Resp...
def issubclass(cls, ifaces): """Check if the given class is an implementation of the given iface.""" ifaces = _ensure_ifaces_tuple(ifaces) for iface in ifaces: return all(( _check_for_definition( iface, cls, '__iclassattribute__', ...
Check if the given class is an implementation of the given iface.
def get(self, resource): """Get attributes of the data model object named by the given resource. Args: resource (intern.resource.boss.BossResource): resource.name as well as any parents must be identified to succeed. Returns: (intern.resource.boss.BossResource): Returns...
Get attributes of the data model object named by the given resource. Args: resource (intern.resource.boss.BossResource): resource.name as well as any parents must be identified to succeed. Returns: (intern.resource.boss.BossResource): Returns resource of type requested on succe...
def extract_bbox(layers): """ Returns a bounding box for ``layers`` or (0, 0, 0, 0) if the layers have no bounding box. """ if not hasattr(layers, '__iter__'): layers = [layers] bboxes = [ layer.bbox for layer in layers if layer.is_visible() and not layer.bbox == (0, 0, 0...
Returns a bounding box for ``layers`` or (0, 0, 0, 0) if the layers have no bounding box.
def populate_values(self): ''' Add values from the underlying dash layout configuration ''' obj = self._get_base_state() self.base_state = json.dumps(obj)
Add values from the underlying dash layout configuration
def qteTextChanged(self): """ Search for sub-string matches. This method is triggered by Qt whenever the text changes, ie. whenever the user has altered the input. Extract the new input, find all matches, and highlight them accordingly. """ # Remove any previous ...
Search for sub-string matches. This method is triggered by Qt whenever the text changes, ie. whenever the user has altered the input. Extract the new input, find all matches, and highlight them accordingly.
def dim_dc(self, pars): r""" :math:`\frac{\partial \hat{\rho''}(\omega)}{\partial c} = \rho_0 \frac{-m sin(\frac{c \pi}{2}) ln(\omega \tau)(\omega \tau)^c - m (\omega \tau)^c \frac{\pi}{2} cos(\frac{\pi}{2}}{1 + 2 (\omega \tau)^c cos(\frac{c \pi}{2}) + (\omega \tau)^{2 c}} + \rho...
r""" :math:`\frac{\partial \hat{\rho''}(\omega)}{\partial c} = \rho_0 \frac{-m sin(\frac{c \pi}{2}) ln(\omega \tau)(\omega \tau)^c - m (\omega \tau)^c \frac{\pi}{2} cos(\frac{\pi}{2}}{1 + 2 (\omega \tau)^c cos(\frac{c \pi}{2}) + (\omega \tau)^{2 c}} + \rho_0 \frac{\left[-m (\omeg...
def check_status(self): """ This function checks the status of the task by inspecting the output and the error files produced by the application and by the queue manager. """ # 1) see it the job is blocked # 2) see if an error occured at submitting the job the job was sub...
This function checks the status of the task by inspecting the output and the error files produced by the application and by the queue manager.
def calc_area_extent(self, key): """Calculate area extent for a dataset.""" # Calculate the area extent of the swath based on start line and column # information, total number of segments and channel resolution xyres = {500: 22272, 1000: 11136, 2000: 5568} chkres = xyres[key.reso...
Calculate area extent for a dataset.
def path(path_name=None, override=None, *, root=None, name=None, ext=None, inject=None, relpath=None, reduce=False): """ Path manipulation black magic """ path_name, identity, root = _initialize(path_name, override, root, inject) new_name = _process_name(path_name, identity, name, ext) ...
Path manipulation black magic
def usergroup_update(usrgrpid, **kwargs): ''' .. versionadded:: 2016.3.0 Update existing user group .. note:: This function accepts all standard user group properties: keyword argument names differ depending on your zabbix version, see here__. .. __: https://www.zabbix.com/doc...
.. versionadded:: 2016.3.0 Update existing user group .. note:: This function accepts all standard user group properties: keyword argument names differ depending on your zabbix version, see here__. .. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/usergroup/object#u...
def update(self, d): """Works like regular update, but only actually updates when the new value and the old value differ. This is necessary to prevent certain infinite loops. :arg d: a dictionary """ for (k, v) in d.items(): if k not in self or self[k] != v:...
Works like regular update, but only actually updates when the new value and the old value differ. This is necessary to prevent certain infinite loops. :arg d: a dictionary
def get_critical_original_kink_ratio(self): """ Returns a list of molar mixing ratio for each kink between ORIGINAL (instead of processed) reactant compositions. This is the same list as mixing ratio obtained from get_kinks method if self.norm = False. Returns: ...
Returns a list of molar mixing ratio for each kink between ORIGINAL (instead of processed) reactant compositions. This is the same list as mixing ratio obtained from get_kinks method if self.norm = False. Returns: A list of floats representing molar mixing ratios between ...
def helices(self): """Generates new `Assembly` containing just α-helices. Notes ----- Metadata is not currently preserved from the parent object. Returns ------- hel_assembly : ampal.Protein `Assembly` containing only the α-helices of the original `A...
Generates new `Assembly` containing just α-helices. Notes ----- Metadata is not currently preserved from the parent object. Returns ------- hel_assembly : ampal.Protein `Assembly` containing only the α-helices of the original `Assembly`.
def make_sentence(self, init_state=None, **kwargs): """ Attempts `tries` (default: 10) times to generate a valid sentence, based on the model and `test_sentence_output`. Passes `max_overlap_ratio` and `max_overlap_total` to `test_sentence_output`. If successful, returns the sent...
Attempts `tries` (default: 10) times to generate a valid sentence, based on the model and `test_sentence_output`. Passes `max_overlap_ratio` and `max_overlap_total` to `test_sentence_output`. If successful, returns the sentence as a string. If not, returns None. If `init_state` (a tupl...
def vol_per_rev_LS(id_number): """Look up the volume per revolution output by a Masterflex L/S pump through L/S tubing of the given ID number. :param id_number: Identification number of the L/S tubing. Valid numbers are 13-18, 24, 35, and 36. :type id_number: int :return: Volume per revolution out...
Look up the volume per revolution output by a Masterflex L/S pump through L/S tubing of the given ID number. :param id_number: Identification number of the L/S tubing. Valid numbers are 13-18, 24, 35, and 36. :type id_number: int :return: Volume per revolution output by a Masterflex L/S pump through t...
def fit(self, dataset): """ Computes the mean and variance and stores as a model to be used for later scaling. :param dataset: The data used to compute the mean and variance to build the transformation model. :return: a StandardScalarModel """ ...
Computes the mean and variance and stores as a model to be used for later scaling. :param dataset: The data used to compute the mean and variance to build the transformation model. :return: a StandardScalarModel
def get_signature_challenge(self): """Returns new signature challenge""" devices = [DeviceRegistration.wrap(device) for device in self.__get_u2f_devices()] if devices == []: return { 'status' : 'failed', 'error' : 'No devices been associated with t...
Returns new signature challenge
def fit(self, X): """Fit Kernel density estimation to an list of values. Args: X: 1-d `np.ndarray` or `pd.Series` or `list` datapoints to be estimated from. This function will fit a gaussian_kde model to a list of datapoints and store it as a class attribute. """ ...
Fit Kernel density estimation to an list of values. Args: X: 1-d `np.ndarray` or `pd.Series` or `list` datapoints to be estimated from. This function will fit a gaussian_kde model to a list of datapoints and store it as a class attribute.
def activate(self, asset): '''Request activation of the specified asset representation. Asset representations are obtained from :py:meth:`get_assets`. :param request dict: An asset representation from the API. :returns: :py:class:`planet.api.models.Body` with no response content ...
Request activation of the specified asset representation. Asset representations are obtained from :py:meth:`get_assets`. :param request dict: An asset representation from the API. :returns: :py:class:`planet.api.models.Body` with no response content :raises planet.api.exceptions.APIExc...
def to_tokens(self, indices): """Converts token indices to tokens according to the vocabulary. Parameters ---------- indices : int or list of ints A source token index or token indices to be converted. Returns ------- str or list of strs ...
Converts token indices to tokens according to the vocabulary. Parameters ---------- indices : int or list of ints A source token index or token indices to be converted. Returns ------- str or list of strs A token or a list of tokens according t...
def requestTimingInfo(self): """ Returns the time needed to process the request by the frontend server in microseconds and the EPOC timestamp of the request in microseconds. :rtype: tuple containing processing time and timestamp """ try: return tuple(item.spl...
Returns the time needed to process the request by the frontend server in microseconds and the EPOC timestamp of the request in microseconds. :rtype: tuple containing processing time and timestamp
def __is_function_action(self, action_function): """ Detect if given function is really an action function. Args: action_function: Function to test. Note: We don't care if the variable refer to a function but rather if it is callable or not. """ ...
Detect if given function is really an action function. Args: action_function: Function to test. Note: We don't care if the variable refer to a function but rather if it is callable or not.
def _convert_to_image_color(self, color): """:return: a color that can be used by the image""" rgb = self._convert_color_to_rrggbb(color) return self._convert_rrggbb_to_image_color(rgb)
:return: a color that can be used by the image
def hgsub_report(self): """ Yields: str: .hgsubs line for this repository """ if self.relpath == '.': return yield "%s = [%s]%s" % ( self.fpath.lstrip('./'), self.label, self.remote_url)
Yields: str: .hgsubs line for this repository
def shutdown(self, delete=False): """ Shutdown this VM :param delete: Should we delete after shutting the VM down? :type delete: bool """ disks = self.get_disks() self.domain.destroy() if delete: for disk in disks: disk.wipe() ...
Shutdown this VM :param delete: Should we delete after shutting the VM down? :type delete: bool
def create(self, image, geometry, options): """ Processing conductor, returns the thumbnail as an image engine instance """ image = self.cropbox(image, geometry, options) image = self.orientation(image, geometry, options) image = self.colorspace(image, geometry, options) ...
Processing conductor, returns the thumbnail as an image engine instance
def _construct_retry(method_config, retry_codes, retry_params, retry_names): """Helper for ``construct_settings()``. Args: method_config (dict): A dictionary representing a single ``methods`` entry of the standard API client config file. (See ``construct_settings()`` for information on th...
Helper for ``construct_settings()``. Args: method_config (dict): A dictionary representing a single ``methods`` entry of the standard API client config file. (See ``construct_settings()`` for information on this yaml.) retry_codes (dict): A dictionary parsed from the ``retry_codes`` ent...
def valid_file(cls, filename): """ Check if the provided file is a valid file for this plugin. :arg filename: the path to the file to check. """ file_ex = os.path.splitext(filename)[1].replace('.', '', 1) return file_ex in SUPPORTED_FILES and is_excel_file(filename)
Check if the provided file is a valid file for this plugin. :arg filename: the path to the file to check.
def call(self): """ call: ['mut'] ID ['(' parameters ')'] """ is_mutable = False if self.token.nature == Nature.MUT: is_mutable = True self._process(Nature.MUT) identifier = Identifier(name=self.token.value) self._process(Nature.ID) ...
call: ['mut'] ID ['(' parameters ')']
def prepare_framework(estimator, s3_operations): """Prepare S3 operations (specify where to upload `source_dir`) and environment variables related to framework. Args: estimator (sagemaker.estimator.Estimator): The framework estimator to get information from and update. s3_operations (dict):...
Prepare S3 operations (specify where to upload `source_dir`) and environment variables related to framework. Args: estimator (sagemaker.estimator.Estimator): The framework estimator to get information from and update. s3_operations (dict): The dict to specify s3 operations (upload `source_dir`)...
def translated(structure, values, lang_spec): """Return code associated to given structure and values, translate with given language specification.""" # LANGUAGE SPECS indentation = '\t' endline = '\n' object_code = "" stack = [] # define shortcuts to behavior push = lambda x: sta...
Return code associated to given structure and values, translate with given language specification.
def simulate_moment_steps( self, circuit: circuits.Circuit, param_resolver: 'study.ParamResolverOrSimilarType' = None, qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT, initial_state: Any = None ) -> Iterator: """Returns an iterator of StepResults for each m...
Returns an iterator of StepResults for each moment simulated. If the circuit being simulated is empty, a single step result should be returned with the state being set to the initial state. Args: circuit: The Circuit to simulate. param_resolver: A ParamResolver for dete...
def _getMethodsVoc(self): """Return the registered methods as DisplayList """ methods = api.search({ "portal_type": "Method", "is_active": True }, "bika_setup_catalog") items = map(lambda m: (api.get_uid(m), api.get_title(m)), methods) items.sort(...
Return the registered methods as DisplayList
def create(self, locator): """ Creates a component identified by given locator. :param locator: a locator to identify component to be created. :return: the created component. """ for registration in self._registrations: this_locator = registration.locator ...
Creates a component identified by given locator. :param locator: a locator to identify component to be created. :return: the created component.
def transform(self, Z): """Transform ArrayRDD's (or DictRDD's 'X' column's) feature->value dicts to array or sparse matrix. Named features not encountered during fit or fit_transform will be silently ignored. Parameters ---------- Z : ArrayRDD or DictRDD with col...
Transform ArrayRDD's (or DictRDD's 'X' column's) feature->value dicts to array or sparse matrix. Named features not encountered during fit or fit_transform will be silently ignored. Parameters ---------- Z : ArrayRDD or DictRDD with column 'X' containing Mapping or ...
def custom_pygments_guess_lexer_for_filename(_fn, _text, **options): """Overwrite pygments.lexers.guess_lexer_for_filename to customize the priority of different lexers based on popularity of languages.""" fn = basename(_fn) primary = {} matching_lexers = set() for lexer in _iter_lexerclasses()...
Overwrite pygments.lexers.guess_lexer_for_filename to customize the priority of different lexers based on popularity of languages.
def load_training_rasters(response_raster, explanatory_rasters, selected=None): """ Parameters ---------- response_raster : Path to GDAL raster containing responses explanatory_rasters : List of Paths to GDAL rasters containing explanatory variables Returns ------- train_xs : Array of e...
Parameters ---------- response_raster : Path to GDAL raster containing responses explanatory_rasters : List of Paths to GDAL rasters containing explanatory variables Returns ------- train_xs : Array of explanatory variables train_ys : 1xN array of known responses
def websocket( self, uri, host=None, strict_slashes=None, subprotocols=None, name=None ): """Decorate a function to be registered as a websocket route :param uri: path of the URL :param subprotocols: optional list of str with supported subprotocols :param host: :retur...
Decorate a function to be registered as a websocket route :param uri: path of the URL :param subprotocols: optional list of str with supported subprotocols :param host: :return: decorated function
def _syspath_modname_to_modpath(modname, sys_path=None, exclude=None): """ syspath version of modname_to_modpath Args: modname (str): name of module to find sys_path (List[PathLike], default=None): if specified overrides `sys.path` exclude (List[PathLike], default=None):...
syspath version of modname_to_modpath Args: modname (str): name of module to find sys_path (List[PathLike], default=None): if specified overrides `sys.path` exclude (List[PathLike], default=None): list of directory paths. if specified prevents these directories ...
def guess_segments_lines(segments, lines, nearline_tolerance=5.0): """ given segments, outputs a array of line numbers, or -1 if it doesn't belong to any """ ys = segments[:, 1] closeness = numpy.abs(numpy.subtract.outer(ys, lines)) # each row a y, each collumn a distance to each line line_...
given segments, outputs a array of line numbers, or -1 if it doesn't belong to any
def EncloseAnsiText(text): """Enclose ANSI/SGR escape sequences with ANSI_START and ANSI_END.""" return sgr_re.sub(lambda x: ANSI_START + x.group(1) + ANSI_END, text)
Enclose ANSI/SGR escape sequences with ANSI_START and ANSI_END.
def add_remote(self, path, name, remote_url, use_sudo=False, user=None, fetch=True): """ Add a remote Git repository into a directory. :param path: Path of the working copy directory. This directory must exist and be a Git working copy with a default remote to fetch from. ...
Add a remote Git repository into a directory. :param path: Path of the working copy directory. This directory must exist and be a Git working copy with a default remote to fetch from. :type path: str :param use_sudo: If ``True`` execute ``git`` with ...
def monitor_running_process(context: RunContext): """ Runs an infinite loop that waits for the process to either exit on its or time out Captures all output from the running process :param context: run context :type context: RunContext """ while True: capture_output_from_running_pr...
Runs an infinite loop that waits for the process to either exit on its or time out Captures all output from the running process :param context: run context :type context: RunContext
def assert_called(_mock_self): """assert that the mock was called at least once """ self = _mock_self if self.call_count == 0: msg = ("Expected '%s' to have been called." % self._mock_name or 'mock') raise AssertionError(msg)
assert that the mock was called at least once
def _index(self): """Keys a list of file paths that have been pickled in this directory. The index is stored in a json file in the same directory as the pickled objects.""" if self.__index is None: try: with open(self._get_path('index.json')) as f: ...
Keys a list of file paths that have been pickled in this directory. The index is stored in a json file in the same directory as the pickled objects.
def bandwidth(self, subid, params=None): ''' /v1/server/bandwidth GET - account Get the bandwidth used by a virtual machine Link: https://www.vultr.com/api/#server_bandwidth ''' params = update_params(params, {'SUBID': subid}) return self.request('/v1/server/band...
/v1/server/bandwidth GET - account Get the bandwidth used by a virtual machine Link: https://www.vultr.com/api/#server_bandwidth
def list_metrics(self, project, page_size=None, page_token=None): """List metrics for the project associated with this client. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/list :type project: str :param project: ID of the project whose metrics...
List metrics for the project associated with this client. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/list :type project: str :param project: ID of the project whose metrics are to be listed. :type page_size: int :param page_size: ma...
def handle_heartbeat_response_22(msg): """Process an internal heartbeat response message.""" if not msg.gateway.is_sensor(msg.node_id): return None msg.gateway.sensors[msg.node_id].heartbeat = msg.payload msg.gateway.alert(msg) return None
Process an internal heartbeat response message.
def persistent_menu(menu): """ more: https://developers.facebook.com/docs/messenger-platform/thread-settings/persistent-menu :param menu: :return: """ if len(menu) > 3: raise Invalid('menu should not exceed 3 call to actions') if any(len(item['call_to_actions']) > 5 for item in men...
more: https://developers.facebook.com/docs/messenger-platform/thread-settings/persistent-menu :param menu: :return:
def calc_measurement_error(self, tangents): ''' formula for measurement error sqrt ( (sum(1, n, (k_i - <k>)**2) / (n*(n-1))) ''' if len(tangents) < 2: return 0.0 avg_tan = float(sum(tangents) / len(tangents)) numerator = float() for i in tang...
formula for measurement error sqrt ( (sum(1, n, (k_i - <k>)**2) / (n*(n-1)))
def MultiReadClientSnapshot(self, client_ids, cursor=None): """Reads the latest client snapshots for a list of clients.""" int_ids = [db_utils.ClientIDToInt(cid) for cid in client_ids] query = ( "SELECT h.client_id, h.client_snapshot, UNIX_TIMESTAMP(h.timestamp)," " s.startup_info " ...
Reads the latest client snapshots for a list of clients.
def main(args): '''For command line experimentation. Sample output: $ python l2cs.py 'foo:bar AND baz:bork' Lucene input: foo:bar AND baz:bork Parsed representation: And([Term(u'foo', u'bar'), Term(u'baz', u'bork')]) Lucene form: (foo:bar AND baz:bork) Cloudsearch form: (and (field foo 'bar...
For command line experimentation. Sample output: $ python l2cs.py 'foo:bar AND baz:bork' Lucene input: foo:bar AND baz:bork Parsed representation: And([Term(u'foo', u'bar'), Term(u'baz', u'bork')]) Lucene form: (foo:bar AND baz:bork) Cloudsearch form: (and (field foo 'bar') (field baz 'bork'))
def select_source(self, source): """Select a source from the list of sources.""" status = self.status() if status['power']: # Changing source when off may hang NAD7050 if status['source'] != source: # Setting the source to the current source will hang the NAD7050 if...
Select a source from the list of sources.
def run_eidos(endpoint, *args): """Run a given enpoint of Eidos through the command line. Parameters ---------- endpoint : str The class within the Eidos package to run, for instance 'apps.ExtractFromDirectory' will run 'org.clulab.wm.eidos.apps.ExtractFromDirectory' *args ...
Run a given enpoint of Eidos through the command line. Parameters ---------- endpoint : str The class within the Eidos package to run, for instance 'apps.ExtractFromDirectory' will run 'org.clulab.wm.eidos.apps.ExtractFromDirectory' *args Any further arguments to be pass...
def cum_returns(returns, starting_value=0, out=None): """ Compute cumulative returns from simple returns. Parameters ---------- returns : pd.Series, np.ndarray, or pd.DataFrame Returns of the strategy as a percentage, noncumulative. - Time series with decimal returns. - Ex...
Compute cumulative returns from simple returns. Parameters ---------- returns : pd.Series, np.ndarray, or pd.DataFrame Returns of the strategy as a percentage, noncumulative. - Time series with decimal returns. - Example:: 2015-07-16 -0.012143 2015-07-17...
def copy(source, dest, name=None, shallow=False, without_attrs=False, log=None, if_exists='raise', dry_run=False, **create_kws): """Copy the `source` array or group into the `dest` group. Parameters ---------- source : group or array/dataset A zarr group or array, or an h5py group or d...
Copy the `source` array or group into the `dest` group. Parameters ---------- source : group or array/dataset A zarr group or array, or an h5py group or dataset. dest : group A zarr or h5py group. name : str, optional Name to copy the object to. shallow : bool, optional ...
def draw_spectra(md, ds): """ Generate best-fit spectra for all the test objects Parameters ---------- md: model The Cannon spectral model ds: Dataset Dataset object Returns ------- best_fluxes: ndarray The best-fit test fluxes best_ivars: The ...
Generate best-fit spectra for all the test objects Parameters ---------- md: model The Cannon spectral model ds: Dataset Dataset object Returns ------- best_fluxes: ndarray The best-fit test fluxes best_ivars: The best-fit test inverse variances
def all_with(self, x): """Returns all arguments containing given string (or list thereof)""" _args = [] for arg in self.all: if is_collection(x): for _x in x: if _x in arg: _args.append(arg) break ...
Returns all arguments containing given string (or list thereof)
def get_default_config(self): """ Return the default config for the handler """ config = super(ArchiveHandler, self).get_default_config() config.update({ 'log_file': '', 'when': 'midnight', 'days': 7, 'rollover_interval': 1, ...
Return the default config for the handler
def remove_direct_link_triples(train, valid, test): """Remove direct links in the training sets.""" pairs = set() merged = valid + test for t in merged: pairs.add((t.head, t.tail)) filtered = filterfalse(lambda t: (t.head, t.tail) in pairs or (t.tail, t.head) in pairs, train) return lis...
Remove direct links in the training sets.
def load_dataframe(fobj, compression='gzip'): """Given an open file for `hip_main.dat.gz`, return a parsed dataframe. If your copy of ``hip_main.dat`` has already been unzipped, pass the optional argument ``compression=None``. """ try: from pandas import read_fwf except ImportError: ...
Given an open file for `hip_main.dat.gz`, return a parsed dataframe. If your copy of ``hip_main.dat`` has already been unzipped, pass the optional argument ``compression=None``.
def display_multi(annotations, fig_kw=None, meta=True, **kwargs): '''Display multiple annotations with shared axes Parameters ---------- annotations : jams.AnnotationArray A collection of annotations to display fig_kw : dict Keyword arguments to `plt.figure` meta : bool ...
Display multiple annotations with shared axes Parameters ---------- annotations : jams.AnnotationArray A collection of annotations to display fig_kw : dict Keyword arguments to `plt.figure` meta : bool If `True`, display annotation metadata for each annotation kwargs ...
def get_instance(self, payload): """ Build an instance of ApplicationInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.application.ApplicationInstance :rtype: twilio.rest.api.v2010.account.application.ApplicationInstance ...
Build an instance of ApplicationInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.application.ApplicationInstance :rtype: twilio.rest.api.v2010.account.application.ApplicationInstance
def remove_pid_file(process_name): """ removes pid file """ pid_filename = get_pid_filename(process_name) try: os.remove(pid_filename) print('Removed pid file at: {0}'.format(pid_filename), file=sys.stdout) except Exception as e: print('Unable to remove pid file at: {0}, because ...
removes pid file
def from_path(cls, path): """Takes a path and returns a File object with the path as the PFN.""" urlparts = urlparse.urlsplit(path) site = 'nonlocal' if (urlparts.scheme == '' or urlparts.scheme == 'file'): if os.path.isfile(urlparts.path): path = os.path.absp...
Takes a path and returns a File object with the path as the PFN.
def build_command(chunks): """ Create a command from various parts. The parts provided may include a base, flags, option-bound arguments, and positional arguments. Each element must be either a string or a two-tuple. Raw strings are interpreted as either the command base, a pre-joined pair (or ...
Create a command from various parts. The parts provided may include a base, flags, option-bound arguments, and positional arguments. Each element must be either a string or a two-tuple. Raw strings are interpreted as either the command base, a pre-joined pair (or multiple pairs) of option and argument,...
def from_linearized(first, second, intersections): """Determine curve-curve intersection from pair of linearizations. .. note:: This assumes that at least one of ``first`` and ``second`` is not a line. The line-line case should be handled "early" by :func:`check_lines`. .. note:: ...
Determine curve-curve intersection from pair of linearizations. .. note:: This assumes that at least one of ``first`` and ``second`` is not a line. The line-line case should be handled "early" by :func:`check_lines`. .. note:: This assumes the caller has verified that the boundin...
def get_indirect_url_lock_list(self, url, principal=None): """Return a list of valid lockDicts, that protect <path> directly or indirectly. If a principal is given, only locks owned by this principal are returned. Side effect: expired locks for this path and all parents are purged. """ ...
Return a list of valid lockDicts, that protect <path> directly or indirectly. If a principal is given, only locks owned by this principal are returned. Side effect: expired locks for this path and all parents are purged.
def generate_np(self, x, **kwargs): """ Generate adversarial images in a for loop. :param y: An array of shape (n, nb_classes) for true labels. :param y_target: An array of shape (n, nb_classes) for target labels. Required for targeted attack. :param image_target: An array of shape (n, **image ...
Generate adversarial images in a for loop. :param y: An array of shape (n, nb_classes) for true labels. :param y_target: An array of shape (n, nb_classes) for target labels. Required for targeted attack. :param image_target: An array of shape (n, **image shape) for initial target images. Required f...
def dec_ptr(self, ptr): """Get previous circular buffer data pointer.""" result = ptr - self.reading_len[self.ws_type] if result < self.data_start: result = 0x10000 - self.reading_len[self.ws_type] return result
Get previous circular buffer data pointer.
def bash(filename): """Runs a bash script in the local directory""" sys.stdout.flush() subprocess.call("bash {}".format(filename), shell=True)
Runs a bash script in the local directory
def get_group(self, t, i): """Get group number.""" try: value = [] if t in _DIGIT and t != '0': value.append(t) t = next(i) if t in _DIGIT: value.append(t) else: i.rewind(1) ...
Get group number.
def _walk_tree(self, data, scheme, ancestors=None, property_name=None, prefix=None): """ This function takes configuration data and a validation scheme then walk the configuration tree validating the configuraton data agenst the scheme provided. Will raise error on failure otherwise return None....
This function takes configuration data and a validation scheme then walk the configuration tree validating the configuraton data agenst the scheme provided. Will raise error on failure otherwise return None. Usage:: >>> self._walk_tree( >>> OrderedDict([('root', confi...
def _add_arguments(param, parser, used_char_args, add_nos): ''' Add the argument(s) to an ArgumentParser (using add_argument) for a given parameter. used_char_args is the set of -short options currently already in use, and is updated (if necessary) by this function. If add_nos is True, this will als...
Add the argument(s) to an ArgumentParser (using add_argument) for a given parameter. used_char_args is the set of -short options currently already in use, and is updated (if necessary) by this function. If add_nos is True, this will also add an inverse switch for all boolean options. For instance, for t...
def _build_default_options(self): """"Provide the default value for all allowed fields. Custom FactoryOptions classes should override this method to update() its return value. """ return [ OptionDefault('model', None, inherit=True), OptionDefault('abstrac...
Provide the default value for all allowed fields. Custom FactoryOptions classes should override this method to update() its return value.
def display(contents, domain=DEFAULT_DOMAIN, force_gist=False): """ Open a web browser pointing to geojson.io with the specified content. If the content is large, an anonymous gist will be created on github and the URL will instruct geojson.io to download the gist data and then display. If the cont...
Open a web browser pointing to geojson.io with the specified content. If the content is large, an anonymous gist will be created on github and the URL will instruct geojson.io to download the gist data and then display. If the content is small, this step is not needed as the data can be included in the...
def posterior(self, x, s=1.): """Model is X_1,...,X_n ~ N(theta, s^2), theta~self, s fixed""" pr0 = 1. / self.sigma**2 # prior precision prd = x.size / s**2 # data precision varp = 1. / (pr0 + prd) # posterior variance mu = varp * (pr0 * self.mu + prd * x.mean()) retur...
Model is X_1,...,X_n ~ N(theta, s^2), theta~self, s fixed
def stat_file(self, id=None, path="/"): """ Stat a file in an allocation directory. https://www.nomadproject.io/docs/http/client-fs-stat.html arguments: - id - path returns: dict raises: - nomad.api.exceptions.BaseNomadEx...
Stat a file in an allocation directory. https://www.nomadproject.io/docs/http/client-fs-stat.html arguments: - id - path returns: dict raises: - nomad.api.exceptions.BaseNomadException - nomad.api.exceptions.URLNotF...
def close(self): """Close open resources.""" self._close_proc() super(PipeReader, self).close() if self._tempfile: try: os.unlink(self._tempfile) except OSError: pass self._tempfile = None
Close open resources.
def from_dict(d: Dict[str, Any]) -> 'CoverageInstructions': """ Loads a set of coverage instructions from a given dictionary. Raises: BadCoverageInstructions: if the given coverage instructions are illegal. """ name_type = d['type'] cls = _NAM...
Loads a set of coverage instructions from a given dictionary. Raises: BadCoverageInstructions: if the given coverage instructions are illegal.
def iter_list_market_profit_and_loss( self, market_ids, chunk_size, **kwargs): """Split call to `list_market_profit_and_loss` into separate requests. :param list market_ids: List of market IDs :param int chunk_size: Number of records per chunk :param dict kwargs: Arguments p...
Split call to `list_market_profit_and_loss` into separate requests. :param list market_ids: List of market IDs :param int chunk_size: Number of records per chunk :param dict kwargs: Arguments passed to `list_market_profit_and_loss`
def branch(self): """ Get a flattened representation of the branch. @return: A flat list of nodes. @rtype: [L{Element},..] """ branch = [self] for c in self.children: branch += c.branch() return branch
Get a flattened representation of the branch. @return: A flat list of nodes. @rtype: [L{Element},..]
def calculate_derivative_P(self, P, T, zs, ws, method, order=1): r'''Method to calculate a derivative of a mixture property with respect to pressure at constant temperature and composition of a given order using a specified method. Uses SciPy's derivative function, with a delta of 0.01...
r'''Method to calculate a derivative of a mixture property with respect to pressure at constant temperature and composition of a given order using a specified method. Uses SciPy's derivative function, with a delta of 0.01 Pa and a number of points equal to 2*order + 1. This m...
def create(model_config, reinforcer, optimizer, storage, total_frames, batches_per_epoch, callbacks=None, scheduler=None, openai_logging=False): """ Vel factory function """ from vel.openai.baselines import logger logger.configure(dir=model_config.openai_dir()) return RlTrainCommand( ...
Vel factory function
def _check_custom_url_parameters(self): """Checks if custom url parameters are valid parameters. Throws ValueError if the provided parameter is not a valid parameter. """ for param in self.custom_url_params.keys(): if param is not CustomUrlParam.TRANSPARENT: ...
Checks if custom url parameters are valid parameters. Throws ValueError if the provided parameter is not a valid parameter.
def __neuron_evolution(self, index): """! @brief Calculates state of the neuron with specified index. @param[in] index (uint): Index of neuron in the network. @return (double) New output of the specified neuron. """ value = 0.0 ...
! @brief Calculates state of the neuron with specified index. @param[in] index (uint): Index of neuron in the network. @return (double) New output of the specified neuron.
def __generate_file(self, template_filename, context, generated_filename, force=False): """ Generate **one** (source code) file from a template. The file is **only** generated if needed, i.e. if ``force`` is set to ``True`` or if generated file is older than the template file. The gener...
Generate **one** (source code) file from a template. The file is **only** generated if needed, i.e. if ``force`` is set to ``True`` or if generated file is older than the template file. The generated file is written in the same directory as the template file. Args: template_filenam...
def unstructure_attrs_astuple(self, obj): # type: (Any) -> Tuple """Our version of `attrs.astuple`, so we can call back to us.""" attrs = obj.__class__.__attrs_attrs__ return tuple(self.unstructure(getattr(obj, a.name)) for a in attrs)
Our version of `attrs.astuple`, so we can call back to us.
def _format_background(background): """Formats the background section :param background: the background content or file. :type background: str or file :returns: the background content. :rtype: str """ # Getting the background if os.path.isfile(background): with open(backgroun...
Formats the background section :param background: the background content or file. :type background: str or file :returns: the background content. :rtype: str
def make_describe_attrs(self): """Create tokens for setting is_noy_spec on describes""" lst = [] if self.all_groups: lst.append((NEWLINE, '\n')) lst.append((INDENT, '')) for group in self.all_groups: if group.name: lst.exte...
Create tokens for setting is_noy_spec on describes